diff --git a/module/.gitignore b/module/.gitignore new file mode 100644 index 000000000..9f2a07880 --- /dev/null +++ b/module/.gitignore @@ -0,0 +1,2 @@ +build/ +.gradle/ diff --git a/module/README.md b/module/README.md new file mode 100644 index 000000000..b33160710 --- /dev/null +++ b/module/README.md @@ -0,0 +1,229 @@ +# Iris default module + +This project owns the built-in Iris feature and setting sources under +`src/main/java/art/arcane/iris`. The files keep the packages and pack fields they had in Iris. They build against +the Iris API alone (see "Building" below); Iris depends on this project, never the reverse. + +Ported features are IrisApi modules that every pack loads before its own: object placement +(`iris:prepare`, `iris:anchor`, `iris:validate`, `iris:bore`, `iris:blocks`, `iris:stilt`, +`iris:vacuum`, `iris:snow`, shipped in the built-ins jar), the mantle, and chunk generation. Every mantle stage is a pass of Iris's +mantle of its own, in the stage graph's order: `iris:carve/caves`, `iris:objects/place`, +`iris:floating/objects`, `iris:structure/place`, so a pack's mantle stage can order itself after any of +them. Chunk generation then runs, in this order: `iris:biome`, `iris:terrain`, `iris:carve` (cutting the +planned caves), `iris:post`, `iris:floating` (solids), `iris:deposit`, `iris:matter`, `iris:decorant`, +`iris:floating` (decoration), `iris:perfection` and `iris:custom`. There are no world modes and no Iris +mantle components outside the stage graph any more. Their stage constants, and the settings and output +types packs may read, live in `src/main/java/art/arcane/iris/builtin`, the package Iris exposes to pack +modules; their stage bodies live beside the features they replace. Settings and helper types that only the jar's modules read, +which Iris itself never touches, live in `art.arcane.iris.modules` instead, which Iris does not expose: the jar loads its own copy. +Every built-in snippet is named under its module's id, `iris//` (folder `snippet/iris/carve/cave-profile/`), so a +snippet type may live in either package. A type stays in `art.arcane.iris.builtin` only when Iris reads it or an exposed type holds it. + +Two of those modules are not in this project: `iris:biome` (writes the layout's platform biomes into the chunk) and +`iris:custom` (records the platform's custom blocks of content plugins) are Iris itself, so their classes live in Iris +core (`art.arcane.iris.core.modules.BiomeModule` and `CustomModule`) and Iris registers them (`IrisModuleHost`), not +the built-ins jar. Their stage constants stay in `art.arcane.iris.builtin.IrisStages`, so packs can still order after them. + +Built-in modules log through the `ModuleLog` IrisApi hands them (`context.log()` in a stage body, `world.log()` in a +service or hook, `setup.log()` during setup), which labels each line with the module's id, so these sources do not +use `IrisLogging`. Classes of the host's object model (the host-classes list) and code that only has an engine or pack +data still log as Iris itself. + +Modules also own pack resources and checks of their own. `iris:structure` (`StructureModule`) reads structures, jigsaw +pools and jigsaw pieces as resource kinds (`StructureResources`, `iris:structure/structure`, `/pool`, `/piece`), from the +folders and files packs have always used, and declares the structure placement settings and the mantle stage. Its +definitions (`IrisStructure`, `IrisJigsawPiece`, `IrisJigsawPool` and their parts in `engine/object/structure`) live +here and build against the API. It is not in the built-ins jar: Iris registers it with its own modules, because Iris's +jigsaw studio, importers and exporters read the structures it registers as the same classes, which a jar's own copy of +a class is not. Iris's own module `iris:structure-model` (core `StructureModelModule`) checks them with its validator +(`StructureValidator`: assembly samples and vanilla structure replacement) wherever Iris validates a pack. The +assembler, locator, fitting and placing are still Iris's, and `iris:structure` places through the `StructureHost` +facade (`art.arcane.iris.builtin.structure`). + +Built-in modules answer Iris through IrisApi services instead of Iris reading their features: `iris:objects` +provides `ObjectsAt` (the objects a chunk would get, for the object search and studio tools) and `iris:structure-model` +provides `StructureLocator` (`StructureLocating`: the pack's structure keys for Iris's structure index, the ones a +world places, and their nearest start for the find commands). A world's structure index lives in the world's state +(`engine.getGeneration().state(...)`), so every reload of the pack's structure files, which starts a new world, builds +it again. +`iris:structure-model` also provides `VanillaStructures` (`StructureVanillaStructures`) for the platform's own structures: +which ones its placements replace or the dimension's `importedStructures` disables, the starts its `nativeStructures` +placements make (`startedStructures`, `locatableStarts`, `locateStart`), the shift and band of the platform's starts, and the whole terrain fit of every start (SOURCE, +PRESERVE, VACUUM, ENCASE, BORE, FORCE_CARVE, stilts) in `engine/framework/structure/fit`, written against IrisApi's +`StructureFit` and `BlockAccess` only. A start carries its fit as a memo (its terrain and stilts JSON), so every +chunk it reaches and every restart fits it the same way. `iris:vanilla-features` (`VanillaFeaturesModule`, no stages) +reads the dimension's `importedFeatures` (`ImportedFeaturesSettings`) and provides `VanillaFeatures` (`ImportedFeatures`): +whether the platform's own placed features run over the terrain and which decoration steps and features they leave out; +the family patterns of `disabled` and of `importedStructures` share one rule (`art.arcane.iris.builtin.RegistryKeyFamily`). +Object place modes are data (`PlaceMode`: height sampling, +stilt, `VacuumProfile`, `PlaceTrait`s) that the placement stages ask; the pack JSON keeps the mode names. +`iris:objects` also provides `SaplingGrowth` (`TreeGrowing`: the tree a sapling grows into, as placed blocks, and which +objects are trees) and says which biomes and regions place an object (`ObjectLocating`, for the object search). +`iris:objects` ships in the built-ins jar. It declares the settings `objects` (region, biome: the list of `ObjectPlacement`s), +`proceduralObjects` (region, biome), `treeSettings` (dimension), `requireObjectSurfaceSupport`, `objectSurfaceSupportBuffer`, +`upperDimensionObjects` and `upperObjectsForcePlace` (dimension), all written as they always were. `ObjectPlacement` is the +placement itself, read by the module decoder like any settings class, and the one type Iris places with. What a jar cannot do, Iris does through the facades `ObjectHost` and +`ObjectChunk` in `art.arcane.iris.builtin.objects`: loading and scaling the pack's objects, placing one with the placement +stages into the chunk's mantle (on the surface, in a cave inside the cave's bounds, or hung from the terrain above), reading the +carved space the cave carver planned, and the loot an object placed at a block defines; the layout, the settings of a column and +the upper dimension's objects come from IrisApi (`TerrainSampler`, `FeatureSettings`, `UpperDimension`). `ObjectPlacing` and its helpers (`ChunkObjectPlacing`, +`CaveAnchors`, `PlacementReach`) decide what to place and where. Procedural objects (`engine/procedural`, resource kind +`iris:objects/procedural`, folder `procedural`) are definitions of parts that bake into variants; a placement names them as +`procedural/`, or `procedural/#` for one variant, like any object. +`iris:loot` owns the loot table resource kind (`LootResources`, folder `loot`), checks the tables and the references to +them (`LootValidator`), and provides `Loot` (`LootGiving`: which tables a container draws from and the `ItemDrop`s a +table gives) and `BlockDrops` (`BlockDropping`). `iris:spawn` owns spawners, entities and markers (`SpawnResources`, +folders `spawners`, `entities`, `markers`) and provides `EntitySpawns` (`EntitySpawning`: what to spawn in a chunk or at +a marker, as `EntitySpec`s; `EntityResolution` makes the entity's random choices) and `AmbientEffects` (`AmbientEffecting`: +the effects due around a player, with their random values). Iris's Bukkit code creates the items and entities from those +values (`BukkitItemStacks`, `BukkitEntitySpawner`, `BukkitAmbientEffects`); the modded adapters, which cannot name IrisApi +types, ask through the host-typed `ContentServices`. +The settings of both modules are `builtin.loot` and `builtin.spawn` types of IrisApi annotations only: `iris:loot` declares +`loot` (object, also the shape of an entity's `loot`) and `blockDrops` (list) for dimensions, regions and biomes; +`iris:spawn` declares `entitySpawners` (list of spawner keys) for the same and `effects` (list, `iris:spawn/effects`) for +regions and biomes. The loot tables, spawners, entities and markers are plain module types too (`LootTable`, `Spawner`, +`EntityDefinition`, `SpawnMarker`). `PlacementLoot` picks the table an object placement gives one of its chests. +`iris:decorant`, `iris:terrain` and `iris:deposit` ship in the built-ins jar and keep their per-world workers (`BiomeDecorators`, `TerrainShaper`, +`DepositPlacer`) in the world's state store (`context.world().state(...)`); the modules still compiled into Iris reach the same store through +the `IrisChunk` their invocation offers (`context.extension(IrisChunk.class)`, then `state(...)`) or `engine.getGeneration().state(...)`. + +Settings move off Iris's classes one feature at a time. `iris:deposit` is the first whose settings are IrisApi types +only: `DepositSettings` (`art.arcane.iris.modules.deposit`) holds `DepositGenerator`s (blocks as `BlockSpec`, its enums beside it; packs write generators as +`snippet/iris/deposit/deposit/...`), and packs write `"deposits": [...]`, as they always have (`@Feature(key = "deposits", root = "generators")`: the key holds the one option's list). What needs Iris (resolving the +palette, ore checks, clump shapes per world seed) lives in the module's own code, `ResolvedDeposit`. The deposits run one generator after the other, each +with a random of its own; they used to spread over threads on a multicore pregen, which no module can do (stages run on the host's threads). + +An object placement is `iris:objects` settings (`objects.ObjectPlacement`, under a biome's or region's `objects`), and the +settings inside it, such as its clamp, stilt, vacuum and edit settings, its slope condition or a procedural coral, are +module-owned classes too (`art.arcane.iris.builtin.validate`, `.stilt`, `.vacuum`, `.blocks`, `.prepare`, `.carve`, +`.floating`, `.objects.*`), so studio describes them from the module's own annotations. Iris reads a placement's module +settings (the keys pack modules add at `Level.PLACEMENT`) from the JSON the placement was written as (`json()`); a +placement made in code uses `ObjectPlacement.builder()` or `toBuilder()`. Packs write the same JSON as before. Behaviour +that needs Iris (noise built from the styles, blocks resolved through the pack, baked object variants) lives in `Resolved*` classes beside the +worker (`ResolvedReplace`, `ResolvedCaveProfile`, `ResolvedFloatingChild`, `ResolvedProceduralPlacement`). + +`iris:decorant` is the second: `DecorantSettings` (biome level) holds `Decorator`s in `art.arcane.iris.builtin.decorant`, +written `"decorators": [...]` as always (`@Feature(key = "decorators", root = "decorators")`). +`ResolvedDecorator` resolves one decorator's blocks and noise for a world; `BiomeDecorators`, the world's state, keeps them +per biome and place. A chunk's decorators place into a `DecorationScene` (its blocks, the planned blocks around it, the terrain and the pack's block +rules); other modules that decorate (the caves' floors and ceilings, floating islands) build one from their chunk's stage context. Whether a +dimension decorates at all is its `decorate` key (`DecorateSettings`). A decorator's noise +seed is the world's decorator seed, its biome's key and its place in the biome's list. The module's `warmUp` builds +them ahead of generation; `iris:terrain` and `iris:objects` warm their ore generators, placements and procedural +objects the same way. + +`iris:terrain` and `iris:post` own the fields that shape a column's blocks. Per biome: `layers`, `seaLayers`, `caveCeilingLayers` (lists of +`PaletteLayer`, the old biome palette layer, in `art.arcane.iris.builtin.terrain`), `slab` and `wall` (one `PaletteLayer` each), `lockLayers` (a +boolean) and `lockLayersMax` (a number). Per dimension: `rockPalette` and `fluidPalette` (a `PaletteSpec` each) in `art.arcane.iris.modules.terrain`, and +`postProcessing`, `postProcessingSlabs`, `postProcessingWalls` (booleans) in `art.arcane.iris.modules.post`; `bedrock`, `explodeBiomePalettes` and +`explodeBiomePaletteSize` are dimension keys of `iris:terrain` too. A key a pack leaves out has the +default Iris always had (one grass layer, no slab or wall, stone and water, post processing on). `ResolvedLayer` resolves one layer's blocks and noise +for a pack, `BiomeLayers`, the world's state, keeps them and stacks a biome's layers into the blocks of a column, and `TerrainPalettes` is the world's +rock and fluid as a block for every column; the terrain, cave, floating, post and vacuum stages ask them. All of them are the jar's own +(`art.arcane.iris.modules.terrain`), and every stage that asks is in the jar, so one copy serves them all: a biome's layer thickness noise is built once, +from the random of whoever asks first, as it always was. The slope limit of a layer, a decorator and an +object placement is the one `SlopeClip`. + +Caves, floating islands and ores are settings of their modules too, written under the keys they always had. `iris:carve` owns +`caveProfile` (dimension, region, biome; an object, or a `snippet/iris/carve/cave-profile/...` reference), `carving` (dimension; a list of bands) and +`carvingEnabled` (dimension; a boolean), `carvingBiome` (biome; a biome key) and `caveMinDepthBelowSurface` (biome; a number). `iris:floating` +owns `floatingChildBiomes` (biome; a list) and `mergeFloatingChildBiomes` (biome; a boolean). `iris:terrain` owns `ores` (dimension, region, +biome; a list of generators) and `hideOresForHiddenOre` (dimension; a boolean); `iris:deposit` owns `depositVariants` (dimension, region, biome; a list) +and `oreDepositFrequencyMultiplier` and `oreDepositSizeMultiplier` (biome; numbers). Behaviour that needs Iris lives in the `Resolved*` classes beside the +workers: `ResolvedOre`/`ResolvedOres` (blocks and chance noise per world, `TerrainOres` the world's state), `ResolvedDepositVariant`, +`ResolvedCarvingEntry`/`CarvingBands`/`CarvingResolver` (the band for a position) and `ResolvedFloatingChild`. The settings that name biomes +(`carvingBiome`, a band's biome, a floating child's target and carving) implement `LinkedBiomes`, which is how Iris's biome tree and the biomes a +dimension reaches learn of them without reading the settings classes; and `iris:carve` provides the `CaveBiomes` service +(`CaveBiomeBands`), which Iris asks for the dimension's carving band at a position and for a biome's minimum cave depth. +`iris:floating` ships in the built-ins jar: `FloatingWorld` holds a world's floating children, noise and seeds. It asks the +API alone: the running world's layout for a column's surface biome and a biome's height for the `BIOME` top shape +(`TerrainSampler.biomeHeight`), the chunk's terrain for a child's sky biome (`skyBiome`), which it writes with +`Mantle.setPlatformBiome`, and `PackWorld.placements()` to place an object floating, on an island's top or hung under it, +where the jar's `IslandAnchor` says where the island face is. + +Packs write each settings feature under the short key it declares: `deposits` (dimension, region, biome; a list), `decorators` +(biome; a list), `importedStructures` (dimension; an object of `disabled`, `adjustments` and the rest) and `structures` +(dimension, region, biome; a list of `StructurePlacement`s, `StructurePlacementSettings`). The feature ids +(`iris:deposit`, `iris:decorant`, `iris:structure`) stay the modules' identity in the stage graph and logs. A key is unique +per target across all modules and Iris's own fields, so a new built-in or pack module picks a key no field of the target uses. + +Every built-in stage is a full port: the module owns its logic and per-engine state, and the mantle stages +work out their reach from the pack when it loads. A dimension's `disabledComponents` turns a mantle stage off +by its stage id, such as `iris:carve/caves`; a name that matches no stage fails the world. + +## Building + +This is a Gradle build of its own (`art.arcane:iris-module`). Its compile classpath is the Iris API +(`com.volmit:iris-api`, from the sibling `../IrisApi` checkout; never `iris-host`), VolmLib, Gson, Lombok and the JDK, +all `compileOnly`: a host provides them at runtime. VolmLib comes from a sibling `VolmLib` checkout when there is one, +found the way Iris finds it (`-PuseLocalVolmLib=false`, `-PlocalVolmLibDirectory=` or `VOLMLIB_DIR`), otherwise +from the published `volmLibCoordinate` in `gradle.properties`, which matches Iris's. Classes compile with Iris's options +(`-parameters`, no debug info) and `lombok.config` repeats Iris's, so they are the classes Iris shipped when it +compiled these sources itself. + +Iris includes this build (`includeBuild('../IrisModule')` in its `settings.gradle`) and depends on its classes: Iris +core and its adapters still name many of them (the cut-over that ends this comes later). Classes that need Iris itself +are Iris's and live in Iris core: the layout model (`IrisBiome`, `IrisRegion`, `IrisDimension`, generators, noise +styles, expressions, images), the pack's objects and blocks, the structure assembler, locator, fitting and placer +(behind `StructureHost`), and the placement service behind `PackWorld.placements()`. A module this build holds +but the jar does not, such as `iris:structure`, is one Iris registers with its own modules (`IrisModuleHost`): its +classes are then the ones Iris's own code sees. + +`./gradlew check` compiles every source and builds the built-ins jar below, which runs the pack class checks. + +## Built-in modules as a pack module jar + +This build packages the built-in modules as an ordinary pack module jar, `build/libs/iris-builtins.jar`, from its own +classes, and Iris bundles it into the plugin: every pack loads it as if it were in its `modules/` folder (IrisApi's +`ModuleHost.bundlingJars`). A pack must not hold a copy of it: its classes would be in two jars, so the pack fails to load +naming both. `./gradlew builtinModulesJar` builds it. `builtin-modules.txt` lists what goes in: `module ` lines +(the jar's entry points, written to `META-INF/services/com.volmit.IrisModule`) and `include ` lines for further +classes. Iris asks for the jar by the capability `art.arcane:iris-builtins`; its plugin leaves the jar's classes out of +its own, and its Bukkit artifact check fails the build if Iris still uses one of them. +Before the jar is written, `ModuleJarCheck` of IrisApi runs the class checks of a pack load on it, with the packages Iris +exposes (`art.arcane.iris.builtin`, VolmLib's `art.arcane.volmlib` and Gson's `com.google.gson`, all three on the check's +classpath, with this build's other classes as the host's); a listed class that uses a class outside the jar and those +packages fails the task naming the class and what it uses. Iris checks the jar once more before bundling it, against the +VolmLib classes its Bukkit jar strips (`core/volmlib-left-out-of-bukkit-jar.txt`), which only Iris knows. + +The jar holds `iris:post`, `iris:perfection`, `iris:matter`, `iris:loot`, `iris:spawn`, `iris:vanilla-features` and +`iris:carve`, and the object placement stages `iris:prepare`, `iris:anchor`, `iris:validate`, `iris:bore`, `iris:blocks`, `iris:stilt`, `iris:vacuum` and `iris:snow`. They are +written against IrisApi and `art.arcane.iris.builtin` alone: the chunk's `BlockState` hunk, the block registry's traits and +`canPlaceOn`, the terrain sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the +mantle's planned blocks; the placement stages read the placement being run through the `ObjectPlacement` facade, and the loot and +spawn services, which have no chunk to ask, ask the running world (`world.running()`, IrisApi's `RunningWorld`). Without the jar a pack's world has no caves, vanilla +placed features, loot, block drops, entity spawns or ambient effects, and its biomes' `loot`, `blockDrops`, `entitySpawners` and +`effects` are not read. +Iris no longer compiles them in (`IrisModuleHost.generationModules()`); every pack gets them from the bundled jar. A pack +still loads without them, as with an Iris build that bundles no jar, and Iris warns once per pack folder when a pack loads +none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps equal to +`builtin-modules.txt`): add a module to the jar and to that list together. + +`art.arcane.iris.builtin` also holds what the compiled-in built-ins and the jar must share, because each sees its own copy of +every other class. The facades among them are interfaces Iris implements and offers through IrisApi's extension point, never +through the thread or a cast: a module asks `world.extension(X.class)` for what belongs to a world (`StructureHost`), +`context.extension(X.class)` for what belongs to one invocation (`IrisChunk` in a chunk stage, `IrisMantleChunk` in a mantle stage) and +`settings.extension(X.class)` for a reach worked out +before any world exists, each with `.orElseThrow()`, since a built-in runs only where Iris offers them. Iris's per-feature world seeds are +IrisApi purpose seeds: `world.seed(IrisSeedPurposes.CARVE)` (`iris:seed/carve`), by the API's rule like any module's. What the +built-ins keep with a world across restarts, such as the spawner cooldowns (`SpawnCooldownBook`), they save through +`RunningWorld.saved`; object placing seeds its chunk random, density noise and virtual heightmaps from purpose seeds and IrisApi noise. +The package also holds `loot.LootResolver` (the random streams loot is drawn from, shared with the hosts that fill containers) and the loot and +marker lists of an object placement (`loot.ObjectLoot`, `loot.ObjectVanillaLoot`, `spawn.PlacementMarker`). The placement stages need more of the object being +placed than IrisApi describes, so `placement.ObjectPlacement` is the facade Iris implements for each placement and offers with +its invocation (`context.extension(ObjectPlacement.class)`): the object's size (`ObjectShape`), the placement's settings (`PlacementSettings`, read from +the `objects.ObjectPlacement` being placed), the terrain questions of its placer and the world around it (`PlacementTerrain`), the surface warp, +and the block operations only the platform can do (turning a state with the object, merging two states, matching, traits of the +placement's own states). Its types answer with IrisApi, VolmLib and built-in values only. `prepare.PreparedPlacement`, the output of +`iris:prepare/transforms`, lives in the exposed package too, because `IrisStages` names it. `iris:post` reads its switches +(`postProcessingWalls`, `postProcessingSlabs`) and the biome's `wall` and `slab` as module settings through its context. + +`iris:carve` plans its caves in IrisApi's host-owned `Mantle.carved()` layer (`CarvedVoid`: open, fluid, lava or air, and optionally a +biome), which Iris keeps in its own form for the platform and the rest of Iris to read. The mantle stage writes it; the apply stage +reads it, and one block beyond its chunk to wall the caves that cross the border. The cave floors the spawners use are marked by the mantle +stage with `PlacementTerrain.mark(PackMarker("cave_floor"))`. What a +cave's walls, floor and ceiling get comes from the terrain and decorant built-ins of the same jar (`modules.terrain.BiomeLayers`, +`modules.terrain.TerrainPalettes`, the biome decorators), through carve's own `CaveDressing`, which tests replace with fixed blocks. +A cave's dimension, region and biome settings are found by the id the layout's biome samples carry (`DeclaredByLevel`), its +absolute world Y bands convert with `PackWorld.minWorldY()`, and its noise reads `NoiseSampler.signed(...)` (Iris's memoised signed read) +and `scaled(...)`. `caveLavaHeight` and `upperDimensionCarving` are its dimension settings. diff --git a/module/build.gradle.kts b/module/build.gradle.kts new file mode 100644 index 000000000..a9122a20e --- /dev/null +++ b/module/build.gradle.kts @@ -0,0 +1,179 @@ +import org.gradle.jvm.tasks.Jar +import java.io.ByteArrayOutputStream + +plugins { + `java-library` +} + +group = "art.arcane" +version = "1.0-SNAPSHOT" + +base { + archivesName.set("iris-module") +} + +java { + toolchain.languageVersion.set(JavaLanguageVersion.of(25)) + withSourcesJar() +} + +repositories { + mavenCentral() + maven("https://jitpack.io") // VolmLib, when no sibling checkout is found +} + +val volmLibCoordinate = providers.gradleProperty("volmLibCoordinate").get() + +// What a module may use: the Iris API, VolmLib and Gson, which every Iris host provides, and the JDK. None of them ships +// with the module. +dependencies { + compileOnly("com.volmit:iris-api") + compileOnly(volmLibCoordinate) { + isTransitive = false + } + compileOnly("com.google.code.gson:gson:2.14.0") + compileOnly("org.projectlombok:lombok:1.18.46") + annotationProcessor("org.projectlombok:lombok:1.18.46") +} + +// The same options as Iris's own compilation, so the classes, and the built-ins jar made from them, are the ones Iris +// shipped when it compiled these sources itself. +tasks.named("compileJava") { + options.encoding = "UTF-8" + options.compilerArgs.add("-parameters") + options.debugOptions.debugLevel = "none" + // lombok.config decides which members Lombok generates; Gradle does not know it is an input. + inputs.file(layout.projectDirectory.file("lombok.config")) + .withPropertyName("lombokConfig") + .withPathSensitivity(PathSensitivity.NONE) +} + +// The built-ins as a pack module jar, build/libs/iris-builtins.jar. builtin-modules.txt lists what goes in: +// "module " (an entry point, with its nested classes) or "include ". +val builtinModulesJarName = "iris-builtins.jar" +val builtinModuleEntryFile = "com.volmit.IrisModule" +val builtinModulesFile = layout.projectDirectory.file("builtin-modules.txt").asFile +// The packages an Iris host exposes to pack modules besides the API (Iris's IrisModuleHost.EXPOSED_PACKAGES). +val exposedHostPackages = listOf("art.arcane.iris.builtin", "art.arcane.volmlib", "com.google.gson") + +data class BuiltinModulesList(val moduleClasses: List, val classPatterns: List) + +fun readBuiltinModulesList(): BuiltinModulesList { + val moduleClasses = mutableListOf() + val classPatterns = mutableListOf() + builtinModulesFile.readLines() + .map { it.substringBefore('#').trim() } + .filter { it.isNotEmpty() } + .forEach { line -> + val parts = line.split(Regex("\\s+"), limit = 2) + if (parts.size < 2 || parts[1].isBlank()) { + throw GradleException("${builtinModulesFile.name}: '$line' needs a value after '${parts[0]}'") + } + when (parts[0]) { + "module" -> moduleClasses.add(parts[1].trim()) + "include" -> classPatterns.add(parts[1].trim()) + else -> throw GradleException("${builtinModulesFile.name}: unknown line '$line'; start it with 'module' or 'include'") + } + } + return BuiltinModulesList(moduleClasses, classPatterns) +} + +val builtinModulesList = readBuiltinModulesList() +val builtinPackagedPatterns = builtinModulesList.moduleClasses.flatMap { moduleClass -> + val path = moduleClass.replace('.', '/') + listOf("$path.class", "$path\$*.class") +} + builtinModulesList.classPatterns +val builtinModulesBuild = layout.buildDirectory.dir("builtin-modules") + +val writeBuiltinModuleEntries = tasks.register("writeBuiltinModuleEntries") { + description = "Writes the built-ins jar's META-INF/services/$builtinModuleEntryFile, one module class per line." + val entries = builtinModulesBuild.map { it.file("services/$builtinModuleEntryFile") } + inputs.file(builtinModulesFile) + outputs.file(entries) + doLast { + val entriesFile = entries.get().asFile + entriesFile.parentFile.mkdirs() + entriesFile.writeText(builtinModulesList.moduleClasses.joinToString("\n") + "\n") + } +} + +val packageBuiltinModules = tasks.register("packageBuiltinModules") { + description = "Packages the listed built-in modules and classes before they are checked." + archiveFileName.set(builtinModulesJarName) + destinationDirectory.set(builtinModulesBuild.map { it.dir("unchecked") }) + inputs.file(builtinModulesFile) + from(sourceSets.main.map { it.java.classesDirectory }) { + include(builtinPackagedPatterns) + } + from(writeBuiltinModuleEntries) { + into("META-INF/services") + } +} + +// The check runs on the API's host side, which knows the rules of a pack load; the module classes are on its class path as +// the host's, so a listed class that uses one left out of the jar fails as it would in Iris. +val builtinModulesCheckClasspath = configurations.create("builtinModulesCheckClasspath") { + isCanBeConsumed = false + isTransitive = false + attributes { + attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME)) + } +} + +dependencies { + builtinModulesCheckClasspath("com.volmit:iris-api") + builtinModulesCheckClasspath("com.volmit:iris-host") + builtinModulesCheckClasspath(volmLibCoordinate) + builtinModulesCheckClasspath("com.google.code.gson:gson:2.14.0") +} + +val builtinModulesJar = tasks.register("builtinModulesJar") { + group = "build" + description = "Builds build/libs/$builtinModulesJarName, the built-in modules as a pack module jar, checked with IrisApi's" + + " pack class and reference checks as a pack load would." + val unchecked = packageBuiltinModules.flatMap { it.archiveFile } + val checked = layout.buildDirectory.file("libs/$builtinModulesJarName") + classpath = builtinModulesCheckClasspath + files(sourceSets.main.map { it.java.classesDirectory }) + mainClass.set("com.volmit.host.ModuleJarCheck") + inputs.file(unchecked) + outputs.file(checked) + argumentProviders.add(CommandLineArgumentProvider { listOf(unchecked.get().asFile.absolutePath) + exposedHostPackages }) + isIgnoreExitValue = true + val problems = ByteArrayOutputStream() + errorOutput = problems + doFirst { + // A jar from an earlier run that passed must not survive a run that fails. + checked.get().asFile.delete() + } + doLast { + if (executionResult.get().exitValue != 0) { + throw GradleException("The built-in modules jar breaks the rules of a pack module jar:\n" + problems.toString().trim() + + "\nFix the classes listed in ${builtinModulesFile.name}, or move what they use into the jar or into art.arcane.iris.builtin.") + } + unchecked.get().asFile.copyTo(checked.get().asFile, overwrite = true) + } +} + +// Iris bundles the checked jar into its plugin. It asks for it by this capability of the module's coordinate. +configurations.create("builtinModulesJarElements") { + isCanBeConsumed = true + isCanBeResolved = false + attributes { + attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME)) + attribute(Category.CATEGORY_ATTRIBUTE, objects.named(Category.LIBRARY)) + attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objects.named(LibraryElements.JAR)) + attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.EXTERNAL)) + } + outgoing.capability("art.arcane:iris-builtins:${project.version}") + outgoing.artifact(builtinModulesJar.map { layout.buildDirectory.file("libs/$builtinModulesJarName").get() }) { + builtBy(builtinModulesJar) + } +} + +tasks.named("check") { + dependsOn(builtinModulesJar) +} + +tasks.named("assemble") { + dependsOn(builtinModulesJar) +} diff --git a/module/builtin-modules.txt b/module/builtin-modules.txt new file mode 100644 index 000000000..9b89e2c4c --- /dev/null +++ b/module/builtin-modules.txt @@ -0,0 +1,102 @@ +# What goes into build/libs/iris-builtins.jar, the built-in modules as a pack module jar. +# +# A line is one of (blank lines and # comments are ignored): +# +# module an IrisModule class. It is listed in META-INF/services/com.volmit.IrisModule, +# and its nested classes are packaged with it. +# include more classes for the jar, as an Ant pattern relative to the class root, such as +# art/arcane/iris/engine/modifier/carve/** Settings types, helpers and stage +# constants a listed module owns go here. +# +# A class here must be one a pack module may have: it may use only the IrisApi, the packages Iris exposes +# (art.arcane.iris.builtin), the JDK and the other classes of the jar. `./gradlew builtinModulesJar` checks +# that with IrisApi's pack class checks and fails naming the class and what it uses. +# +# Moving a module here means removing it from IrisModuleHost.generationModules() in Iris. + +# The settings and helper types only the jar's modules use, which Iris does not expose. +include art/arcane/iris/modules/** + +module art.arcane.iris.engine.modifier.PostModule +include art/arcane/iris/engine/modifier/SurfaceSmoothing*.class +module art.arcane.iris.engine.modifier.PerfectionModule +module art.arcane.iris.engine.modifier.MatterModule +module art.arcane.iris.engine.loot.LootModule +include art/arcane/iris/engine/loot/** +module art.arcane.iris.engine.spawn.SpawnModule +include art/arcane/iris/engine/spawn/** +module art.arcane.iris.engine.object.placement.PrepareModule +module art.arcane.iris.engine.object.placement.AnchorModule +module art.arcane.iris.engine.object.placement.ValidateModule +module art.arcane.iris.engine.object.placement.BoreModule +module art.arcane.iris.engine.object.placement.BlocksModule +module art.arcane.iris.engine.object.placement.StiltModule +module art.arcane.iris.engine.object.placement.VacuumModule +module art.arcane.iris.engine.object.placement.SnowModule +include art/arcane/iris/engine/object/placement/PlacementModules.class +include art/arcane/iris/engine/object/placement/PlacementWorld.class +include art/arcane/iris/engine/object/placement/WorldVolume.class +include art/arcane/iris/engine/object/placement/ObjectEdits*.class +include art/arcane/iris/engine/object/placement/ResolvedReplace*.class +include art/arcane/iris/engine/object/placement/IrisSurfaceSupport*.class +include art/arcane/iris/engine/object/placement/IrisObjectVacuum.class +module art.arcane.iris.engine.framework.vanillafeatures.VanillaFeaturesModule +include art/arcane/iris/engine/framework/vanillafeatures/** +module art.arcane.iris.engine.modifier.CarveModule +include art/arcane/iris/engine/modifier/CaveApplying*.class +include art/arcane/iris/engine/modifier/CaveDressing.class +include art/arcane/iris/engine/modifier/BuiltInCaveDressing.class +include art/arcane/iris/engine/modifier/CaveBiomeBands*.class +include art/arcane/iris/engine/modifier/CaveBiomeCache.class +include art/arcane/iris/engine/modifier/CaveBlockClasses.class +include art/arcane/iris/engine/modifier/CarveColumnMask.class +include art/arcane/iris/engine/modifier/CarveWallBuffer*.class +include art/arcane/iris/engine/modifier/IrisCarveScratch.class +include art/arcane/iris/engine/mantle/components/CarveOrphanSweep*.class +include art/arcane/iris/engine/mantle/components/CarveWorld.class +include art/arcane/iris/engine/mantle/components/CaveCarveScratch*.class +include art/arcane/iris/engine/mantle/components/CaveCarving*.class +include art/arcane/iris/engine/mantle/components/CaveFieldModuleState.class +include art/arcane/iris/engine/mantle/components/CaveFloorMarking*.class +include art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan*.class +include art/arcane/iris/engine/mantle/components/IrisCaveCarver3D*.class +include art/arcane/iris/engine/mantle/components/SurfaceFluidBoundaryPlan*.class +include art/arcane/iris/engine/object/terrain/carving/CarvingResolver*.class +include art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler*.class +include art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.class +include art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.class +include art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.class +module art.arcane.iris.engine.modifier.DepositModule +include art/arcane/iris/engine/modifier/DepositPlacer*.class +include art/arcane/iris/engine/modifier/DepositClump*.class +include art/arcane/iris/engine/modifier/ResolvedDeposit*.class +module art.arcane.iris.engine.actuator.DecorantModule +include art/arcane/iris/engine/decorator/** +module art.arcane.iris.engine.actuator.TerrainModule +include art/arcane/iris/engine/actuator/Terrain*.class +include art/arcane/iris/engine/actuator/ResolvedOre*.class +include art/arcane/iris/engine/actuator/OreWarmUp*.class +module art.arcane.iris.engine.mantle.components.ObjectModule +include art/arcane/iris/engine/mantle/components/ObjectPlacing*.class +include art/arcane/iris/engine/mantle/components/ChunkObjectPlacing*.class +include art/arcane/iris/engine/mantle/components/CaveAnchors*.class +include art/arcane/iris/engine/mantle/components/CaveSettings*.class +include art/arcane/iris/engine/mantle/components/CaveRejects*.class +include art/arcane/iris/engine/mantle/components/EffectivePlacements*.class +include art/arcane/iris/engine/mantle/components/PlacementReach*.class +include art/arcane/iris/engine/mantle/components/ObjectWarmUp*.class +include art/arcane/iris/engine/mantle/components/ObjectLocating*.class +include art/arcane/iris/engine/mantle/components/TreeGrowing*.class +include art/arcane/iris/engine/mantle/components/ObjectChunk*.class +include art/arcane/iris/engine/mantle/components/GoldenDebugTerrain*.class +include art/arcane/iris/engine/procedural/** +module art.arcane.iris.engine.modifier.FloatingModule +include art/arcane/iris/engine/modifier/FloatingIslands*.class +include art/arcane/iris/engine/object/terrain/floating/** +include art/arcane/iris/engine/mantle/components/FloatingObjectPlacing*.class +include art/arcane/iris/engine/mantle/components/FloatingPlacer*.class +include art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver*.class +include art/arcane/iris/engine/mantle/components/IslandFace*.class +include art/arcane/iris/engine/mantle/components/UndersideTurn*.class +# iris:structure (art.arcane.iris.engine.mantle.components.StructureModule) is not here: Iris registers it with its own +# modules, because its jigsaw studio reads the structure resources the module registers. diff --git a/module/gradle.properties b/module/gradle.properties new file mode 100644 index 000000000..966645f9f --- /dev/null +++ b/module/gradle.properties @@ -0,0 +1,3 @@ +# The published VolmLib the build resolves when no sibling checkout is found (see settings.gradle.kts). Keep it equal to +# Iris's volmLibCoordinate: Iris ships VolmLib and the built-ins run against that copy. +volmLibCoordinate=com.github.VolmitSoftware:VolmLib:e6574cf814b3dd670385a4d632a63fde2038e186 diff --git a/module/gradle/wrapper/gradle-wrapper.jar b/module/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..b1b8ef56b Binary files /dev/null and b/module/gradle/wrapper/gradle-wrapper.jar differ diff --git a/module/gradle/wrapper/gradle-wrapper.properties b/module/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..eb84db68d --- /dev/null +++ b/module/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/module/gradlew b/module/gradlew new file mode 100755 index 000000000..249efbb03 --- /dev/null +++ b/module/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/module/gradlew.bat b/module/gradlew.bat new file mode 100644 index 000000000..a51ec4f58 --- /dev/null +++ b/module/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/module/lombok.config b/module/lombok.config new file mode 100644 index 000000000..803015b8e --- /dev/null +++ b/module/lombok.config @@ -0,0 +1,5 @@ +# Iris compiled these sources itself before they had a build of their own, so this repeats ../Iris/lombok.config to keep +# the members Lombok generates, and with them the classes Iris ships, unchanged. ../Iris/lombok.config explains each setting. +config.stopBubbling = true +lombok.equalsAndHashCode.doNotUseGetters = true +lombok.toString.doNotUseGetters = true diff --git a/module/settings.gradle.kts b/module/settings.gradle.kts new file mode 100644 index 000000000..500d94cba --- /dev/null +++ b/module/settings.gradle.kts @@ -0,0 +1,42 @@ +rootProject.name = "IrisModule" + +// The built-ins compile against the Iris API alone, from the sibling checkout. Never against iris-host: that is what a host +// such as Iris uses to load modules, and packs never see it. +includeBuild("../IrisApi") { + dependencySubstitution { + substitute(module("com.volmit:iris-api")).using(project(":api")) + substitute(module("com.volmit:iris-host")).using(project(":host")) + } +} + +// VolmLib from a sibling checkout when there is one, as Iris resolves it (Iris's gradle/volmlib-resolution.settings.gradle): +// -PuseLocalVolmLib=false turns it off, -PlocalVolmLibDirectory= or VOLMLIB_DIR names the checkout, and otherwise the +// first `VolmLib` folder with a settings script above this one is used. Without one, the build resolves the published +// coordinate in gradle.properties. +fun hasSettingsScript(directory: File): Boolean = + File(directory, "settings.gradle.kts").exists() || File(directory, "settings.gradle").exists() + +fun localVolmLibDirectory(): File? { + val configuredPath = providers.gradleProperty("localVolmLibDirectory") + .orElse(providers.environmentVariable("VOLMLIB_DIR")) + .orNull + if (!configuredPath.isNullOrBlank()) { + val configured = File(configuredPath).let { if (it.isAbsolute) it else File(settingsDir, configuredPath) } + if (hasSettingsScript(configured)) { + return configured + } + } + return generateSequence(settingsDir) { it.parentFile } + .map { File(it, "VolmLib") } + .firstOrNull { hasSettingsScript(it) } +} + +val useLocalVolmLib = providers.gradleProperty("useLocalVolmLib").orElse("true").get().equals("true", ignoreCase = true) +val volmLibCheckout = if (useLocalVolmLib) localVolmLibDirectory() else null +if (volmLibCheckout != null) { + includeBuild(volmLibCheckout) { + dependencySubstitution { + substitute(module("com.github.VolmitSoftware:VolmLib")).using(project(":shared")) + } + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java b/module/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java new file mode 100644 index 000000000..f05347f18 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java @@ -0,0 +1,57 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin; + +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +/** + * The purposes Iris's built-in modules ask {@link PackWorld#seed(ResourceId)} for, one per feature. + */ +public final class IrisSeedPurposes { + public static final ResourceId BIOME = purpose("biome"); + public static final ResourceId CARVE = purpose("carve"); + public static final ResourceId COMPLEX = purpose("complex"); + public static final ResourceId COMPONENT = purpose("component"); + public static final ResourceId DECORATOR = purpose("decorator"); + public static final ResourceId DEPOSIT = purpose("deposit"); + public static final ResourceId ENTITY = purpose("entity"); + public static final ResourceId LOOT = purpose("loot"); + public static final ResourceId MANTLE = purpose("mantle"); + /** The random each chunk's objects are placed with, before the chunk's coordinates are mixed in. */ + public static final ResourceId OBJECT_CHUNK = purpose("object-chunk"); + /** The noise that picks the count of a placement with a density style. */ + public static final ResourceId OBJECT_DENSITY = purpose("object-density"); + /** The noise that warps the columns of object placements with a surface warp. */ + public static final ResourceId OBJECT_WARP = purpose("object-warp"); + /** The candidate spots, ranks and chance noise of separated object placements. */ + public static final ResourceId OBJECT_SEPARATION = purpose("object-separation"); + public static final ResourceId POST = purpose("post"); + public static final ResourceId TERRAIN = purpose("terrain"); + + private static final String NAMESPACE = "iris"; + private static final String PATH_PREFIX = "seed/"; + + private IrisSeedPurposes() { + } + + private static ResourceId purpose(String name) { + return new ResourceId(NAMESPACE, PATH_PREFIX + name); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/IrisStages.java b/module/src/main/java/art/arcane/iris/builtin/IrisStages.java new file mode 100644 index 000000000..2eec153ca --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/IrisStages.java @@ -0,0 +1,132 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin; + +import com.volmit.stage.ChunkStage; +import com.volmit.stage.MantleStage; +import com.volmit.stage.Stage; + +/** + * The mantle and chunk stages of Iris's built-in modules, one nested class per module, in the order their pipelines + * run them: mantle, then chunk. The stage graph decides the actual order. The object placement stages are the + * placement modules' own. + */ +public final class IrisStages { + private IrisStages() { + } + + /** Module {@code iris:carve}: caves, planned in the mantle and cut into each chunk's terrain. */ + public static final class Carve { + /** Plans the caves of the dimension's cave profiles into the mantle, one block into each neighbor. */ + public static final MantleStage CAVES = Stage.mantle("iris:carve/caves"); + /** Cuts the planned caves out of the chunk's terrain and decorates their floors and ceilings. */ + public static final ChunkStage APPLY = Stage.chunk("iris:carve/apply"); + + private Carve() { + } + } + + /** Module {@code iris:objects}: the objects the dimension's regions and biomes place. */ + public static final class Objects { + /** Places surface, cave and upper-dimension objects into the mantle, after the caves they anchor in. */ + public static final MantleStage PLACE = Stage.mantle("iris:objects/place"); + + private Objects() { + } + } + + /** Module {@code iris:floating}: the floating islands of floating child biomes. */ + public static final class Floating { + /** Places the objects on and under the islands into the mantle, after the dimension's other objects. */ + public static final MantleStage OBJECTS = Stage.mantle("iris:floating/objects"); + /** Writes the islands' solid blocks. */ + public static final ChunkStage SOLIDS = Stage.chunk("iris:floating/solids"); + /** Decorates the islands' tops and bottoms once the chunk's own decoration is done. */ + public static final ChunkStage DECORATE = Stage.chunk("iris:floating/decorate"); + + private Floating() { + } + } + + /** Module {@code iris:structure}: Iris structures, assembled from pieces. */ + public static final class Structure { + /** Places the structures of the dimension, its regions and biomes into the mantle, after objects and floating objects. */ + public static final MantleStage PLACE = Stage.mantle("iris:structure/place"); + + private Structure() { + } + } + + /** Module {@code iris:terrain}: the solid ground, fluids and biome layers of a chunk. */ + public static final class Terrain { + /** Fills each column from bedrock up to its height and the fluid height, with its biome's layers. */ + public static final ChunkStage SHAPE = Stage.chunk("iris:terrain/shape"); + + private Terrain() { + } + } + + /** Module {@code iris:post}: smoothing a chunk's surface after carving. */ + public static final class Post { + /** Fills single-block holes, places slabs and walls on steps and settles snow. */ + public static final ChunkStage SMOOTH = Stage.chunk("iris:post/smooth"); + + private Post() { + } + } + + /** Module {@code iris:deposit}: ores and other deposits. */ + public static final class Deposit { + /** + * Places the deposits every level declares at the chunk's centre column, the dimension's, the region's and + * the biome's, each with its own clumps. Active where any column of the chunk has deposits. + */ + public static final ChunkStage ORES = Stage.chunk("iris:deposit/ores"); + + private Deposit() { + } + } + + /** Module {@code iris:matter}: the blocks the mantle planned for a chunk, such as objects and structures. */ + public static final class Matter { + /** Copies the chunk's planned mantle blocks into it. */ + public static final ChunkStage INSERT = Stage.chunk("iris:matter/insert"); + + private Matter() { + } + } + + /** Module {@code iris:decorant}: the decorators of biomes, such as grass, flowers and cave ceilings. */ + public static final class Decorant { + /** Places every column's surface, sea, shore and cave decorators. */ + public static final ChunkStage DECORATE = Stage.chunk("iris:decorant/decorate"); + + private Decorant() { + } + } + + /** Module {@code iris:perfection}: the last touches on an overworld chunk's blocks. */ + public static final class Perfection { + /** Hides ores when the dimension asks, then removes decorations that nothing holds up. */ + public static final ChunkStage SURFACE = Stage.chunk("iris:perfection/surface"); + + private Perfection() { + } + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/RegistryKeyFamily.java b/module/src/main/java/art/arcane/iris/builtin/RegistryKeyFamily.java new file mode 100644 index 000000000..eec55b733 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/RegistryKeyFamily.java @@ -0,0 +1,57 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin; + +import java.util.Locale; + +/** + * How the settings of Iris's built-ins name families of the platform's registry keys, such as structures and placed + * features: a pattern matches the keys equal to it and the keys it starts at a namespace, slash or underscore boundary, + * ignoring case and surrounding space. So {@code minecraft:village} matches {@code minecraft:village_plains}, + * {@code minecraft:ore} every vanilla ore, and {@code nova_structures:} a whole namespace. + */ +public final class RegistryKeyFamily { + private RegistryKeyFamily() { + } + + /** Whether the family pattern {@code pattern} matches the registry key {@code key}. */ + public static boolean matches(String pattern, String key) { + if (pattern == null || key == null) { + return false; + } + String normalizedPattern = normalize(pattern); + String normalizedKey = normalize(key); + if (normalizedPattern.isEmpty() || !normalizedKey.startsWith(normalizedPattern)) { + return false; + } + if (normalizedKey.length() == normalizedPattern.length()) { + return true; + } + char patternEnd = normalizedPattern.charAt(normalizedPattern.length() - 1); + if (patternEnd == ':' || patternEnd == '/' || patternEnd == '_') { + return true; + } + char boundary = normalizedKey.charAt(normalizedPattern.length()); + return boundary == '/' || boundary == '_'; + } + + private static String normalize(String key) { + return key.trim().toLowerCase(Locale.ROOT); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/anchor/AnchorHeight.java b/module/src/main/java/art/arcane/iris/builtin/anchor/AnchorHeight.java new file mode 100644 index 000000000..0b2806875 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/anchor/AnchorHeight.java @@ -0,0 +1,23 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.anchor; + +/** The height an object's anchor is placed at. */ +public record AnchorHeight(int y) { +} diff --git a/module/src/main/java/art/arcane/iris/builtin/anchor/AnchorSampling.java b/module/src/main/java/art/arcane/iris/builtin/anchor/AnchorSampling.java new file mode 100644 index 000000000..bd4c53a9d --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/anchor/AnchorSampling.java @@ -0,0 +1,39 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.anchor; + +/** How a placement mode finds the height of an object placed without a requested height. */ +public enum AnchorSampling { + /** The surface at the object's center, or the floor of the cave it is placed in. */ + CENTER, + /** The highest surface under any column of the object. */ + HIGHEST, + /** The highest surface under the object's four corners. */ + HIGHEST_CORNER, + /** The lowest surface under any column of the object. */ + LOWEST, + /** The lowest surface under the object's four corners. */ + LOWEST_CORNER, + /** The surface at the object's center, ignoring caves; each block then follows its own column. */ + SURFACE, + /** The translation alone, in open air. */ + TRANSLATION, + /** The requested height, even when negative. */ + REQUESTED +} diff --git a/module/src/main/java/art/arcane/iris/builtin/anchor/ObjectPlaceMode.java b/module/src/main/java/art/arcane/iris/builtin/anchor/ObjectPlaceMode.java new file mode 100644 index 000000000..116120b50 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/anchor/ObjectPlaceMode.java @@ -0,0 +1,138 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.anchor; + +import com.volmit.config.Desc; + + +@Desc("Object Place modes are useful for positioning objects just right. The default value is CENTER_HEIGHT.") +public enum ObjectPlaceMode { + @Desc("The default place mode. This mode picks a center point (where the center of the object will be) and takes the height. That height is used for the whole object.") + + CENTER_HEIGHT(PlaceMode.of(AnchorSampling.CENTER, StiltShape.NONE)), + + @Desc("Samples a lot of points where the object will cover (horizontally) and picks the highest height, that height is then used to place the object. This mode is useful for preventing any part of your object from being buried though it will float off of cliffs.") + + MAX_HEIGHT(PlaceMode.of(AnchorSampling.HIGHEST, StiltShape.NONE)), + + @Desc("Samples only 4 points where the object will cover (horizontally) and picks the highest height, that height is then used to place the object. This mode is useful for preventing any part of your object from being buried though it will float off of cliffs.\"") + + FAST_MAX_HEIGHT(PlaceMode.of(AnchorSampling.HIGHEST_CORNER, StiltShape.NONE)), + + @Desc("Samples a lot of points where the object will cover (horizontally) and picks the lowest height, that height is then used to place the object. This mode is useful for preventing any part of your object from overhanging a cliff though it gets buried a lot") + MIN_HEIGHT(PlaceMode.of(AnchorSampling.LOWEST, StiltShape.NONE)), + + @Desc("Samples only 4 points where the object will cover (horizontally) and picks the lowest height, that height is then used to place the object. This mode is useful for preventing any part of your object from overhanging a cliff though it gets buried a lot") + + FAST_MIN_HEIGHT(PlaceMode.of(AnchorSampling.LOWEST_CORNER, StiltShape.NONE)), + + @Desc("Stilting is MAX_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") + + STILT(PlaceMode.of(AnchorSampling.HIGHEST, StiltShape.STRAIGHT)), + + @Desc("Just like stilting but very inaccurate. Useful for stilting a lot of objects without too much care on accuracy (you can use the over-stilt value to force stilts under ground further)") + + FAST_STILT(PlaceMode.of(AnchorSampling.HIGHEST_CORNER, StiltShape.STRAIGHT)), + + @Desc("Stilting is MIN_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") + + MIN_STILT(PlaceMode.of(AnchorSampling.LOWEST, StiltShape.STRAIGHT)), + + @Desc("Just like MIN_STILT but very inaccurate. Useful for stilting a lot of objects without too much care on accuracy (you can use the over-stilt value to force stilts under ground further)") + + FAST_MIN_STILT(PlaceMode.of(AnchorSampling.LOWEST_CORNER, StiltShape.STRAIGHT)), + + @Desc("Stilting is CENTER_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") + + CENTER_STILT(PlaceMode.of(AnchorSampling.CENTER, StiltShape.STRAIGHT)), + + @Desc("Erode stilting tapers columns downward like an ice cream cone. Blocks near the center extend deepest while edge blocks drop off first. Blocks are randomly skipped in the lower portion for a rough organic eroded texture.") + + ERODE_STILT(PlaceMode.of(AnchorSampling.HIGHEST, StiltShape.ERODE)), + + @Desc("Organic stilting scans straight down from the bottom of the object to the first solid block (the cave floor, or terrain) and fills the gap with the object's own bottom block. Each column stops at a slightly different, noise-varied depth and the lower portion is randomly broken up, so the underside reads as rough organic roots rather than a flat disc. Designed for objects placed inside caves so they connect to the floor instead of floating. Tune with stilt-settings (organicMaxScan, organicJitter, organicScratch).") + + ORGANIC_STILT(PlaceMode.of(AnchorSampling.CENTER, StiltShape.ORGANIC, PlaceTrait.CAVE_ANCHORED)), + + @Desc("Hangs the object upside-down from a cave ceiling. The object is flipped vertically (its tip points down like a stalactite) and its top is anchored to the ceiling, while an organic, noise-varied stilt grows up into the ceiling so it never floats below the roof. Use inside caves; tune with stilt-settings (organicMaxScan, organicJitter, organicScratch).") + + CEILING_HANG(PlaceMode.of(AnchorSampling.CENTER, StiltShape.CEILING, PlaceTrait.UPSIDE_DOWN, PlaceTrait.CAVE_ANCHORED)), + + @Desc("Anchors the object at the terrain surface (plus translate.y) like CENTER_HEIGHT, then bends the surrounding terrain to be flush with the object's base. Columns inside the object footprint are raised (or lowered) to meet the base, and the deformation falls off parabolically out to a radius so the terrain smoothly blends back to its natural height. Use this to seat a floating/translated object on the ground without a flat stilt disc, e.g. a cube translated up 10 on a mountain pulls the terrain up to meet it. Tune with vacuum-settings (radius, falloff).") + + VACUUM(PlaceMode.vacuum(VacuumProfile.STANDARD)), + + @Desc("VACUUM with a larger radius and finer per-column sampling for the smoothest terrain blend. More expensive.") + + VACUUM_HIGH(PlaceMode.vacuum(VacuumProfile.HIGH)), + + @Desc("VACUUM with a smaller radius and coarser sampling for performance. Use when seating many objects.") + + VACUUM_FAST(PlaceMode.vacuum(VacuumProfile.FAST)), + + @Desc("VACUUM whose falloff radius is perturbed by noise per column, so the terrain meets the object with an irregular organic edge rather than a clean parabolic bowl.") + + VACUUM_ORGANIC(PlaceMode.vacuum(VacuumProfile.ORGANIC)), + + @Desc("VACUUM whose terrain bend is bent by smooth coherent simplex noise so the surface meets the object with a gently rolling, wavy slope instead of the ragged white-noise edge of VACUUM_ORGANIC or a clean parabolic bowl. The object itself still seats flush; the waves fade to zero under the object and at the outer rim, peaking across the mid-slope. Tune with vacuum-settings (waveAmplitude, waveScale).") + + VACUUM_WAVY(PlaceMode.vacuum(VacuumProfile.WAVY)), + + @Desc("Samples the height of the terrain at every x,z position of your object and pushes it down to the surface. It's pretty much like a melt function over the terrain.") + + PAINT(PlaceMode.of(AnchorSampling.SURFACE, StiltShape.NONE)), + + @Desc("Places the object in pure air at an absolute Y driven entirely by translate.y (plus optional translate.yRandom). Terrain height, underwater, and carving anchor checks are skipped. Use this for floating islands, sky structures, clouds, or blimps where the object must not be translated to the ground.") + + FLOATING(PlaceMode.of(AnchorSampling.TRANSLATION, StiltShape.NONE, PlaceTrait.FREE_HEIGHT)), + + @Desc("Raw stamp at the caller-supplied (x, y, z). No terrain sampling, no stilting, no Y recomputation, no underwater or carving anchor guards. Used internally to route native Minecraft structure pieces (villages etc.) through the Iris object placer.") + + STRUCTURE_PIECE(PlaceMode.of(AnchorSampling.REQUESTED, StiltShape.NONE, PlaceTrait.RAW_STAMP, PlaceTrait.FREE_HEIGHT)); + + private final PlaceMode placeMode; + + ObjectPlaceMode(PlaceMode placeMode) { + this.placeMode = placeMode; + } + + /** What the mode does, for the placement stages to ask. */ + public PlaceMode placeMode() { + return placeMode; + } + + /** + * The mode an object takes on a floating island, which has no ground below to grow stilts to or to stamp into: a + * stilt down to the ground becomes the same height sampling without the stilt, a raw stamp the default mode. + */ + public ObjectPlaceMode onFloatingIsland() { + if (placeMode.has(PlaceTrait.RAW_STAMP)) { + return CENTER_HEIGHT; + } + if (placeMode.stilt() != StiltShape.STRAIGHT && placeMode.stilt() != StiltShape.ERODE) { + return this; + } + for (ObjectPlaceMode mode : values()) { + if (mode.placeMode.equals(PlaceMode.of(placeMode.anchor(), StiltShape.NONE))) { + return mode; + } + } + throw new IllegalStateException("No place mode samples " + placeMode.anchor() + " without a stilt"); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/anchor/PlaceMode.java b/module/src/main/java/art/arcane/iris/builtin/anchor/PlaceMode.java new file mode 100644 index 000000000..ca9905946 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/anchor/PlaceMode.java @@ -0,0 +1,47 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.builtin.anchor; + +import java.util.Set; + +/** + * What an object place mode does, as data the placement stages ask instead of comparing modes: how it finds its + * height, the stilt it grows, how it bends the terrain around the object, and its traits. + */ +public record PlaceMode(AnchorSampling anchor, StiltShape stilt, VacuumProfile vacuum, Set traits) { + public PlaceMode { + traits = Set.copyOf(traits); + } + + public static PlaceMode of(AnchorSampling anchor, StiltShape stilt, PlaceTrait... traits) { + return new PlaceMode(anchor, stilt, VacuumProfile.NONE, Set.of(traits)); + } + + public static PlaceMode vacuum(VacuumProfile vacuum) { + return new PlaceMode(AnchorSampling.CENTER, StiltShape.NONE, vacuum, Set.of()); + } + + public boolean has(PlaceTrait trait) { + return traits.contains(trait); + } + + /** Whether the mode bends the terrain to meet the object's base. */ + public boolean bendsTerrain() { + return vacuum != VacuumProfile.NONE; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/anchor/PlaceTrait.java b/module/src/main/java/art/arcane/iris/builtin/anchor/PlaceTrait.java new file mode 100644 index 000000000..19a6bde7b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/anchor/PlaceTrait.java @@ -0,0 +1,30 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.builtin.anchor; + +/** A trait of an object place mode that changes what the placement stages do. */ +public enum PlaceTrait { + /** Stamps the object at the requested position as it is: no terrain sampling, no height recomputation. */ + RAW_STAMP, + /** Takes its height from the placement alone, so the terrain, water and carving guards do not apply. */ + FREE_HEIGHT, + /** Flips the object upside down and anchors its top. */ + UPSIDE_DOWN, + /** Anchors to a cave's floor or ceiling, so it keeps its own mode underground. */ + CAVE_ANCHORED +} diff --git a/module/src/main/java/art/arcane/iris/builtin/anchor/StiltShape.java b/module/src/main/java/art/arcane/iris/builtin/anchor/StiltShape.java new file mode 100644 index 000000000..1eef735f5 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/anchor/StiltShape.java @@ -0,0 +1,32 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.anchor; + +/** What a placement mode grows between the object and the ground or ceiling. */ +public enum StiltShape { + NONE, + /** Repeats the bottom layer straight down to the surface. */ + STRAIGHT, + /** Like {@link #STRAIGHT}, tapering toward the edges and broken up at depth. */ + ERODE, + /** Repeats the bottom layer down to the first solid block, each column a little different. */ + ORGANIC, + /** Hangs the flipped object from a ceiling and grows its top layer up into it. */ + CEILING +} diff --git a/module/src/main/java/art/arcane/iris/builtin/anchor/VacuumProfile.java b/module/src/main/java/art/arcane/iris/builtin/anchor/VacuumProfile.java new file mode 100644 index 000000000..2267d1a15 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/anchor/VacuumProfile.java @@ -0,0 +1,61 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.builtin.anchor; + +/** How a place mode bends the terrain around the object to meet its base; NONE leaves the terrain alone. */ +public enum VacuumProfile { + NONE(0, 1, Edge.PARABOLIC), + STANDARD(12, 1, Edge.PARABOLIC), + HIGH(20, 1, Edge.PARABOLIC), + FAST(8, 2, Edge.PARABOLIC), + ORGANIC(12, 1, Edge.JITTERED), + WAVY(12, 1, Edge.WAVY); + + /** The shape of the bend's outer edge. */ + public enum Edge { + PARABOLIC, + /** The radius perturbed per column. */ + JITTERED, + /** The bend rolled by smooth noise. */ + WAVY + } + + private final int defaultRadiusBlocks; + private final int columnStepBlocks; + private final Edge edge; + + VacuumProfile(int defaultRadiusBlocks, int columnStepBlocks, Edge edge) { + this.defaultRadiusBlocks = defaultRadiusBlocks; + this.columnStepBlocks = columnStepBlocks; + this.edge = edge; + } + + /** How far the bend reaches when the vacuum settings leave the radius open. */ + public int defaultRadiusBlocks() { + return defaultRadiusBlocks; + } + + /** Every how many columns the bend samples the terrain. */ + public int columnStepBlocks() { + return columnStepBlocks; + } + + public Edge edge() { + return edge; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java b/module/src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java new file mode 100644 index 000000000..bc7fc4a56 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java @@ -0,0 +1,67 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.blocks; + +import com.volmit.block.BlockSpec; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +/** One find-and-replace of an object placement's blocks, an entry of the placement's {@code edit}. */ +@Snippet("iris/blocks/object-block-replacer") +@Desc("Find and replace object materials") +public final class ObjectReplace { + @Required + @Desc("Find this block") + private List find = List.of(); + @Required + @Desc("Replace it with this block palette") + private PaletteSpec replace = PaletteSpec.of(List.of(BlockSpec.of("stone"))); + @Desc("Exactly match the block data or not") + private boolean exact = false; + @MinNumber(0) + @MaxNumber(1) + @Desc("Modifies the chance the block is replaced") + private float chance = 1; + + public ObjectReplace() { + } + + public List find() { + return find == null ? List.of() : Collections.unmodifiableList(find); + } + + public PaletteSpec replace() { + return replace == null ? PaletteSpec.of(List.of(BlockSpec.of("stone"))) : replace; + } + + public boolean exact() { + return exact; + } + + public float chance() { + return chance; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java b/module/src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java new file mode 100644 index 000000000..4f185a321 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java @@ -0,0 +1,61 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.blocks; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.BiConsumer; + +/** + * The object's own blocks a placement wrote, in world positions, in the order they were written. Positions and states + * are kept side by side, so recording a block allocates nothing beyond the position the placement already has. + */ +public final class WrittenBlocks { + private final List positions = new ArrayList<>(); + private final List states = new ArrayList<>(); + + public void add(BlockPosition position, BlockState state) { + positions.add(position); + states.add(state); + } + + public List positions() { + return Collections.unmodifiableList(positions); + } + + /** The written states, each at the index of its position in {@link #positions()}. */ + public List states() { + return Collections.unmodifiableList(states); + } + + /** Each written block's position and state, in the order they were written. */ + public void forEach(BiConsumer action) { + for (int index = 0; index < positions.size(); index++) { + action.accept(positions.get(index), states.get(index)); + } + } + + public boolean isEmpty() { + return positions.isEmpty(); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/carve/CarvingMode.java b/module/src/main/java/art/arcane/iris/builtin/carve/CarvingMode.java new file mode 100644 index 000000000..8a12fbefd --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/carve/CarvingMode.java @@ -0,0 +1,43 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.carve; + +import com.volmit.config.Desc; + +@Desc("Defines if an object is allowed to place in carvings, surfaces or both.") +public enum CarvingMode { + @Desc("Only place this object on surfaces (NOT under carvings)") + SURFACE_ONLY, + + @Desc("Only place this object under carvings (NOT on the surface)") + CARVING_ONLY, + + @Desc("This object can place anywhere") + ANYWHERE; + + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + public boolean supportsCarving() { + return this.equals(ANYWHERE) || this.equals(CARVING_ONLY); + } + + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + public boolean supportsSurface() { + return this.equals(ANYWHERE) || this.equals(SURFACE_ONLY); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/carve/CaveAnchorMode.java b/module/src/main/java/art/arcane/iris/builtin/carve/CaveAnchorMode.java new file mode 100644 index 000000000..189e5739a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/carve/CaveAnchorMode.java @@ -0,0 +1,21 @@ +package art.arcane.iris.builtin.carve; + +import com.volmit.config.Desc; + +@Desc("Defines which carved-space anchor to target for cave object placement.") +public enum CaveAnchorMode { + @Desc("Use the active cave profile default anchor mode.") + PROFILE_DEFAULT, + + @Desc("Target cave floor anchors where carved space has solid support below.") + FLOOR, + + @Desc("Target cave ceiling anchors where carved space has solid support above.") + CEILING, + + @Desc("Target carved positions with no immediate solid support above or below.") + CENTER, + + @Desc("Target any carved-space anchor.") + ANY +} diff --git a/module/src/main/java/art/arcane/iris/builtin/carve/CaveFieldModule.java b/module/src/main/java/art/arcane/iris/builtin/carve/CaveFieldModule.java new file mode 100644 index 000000000..e2267807d --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/carve/CaveFieldModule.java @@ -0,0 +1,66 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.carve; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Range; +import com.volmit.noise.NoiseStyle; + +/** One more layer of noise a cave profile blends into its density, an entry of the profile's {@code modules}. */ +@Desc("Represents a modular cave-density layer.") +public final class CaveFieldModule { + @Desc("Density style used by this module.") + private NoiseStyle style = NoiseStyle.of("CELLULAR_IRIS_DOUBLE"); + @MinNumber(0) + @Desc("Layer contribution multiplier.") + private double weight = 1; + @MinNumber(-1) + @MaxNumber(1) + @Desc("Threshold offset applied to this layer before blending.") + private double threshold = 0; + @Desc("Vertical bounds where this module can contribute, in engine-local Y where 0 is the bottom of the dimension, not world Y.") + private Range verticalRange = Range.of(0, 384); + @Desc("Invert this module before weighting.") + private boolean invert = false; + + public CaveFieldModule() { + } + + public NoiseStyle style() { + return style; + } + + public double weight() { + return weight; + } + + public double threshold() { + return threshold; + } + + public Range verticalRange() { + return verticalRange; + } + + public boolean invert() { + return invert; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/carve/CaveLavaHeightSettings.java b/module/src/main/java/art/arcane/iris/builtin/carve/CaveLavaHeightSettings.java new file mode 100644 index 000000000..51b174715 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/carve/CaveLavaHeightSettings.java @@ -0,0 +1,49 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.carve; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** A dimension's {@code caveLavaHeight}, written as the bare number. */ +@Desc("The subterranean fluid (cave lava) layer height, in engine-local Y where 0 is the bottom of the dimension, not world Y. With the default -64..320 height, 8 means world Y -56.") +@Feature(id = "iris:carve/lava-height", name = "Cave lava height", key = "caveLavaHeight", root = "height", targets = Level.DIMENSION) +public final class CaveLavaHeightSettings implements IrisFeature { + public static final int DEFAULT_HEIGHT = 8; + + @MinNumber(0) + @MaxNumber(318) + @Desc("The subterranean fluid (cave lava) layer height, in engine-local Y where 0 is the bottom of the dimension, not world Y. With the default -64..320 height, 8 means world Y -56.") + private int height = DEFAULT_HEIGHT; + + public CaveLavaHeightSettings() { + } + + public CaveLavaHeightSettings(int height) { + this.height = height; + } + + public int height() { + return height; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java b/module/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java new file mode 100644 index 000000000..32a99697e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java @@ -0,0 +1,49 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.decorant; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.Collections; +import java.util.List; + +/** + * The decorators one biome declares, written as {@code "decorators": [...]}, the list of decorators. IrisApi types only, like + * {@link Decorator}. + */ +@Desc("Decorators are used for things like tall grass, bisected flowers, and even kelp or cactus (random heights)") +@Feature(id = "iris:decorant", name = "Decorators", key = "decorators", root = "decorators", targets = Level.BIOME) +public final class DecorantSettings implements IrisFeature { + @Desc("Decorators are used for things like tall grass, bisected flowers, and even kelp or cactus (random heights)") + private List decorators = List.of(); + + public DecorantSettings() { + } + + public DecorantSettings(List decorators) { + this.decorators = List.copyOf(decorators); + } + + public List decorators() { + return decorators == null ? List.of() : Collections.unmodifiableList(decorators); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/decorant/DecorationPart.java b/module/src/main/java/art/arcane/iris/builtin/decorant/DecorationPart.java new file mode 100644 index 000000000..433ac4f25 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/decorant/DecorationPart.java @@ -0,0 +1,39 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.decorant; + +import com.volmit.config.Desc; + +@Desc("Represents a location where decorations should go") +public enum DecorationPart { + @Desc("The default, decorate anywhere") + NONE, + + @Desc("Targets shore lines (typically for sugar cane)") + SHORE_LINE, + + @Desc("Target sea surfaces (typically for lilypads)") + SEA_SURFACE, + + @Desc("Targets the sea floor (entire placement must be bellow sea level)") + SEA_FLOOR, + + @Desc("Decorates on cave & carving ceilings or underside of overhangs") + CEILING, +} diff --git a/module/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java b/module/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java new file mode 100644 index 000000000..4515ece32 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java @@ -0,0 +1,200 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.decorant; + +import art.arcane.iris.builtin.prepare.SlopeClip; +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; +import com.volmit.noise.NoiseStyle; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +/** + * One decorator of a biome, as packs write it in the {@code "decorators"} list or under + * {@code snippet/iris/decorant/decorator/}: which blocks it places, where, how often and how tall. A value of IrisApi types only; the + * decorant module resolves the blocks and builds the noise. + */ +@Snippet("iris/decorant/decorator") +@Desc("A biome decorator is used for placing flowers, grass, cacti and so on") +public final class Decorator { + private static final String STATIC_NOISE = "STATIC"; + private static final String DEFAULT_BLOCK = "grass"; + + @Desc("The varience dispersion is used when multiple blocks are put in the palette. Scatter scrambles them, Wispy shows streak-looking varience") + private NoiseStyle variance = NoiseStyle.of(STATIC_NOISE); + + @Desc("Forcefully place this decorant anywhere it is supposed to go even if it should not go on a specific surface block. For example, you could force tallgrass to place on top of stone by using this.") + private boolean forcePlace = false; + + @Desc("Forced the surface block of this decorant to be the specified block. Assumes forcePlace.") + private BlockSpec forceBlock; + + @Desc("When set, the decorator can only place onto any of these blocks.") + private List whitelist; + + @Desc("When set, the decorator will never place onto any of these blocks.") + private List blacklist; + + @Desc("The slope at which this decorator can be placed. Range from 0 to 10 by default. Calculated from a 3-block radius from the center of the decorator placement.") + private SlopeClip slopeCondition = new SlopeClip(); + + @Desc("If stackMax is set to true, use this to limit its max height for large caverns") + private int absoluteMaxStack = 30; + + @Desc("Dispersion is used to pick places to spawn. Scatter randomly places them (vanilla) or Wispy for a streak like patch system.") + private NoiseStyle style = NoiseStyle.of(STATIC_NOISE); + + @Desc("If this decorator has a height more than 1 this changes how it picks the height between your maxes. Scatter = random, Wispy = wavy heights") + private NoiseStyle heightVariance = NoiseStyle.of(STATIC_NOISE); + + @Desc("Tells iris where this decoration is a part of. I.e. SHORE_LINE or SEA_SURFACE") + private DecorationPart partOf = DecorationPart.NONE; + + @MinNumber(1) + @MaxNumber(2032) + @Desc("The minimum repeat stack height (setting to 3 would stack 3 of on top of each other") + private int stackMin = 1; + + @MinNumber(1) + @MaxNumber(2032) + @Desc("The maximum repeat stack height") + private int stackMax = 1; + + @Desc(""" + Changes stackMin and stackMin from being absolute block heights and instead uses them as a percentage to scale the stack based on the cave height + + Within a cave, setting them stackMin/max to 50 would make the stack 50% of the cave height""") + private boolean scaleStack = false; + + @Required + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance for this decorator to decorate at a given X,Y coordinate. This is hit 256 times per chunk (per surface block)") + private double chance = 0.1; + + @Required + @MinItems(1) + @Desc("The palette of blocks to pick from when this decorator needs to place.") + private List palette = List.of(BlockSpec.of(DEFAULT_BLOCK)); + + @Desc("The palette of blocks used at the very top of a 'stackMax' of higher than 1. For example, bamboo tops.") + private List topPalette = List.of(); + + @MinNumber(0.01) + @MaxNumber(1.0) + @Desc("When the stack passes the top threshold, the top palette will start being used instead of the normal palette.") + private double topThreshold = 1.0; + + /** A decorator with every option at its default, as packs get it from {@code {}}. */ + public Decorator() { + } + + public NoiseStyle variance() { + return variance == null ? NoiseStyle.of(STATIC_NOISE) : variance; + } + + public boolean forcePlace() { + return forcePlace; + } + + public Optional forceBlock() { + return Optional.ofNullable(forceBlock); + } + + /** The blocks it may only be placed onto; empty when unset, which {@link #hasWhitelist()} tells apart from an explicitly empty list that blocks all placement. */ + public List whitelist() { + return listOrEmpty(whitelist); + } + + public boolean hasWhitelist() { + return whitelist != null; + } + + public List blacklist() { + return listOrEmpty(blacklist); + } + + public boolean hasBlacklist() { + return blacklist != null; + } + + public SlopeClip slopeCondition() { + return slopeCondition == null ? new SlopeClip() : slopeCondition; + } + + public int absoluteMaxStack() { + return absoluteMaxStack; + } + + public NoiseStyle style() { + return style == null ? NoiseStyle.of(STATIC_NOISE) : style; + } + + public NoiseStyle heightVariance() { + return heightVariance == null ? NoiseStyle.of(STATIC_NOISE) : heightVariance; + } + + public DecorationPart partOf() { + return partOf == null ? DecorationPart.NONE : partOf; + } + + public int stackMin() { + return stackMin; + } + + public int stackMax() { + return stackMax; + } + + public boolean scaleStack() { + return scaleStack; + } + + public double chance() { + return chance; + } + + public List palette() { + return listOrEmpty(palette); + } + + public List topPalette() { + return listOrEmpty(topPalette); + } + + public double topThreshold() { + return topThreshold; + } + + /** Whether it places more than one block per column. */ + public boolean isStacking() { + return stackMax > 1; + } + + private static List listOrEmpty(List list) { + return list == null ? List.of() : Collections.unmodifiableList(list); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/loot/ItemAttributeModifier.java b/module/src/main/java/art/arcane/iris/builtin/loot/ItemAttributeModifier.java new file mode 100644 index 000000000..0a660809f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/loot/ItemAttributeModifier.java @@ -0,0 +1,78 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.loot; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +@Snippet("iris/loot/attribute-modifier") +@Desc("Represents an attribute modifier for an item or an entity. This allows you to create modifications to basic game attributes such as MAX_HEALTH or ARMOR_VALUE.") +public final class ItemAttributeModifier { + @Required + @Desc("The Attribute type key such as max_health or minecraft:armor. This type is pulled from the game attributes. Zombie & Horse attributes will not work on non-zombie/horse entities.\nUsing an attribute on an item will have affects when held, or worn. There is no way to specify further granularity as the game picks this depending on the item type.") + private String attribute = null; + + @Required + @Desc("The Attribute Name is used internally only for the game. This value should be unique to all other attributes applied to this item/entity. It is not shown in game.") + private String name = ""; + + @Desc("The application operation: ADD_NUMBER (default), ADD_SCALAR or MULTIPLY_SCALAR_1. Add Number adds to the default value. \nAdd scalar_1 will multiply by 1 for example if the health is 20 and you multiply_scalar_1 by 0.5, the health will result in 30, not 10. Use negative values to achieve that.") + private String operation = "ADD_NUMBER"; + + @Desc("Minimum amount for this modifier. Iris randomly chooses an amount, this is the minimum it can choose randomly for this attribute.") + private double minAmount = 1; + + @Desc("Maximum amount for this modifier Iris randomly chooses an amount, this is the maximum it can choose randomly for this attribute.") + private double maxAmount = 1; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance that this attribute is applied (0 to 1). If the chance is 0.5 (50%), then Iris will only apply this attribute 50% of the time.") + private double chance = 1; + + public ItemAttributeModifier() { + } + + public String attribute() { + return attribute; + } + + public String name() { + return name; + } + + public String operation() { + return operation; + } + + public double minAmount() { + return minAmount; + } + + public double maxAmount() { + return maxAmount; + } + + public double chance() { + return chance; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/loot/LootEnchantment.java b/module/src/main/java/art/arcane/iris/builtin/loot/LootEnchantment.java new file mode 100644 index 000000000..fdb4d10ac --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/loot/LootEnchantment.java @@ -0,0 +1,68 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.loot; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +@Snippet("iris/loot/enchantment") +@Desc("Represents an enchantment & level") +public final class LootEnchantment { + @Required + @Ref(Reference.ENCHANTMENT) + @Desc("The enchantment") + private String enchantment; + + @MinNumber(1) + @Desc("Minimum amount of this loot") + private int minLevel = 1; + + @MinNumber(1) + @Desc("Maximum amount of this loot") + private int maxLevel = 1; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance that this enchantment is applied (0 to 1)") + private double chance = 1; + + public LootEnchantment() { + } + + public String enchantment() { + return enchantment; + } + + public int minLevel() { + return minLevel; + } + + public int maxLevel() { + return maxLevel; + } + + public double chance() { + return chance; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/loot/LootEntry.java b/module/src/main/java/art/arcane/iris/builtin/loot/LootEntry.java new file mode 100644 index 000000000..bd1649c1a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/loot/LootEntry.java @@ -0,0 +1,176 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.loot; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +@Snippet("iris/loot/loot") +@Desc("Represents a loot entry") +public final class LootEntry { + public static final int MAX_AMOUNT = 64; + + @Desc("The target inventory slot types to fill this loot with. World generation only ever fills STORAGE; the other values are inert during worldgen.") + private LootSlot slotTypes = LootSlot.STORAGE; + + @MinNumber(1) + @Desc("The sub rarity of this loot. Calculated after this loot table has been picked.") + private int rarity = 1; + + @MinNumber(1) + @MaxNumber(MAX_AMOUNT) + @Desc("Minimum amount of this loot, from 1 to 64") + private int minAmount = 1; + + @MinNumber(1) + @MaxNumber(MAX_AMOUNT) + @Desc("Maximum amount of this loot, from 1 to 64") + private int maxAmount = 1; + + @Desc("The display name of this item") + private String displayName = null; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Minimum durability percent") + private double minDurability = 0; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Maximum durability percent") + private double maxDurability = 1; + + @Desc("Define a custom model identifier 1.14+ only") + private Integer customModel = null; + + @Desc("Set this to true to prevent it from being broken") + private boolean unbreakable = false; + + @Desc("The item flags to add") + private List itemFlags = List.of(); + + @Desc("Apply enchantments to this item") + private List enchantments = List.of(); + + @Desc("Apply attribute modifiers to this item") + private List attributes = List.of(); + + @Desc("Add lore to this item") + private List lore = List.of(); + + @Ref(Reference.ITEM) + @Required + @Desc("This is the item or block type. Does not accept minecraft:*, only materials such as DIAMOND_SWORD or DIRT. The exception are modded materials, as they require a namespace.") + private String type = ""; + + @Desc("The dye color") + private String dyeColor = null; + + @Desc("The leather armor color") + private String leatherColor = null; + + @Desc("Defines a custom NBT Tag for the item.") + private Map customNbt; + + public LootEntry() { + } + + public LootSlot slotTypes() { + return slotTypes == null ? LootSlot.STORAGE : slotTypes; + } + + public int rarity() { + return rarity; + } + + public int minAmount() { + return minAmount; + } + + public int maxAmount() { + return maxAmount; + } + + public String displayName() { + return displayName; + } + + public double minDurability() { + return minDurability; + } + + public double maxDurability() { + return maxDurability; + } + + public Integer customModel() { + return customModel; + } + + public boolean unbreakable() { + return unbreakable; + } + + public List itemFlags() { + return listOrEmpty(itemFlags); + } + + public List enchantments() { + return listOrEmpty(enchantments); + } + + public List attributes() { + return listOrEmpty(attributes); + } + + public List lore() { + return listOrEmpty(lore); + } + + /** The authored item key, exactly as written in the pack. Each platform resolves it against its own item registry. */ + public String type() { + return type; + } + + public String dyeColor() { + return dyeColor; + } + + public String leatherColor() { + return leatherColor; + } + + /** The custom data of the item; empty when unset. */ + public Map customNbt() { + return customNbt == null ? Map.of() : Collections.unmodifiableMap(customNbt); + } + + private static List listOrEmpty(List list) { + return list == null ? List.of() : Collections.unmodifiableList(list); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/loot/LootMode.java b/module/src/main/java/art/arcane/iris/builtin/loot/LootMode.java new file mode 100644 index 000000000..7fe817478 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/loot/LootMode.java @@ -0,0 +1,33 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.loot; + +import com.volmit.config.Desc; + +@Desc("A loot mode is used to describe what to do with the existing loot layers before adding this loot. ADD appends to the building list of tables (dimension tables, then region tables, then biome tables). REPLACE swaps the parent tables for this reference's tables. CLEAR suppresses loot entirely at this point.") +public enum LootMode { + @Desc("Add to the existing parent loot tables") + ADD, + @Desc("Clear all parent loot tables and contribute nothing at this level. Any tables listed here are ignored.") + CLEAR, + @Desc("Replace all parent loot tables with this reference's tables") + REPLACE, + @Desc("Only use when there was no loot table defined by an object") + FALLBACK +} diff --git a/module/src/main/java/art/arcane/iris/builtin/loot/LootResolver.java b/module/src/main/java/art/arcane/iris/builtin/loot/LootResolver.java new file mode 100644 index 000000000..71eb99106 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/loot/LootResolver.java @@ -0,0 +1,200 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.loot; + +import art.arcane.volmlib.util.math.RNG; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.ToIntFunction; + +/** + * The random streams loot is drawn from and the picks made on them, shared by the loot module and the hosts that fill + * containers, so a container always holds the same loot. Changing a seed, a salt or a draw changes the loot of existing worlds. + */ +public final class LootResolver { + private static final int MAX_SCALED_SOURCE_COUNT = 256; + private static final long CONTAINER_SALT = 0x632BE59BD9B4E019L; + private static final long TABLE_SALT = 0x94D049BB133111EBL; + private static final long ENTRY_SALT = 0x9E3779B97F4A7C15L; + + private LootResolver() { + } + + public static RNG containerRng(long lootSeed, int x, int y, int z) { + return new RNG(containerSeed(lootSeed, x, y, z)); + } + + public static long containerSeed(long lootSeed, int x, int y, int z) { + long seed = mix(lootSeed ^ CONTAINER_SALT); + seed = mix(seed ^ ((long) x * 0xD6E8FEB86659FD93L)); + seed = mix(seed ^ ((long) y * 0xA5A3564E27F886A7L)); + return mix(seed ^ ((long) z * 0x8CB92BA72F3D8DD7L)); + } + + /** The random stream of one loot table at one position; {@code tableIdentity} names the table (its key, else its name). */ + public static RNG tableRng(long lootSeed, String tableIdentity, int x, int y, int z) { + return new RNG(tableSeed(lootSeed, tableIdentity, x, y, z)); + } + + public static long tableSeed(long lootSeed, String tableIdentity, int x, int y, int z) { + return mix(containerSeed(lootSeed, x, y, z) ^ stableHash(tableIdentity) ^ TABLE_SALT); + } + + public static boolean spatialOneIn( + long lootSeed, + String tableIdentity, + int entryIndex, + int x, + int y, + int z, + long rarity + ) { + if (rarity <= 1L) { + return true; + } + long roll = mix(tableSeed(lootSeed, tableIdentity, x, y, z) ^ ((long) entryIndex * ENTRY_SALT)); + return new RNG(roll).nextLong(rarity) == 0L; + } + + public static long combinedRarity(int tableRarity, int entryRarity) { + long table = Math.max(1, tableRarity); + long entry = Math.max(1, entryRarity); + if (table > Long.MAX_VALUE / entry) { + return Long.MAX_VALUE; + } + return table * entry; + } + + public static boolean oneIn(RNG rng, int rarity) { + int bound = Math.max(1, rarity); + return bound == 1 || rng.nextInt(bound) == 0; + } + + public static int inclusive(RNG rng, int first, int second) { + int lower = Math.min(first, second); + int upper = Math.max(first, second); + if (lower == upper) { + return lower; + } + long span = (long) upper - lower + 1L; + return (int) (lower + rng.nextLong(span)); + } + + public static T pickWeighted(List choices, ToIntFunction weight, RNG rng) { + long total = 0L; + for (T choice : choices) { + int value = Math.max(0, weight.applyAsInt(choice)); + total = Long.MAX_VALUE - total < value ? Long.MAX_VALUE : total + value; + } + if (total <= 0L) { + return null; + } + long pull = rng.nextLong(total); + for (T choice : choices) { + pull -= Math.max(0, weight.applyAsInt(choice)); + if (pull < 0L) { + return choice; + } + } + return null; + } + + public static void scaleSources(List sources, double multiplier, RNG rng) { + if (!Double.isFinite(multiplier) || multiplier < 0D) { + throw new IllegalArgumentException("Effective loot source multiplier must be finite and non-negative, got " + + multiplier + "."); + } + if (sources.isEmpty()) { + return; + } + if (sources.size() > MAX_SCALED_SOURCE_COUNT) { + throw new IllegalArgumentException("Loot source scaling starts above the maximum of " + + MAX_SCALED_SOURCE_COUNT + " sources: " + sources.size() + "."); + } + double scaledSize = sources.size() * multiplier; + if (!Double.isFinite(scaledSize) || scaledSize > MAX_SCALED_SOURCE_COUNT) { + throw new IllegalArgumentException("Loot source scaling exceeds the maximum of " + + MAX_SCALED_SOURCE_COUNT + " sources: " + sources.size() + " * " + multiplier + "."); + } + int target = (int) Math.round(scaledSize); + if (target == sources.size()) { + return; + } + List original = new ArrayList<>(sources); + int[] order = new int[original.size()]; + if (target < original.size()) { + shrinkSources(sources, original, order, target, rng); + return; + } + expandSources(sources, original, order, target, rng); + } + + private static void shrinkSources(List sources, List original, int[] order, int target, RNG rng) { + shuffleOrder(order, rng); + boolean[] selected = new boolean[original.size()]; + for (int index = 0; index < target; index++) { + selected[order[index]] = true; + } + sources.clear(); + for (int index = 0; index < original.size(); index++) { + if (selected[index]) { + sources.add(original.get(index)); + } + } + } + + private static void expandSources(List sources, List original, int[] order, int target, RNG rng) { + while (sources.size() < target) { + shuffleOrder(order, rng); + int additions = Math.min(target - sources.size(), original.size()); + for (int index = 0; index < additions; index++) { + sources.add(original.get(order[index])); + } + } + } + + private static void shuffleOrder(int[] order, RNG rng) { + for (int index = 0; index < order.length; index++) { + order[index] = index; + } + for (int index = 0; index < order.length - 1; index++) { + int selected = index + rng.nextInt(order.length - index); + int previous = order[index]; + order[index] = order[selected]; + order[selected] = previous; + } + } + + private static long stableHash(String value) { + long hash = 0xCBF29CE484222325L; + for (int i = 0; i < value.length(); i++) { + hash ^= value.charAt(i); + hash *= 0x100000001B3L; + } + return mix(hash); + } + + private static long mix(long value) { + long mixed = value; + mixed = (mixed ^ (mixed >>> 30)) * 0xBF58476D1CE4E5B9L; + mixed = (mixed ^ (mixed >>> 27)) * 0x94D049BB133111EBL; + return mixed ^ (mixed >>> 31); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java b/module/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java new file mode 100644 index 000000000..5fa19fdf4 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java @@ -0,0 +1,72 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.loot; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.ResourceRef; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +/** + * The loot tables one dimension, region or biome adds to the containers it covers, written as + * {@code "loot": {"mode": "ADD", "tables": [...], "multiplier": 1}}. Levels stack, dimension first, then region and + * biome; {@link LootMode} says what each does with the tables before it. An entity's {@code loot} has the same shape. + */ +@Snippet("iris/loot/loot-registry") +@Desc("Reference loot tables in this area") +@Feature(id = "iris:loot", name = "Loot", key = "loot", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) +public final class LootSettings implements IrisFeature { + public static final double MAX_MULTIPLIER = 16D; + + @Desc("ADD = add on top of parent tables. REPLACE = clear parent tables, then add these. CLEAR = clear parent tables and add nothing, even if tables are listed. FALLBACK = only used when nothing else defined a table.") + private LootMode mode = LootMode.ADD; + + @ResourceRef(LootTable.class) + @Desc("Add loot table registries here") + private List tables = List.of(); + + @MinNumber(0) + @MaxNumber(MAX_MULTIPLIER) + @Desc("Scale loot sources in this area from 0 to 16 times their normal count") + private double multiplier = 1D; + + /** Nothing added, nothing scaled: what a level without loot settings means. */ + public LootSettings() { + } + + public LootMode mode() { + return mode == null ? LootMode.ADD : mode; + } + + /** The keys of the loot tables, in order. */ + public List tables() { + return tables == null ? List.of() : Collections.unmodifiableList(tables); + } + + public double multiplier() { + return multiplier; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/loot/LootSlot.java b/module/src/main/java/art/arcane/iris/builtin/loot/LootSlot.java new file mode 100644 index 000000000..6723d461a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/loot/LootSlot.java @@ -0,0 +1,38 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.loot; + +import com.volmit.config.Desc; + +@Desc("An inventory slot type is used to represent a type of slot for items to fit into in any given inventory.") +public enum LootSlot { + @Desc("Typically the one you want to go with. Storage represnents most slots in inventories.") + STORAGE, + + @Desc("Used for the fuel slot in Furnaces, Blast furnaces, smokers etc.") + FUEL, + + @Desc("Used for the cook slot in furnaces") + FURNACE, + @Desc("Used for the cook slot in blast furnaces") + BLAST_FURNACE, + + @Desc("Used for the cook slot in smokers") + SMOKER, +} diff --git a/module/src/main/java/art/arcane/iris/builtin/loot/LootTable.java b/module/src/main/java/art/arcane/iris/builtin/loot/LootTable.java new file mode 100644 index 000000000..a2ac13151 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/loot/LootTable.java @@ -0,0 +1,87 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.loot; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; + +import java.util.Collections; +import java.util.List; + +/** A loot table of the pack, one file of {@code loot/}. */ +@Desc("Represents a loot table. Biomes, Regions & Objects can add or replace the virtual table with these loot tables") +public final class LootTable { + public static final int MAX_PICKED = 64; + public static final int MAX_TRIES = 256; + + @Required + @Desc("The name of this loot table") + private String name = ""; + + @MinNumber(1) + @Desc("The rarity as in 1 in X chance") + private int rarity = 1; + + @MinNumber(1) + @MaxNumber(MAX_PICKED) + @Desc("The maximum amount of loot that can be picked in this table at a time, from 1 to 64") + private int maxPicked = 5; + + @MinNumber(0) + @MaxNumber(MAX_PICKED) + @Desc("The minimum amount of loot that can be picked in this table at a time, from 0 to 64") + private int minPicked = 1; + + @MinNumber(1) + @MaxNumber(MAX_TRIES) + @Desc("The maximum amount of tries to generate loot, from 1 to 256") + private int maxTries = 10; + + @Desc("The loot in this table") + private List loot = List.of(); + + public LootTable() { + } + + public String name() { + return name == null ? "" : name; + } + + public int rarity() { + return rarity; + } + + public int maxPicked() { + return maxPicked; + } + + public int minPicked() { + return minPicked; + } + + public int maxTries() { + return maxTries; + } + + public List loot() { + return loot == null ? List.of() : Collections.unmodifiableList(loot); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java b/module/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java new file mode 100644 index 000000000..6a869e548 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java @@ -0,0 +1,74 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.loot; + +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.ResourceRef; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +@Snippet("iris/loot/object-loot") +@Desc("Represents loot within this object") +public final class ObjectLoot implements ObjectLootEntry { + @Desc("The list of blocks this loot table should apply to") + private List filter = List.of(); + @Desc("Exactly match the block data or not") + private boolean exact = false; + @Desc("The loot table name") + @Required + @ResourceRef(LootTable.class) + private String name; + @Desc("The weight of this loot table being chosen") + @MinNumber(1) + private int weight = 1; + + public ObjectLoot() { + } + + /** A table for every container of the placement. */ + public ObjectLoot(String name, int weight) { + this.name = name; + this.weight = weight; + } + + @Override + public String name() { + return name; + } + + @Override + public int weight() { + return weight; + } + + @Override + public boolean exact() { + return exact; + } + + @Override + public List filter() { + return filter == null ? List.of() : Collections.unmodifiableList(filter); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/loot/ObjectLootEntry.java b/module/src/main/java/art/arcane/iris/builtin/loot/ObjectLootEntry.java new file mode 100644 index 000000000..92a2a5d77 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/loot/ObjectLootEntry.java @@ -0,0 +1,41 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.loot; + +import com.volmit.block.BlockSpec; + +import java.util.List; + +/** + * One loot table an object placement gives its containers: which table, how often it is picked among the placement's + * tables, and which of the object's containers it is for. + */ +public interface ObjectLootEntry { + /** The table: a key of the pack's loot tables, or a key of the platform's. */ + String name(); + + /** How often the table is picked among equals; a table with no weight is never picked. */ + int weight(); + + /** Whether the table applies to the exact state of the blocks in {@link #filter}, not to every state of their kind of block. */ + boolean exact(); + + /** The blocks the table is for; none means every container the placement holds. */ + List filter(); +} diff --git a/module/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java b/module/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java new file mode 100644 index 000000000..7af357045 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java @@ -0,0 +1,69 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.loot; + +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +@Snippet("iris/loot/object-vanilla-loot") +@Desc("Represents vanilla loot within this object") +public final class ObjectVanillaLoot implements ObjectLootEntry { + @Desc("The list of blocks this loot table should apply to") + private List filter = List.of(); + @Desc("Exactly match the block data or not") + private boolean exact = false; + @Desc("The vanilla loot table key") + @Required + @Ref(Reference.LOOT_TABLE) + private String name; + @Desc("The weight of this loot table being chosen") + @MinNumber(1) + private int weight = 1; + + public ObjectVanillaLoot() { + } + + @Override + public String name() { + return name; + } + + @Override + public int weight() { + return weight; + } + + @Override + public boolean exact() { + return exact; + } + + @Override + public List filter() { + return filter == null ? List.of() : Collections.unmodifiableList(filter); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java b/module/src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java new file mode 100644 index 000000000..c4b7857b7 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java @@ -0,0 +1,134 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; +import com.volmit.noise.NoiseStyle; + +import java.util.Collections; +import java.util.List; + +/** The virtual heightmap an object placement may sit on instead of the terrain, written as the placement's {@code heightmap}. */ +@Snippet("iris/objects/generator") +@Desc("A noise generator") +public final class HeightmapNoise { + @MinNumber(0.0001) + @Desc("The coordinate input zoom") + private double zoom = 1; + @Desc("Reverse the output. So that noise = -noise + opacity") + private boolean negative = false; + @MinNumber(0) + @MaxNumber(1) + @Desc("The output multiplier") + private double opacity = 1; + @Desc("Coordinate offset x") + private double offsetX = 0; + @Desc("Height output offset y. Avoid using with terrain generation.") + private double offsetY = 0; + @Desc("Coordinate offset z") + private double offsetZ = 0; + @Required + @Desc("The seed") + private long seed = 0; + @Desc("Apply a parametric curve on the output") + private boolean parametric = false; + @Desc("Apply a bezier curve on the output") + private boolean bezier = false; + @Desc("Apply a sin-center curve on the output (0, and 1 = 0 and 0.5 = 1.0 using a sinoid shape.)") + private boolean sinCentered = false; + @Desc("The exponent noise^EXPONENT") + private double exponent = 1; + @Desc("Enable / disable. Outputs offsetY if disabled") + private boolean enabled = true; + @Required + @Desc("The Noise Style") + private NoiseStyle style = NoiseStyle.of("IRIS"); + @MinNumber(1) + @Desc("Multiple octaves for multple generators of changing zooms added together") + private int octaves = 1; + @Desc("Apply a child noise generator to fracture the input coordinates of this generator") + private List fracture = List.of(); + + public HeightmapNoise() { + } + + public double zoom() { + return zoom; + } + + public boolean negative() { + return negative; + } + + public double opacity() { + return opacity; + } + + public double offsetX() { + return offsetX; + } + + public double offsetY() { + return offsetY; + } + + public double offsetZ() { + return offsetZ; + } + + public long seed() { + return seed; + } + + public boolean parametric() { + return parametric; + } + + public boolean bezier() { + return bezier; + } + + public boolean sinCentered() { + return sinCentered; + } + + public double exponent() { + return exponent; + } + + public boolean enabled() { + return enabled; + } + + public NoiseStyle style() { + return style; + } + + public int octaves() { + return octaves; + } + + public List fracture() { + return fracture == null ? List.of() : Collections.unmodifiableList(fracture); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java b/module/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java new file mode 100644 index 000000000..db0040d1a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java @@ -0,0 +1,717 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.blocks.ObjectReplace; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.carve.CaveAnchorMode; +import art.arcane.iris.builtin.loot.ObjectLoot; +import art.arcane.iris.builtin.loot.ObjectVanillaLoot; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.builtin.prepare.SlopeClip; +import art.arcane.iris.builtin.spawn.PlacementMarker; +import art.arcane.iris.builtin.stilt.StiltSettings; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.builtin.validate.ObjectLimit; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.ResourceRef; +import com.volmit.config.Snippet; +import com.volmit.noise.NoiseStyle; +import com.volmit.noise.StyledRange; +import com.volmit.object.GeneratedObject; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; + +/** + * One object placement of a biome or region, an entry of its {@code objects}: which objects, how often, and how they sit + * in the world. {@code iris:objects} decides from the options it owns (what to place, chance, density, carving and + * surface support); Iris's placement stages read the rest from the placement itself, so this keeps the JSON the placement + * was written as ({@link #json()}) for Iris to read it again the way it reads placements everywhere else. + */ +@Snippet("iris/objects/object-placer") +@Desc("Represents an iris object placer. It places objects.") +@JsonAdapter(ObjectPlacement.KeepingItsJson.class) +public final class ObjectPlacement { + private static final int DEFAULT_SURFACE_SUPPORT_BUFFER = 2; + private static final int DEFAULT_SURFACE_SUPPORT_DEPTH = 2; + + @Required + @ResourceRef(GeneratedObject.class) + @Desc("List of objects to place") + private List place = List.of(); + @Desc("Rotate this objects placement") + private ObjectRotation rotation = new ObjectRotation(); + @Desc("Limit the max height or min height of placement.") + private ObjectLimit clamp = new ObjectLimit(); + @MinNumber(0) + @MaxNumber(1) + @Desc("The maximum layer level of a snow filter overtop of this placement. Set to 0 to disable. Max of 1.") + private double snow = 0; + @Desc("Whether or not this object can be targeted by a dolphin.") + private boolean isDolphinTarget = false; + @Desc("The slope at which this object can be placed. Range from 0 to 10 by default. Calculated from a 3-block radius from the center of the object placement.") + private SlopeClip slopeCondition = new SlopeClip(); + @Desc("Set to true to add the rotation of the direction of the slope of the terrain (wherever the slope is going down) to the y-axis rotation of the object." + + "Rounded to 90 degrees. Adds the *min* rotation of the y axis as well (to still allow you to rotate objects nicely). Discards *max* and *interval* on *yaxis*") + private boolean rotateTowardsSlope = false; + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance for this to place in a chunk. If you need multiple per chunk, set this to 1 and use density.") + private double chance = 1; + @Desc("If set, chance is multiplied by this noise (0 to 1) at the chunk, so objects gather in some areas and thin out in others.") + private NoiseStyle chanceStyle = null; + @MinNumber(0) + @Desc("Keeps objects of this placement at least this many blocks apart, also across chunks and biomes that place the same objects. Each chunk then places at most one. 0 turns it off. Surface placements only.") + private int separation = 0; + @MinNumber(1) + @Desc("If the chance check passes, place this many in a single chunk. Ignored when separation is set.") + private int density = 1; + @Desc("If the chance check passes, and you specify this, it picks a number in the range based on noise, and 'density' is ignored.") + private StyledRange densityStyle = null; + @Desc("When stilting is enabled, this object will define various properties related to it.") + private StiltSettings stiltSettings; + @Desc("When a VACUUM place mode is used, this defines the deformation radius and falloff.") + private VacuumSettings vacuumSettings; + @MaxNumber(64) + @MinNumber(0) + @Desc("When bore is enabled, expand max-y of the cuboid it removes") + private int boreExtendMaxY = 0; + @Desc("Add markers to blocks in this object") + private List markers = List.of(); + @MaxNumber(64) + @MinNumber(-1) + @Desc("When bore is enabled, lower min-y of the cuboid it removes") + private int boreExtendMinY = 0; + @Desc("If set to true, objects will place on the terrain height, ignoring the water surface.") + private boolean underwater = false; + @Desc("If set to true, objects will place in carvings (such as underground) or under an overhang.") + private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; + @MinNumber(0) + @MaxNumber(16) + @Desc("Extra buffer, in blocks, around this object's base footprint that must also be solid, un-carved ground. 0 checks only the footprint itself.") + private int surfaceSupportBuffer = DEFAULT_SURFACE_SUPPORT_BUFFER; + @MinNumber(1) + @MaxNumber(16) + @Desc("Minimum thickness, in blocks, of un-carved ground required under every column of this object's base footprint.") + private int surfaceSupportDepth = DEFAULT_SURFACE_SUPPORT_DEPTH; + @Desc("Set to false to let this placement sit over carved surface openings such as cave entrances.") + private boolean requireSurfaceSupport = true; + @Desc("When carving placement is enabled, select which carved-space anchor this placement targets.") + private CaveAnchorMode caveAnchorMode = CaveAnchorMode.PROFILE_DEFAULT; + @Desc("If this is defined, this object wont place on the terrain heightmap, but instead on this virtual heightmap") + private HeightmapNoise heightmap; + @Desc("If set to true, Iris will try to fill the insides of 'rooms' and 'pockets' where air should fit based off of raytrace checks. This prevents a village house placing in an area where a tree already exists, and instead replaces the parts of the tree where the interior of the structure is. \n\nThis operation does not affect warmed-up generation speed however it does slow down loading objects.") + private boolean smartBore = false; + @Desc("If set to true, Blocks placed underwater that could be waterlogged are waterlogged.") + private boolean waterloggable = false; + @Desc("If set to true, objects will place on the fluid height level Such as boats.") + private boolean onwater = false; + @Desc("If set to true, this object will only place parts of itself where blocks already exist. Warning: Melding is very performance intensive!") + private boolean meld = false; + @Desc("If set to true, this object will get placed from the bottom of the world up") + private boolean fromBottom; + @Desc("If set to true, this object will place from the ground up instead of height checks when not y locked to the surface. This is not compatable with X and Z axis rotations (it may look off)") + private boolean bottom = false; + @Desc("If set to true, air will be placed before the schematic places.") + private boolean bore = false; + @Desc("Use a generator to warp the field of coordinates. Using simplex for example would make a square placement warp like a flag") + private NoiseStyle warp = NoiseStyle.of(NoiseStyle.FLAT); + @Desc("The placement mode") + private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; + @Desc("Find and replace blocks") + private List edit = List.of(); + @Desc("Translate this object's placement") + private ObjectTranslate translate = new ObjectTranslate(); + @Desc("Scale Objects") + private ObjectScale scale = new ObjectScale(); + @Desc("The loot tables to apply to these objects") + private List loot = List.of(); + @Desc("The vanilla loot tables to apply to these objects") + private List vanillaLoot = List.of(); + @Desc("Whether the given loot tables override any and all other loot tables available in the dimension, region or biome.") + private boolean overrideGlobalLoot = false; + @Desc("This object / these objects override the following trees when they grow...") + private List trees = List.of(); + @ResourceRef(GeneratedObject.class) + @Desc("List of objects to this object is allowed to collied with") + private List allowedCollisions = List.of(); + @ResourceRef(GeneratedObject.class) + @Desc("List of objects to this object is forbidden to collied with") + private List forbiddenCollisions = List.of(); + @Desc("Ignore any placement restrictions for this object") + @SerializedName(value = "forcePlace", alternate = {"force"}) + private boolean forcePlace = false; + + private transient volatile String json; + + public ObjectPlacement() { + } + + private ObjectPlacement(ObjectPlacement source) { + place = source.place; + rotation = source.rotation; + clamp = source.clamp; + snow = source.snow; + isDolphinTarget = source.isDolphinTarget; + slopeCondition = source.slopeCondition; + rotateTowardsSlope = source.rotateTowardsSlope; + chance = source.chance; + chanceStyle = source.chanceStyle; + separation = source.separation; + density = source.density; + densityStyle = source.densityStyle; + stiltSettings = source.stiltSettings; + vacuumSettings = source.vacuumSettings; + boreExtendMaxY = source.boreExtendMaxY; + markers = source.markers; + boreExtendMinY = source.boreExtendMinY; + underwater = source.underwater; + carvingSupport = source.carvingSupport; + surfaceSupportBuffer = source.surfaceSupportBuffer; + surfaceSupportDepth = source.surfaceSupportDepth; + requireSurfaceSupport = source.requireSurfaceSupport; + caveAnchorMode = source.caveAnchorMode; + heightmap = source.heightmap; + smartBore = source.smartBore; + waterloggable = source.waterloggable; + onwater = source.onwater; + meld = source.meld; + fromBottom = source.fromBottom; + bottom = source.bottom; + bore = source.bore; + warp = source.warp; + mode = source.mode; + edit = source.edit; + translate = source.translate; + scale = source.scale; + loot = source.loot; + vanillaLoot = source.vanillaLoot; + overrideGlobalLoot = source.overrideGlobalLoot; + trees = source.trees; + allowedCollisions = source.allowedCollisions; + forbiddenCollisions = source.forbiddenCollisions; + forcePlace = source.forcePlace; + json = source.json; + } + + /** A builder of a placement made in code, starting from the defaults a pack's placement starts from. */ + public static Builder builder() { + return new Builder(new ObjectPlacement()); + } + + /** + * A builder of a copy of this placement with some options changed. The copy keeps the JSON this placement was + * read from, so the module settings it declares, and what Iris made of it, unless a noise option changes. + */ + public Builder toBuilder() { + return new Builder(new ObjectPlacement(this)); + } + + /** The objects to pick from, by the keys of the pack's objects. */ + public List place() { + return listOf(place); + } + + public ObjectRotation rotation() { + return rotation; + } + + public ObjectLimit clamp() { + return clamp; + } + + public double snow() { + return snow; + } + + public boolean isDolphinTarget() { + return isDolphinTarget; + } + + public SlopeClip slopeCondition() { + return slopeCondition; + } + + public boolean rotateTowardsSlope() { + return rotateTowardsSlope; + } + + public double chance() { + return chance; + } + + /** The noise, from 0 to 1, that {@link #chance()} is multiplied by at each chunk; empty when the chance is the same everywhere. */ + public Optional chanceStyle() { + return Optional.ofNullable(chanceStyle); + } + + /** The least distance in blocks between two objects of placements with the same objects; 0 when they are not kept apart. */ + public int separation() { + return separation; + } + + public boolean isSeparated() { + return separation > 0; + } + + /** The count of placements when the chance check passes, unless {@link #densityStyle()} picks it. */ + public int density() { + return density; + } + + public Optional densityStyle() { + return Optional.ofNullable(densityStyle); + } + + /** The fixed density, or, when a style picks the count, the middle of its range. */ + public int middleDensity() { + if (densityStyle == null) { + return density; + } + return (int) ((densityStyle.max() + densityStyle.min()) / 2); + } + + public Optional stiltSettings() { + return Optional.ofNullable(stiltSettings); + } + + public Optional vacuumSettings() { + return Optional.ofNullable(vacuumSettings); + } + + public int boreExtendMaxY() { + return boreExtendMaxY; + } + + public List markers() { + return listOf(markers); + } + + public int boreExtendMinY() { + return boreExtendMinY; + } + + public boolean underwater() { + return underwater; + } + + public CarvingMode carvingSupport() { + return carvingSupport; + } + + public int surfaceSupportBuffer() { + return surfaceSupportBuffer; + } + + public int surfaceSupportDepth() { + return surfaceSupportDepth; + } + + public boolean requireSurfaceSupport() { + return requireSurfaceSupport; + } + + public CaveAnchorMode caveAnchorMode() { + return caveAnchorMode; + } + + /** The virtual heightmap the objects place on instead of the terrain, if one is set. */ + public Optional heightmap() { + return Optional.ofNullable(heightmap); + } + + public boolean smartBore() { + return smartBore; + } + + public boolean waterloggable() { + return waterloggable; + } + + public boolean onwater() { + return onwater; + } + + public boolean meld() { + return meld; + } + + public boolean fromBottom() { + return fromBottom; + } + + public boolean bottom() { + return bottom; + } + + public boolean bore() { + return bore; + } + + public NoiseStyle warp() { + return warp; + } + + public ObjectPlaceMode mode() { + return mode; + } + + public List edit() { + return listOf(edit); + } + + public ObjectTranslate translate() { + return translate; + } + + public ObjectScale scale() { + return scale; + } + + public List loot() { + return listOf(loot); + } + + public List vanillaLoot() { + return listOf(vanillaLoot); + } + + public boolean overrideGlobalLoot() { + return overrideGlobalLoot; + } + + public List trees() { + return listOf(trees); + } + + /** Whether one of the trees this placement overrides is the species {@code species} grown on a sapling area of {@code width} by {@code depth}. */ + public boolean overridesTree(int width, int depth, String species) { + return trees().stream().anyMatch(tree -> tree.matches(width, depth, species)); + } + + public List allowedCollisions() { + return listOf(allowedCollisions); + } + + public List forbiddenCollisions() { + return listOf(forbiddenCollisions); + } + + public boolean forcePlace() { + return forcePlace; + } + + /** The JSON this placement was read from, which declares its module settings; null for one made in code. */ + public String json() { + return json; + } + + /** + * The names a placement's own options are written under: every field Gson reads, under its {@code @SerializedName} and + * alternates. Settings other modules declare on a placement may not take these keys + * ({@link com.volmit.FeatureRegistry#registerPlacementType}). + */ + public static Set jsonFields() { + Set names = new TreeSet<>(); + for (Field field : ObjectPlacement.class.getDeclaredFields()) { + int modifiers = field.getModifiers(); + if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers) || field.isSynthetic()) { + continue; + } + SerializedName serialized = field.getAnnotation(SerializedName.class); + if (serialized == null) { + names.add(field.getName()); + continue; + } + names.add(serialized.value()); + names.addAll(Arrays.asList(serialized.alternate())); + } + return names; + } + + private static List listOf(List values) { + return values == null ? List.of() : Collections.unmodifiableList(values); + } + + /** Sets the options of a placement made in code; each setter returns the builder. */ + public static final class Builder { + private final ObjectPlacement placement; + + private Builder(ObjectPlacement placement) { + this.placement = placement; + } + + public Builder place(List keys) { + placement.place = List.copyOf(keys); + return this; + } + + public Builder rotation(ObjectRotation rotation) { + placement.rotation = rotation; + return this; + } + + public Builder clamp(ObjectLimit clamp) { + placement.clamp = clamp; + return this; + } + + public Builder snow(double snow) { + placement.snow = snow; + return this; + } + + public Builder slopeCondition(SlopeClip slopeCondition) { + placement.slopeCondition = slopeCondition; + return this; + } + + public Builder rotateTowardsSlope(boolean rotateTowardsSlope) { + placement.rotateTowardsSlope = rotateTowardsSlope; + return this; + } + + public Builder chance(double chance) { + placement.chance = chance; + return this; + } + + public Builder density(int density) { + placement.density = density; + return this; + } + + public Builder densityStyle(StyledRange densityStyle) { + placement.densityStyle = densityStyle; + return this; + } + + public Builder stiltSettings(StiltSettings stiltSettings) { + placement.stiltSettings = stiltSettings; + return this; + } + + public Builder vacuumSettings(VacuumSettings vacuumSettings) { + placement.vacuumSettings = vacuumSettings; + return this; + } + + public Builder boreExtendMaxY(int blocks) { + placement.boreExtendMaxY = blocks; + return this; + } + + public Builder markers(List markers) { + placement.markers = List.copyOf(markers); + return this; + } + + public Builder boreExtendMinY(int blocks) { + placement.boreExtendMinY = blocks; + return this; + } + + public Builder underwater(boolean underwater) { + placement.underwater = underwater; + return this; + } + + public Builder carvingSupport(CarvingMode carvingSupport) { + placement.carvingSupport = carvingSupport; + return this; + } + + public Builder surfaceSupportBuffer(int blocks) { + placement.surfaceSupportBuffer = blocks; + return this; + } + + public Builder surfaceSupportDepth(int blocks) { + placement.surfaceSupportDepth = blocks; + return this; + } + + public Builder requireSurfaceSupport(boolean require) { + placement.requireSurfaceSupport = require; + return this; + } + + public Builder caveAnchorMode(CaveAnchorMode caveAnchorMode) { + placement.caveAnchorMode = caveAnchorMode; + return this; + } + + public Builder heightmap(HeightmapNoise heightmap) { + placement.heightmap = heightmap; + return this; + } + + public Builder smartBore(boolean smartBore) { + placement.smartBore = smartBore; + return this; + } + + public Builder waterloggable(boolean waterloggable) { + placement.waterloggable = waterloggable; + return this; + } + + public Builder onwater(boolean onwater) { + placement.onwater = onwater; + return this; + } + + public Builder meld(boolean meld) { + placement.meld = meld; + return this; + } + + public Builder fromBottom(boolean fromBottom) { + placement.fromBottom = fromBottom; + return this; + } + + public Builder bottom(boolean bottom) { + placement.bottom = bottom; + return this; + } + + public Builder bore(boolean bore) { + placement.bore = bore; + return this; + } + + public Builder warp(NoiseStyle warp) { + placement.warp = warp; + return this; + } + + public Builder mode(ObjectPlaceMode mode) { + placement.mode = mode; + return this; + } + + public Builder edit(List edit) { + placement.edit = List.copyOf(edit); + return this; + } + + public Builder translate(ObjectTranslate translate) { + placement.translate = translate; + return this; + } + + public Builder scale(ObjectScale scale) { + placement.scale = scale; + return this; + } + + public Builder loot(List loot) { + placement.loot = List.copyOf(loot); + return this; + } + + public Builder vanillaLoot(List vanillaLoot) { + placement.vanillaLoot = List.copyOf(vanillaLoot); + return this; + } + + public Builder overrideGlobalLoot(boolean override) { + placement.overrideGlobalLoot = override; + return this; + } + + public Builder trees(List trees) { + placement.trees = List.copyOf(trees); + return this; + } + + public Builder allowedCollisions(List keys) { + placement.allowedCollisions = List.copyOf(keys); + return this; + } + + public Builder forbiddenCollisions(List keys) { + placement.forbiddenCollisions = List.copyOf(keys); + return this; + } + + public Builder forcePlace(boolean forcePlace) { + placement.forcePlace = forcePlace; + return this; + } + + /** The placement; the builder must not be used after. */ + /** The placement as set so far; later changes to the builder do not reach it. */ + public ObjectPlacement build() { + return new ObjectPlacement(placement); + } + } + + /** Reads a placement like any settings and keeps the JSON it was read from. */ + public static final class KeepingItsJson implements TypeAdapterFactory { + @Override + @SuppressWarnings("unchecked") // The type is checked to be ObjectPlacement. + public TypeAdapter create(Gson gson, TypeToken type) { + if (type.getRawType() != ObjectPlacement.class) { + return null; + } + TypeAdapter placements = gson.getDelegateAdapter(this, TypeToken.get(ObjectPlacement.class)); + TypeAdapter elements = gson.getAdapter(JsonElement.class); + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ObjectPlacement placement) throws IOException { + placements.write(out, placement); + } + + @Override + public ObjectPlacement read(JsonReader in) throws IOException { + JsonElement written = elements.read(in); + ObjectPlacement placement = placements.fromJsonTree(written); + if (placement != null) { + placement.json = written.toString(); + } + return placement; + } + }.nullSafe(); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/objects/ObjectRun.java b/module/src/main/java/art/arcane/iris/builtin/objects/ObjectRun.java new file mode 100644 index 000000000..9b30d09df --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/objects/ObjectRun.java @@ -0,0 +1,219 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.noise.NoiseStyle; +import com.volmit.object.PackObjects; +import com.volmit.object.PlaceableObject; +import com.volmit.placement.PlacementOutcome; +import com.volmit.placement.PlacementRequest; +import com.volmit.placement.PlacementRun; +import com.volmit.placement.PlacementTerrain; +import com.volmit.world.PackWorld; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.OptionalInt; + +/** + * One object placed through the pack's placement stages with an object placement's settings: the input Iris's built-in + * placement stages read ({@link PlacementRun#input}), and what they report back, the height the object was anchored at + * and which of the written blocks are the object's own. Made for one placement; not thread-safe. + */ +public final class ObjectRun { + private static final int NOT_ANCHORED = Integer.MIN_VALUE; + private static final int NEIGHBOR_READ_BLOCKS = 1; + private static final long X_MULTIPLIER = 0x9E3779B97F4A7C15L; + private static final long Z_MULTIPLIER = 0xC2B2AE3D27D4EB4FL; + private static final long Y_MULTIPLIER = 0x165667B19E3779F9L; + private static final long FNV_OFFSET_BASIS = 0xCBF29CE484222325L; + private static final long FNV_PRIME = 0x100000001B3L; + + private PlaceableObject object; + private final ObjectPlacement settings; + private final int x; + private final int requestedY; + private final int z; + private final Cave cave; + private final List objectBlocks = new ArrayList<>(); + private int anchorY = NOT_ANCHORED; + + private ObjectRun(PlaceableObject object, ObjectPlacement settings, int x, int requestedY, int z, Cave cave) { + this.object = Objects.requireNonNull(object, "object"); + this.settings = Objects.requireNonNull(settings, "settings"); + this.x = x; + this.requestedY = requestedY; + this.z = z; + this.cave = cave; + } + + /** @param requestedY the height to place at, or a negative value for the stages to sample it */ + public static ObjectRun of(PlaceableObject object, ObjectPlacement settings, int x, int requestedY, int z) { + return new ObjectRun(object, settings, x, requestedY, z, null); + } + + /** A placement inside {@code cave}, which the stages anchor in and keep the object's height within. */ + public static ObjectRun inCave(PlaceableObject object, ObjectPlacement settings, int x, int requestedY, int z, Cave cave) { + return new ObjectRun(object, settings, x, requestedY, z, Objects.requireNonNull(cave, "cave")); + } + + /** + * The cave an object is placed in. + * + * @param surface the height of its floor + * @param height how many blocks high it is + */ + public record Cave(int surface, int height) { + } + + /** Places the object into {@code terrain} through the pack's placement stages of {@code world} ({@link #toRun}). */ + public PlacementOutcome placeIn(PackWorld world, PlacementTerrain terrain) { + return world.placements().place(toRun(terrain, world)); + } + + /** + * The run of this placement in {@code terrain}. Its seed comes from the world's seed and the placement's identity, the + * object's name and requested position, so the same placement draws the same in every run. Its area is every column + * the object reaches in any rotation around its anchor, moved by its translation and surface warp, and one block more + * for neighbor reads. A placement that smart bores bores its object first, so the stages see the bored air. + */ + public PlacementRun toRun(PlacementTerrain terrain, PackWorld world) { + return toRun(terrain, world.seed(), world.resources().objects()); + } + + /** As {@link #toRun(PlacementTerrain, PackWorld)}, for a world of seed {@code worldSeed} whose pack's objects are {@code objects}. */ + public PlacementRun toRun(PlacementTerrain terrain, long worldSeed, PackObjects objects) { + if (settings.smartBore()) { + object = objects.smartBored(object); + } + PlacementRequest request = new PlacementRequest(object.geometry(), new BlockPosition(x, requestedY, z)); + return new PlacementRun(request, object.name(), Optional.ofNullable(settings.json()), area(), terrain, this, + placementSeed(worldSeed)); + } + + public PlaceableObject object() { + return object; + } + + /** The settings as the caller passed them; the stages derive what they change, such as the rotation, themselves. */ + public ObjectPlacement settings() { + return settings; + } + + public int x() { + return x; + } + + /** The height the caller asked for, negative when the stages sample it. */ + public int requestedY() { + return requestedY; + } + + public int z() { + return z; + } + + /** The cave the object is placed in; empty outside caves. */ + public Optional cave() { + return Optional.ofNullable(cave); + } + + /** Reports the height the object was anchored at. */ + public void anchoredAt(int y) { + anchorY = y; + } + + /** The height the object was anchored at; empty until a stage anchors it. */ + public OptionalInt anchorY() { + return anchorY == NOT_ANCHORED ? OptionalInt.empty() : OptionalInt.of(anchorY); + } + + /** Reports a written block as one of the object's own, as opposed to boring, stilts, snow or a terrain bend. */ + public void objectBlockWritten(BlockPosition position) { + objectBlocks.add(position); + } + + /** The object's own blocks the stages wrote, in the order they wrote them; they reach the world only if it is placed. */ + public List objectBlocks() { + return Collections.unmodifiableList(objectBlocks); + } + + private BlockBox area() { + int objectRadius = Math.max(rotationRadius(object.geometry().bounds()), rotationRadius(declaredBox())); + int reach = objectRadius + translationLength(settings.translate()) + warpMargin(settings.warp()) + NEIGHBOR_READ_BLOCKS; + return new BlockBox(x - reach, Integer.MIN_VALUE, z - reach, x + reach + 1, Integer.MAX_VALUE, z + reach + 1); + } + + /** The object's declared size around its center, which its block offsets count from. */ + private BlockBox declaredBox() { + BlockPosition center = object.center(); + return new BlockBox(-center.x(), -center.y(), -center.z(), Math.max(1, object.width()) - center.x(), + Math.max(1, object.height()) - center.y(), Math.max(1, object.depth()) - center.z()); + } + + /** The farthest any block of {@code bounds} lies from the origin, which rotations turn around. */ + private static int rotationRadius(BlockBox bounds) { + long farthestX = farthest(bounds.minX(), bounds.maxX()); + long farthestY = farthest(bounds.minY(), bounds.maxY()); + long farthestZ = farthest(bounds.minZ(), bounds.maxZ()); + return (int) Math.ceil(Math.sqrt(farthestX * farthestX + farthestY * farthestY + farthestZ * farthestZ)); + } + + private static long farthest(int min, int maxExclusive) { + return Math.max(Math.abs((long) min), Math.abs((long) maxExclusive - 1)); + } + + private static int translationLength(ObjectTranslate translate) { + long translateX = translate.x(); + long translateY = translate.y(); + long translateZ = translate.z(); + return (int) Math.ceil(Math.sqrt(translateX * translateX + translateY * translateY + translateZ * translateZ)); + } + + private static int warpMargin(NoiseStyle warp) { + return warps(warp) ? (int) Math.ceil(Math.abs(warp.multiplier()) / 2D) : 0; + } + + /** + * Whether {@code warp} moves the placement's columns: any base style but {@link NoiseStyle#FLAT}. Unlike + * {@link NoiseStyle#isFlat()}, a flat style with an expression still does not warp, as Iris always read it. + */ + public static boolean warps(NoiseStyle warp) { + return !NoiseStyle.FLAT.equals(warp.style()); + } + + private long placementSeed(long worldSeed) { + return worldSeed ^ fnv1a(object.name()) ^ (x * X_MULTIPLIER) ^ (requestedY * Y_MULTIPLIER) ^ (z * Z_MULTIPLIER); + } + + private static long fnv1a(String text) { + long hash = FNV_OFFSET_BASIS; + for (byte value : text.getBytes(StandardCharsets.UTF_8)) { + hash = (hash ^ (value & 0xFF)) * FNV_PRIME; + } + return hash; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/objects/ObjectScale.java b/module/src/main/java/art/arcane/iris/builtin/objects/ObjectScale.java new file mode 100644 index 000000000..67330c549 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/objects/ObjectScale.java @@ -0,0 +1,85 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Snippet; + +/** How an object placement scales its objects, written as the placement's {@code scale}. */ +@Snippet("iris/objects/object-scale") +@Desc("Scale Objects") +public final class ObjectScale { + private static final double NO_SCALE = 1; + + @MinNumber(0.01) + @MaxNumber(50) + @Desc("Fixed scale multiplier for this object. 0.5 shrinks to half size, 2.0 doubles the size. When set to anything other than 1, this overrides minimumScale and maximumScale. Leave at 1 to use the minimumScale/maximumScale range.") + private double size = NO_SCALE; + + @MinNumber(1) + @MaxNumber(32) + @Desc("Iris Objects are scaled and cached to speed up placements. Because of this extra memory is used, so we evenly distribute variations across the defined scale range, then pick one randomly. If the differences is small, use a lower number. For more possibilities on the scale spectrum, increase this at the cost of memory.") + private int variations = 7; + + @MinNumber(0.01) + @MaxNumber(50) + @Desc("The minimum scale. Used when size is 1 to pick a random scale per placement.") + private double minimumScale = NO_SCALE; + + @MinNumber(0.01) + @MaxNumber(50) + @Desc("The maximum scale. Used when size is 1 to pick a random scale per placement.") + private double maximumScale = NO_SCALE; + + @Desc("If this object is scaled up beyond its origin size, specify a 3D interpolator. NONE keeps blocky scaled output, TRILINEAR (LERP) smooths with linear interpolation, TRICUBIC and TRIHERMITE produce smoother but slower output.") + private ScaleInterpolation interpolation = ScaleInterpolation.NONE; + + public ObjectScale() { + } + + public double size() { + return size; + } + + public int variations() { + return variations; + } + + public double minimumScale() { + return minimumScale; + } + + public double maximumScale() { + return maximumScale; + } + + public ScaleInterpolation interpolation() { + return interpolation == null ? ScaleInterpolation.NONE : interpolation; + } + + /** The largest factor this scale makes an object, which a placement's reach has to cover. */ + public double maxScale() { + if (size != NO_SCALE) { + return size; + } + return Math.max(minimumScale, maximumScale); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java b/module/src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java new file mode 100644 index 000000000..a5a420060 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java @@ -0,0 +1,45 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.Collections; +import java.util.List; + +/** + * The object placements a region or biome declares, written as {@code "objects": [...]}, the list of placements. A chunk + * places those of its centre column's region and of that column's biome, and of the cave biome where it places in caves. + */ +@Desc("Objects define what schematics (iob files) iris will place here") +@Feature(id = "iris:objects", name = "Objects", key = "objects", root = "objects", targets = {Level.REGION, Level.BIOME}) +public final class ObjectSettings implements IrisFeature { + @Desc("Objects define what schematics (iob files) iris will place here") + private List objects = List.of(); + + public ObjectSettings() { + } + + public List objects() { + return objects == null ? List.of() : Collections.unmodifiableList(objects); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/objects/RequireSurfaceSupportSettings.java b/module/src/main/java/art/arcane/iris/builtin/objects/RequireSurfaceSupportSettings.java new file mode 100644 index 000000000..a612ba35e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/objects/RequireSurfaceSupportSettings.java @@ -0,0 +1,41 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** Whether a dimension refuses surface objects over carved openings, written as {@code "requireObjectSurfaceSupport": true}. */ +@Desc("Refuse to place surface objects and trees over carved surface openings.") +@Feature(id = "iris:objects/surface-support", name = "Require surface support", key = "requireObjectSurfaceSupport", root = "require", targets = Level.DIMENSION) +public final class RequireSurfaceSupportSettings implements IrisFeature { + private static final boolean DEFAULT_REQUIRED = true; + + @Desc("Refuse to place surface objects and trees over carved surface openings.") + private boolean require = DEFAULT_REQUIRED; + + public RequireSurfaceSupportSettings() { + } + + public boolean require() { + return require; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/objects/ScaleInterpolation.java b/module/src/main/java/art/arcane/iris/builtin/objects/ScaleInterpolation.java new file mode 100644 index 000000000..077e3e80e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/objects/ScaleInterpolation.java @@ -0,0 +1,33 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import com.volmit.config.Desc; + +@Desc("Use 3D Interpolation on scaled objects if they are larger than the origin.") +public enum ScaleInterpolation { + @Desc("Don't interpolate, big cubes") + NONE, + @Desc("Uses linear interpolation in 3 dimensions, generally pretty good, but slow") + TRILINEAR, + @Desc("Uses cubic spline interpolation in 3 dimensions, even better, but extreme slowdowns") + TRICUBIC, + @Desc("Uses hermite spline interpolation in 3 dimensions, even better, but extreme slowdowns") + TRIHERMITE +} diff --git a/module/src/main/java/art/arcane/iris/builtin/objects/SurfaceSupportBufferSettings.java b/module/src/main/java/art/arcane/iris/builtin/objects/SurfaceSupportBufferSettings.java new file mode 100644 index 000000000..4070d0713 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/objects/SurfaceSupportBufferSettings.java @@ -0,0 +1,45 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** The least surface-support buffer a dimension gives its surface objects, written as {@code "objectSurfaceSupportBuffer": 2}. */ +@Desc("Minimum surface-support buffer, in blocks, applied to every surface object placement in this dimension. A placement may ask for more but never less.") +@Feature(id = "iris:objects/surface-support-buffer", name = "Surface support buffer", key = "objectSurfaceSupportBuffer", root = "buffer", targets = Level.DIMENSION) +public final class SurfaceSupportBufferSettings implements IrisFeature { + private static final int DEFAULT_BUFFER_BLOCKS = 2; + + @MinNumber(0) + @MaxNumber(16) + @Desc("Minimum surface-support buffer, in blocks, applied to every surface object placement in this dimension. A placement may ask for more but never less.") + private int buffer = DEFAULT_BUFFER_BLOCKS; + + public SurfaceSupportBufferSettings() { + } + + public int buffer() { + return buffer; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java b/module/src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java new file mode 100644 index 000000000..584c1eb87 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java @@ -0,0 +1,73 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import com.volmit.config.Desc; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +/** The trees an object placement overrides when their saplings grow, an entry of the placement's {@code trees}. */ +@Snippet("iris/objects/tree") +@Desc("Tree replace options for this object placer") +public final class TreeOverride { + @Required + @Desc("The types of trees overwritten by this object") + private List treeTypes = List.of(); + + @Required + @Desc("The size of the square of saplings this applies to (2 means a 2 * 2 sapling area)") + private List sizes = List.of(); + + public TreeOverride() { + } + + public List treeTypes() { + return treeTypes == null ? List.of() : Collections.unmodifiableList(treeTypes); + } + + public List sizes() { + return sizes == null ? List.of() : Collections.unmodifiableList(sizes); + } + + /** Whether this override is for a sapling area of {@code width} by {@code depth} growing the species {@code species}. */ + public boolean matches(int width, int depth, String species) { + return matchesSize(width, depth) && matchesSpecies(species); + } + + private boolean matchesSize(int width, int depth) { + for (TreeSize size : sizes()) { + if (size.matches(width, depth)) { + return true; + } + } + return false; + } + + private boolean matchesSpecies(String species) { + for (String type : treeTypes()) { + if (type != null && type.equalsIgnoreCase(species)) { + return true; + } + } + return false; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/objects/TreeSize.java b/module/src/main/java/art/arcane/iris/builtin/objects/TreeSize.java new file mode 100644 index 000000000..25b6e4928 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/objects/TreeSize.java @@ -0,0 +1,57 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import com.volmit.config.Desc; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +/** The size of a sapling area, in saplings, that a tree override applies to. */ +@Snippet("iris/objects/tree-size") +@Desc("Sapling override object picking options") +public final class TreeSize { + @Required + @Desc("The width of the sapling area") + private int width = 1; + + @Required + @Desc("The depth of the sapling area") + private int depth = 1; + + public TreeSize() { + } + + public TreeSize(int width, int depth) { + this.width = width; + this.depth = depth; + } + + public int width() { + return width; + } + + public int depth() { + return depth; + } + + /** Whether an area of {@code otherWidth} by {@code otherDepth} saplings is this size, turned either way. */ + public boolean matches(int otherWidth, int otherDepth) { + return (width == otherWidth && depth == otherDepth) || (depth == otherWidth && width == otherDepth); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsForceSettings.java b/module/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsForceSettings.java new file mode 100644 index 000000000..1e4a6c507 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsForceSettings.java @@ -0,0 +1,39 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** Whether the objects placed in the terrain stacked above ignore placement restrictions, written as {@code "upperObjectsForcePlace": true}. */ +@Desc("When true, upper-dimension objects force-place regardless of placement restrictions (slope, underwater, clamp, collisions, carving). Normal dimension objects always place first; upper objects place second and may clip or occlude lower-dimension placements when this is enabled.") +@Feature(id = "iris:objects/upper-force", name = "Force upper dimension objects", key = "upperObjectsForcePlace", root = "force", targets = Level.DIMENSION) +public final class UpperObjectsForceSettings implements IrisFeature { + @Desc("When true, upper-dimension objects force-place regardless of placement restrictions (slope, underwater, clamp, collisions, carving). Normal dimension objects always place first; upper objects place second and may clip or occlude lower-dimension placements when this is enabled.") + private boolean force = false; + + public UpperObjectsForceSettings() { + } + + public boolean force() { + return force; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsSettings.java b/module/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsSettings.java new file mode 100644 index 000000000..27592d959 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsSettings.java @@ -0,0 +1,39 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** Whether the objects of a dimension are also placed in the terrain stacked above it, written as {@code "upperDimensionObjects": true}. */ +@Desc("When true, objects from the mantle (structures, trees, etc.) can be placed in the upper dimension terrain zone. When false, the upper terrain is protected from object placement.") +@Feature(id = "iris:objects/upper", name = "Upper dimension objects", key = "upperDimensionObjects", root = "enabled", targets = Level.DIMENSION) +public final class UpperObjectsSettings implements IrisFeature { + @Desc("When true, objects from the mantle (structures, trees, etc.) can be placed in the upper dimension terrain zone. When false, the upper terrain is protected from object placement.") + private boolean enabled = false; + + public UpperObjectsSettings() { + } + + public boolean enabled() { + return enabled; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/package-info.java b/module/src/main/java/art/arcane/iris/builtin/package-info.java new file mode 100644 index 000000000..8d084d393 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/package-info.java @@ -0,0 +1,40 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * The public face of Iris's built-in modules: every stage constant, in {@link art.arcane.iris.builtin.IrisStages}, + * and the settings and output types of those stages. {@link art.arcane.iris.core.modules.IrisModuleHost} exposes this package, with its + * subpackages, to pack modules, so a pack jar can {@code requires(...)} a built-in stage and read its + * output. Everything here is part of what packs compile against. + *

+ * Keep implementation out of it: stage bodies and anything that uses Iris internals live in the + * built-in module classes outside this package, which packs cannot see. Settings and output types go in one + * subpackage per built-in module, named after the module path, such as {@code art.arcane.iris.builtin.spawn} + * for {@code iris:spawn}. A type only the built-ins jar uses, which Iris itself never reads, lives in + * {@code art.arcane.iris.modules} instead, which Iris does not expose. + *

+ * Besides those, it holds what Iris and the built-ins jar must share, since each sees its own copy + * of every other class: narrow facades only Iris's own built-ins use, interfaces Iris's worlds implement + * ({@link art.arcane.iris.builtin.structure.StructureHost}), and the seed purposes of the built-in features + * ({@link art.arcane.iris.builtin.IrisSeedPurposes}). Keep them few: each is a promise. + *

+ * The placement stages ({@code iris:prepare} to {@code iris:snow}) run in the pack's placement graph, which + * {@code PackWorld.placements()} runs. They read the object and its settings from the run's input, + * {@link art.arcane.iris.builtin.objects.ObjectRun}, which Iris also builds when it places an object itself. + */ +package art.arcane.iris.builtin; diff --git a/module/src/main/java/art/arcane/iris/builtin/prepare/AxisRotationClamp.java b/module/src/main/java/art/arcane/iris/builtin/prepare/AxisRotationClamp.java new file mode 100644 index 000000000..5a2ab46e4 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/prepare/AxisRotationClamp.java @@ -0,0 +1,132 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.prepare; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Objects; + +/** One axis of an object rotation, with the angles it may turn by and the steps between them. */ +@Snippet("iris/prepare/axis-rotation") +@Desc("Represents a rotation axis with intervals and maxes. The x and z axis values are defaulted to disabled. The Y axis defaults to on, rotating by 90 degree increments.") +public final class AxisRotationClamp { + private static final double FULL_TURN_DEGREES = 360D; + + @Desc("Should this axis be rotated at all?") + private boolean enabled = false; + + private transient boolean forceLock = false; + + @Required + @MinNumber(-360) + @MaxNumber(360) + @Desc("The minimum angle (from) or set this and max to zero for any angle degrees. Set both to the same non-zero value to force it to that angle only") + private double min = 0; + + @Required + @MinNumber(-360) + @MaxNumber(360) + @Desc("The maximum angle (to) or set this and min to zero for any angle degrees. Set both to the same non-zero value to force it to that angle only") + private double max = 0; + + @Required + @MinNumber(0) + @MaxNumber(360) + @Desc("Iris spins the axis but not freely. For example an interval of 90 would mean 4 possible angles (right angles) degrees. \nSetting this to 0 means totally free rotation.\n\nNote that a lot of structures can have issues with non 90 degree intervals because the minecraft block resolution is so low.") + private double interval = 0; + + public AxisRotationClamp() { + } + + /** An axis turned as {@code enabled} says, by angles from {@code min} to {@code max} in steps of {@code interval}. */ + public static AxisRotationClamp of(boolean enabled, boolean forceLock, double min, double max, double interval) { + AxisRotationClamp clamp = new AxisRotationClamp(); + clamp.enabled = enabled; + clamp.forceLock = forceLock; + clamp.min = min; + clamp.max = max; + clamp.interval = interval; + return clamp; + } + + /** An axis that turns to exactly {@code angle}, in steps of {@code interval}, whatever its min and max say. */ + public static AxisRotationClamp locked(boolean enabled, double angle, double interval) { + return of(enabled, true, angle, angle, interval); + } + + public boolean enabled() { + return enabled; + } + + public double min() { + return min; + } + + public double max() { + return max; + } + + public double interval() { + return interval; + } + + public boolean isUnlimited() { + return min == max && min == 0; + } + + public boolean isLocked() { + return min == max && !isUnlimited(); + } + + public double getRadians(int rng) { + if (forceLock) { + return Math.toRadians(Math.ceil(Math.abs((max % FULL_TURN_DEGREES)))); + } + + if (isUnlimited()) { + double resolvedInterval = interval < 1 ? 1 : interval; + return Math.toRadians((resolvedInterval * (Math.ceil(Math.abs((rng % FULL_TURN_DEGREES) / resolvedInterval)))) % FULL_TURN_DEGREES); + } + + if (min == max && min != 0) { + return Math.toRadians(max); + } + + double angle = (interval * (Math.ceil(Math.abs((rng % FULL_TURN_DEGREES) / interval)))) % FULL_TURN_DEGREES; + return Math.toRadians(Math.min(Math.max(min, max), Math.max(Math.min(min, max), angle))); + } + + @Override + public boolean equals(Object other) { + return other instanceof AxisRotationClamp clamp + && enabled == clamp.enabled + && Double.compare(min, clamp.min) == 0 + && Double.compare(max, clamp.max) == 0 + && Double.compare(interval, clamp.interval) == 0; + } + + @Override + public int hashCode() { + return Objects.hash(enabled, min, max, interval); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java b/module/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java new file mode 100644 index 000000000..12ad4e3b7 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java @@ -0,0 +1,279 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.prepare; + +import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.value.IrisPosition; +import art.arcane.volmlib.util.math.IrisBlockVector; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; + +import java.util.Objects; + +/** + * How an object is turned around each axis, written as a placement's {@code rotation}. Positions turn around X, then Z, + * then Y; an axis locked to a multiple of a quarter turn swaps coordinates exactly instead of turning by an angle. + */ +@Snippet("iris/prepare/object-rotator") +@Desc("Configures rotation for iris") +public final class ObjectRotation { + private static final double QUARTER_TURN_DEGREES = 90; + private static final double HALF_TURN_DEGREES = 180; + private static final double THREE_QUARTER_TURN_DEGREES = 270; + private static final double FULL_TURN_DEGREES = 360; + + @Desc("If this rotator is enabled or not") + private boolean enabled = true; + + @Desc("The x axis rotation") + private AxisRotationClamp xAxis = new AxisRotationClamp(); + + @Desc("The y axis rotation") + private AxisRotationClamp yAxis = AxisRotationClamp.of(true, false, 0, 0, QUARTER_TURN_DEGREES); + + @Desc("The z axis rotation") + private AxisRotationClamp zAxis = new AxisRotationClamp(); + + public ObjectRotation() { + } + + /** A rotation with the given axes. */ + public static ObjectRotation of(boolean enabled, AxisRotationClamp xAxis, AxisRotationClamp yAxis, AxisRotationClamp zAxis) { + ObjectRotation rotation = new ObjectRotation(); + rotation.enabled = enabled; + rotation.xAxis = xAxis; + rotation.yAxis = yAxis; + rotation.zAxis = zAxis; + return rotation; + } + + /** A rotation locked to the given angles, in degrees; enabled only when one of them is not 0. */ + public static ObjectRotation of(double x, double y, double z) { + return of(x != 0 || y != 0 || z != 0, + AxisRotationClamp.locked(x != 0, x, QUARTER_TURN_DEGREES), + AxisRotationClamp.locked(y != 0, y, QUARTER_TURN_DEGREES), + AxisRotationClamp.locked(z != 0, z, QUARTER_TURN_DEGREES)); + } + + /** Upside down: half a turn around X and no turn around Y or Z. */ + public static ObjectRotation xFlip180() { + return of(true, AxisRotationClamp.locked(true, HALF_TURN_DEGREES, 0), new AxisRotationClamp(), new AxisRotationClamp()); + } + + /** Upside down, then a random quarter turn around Y. */ + public static ObjectRotation xFlip180RandomY() { + return xFlip180().withYAxis(AxisRotationClamp.of(true, false, 0, 0, QUARTER_TURN_DEGREES)); + } + + /** Upside down, then {@code y} degrees around Y. */ + public static ObjectRotation xFlip180WithY(double y) { + return xFlip180().withYAxis(AxisRotationClamp.locked(true, y, QUARTER_TURN_DEGREES)); + } + + /** This rotation with {@code axis} around Y. */ + public ObjectRotation withYAxis(AxisRotationClamp axis) { + return of(enabled, xAxis, axis, zAxis); + } + + public boolean enabled() { + return enabled; + } + + public AxisRotationClamp xAxis() { + return xAxis; + } + + public AxisRotationClamp yAxis() { + return yAxis; + } + + public AxisRotationClamp zAxis() { + return zAxis; + } + + public boolean canRotateX() { + return enabled && xAxis.enabled(); + } + + public boolean canRotateY() { + return enabled && yAxis.enabled(); + } + + public boolean canRotateZ() { + return enabled && zAxis.enabled(); + } + + public boolean canRotate() { + return canRotateX() || canRotateY() || canRotateZ(); + } + + /** The angle, in radians, the object turns around {@code axis} for the random {@code spin}; 0 when the rotation or the axis is off. */ + public double radians(AxisRotationClamp axis, int spin) { + if (!enabled || !axis.enabled()) { + return 0; + } + return axis.getRadians(spin); + } + + public double xRadians(int spin) { + return radians(xAxis, spin); + } + + public double yRadians(int spin) { + return radians(yAxis, spin); + } + + public double zRadians(int spin) { + return radians(zAxis, spin); + } + + public IrisBlockVector rotate(IrisBlockVector position) { + return rotate(position, 0, 0, 0); + } + + public IrisPosition rotate(IrisPosition position) { + return rotate(position, 0, 0, 0); + } + + public IrisPosition rotate(IrisPosition position, int spinX, int spinY, int spinZ) { + IrisBlockVector turned = rotate(new IrisBlockVector(position.getX(), position.getY(), position.getZ()), spinX, spinY, spinZ); + return new IrisPosition(turned.getBlockX(), turned.getBlockY(), turned.getBlockZ()); + } + + /** The direction closest to {@code direction} turned by this rotation. */ + public IrisDirection rotate(IrisDirection direction) { + IrisBlockVector turned = rotate(new IrisBlockVector(direction.x(), direction.y(), direction.z())); + double closestDistance = Double.MAX_VALUE; + IrisDirection closest = null; + for (IrisDirection candidate : IrisDirection.values()) { + double distance = new IrisBlockVector(candidate.x(), candidate.y(), candidate.z()).distance(turned); + if (distance < closestDistance) { + closestDistance = distance; + closest = candidate; + } + } + return closest; + } + + /** {@code position} turned around X, then Z, then Y, each by the angle {@code spin} picks for it; a copy unless nothing turns. */ + public IrisBlockVector rotate(IrisBlockVector position, int spinX, int spinY, int spinZ) { + if (!canRotate()) { + return position; + } + IrisBlockVector turned = position.clone(); + if (canRotateX()) { + turnAroundX(turned, spinX); + } + if (canRotateZ()) { + turnAroundZ(turned, spinZ); + } + if (canRotateY()) { + turnAroundY(turned, spinY); + } + return turned; + } + + private void turnAroundX(IrisBlockVector v, int spin) { + if (!xAxis.isLocked()) { + v.rotateAroundX(xRadians(spin)); + return; + } + double angle = xAxis.max(); + if (Math.abs(angle) % FULL_TURN_DEGREES == HALF_TURN_DEGREES) { + v.setZ(-v.getZ()); + v.setY(-v.getY()); + } else if (isQuarterTurn(angle)) { + double z = v.getZ(); + v.setZ(v.getY()); + v.setY(-z); + } else if (isThreeQuarterTurn(angle)) { + double z = v.getZ(); + v.setZ(-v.getY()); + v.setY(z); + } else { + v.rotateAroundX(xRadians(spin)); + } + } + + private void turnAroundZ(IrisBlockVector v, int spin) { + if (!zAxis.isLocked()) { + v.rotateAroundZ(zRadians(spin)); + return; + } + double angle = zAxis.max(); + if (Math.abs(angle) % FULL_TURN_DEGREES == HALF_TURN_DEGREES) { + v.setY(-v.getY()); + v.setX(-v.getX()); + } else if (isQuarterTurn(angle)) { + double y = v.getY(); + v.setY(v.getX()); + v.setX(-y); + } else if (isThreeQuarterTurn(angle)) { + double y = v.getY(); + v.setY(-v.getX()); + v.setX(y); + } else { + v.rotateAroundZ(zRadians(spin)); + } + } + + private void turnAroundY(IrisBlockVector v, int spin) { + if (!yAxis.isLocked()) { + v.rotateAroundY(yRadians(spin)); + return; + } + double angle = yAxis.max(); + if (Math.abs(angle) % FULL_TURN_DEGREES == HALF_TURN_DEGREES) { + v.setX(-v.getX()); + v.setZ(-v.getZ()); + } else if (isQuarterTurn(angle)) { + double x = v.getX(); + v.setX(v.getZ()); + v.setZ(-x); + } else if (isThreeQuarterTurn(angle)) { + double x = v.getX(); + v.setX(-v.getZ()); + v.setZ(x); + } else { + v.rotateAroundY(yRadians(spin)); + } + } + + private static boolean isQuarterTurn(double angle) { + return angle % FULL_TURN_DEGREES == QUARTER_TURN_DEGREES || angle % FULL_TURN_DEGREES == -THREE_QUARTER_TURN_DEGREES; + } + + private static boolean isThreeQuarterTurn(double angle) { + return angle == -QUARTER_TURN_DEGREES || angle % FULL_TURN_DEGREES == THREE_QUARTER_TURN_DEGREES; + } + + @Override + public boolean equals(Object other) { + return other instanceof ObjectRotation rotation + && enabled == rotation.enabled + && Objects.equals(xAxis, rotation.xAxis) + && Objects.equals(yAxis, rotation.yAxis) + && Objects.equals(zAxis, rotation.zAxis); + } + + @Override + public int hashCode() { + return Objects.hash(enabled, xAxis, yAxis, zAxis); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/prepare/ObjectSpinKernel.java b/module/src/main/java/art/arcane/iris/builtin/prepare/ObjectSpinKernel.java new file mode 100644 index 000000000..9c1decba9 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/prepare/ObjectSpinKernel.java @@ -0,0 +1,151 @@ +package art.arcane.iris.builtin.prepare; + +import art.arcane.volmlib.util.math.IrisBlockVector; + +/** + * Precomputed vector rotation for a single placement. + *

+ * Turns vectors branch for branch as Iris's object rotation does, with two differences: it mutates the vector + * handed to it instead of cloning, and the per-axis angle plus its cosine and sine are resolved once instead of once + * per block. The angle is a pure function of the axis clamp and the spin, both fixed for the placement, and + * Math.cos/Math.sin are pure, so every produced double is identical to the value the per-call form would have produced. + */ +public final class ObjectSpinKernel { + private static final int MODE_NONE = 0; + private static final int MODE_FLIP = 1; + private static final int MODE_QUARTER = 2; + private static final int MODE_THREE_QUARTER = 3; + private static final int MODE_ANGLE = 4; + + private final ObjectRotation rotation; + + private final int xMode; + private final int yMode; + private final int zMode; + private final double xCos; + private final double xSin; + private final double yCos; + private final double ySin; + private final double zCos; + private final double zSin; + + public ObjectSpinKernel(ObjectRotation rotation, int spinX, int spinY, int spinZ) { + this.rotation = rotation; + xMode = rotation.canRotateX() ? modeOf(rotation.xAxis()) : MODE_NONE; + zMode = rotation.canRotateZ() ? modeOf(rotation.zAxis()) : MODE_NONE; + yMode = rotation.canRotateY() ? modeOf(rotation.yAxis()) : MODE_NONE; + double xAngle = xMode == MODE_ANGLE ? rotation.radians(rotation.xAxis(), spinX) : 0; + double zAngle = zMode == MODE_ANGLE ? rotation.radians(rotation.zAxis(), spinZ) : 0; + double yAngle = yMode == MODE_ANGLE ? rotation.radians(rotation.yAxis(), spinY) : 0; + xCos = Math.cos(xAngle); + xSin = Math.sin(xAngle); + zCos = Math.cos(zAngle); + zSin = Math.sin(zAngle); + yCos = Math.cos(yAngle); + ySin = Math.sin(yAngle); + } + + private static int modeOf(AxisRotationClamp clamp) { + if (!clamp.isLocked()) { + return MODE_ANGLE; + } + + if (Math.abs(clamp.max()) % 360D == 180D) { + return MODE_FLIP; + } + + if (clamp.max() % 360D == 90D || clamp.max() % 360D == -270D) { + return MODE_QUARTER; + } + + if (clamp.max() == -90D || clamp.max() % 360D == 270D) { + return MODE_THREE_QUARTER; + } + + return MODE_ANGLE; + } + + /** + * Rotates in place. Axis order (X, then Z, then Y) is load bearing. + */ + public void rotate(IrisBlockVector v) { + if (!rotation.canRotate()) { + return; + } + + switch (xMode) { + case MODE_FLIP -> { + v.setZ(-v.getZ()); + v.setY(-v.getY()); + } + case MODE_QUARTER -> { + double z = v.getZ(); + v.setZ(v.getY()); + v.setY(-z); + } + case MODE_THREE_QUARTER -> { + double z = v.getZ(); + v.setZ(-v.getY()); + v.setY(z); + } + case MODE_ANGLE -> { + double y = xCos * v.getY() - xSin * v.getZ(); + double z = xSin * v.getY() + xCos * v.getZ(); + v.setY(y); + v.setZ(z); + } + default -> { + } + } + + switch (zMode) { + case MODE_FLIP -> { + v.setY(-v.getY()); + v.setX(-v.getX()); + } + case MODE_QUARTER -> { + double y = v.getY(); + v.setY(v.getX()); + v.setX(-y); + } + case MODE_THREE_QUARTER -> { + double y = v.getY(); + v.setY(-v.getX()); + v.setX(y); + } + case MODE_ANGLE -> { + double x = zCos * v.getX() - zSin * v.getY(); + double y = zSin * v.getX() + zCos * v.getY(); + v.setX(x); + v.setY(y); + } + default -> { + } + } + + switch (yMode) { + case MODE_FLIP -> { + v.setX(-v.getX()); + v.setZ(-v.getZ()); + } + case MODE_QUARTER -> { + double x = v.getX(); + v.setX(v.getZ()); + v.setZ(-x); + } + case MODE_THREE_QUARTER -> { + double x = v.getX(); + v.setX(-v.getZ()); + v.setZ(x); + } + case MODE_ANGLE -> { + double x = yCos * v.getX() + ySin * v.getZ(); + double z = -ySin * v.getX() + yCos * v.getZ(); + v.setX(x); + v.setZ(z); + } + default -> { + } + } + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java b/module/src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java new file mode 100644 index 000000000..a67eadbc2 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java @@ -0,0 +1,84 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.prepare; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +/** How far an object is shifted from where it would be placed, written as a placement's {@code translate}. */ +@Snippet("iris/prepare/object-translator") +@Desc("Translate objects") +public final class ObjectTranslate { + @MinNumber(-128) + @MaxNumber(128) + @Desc("The x shift in blocks") + private int x = 0; + + @Required + @MinNumber(-128) + @MaxNumber(128) + @Desc("The y shift in blocks") + private int y = 0; + + @MinNumber(-128) + @MaxNumber(128) + @Desc("Adds an additional amount of height randomly (translateY + rand(0 - yRandom))") + private int yRandom = 0; + + @MinNumber(-128) + @MaxNumber(128) + @Desc("The z shift in blocks") + private int z = 0; + + public ObjectTranslate() { + } + + /** A shift of the given size, as Iris's own translate model hands it to the placement stages. */ + public static ObjectTranslate of(int x, int y, int yRandom, int z) { + ObjectTranslate translate = new ObjectTranslate(); + translate.x = x; + translate.y = y; + translate.yRandom = yRandom; + translate.z = z; + return translate; + } + + public boolean canTranslate() { + return x != 0 || y != 0 || z != 0; + } + + public int x() { + return x; + } + + public int y() { + return y; + } + + public int yRandom() { + return yRandom; + } + + public int z() { + return z; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/prepare/SlopeClip.java b/module/src/main/java/art/arcane/iris/builtin/prepare/SlopeClip.java new file mode 100644 index 000000000..3ce6bbf12 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/prepare/SlopeClip.java @@ -0,0 +1,66 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.prepare; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Snippet; + +/** The terrain slopes an object placement, a decorator or a terrain layer may sit on, written as its {@code slopeCondition}. */ +@Snippet("iris/prepare/slope-clip") +@Desc("Limits placement to a minimum and maximum terrain slope") +public final class SlopeClip { + private static final double DEFAULT_MINIMUM_SLOPE = 0; + private static final double DEFAULT_MAXIMUM_SLOPE = 10; + + @MinNumber(0) + @MaxNumber(1024) + @Desc("The minimum slope for placement") + private double minimumSlope = DEFAULT_MINIMUM_SLOPE; + + @MinNumber(0) + @MaxNumber(1024) + @Desc("The maximum slope for placement") + private double maximumSlope = DEFAULT_MAXIMUM_SLOPE; + + public SlopeClip() { + } + + public double minimumSlope() { + return minimumSlope; + } + + public double maximumSlope() { + return maximumSlope; + } + + /** Whether every slope passes. */ + public boolean isDefault() { + return minimumSlope <= 0 && maximumSlope >= DEFAULT_MAXIMUM_SLOPE; + } + + public boolean isValid(double slope) { + if (isDefault()) { + return true; + } + + return !(minimumSlope > slope) && !(maximumSlope < slope); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/prepare/TransformedBounds.java b/module/src/main/java/art/arcane/iris/builtin/prepare/TransformedBounds.java new file mode 100644 index 000000000..a594181fb --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/prepare/TransformedBounds.java @@ -0,0 +1,23 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.prepare; + +/** The bounds of a transformed object around its anchor, inclusive, widened by the surface warp along X and Z. */ +public record TransformedBounds(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { +} diff --git a/module/src/main/java/art/arcane/iris/builtin/spawn/AmbientEffect.java b/module/src/main/java/art/arcane/iris/builtin/spawn/AmbientEffect.java new file mode 100644 index 000000000..044ac6ffd --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/spawn/AmbientEffect.java @@ -0,0 +1,247 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.spawn; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +/** + * A sound, particles, potion effect or commands that play now and then around the players in an area. The same + * settings make the effect an entity shows when it appears ({@link EntityDefinition#spawnEffect()}). + */ +@Snippet("iris/spawn/effect") +@Desc("An iris effect") +public final class AmbientEffect { + @Ref(Reference.POTION_EFFECT) + @Desc("The potion effect to apply in this area") + private String potionEffect = ""; + + @Desc("The particle effect to apply in the area") + private String particleEffect = null; + + @MinNumber(-32) + @MaxNumber(32) + @Desc("Randomly offset from the surface to this surface+value") + private int particleOffset = 0; + + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt x, usually represents motion if the particle count is zero. Otherwise an offset.") + private double particleAltX = 0; + + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt y, usually represents motion if the particle count is zero. Otherwise an offset.") + private double particleAltY = 0; + + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt z, usually represents motion if the particle count is zero. Otherwise an offset.") + private double particleAltZ = 0; + + @Desc("Randomize the altX by -altX to altX") + private boolean randomAltX = true; + + @Desc("Randomize the altY by -altY to altY") + private boolean randomAltY = false; + + @Desc("Randomize the altZ by -altZ to altZ") + private boolean randomAltZ = true; + + @Desc("The sound to play") + private String sound = null; + + @MinNumber(0) + @MaxNumber(512) + @Desc("The max distance from the player the sound will play") + private int soundDistance = 12; + + @MinNumber(0.01) + @MaxNumber(1.99) + @Desc("The minimum sound pitch") + private double minPitch = 0.5D; + + @MinNumber(0.01) + @MaxNumber(1.99) + @Desc("The max sound pitch") + private double maxPitch = 1.5D; + + @MinNumber(0.001) + @MaxNumber(512) + @Desc("The sound volume.") + private double volume = 1.5D; + + @MinNumber(0) + @MaxNumber(512) + @Desc("The particle count. Try setting to zero for using the alt xyz to a motion value instead of an offset") + private int particleCount = 0; + + @MinNumber(0) + @MaxNumber(64) + @Desc("How far away from the player particles can play") + private int particleDistance = 20; + + @MinNumber(0) + @MaxNumber(128) + @Desc("How wide the particles can play (player's view left and right) RADIUS") + private int particleDistanceWidth = 24; + + @Desc("An extra value for some particles... Which bukkit doesn't even document.") + private double extra = 0; + + @MinNumber(-1) + @MaxNumber(1024) + @Desc("The Potion Strength or -1 to disable") + private int potionStrength = -1; + + @MinNumber(1) + @Desc("The max time the potion will last for") + private int potionTicksMax = 155; + + @MinNumber(1) + @Desc("The min time the potion will last for") + private int potionTicksMin = 75; + + @Required + @MinNumber(0) + @Desc("The effect interval in milliseconds") + private int interval = 150; + + @MinNumber(0) + @MaxNumber(16) + @Desc("The effect distance start away") + private int particleAway = 5; + + @Required + @MinNumber(1) + @Desc("The chance is 1 in CHANCE per interval") + private int chance = 50; + + @Desc("Run commands, with configurable location parameters") + private EffectCommands commandRegistry = null; + + public AmbientEffect() { + } + + public String potionEffect() { + return potionEffect; + } + + public String particleEffect() { + return particleEffect; + } + + public int particleOffset() { + return particleOffset; + } + + public double particleAltX() { + return particleAltX; + } + + public double particleAltY() { + return particleAltY; + } + + public double particleAltZ() { + return particleAltZ; + } + + public boolean randomAltX() { + return randomAltX; + } + + public boolean randomAltY() { + return randomAltY; + } + + public boolean randomAltZ() { + return randomAltZ; + } + + public String sound() { + return sound; + } + + public int soundDistance() { + return soundDistance; + } + + public double minPitch() { + return minPitch; + } + + public double maxPitch() { + return maxPitch; + } + + public double volume() { + return volume; + } + + public int particleCount() { + return particleCount; + } + + public int particleDistance() { + return particleDistance; + } + + public int particleDistanceWidth() { + return particleDistanceWidth; + } + + public double extra() { + return extra; + } + + public int potionStrength() { + return potionStrength; + } + + public int potionTicksMax() { + return potionTicksMax; + } + + public int potionTicksMin() { + return potionTicksMin; + } + + public int interval() { + return interval; + } + + public int particleAway() { + return particleAway; + } + + public int chance() { + return chance; + } + + /** The commands the effect runs; null for none. */ + public EffectCommands commandRegistry() { + return commandRegistry; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java b/module/src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java new file mode 100644 index 000000000..0bf953bfd --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java @@ -0,0 +1,98 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.spawn; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +@Snippet("iris/spawn/command-registry") +@Desc("Represents a casting location for a command") +public final class EffectCommands { + @Required + @Desc("Run commands, at the exact location of the player") + private List rawCommands = List.of(); + + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt x, usually represents motion if the particle count is zero. Otherwise an offset.") + private double commandOffsetX = 0; + + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt y, usually represents motion if the particle count is zero. Otherwise an offset.") + private double commandOffsetY = 0; + + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt z, usually represents motion if the particle count is zero. Otherwise an offset.") + private double commandOffsetZ = 0; + + @Desc("Randomize the altX from -altX to altX") + private boolean commandRandomAltX = true; + + @Desc("Randomize the altY from -altY to altY") + private boolean commandRandomAltY = false; + + @Desc("Randomize the altZ from -altZ to altZ") + private boolean commandRandomAltZ = true; + + @Desc("Randomize location for all separate commands (true), or run all on the same location (false)") + private boolean commandAllRandomLocations = true; + + public EffectCommands() { + } + + public List rawCommands() { + return rawCommands == null ? List.of() : Collections.unmodifiableList(rawCommands); + } + + public double commandOffsetX() { + return commandOffsetX; + } + + public double commandOffsetY() { + return commandOffsetY; + } + + public double commandOffsetZ() { + return commandOffsetZ; + } + + public boolean commandRandomAltX() { + return commandRandomAltX; + } + + public boolean commandRandomAltY() { + return commandRandomAltY; + } + + public boolean commandRandomAltZ() { + return commandRandomAltZ; + } + + public boolean commandAllRandomLocations() { + return commandAllRandomLocations; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/spawn/EntityDefinition.java b/module/src/main/java/art/arcane/iris/builtin/spawn/EntityDefinition.java new file mode 100644 index 000000000..8429dffc2 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/spawn/EntityDefinition.java @@ -0,0 +1,270 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.spawn; + +import art.arcane.iris.builtin.loot.ItemAttributeModifier; +import art.arcane.iris.builtin.loot.LootEntry; +import art.arcane.iris.builtin.loot.LootSettings; +import com.volmit.config.Desc; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; + +import java.util.Collections; +import java.util.List; + +/** An entity of the pack, one file of {@code entities/}: what spawners and markers spawn, with its equipment, attributes, passengers and loot. */ +@Desc("Represents an iris entity.") +public final class EntityDefinition { + @Required + @Ref(Reference.ENTITY) + @Desc("The namespaced key of the entity type to spawn, such as minecraft:zombie or alexsmobs:grizzly_bear. To spawn a mob from another plugin or provider, set this type to unknown and define the special type.") + private String type = null; + + @Desc("The SpawnReason name to spawn the entity with, such as NATURAL or COMMAND.") + private String reason = null; + + @Desc("The custom name of this entity") + private String customName = ""; + + @Desc("Should the name on this entity be visible even if you arent looking at it.") + private boolean customNameVisible = false; + + @Desc("If this entity type is a mob, should it be aware of it's surroundings & interact with the world.") + private boolean aware = true; + + @Desc("If this entity type is a creature, should it have ai goals.") + private boolean ai = true; + + @Desc("Should this entity be glowing") + private boolean glowing = false; + + @Desc("Should gravity apply to this entity") + private boolean gravity = true; + + @Desc("When an entity is invulnerable it can only be damaged by players increative mode.") + private boolean invulnerable = false; + + @Desc("When an entity is silent it will not produce any sound.") + private boolean silent = false; + + @Desc("Should this entity be allowed to pickup items") + private boolean pickupItems = false; + + @Desc("Should this entity be removed when far away") + private boolean removable = false; + + @Desc("Entity helmet equipment") + private LootEntry helmet = null; + + @Desc("Entity chestplate equipment") + private LootEntry chestplate = null; + + @Desc("Entity boots equipment") + private LootEntry boots = null; + + @Desc("Entity leggings equipment") + private LootEntry leggings = null; + + @Desc("Entity main hand equipment") + private LootEntry mainHand = null; + + @Desc("Entity off hand equipment") + private LootEntry offHand = null; + + @Desc("Make other entities ride this entity") + private List passengers = List.of(); + + @Desc("Attribute modifiers for this entity") + private List attributes = List.of(); + + @Desc("Loot tables for drops. Only the tables list is honored for entities; mode and multiplier are ignored, and the tables replace vanilla drops entirely.") + private LootSettings loot = new LootSettings(); + + @Desc("If specified, this entity will be leashed by this entity. I.e. THIS ENTITY Leashed by SPECIFIED. This has no effect on EnderDragons, Withers, Players, or Bats.Non-living entities excluding leashes will not persist as leashholders.") + private EntityDefinition leashHolder = null; + + @Desc("If specified, this entity will spawn with an effect") + private AmbientEffect spawnEffect = null; + + @Desc("Simply moves the entity from below the surface slowly out of the ground as a spawn-in effect") + private boolean spawnEffectRiseOutOfGround = false; + + @Desc("The main gene for a panda if the entity type is a panda. One of NORMAL, LAZY, WORRIED, PLAYFUL, BROWN, WEAK or AGGRESSIVE.") + private String pandaMainGene = null; + + @Desc("The hidden gene for a panda if the entity type is a panda. One of NORMAL, LAZY, WORRIED, PLAYFUL, BROWN, WEAK or AGGRESSIVE.") + private String pandaHiddenGene = null; + + @Desc("The this entity is ageable, set it's baby status") + private boolean baby = false; + + @Desc("If the entity should never be culled.") + private boolean keepEntity = false; + + @Desc("The surface type to spawn this mob on") + private SpawnSurface surface = SpawnSurface.LAND; + + @Ref(Reference.SPECIAL_ENTITY) + @Desc("Create a mob from another plugin, such as Mythic Mobs. Should be in the format of a namespace of PluginName:MobName") + private String specialType = ""; + + @Desc("Set to true if you want to apply all of the settings here to the mob, even though an external plugin has already done so.") + private boolean applySettingsToCustomMobAnyways = false; + + @Desc("Run raw commands when this entity is spawned. Use {x}, {y}, and {z} for location. /summon pig {x} {y} {z}") + private List rawCommands = List.of(); + + public EntityDefinition() { + } + + public String type() { + return type; + } + + public String reason() { + return reason; + } + + public String customName() { + return customName; + } + + public boolean customNameVisible() { + return customNameVisible; + } + + public boolean aware() { + return aware; + } + + public boolean ai() { + return ai; + } + + public boolean glowing() { + return glowing; + } + + public boolean gravity() { + return gravity; + } + + public boolean invulnerable() { + return invulnerable; + } + + public boolean silent() { + return silent; + } + + public boolean pickupItems() { + return pickupItems; + } + + public boolean removable() { + return removable; + } + + public LootEntry helmet() { + return helmet; + } + + public LootEntry chestplate() { + return chestplate; + } + + public LootEntry boots() { + return boots; + } + + public LootEntry leggings() { + return leggings; + } + + public LootEntry mainHand() { + return mainHand; + } + + public LootEntry offHand() { + return offHand; + } + + public List passengers() { + return passengers == null ? List.of() : Collections.unmodifiableList(passengers); + } + + public List attributes() { + return attributes == null ? List.of() : Collections.unmodifiableList(attributes); + } + + /** The loot the entity drops when it dies; only its tables count. */ + public LootSettings loot() { + return loot == null ? new LootSettings() : loot; + } + + public EntityDefinition leashHolder() { + return leashHolder; + } + + public AmbientEffect spawnEffect() { + return spawnEffect; + } + + public boolean spawnEffectRiseOutOfGround() { + return spawnEffectRiseOutOfGround; + } + + public String pandaMainGene() { + return pandaMainGene; + } + + public String pandaHiddenGene() { + return pandaHiddenGene; + } + + public boolean baby() { + return baby; + } + + public boolean keepEntity() { + return keepEntity; + } + + public SpawnSurface surface() { + return surface == null ? SpawnSurface.LAND : surface; + } + + public String specialType() { + return specialType; + } + + /** Whether the entity is a mob of another plugin. */ + public boolean isSpecialType() { + return specialType != null && !specialType.isEmpty(); + } + + public boolean applySettingsToCustomMobAnyways() { + return applySettingsToCustomMobAnyways; + } + + public List rawCommands() { + return rawCommands == null ? List.of() : Collections.unmodifiableList(rawCommands); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java b/module/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java new file mode 100644 index 000000000..371c3122e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java @@ -0,0 +1,66 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.spawn; + +import com.volmit.config.Desc; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.ResourceRef; +import com.volmit.config.Snippet; + +@Snippet("iris/spawn/entity-spawn") +@Desc("Represents an entity spawn during initial chunk generation") +public final class EntitySpawn { + @ResourceRef(EntityDefinition.class) + @Required + @Desc("The entity") + private String entity = ""; + + @MinNumber(1) + @Desc("The 1 in RARITY chance for this entity to spawn") + private int rarity = 1; + + @MinNumber(1) + @Desc("The minumum of this entity to spawn") + private int minSpawns = 1; + + @MinNumber(1) + @Desc("The max of this entity to spawn") + private int maxSpawns = 1; + + public EntitySpawn() { + } + + /** The key of the entity of the pack. */ + public String entity() { + return entity; + } + + public int rarity() { + return rarity; + } + + public int minSpawns() { + return minSpawns; + } + + public int maxSpawns() { + return maxSpawns; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java b/module/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java new file mode 100644 index 000000000..a1b7d1ee2 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java @@ -0,0 +1,70 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.spawn; + +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.ResourceRef; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +/** Blocks of an object placement that get a {@link SpawnMarker}, an entry of the placement's {@code markers}. */ +@Snippet("iris/spawn/object-marker") +@Desc("Find blocks to mark") +public final class PlacementMarker { + @Required + @Desc("Find block types to mark") + private List mark = List.of(); + @MinNumber(1) + @MaxNumber(16) + @Desc("The maximum amount of markers to place. Use these sparingly!") + private int maximumMarkers = 8; + @Desc("If true, markers will only be placed if the block matches the mark list perfectly.") + private boolean exact = false; + @Required + @ResourceRef(SpawnMarker.class) + @Desc("The marker to add") + private String marker; + + public PlacementMarker() { + } + + /** The blocks that get a marker. */ + public List mark() { + return mark == null ? List.of() : Collections.unmodifiableList(mark); + } + + public int maximumMarkers() { + return maximumMarkers; + } + + public boolean exact() { + return exact; + } + + /** The key of the {@link SpawnMarker} to place. */ + public String marker() { + return marker; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnCommand.java b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnCommand.java new file mode 100644 index 000000000..77aebce99 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnCommand.java @@ -0,0 +1,76 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.spawn; + +import com.volmit.config.Desc; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +@Snippet("iris/spawn/command") +@Desc("Represents a set of Iris commands") +public final class SpawnCommand { + @Required + @Desc("List of commands. Iris replaces {x} {y} and {z} with the location of the entity spawn") + private List commands = List.of(); + + @Desc("The delay for running the command. Instant by default") + private long delay = 0; + + @Desc("If this should be repeated (indefinitely, cannot be cancelled). This does not persist with server-restarts, so it only repeats when the chunk is generated.") + private boolean repeat = false; + + @Desc("The delay between repeats, in server ticks (by default 100, so 5 seconds)") + private long repeatDelay = 100; + + @Desc("The block of 24 hour time in which the command should execute.") + private SpawnTimeBlock timeBlock = new SpawnTimeBlock(); + + @Desc("The weather that is required for the command to execute.") + private SpawnWeather weather = SpawnWeather.ANY; + + public SpawnCommand() { + } + + public List commands() { + return commands == null ? List.of() : Collections.unmodifiableList(commands); + } + + public long delay() { + return delay; + } + + public boolean repeat() { + return repeat; + } + + public long repeatDelay() { + return repeatDelay; + } + + public SpawnTimeBlock timeBlock() { + return timeBlock == null ? new SpawnTimeBlock() : timeBlock; + } + + public SpawnWeather weather() { + return weather == null ? SpawnWeather.ANY : weather; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnDuration.java b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnDuration.java new file mode 100644 index 000000000..8ae3a109b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnDuration.java @@ -0,0 +1,80 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.spawn; + +import com.volmit.config.Desc; +import com.volmit.config.Snippet; + +import java.util.concurrent.TimeUnit; + +@Snippet("iris/spawn/duration") +@Desc("Represents a combined duration. Fill each property to add time into a single duration") +public final class SpawnDuration { + private static final long MILLISECONDS_PER_MINECRAFT_TICK = 50L; + private static final long MILLISECONDS_PER_MINECRAFT_HOUR = 50_000L; + private static final long MILLISECONDS_PER_MINECRAFT_DAY = 1_200_000L; + private static final long MILLISECONDS_PER_MINECRAFT_WEEK = 8_400_000L; + private static final long MILLISECONDS_PER_MINECRAFT_LUNAR_CYCLE = 9_600_000L; + + @Desc("Milliseconds (1000ms = 1 second)") + private int milliseconds = 0; + + @Desc("Minecraft Ticks (20 minecraft ticks = 1 second)") + private int minecraftTicks = 0; + + @Desc("Seconds (60 seconds = 1 minute)") + private int seconds = 0; + + @Desc("Minutes (60 minutes = 1 hour)") + private int minutes = 0; + + @Desc("Minecraft Hours (about 50 real seconds)") + private int minecraftHours = 0; + + @Desc("Hours (24 hours = 1 day)") + private int hours = 0; + + @Desc("Minecraft Days (1 minecraft day = 20 real minutes)") + private int minecraftDays = 0; + + @Desc("Minecraft Weeks (7 minecraft days = 2 real hours and 20 real minutes)") + private int minecraftWeeks = 0; + + @Desc("Minecraft Lunar Cycles (8 minecraft days = 2 real hours and 40 real minutes)") + private int minecraftLunarCycles = 0; + + @Desc("REAL (not minecraft) Days") + private int days = 0; + + public SpawnDuration() { + } + + public long toMilliseconds() { + return milliseconds + + TimeUnit.SECONDS.toMillis(seconds) + + TimeUnit.MINUTES.toMillis(minutes) + + TimeUnit.HOURS.toMillis(hours) + + TimeUnit.DAYS.toMillis(days) + + (minecraftTicks * MILLISECONDS_PER_MINECRAFT_TICK) + + (minecraftHours * MILLISECONDS_PER_MINECRAFT_HOUR) + + (minecraftDays * MILLISECONDS_PER_MINECRAFT_DAY) + + (minecraftWeeks * MILLISECONDS_PER_MINECRAFT_WEEK) + + (minecraftLunarCycles * MILLISECONDS_PER_MINECRAFT_LUNAR_CYCLE); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnGroup.java b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnGroup.java new file mode 100644 index 000000000..0e2b1abd8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnGroup.java @@ -0,0 +1,36 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.spawn; + +import com.volmit.config.Desc; + +@Desc("Terrain modes are used to decide the generator type currently used") +public enum SpawnGroup { + @Desc("Spawns on the terrain surface") + NORMAL, + + @Desc("Spawns in cave-air and low light level areas") + CAVE, + + @Desc("Spawns underwater") + UNDERWATER, + + @Desc("Spawns in beaches") + BEACH +} diff --git a/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java new file mode 100644 index 000000000..048699ad8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java @@ -0,0 +1,62 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.spawn; + +import com.volmit.config.Desc; +import com.volmit.config.ResourceRef; + +import java.util.Collections; +import java.util.List; + +/** A marker of the pack, one file of {@code markers/}: object placements put markers in the world and a marker names the spawners that fire there. */ +@Desc("Represents a marker") +public final class SpawnMarker { + @Desc("A list of spawners to add to anywhere this marker is.") + @ResourceRef(Spawner.class) + private List spawners = List.of(); + + @Desc("Remove this marker when the block it's assigned to is changed.") + private boolean removeOnChange = true; + + @Desc("If true, markers will only be placed here if there is 2 air blocks above it.") + private boolean emptyAbove = true; + + @Desc("If this marker is used, what is the chance it removes itself. For example 25% (0.25) would mean that on average 4 uses will remove a specific marker. Set this below 0 (-1) to never exhaust & set this to 1 or higher to always exhaust on first use.") + private double exhaustionChance = 0; + + public SpawnMarker() { + } + + /** The keys of the spawners that fire at the marker. */ + public List spawners() { + return spawners == null ? List.of() : Collections.unmodifiableList(spawners); + } + + public boolean removeOnChange() { + return removeOnChange; + } + + public boolean emptyAbove() { + return emptyAbove; + } + + public double exhaustionChance() { + return exhaustionChance; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnRate.java b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnRate.java new file mode 100644 index 000000000..5ebbd6225 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnRate.java @@ -0,0 +1,50 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.spawn; + +import com.volmit.config.Desc; +import com.volmit.config.Snippet; + +@Snippet("iris/spawn/rate") +@Desc("Represents a count of something per time duration") +public final class SpawnRate { + @Desc("The amount of things. Leave 0 for infinite (meaning always spawn whenever)") + private int amount = 0; + + @Desc("The time interval. Leave blank for infinite 0 (meaning always spawn all the time)") + private SpawnDuration per = new SpawnDuration(); + + public SpawnRate() { + } + + /** The milliseconds between two things: the interval divided by the amount, at least 1. */ + public long interval() { + long t = duration().toMilliseconds() / (amount == 0 ? 1 : amount); + return Math.abs(t <= 0 ? 1 : t); + } + + /** Whether there is no limit: no interval was given. */ + public boolean isInfinite() { + return duration().toMilliseconds() == 0; + } + + private SpawnDuration duration() { + return per == null ? new SpawnDuration() : per; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnSurface.java b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnSurface.java new file mode 100644 index 000000000..45a9ad3c8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnSurface.java @@ -0,0 +1,40 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.spawn; + +import com.volmit.config.Desc; + +@Desc("The type of surface entities should spawn on") +public enum SpawnSurface { + + @Desc("Land surfaces") + LAND, + + @Desc("Any surfaces animals can spawn on, such as dirt, grass and podzol") + ANIMAL, + + @Desc("Within the water") + WATER, + + @Desc("On land or on water") + OVERWORLD, + + @Desc("Within lava") + LAVA +} diff --git a/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnTimeBlock.java b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnTimeBlock.java new file mode 100644 index 000000000..ff9110133 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnTimeBlock.java @@ -0,0 +1,50 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.spawn; + +import com.volmit.config.Desc; +import com.volmit.config.Snippet; + +@Snippet("iris/spawn/time-block") +@Desc("Represents a time of day (24h time, not 12h am/pm). Set both to the same number for any time. If they are both set to -1, it will always be not allowed.") +public final class SpawnTimeBlock { + private static final double NEVER = -1; + + @Desc("The beginning hour. Set both to the same number for any time. If they are both set to -1, it will always be not allowed.") + private double startHour = 0; + + @Desc("The ending hour. Set both to the same number for any time. If they are both set to -1, it will always be not allowed.") + private double endHour = 0; + + public SpawnTimeBlock() { + } + + /** Whether {@code hour}, a time of day from 0 to 24, lies in the block; a block that wraps past midnight includes both ends. */ + public boolean contains(double hour) { + if (startHour == endHour) { + return endHour != NEVER; + } + + if (startHour > endHour) { + return hour >= startHour || hour <= endHour; + } + + return hour >= startHour && hour <= endHour; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnWeather.java b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnWeather.java new file mode 100644 index 000000000..a19bd6eda --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/spawn/SpawnWeather.java @@ -0,0 +1,46 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.spawn; + +import com.volmit.config.Desc; + +@Desc("Represents a weather type") +public enum SpawnWeather { + @Desc("Represents when weather is not causing downfall") + NONE, + + @Desc("Represents rain or snow") + DOWNFALL, + + @Desc("Represents rain or snow with thunder") + DOWNFALL_WITH_THUNDER, + + @Desc("Any weather") + ANY; + + /** Whether the weather of a world, which is {@code storming} and {@code thundering} or neither, is this one. */ + public boolean matches(boolean storming, boolean thundering) { + return switch (this) { + case NONE -> !storming && !thundering; + case DOWNFALL -> storming; + case DOWNFALL_WITH_THUNDER -> storming && thundering; + case ANY -> true; + }; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/spawn/Spawner.java b/module/src/main/java/art/arcane/iris/builtin/spawn/Spawner.java new file mode 100644 index 000000000..e7850f2bd --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/spawn/Spawner.java @@ -0,0 +1,95 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.spawn; + +import com.volmit.config.Desc; +import com.volmit.config.Range; + +import java.util.Collections; +import java.util.List; + +/** A spawner of the pack, one file of {@code spawners/}: which entities appear where, when and how often. */ +@Desc("Represents an entity spawn during initial chunk generation") +public final class Spawner { + @Desc("The entity spawns to add") + private List spawns = List.of(); + + @Desc("The entity spawns to add initially. EXECUTES PER CHUNK!") + private List initialSpawns = List.of(); + + @Desc("This spawner will not spawn in a given chunk if that chunk has more than the defined amount of living entities.") + private int maxEntitiesPerChunk = 1; + + @Desc("The block of 24 hour time to contain this spawn in.") + private SpawnTimeBlock timeBlock = new SpawnTimeBlock(); + + @Desc("The weather condition required for this spawner to fire.") + private SpawnWeather weather = SpawnWeather.ANY; + + @Desc("The maximum rate this spawner can fire") + private SpawnRate maximumRate = new SpawnRate(); + + @Desc("The maximum rate this spawner can fire on a specific chunk") + private SpawnRate maximumRatePerChunk = new SpawnRate(); + + @Desc("The light levels this spawn is allowed to run in (0-15 inclusive)") + private Range allowedLightLevels = Range.of(0, 15); + + @Desc("Where should these spawns be placed") + private SpawnGroup group = SpawnGroup.NORMAL; + + public Spawner() { + } + + public List spawns() { + return spawns == null ? List.of() : Collections.unmodifiableList(spawns); + } + + public List initialSpawns() { + return initialSpawns == null ? List.of() : Collections.unmodifiableList(initialSpawns); + } + + public int maxEntitiesPerChunk() { + return maxEntitiesPerChunk; + } + + public SpawnTimeBlock timeBlock() { + return timeBlock == null ? new SpawnTimeBlock() : timeBlock; + } + + public SpawnWeather weather() { + return weather == null ? SpawnWeather.ANY : weather; + } + + public SpawnRate maximumRate() { + return maximumRate == null ? new SpawnRate() : maximumRate; + } + + public SpawnRate maximumRatePerChunk() { + return maximumRatePerChunk == null ? new SpawnRate() : maximumRatePerChunk; + } + + public Range allowedLightLevels() { + return allowedLightLevels == null ? Range.of(0, 15) : allowedLightLevels; + } + + public SpawnGroup group() { + return group == null ? SpawnGroup.NORMAL : group; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/stilt/StiltLayers.java b/module/src/main/java/art/arcane/iris/builtin/stilt/StiltLayers.java new file mode 100644 index 000000000..5ad22327e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/stilt/StiltLayers.java @@ -0,0 +1,74 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.stilt; + +import com.volmit.object.ObjectBlock; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * The bottom and top layers of the blocks a stilt can repeat, with their positions already transformed + * around the anchor. Each layer keeps the blocks at its lowest or highest height seen so far. + */ +public final class StiltLayers { + private final List bottom = new ArrayList<>(); + private final List top = new ArrayList<>(); + private int bottomY = Integer.MAX_VALUE; + private int topY = Integer.MIN_VALUE; + + public void include(ObjectBlock transformed) { + int y = transformed.position().y(); + if (y < bottomY) { + bottomY = y; + bottom.clear(); + } + if (y == bottomY) { + bottom.add(transformed); + } + if (y > topY) { + topY = y; + top.clear(); + } + if (y == topY) { + top.add(transformed); + } + } + + public boolean isEmpty() { + return bottom.isEmpty(); + } + + public List bottom() { + return Collections.unmodifiableList(bottom); + } + + public List top() { + return Collections.unmodifiableList(top); + } + + public int bottomY() { + return bottomY; + } + + public int topY() { + return topY; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/stilt/StiltSettings.java b/module/src/main/java/art/arcane/iris/builtin/stilt/StiltSettings.java new file mode 100644 index 000000000..1c2e87894 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/stilt/StiltSettings.java @@ -0,0 +1,90 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.stilt; + +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Snippet; + +import java.util.Optional; + +/** How far and with which blocks an object stilts into the ground, written as the placement's {@code stiltSettings}. */ +@Snippet("iris/stilt/stilt-settings") +@Desc("Defines stilting behaviour.") +public final class StiltSettings { + @MinNumber(0) + @MaxNumber(64) + @Desc("Defines the maximum amount of blocks the object stilts verticially before overstilting and randomRange.") + private int yMax; + @MinNumber(0) + @MaxNumber(64) + @Desc("Defines the upper boundary for additional blocks after overstilting and/or maxStiltRange.") + private int yRand; + @MaxNumber(64) + @MinNumber(0) + @Desc("If the place mode is set to stilt, you can over-stilt it even further into the ground. Especially useful when using fast stilt due to inaccuracies.") + private int overStilt; + @Desc("If defined, stilting will be done using this block palette rather than the last layer of the object.") + private PaletteSpec palette; + @MinNumber(1) + @MaxNumber(256) + @Desc("For ORGANIC_STILT / CEILING_HANG: the maximum number of blocks to scan toward the cave floor (or ceiling) looking for solid ground before giving up.") + private int organicMaxScan = 48; + @MinNumber(0) + @MaxNumber(32) + @Desc("For ORGANIC_STILT / CEILING_HANG: the maximum number of blocks each column's stilt is randomly shortened by, giving the underside a ragged organic edge instead of a flat disc.") + private int organicJitter = 3; + @MinNumber(0) + @MaxNumber(1) + @Desc("For ORGANIC_STILT / CEILING_HANG: in the deepest fraction of each stilt column, blocks are randomly skipped to break the tip up. Higher = more broken and scratchy. 0 disables.") + private double organicScratch = 0.55; + + public StiltSettings() { + } + + public int yMax() { + return yMax; + } + + public int yRand() { + return yRand; + } + + public int overStilt() { + return overStilt; + } + + public Optional palette() { + return Optional.ofNullable(palette); + } + + public int organicMaxScan() { + return organicMaxScan; + } + + public int organicJitter() { + return organicJitter; + } + + public double organicScratch() { + return organicScratch; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java b/module/src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java new file mode 100644 index 000000000..ef2bcfc55 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java @@ -0,0 +1,34 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.structure; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Iris extension: says that a text option names structures of Iris's structure model by key, which Iris completes in + * studio and carries along when it exports the pack. The structure model is Iris's own resource kind, whose class a + * module cannot see, so {@code @ResourceRef} cannot name it; to another host the option is plain text. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface IrisStructureRef { +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/NativeStructureSource.java b/module/src/main/java/art/arcane/iris/builtin/structure/NativeStructureSource.java new file mode 100644 index 000000000..8cb515fdd --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/NativeStructureSource.java @@ -0,0 +1,64 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.structure; + +import com.volmit.config.Desc; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import com.volmit.vanilla.JigsawOverrides; + +import java.util.Optional; + +/** + * One platform structure a structure placement starts itself, written as + * {@code {"structure": "minecraft:ancient_city", "weight": 2, "jigsaw": {...}}}. IrisApi types only. + */ +@Desc("A live vanilla, datapack, or modded structure generated by Minecraft at an Iris-controlled placement.") +public final class NativeStructureSource { + @Required + @Ref(Reference.STRUCTURE) + @Desc("Registered structure key. The source retains its native generator, pieces, templates, processors, entities, markers, and data.") + private String structure = ""; + + @MinNumber(1) + @Desc("Relative selection weight when a placement offers multiple native structure sources.") + private int weight = 1; + + @Desc("Optional jigsaw-only assembly overrides. Null preserves the complete registered structure definition.") + private JigsawOverrides jigsaw = null; + + public NativeStructureSource() { + } + + /** The registry key of the platform structure, as the pack wrote it. */ + public String structure() { + return structure; + } + + public int weight() { + return weight; + } + + /** The overrides of the platform's jigsaw assembly; empty to keep its own. */ + public Optional jigsaw() { + return Optional.ofNullable(jigsaw); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/NativeStructureSuppression.java b/module/src/main/java/art/arcane/iris/builtin/structure/NativeStructureSuppression.java new file mode 100644 index 000000000..8522a480e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/NativeStructureSuppression.java @@ -0,0 +1,31 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.structure; + +import com.volmit.config.Desc; + +/** Whether a structure placement replaces the platform structure its structures stand in for. */ +@Desc("Controls whether an Iris structure placement suppresses its imported native source.") +public enum NativeStructureSuppression { + @Desc("Leaves native generation enabled alongside this Iris structure placement.") + NONE, + + @Desc("Suppresses the structure's vanillaSource when used by a validated dimension-level replacement placement.") + REPLACE_SOURCE +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureAdjustment.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureAdjustment.java new file mode 100644 index 000000000..63efe0662 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureAdjustment.java @@ -0,0 +1,91 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.structure; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; + +import java.util.List; +import java.util.Optional; + +/** One entry of {@link StructureSettings#adjustments()}: how the platform's own starts of the structures it matches are moved and fitted. */ +@Desc("A per-structure adjustment applied to vanilla, mod, and datapack structures that still generate natively (those NOT suppressed by an Iris 'structures' placement). Vertical shifts move the structure start, pieces, bounds, and jigsaw metadata together before references and placement. Intersecting trees are cleared automatically inside structure piece envelopes; optional postprocessing can build palette-driven foundation columns.") +public final class StructureAdjustment { + @Ref(Reference.STRUCTURE_PREFIX) + @Desc("Structure keys this adjustment applies to, e.g. 'minecraft:stronghold'. A namespace:path prefix also matches, so 'minecraft:village' adjusts every village variant and 'minecraft:ruined_portal' adjusts every ruined portal. Empty matches nothing.") + private List match = List.of(); + + @MinNumber(-512) + @MaxNumber(512) + @Desc("Vertical block offset. Negative pushes the structure down, positive lifts it. The resolved shift is clamped so the structure remains inside the world's vertical build bounds.") + private int yShift = 0; + + @Desc("Optional absolute world Y band. The structure is relocated so its vertical midpoint lands inside the band, deterministically from its start chunk and clamped to the world's build bounds. Precedence: preserveSourceY wins over yBand, and yBand wins over both yShift and Iris burial repositioning. Structures with a fixed vanilla alignment (ocean monument sea level, desert and jungle pyramid surface fit) ignore it.") + private StructureYBand yBand = null; + + @Desc("When true, skip Iris burial repositioning so the structure keeps the Y its own vanilla placement chose. Underground structures are otherwise pushed below the lowest solid column across their whole footprint, which hides terrain-aware structures such as mineshafts that intentionally breach cliffs and surfaces. Vertical shifts still apply on top of the preserved Y: this dimension's undergroundYShift plus every matching adjustment's yShift.") + private boolean preserveSourceY = false; + + @Desc("Optional foundation columns placed beneath the native structure piece bases after placement.") + private StructureStilts stilt = null; + + @Desc("Optional terrain integration override. VACUUM raises surface terrain from processed solid rigid-template foundations at or below each authored ground plane with a 12-block falloff without lowering existing ground. BORE and FORCE_CARVE clear every intersecting chunk before native pieces are placed, while ENCASE fills it with solid blocks instead. Left unset, SOURCE replays the registered structure's authored terrain adaptation, including surface fitting, burial, and encapsulation.") + private StructureTerrain terrain = null; + + public StructureAdjustment() { + } + + public StructureAdjustment(List match, int yShift, StructureYBand yBand, boolean preserveSourceY, StructureStilts stilt, + StructureTerrain terrain) { + this.match = List.copyOf(match); + this.yShift = yShift; + this.yBand = yBand; + this.preserveSourceY = preserveSourceY; + this.stilt = stilt; + this.terrain = terrain; + } + + /** Family patterns of the structures this adjustment applies to. */ + public List match() { + return StructureSettings.listOrEmpty(match); + } + + public int yShift() { + return yShift; + } + + public Optional yBand() { + return Optional.ofNullable(yBand); + } + + public boolean preserveSourceY() { + return preserveSourceY; + } + + public Optional stilt() { + return Optional.ofNullable(stilt); + } + + public Optional terrain() { + return Optional.ofNullable(terrain); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureAnchorMode.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureAnchorMode.java new file mode 100644 index 000000000..7fbeb7900 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureAnchorMode.java @@ -0,0 +1,54 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.structure; + +import com.volmit.config.Desc; + +/** How a structure placement picks the height it anchors a structure at. The placement identity hashes the order. */ +@Desc("Selects the vertical environment used to anchor an Iris structure placement.") +public enum StructureAnchorMode { + @Desc("Preserve the historical underground boolean behavior.") + LEGACY, + + @Desc("Anchor to the terrain surface and use minHeight/maxHeight as a surface gate.") + SURFACE, + + @Desc("Choose a deterministic Y inside the minHeight/maxHeight band.") + HEIGHT_BAND, + + @Desc("Anchor in carved space with solid support below.") + CAVE_FLOOR, + + @Desc("Anchor in carved space with solid support above.") + CAVE_CEILING, + + @Desc("Anchor in carved space without nearby floor or ceiling support.") + CAVE_CENTER, + + @Desc("Anchor at any carved-space position.") + CAVE_ANY; + + /** Whether the anchor looks for carved space. */ + public boolean isCave() { + return switch (this) { + case CAVE_FLOOR, CAVE_CEILING, CAVE_CENTER, CAVE_ANY -> true; + default -> false; + }; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureCarveShape.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureCarveShape.java new file mode 100644 index 000000000..a666f7ff2 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureCarveShape.java @@ -0,0 +1,56 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.builtin.structure; + +import com.volmit.config.Desc; + +@Desc("Controls the shape of the expanded terrain carve around an overbored structure.") +public enum StructureCarveShape { + @Desc("Carves the full expanded rectangular volume with straight walls, ceiling, and floor.") + BOX, + + @Desc("Carves a smooth rounded volume around the structure without erosion noise.") + ROUNDED, + + @Desc("Carves a rounded volume whose outer boundary is eroded by deterministic noise.") + ERODED; + + private static final double ERODED_CEILING_GROWTH = 0.8D; + + public double maximumCeilingScale() { + return maximumCeilingScale(1D); + } + + /** How far above its configured head room a carve of this shape may reach, as a multiple of it. */ + public double maximumCeilingScale(double erosionStrength) { + double strength = Double.isFinite(erosionStrength) + ? Math.max(0D, Math.min(1D, erosionStrength)) : 1D; + return switch (this) { + case BOX, ROUNDED -> 1D; + case ERODED -> 1D + ERODED_CEILING_GROWTH * strength; + }; + } + + public int maximumCeilingExtension(int configuredHeight) { + return maximumCeilingExtension(configuredHeight, 1D); + } + + public int maximumCeilingExtension(int configuredHeight, double erosionStrength) { + return (int) Math.ceil(Math.max(0, configuredHeight) * maximumCeilingScale(erosionStrength)); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureDistribution.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureDistribution.java new file mode 100644 index 000000000..9a42c935a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureDistribution.java @@ -0,0 +1,34 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.structure; + +import com.volmit.config.Desc; + +/** How a structure placement scatters its starts. The placement identity hashes the order. */ +@Desc("Controls how structure start positions are scattered across the world.") +public enum StructureDistribution { + @Desc("Vanilla-style spacing/separation grid. One placement attempt per grid cell, randomly offset within it by the separation. Use spacing, separation and salt.") + RANDOM_SPREAD, + + @Desc("A per-chunk probability roll, like object density. Use density (0-1).") + DENSITY, + + @Desc("Concentric rings around the world origin, like vanilla strongholds. Use rings.") + CONCENTRIC_RINGS +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java new file mode 100644 index 000000000..5703e7117 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java @@ -0,0 +1,41 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.builtin.structure; + +import com.volmit.generation.InvocationContext; +import com.volmit.resource.ResourceId; + +import java.util.List; +import java.util.Optional; + +/** + * What {@code iris:structure} asks of Iris: Iris places its jigsaw structures itself. The structure model (structures, + * pools, pieces), the assembler that builds a structure from them and the locator that spreads them over the world are + * Iris's, shared with the jigsaw studio and the structure importers and exporters. Iris offers it as an extension of its + * worlds and of the settings of the pack it loads: {@code world.extension(StructureHost.class)}. + */ +public interface StructureHost { + /** Places the structures that start in the chunk whose mantle the mantle invocation {@code context} generates. */ + void placeChunk(InvocationContext context); + + /** How far, in blocks along X and Z, a structure may write beyond the chunk it starts in. */ + int reach(); + + /** The loot tables the structure gives its pieces' containers; empty when the pack has no such structure. */ + Optional> lootTables(ResourceId structure); +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java new file mode 100644 index 000000000..edcaadd59 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java @@ -0,0 +1,248 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.structure; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.ResourceRef; +import com.volmit.world.PackBiome; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +/** + * Where and how often the structures of a dimension, region or biome start, written as one entry of its + * {@code "structures": [...]}: the pack's own structures to assemble or the platform's to start natively, the + * distribution of the starts, the height they anchor at, and how they meet the terrain. IrisApi types only. + */ +@Desc("Attaches structures to a biome, region or dimension and controls where and how often they generate. This is independent of a structure's own native generation, so you can add custom placements in tandem with native generation or instead of it.") +public final class StructurePlacement { + @IrisStructureRef + @Desc("Editable Iris assembly resources offered by this placement. Leave empty when nativeStructures supplies the source.") + private List structures = List.of(); + + @Desc("Live registered vanilla, datapack, and modded structures offered by this placement. Minecraft runs their native generator directly, independent of normal biome or dimension eligibility.") + private List nativeStructures = List.of(); + + @Desc("Stable authored identity for this placement. Set this when multiple placements use the same structure and settings. When empty, Iris derives identity from the placement content so list reordering does not move generated structures.") + private String placementId = ""; + + @Desc("Controls native replacement for this placement. REPLACE_SOURCE suppresses each selected Iris structure's vanillaSource or registered native source, and is honored only for dimension-level placements. NONE leaves native generation untouched.") + private NativeStructureSuppression nativeSuppression = NativeStructureSuppression.NONE; + + @Desc("How start positions are scattered.") + private StructureDistribution distribution = StructureDistribution.RANDOM_SPREAD; + + @MinNumber(1) + @MaxNumber(4096) + @Desc("RANDOM_SPREAD only: the grid cell size in chunks. One placement attempt per cell. Larger = rarer.") + private int spacing = 32; + + @MinNumber(0) + @Desc("RANDOM_SPREAD only: the minimum chunk separation between placements within the grid. Must be smaller than spacing.") + private int separation = 8; + + @Desc("RANDOM_SPREAD only: a salt mixed into the placement RNG so different structures using the same spacing do not stack.") + private int salt = 165745296; + + @MinNumber(0) + @MaxNumber(1) + @Desc("DENSITY only: the per-chunk probability (0-1) of a placement starting in a chunk.") + private double density = 0.02; + + @MinNumber(1) + @Desc("CONCENTRIC_RINGS only: the number of placements distributed across the rings.") + private int ringCount = 128; + + @MinNumber(1) + @Desc("CONCENTRIC_RINGS only: the ring spacing in chunks.") + private int ringDistance = 32; + + @MinNumber(1) + @Desc("CONCENTRIC_RINGS only: how many placements share each ring before moving outward.") + private int ringSpread = 3; + + @Desc("Minimum world Y. SURFACE uses it as a terrain-height gate; HEIGHT_BAND and cave anchors use it as the lower candidate bound. LEGACY follows underground.") + private int minHeight = -2032; + + @Desc("Maximum world Y. SURFACE uses it as a terrain-height gate; HEIGHT_BAND and cave anchors use it as the upper candidate bound. LEGACY follows underground.") + private int maxHeight = 2032; + + @Desc("LEGACY anchor only: if true, choose a deterministic world Y inside [minHeight, maxHeight]; otherwise gate the terrain surface. Explicit anchor modes override this field.") + private boolean underground = false; + + @Desc("Vertical anchor policy. LEGACY preserves the underground boolean. Cave modes search existing carved-space data and implicitly behave as underground placements.") + private StructureAnchorMode anchor = StructureAnchorMode.LEGACY; + + @ResourceRef(PackBiome.class) + @Desc("Optional cave-biome allowlist for cave anchor modes. Empty accepts the cave biome resolved at the selected anchor. Entries match by load key, including prefix matches.") + private List caveBiomes = List.of(); + + @MinNumber(1) + @MaxNumber(64) + @Desc("Cave anchor modes only: deterministic X/Z columns tested inside the start chunk before the placement is skipped.") + private int caveAnchorAttempts = 8; + + @MinNumber(1) + @MaxNumber(16) + @Desc("Cave anchor modes only: vertical scan step in blocks. One is exact; larger values trade precision for speed.") + private int caveAnchorScanStep = 1; + + @MinNumber(1) + @MaxNumber(64) + @Desc("Cave anchor modes only: minimum contiguous carved-space height required at the selected anchor.") + private int caveMinimumClearance = 3; + + @Desc("Terrain integration for this placement. The editable structures backend supports SOURCE, PRESERVE, BORE, and FORCE_CARVE. The nativeStructures backend supports every terrain mode.") + private StructureTerrain terrain = new StructureTerrain(); + + @Desc("Optional foundation columns placed beneath the assembled structure's occupied bottom cells. Columns pass through air and fluids until they reach solid ground, up to maxDepth.") + private StructureStilts stilt = null; + + @Desc("If false, the placement is skipped when its selected surface or cave column is submerged.") + private boolean underwater = false; + + public StructurePlacement() { + } + + /** Keys of the pack's structures the placement assembles, one picked per start. */ + public List structures() { + return listOrEmpty(structures); + } + + /** The platform structures the placement starts natively, one picked per start by weight. */ + public List nativeStructures() { + return listOrEmpty(nativeStructures); + } + + public String placementId() { + return placementId; + } + + public NativeStructureSuppression nativeSuppression() { + return nativeSuppression == null ? NativeStructureSuppression.NONE : nativeSuppression; + } + + public StructureDistribution distribution() { + return distribution == null ? StructureDistribution.RANDOM_SPREAD : distribution; + } + + public int spacing() { + return spacing; + } + + public int separation() { + return separation; + } + + public int salt() { + return salt; + } + + public double density() { + return density; + } + + public int ringCount() { + return ringCount; + } + + public int ringDistance() { + return ringDistance; + } + + public int ringSpread() { + return ringSpread; + } + + public int minHeight() { + return minHeight; + } + + public int maxHeight() { + return maxHeight; + } + + public boolean underground() { + return underground; + } + + /** The anchor as written; {@link #resolvedAnchor} says what {@code LEGACY} means for this placement. */ + public StructureAnchorMode anchor() { + return anchor == null ? StructureAnchorMode.LEGACY : anchor; + } + + /** Cave biome keys or key prefixes a cave anchor accepts; empty for any. */ + public List caveBiomes() { + return listOrEmpty(caveBiomes); + } + + public int caveAnchorAttempts() { + return caveAnchorAttempts; + } + + public int caveAnchorScanStep() { + return caveAnchorScanStep; + } + + public int caveMinimumClearance() { + return caveMinimumClearance; + } + + /** How the placement's structures meet the terrain; the defaults when the pack wrote none. */ + public StructureTerrain resolvedTerrain() { + return terrain == null ? new StructureTerrain() : terrain; + } + + /** The foundation columns under the structures; empty for none. */ + public Optional stilt() { + return Optional.ofNullable(stilt); + } + + public boolean underwater() { + return underwater; + } + + public boolean hasIrisStructures() { + return !structures().isEmpty(); + } + + public boolean hasNativeStructures() { + return !nativeStructures().isEmpty(); + } + + /** The anchor this placement uses: {@code LEGACY} is the band when {@link #underground}, else the surface. */ + public StructureAnchorMode resolvedAnchor() { + if (anchor() == StructureAnchorMode.LEGACY) { + return underground ? StructureAnchorMode.HEIGHT_BAND : StructureAnchorMode.SURFACE; + } + return anchor(); + } + + public boolean isAnchoredUnderground() { + StructureAnchorMode activeAnchor = resolvedAnchor(); + return activeAnchor == StructureAnchorMode.HEIGHT_BAND || activeAnchor.isCave(); + } + + private static List listOrEmpty(List list) { + return list == null ? List.of() : Collections.unmodifiableList(list); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java new file mode 100644 index 000000000..1929d370c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java @@ -0,0 +1,46 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.structure; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.Collections; +import java.util.List; + +/** + * The structure placements of a dimension, region or biome, written as {@code "structures": [...]}: one + * {@link StructurePlacement} per entry. IrisApi types only. + */ +@Desc("Iris structure placements of this dimension, region or biome: where and how often its structures start.") +@Feature(id = "iris:structure/placements", name = "Structure placements", key = "structures", root = "placements", + targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) +public final class StructurePlacementSettings implements IrisFeature { + @Desc("Iris structure placements, each independent of the others.") + private List placements = List.of(); + + public StructurePlacementSettings() { + } + + public List placements() { + return placements == null ? List.of() : Collections.unmodifiableList(placements); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureSetFrequency.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureSetFrequency.java new file mode 100644 index 000000000..b273697d7 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureSetFrequency.java @@ -0,0 +1,54 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.structure; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; + +/** One entry of {@link StructureSettings#frequencyOverrides()}: how often the structures of one platform structure set start. */ +@Desc("An exact registered structure-set frequency multiplier. Iris retains the set's structures, weights, biome eligibility, placement algorithm, salt, exclusion zone, starts, processors, mobs, loot, and locate behavior while scaling only its native placement density.") +public final class StructureSetFrequency { + @Ref(Reference.STRUCTURE_SET) + @Desc("Exact registered structure-set key, for example 'minecraft:nether_complexes'. Structure keys such as 'minecraft:fortress' are not valid here.") + private String structureSet = ""; + + @MinNumber(0.01) + @MaxNumber(16) + @Desc("Requested placement-density multiplier. Random-spread sets scale their placement frequency first and then their integer chunk spacing; integer spacing and separation constraints can make the realized increase slightly lower or higher. The default 1 leaves the registered placement unchanged.") + private double multiplier = 1D; + + public StructureSetFrequency() { + } + + public StructureSetFrequency(String structureSet, double multiplier) { + this.structureSet = structureSet; + this.multiplier = multiplier; + } + + public String structureSet() { + return structureSet == null ? "" : structureSet; + } + + public double multiplier() { + return multiplier; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java new file mode 100644 index 000000000..28c180f18 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java @@ -0,0 +1,106 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.structure; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; + +import java.util.Collections; +import java.util.List; + +/** + * How a dimension treats the platform's own structures (vanilla, data pack and mod structures), written as + * {@code "importedStructures": {"disabled": [...], "adjustments": [...]}}: which ones it disables, how the ones that still + * generate are moved and fitted, how often structure sets start, and whether installed data packs may replace the + * platform's own definitions. IrisApi types only. + */ +@Desc("Controls native vanilla, mod, and ingested datapack structure generation for this dimension. Every registered structure generates through its native placement unless its key matches 'disabled', equals a key in 'disabledExact', or a viable dimension-level Iris placement explicitly replaces its source. Family matching uses namespace, slash, or underscore boundaries, while exact matching compares normalized complete keys only. Run '/iris module structure list' to dump every valid key. Only affects newly generated chunks and is separate from Iris structure placements.") +@Feature(id = "iris:structure", name = "Structures", key = "importedStructures", targets = Level.DIMENSION) +public final class StructureSettings implements IrisFeature { + @Ref(Reference.STRUCTURE_PREFIX) + @Desc("Structure keys to deny explicitly, e.g. 'minecraft:stronghold'. A namespace:path prefix also matches, so 'minecraft:village' disables every village variant and 'minecraft:ruined_portal' disables every ruined portal. Every key not matched here remains enabled.") + private List disabled = List.of(); + + @Ref(Reference.STRUCTURE) + @Desc("Exact structure keys to deny after trimming and case normalization. Unlike 'disabled', entries never match key families, so 'minecraft:ruined_portal' does not disable 'minecraft:ruined_portal_nether'.") + private List disabledExact = List.of(); + + @MinNumber(-512) + @MaxNumber(512) + @Desc("Vertical block offset applied only to UNDERGROUND vanilla structures (the UNDERGROUND_STRUCTURES, UNDERGROUND_DECORATION, and STRONGHOLDS generation steps: strongholds, trial chambers, mineshafts, ancient cities, etc.). Surface structures (villages, outposts, etc.) are never shifted. Use a negative value to push deep structures lower when your dimension's sea/terrain level differs from vanilla's (e.g. -64 if you lowered the fluid height to 0). 0 = no shift.") + private int undergroundYShift = 0; + + @Desc("Controls whether ingested datapacks may replace minecraft-namespaced structure definitions, sets, pools, and templates. When false, those overrides are stripped from installed datapack copies so vanilla definitions stay intact. Non-minecraft structures from datapacks and mods remain governed by disabled because namespace alone cannot identify their origin. Resolved globally across loaded packs: if any dimension sets this false, minecraft-namespaced overrides are stripped from every installed datapack copy.") + private boolean datapackOverrides = true; + + @Desc("Exact registered structure-set frequency overrides for native generation. The last entry for a normalized structure-set key wins. These do not convert native structures into Iris placements and affect only newly generated chunks.") + private List frequencyOverrides = List.of(); + + @Desc("Per-structure adjustments applied to vanilla, mod, and datapack structures that still generate natively. Vertical shifts from every matching entry stack. A matching preserveSourceY option disables Iris burial repositioning for that structure. The last matching entry with stilt settings controls foundation columns, and likewise for terrain and yBand settings. A structure suppressed by an Iris placement is unaffected.") + private List adjustments = List.of(); + + public StructureSettings() { + } + + public StructureSettings(List disabled, List disabledExact, int undergroundYShift, boolean datapackOverrides, + List frequencyOverrides, List adjustments) { + this.disabled = List.copyOf(disabled); + this.disabledExact = List.copyOf(disabledExact); + this.undergroundYShift = undergroundYShift; + this.datapackOverrides = datapackOverrides; + this.frequencyOverrides = List.copyOf(frequencyOverrides); + this.adjustments = List.copyOf(adjustments); + } + + /** Family patterns of the structures the dimension disables. */ + public List disabled() { + return listOrEmpty(disabled); + } + + /** Complete keys of the structures the dimension disables. */ + public List disabledExact() { + return listOrEmpty(disabledExact); + } + + public int undergroundYShift() { + return undergroundYShift; + } + + public boolean datapackOverrides() { + return datapackOverrides; + } + + public List frequencyOverrides() { + return listOrEmpty(frequencyOverrides); + } + + public List adjustments() { + return listOrEmpty(adjustments); + } + + static List listOrEmpty(List list) { + return list == null ? List.of() : Collections.unmodifiableList(list); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureStilts.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureStilts.java new file mode 100644 index 000000000..36d53e374 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureStilts.java @@ -0,0 +1,74 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.structure; + +import com.volmit.block.BlockSpec; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +import java.util.List; +import java.util.Optional; + +/** + * Foundation columns built beneath a structure's pieces after they are placed, as packs write it: + * {"maxDepth": 32, "palette": {"palette": [{"block": "stone_bricks"}]}, "spacing": 2}. Held by structure placements and + * by the {@code importedStructures} adjustments; ownership records keep its JSON for the starts they track. + */ +@Desc("Defines foundation columns placed beneath a structure.") +public final class StructureStilts { + private static final String DEFAULT_BLOCK = "minecraft:cobblestone"; + + @MinNumber(1) + @MaxNumber(4064) + @Desc("Maximum number of blocks each foundation column may descend while searching for solid ground.") + private int maxDepth = 64; + + @Desc("Block palette used for foundation columns.") + private PaletteSpec palette = PaletteSpec.of(List.of(BlockSpec.of(DEFAULT_BLOCK))); + + @MinNumber(1) + @MaxNumber(64) + @Desc("Horizontal spacing between support columns. One fills every eligible foundation column; larger values create sparse stilts.") + private int spacing = 1; + + @Desc("For Iris-authored structures, whether solid partial blocks such as slabs, stairs, and walls may seed foundation columns instead of requiring a fully occluding base block.") + private boolean supportNonOccluding = false; + + public StructureStilts() { + } + + public int maxDepth() { + return maxDepth; + } + + /** The blocks of the columns; empty when the pack wrote {@code "palette": null}. */ + public Optional palette() { + return Optional.ofNullable(palette); + } + + public int spacing() { + return spacing; + } + + public boolean supportNonOccluding() { + return supportNonOccluding; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureTerrain.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureTerrain.java new file mode 100644 index 000000000..c014e65ef --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureTerrain.java @@ -0,0 +1,144 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.structure; + +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +import java.util.Optional; + +/** + * How a structure meets the terrain, as packs write it: {"mode": "FORCE_CARVE", "horizontalPadding": 4, "shape": "ERODED"}. + * Held by structure placements and by the {@code importedStructures} adjustments; ownership records keep its JSON for + * the starts they track, so its field names and defaults are the persisted format. + */ +@Desc("Terrain integration applied after a structure graph is assembled and before its pieces are placed.") +public final class StructureTerrain { + private static final double AUTO_LOBE_FREQUENCY_RATIO = 0.3D; + private static final double DEFAULT_EROSION_STRENGTH = 0.8D; + private static final double DEFAULT_EROSION_FREQUENCY = 0.07D; + private static final double DEFAULT_LOBE_STRENGTH = 0.85D; + private static final double MIN_EROSION_FREQUENCY = 0.001D; + private static final double MAX_EROSION_FREQUENCY = 1D; + private static final double MAX_LOBE_FREQUENCY = 1D; + + @Desc("Terrain operation. SOURCE applies the registered native structure's authored terrain adaptation and is a no-op for editable Iris structures. PRESERVE disables terrain integration. VACUUM raises terrain from processed rigid-template foundations at or below each authored ground plane with a 12-block falloff without lowering existing ground. BORE and FORCE_CARVE clear the requested envelope, while ENCASE fills it before placement so native shells are not lost to pre-carved air.") + private StructureTerrainMode mode = StructureTerrainMode.SOURCE; + + @MinNumber(0) + @MaxNumber(128) + @Desc("Horizontal clearance around the assembled pieces for BORE, FORCE_CARVE, and ENCASE. VACUUM uses its fixed 12-block terrain falloff.") + private int horizontalPadding = 0; + + @MinNumber(0) + @MaxNumber(128) + @Desc("Air clearance above the assembled pieces.") + private int ceilingPadding = 0; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Terrain cleared below the assembled pieces. Zero preserves their supporting floor.") + private int floorPadding = 0; + + @Desc("Shape used by FORCE_CARVE.") + private StructureCarveShape shape = StructureCarveShape.BOX; + + @Desc("Block palette used by ENCASE. When unset, the Overworld uses stone or deepslate, the Nether uses netherrack, and the End uses end stone.") + private PaletteSpec encasePalette = null; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Boundary erosion strength for ERODED force carving.") + private double erosionStrength = DEFAULT_EROSION_STRENGTH; + + @MinNumber(MIN_EROSION_FREQUENCY) + @MaxNumber(MAX_EROSION_FREQUENCY) + @Desc("Boundary noise frequency for ERODED force carving.") + private double erosionFrequency = DEFAULT_EROSION_FREQUENCY; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Low frequency lobe wavelength for ERODED force carving. Zero derives it from the erosion frequency.") + private double lobeFrequency = 0D; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Fraction of the horizontal padding the lobes may remove for ERODED force carving. Zero keeps a uniform boundary.") + private double lobeStrength = DEFAULT_LOBE_STRENGTH; + + public StructureTerrain() { + } + + /** The terrain operation; SOURCE where the pack wrote none or one Iris does not know. */ + public StructureTerrainMode resolvedMode() { + return mode == null ? StructureTerrainMode.SOURCE : mode; + } + + public int horizontalPadding() { + return horizontalPadding; + } + + public int ceilingPadding() { + return ceilingPadding; + } + + public int floorPadding() { + return floorPadding; + } + + /** The carve shape; BOX where the pack wrote none or one Iris does not know. */ + public StructureCarveShape resolvedShape() { + return shape == null ? StructureCarveShape.BOX : shape; + } + + /** The blocks ENCASE fills with; empty for the dimension's own stone. */ + public Optional encasePalette() { + return Optional.ofNullable(encasePalette); + } + + public double resolvedErosionStrength() { + if (!Double.isFinite(erosionStrength)) { + return DEFAULT_EROSION_STRENGTH; + } + return Math.max(0D, Math.min(1D, erosionStrength)); + } + + public double resolvedErosionFrequency() { + if (!Double.isFinite(erosionFrequency)) { + return DEFAULT_EROSION_FREQUENCY; + } + return Math.max(MIN_EROSION_FREQUENCY, Math.min(MAX_EROSION_FREQUENCY, erosionFrequency)); + } + + public double resolvedLobeFrequency() { + if (!Double.isFinite(lobeFrequency) || lobeFrequency <= 0D) { + return resolvedErosionFrequency() * AUTO_LOBE_FREQUENCY_RATIO; + } + return Math.min(MAX_LOBE_FREQUENCY, lobeFrequency); + } + + public double resolvedLobeStrength() { + if (!Double.isFinite(lobeStrength)) { + return DEFAULT_LOBE_STRENGTH; + } + return Math.max(0D, Math.min(1D, lobeStrength)); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureTerrainMode.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureTerrainMode.java new file mode 100644 index 000000000..d7c7cf955 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureTerrainMode.java @@ -0,0 +1,42 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.structure; + +import com.volmit.config.Desc; + +@Desc("Controls how terrain is integrated with a structure.") +public enum StructureTerrainMode { + @Desc("Replays the registered native structure's own authored terrain adaptation (beard surface fitting, BURY/ENCAPSULATE fill, legacy template-air clearing). Does nothing for editable Iris structures, which have no source adaptation to replay.") + SOURCE, + + @Desc("Disables all terrain integration. Pieces are placed into completely unmodified terrain and may end up embedded in solid rock or floating over dips.") + PRESERVE, + + @Desc("Clears one straight axis-aligned box around the assembled pieces, expanded by horizontalPadding, ceilingPadding, and floorPadding. Ignores the carve shape and erosion settings.") + BORE, + + @Desc("Clears the padded envelope using the configured carve shape (BOX, ROUNDED, or noise-eroded ERODED) so the cavity hugs the assembled pieces instead of a straight box.") + FORCE_CARVE, + + @Desc("Raises surface terrain from processed solid rigid-template foundations at or below each authored ground plane with a 12-block falloff, even when the registered structure has no terrain adaptation. Existing higher terrain and authored air remain untouched.") + VACUUM, + + @Desc("Fills the padded piece volume with solid blocks before any piece is placed so shells, walls, and floors land in solid ground instead of pre-carved air. Only air and liquid cells are filled; existing terrain and structures are never overwritten. Native pieces then carve their own interiors.") + ENCASE +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureYBand.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureYBand.java new file mode 100644 index 000000000..f21320a86 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureYBand.java @@ -0,0 +1,52 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.structure; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** + * A band of absolute world heights a platform structure is moved into, as packs write it: {"min": -120, "max": -20}. + * Unlike the API's heights these are world Y, as the platform's own structure definitions use them. Reversed bounds + * mean the same band. + */ +@Desc("An absolute world Y band a native structure is relocated into. Reversed bounds are normalized.") +public final class StructureYBand { + @MinNumber(-4064) + @MaxNumber(4064) + @Desc("Lowest absolute world Y of the band.") + private int min = 0; + + @MinNumber(-4064) + @MaxNumber(4064) + @Desc("Highest absolute world Y of the band.") + private int max = 0; + + public StructureYBand() { + } + + public int resolvedMin() { + return Math.min(min, max); + } + + public int resolvedMax() { + return Math.max(min, max); + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/terrain/BedrockSettings.java b/module/src/main/java/art/arcane/iris/builtin/terrain/BedrockSettings.java new file mode 100644 index 000000000..c22523760 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/terrain/BedrockSettings.java @@ -0,0 +1,38 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.builtin.terrain; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** Whether a dimension has a layer of bedrock at its bottom, written as {@code "bedrock": false}. A dimension without the key has it. */ +@Desc("Should bedrock be generated or not.") +@Feature(id = "iris:terrain/bedrock", name = "Bedrock", key = "bedrock", root = "bedrock", targets = Level.DIMENSION) +public final class BedrockSettings implements IrisFeature { + @Desc("Should bedrock be generated or not.") + private boolean bedrock = true; + + public BedrockSettings() { + } + + public boolean bedrock() { + return bedrock; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/terrain/LayersSettings.java b/module/src/main/java/art/arcane/iris/builtin/terrain/LayersSettings.java new file mode 100644 index 000000000..41151447e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/terrain/LayersSettings.java @@ -0,0 +1,44 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.terrain; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.List; + +/** + * The layers of material a biome is made of below its surface, written as {@code "layers": [...]}, the list of layers. A biome + * that declares none gets one layer of grass, so the settings class default is what a biome without the key has. + */ +@Desc("This defines the layers of materials in this biome. Each layer has a palette and min/max height and some other properties. Usually a grassy/sandy layer then a dirt layer then a stone layer. Iris will fill in the remaining blocks below your layers with stone.") +@Feature(id = "iris:terrain/layers", name = "Layers", key = "layers", root = "layers", targets = Level.BIOME) +public final class LayersSettings implements IrisFeature { + @Desc("This defines the layers of materials in this biome. Each layer has a palette and min/max height and some other properties. Usually a grassy/sandy layer then a dirt layer then a stone layer. Iris will fill in the remaining blocks below your layers with stone.") + private List layers = List.of(new PaletteLayer()); + + public LayersSettings() { + } + + public List layers() { + return layers == null ? List.of() : layers; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/terrain/PaletteLayer.java b/module/src/main/java/art/arcane/iris/builtin/terrain/PaletteLayer.java new file mode 100644 index 000000000..c0d30cb1a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/terrain/PaletteLayer.java @@ -0,0 +1,103 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.terrain; + +import art.arcane.iris.builtin.prepare.SlopeClip; +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; +import com.volmit.noise.NoiseStyle; + +import java.util.List; + +/** + * One layer of surface or subsurface material of a biome, as packs write it in the biome's layers, sea layers, cave + * ceiling layers, slab and wall, in a floating island's bottom palette or under {@code snippet/iris/terrain/biome-palette/}. A value of + * IrisApi types only; the terrain module resolves the blocks and builds the noise. + */ +@Snippet("iris/terrain/biome-palette") +@Desc("A layer of surface / subsurface material in biomes") +public final class PaletteLayer { + private static final String STATIC_NOISE = "STATIC"; + private static final String DEFAULT_BLOCK = "grass_block"; + + @Desc("The style of noise") + private NoiseStyle style = NoiseStyle.of(STATIC_NOISE); + + @MinNumber(0) + @MaxNumber(2032) + @Desc("The min thickness of this layer") + private int minHeight = 1; + + @MinNumber(1) + @MaxNumber(2032) + @Desc("The max thickness of this layer") + private int maxHeight = 1; + + @Desc("If set, this layer only shows where the terrain slope is within these bounds; outside them the layer is skipped entirely. Thickness is not scaled by slope.") + private SlopeClip slopeCondition = new SlopeClip(); + + @MinNumber(0.0001) + @Desc("The terrain zoom mostly for zooming in on a wispy palette") + private double zoom = 5; + + @Required + @MinItems(1) + @Desc("The palette of blocks to be used in this layer") + private List palette = List.of(BlockSpec.of(DEFAULT_BLOCK)); + + /** A layer with every option at its default, as packs get it from {@code {}}. */ + public PaletteLayer() { + } + + /** A layer with the default options and no block to place, which is what a biome without a slab or wall has. */ + public static PaletteLayer withoutBlocks() { + PaletteLayer layer = new PaletteLayer(); + layer.palette = List.of(); + return layer; + } + + public NoiseStyle style() { + return style == null ? NoiseStyle.of(STATIC_NOISE) : style; + } + + public int minHeight() { + return minHeight; + } + + public int maxHeight() { + return maxHeight; + } + + public SlopeClip slopeCondition() { + return slopeCondition == null ? new SlopeClip() : slopeCondition; + } + + public double zoom() { + return zoom; + } + + public List palette() { + return palette == null ? List.of() : palette; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/vacuum/VacuumSettings.java b/module/src/main/java/art/arcane/iris/builtin/vacuum/VacuumSettings.java new file mode 100644 index 000000000..159e8eb58 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/vacuum/VacuumSettings.java @@ -0,0 +1,73 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.vacuum; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Snippet; + +/** How a VACUUM place mode bends terrain to meet an object's base, written as the placement's {@code vacuumSettings}. */ +@Snippet("iris/vacuum/vacuum-settings") +@Desc("Defines how a VACUUM place mode bends terrain to meet an object's base.") +public final class VacuumSettings { + @MinNumber(0) + @MaxNumber(128) + @Desc("The horizontal radius (in blocks) the terrain deformation extends beyond the object footprint before it blends back to the natural surface. 0 = derive automatically from the place mode (VACUUM, VACUUM_HIGH larger, VACUUM_FAST smaller).") + private int radius = 0; + @MinNumber(0.25) + @MaxNumber(8) + @Desc("The falloff exponent controlling how the deformation eases out across the radius. 1 = linear (cone), 2 = parabolic (default, gentle bowl), higher = flatter near the object with a sharper drop at the edge.") + private double falloff = 2.0; + @MinNumber(0) + @MaxNumber(64) + @Desc("For VACUUM_ORGANIC: the maximum number of blocks the effective radius is randomly perturbed per column, giving the meeting edge an irregular organic outline instead of a clean circle.") + private int organicJitter = 4; + @MinNumber(0) + @MaxNumber(64) + @Desc("For VACUUM_WAVY: the vertical amplitude (in blocks) of the rolling simplex wave applied across the terrain bend. The wave fades to zero under the object (so it stays flush) and at the outer radius (so it blends back to the surface), peaking across the mid-slope. 0 disables the wave.") + private int waveAmplitude = 3; + @MinNumber(0.1) + @MaxNumber(64) + @Desc("For VACUUM_WAVY: the frequency of the simplex wave. Higher values make tighter, choppier ripples; lower values make broad, gentle swells. The wavelength in blocks is roughly 100 / waveScale.") + private double waveScale = 5.0; + + public VacuumSettings() { + } + + public int radius() { + return radius; + } + + public double falloff() { + return falloff; + } + + public int organicJitter() { + return organicJitter; + } + + public int waveAmplitude() { + return waveAmplitude; + } + + public double waveScale() { + return waveScale; + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/validate/ObjectLimit.java b/module/src/main/java/art/arcane/iris/builtin/validate/ObjectLimit.java new file mode 100644 index 000000000..76c15f177 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/validate/ObjectLimit.java @@ -0,0 +1,55 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.validate; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Snippet; + +/** The heights an object placement may sit between, written as the placement's {@code clamp}. */ +@Snippet("iris/validate/object-limit") +@Desc("Limits object placement by minimum and maximum world height") +public final class ObjectLimit { + @MinNumber(-2048) + @MaxNumber(2048) + @Desc("The minimum height for placement (bottom of object)") + private int minimumHeight = -2048; + + @MinNumber(-2048) + @MaxNumber(2048) + @Desc("The maximum height for placement (top of object)") + private int maximumHeight = 2048; + + public ObjectLimit() { + } + + public int minimumHeight() { + return minimumHeight; + } + + public int maximumHeight() { + return maximumHeight; + } + + /** Whether an object whose top is at {@code highest} and bottom at {@code lowest} fits between the limits. */ + public boolean canPlace(int highest, int lowest) { + return highest <= maximumHeight && lowest >= minimumHeight; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/module/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java new file mode 100644 index 000000000..bbf21ced0 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -0,0 +1,130 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.actuator; + +import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.decorant.DecorantSettings; +import art.arcane.iris.modules.decorant.DecorateSettings; +import art.arcane.iris.engine.decorator.BiomeDecorators; +import art.arcane.iris.engine.decorator.DecoratedBiome; +import art.arcane.iris.engine.decorator.DecorationScene; +import art.arcane.iris.engine.decorator.IrisSeaFloorDecorator; +import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; +import art.arcane.iris.engine.decorator.IrisShoreLineDecorator; +import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleLifecycle; +import com.volmit.ModuleSetup; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.hunk.Hunk; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.BiomeKind; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; + +/** + * Module {@code iris:decorant}: the biomes' decorators ({@link DecorantSettings}), placed on the surface the mantle's + * blocks left: the surface itself, the sea surface and floor, and the shore line. A dimension turns decorating off with + * {@link DecorateSettings}. The decorators' noise is built ahead of generation, in {@link #warmUp}. + */ +public final class DecorantModule implements IrisModule, ModuleLifecycle { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:decorant", "Decorators", VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + // Ordering only: iris:matter ships in the built-ins jar, which a pack may not have. + setup.stages().define(IrisStages.Decorant.DECORATE).softAfter(IrisStages.Matter.INSERT).run(DecorantModule::decorate); + var registry = setup.registry(); + registry.registerSettings(DecorantSettings.class); + registry.registerSettings(DecorateSettings.class); + registry.registerLifecycle(this); + } + + @Override + public void warmUp(PackWorld world) { + BiomeDecorators.of(world).warm(); + } + + private static void decorate(ChunkStageContext context) { + if (!decorates(context)) { + return; + } + decorate(DecorationScene.of(context), context.settings(), context.originX(), context.originZ()); + } + + /** A dimension decorates unless it says {@code decorate: false}. */ + private static boolean decorates(ChunkStageContext context) { + return context.settings().at(DecorateSettings.class, context.centreX(), context.centreZ()).dimension() + .map(DecorateSettings::decorate).orElse(true); + } + + /** Decorates the 16 x 16 columns of the chunk whose first block is {@code x}, {@code z}, a biome's decorators on the surface its blocks left. */ + static void decorate(DecorationScene scene, FeatureSettings settings, int x, int z) { + Hunk output = scene.blocks(); + TerrainSampler terrain = scene.terrain(); + BiomeDecorators decorators = scene.decorators(); + IrisSurfaceDecorator surfaceDecorator = new IrisSurfaceDecorator(scene); + IrisSeaSurfaceDecorator seaSurfaceDecorator = new IrisSeaSurfaceDecorator(scene); + IrisSeaFloorDecorator seaFloorDecorator = new IrisSeaFloorDecorator(scene); + IrisShoreLineDecorator shoreLineDecorator = new IrisShoreLineDecorator(scene); + int fluidHeight = scene.fluidHeight(); + int worldHeight = scene.worldHeight(); + + for (int i = 0; i < output.width(); i++) { + int realX = Math.round(x + i); + for (int j = 0; j < output.depth(); j++) { + int realZ = Math.round(z + j); + DecoratedBiome biome = BiomeDecorators.biomeOf(settings, realX, realZ, terrain.surfaceKind(realX, realZ)); + if (!decorators.hasDecorators(biome)) { + continue; + } + int height = terrain.surfaceHeight(realX, realZ); + + if (height >= 0 && height < fluidHeight && scene.isSolid(output.get(i, height, j)) + && height + 1 < output.height() && scene.isWater(output.get(i, height + 1, j))) { + seaSurfaceDecorator.decorate(i, j, + realX, Math.round(i + 1), Math.round(x + i - 1), + realZ, Math.round(z + j + 1), Math.round(z + j - 1), + biome, fluidHeight, worldHeight); + seaFloorDecorator.decorate(i, j, + realX, realZ, biome, height + 1, + fluidHeight + 1); + } + + if (height == fluidHeight) { + shoreLineDecorator.decorate(i, j, + realX, Math.round(x + i + 1), Math.round(x + i - 1), + realZ, Math.round(z + j + 1), Math.round(z + j - 1), + biome, height, worldHeight); + } + + if (height >= 0 && height < output.height()) { + surfaceDecorator.decorate(i, j, realX, realZ, biome, height, worldHeight - height); + } + } + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java b/module/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java new file mode 100644 index 000000000..8c54bb907 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java @@ -0,0 +1,76 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.actuator; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.modules.terrain.OreSettings; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.Comparator; +import java.util.function.LongSupplier; + +/** + * Builds the noise of every ore generator the world's biomes, regions and dimension declare before generation needs it. + * A generator keeps the noise of the first seed it is given, so each one is warmed with the seed of its place in + * this order: the biomes by key, the regions by key, then the dimension. The order is part of what a world generates. + */ +final class OreWarmUp { + private static final long ROOT_SEED_SALT = 7777L; + + private final PackWorld world; + private final TerrainOres ores; + private final RNG root; + private int warmed; + + OreWarmUp(PackWorld world) { + this(world, TerrainOres.of(world)); + } + + OreWarmUp(PackWorld world, TerrainOres ores) { + this.world = world; + this.ores = ores; + this.root = new RNG(world.seed(IrisSeedPurposes.COMPONENT) + ROOT_SEED_SALT); + } + + void warm() { + LongSupplier seeds = () -> root.nextParallelRNG(warmed++).getSeed(); + + SettingsStack declared = world.settings().declared(OreSettings.class); + warmLevel(declared, Level.BIOME, seeds); + warmLevel(declared, Level.REGION, seeds); + warmLevel(declared, Level.DIMENSION, seeds); + } + + /** The ores of every owner at {@code level}, ordered by the key of the biome, region or dimension that declares them. */ + private void warmLevel(SettingsStack declared, Level level, LongSupplier seeds) { + declared.entries().stream() + .filter(entry -> entry.level() == level) + .sorted(Comparator.comparing((Entry entry) -> key(entry.source()))) + .forEach(entry -> ores.of(entry.value()).warm(seeds)); + } + + private static String key(ResourceId source) { + String path = source.path(); + return path.substring(path.indexOf('/') + 1); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java b/module/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java new file mode 100644 index 000000000..dfd2a243a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java @@ -0,0 +1,127 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.actuator; + +import art.arcane.iris.modules.terrain.OreGenerator; +import art.arcane.volmlib.util.cache.AtomicCache; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; +import com.volmit.block.PaletteSampler; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.PackResources; + +import java.util.ArrayList; +import java.util.List; + +/** + * One {@link OreGenerator} made ready for one world: its palette resolved to blocks and the noise that + * decides where it places ore, built from the seed it is warmed with or, when nothing warmed it, from the terrain seed + * of its first use. The palette picks with the terrain seed. What the generator describes stays in the settings; + * everything that needs the platform, the pack or the world seed is here. + */ +final class ResolvedOre { + private final OreGenerator settings; + private final NoiseFactory noise; + private final BlockRegistry blockRegistry; + private final long terrainSeed; + private final List blocks; + private final AtomicCache chance = new AtomicCache<>(); + private final AtomicCache palette = new AtomicCache<>(); + + /** + * @param terrainSeed the seed the palette picks with, and the noise is built from when nothing warmed it first + * @param blocks the palette as the platform's blocks, each repeated by its weight + */ + ResolvedOre(OreGenerator settings, NoiseFactory noise, BlockRegistry blockRegistry, long terrainSeed, List blocks) { + this.settings = settings; + this.noise = noise; + this.blockRegistry = blockRegistry; + this.terrainSeed = terrainSeed; + this.blocks = List.copyOf(blocks); + } + + /** {@code settings} ready for a world with {@code resources}: its blocks resolved through the pack, its picks seeded with the terrain seed. */ + static ResolvedOre of(OreGenerator settings, PackResources resources, long terrainSeed) { + BlockRegistry registry = resources.blocks(); + return new ResolvedOre(settings, resources.noise(), registry, terrainSeed, weighted(registry, settings.palette().palette())); + } + + private static List weighted(BlockRegistry registry, List specs) { + List weighted = new ArrayList<>(); + for (BlockSpec spec : specs) { + BlockState state = registry.resolve(spec); + for (int n = 0; n < spec.weight(); n++) { + weighted.add(state); + } + } + return weighted; + } + + boolean generatesSurface() { + return settings.generateSurface(); + } + + double minY() { + return settings.range().min(); + } + + double maxY() { + return settings.range().max(); + } + + /** Builds the chance noise from {@code seed}, unless it is built already: the first seed it is given is the one it keeps. */ + void warm(long seed) { + chance.aquire(() -> noise.sampler(settings.chanceStyle(), seed)); + } + + /** The ore block at the position, or null when the position is out of the band, the chance noise is above the threshold or the palette has no block. */ + BlockState generate(int x, int y, int z) { + if (!settings.range().contains(y)) { + return null; + } + if (settings.palette().palette().isEmpty()) { + return null; + } + if (chanceNoise().sample(x, y, z) > settings.threshold()) { + return null; + } + return pick(x, y, z); + } + + /** The chance noise, which this runs per block of the terrain, so a built one is read without creating a supplier. */ + private NoiseSampler chanceNoise() { + NoiseSampler built = chance.getIfPresent(); + if (built != null) { + return built; + } + return chance.aquire(() -> noise.sampler(settings.chanceStyle(), terrainSeed)); + } + + private BlockState pick(int x, int y, int z) { + if (blocks.isEmpty()) { + return null; + } + if (blocks.size() == 1) { + return blocks.getFirst(); + } + PaletteSampler sampler = palette.aquire(() -> blockRegistry.palette(settings.palette(), terrainSeed)); + return sampler.at(x, y, z); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java b/module/src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java new file mode 100644 index 000000000..002113c92 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java @@ -0,0 +1,118 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.actuator; + +import art.arcane.iris.modules.terrain.OreGenerator; +import art.arcane.iris.modules.terrain.OreSettings; +import com.volmit.block.BlockState; +import com.volmit.resource.PackResources; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.LongSupplier; + +/** + * The ore generators of one dimension, region or biome made ready ({@link ResolvedOre}), in the order its settings list them + * and split into the ones that also replace surface blocks and the ones that only replace rock. A level without ores is + * {@link #NONE}. + */ +final class ResolvedOres { + static final ResolvedOres NONE = new ResolvedOres(List.of()); + + private final List all; + private final List surface; + private final List underground; + private final YBand surfaceBand; + private final YBand undergroundBand; + + ResolvedOres(List all) { + this.all = List.copyOf(all); + this.surface = this.all.stream().filter(ResolvedOre::generatesSurface).toList(); + this.underground = this.all.stream().filter(ore -> !ore.generatesSurface()).toList(); + this.surfaceBand = YBand.of(surface); + this.undergroundBand = YBand.of(underground); + } + + /** {@code settings} ready for a world with {@code resources}; generators the pack wrote as {@code null} are left out. */ + static ResolvedOres of(OreSettings settings, PackResources resources, long terrainSeed) { + List ores = new ArrayList<>(); + for (OreGenerator generator : settings.generators()) { + if (generator != null) { + ores.add(ResolvedOre.of(generator, resources, terrainSeed)); + } + } + return ores.isEmpty() ? NONE : new ResolvedOres(ores); + } + + /** The heights where any surface ore can generate. */ + YBand surfaceBand() { + return surfaceBand; + } + + /** The heights where any rock-only ore can generate. */ + YBand undergroundBand() { + return undergroundBand; + } + + /** Warms every ore in the order the settings list them, each with the next seed. */ + void warm(LongSupplier seeds) { + for (ResolvedOre ore : all) { + ore.warm(seeds.getAsLong()); + } + } + + BlockState generateSurface(int x, int y, int z) { + return firstOre(surface, x, y, z); + } + + BlockState generateUnderground(int x, int y, int z) { + return firstOre(underground, x, y, z); + } + + private static BlockState firstOre(List ores, int x, int y, int z) { + for (int index = 0; index < ores.size(); index++) { + BlockState ore = ores.get(index).generate(x, y, z); + if (ore != null) { + return ore; + } + } + return null; + } + + /** The lowest and highest height any of a set of ores reaches; empty when there are none. */ + record YBand(boolean hasOres, double min, double max) { + static final YBand EMPTY = new YBand(false, 0, 0); + + static YBand of(List ores) { + if (ores.isEmpty()) { + return EMPTY; + } + double min = Double.POSITIVE_INFINITY; + double max = Double.NEGATIVE_INFINITY; + for (ResolvedOre ore : ores) { + min = Math.min(min, ore.minY()); + max = Math.max(max, ore.maxY()); + } + return new YBand(true, min, max); + } + + boolean contains(int y) { + return hasOres && y >= min && y <= max; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/module/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java new file mode 100644 index 000000000..41ac61347 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -0,0 +1,89 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.actuator; + +import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.terrain.BedrockSettings; +import art.arcane.iris.modules.terrain.BiomePalettes; +import art.arcane.iris.modules.terrain.CaveCeilingLayersSettings; +import art.arcane.iris.modules.terrain.ExplodeBiomePaletteSizeSettings; +import art.arcane.iris.modules.terrain.ExplodeBiomePalettesSettings; +import art.arcane.iris.modules.terrain.FluidPaletteSettings; +import art.arcane.iris.modules.terrain.HideOresSettings; +import art.arcane.iris.builtin.terrain.LayersSettings; +import art.arcane.iris.modules.terrain.LockLayersMaxSettings; +import art.arcane.iris.modules.terrain.LockLayersSettings; +import art.arcane.iris.modules.terrain.OreSettings; +import art.arcane.iris.modules.terrain.RockPaletteSettings; +import art.arcane.iris.modules.terrain.SeaLayersSettings; +import art.arcane.iris.modules.terrain.SlabSettings; +import art.arcane.iris.modules.terrain.WallSettings; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleLifecycle; +import com.volmit.ModuleSetup; +import com.volmit.service.ProtectedFloor; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.PackWorld; + +import art.arcane.iris.modules.terrain.TerrainPalettes; + +import java.util.List; + +/** + * Module {@code iris:terrain}: the chunk's ground, fluids and biome layers. Each column is filled from bedrock up + * to its height and the fluid height with its biome's layers, with ore generators of the dimension, region and + * biome replacing blocks on the way and the upper dimension's ground filled in from the top. The ore generators' noise + * and the rock and fluid palettes' noise are built ahead of generation, in {@link #warmUp}. + */ +public final class TerrainModule implements IrisModule, ModuleLifecycle { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:terrain", "Terrain", VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + setup.stages().define(IrisStages.Terrain.SHAPE).run(TerrainModule::shape); + var registry = setup.registry(); + List.of(LayersSettings.class, SeaLayersSettings.class, CaveCeilingLayersSettings.class, SlabSettings.class, + WallSettings.class, LockLayersSettings.class, LockLayersMaxSettings.class, RockPaletteSettings.class, FluidPaletteSettings.class, + OreSettings.class, HideOresSettings.class, BedrockSettings.class, ExplodeBiomePalettesSettings.class, + ExplodeBiomePaletteSizeSettings.class).forEach(registry::registerSettings); + registry.registerService(ProtectedFloor.class, TerrainModule::protectsFloor); + registry.registerLifecycle(this); + setup.tooling().registerView(new BiomePalettes()); + } + + /** The bedrock row belongs to the terrain while the dimension has bedrock, as it does unless the pack says otherwise. */ + private static boolean protectsFloor(PackWorld world) { + return world.settings().declared(BedrockSettings.class).dimension().map(BedrockSettings::bedrock).orElse(true); + } + + @Override + public void warmUp(PackWorld world) { + TerrainPalettes.of(world).warm(); + new OreWarmUp(world).warm(); + } + + private static void shape(ChunkStageContext context) { + TerrainShaper.of(context.world()).shape(context); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java b/module/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java new file mode 100644 index 000000000..49967a2b8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java @@ -0,0 +1,61 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.actuator; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.modules.terrain.OreSettings; +import com.volmit.resource.PackResources; +import com.volmit.world.PackWorld; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * What the terrain module keeps for one world: the ore generators of its dimension, regions and biomes made ready + * ({@link ResolvedOres}), built from their {@link OreSettings} when first asked for or ahead of generation by {@link OreWarmUp}. + */ +final class TerrainOres { + private final PackResources resources; + private final long terrainSeed; + private final Map resolved = new ConcurrentHashMap<>(); + + TerrainOres(PackWorld world) { + this.resources = world.resources(); + this.terrainSeed = world.seed(IrisSeedPurposes.TERRAIN); + } + + /** The ores of {@code world}. */ + static TerrainOres of(PackWorld world) { + return world.state(TerrainOres.class, TerrainOres::new); + } + + /** + * The ore generators {@code settings}, those a dimension, region or biome declares, make ready; {@link ResolvedOres#NONE} when it + * declares none. The terrain asks this for two owners per column, so a resolved set is read without taking the map's lock. + */ + ResolvedOres of(OreSettings settings) { + if (settings == null) { + return ResolvedOres.NONE; + } + ResolvedOres existing = resolved.get(settings); + if (existing != null) { + return existing; + } + return resolved.computeIfAbsent(settings, declared -> ResolvedOres.of(declared, resources, terrainSeed)); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java b/module/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java new file mode 100644 index 000000000..3c897c989 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java @@ -0,0 +1,304 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.actuator; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.builtin.terrain.BedrockSettings; +import art.arcane.iris.modules.terrain.HideOresSettings; +import art.arcane.iris.modules.terrain.OreSettings; +import art.arcane.iris.engine.actuator.ResolvedOres.YBand; +import art.arcane.iris.modules.terrain.BiomeLayers; +import art.arcane.iris.modules.terrain.ColumnSlope; +import art.arcane.iris.modules.terrain.LayeredBiome; +import art.arcane.iris.modules.terrain.PaletteExplosion; +import art.arcane.iris.modules.terrain.TerrainPalettes; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.IrisFeature; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.hunk.Hunk; +import com.volmit.resource.ResourceId; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; +import com.volmit.world.UpperDimension; + +import java.util.Optional; +import java.util.OptionalInt; + +/** What shaping terrain keeps for one world: the terrain stream's random and the palettes, layers and ores the columns are filled from. */ +final class TerrainShaper { + private static final BlockState BEDROCK = new BlockState("minecraft:bedrock"); + + private final TerrainPalettes palettes; + private final BiomeLayers layers; + private final TerrainOres ores; + private final RNG rng; + private final boolean levelsBelowTheDimensionDeclareOres; + + static TerrainShaper of(PackWorld world) { + return world.state(TerrainShaper.class, TerrainShaper::new); + } + + TerrainShaper(PackWorld world) { + this(world, TerrainPalettes.of(world), BiomeLayers.of(world), TerrainOres.of(world)); + } + + TerrainShaper(PackWorld world, TerrainPalettes palettes, BiomeLayers layers, TerrainOres ores) { + this.palettes = palettes; + this.layers = layers; + this.ores = ores; + this.rng = new RNG(world.seed(IrisSeedPurposes.TERRAIN)); + this.levelsBelowTheDimensionDeclareOres = world.settings().declared(OreSettings.class).entries().stream() + .anyMatch(entry -> entry.level() != Level.DIMENSION); + } + + /** Fills the 16 x 16 columns of the chunk, one slice along x at a time. */ + void shape(ChunkStageContext context) { + Chunk chunk = new Chunk(context); + for (int sliceX = 0; sliceX < chunk.blocks.width(); sliceX++) { + shapeSliver(chunk, sliceX); + } + } + + /** One plane from the sky to bedrock, one block thick along x. */ + private void shapeSliver(Chunk chunk, int xf) { + Hunk h = chunk.blocks; + int chunkHeight = h.height(); + int chunkDepth = h.depth(); + int realX = xf + chunk.originX; + + for (int zf = 0; zf < chunkDepth; zf++) { + int realZ = zf + chunk.originZ; + int he = Math.min(chunkHeight, chunk.terrain.surfaceHeight(realX, realZ)); + int hf = Math.max(chunk.clampedFluidHeight, he); + if (hf < 0) { + continue; + } + + int topY = Math.min(hf, chunkHeight - 1); + BlockState fluid = palettes.fluidAt(realX, realZ); + BlockState rock = palettes.rockAt(realX, realZ); + BlockState mappedSurfaceBlock = chunk.terrain.surfaceBlock(realX, realZ).orElse(null); + LayeredBiome biome = layers.biome(chunk.terrain.surfaceBiome(realX, realZ), chunk.settings); + ColumnOres columnOres = chunk.oresAt(realX, realZ); + ResolvedOres biomeOres = columnOres.biome; + ResolvedOres regionOres = columnOres.region; + YBand biomeSurfaceBand = biomeOres.surfaceBand(); + YBand regionSurfaceBand = regionOres.surfaceBand(); + YBand biomeUndergroundBand = biomeOres.undergroundBand(); + YBand regionUndergroundBand = regionOres.undergroundBand(); + ResolvedOres dimensionOres = chunk.dimensionOres; + YBand dimensionSurfaceBand = dimensionOres.surfaceBand(); + YBand dimensionUndergroundBand = dimensionOres.undergroundBand(); + boolean hasSurfaceOres = biomeSurfaceBand.hasOres() || regionSurfaceBand.hasOres() || dimensionSurfaceBand.hasOres(); + boolean hasUndergroundOres = biomeUndergroundBand.hasOres() || regionUndergroundBand.hasOres() || dimensionUndergroundBand.hasOres(); + KList blocks = null; + KList fblocks = null; + + for (int i = topY; i >= 0; i--) { + if (i == 0 && chunk.bedrockEnabled) { + place(h, xf, i, zf, BEDROCK); + continue; + } + + BlockState ore = null; + if (hasSurfaceOres) { + if (biomeSurfaceBand.contains(i)) { + ore = biomeOres.generateSurface(realX, i, realZ); + } + if (ore == null && regionSurfaceBand.contains(i)) { + ore = regionOres.generateSurface(realX, i, realZ); + } + if (ore == null && dimensionSurfaceBand.contains(i)) { + ore = dimensionOres.generateSurface(realX, i, realZ); + } + } + if (ore != null) { + place(h, xf, i, zf, ore); + continue; + } + + if (i > he && i <= hf) { + int fdepth = hf - i; + if (fblocks == null) { + fblocks = layers.generateSeaLayers(biome, realX, realZ, rng, hf - he); + } + + if (fblocks.hasIndex(fdepth)) { + place(h, xf, i, zf, fblocks.get(fdepth)); + } else { + place(h, xf, i, zf, fluid); + } + continue; + } + + if (i <= he) { + int depth = he - i; + if (depth == 0 && mappedSurfaceBlock != null) { + place(h, xf, i, zf, mappedSurfaceBlock); + continue; + } + if (blocks == null) { + blocks = layers.generateLayers(biome, chunk.explosion, realX, realZ, rng, he, he, chunk.slope); + } + + if (blocks.hasIndex(depth)) { + place(h, xf, i, zf, blocks.get(depth)); + continue; + } + + if (hasUndergroundOres) { + if (biomeUndergroundBand.contains(i)) { + ore = biomeOres.generateUnderground(realX, i, realZ); + } + if (ore == null && regionUndergroundBand.contains(i)) { + ore = regionOres.generateUnderground(realX, i, realZ); + } + if (ore == null && dimensionUndergroundBand.contains(i)) { + ore = dimensionOres.generateUnderground(realX, i, realZ); + } + } + + place(h, xf, i, zf, ore != null ? ore : rock); + } + } + + if (chunk.upper.isPresent()) { + fillUpperDimension(chunk, chunk.upper.get(), xf, zf, realX, realZ); + } + } + } + + /** The upper dimension's ground, filled in from the top of the column down to where it ends. */ + private void fillUpperDimension(Chunk chunk, UpperDimension upper, int xf, int zf, int realX, int realZ) { + Hunk h = chunk.blocks; + int chunkHeight = h.height(); + OptionalInt upperY = chunk.terrain.upperDimensionY(realX, realZ); + if (upperY.isEmpty()) { + return; + } + int upperSurfaceY = upperY.getAsInt(); + if (upperSurfaceY >= chunkHeight - 1) { + return; + } + + FeatureSettings upperSettings = upper.settings(); + BlockState upperRock = palettes.upperRockAt(upper, realX, realZ); + BlockState upperMappedSurface = upper.surfaceBlock(realX, realZ).orElse(null); + int upperThickness = chunkHeight - 1 - upperSurfaceY; + LayeredBiome upperBiome = upperBiome(upperSettings, realX, realZ); + KList upperBlocks = layers.generateLayers(upperBiome, chunk.upperExplosion(upperSettings, realX, realZ), + realX, realZ, rng, upperThickness, upperThickness, chunk.slope); + + for (int y = chunkHeight - 1; y >= upperSurfaceY; y--) { + if (y == chunkHeight - 1 && chunk.bedrockEnabled) { + place(h, xf, y, zf, BEDROCK); + continue; + } + if (y == upperSurfaceY && upperMappedSurface != null) { + place(h, xf, y, zf, upperMappedSurface); + continue; + } + int depthFromFace = y - upperSurfaceY; + if (upperBlocks.hasIndex(depthFromFace)) { + place(h, xf, y, zf, upperBlocks.get(depthFromFace)); + } else { + place(h, xf, y, zf, upperRock); + } + } + } + + /** What the biome of the upper dimension at the column declares about its layers. */ + private LayeredBiome upperBiome(FeatureSettings upperSettings, int worldX, int worldZ) { + return new LayeredBiome(biomeLevel(upperSettings, art.arcane.iris.builtin.terrain.LayersSettings.class, worldX, worldZ), null, null, + biomeLevel(upperSettings, art.arcane.iris.modules.terrain.LockLayersSettings.class, worldX, worldZ), + biomeLevel(upperSettings, art.arcane.iris.modules.terrain.LockLayersMaxSettings.class, worldX, worldZ), null); + } + + private static S biomeLevel(FeatureSettings settings, Class type, int worldX, int worldZ) { + return settings.at(type, worldX, worldZ).level(Level.BIOME).orElse(null); + } + + /** A block the palette has none of leaves the column as it is. */ + private static void place(Hunk blocks, int x, int y, int z, BlockState block) { + if (block != null) { + blocks.set(x, y, z, block); + } + } + + /** The ores of a column's region and biome. */ + private record ColumnOres(ResolvedOres region, ResolvedOres biome) { + static final ColumnOres NONE = new ColumnOres(ResolvedOres.NONE, ResolvedOres.NONE); + } + + /** What one chunk's columns share: its views, its dimension's switches and ores. */ + private final class Chunk { + final Hunk blocks; + final TerrainSampler terrain; + final FeatureSettings settings; + final int originX; + final int originZ; + final int clampedFluidHeight; + final boolean bedrockEnabled; + final PaletteExplosion explosion; + final ColumnSlope slope; + final Optional upper; + final ResolvedOres dimensionOres; + private final boolean hideOres; + private PaletteExplosion upperExplosion; + + Chunk(ChunkStageContext context) { + this.blocks = context.blocks(); + this.terrain = context.terrain(); + this.settings = context.settings(); + this.originX = context.originX(); + this.originZ = context.originZ(); + this.clampedFluidHeight = Math.min(blocks.height(), terrain.fluidHeight()); + int centreX = context.centreX(); + int centreZ = context.centreZ(); + this.bedrockEnabled = settings.at(BedrockSettings.class, centreX, centreZ).dimension().map(BedrockSettings::bedrock).orElse(true); + this.hideOres = settings.at(HideOresSettings.class, centreX, centreZ).dimension().map(HideOresSettings::hide).orElse(false); + this.explosion = PaletteExplosion.of(settings, centreX, centreZ); + this.slope = (x, z) -> terrain.column((int) x, (int) z).slope(); + this.upper = terrain.upperDimension(); + // Dimension-level ore lookups are chunk-invariant; resolving them per column paid the settings lookup times 256 per chunk for a constant. + this.dimensionOres = hideOres ? ResolvedOres.NONE : ores.of(settings.at(OreSettings.class, centreX, centreZ).dimension().orElse(null)); + } + + /** What the upper dimension declares about exploded palettes: a setting of the dimension, so the same for every column of the chunk. */ + PaletteExplosion upperExplosion(FeatureSettings upperSettings, int worldX, int worldZ) { + if (upperExplosion == null) { + upperExplosion = PaletteExplosion.of(upperSettings, worldX, worldZ); + } + return upperExplosion; + } + + /** The ores of the column's region and biome; none where the levels below the dimension declare none, or the dimension hides ores. */ + ColumnOres oresAt(int worldX, int worldZ) { + if (hideOres || !levelsBelowTheDimensionDeclareOres) { + return ColumnOres.NONE; + } + SettingsStack declared = settings.at(OreSettings.class, worldX, worldZ); + return new ColumnOres(ores.of(declared.level(Level.REGION).orElse(null)), ores.of(declared.level(Level.BIOME).orElse(null))); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java b/module/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java new file mode 100644 index 000000000..67888f7ca --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java @@ -0,0 +1,143 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.decorator; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.builtin.decorant.DecorantSettings; +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.iris.builtin.decorant.Decorator; +import com.volmit.config.FeatureSettings; +import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * What the decorant module keeps for one world: the decorators of its biomes made ready ({@link ResolvedDecorator}), sorted into + * the places they decorate. Built from the biomes' {@link DecorantSettings} when first asked for, or ahead of generation by + * {@link #warm()}. + * + *

A decorator's noise seed is a function of the world's decorator seed, its biome's key and its place in the biome's + * list, so it does not depend on which column or which warm-up reached it first. + */ +public final class BiomeDecorators { + private static final ResolvedDecorator[] NO_DECORATORS = new ResolvedDecorator[0]; + private static final String BIOME_PATH_PREFIX = "biome/"; + private static final long KEY_SEED_FACTOR = 0x9E3779B97F4A7C15L; + private static final long INDEX_SEED_FACTOR = 0xC2B2AE3D27D4EB4FL; + + private final PackWorld world; + private final PackResources resources; + private final ModuleLog log; + private final long decoratorSeed; + private final Map> decorators = new ConcurrentHashMap<>(); + + BiomeDecorators(PackWorld world) { + this.world = world; + this.resources = world.resources(); + this.log = world.log(); + this.decoratorSeed = world.seed(IrisSeedPurposes.DECORATOR); + } + + /** The world's decorators, kept in its state store. */ + public static BiomeDecorators of(PackWorld world) { + return world.state(BiomeDecorators.class, BiomeDecorators::new); + } + + /** The key of the biome a settings entry was declared by, such as {@code desert/dunes} for {@code overworld:biome/desert/dunes}. */ + public static String biomeKey(ResourceId source) { + String path = source.path(); + return path.startsWith(BIOME_PATH_PREFIX) ? path.substring(BIOME_PATH_PREFIX.length()) : path; + } + + /** The biome of the entry a column's settings gave, which is the column's surface biome; null when the biome declares nothing. */ + public static DecoratedBiome biomeOf(FeatureSettings settings, int worldX, int worldZ, com.volmit.world.BiomeKind kind) { + List> entries = settings.at(DecorantSettings.class, worldX, worldZ).entries(); + if (entries.isEmpty()) { + return null; + } + Entry entry = entries.getLast(); + return new DecoratedBiome(biomeKey(entry.source()), entry.value(), kind); + } + + /** The log of the module that decorates, which the decorators write to. */ + ModuleLog log() { + return log; + } + + /** Whether the biome declares any decorator. */ + public boolean hasDecorators(DecoratedBiome biome) { + return biome != null && biome.settings() != null && !biome.settings().decorators().isEmpty(); + } + + /** The biome's decorators for {@code part}, in the order the biome lists them. */ + ResolvedDecorator[] decorators(DecoratedBiome biome, DecorationPart part) { + if (biome == null || biome.settings() == null) { + return NO_DECORATORS; + } + return decorators.computeIfAbsent(biome.settings(), declared -> resolve(biome.key(), declared)).getOrDefault(part, NO_DECORATORS); + } + + /** Whether the biome has a decorator for {@code part}. */ + public boolean hasDecorators(DecoratedBiome biome, DecorationPart part) { + return decorators(biome, part).length > 0; + } + + /** Resolves every decorator of every biome the dimension reaches and builds its noise, so that generation finds them ready. */ + public void warm() { + List> declared = new ArrayList<>(world.settings().declared(DecorantSettings.class).entries()); + declared.sort(Comparator.comparing(entry -> biomeKey(entry.source()))); + for (Entry entry : declared) { + DecoratedBiome biome = new DecoratedBiome(biomeKey(entry.source()), entry.value(), null); + for (DecorationPart part : DecorationPart.values()) { + for (ResolvedDecorator decorator : decorators(biome, part)) { + decorator.warm(); + } + } + } + } + + private Map resolve(String biomeKey, DecorantSettings settings) { + Map> staging = new EnumMap<>(DecorationPart.class); + List declared = settings.decorators(); + for (int index = 0; index < declared.size(); index++) { + Decorator decorator = declared.get(index); + if (decorator == null) { + continue; + } + ResolvedDecorator resolved = ResolvedDecorator.of(decorator, resources, seedOf(biomeKey, index), log, biomeKey); + staging.computeIfAbsent(decorator.partOf(), part -> new ArrayList<>()).add(resolved); + } + + Map buckets = new EnumMap<>(DecorationPart.class); + staging.forEach((part, list) -> buckets.put(part, list.toArray(NO_DECORATORS))); + return buckets; + } + + private long seedOf(String biomeKey, int index) { + return decoratorSeed + (biomeKey.hashCode() * KEY_SEED_FACTOR) + (index * INDEX_SEED_FACTOR); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/decorator/DecoratedBiome.java b/module/src/main/java/art/arcane/iris/engine/decorator/DecoratedBiome.java new file mode 100644 index 000000000..2bad9d80c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/decorator/DecoratedBiome.java @@ -0,0 +1,28 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.decorator; + +import art.arcane.iris.builtin.decorant.DecorantSettings; +import com.volmit.world.BiomeKind; + +/** + * A biome as the decorators see it: the key the pack names it by, which seeds its decorators' noise, the decorators it declares + * (none when it declares no {@link DecorantSettings}) and what it was generated as. + */ +public record DecoratedBiome(String key, DecorantSettings settings, BiomeKind kind) { +} diff --git a/module/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java b/module/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java new file mode 100644 index 000000000..485f82150 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java @@ -0,0 +1,149 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.decorator; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.hunk.Hunk; +import com.volmit.mantle.Mantle; +import com.volmit.mantle.MantleLayer; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.TerrainSampler; + +import java.util.EnumMap; +import java.util.IdentityHashMap; +import java.util.Map; + +/** + * Everything the decorators of one chunk look at: its blocks, the blocks the mantle planned around it, the terrain, the pack's + * block rules and the biomes' decorators. A decorator places into {@link #blocks()} only. What it asks of a block is asked + * once for each distinct block instance, since a chunk holds few. + */ +public final class DecorationScene { + private final Hunk blocks; + private final BlockRegistry registry; + private final TerrainSampler terrain; + private final MantleLayer planned; + private final BiomeDecorators decorators; + private final long seed; + private final ModuleLog log; + private final Map> traits = new EnumMap<>(BlockTrait.class); + private final Map> supports = new IdentityHashMap<>(); + + /** The chunk of {@code context}, decorated with the world's decorators. */ + public static DecorationScene of(ChunkStageContext context) { + Mantle mantle = context.mantle(); + return new DecorationScene(context.blocks(),context.world().resources().blocks(), context.terrain(), + mantle == null ? null : mantle.blocks(), BiomeDecorators.of(context.world()), context.world().seed(IrisSeedPurposes.COMPONENT), + context.log()); + } + + public DecorationScene(Hunk blocks, BlockRegistry registry, TerrainSampler terrain, MantleLayer planned, + BiomeDecorators decorators, long seed, ModuleLog log) { + this.blocks = blocks; + this.registry = registry; + this.terrain = terrain; + this.planned = planned; + this.decorators = decorators; + this.seed = seed; + this.log = log; + } + + public Hunk blocks() { + return blocks; + } + + public BlockRegistry registry() { + return registry; + } + + public TerrainSampler terrain() { + return terrain; + } + + public BiomeDecorators decorators() { + return decorators; + } + + /** The seed the decorators of every place draw from, each shifted by its own part. */ + long seed() { + return seed; + } + + ModuleLog log() { + return log; + } + + /** The height of the chunk's volume. */ + public int worldHeight() { + return blocks.height(); + } + + public int fluidHeight() { + return terrain.fluidHeight(); + } + + /** The slope of the terrain at the column. */ + double slopeAt(int worldX, int worldZ) { + return terrain.column(worldX, worldZ).slope(); + } + + /** The height of the terrain at the column, rounded. */ + long roundedHeightAt(int worldX, int worldZ) { + return terrain.surfaceHeight(worldX, worldZ); + } + + /** The block a placement planned at the position, or air; positions the mantle does not cover read as air. */ + BlockState plannedAt(int worldX, int y, int worldZ) { + if (planned == null || y < 0 || y >= worldHeight()) { + return null; + } + return planned.get(worldX, y, worldZ); + } + + boolean has(BlockTrait trait, BlockState block) { + return traits.computeIfAbsent(trait, ignored -> new IdentityHashMap<>()) + .computeIfAbsent(block, known -> registry.hasTrait(known, trait)); + } + + public boolean isAir(BlockState block) { + return has(BlockTrait.AIR, block); + } + + public boolean isFluid(BlockState block) { + return has(BlockTrait.FLUID, block); + } + + public boolean isSolid(BlockState block) { + return has(BlockTrait.SOLID, block); + } + + public boolean isWater(BlockState block) { + return has(BlockTrait.WATER, block); + } + + /** Whether {@code decoration} may stand on {@code surface}: its kind of block on that kind of block, and the surface carries a block on its top face. */ + boolean canGoOn(BlockState decoration, BlockState surface) { + return supports.computeIfAbsent(decoration, ignored -> new IdentityHashMap<>()) + .computeIfAbsent(surface, known -> registry.canPlaceOn(decoration, known) + && registry.canAttach(decoration, known, com.volmit.geometry.BlockFace.UP)); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java b/module/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java new file mode 100644 index 000000000..7e3dc450c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java @@ -0,0 +1,490 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.decorator; + +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.geometry.BlockFace; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.hunk.Hunk; +import com.volmit.resource.ResourceId; + +import java.util.List; +import java.util.Map; + +final class DecoratorCore { + + private static final long SEED_OFFSET = 29356788L; + private static final long PART_FACTOR = 10439677L; + private static final String HALF = "half"; + private static final ResourceId WEEPING_VINES = ResourceId.parse("minecraft:weeping_vines"); + private static final ResourceId WEEPING_VINES_PLANT = ResourceId.parse("minecraft:weeping_vines_plant"); + private static final ResourceId TWISTING_VINES = ResourceId.parse("minecraft:twisting_vines"); + private static final ResourceId TWISTING_VINES_PLANT = ResourceId.parse("minecraft:twisting_vines_plant"); + private static final ResourceId POINTED_DRIPSTONE = ResourceId.parse("minecraft:pointed_dripstone"); + private static final String[] DRIPSTONE_THICKNESS = {"tip", "frustum", "base"}; + private static final BlockState[] DRIPSTONE_UP = dripstones("up"); + private static final BlockState[] DRIPSTONE_DOWN = dripstones("down"); + private static final BlockState AIR = new BlockState("minecraft:air"); + /** The faces a vine can grow on, in the order Iris looks at them, with the neighbour each faces. */ + private static final List FACES = List.of(new Face(BlockFace.NORTH, "north", 0, 0, -1), new Face(BlockFace.EAST, "east", 1, 0, 0), + new Face(BlockFace.SOUTH, "south", 0, 0, 1), new Face(BlockFace.WEST, "west", -1, 0, 0), new Face(BlockFace.UP, "up", 0, 1, 0), + new Face(BlockFace.DOWN, "down", 0, -1, 0)); + private static final Map OPPOSITES = Map.of(BlockFace.NORTH, BlockFace.SOUTH, BlockFace.SOUTH, BlockFace.NORTH, + BlockFace.EAST, BlockFace.WEST, BlockFace.WEST, BlockFace.EAST, BlockFace.UP, BlockFace.DOWN, BlockFace.DOWN, BlockFace.UP); + private static final int CHUNK_LAST = 15; + + static final ThreadLocal SCRATCH_OPTS = ThreadLocal.withInitial(PlaceOpts::new); + + static final class PlaceOpts { + boolean caveSkipFluid; + boolean underwater; + int fluidHeight; + + void reset() { + caveSkipFluid = false; + underwater = false; + fluidHeight = 0; + } + } + + private record Face(BlockFace face, String property, int dx, int dy, int dz) { + } + + static long partSeed(long baseSeed, int partOrdinal) { + return baseSeed + SEED_OFFSET - (partOrdinal * PART_FACTOR); + } + + static long partSeed(long baseSeed, DecorationPart part) { + return partSeed(baseSeed, part.ordinal()); + } + + /** The decorator of {@code bucket} that decorates the column, drawing from {@code colRng} to choose between those whose chance noise passes. */ + static ResolvedDecorator pickDecorator(ResolvedDecorator[] bucket, RNG colRng, double realX, double realZ, ModuleLog log) { + ResolvedDecorator picked = null; + int count = 0; + + for (ResolvedDecorator d : bucket) { + try { + if (d.passesChanceGate(realX, realZ)) { + count++; + if (count == 1 || colRng.nextInt(count) == 0) { + picked = d; + } + } + } catch (Throwable e) { + log.error("A decorator failed to pick for the column", e); + } + } + + return picked; + } + + private static String topHalfValue(String half) { + return half.equals("upper") || half.equals("lower") ? "upper" : "top"; + } + + private static String bottomHalfValue(String half) { + return half.equals("upper") || half.equals("lower") ? "lower" : "bottom"; + } + + static void placeSurfaceSingle(ResolvedDecorator decorator, DecorationScene scene, + int x, int z, int realX, int height, int realZ, + boolean underwater, boolean caveSkipFluid) { + Hunk data = scene.blocks(); + if (height < 0 || height >= data.height()) { + return; + } + + BlockState bdx = data.get(x, height, z); + BlockState bd = decorator.pickBlock(realX, realZ); + + if (!underwater && !canGoOn(scene, bd, bdx) + && !decorator.isForcePlace() && decorator.forceBlock() == null) { + return; + } + + if (decorator.forceBlock() != null) { + if (caveSkipFluid && scene.isFluid(bdx)) { + return; + } + data.set(x, height, z, fixFacesForHunk(scene, decorator.forceBlock(), x, z, realX, height, realZ)); + } + + if (!decorator.isForcePlace() && decorator.rejectsSurface(bdx)) { + return; + } + + String half = bd == null ? null : bd.properties().get(HALF); + if (half != null) { + int lowerY = height + 1; + int upperY = height + 2; + if (!canPlaceTwoBlockPlant(scene, x, z, lowerY, upperY, caveSkipFluid)) { + return; + } + + try { + BlockState upper = bd.withProperty(HALF, topHalfValue(half)); + BlockState lower = fixFacesForHunk(scene, + bd.withProperty(HALF, bottomHalfValue(half)), + x, z, realX, lowerY, realZ); + data.set(x, lowerY, z, lower); + data.set(x, upperY, z, upper); + } catch (Throwable e) { + scene.log().error("Failed to place a two-block plant", e); + } + return; + } + + int targetY = height + 1; + if (bd != null && targetY < data.height() && scene.isAir(data.get(x, targetY, z))) { + data.set(x, targetY, z, fixFacesForHunk(scene, bd, x, z, realX, targetY, realZ)); + } + } + + static void placeSingleAt(ResolvedDecorator decorator, DecorationScene scene, int x, int z, + int realX, int height, int realZ, boolean applyFixFaces) { + BlockState bd = decorator.pickBlock(realX, realZ); + if (bd == null) { + return; + } + if (applyFixFaces) { + bd = fixFacesForHunk(scene, bd, x, z, realX, height, realZ); + } + scene.blocks().set(x, height, z, bd); + } + + static void placeStackUp(ResolvedDecorator decorator, DecorationScene scene, int x, int z, int realX, int realZ, + int height, int max, PlaceOpts opts) { + Hunk data = scene.blocks(); + if (height < 0 || height >= data.height()) { + return; + } + + int effectiveMax = max; + if (opts.underwater && height < opts.fluidHeight) { + effectiveMax = opts.fluidHeight; + } + + int stack = computeStack(decorator, realX, realZ, effectiveMax); + + if (stack == 1) { + int targetY = height + 1; + if (targetY >= data.height()) { + return; + } + + BlockState existing = data.get(x, targetY, z); + if (!canReplaceStackTarget(scene, existing, opts.underwater) + || (opts.caveSkipFluid && scene.isFluid(existing))) { + return; + } + + BlockState block = decorator.pickTopBlock(realX, realZ); + if (block == null || (!opts.underwater && !canGoOn(scene, block, data.get(x, height, z)))) { + return; + } + + block = stackedVineBlock(block, stack, 0); + data.set(x, targetY, z, block); + return; + } + + BlockState bdx = data.get(x, height, z); + + for (int i = 0; i < stack; i++) { + double threshold = ((double) i) / (stack - 1); + BlockState bd = threshold >= decorator.topThreshold() + ? decorator.pickTopBlock(realX, realZ) + : decorator.pickBlock(realX, realZ); + + if (bd == null) { + break; + } + + if (i == 0 && !opts.underwater && !canGoOn(scene, bd, bdx)) { + break; + } + + if (opts.underwater && height + 1 + i > opts.fluidHeight) { + break; + } + + if (height + 1 + i >= data.height()) { + break; + } + + BlockState existing = data.get(x, height + 1 + i, z); + if (!canReplaceStackTarget(scene, existing, opts.underwater) + || (opts.caveSkipFluid && scene.isFluid(existing))) { + break; + } + + if (bd.material().equals(POINTED_DRIPSTONE)) { + bd = dripstoneBlock(stack, i, DRIPSTONE_UP); + } + + bd = stackedVineBlock(bd, stack, i); + data.set(x, height + 1 + i, z, bd); + } + } + + static void placeStackDown(ResolvedDecorator decorator, DecorationScene scene, int x, int z, int realX, int realZ, + int height, int minHeight, int max, PlaceOpts opts) { + Hunk data = scene.blocks(); + if (height < 0 || height >= data.height()) { + return; + } + + int stack = computeStack(decorator, realX, realZ, max); + + if (stack == 1) { + if (opts.caveSkipFluid && scene.isFluid(data.get(x, height, z))) { + return; + } + BlockState block = decorator.pickTopBlock(realX, realZ); + if (block == null) { + return; + } + block = stackedVineBlock(block, stack, 0); + data.set(x, height, z, fixFacesForHunk(scene, block, x, z, realX, height, realZ)); + return; + } + + for (int i = 0; i < stack; i++) { + int h = height - i; + if (h < 0 || h < minHeight) { + break; + } + + double threshold = ((double) i) / (double) (stack - 1); + BlockState bd = threshold >= decorator.topThreshold() + ? decorator.pickTopBlock(realX, realZ) + : decorator.pickBlock(realX, realZ); + + if (bd == null) { + break; + } + + if (bd.material().equals(POINTED_DRIPSTONE)) { + bd = dripstoneBlock(stack, i, DRIPSTONE_DOWN); + } + + bd = stackedVineBlock(bd, stack, i); + if (opts.caveSkipFluid && scene.isFluid(data.get(x, h, z))) { + break; + } + data.set(x, h, z, fixFacesForHunk(scene, bd, x, z, realX, h, realZ)); + } + } + + static void placeFloatingSimple(ResolvedDecorator decorator, DecorationScene scene, + int xf, int zf, int realX, int realZ, + int height, int max) { + Hunk data = scene.blocks(); + BlockState bd = decorator.pickBlock(realX, realZ); + if (bd == null) { + return; + } + + String half = bd.properties().get(HALF); + if (half != null) { + int lowerY = height + 1; + int upperY = height + 2; + if (max <= 2 || !canPlaceTwoBlockPlant(scene, xf, zf, lowerY, upperY, false)) { + return; + } + + try { + BlockState upper = bd.withProperty(HALF, topHalfValue(half)); + BlockState lower = bd.withProperty(HALF, bottomHalfValue(half)); + data.set(xf, lowerY, zf, lower); + data.set(xf, upperY, zf, upper); + } catch (Throwable e) { + scene.log().error("Failed to place a two-block plant", e); + } + return; + } + + if (max > 1 && height + 1 < data.height()) { + data.set(xf, height + 1, zf, bd); + } + } + + static int placeFloatingStacked(ResolvedDecorator decorator, DecorationScene scene, + int xf, int zf, int realX, int realZ, + int height, int max) { + Hunk data = scene.blocks(); + int stack = decorator.stackHeight(realX, realZ); + if (decorator.isScaleStack()) { + stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.absoluteMaxStack()); + } else { + stack = Math.min(max, stack); + } + + int placed = 0; + for (int i = 0; i < stack; i++) { + int h = height + 1 + i; + if (h >= height + max || h >= data.height()) { + break; + } + double threshold = stack == 1 ? 0.0 : ((double) i) / (stack - 1); + BlockState bd = threshold >= decorator.topThreshold() + ? decorator.pickTopBlock(realX, realZ) + : decorator.pickBlock(realX, realZ); + if (bd == null) { + break; + } + bd = stackedVineBlock(bd, stack, i); + data.set(xf, h, zf, bd); + placed++; + } + return placed; + } + + /** + * A vine placed at {@code x}, {@code y}, {@code z} (the chunk's local column {@code rX}, {@code rZ}) faces the neighbours that + * can hold it: the blocks the mantle planned there, else the chunk's own blocks. A vine with no such neighbour faces down, + * or up when it cannot face down. Any other block is returned as it is. + */ + static BlockState fixFacesForHunk(DecorationScene scene, BlockState b, int rX, int rZ, int x, int y, int z) { + if (b == null || !scene.has(BlockTrait.VINE, b)) { + return b; + } + Hunk hunk = scene.blocks(); + BlockState fixed = b; + for (Face face : FACES) { + if (b.properties().containsKey(face.property())) { + fixed = fixed.withProperty(face.property(), "false"); + } + } + + boolean found = false; + for (Face face : FACES) { + int yy = y + face.dy(); + BlockFace opposite = OPPOSITES.get(face.face()); + + BlockState planned = scene.plannedAt(x + face.dx(), yy, z + face.dz()); + BlockState support = planned == null ? AIR : planned; + if (scene.registry().canAttach(b, support, opposite)) { + if (b.properties().containsKey(face.property())) { + found = true; + fixed = fixed.withProperty(face.property(), "true"); + } + continue; + } + + int xx = rX + face.dx(); + int zz = rZ + face.dz(); + if (xx < 0 || xx > CHUNK_LAST || zz < 0 || zz > CHUNK_LAST || yy < 0 || yy >= hunk.height()) { + continue; + } + + if (scene.registry().canAttach(b, hunk.get(xx, yy, zz), opposite)) { + if (b.properties().containsKey(face.property())) { + found = true; + fixed = fixed.withProperty(face.property(), "true"); + } + } + } + if (!found) { + String fallback = b.properties().containsKey("down") ? "down" : "up"; + if (b.properties().containsKey(fallback)) { + fixed = fixed.withProperty(fallback, "true"); + } + } + return fixed; + } + + static boolean canGoOn(DecorationScene scene, BlockState decorator, BlockState surface) { + return decorator != null && surface != null && scene.canGoOn(decorator, surface); + } + + static boolean isValidShorelineSupport(DecorationScene scene, ResolvedDecorator decorator, BlockState decorant, BlockState surface) { + return surface != null + && scene.isSolid(surface) + && (decorator.isForcePlace() || canGoOn(scene, decorant, surface)); + } + + static boolean canReplaceStackTarget(DecorationScene scene, BlockState state, boolean allowFluid) { + return scene.isAir(state) || allowFluid && scene.isFluid(state); + } + + private static boolean canPlaceTwoBlockPlant(DecorationScene scene, int x, int z, + int lowerY, int upperY, boolean caveSkipFluid) { + Hunk data = scene.blocks(); + if (lowerY < 0 || upperY >= data.height()) { + return false; + } + + BlockState lower = data.get(x, lowerY, z); + BlockState upper = data.get(x, upperY, z); + return scene.isAir(lower) && scene.isAir(upper) + && (!caveSkipFluid || !scene.isFluid(lower) && !scene.isFluid(upper)); + } + + private static int computeStack(ResolvedDecorator decorator, double realX, double realZ, int max) { + int stack = decorator.stackHeight(realX, realZ); + if (decorator.isScaleStack()) { + stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.absoluteMaxStack()); + } else { + stack = Math.min(max, stack); + } + return stack; + } + + private static BlockState[] dripstones(String direction) { + BlockState[] arr = new BlockState[DRIPSTONE_THICKNESS.length]; + for (int k = 0; k < arr.length; k++) { + arr[k] = BlockState.parse("minecraft:pointed_dripstone[thickness=" + DRIPSTONE_THICKNESS[k] + ",vertical_direction=" + direction + "]"); + } + return arr; + } + + private static BlockState dripstoneBlock(int stack, int i, BlockState[] byThickness) { + int thIdx; + if (i == stack - 1) { + thIdx = 0; + } else if (i == stack - 2) { + thIdx = 1; + } else { + thIdx = 2; + } + return byThickness[thIdx]; + } + + /** The key of the vine block that fills a stack of vines at {@code index}: the tip at the end, the plant before it; null for other blocks. */ + static ResourceId stackedVineMaterial(BlockState state, int stack, int index) { + ResourceId material = state.material(); + boolean tip = index == stack - 1; + if (material.equals(WEEPING_VINES) || material.equals(WEEPING_VINES_PLANT)) { + return tip ? WEEPING_VINES : WEEPING_VINES_PLANT; + } + if (material.equals(TWISTING_VINES) || material.equals(TWISTING_VINES_PLANT)) { + return tip ? TWISTING_VINES : TWISTING_VINES_PLANT; + } + return null; + } + + private static BlockState stackedVineBlock(BlockState state, int stack, int index) { + ResourceId material = stackedVineMaterial(state, stack, index); + return material == null ? state : new BlockState(material.toString()); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java b/module/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java new file mode 100644 index 000000000..c5c9ec635 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java @@ -0,0 +1,49 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.decorator; + +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.volmlib.util.math.RNG; + +/* + * Floating island decoration path. Bypasses all canGoOn, slope, whitelist, and blacklist + * gating from IrisSurfaceDecorator: the island top IS the biome's designated surface by + * construction, so those material-compatibility checks are never meaningful here. + */ +public class FloatingDecorator { + + public static int decorateColumn(DecorationScene scene, DecoratedBiome target, DecorationPart part, + int xf, int zf, int realX, int realZ, + int height, int max, RNG rng, + Runnable candidatesNullCallback) { + BiomeDecorators decorators = scene.decorators(); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(target, part), rng, realX, realZ, decorators.log()); + + if (decorator == null) { + candidatesNullCallback.run(); + return 0; + } + + if (!decorator.isStacking()) { + DecoratorCore.placeFloatingSimple(decorator, scene, xf, zf, realX, realZ, height, max); + return max > 1 ? 1 : 0; + } + + return DecoratorCore.placeFloatingStacked(decorator, scene, xf, zf, realX, realZ, height, max); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java b/module/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java new file mode 100644 index 000000000..1883d62e3 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java @@ -0,0 +1,52 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.decorator; + +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.volmlib.util.math.RNG; + +public class IrisCeilingDecorator extends IrisEngineDecorator { + public IrisCeilingDecorator(DecorationScene scene) { + super(scene, DecorationPart.CEILING); + } + + @Override + public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, + DecoratedBiome biome, int height, int max) { + boolean caveSkipFluid = IrisSurfaceDecorator.skipsFluid(biome.kind()); + RNG rng = getRNG(realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log()); + + if (decorator == null) { + return; + } + + if (!decorator.isStacking()) { + if (caveSkipFluid && scene.isFluid(scene.blocks().get(x, height, z))) { + return; + } + DecoratorCore.placeSingleAt(decorator, scene, x, z, realX, height, realZ, true); + return; + } + + DecoratorCore.PlaceOpts opts = DecoratorCore.SCRATCH_OPTS.get(); + opts.reset(); + opts.caveSkipFluid = caveSkipFluid; + DecoratorCore.placeStackDown(decorator, scene, x, z, realX, realZ, height, 0, max, opts); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java b/module/src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java new file mode 100644 index 000000000..a34881b2e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java @@ -0,0 +1,63 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.decorator; + +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.volmlib.util.math.RNG; + +/** A decorator of one kind of place, placing into the blocks of a {@link DecorationScene}. */ +public abstract class IrisEngineDecorator { + private static final long COLUMN_X_FACTOR = 29356788L; + private static final long COLUMN_Z_FACTOR = 10439677L; + private static final int X_PART_OFFSET = 6; + private static final int Z_PART_OFFSET = 1; + + private final DecorationPart part; + protected final DecorationScene scene; + protected final BiomeDecorators decorators; + + protected IrisEngineDecorator(DecorationScene scene, DecorationPart part) { + this.scene = scene; + this.part = part; + this.decorators = scene.decorators(); + } + + public DecorationPart getPart() { + return part; + } + + /** + * Decorates one column. {@code x} and {@code z} are the column in the chunk, {@code realX} and {@code realZ} in the world, + * with the world columns next to it on either side; {@code height} is the Y to decorate from and {@code max} how much room + * there is. + */ + public abstract void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, + DecoratedBiome biome, int height, int max); + + /** {@link #decorate} for a decorator that looks at no neighbouring column. */ + public void decorate(int x, int z, int realX, int realZ, DecoratedBiome biome, int height, int max) { + decorate(x, z, realX, realX, realX, realZ, realZ, realZ, biome, height, max); + } + + protected RNG getRNG(int x, int z) { + long seed = DecoratorCore.partSeed(scene.seed(), part); + long modX = COLUMN_X_FACTOR ^ (part.ordinal() + X_PART_OFFSET); + long modZ = COLUMN_Z_FACTOR ^ (part.ordinal() + Z_PART_OFFSET); + return new RNG(x * modX + z * modZ + seed); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java b/module/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java new file mode 100644 index 000000000..61050f085 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java @@ -0,0 +1,81 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.decorator; + +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; + +public class IrisSeaFloorDecorator extends IrisEngineDecorator { + public IrisSeaFloorDecorator(DecorationScene scene) { + super(scene, DecorationPart.SEA_FLOOR); + } + + @Override + public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, + DecoratedBiome biome, int height, int max) { + RNG rng = getRNG(realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log()); + + if (decorator == null) { + return; + } + + var data = scene.blocks(); + if (!decorator.isStacking()) { + if (decorator.slopeBlocks(() -> scene.slopeAt(realX, realZ))) { + return; + } + if (height >= 0 && height < scene.worldHeight()) { + place(x, height, z, decorator.blockAt(realX, height, realZ)); + } + return; + } + + int stack = decorator.stackHeight(realX, realZ); + if (decorator.isScaleStack()) { + stack = (int) Math.ceil((double) (max - height) * ((double) stack / 100)); + } else { + stack = Math.min(stack, max - height); + } + + if (stack == 1) { + place(x, height, z, decorator.topBlockAt(realX, height, realZ)); + return; + } + + int engineHeight = scene.worldHeight(); + for (int i = 0; i < stack; i++) { + int h = height + i; + if (h > max || h > engineHeight) { + continue; + } + double threshold = ((double) i) / (stack - 1); + place(x, h, z, threshold >= decorator.topThreshold() + ? decorator.topBlockAt(realX, h, realZ) + : decorator.blockAt(realX, h, realZ)); + } + } + + /** A block the decorator has none of leaves the water as it is. */ + private void place(int x, int y, int z, BlockState block) { + if (block != null && y < scene.worldHeight()) { + scene.blocks().set(x, y, z, block); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java b/module/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java new file mode 100644 index 000000000..e5b1fd4e6 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java @@ -0,0 +1,88 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.decorator; + +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; + +public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { + public IrisSeaSurfaceDecorator(DecorationScene scene) { + super(scene, DecorationPart.SEA_SURFACE); + } + + @Override + public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, + DecoratedBiome biome, int height, int max) { + RNG rng = getRNG(realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log()); + + if (decorator == null) { + return; + } + + var data = scene.blocks(); + if (!decorator.isStacking()) { + int targetY = height + 1; + if (height >= 0 && targetY < scene.worldHeight() + && DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { + BlockState block = decorator.blockAt(realX, height, realZ); + if (block != null) { + data.set(x, targetY, z, block); + } + } + return; + } + + int stack = decorator.stackHeight(realX, realZ); + if (decorator.isScaleStack()) { + stack = (int) Math.ceil((double) (max - height) * ((double) stack / 100)); + } + + if (stack == 1) { + int targetY = height + 1; + if (targetY >= data.height() || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { + return; + } + + BlockState block = decorator.topBlockAt(realX, height, realZ); + if (block != null) { + data.set(x, targetY, z, block); + } + return; + } + + int engineHeight = scene.worldHeight(); + for (int i = 0; i < stack; i++) { + int h = height + i; + int targetY = h + 1; + if (h >= max || targetY >= engineHeight + || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { + break; + } + double threshold = ((double) i) / (stack - 1); + BlockState block = threshold >= decorator.topThreshold() + ? decorator.topBlockAt(realX, h, realZ) + : decorator.blockAt(realX, h, realZ); + if (block == null) { + break; + } + data.set(x, targetY, z, block); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java b/module/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java new file mode 100644 index 000000000..36218b994 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java @@ -0,0 +1,114 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.decorator; + +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; + +public class IrisShoreLineDecorator extends IrisEngineDecorator { + public IrisShoreLineDecorator(DecorationScene scene) { + super(scene, DecorationPart.SHORE_LINE); + } + + @Override + public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, + DecoratedBiome biome, int height, int max) { + if (height != scene.fluidHeight()) { + return; + } + + double complexFluidHeight = scene.fluidHeight(); + if (scene.roundedHeightAt(realX1, realZ) >= complexFluidHeight + && scene.roundedHeightAt(realX_1, realZ) >= complexFluidHeight + && scene.roundedHeightAt(realX, realZ1) >= complexFluidHeight + && scene.roundedHeightAt(realX, realZ_1) >= complexFluidHeight) { + return; + } + + RNG rng = getRNG(realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log()); + + if (decorator == null) { + return; + } + + if (decorator.slopeBlocks(() -> scene.slopeAt(realX, realZ))) { + return; + } + + var data = scene.blocks(); + BlockState support = data.get(x, height, z); + if (support == null || !scene.isSolid(support)) { + return; + } + + if (!decorator.isStacking()) { + int targetY = height + 1; + if (targetY >= data.height() + || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { + return; + } + BlockState block = decorator.blockAt(realX, height, realZ); + if (block != null && DecoratorCore.isValidShorelineSupport(scene, decorator, block, support)) { + data.set(x, targetY, z, block); + } + return; + } + + int stack = decorator.stackHeight(realX, realZ); + if (decorator.isScaleStack()) { + stack = (int) Math.ceil((double) (max - height) * ((double) stack / 100)); + } else { + stack = Math.min(max - height, stack); + } + + if (stack == 1) { + int targetY = height + 1; + if (targetY >= data.height() || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { + return; + } + + BlockState block = decorator.topBlockAt(realX, height, realZ); + if (block != null && DecoratorCore.isValidShorelineSupport(scene, decorator, block, support)) { + data.set(x, targetY, z, block); + } + return; + } + + for (int i = 0; i < stack; i++) { + int h = height + i; + int targetY = h + 1; + if (targetY >= data.height() + || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { + break; + } + double threshold = ((double) i) / (stack - 1); + BlockState block = threshold >= decorator.topThreshold() + ? decorator.topBlockAt(realX, h, realZ) + : decorator.blockAt(realX, h, realZ); + if (block == null) { + break; + } + if (i == 0 && !DecoratorCore.isValidShorelineSupport(scene, decorator, block, support)) { + break; + } + data.set(x, targetY, z, block); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java b/module/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java new file mode 100644 index 000000000..041a13731 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java @@ -0,0 +1,71 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.decorator; + +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.world.BiomeKind; + +public class IrisSurfaceDecorator extends IrisEngineDecorator { + public IrisSurfaceDecorator(DecorationScene scene) { + super(scene, DecorationPart.NONE); + } + + protected boolean isSlopeValid(ResolvedDecorator decorator, int realX, int realZ) { + return !decorator.slopeBlocks(() -> scene.slopeAt(realX, realZ)); + } + + @Override + public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, + DecoratedBiome biome, int height, int max) { + BiomeKind kind = biome.kind(); + int fluidHeight = scene.fluidHeight(); + if (kind == BiomeKind.SHORE && height < fluidHeight) { + return; + } + + boolean underwater = isUnderwater(kind, height, fluidHeight); + boolean caveSkipFluid = skipsFluid(kind); + RNG rng = getRNG(realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log()); + + if (decorator == null || !isSlopeValid(decorator, realX, realZ)) { + return; + } + + if (decorator.isStacking()) { + DecoratorCore.PlaceOpts opts = DecoratorCore.SCRATCH_OPTS.get(); + opts.reset(); + opts.underwater = underwater; + opts.fluidHeight = fluidHeight; + opts.caveSkipFluid = caveSkipFluid; + DecoratorCore.placeStackUp(decorator, scene, x, z, realX, realZ, height, max, opts); + return; + } + + DecoratorCore.placeSurfaceSingle(decorator, scene, x, z, realX, height, realZ, underwater, caveSkipFluid); + } + + static boolean isUnderwater(BiomeKind kind, int height, int fluidHeight) { + return height < fluidHeight && kind != BiomeKind.CAVE; + } + + static boolean skipsFluid(BiomeKind kind) { + return kind == BiomeKind.CAVE; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java b/module/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java new file mode 100644 index 000000000..1d8b330c3 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java @@ -0,0 +1,279 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.decorator; + +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.iris.builtin.decorant.Decorator; +import art.arcane.volmlib.util.cache.AtomicCache; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.PackResources; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.DoubleSupplier; + +/** + * One {@link Decorator} made ready for one world: its palettes resolved to blocks, and the noise that + * decides where it places, which block of the palette it picks and how tall it stacks, built when first asked for. What + * the decorator describes stays in the settings; everything that needs the platform, the pack or the world seed is here. + * + *

The noise seeds are the decorator's own seed plus the same offsets Iris's decorator always used, so a decorator + * noise is a pure function of its seed. + */ +final class ResolvedDecorator { + private final Decorator settings; + private final long seed; + private final NoiseFactory noise; + private final List blocks; + private final List topBlocks; + private final BlockState[] blockArray; + private final BlockState[] topBlockArray; + private final BlockState forceBlock; + private final BlockState[] whitelist; + private final BlockState[] blacklist; + private final AtomicCache chanceNoise = new AtomicCache<>(); + private final AtomicCache varianceNoise = new AtomicCache<>(); + private final AtomicCache heightNoise = new AtomicCache<>(); + private final ModuleLog log; + private final String biomeKey; + + /** + * @param blocks the palette as the platform's blocks, each repeated by its weight + * @param topBlocks the top palette the same way + * @param forceBlock the block it forces onto the surface, or null + * @param whitelist the blocks it may only be placed onto; ignored unless the decorator has a whitelist + * @param blacklist the blocks it is never placed onto; ignored unless the decorator has a blacklist + * @param log the log of the module that decorates + * @param biomeKey the key of the biome that declares the decorator, which names it in the log + */ + ResolvedDecorator(Decorator settings, long seed, NoiseFactory noise, List blocks, List topBlocks, + BlockState forceBlock, List whitelist, List blacklist, + ModuleLog log, String biomeKey) { + this.settings = settings; + this.seed = seed; + this.noise = noise; + this.blocks = List.copyOf(blocks); + this.topBlocks = List.copyOf(topBlocks); + this.blockArray = blocks.toArray(new BlockState[0]); + this.topBlockArray = topBlocks.toArray(new BlockState[0]); + this.forceBlock = forceBlock; + this.whitelist = whitelist.toArray(new BlockState[0]); + this.blacklist = blacklist.toArray(new BlockState[0]); + this.log = log; + this.biomeKey = biomeKey; + } + + /** {@code settings} ready for a world with {@code resources}: its blocks resolved through the pack, its noise seeded from {@code seed}. */ + static ResolvedDecorator of(Decorator settings, PackResources resources, long seed, ModuleLog log, String biomeKey) { + BlockRegistry registry = resources.blocks(); + BlockState forced = settings.forceBlock().map(registry::resolve).orElse(null); + return new ResolvedDecorator(settings, seed, resources.noise(), weighted(registry, settings.palette()), + weighted(registry, settings.topPalette()), forced, each(registry, settings.whitelist()), each(registry, settings.blacklist()), log, + biomeKey); + } + + private static List weighted(BlockRegistry registry, List palette) { + List weighted = new ArrayList<>(); + for (BlockSpec spec : palette) { + BlockState state = registry.resolve(spec); + for (int n = 0; n < spec.weight(); n++) { + weighted.add(state); + } + } + return weighted; + } + + private static List each(BlockRegistry registry, List palette) { + return palette.stream().map(registry::resolve).toList(); + } + + Decorator settings() { + return settings; + } + + /** The seed the decorator's noise is built from. */ + long seed() { + return seed; + } + + DecorationPart part() { + return settings.partOf(); + } + + boolean isStacking() { + return settings.isStacking(); + } + + boolean isForcePlace() { + return settings.forcePlace(); + } + + boolean isScaleStack() { + return settings.scaleStack(); + } + + int absoluteMaxStack() { + return settings.absoluteMaxStack(); + } + + double topThreshold() { + return settings.topThreshold(); + } + + /** The block it forces onto the surface instead of the one found there, or null. */ + BlockState forceBlock() { + return forceBlock; + } + + /** Whether the terrain's slope keeps the decorator off; the slope is only worked out when the decorator limits it. */ + boolean slopeBlocks(DoubleSupplier slope) { + if (settings.forcePlace() || settings.slopeCondition().isDefault()) { + return false; + } + return !settings.slopeCondition().isValid(slope.getAsDouble()); + } + + /** Whether the white and black lists keep the decorator off {@code surface}. */ + boolean rejectsSurface(BlockState surface) { + if (settings.hasWhitelist() && !matches(whitelist, surface)) { + return true; + } + return settings.hasBlacklist() && matches(blacklist, surface); + } + + private static boolean matches(BlockState[] palette, BlockState surface) { + for (BlockState state : palette) { + if (state.equals(surface)) { + return true; + } + } + return false; + } + + /** How many blocks the decorator stacks at the column: the minimum, or a height between the limits drawn from its height noise. */ + int stackHeight(double x, double z) { + if (settings.stackMin() == settings.stackMax()) { + return settings.stackMin(); + } + + double zoom = settings.heightVariance().zoom(); + return fit(settings.stackMin(), settings.stackMax(), heightNoise().sample(x / zoom, z / zoom)); + } + + /** Whether the chance noise lets the decorator place at the column. */ + boolean passesChanceGate(double x, double z) { + if (blocks.isEmpty()) { + return false; + } + return chanceNoisePlacesAt(x, z); + } + + /** + * Whether the style noise stays under the chance at the column. A style without a seed divides by its zoom here on top + * of its own scale; a seeded one is read in plain blocks. + */ + private boolean chanceNoisePlacesAt(double x, double z) { + double blocksPerSample = settings.style().isSeeded() ? 1 : settings.style().zoom(); + return chanceNoise().sample(x / blocksPerSample, z / blocksPerSample) <= settings.chance(); + } + + /** The block of the palette at the position, for decorations that fill a column block by block; null when the palette has no block. */ + BlockState blockAt(double x, double y, double z) { + if (blocks.isEmpty()) { + log.warnOnce("decorator-empty:" + biomeKey, "Empty Block Data for " + biomeKey); + return null; + } + + if (blocks.size() == 1) { + return blocks.get(0); + } + + return blocks.get(fit(0, blocks.size() - 1, varianceNoise().sample(z, y, x))); // X and Z are switched + } + + /** The top palette's block at the position, or the palette's when there is no top palette; null where the chance noise declines. */ + BlockState topBlockAt(double x, double y, double z) { + if (topBlocks.isEmpty()) { + return blockAt(x, y, z); + } + + if (!chanceNoisePlacesAt(x, z)) { + return null; + } + + if (blocks.size() == 1) { + return topBlocks.get(0); + } + + return topBlocks.get(fit(0, topBlocks.size() - 1, varianceNoise().sample(z, y, x))); + } + + /** The palette's block for the column, or null when the palette has no block. */ + BlockState pickBlock(double x, double z) { + return pick(blockArray, x, z); + } + + /** The top palette's block for the column; the palette's when there is no top palette. */ + BlockState pickTopBlock(double x, double z) { + if (topBlockArray.length == 0) { + return pickBlock(x, z); + } + return pick(topBlockArray, x, z); + } + + private BlockState pick(BlockState[] palette, double x, double z) { + if (palette.length == 0) { + return null; + } + if (palette.length == 1) { + return palette[0]; + } + return palette[Math.abs(fit(0, palette.length - 1, varianceNoise().sample(z, x)))]; + } + + /** Builds the noise now instead of when first asked for. */ + void warm() { + heightNoise(); + chanceNoise(); + varianceNoise(); + } + + private NoiseSampler heightNoise() { + return heightNoise.aquireOrThrow(() -> noise.sampler(settings.heightVariance(), + seed + blocks.size() + settings.stackMax() + settings.stackMin())); + } + + private NoiseSampler chanceNoise() { + return chanceNoise.aquireOrThrow(() -> noise.sampler(settings.style(), seed + blocks.size())); + } + + private NoiseSampler varianceNoise() { + return varianceNoise.aquireOrThrow(() -> noise.sampler(settings.variance(), seed + blocks.size())); + } + + /** The whole number between {@code min} and {@code max} that {@code fraction}, from 0 to 1, is the way along. */ + private static int fit(int min, int max, double fraction) { + return (int) Math.round(min + (fraction * (max - min))); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/StructurePlacementGrid.java b/module/src/main/java/art/arcane/iris/engine/framework/StructurePlacementGrid.java new file mode 100644 index 000000000..bc477f26b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/StructurePlacementGrid.java @@ -0,0 +1,281 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework; + +import art.arcane.iris.builtin.structure.NativeStructureSource; +import art.arcane.iris.builtin.structure.StructureAnchorMode; +import art.arcane.iris.builtin.structure.StructurePlacement; +import art.arcane.volmlib.util.math.RNG; + +import java.util.Locale; +import java.util.Set; +import java.util.TreeSet; + +public final class StructurePlacementGrid { + private static final long DENSITY_SIGNATURE = 0x6A09E667F3BCC909L; + + private StructurePlacementGrid() { + } + + public static boolean startsInChunk(StructurePlacement placement, int cx, int cz, long seed) { + return switch (placement.distribution()) { + case RANDOM_SPREAD -> randomSpreadStart(cx, cz, placement.spacing(), placement.separation(), + placementSalt(placement), seed); + case DENSITY -> densityStart(placement, cx, cz, seed); + case CONCENTRIC_RINGS -> concentricRingsStart(cx, cz, placement, seed); + }; + } + + public static RNG placementRng(StructurePlacement placement, int cx, int cz, long seed) { + return new RNG(placementSeed(placement, cx, cz, seed)); + } + + public static boolean randomSpreadStart(int cx, int cz, int spacing, int separation, int salt, long seed) { + int sp = Math.max(1, spacing); + int cellX = Math.floorDiv(cx, sp); + int cellZ = Math.floorDiv(cz, sp); + int[] start = randomSpreadCellChunk(cellX, cellZ, spacing, separation, salt, seed); + return start[0] == cx && start[1] == cz; + } + + /** + * Returns the single {chunkX, chunkZ} that a RANDOM_SPREAD placement occupies within the given + * grid cell. This is the inverse of {@link #randomSpreadStart} and uses the identical formula, so + * a locator can jump straight to the one candidate per cell instead of testing every chunk. + */ + public static int[] randomSpreadCellChunk(int cellX, int cellZ, int spacing, int separation, int salt, long seed) { + int sp = Math.max(1, spacing); + int sep = Math.max(0, Math.min(separation, sp - 1)); + RNG r = new RNG(mix(seed, cellX, cellZ, salt)); + int range = Math.max(1, sp - sep); + int startCx = cellX * sp + r.nextInt(range); + int startCz = cellZ * sp + r.nextInt(range); + return new int[]{startCx, startCz}; + } + + public static int[] concentricRingChunk(StructurePlacement placement, int placementIndex, long seed) { + int count = Math.max(1, placement.ringCount()); + if (placementIndex < 0 || placementIndex >= count) { + return null; + } + int distance = Math.max(1, placement.ringDistance()); + int spread = Math.max(1, placement.ringSpread()); + int ring = Math.floorDiv(placementIndex, spread) + 1; + int firstIndex = (ring - 1) * spread; + int slots = Math.min(spread, count - firstIndex); + int slot = placementIndex - firstIndex; + double slotAngle = (2.0 * Math.PI) / slots; + double offset = unitDouble(mix(seed, ring, count, placementSalt(placement))) * slotAngle; + double angle = offset + (slot * slotAngle); + long configuredRadius = (long) ring * distance; + if (configuredRadius > Integer.MAX_VALUE) { + return null; + } + int radius = (int) configuredRadius; + return new int[]{ + (int) Math.round(Math.cos(angle) * radius), + (int) Math.round(Math.sin(angle) * radius) + }; + } + + private static boolean concentricRingsStart(int cx, int cz, StructurePlacement placement, long seed) { + if (cx == 0 && cz == 0) { + return false; + } + int distance = Math.max(1, placement.ringDistance()); + int count = Math.max(1, placement.ringCount()); + int spread = Math.max(1, placement.ringSpread()); + double dist = Math.sqrt((double) cx * cx + (double) cz * cz); + int estimatedRing = (int) Math.round(dist / distance); + int ringCount = Math.ceilDiv(count, spread); + int firstRing = Math.max(1, estimatedRing - 1); + int lastRing = Math.min(ringCount, estimatedRing + 1); + for (int ring = firstRing; ring <= lastRing; ring++) { + int firstIndex = (ring - 1) * spread; + int slots = Math.min(spread, count - firstIndex); + if (slots <= 0) { + continue; + } + double slotAngle = (2.0 * Math.PI) / slots; + double offset = unitDouble(mix(seed, ring, count, placementSalt(placement))) * slotAngle; + double slotPosition = (Math.atan2(cz, cx) - offset) / slotAngle; + int nearestSlot = Math.floorMod((int) Math.round(slotPosition), slots); + for (int delta = -1; delta <= 1; delta++) { + int slot = Math.floorMod(nearestSlot + delta, slots); + int[] candidate = concentricRingChunk(placement, firstIndex + slot, seed); + if (candidate != null && candidate[0] == cx && candidate[1] == cz) { + return true; + } + } + } + return false; + } + + private static boolean densityStart(StructurePlacement placement, int cx, int cz, long seed) { + double density = placement.density(); + if (density <= 0.0) { + return false; + } + if (density >= 1.0) { + return true; + } + RNG rng = new RNG(placementSeed(placement, cx, cz, seed) ^ DENSITY_SIGNATURE); + return rng.chance(density); + } + + public static long placementIdentity(StructurePlacement placement) { + long signature = 1469598103934665603L; + signature = appendLong(signature, placement.distribution().ordinal()); + signature = appendLong(signature, placement.salt()); + String placementId = placement.placementId(); + if (placementId != null && !placementId.isBlank()) { + signature = appendLong(signature, 1L); + signature = appendSignature(signature, placementId.trim()); + } else { + signature = appendLong(signature, 0L); + signature = appendLong(signature, placement.spacing()); + signature = appendLong(signature, placement.separation()); + signature = appendLong(signature, Double.doubleToLongBits(placement.density())); + signature = appendLong(signature, placement.ringCount()); + signature = appendLong(signature, placement.ringDistance()); + signature = appendLong(signature, placement.ringSpread()); + signature = appendLong(signature, placement.minHeight()); + signature = appendLong(signature, placement.maxHeight()); + signature = appendLong(signature, placement.underground() ? 1L : 0L); + signature = appendLong(signature, placement.underwater() ? 1L : 0L); + signature = appendSources(signature, placement); + signature = appendAnchor(signature, placement); + } + return signature; + } + + private static long placementSeed(StructurePlacement placement, int cx, int cz, long seed) { + long signature = placementIdentity(placement); + int identitySalt = (int) (signature ^ (signature >>> 32)); + return mix(seed ^ signature, cx, cz, placementSalt(placement) ^ identitySalt); + } + + private static long appendSignature(long signature, String value) { + long result = appendLong(signature, value.length()); + for (int index = 0; index < value.length(); index++) { + result = (result ^ value.charAt(index)) * 1099511628211L; + } + return result; + } + + private static long appendLong(long signature, long value) { + long result = signature; + long remaining = value; + for (int index = 0; index < Long.BYTES; index++) { + result = (result ^ (remaining & 0xffL)) * 1099511628211L; + remaining >>>= Byte.SIZE; + } + return result; + } + + private static long appendSources(long signature, StructurePlacement placement) { + long result = signature; + if (placement.hasIrisStructures()) { + result = appendLong(result, 1L); + result = appendLong(result, placement.structures().size()); + for (String key : placement.structures()) { + result = appendSignature(result, key == null ? "" : key); + } + return result; + } + result = appendLong(result, 2L); + result = appendLong(result, placement.nativeStructures().size()); + for (NativeStructureSource source : placement.nativeStructures()) { + if (source == null) { + result = appendSignature(result, ""); + result = appendLong(result, 0L); + continue; + } + result = appendSignature(result, + source.structure() == null ? "" : source.structure()); + result = appendLong(result, source.weight()); + } + return result; + } + + private static long appendAnchor(long signature, StructurePlacement placement) { + StructureAnchorMode anchor = placement.anchor(); + if (anchor == StructureAnchorMode.LEGACY) { + return signature; + } + long result = appendLong(signature, 0x4A49475341574C41L); + result = appendLong(result, anchor.ordinal()); + if (!anchor.isCave()) { + return result; + } + result = appendLong(result, placement.caveAnchorAttempts()); + result = appendLong(result, placement.caveAnchorScanStep()); + result = appendLong(result, placement.caveMinimumClearance()); + Set biomes = new TreeSet<>(); + for (String biome : placement.caveBiomes()) { + if (biome != null && !biome.isBlank()) { + biomes.add(biome.trim().toLowerCase(Locale.ROOT)); + } + } + result = appendLong(result, biomes.size()); + for (String biome : biomes) { + result = appendSignature(result, biome); + } + return result; + } + + static int placementSalt(StructurePlacement placement) { + String placementId = placement.placementId(); + long identity; + if (placementId != null && !placementId.isBlank()) { + identity = appendSignature(1469598103934665603L, placementId.trim()); + } else { + identity = 1469598103934665603L; + identity = appendLong(identity, placement.distribution().ordinal()); + identity = appendLong(identity, placement.spacing()); + identity = appendLong(identity, placement.separation()); + identity = appendLong(identity, Double.doubleToLongBits(placement.density())); + identity = appendLong(identity, placement.ringCount()); + identity = appendLong(identity, placement.ringDistance()); + identity = appendLong(identity, placement.ringSpread()); + identity = appendLong(identity, placement.minHeight()); + identity = appendLong(identity, placement.maxHeight()); + identity = appendLong(identity, placement.underground() ? 1L : 0L); + identity = appendLong(identity, placement.underwater() ? 1L : 0L); + identity = appendSources(identity, placement); + identity = appendAnchor(identity, placement); + } + return placement.salt() ^ (int) (identity ^ (identity >>> 32)); + } + + private static double unitDouble(long value) { + return (value >>> 11) * 0x1.0p-53; + } + + public static long mix(long seed, int a, int b, int salt) { + long h = seed; + h = h * 6364136223846793005L + (a * 341873128712L); + h = h * 6364136223846793005L + (b * 132897987541L); + h = h * 6364136223846793005L + salt; + h ^= (h >>> 33); + h *= 0xff51afd7ed558ccdL; + h ^= (h >>> 33); + return h; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/StructureVerticalBounds.java b/module/src/main/java/art/arcane/iris/engine/framework/StructureVerticalBounds.java new file mode 100644 index 000000000..05e67668c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/StructureVerticalBounds.java @@ -0,0 +1,51 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework; + +public final class StructureVerticalBounds { + private StructureVerticalBounds() { + } + + public static int clampOffset( + int structureMinY, + int structureMaxY, + int requestedOffset, + int worldMinY, + int worldMaxYExclusive + ) { + if (structureMaxY < structureMinY) { + throw new IllegalArgumentException("Structure maximum Y cannot be below its minimum Y"); + } + if (worldMaxYExclusive <= worldMinY) { + throw new IllegalArgumentException("World maximum Y must be above its minimum Y"); + } + + long structureHeight = (long) structureMaxY - structureMinY + 1L; + long worldHeight = (long) worldMaxYExclusive - worldMinY; + if (structureHeight > worldHeight) { + throw new IllegalArgumentException("Structure height " + structureHeight + + " exceeds writable world height " + worldHeight); + } + + long minimumOffset = (long) worldMinY - structureMinY; + long maximumOffset = (long) worldMaxYExclusive - 1L - structureMaxY; + long clamped = Math.max(minimumOffset, Math.min(maximumOffset, (long) requestedOffset)); + return Math.toIntExact(clamped); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java new file mode 100644 index 000000000..9f323742c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java @@ -0,0 +1,113 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.structure; + +import art.arcane.iris.builtin.RegistryKeyFamily; +import art.arcane.iris.builtin.structure.StructureAdjustment; +import art.arcane.iris.builtin.structure.StructureSetFrequency; +import art.arcane.iris.builtin.structure.StructureSettings; +import com.volmit.config.PackSettings; +import com.volmit.resource.ResourceId; +import com.volmit.vanilla.VanillaStructureSetup; + +import java.util.List; +import java.util.Locale; +import java.util.Optional; + +/** + * What a dimension's {@link StructureSettings} say about the platform's own structures: which ones it disables, how + * the starts of the others are adjusted, and how the platform sets them up. Keys match ignoring case and surrounding + * space; a family pattern also matches the keys it starts at a namespace, slash or underscore boundary + * ({@link RegistryKeyFamily}). + */ +public final class ImportedStructures { + private final StructureSettings settings; + + public ImportedStructures(StructureSettings settings) { + this.settings = settings; + } + + /** The settings the dimension of {@code settings} declares, or the defaults when it declares none. */ + public static ImportedStructures of(PackSettings settings) { + return new ImportedStructures(settings.declared(StructureSettings.class).dimension().orElseGet(StructureSettings::new)); + } + + /** Whether the dimension disables the platform structure {@code key}, by family or by its exact key. */ + public boolean disables(String key) { + String normalizedKey = normalize(key); + if (normalizedKey.isEmpty()) { + return false; + } + return settings.disabled().stream().anyMatch(pattern -> RegistryKeyFamily.matches(pattern, key)) + || settings.disabledExact().stream().map(ImportedStructures::normalize) + .anyMatch(exact -> !exact.isEmpty() && exact.equals(normalizedKey)); + } + + /** + * How the platform's own starts of {@code key} are adjusted: the underground shift for underground steps, then every + * matching adjustment in the order the pack lists them. + */ + public NativeStructureFit adjustment(String key, boolean underground) { + NativeStructureFit adjustment = NativeStructureFit.NONE.shifted(underground ? settings.undergroundYShift() : 0); + for (StructureAdjustment entry : settings.adjustments()) { + if (entry != null && matchesAny(entry.match(), key)) { + adjustment = adjustment.then(asAdjustment(entry)); + } + } + return adjustment; + } + + /** + * The structure set frequencies the dimension changes and whether it keeps data packs off the platform's definitions. + * An override naming no namespaced key can match no registered set and is left out. + */ + public VanillaStructureSetup setup() { + VanillaStructureSetup setup = settings.datapackOverrides() + ? VanillaStructureSetup.UNCHANGED + : VanillaStructureSetup.UNCHANGED.protectingVanillaDefinitions(); + for (StructureSetFrequency override : settings.frequencyOverrides()) { + Optional structureSet = override == null ? Optional.empty() : structureSetId(override.structureSet()); + if (structureSet.isPresent()) { + setup = setup.withFrequency(structureSet.get(), override.multiplier()); + } + } + return setup; + } + + private static Optional structureSetId(String key) { + try { + return Optional.of(ResourceId.parse(normalize(key))); + } catch (IllegalArgumentException notAnId) { + return Optional.empty(); + } + } + + private static boolean matchesAny(List patterns, String key) { + return patterns.stream().anyMatch(pattern -> RegistryKeyFamily.matches(pattern, key)); + } + + private static NativeStructureFit asAdjustment(StructureAdjustment entry) { + return new NativeStructureFit(entry.yShift(), entry.yBand().orElse(null), entry.preserveSourceY(), + entry.stilt().orElse(null), entry.terrain().orElse(null)); + } + + private static String normalize(String key) { + return key == null ? "" : key.trim().toLowerCase(Locale.ROOT); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/NativeStructureFit.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/NativeStructureFit.java new file mode 100644 index 000000000..7f46b949d --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/NativeStructureFit.java @@ -0,0 +1,88 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.structure; + +import art.arcane.iris.builtin.structure.StructureStilts; +import art.arcane.iris.builtin.structure.StructureTerrain; +import art.arcane.iris.builtin.structure.StructureYBand; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.volmit.vanilla.StartMemo; + +/** + * How {@code iris:structure} places and fits one platform structure, or one start: how far it moves the platform's own + * starts and into which band of world heights, whether they keep the platform's height, the foundation columns built + * under their pieces and how they meet the terrain. A start the module places itself carries its fit as a memo, one + * JSON object of its terrain and stilts, which the host keeps with the start, so its later chunks use the fit it began with. + * + * @param yBand null for no band + * @param stilts null for no foundation columns + * @param terrain null for the structure's own terrain adaptation (SOURCE) + */ +public record NativeStructureFit(int yShift, StructureYBand yBand, boolean keepsSourceY, StructureStilts stilts, + StructureTerrain terrain) { + /** The platform's starts as the platform makes them. */ + public static final NativeStructureFit NONE = new NativeStructureFit(0, null, false, null, null); + + private static final Gson MEMO_JSON = new Gson(); + private static final String MEMO_TERRAIN = "terrain"; + private static final String MEMO_STILTS = "stilts"; + + /** The fit a start's memo records: its terrain and stilts, with no vertical adjustment. */ + public static NativeStructureFit of(StartMemo memo) { + JsonObject text = MEMO_JSON.fromJson(memo.text(), JsonObject.class); + if (text == null || !text.has(MEMO_TERRAIN)) { + throw new IllegalStateException("A start's memo has no terrain fit: " + memo); + } + StructureTerrain terrain = MEMO_JSON.fromJson(text.get(MEMO_TERRAIN), StructureTerrain.class); + StructureStilts stilts = text.has(MEMO_STILTS) ? MEMO_JSON.fromJson(text.get(MEMO_STILTS), StructureStilts.class) : null; + return new NativeStructureFit(0, null, false, stilts, terrain); + } + + /** The memo of a start placed with this fit's terrain and stilts: one JSON object holding both. */ + public StartMemo memo() { + JsonObject text = new JsonObject(); + text.add(MEMO_TERRAIN, MEMO_JSON.toJsonTree(resolvedTerrain())); + if (stilts != null) { + text.add(MEMO_STILTS, MEMO_JSON.toJsonTree(stilts)); + } + return new StartMemo(MEMO_JSON.toJson(text)); + } + + /** The terrain fitting; the structure's own adaptation (SOURCE) when none is set. */ + public StructureTerrain resolvedTerrain() { + return terrain == null ? new StructureTerrain() : terrain; + } + + public NativeStructureFit shifted(int blocks) { + return new NativeStructureFit(Math.addExact(yShift, blocks), yBand, keepsSourceY, stilts, terrain); + } + + /** + * Both fits, {@code later} after this one: shifts add up, keeping the platform's height sticks, and a band, stilts + * or terrain {@code later} states replaces this one's. + */ + public NativeStructureFit then(NativeStructureFit later) { + return new NativeStructureFit(Math.addExact(yShift, later.yShift), + later.yBand == null ? yBand : later.yBand, + keepsSourceY || later.keepsSourceY, + later.stilts == null ? stilts : later.stilts, + later.terrain == null ? terrain : later.terrain); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyStatus.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyStatus.java new file mode 100644 index 000000000..c8642ab59 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyStatus.java @@ -0,0 +1,17 @@ +package art.arcane.iris.engine.framework.structure; + +public enum StructureAssemblyStatus { + COMPLETE, + INTENTIONAL_EMPTY, + FAILED_UNCAPPED, + FAILED_RULES, + HARD_CAP; + + public boolean isComplete() { + return this == COMPLETE || this == INTENTIONAL_EMPTY; + } + + public boolean isFailure() { + return !isComplete(); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphAssemblySample.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphAssemblySample.java new file mode 100644 index 000000000..b045843f6 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphAssemblySample.java @@ -0,0 +1,30 @@ +package art.arcane.iris.engine.framework.structure; + +import java.util.List; +import java.util.Objects; + +public record StructureGraphAssemblySample(long seed, Outcome outcome) { + public record Outcome( + List pieceKeys, + StructureAssemblyStatus status, + String detail + ) { + public Outcome { + pieceKeys = List.copyOf(Objects.requireNonNull(pieceKeys)); + status = Objects.requireNonNull(status); + detail = Objects.requireNonNull(detail); + } + + public boolean pieceCapReached() { + return status == StructureAssemblyStatus.HARD_CAP; + } + + public boolean intentionalEmpty() { + return status == StructureAssemblyStatus.INTENTIONAL_EMPTY; + } + + public boolean isComplete() { + return status.isComplete(); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphDiagnostic.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphDiagnostic.java new file mode 100644 index 000000000..e6fc5a636 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphDiagnostic.java @@ -0,0 +1,67 @@ +package art.arcane.iris.engine.framework.structure; + +import java.util.Objects; + +public record StructureGraphDiagnostic(Code code, String message) { + public StructureGraphDiagnostic { + Objects.requireNonNull(code); + Objects.requireNonNull(message); + } + + public Severity severity() { + return code.severity(); + } + + public enum Severity { + ERROR, + WARNING + } + + public enum Code { + MISSING_START_POOL(Severity.ERROR), + EMPTY_START_POOL(Severity.ERROR), + MISSING_POOL(Severity.ERROR), + INVALID_MAX_DEPTH(Severity.ERROR), + INVALID_MAX_SIZE(Severity.ERROR), + INVALID_POOL_ENTRY(Severity.ERROR), + INVALID_WEIGHT(Severity.ERROR), + INVALID_CHANCE(Severity.ERROR), + INVALID_THEME(Severity.ERROR), + INVALID_PIECE_RULE(Severity.ERROR), + UNSATISFIABLE_PIECE_RULE(Severity.ERROR), + MISSING_REQUIRED_FALLBACK(Severity.ERROR), + NO_REQUIRED_TERMINAL(Severity.ERROR), + NON_PORTABLE_METADATA(Severity.ERROR), + MISSING_PIECE(Severity.ERROR), + MISSING_OBJECT(Severity.ERROR), + INVALID_OBJECT_BOUNDS(Severity.ERROR), + INVALID_CONNECTOR(Severity.ERROR), + INVALID_CONNECTOR_METADATA(Severity.ERROR), + INVALID_CONNECTOR_POSITION(Severity.ERROR), + INVALID_CONNECTOR_DIRECTION(Severity.ERROR), + INVALID_PLANAR_CELL_SIZE(Severity.ERROR), + INVALID_PLANAR_WORKCELL(Severity.ERROR), + INVALID_PLANAR_OBJECT_SIZE(Severity.ERROR), + INVALID_PLANAR_CONNECTOR(Severity.ERROR), + NON_PORTABLE_CONNECTOR(Severity.ERROR), + MISSING_CONNECTOR_POOL(Severity.ERROR), + FALLBACK_CYCLE(Severity.ERROR), + NO_ENABLED_START_PIECE(Severity.ERROR), + NO_VIABLE_START_PIECE(Severity.WARNING), + NO_COMPATIBLE_CONNECTOR(Severity.WARNING), + UNREACHABLE_POOL(Severity.WARNING), + UNREACHABLE_PIECE(Severity.WARNING), + ASSEMBLY_RUNTIME_FAILURE(Severity.ERROR), + ASSEMBLY_PIECE_CAP_REACHED(Severity.WARNING); + + private final Severity severity; + + Code(Severity severity) { + this.severity = severity; + } + + public Severity severity() { + return severity; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidationException.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidationException.java new file mode 100644 index 000000000..fc2b25643 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidationException.java @@ -0,0 +1,11 @@ +package art.arcane.iris.engine.framework.structure; + +public final class StructureGraphValidationException extends IllegalArgumentException { + public StructureGraphValidationException(String message) { + super(message); + } + + public StructureGraphValidationException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java new file mode 100644 index 000000000..219c84836 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java @@ -0,0 +1,92 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.structure; + +import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; + +import java.util.List; + +/** + * The resource kinds of {@code iris:structure}, which keep the folders and files Iris packs have always used, and + * lookups by pack key for code that names structures, pools and pieces by key. Every lookup goes through the pack's + * {@link PackResources}, so it sees the pack's current snapshot: a hotload, or a tool that rewrote the files and asked + * for a new snapshot, reads them again. + *

+ * Lookups answer null for a blank key, a key the pack has no file for, and a file that fails to load, which was + * reported when it was read. + */ +public final class StructureResources { + /** Jigsaw structures, in {@code structures/}. */ + public static final ResourceKind STRUCTURES = ResourceKind.of("iris:structure/structure", "structures", IrisStructure.class); + /** Jigsaw pools a structure starts from and connectors lead to, in {@code jigsaw-pools/}. */ + public static final ResourceKind POOLS = ResourceKind.of("iris:structure/pool", "jigsaw-pools", IrisJigsawPool.class); + /** Jigsaw pieces pools hold, each an object with connectors, in {@code jigsaw-pieces/}. */ + public static final ResourceKind PIECES = ResourceKind.of("iris:structure/piece", "jigsaw-pieces", IrisJigsawPiece.class); + + private StructureResources() { + } + + /** Every resource kind of the structure model. */ + public static List> kinds() { + return List.of(STRUCTURES, POOLS, PIECES); + } + + public static IrisStructure structure(PackResources pack, String key) { + return find(pack, STRUCTURES, key); + } + + public static IrisJigsawPool pool(PackResources pack, String key) { + return find(pack, POOLS, key); + } + + public static IrisJigsawPiece piece(PackResources pack, String key) { + return find(pack, PIECES, key); + } + + /** The key of every structure of the pack snapshot {@code pack}, in key order. */ + public static List structureKeys(PackResources pack) { + return keys(pack, STRUCTURES); + } + + /** The key of every jigsaw piece of the pack snapshot {@code pack}, in key order. */ + public static List pieceKeys(PackResources pack) { + return keys(pack, PIECES); + } + + private static T find(PackResources pack, ResourceKind kind, String key) { + if (key == null || key.isBlank()) { + return null; + } + try { + return pack.find(kind, pack.idOf(key)).orElse(null); + } catch (IllegalStateException failedToLoad) { + return null; + } + } + + /** A key's id has the key as its path, so the path names the resource again wherever a key is expected. */ + private static List keys(PackResources pack, ResourceKind kind) { + return pack.ids(kind).stream().map(ResourceId::path).toList(); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/Box.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/Box.java new file mode 100644 index 000000000..201cfaf0f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/Box.java @@ -0,0 +1,75 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.structure.fit; + +import com.volmit.geometry.BlockBox; + +/** A box of world blocks, every bound inclusive and Y in world heights, the way the platform's structures measure. */ +record Box(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { + /** {@code box}, an API box above the dimension's bottom with exclusive maxima, in world heights. */ + static Box of(BlockBox box, int bottomY) { + return new Box(box.minX(), box.minY() + bottomY, box.minZ(), + box.maxX() - 1, box.maxY() - 1 + bottomY, box.maxZ() - 1); + } + + /** This box as an API box above the dimension's bottom. */ + BlockBox toApi(int bottomY) { + return new BlockBox(minX, minY - bottomY, minZ, maxX + 1, maxY + 1 - bottomY, maxZ + 1); + } + + int xSpan() { + return maxX - minX + 1; + } + + int ySpan() { + return maxY - minY + 1; + } + + int zSpan() { + return maxZ - minZ + 1; + } + + boolean contains(int x, int y, int z) { + return x >= minX && x <= maxX && y >= minY && y <= maxY && z >= minZ && z <= maxZ; + } + + boolean intersects(Box other) { + return maxX >= other.minX && minX <= other.maxX && maxY >= other.minY && minY <= other.maxY + && maxZ >= other.minZ && minZ <= other.maxZ; + } + + boolean intersectsHorizontally(Box other) { + return maxX >= other.minX && minX <= other.maxX && maxZ >= other.minZ && minZ <= other.maxZ; + } + + /** This box grown by {@code blocks} sideways, keeping its heights. */ + Box widened(int blocks) { + return new Box(minX - blocks, minY, minZ - blocks, maxX + blocks, maxY, maxZ + blocks); + } + + Box encapsulating(Box other) { + return new Box(Math.min(minX, other.minX), Math.min(minY, other.minY), Math.min(minZ, other.minZ), + Math.max(maxX, other.maxX), Math.max(maxY, other.maxY), Math.max(maxZ, other.maxZ)); + } + + /** The column index of a block of this box's columns, rows along X. */ + int columnIndex(int x, int z) { + return (z - minZ) * xSpan() + x - minX; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitBlocks.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitBlocks.java new file mode 100644 index 000000000..00dd3214c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitBlocks.java @@ -0,0 +1,112 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.structure.fit; + +import com.volmit.geometry.BlockFace; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.resource.ResourceId; +import com.volmit.world.BlockAccess; + +/** + * The chunk's live blocks in world heights, and the block questions the structure fit asks. The fit's rules were + * written in world heights (deepslate below 0, bands of world Y, noise sampled at world heights), so it keeps them and + * converts here. + */ +final class FitBlocks { + static final BlockState AIR = new BlockState("minecraft:air"); + static final BlockState STONE = new BlockState("minecraft:stone"); + static final BlockState COBBLESTONE = new BlockState("minecraft:cobblestone"); + private static final ResourceId STRUCTURE_VOID = ResourceId.parse("minecraft:structure_void"); + private static final ResourceId JIGSAW = ResourceId.parse("minecraft:jigsaw"); + private static final ResourceId LOGS_TAG = ResourceId.parse("minecraft:logs"); + private static final ResourceId LEAVES_TAG = ResourceId.parse("minecraft:leaves"); + + private final BlockAccess access; + private final int bottomY; + + FitBlocks(BlockAccess access, int bottomY) { + this.access = access; + this.bottomY = bottomY; + } + + int bottomY() { + return bottomY; + } + + BlockState get(int x, int y, int z) { + return access.get(x, y - bottomY, z); + } + + void set(int x, int y, int z, BlockState state) { + access.set(x, y - bottomY, z, state); + } + + boolean isAir(BlockState state) { + return access.is(state, BlockTrait.AIR); + } + + boolean isSolid(BlockState state) { + return access.is(state, BlockTrait.SOLID); + } + + boolean holdsFluid(BlockState state) { + return access.is(state, BlockTrait.FLUID); + } + + /** Logs, wood, stems, hyphae and leaves: the blocks of trees the fit never treats as terrain. */ + boolean isTree(BlockState state) { + return access.is(state, BlockTrait.LOG) || access.is(state, BlockTrait.LEAVES); + } + + /** Logs or leaves by the platform's tags alone, as stilts tell vegetation from ground. */ + boolean isTaggedVegetation(BlockState state) { + return access.inTag(state, LOGS_TAG) || access.inTag(state, LEAVES_TAG); + } + + boolean inTag(BlockState state, ResourceId tag) { + return access.inTag(state, tag); + } + + /** Solid ground that is not part of a tree. */ + boolean isTerrain(BlockState state) { + return isSolid(state) && !isTree(state); + } + + /** Air or anything holding a fluid: the cells a fill may claim. */ + boolean isEncaseable(BlockState state) { + return isAir(state) || holdsFluid(state); + } + + /** A block a structure can stand on: solid, dry, and neither structure void nor a jigsaw. */ + boolean isSolidBase(BlockState state) { + return state != null && isSolid(state) + && !state.material().equals(STRUCTURE_VOID) + && !state.material().equals(JIGSAW) + && !holdsFluid(state); + } + + boolean sturdyTop(int x, int y, int z) { + return access.sturdy(x, y - bottomY, z, BlockFace.UP); + } + + BlockState fluidOf(BlockState state) { + return access.fluid(state); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPalettes.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPalettes.java new file mode 100644 index 000000000..89b10df9e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPalettes.java @@ -0,0 +1,29 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.structure.fit; + +import com.volmit.block.BlockState; +import com.volmit.block.PaletteSpec; + +/** Picks a block of a pack palette for the structure fit, seeded the way the fit's own randomness is. */ +@FunctionalInterface +interface FitPalettes { + /** The block {@code palette}, seeded with {@code seed}, gives at the world position. */ + BlockState at(PaletteSpec palette, long seed, int x, int y, int z); +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPiece.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPiece.java new file mode 100644 index 000000000..c9f74fc3b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPiece.java @@ -0,0 +1,102 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.structure.fit; + +import com.volmit.vanilla.PieceKind; +import com.volmit.vanilla.StructureFit; +import com.volmit.vanilla.TemplateCells; +import com.volmit.geometry.BlockPosition; + +import java.util.ArrayList; +import java.util.List; + +/** A piece of a start in world heights with inclusive bounds. */ +final class FitPiece { + private final StructureFit.Piece piece; + private final Box box; + private final int bottomY; + + FitPiece(StructureFit.Piece piece, int bottomY) { + this.piece = piece; + this.box = Box.of(piece.box(), bottomY); + this.bottomY = bottomY; + } + + Box box() { + return box; + } + + PieceKind kind() { + return piece.kind(); + } + + boolean isJigsaw() { + return piece.kind() != PieceKind.FIXED; + } + + boolean isRigid() { + return piece.kind() == PieceKind.RIGID; + } + + /** Whether the piece keeps its shape over the terrain: every piece built in code, and rigid jigsaw pieces. */ + boolean isRigidOrFixed() { + return piece.kind() != PieceKind.TERRAIN_MATCHING; + } + + int groundLevelDelta() { + return piece.groundLevelDelta(); + } + + /** The world height of the piece's ground level. */ + int groundY() { + return box.minY() + piece.groundLevelDelta(); + } + + /** The junctions, their Y the world height of the ground at their source. */ + List junctions() { + List junctions = new ArrayList<>(piece.junctions().size()); + for (BlockPosition junction : piece.junctions()) { + junctions.add(new BlockPosition(junction.x(), junction.y() + bottomY, junction.z())); + } + return junctions; + } + + TemplateCells cells(Box region) { + return piece.cells(region.toApi(bottomY)); + } + + /** The cell's world height. */ + int cellY(TemplateCells cells, int cell) { + return cells.y(cell) + bottomY; + } + + void columns(StructureFit.ColumnVisitor visitor) { + piece.columns((x, z, minY, maxY) -> visitor.column(x, z, minY + bottomY, maxY + bottomY)); + } + + /** Legacy template air inside {@code clip}, in world heights. */ + List legacyAir(Box clip) { + List air = piece.legacyAir(clip.toApi(bottomY)); + List world = new ArrayList<>(air.size()); + for (BlockPosition position : air) { + world.add(new BlockPosition(position.x(), position.y() + bottomY, position.z())); + } + return world; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitStart.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitStart.java new file mode 100644 index 000000000..9418d5350 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitStart.java @@ -0,0 +1,95 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.structure.fit; + +import art.arcane.iris.builtin.structure.StructureTerrain; +import art.arcane.iris.engine.framework.structure.NativeStructureFit; +import com.volmit.vanilla.DecorationStep; +import com.volmit.vanilla.StartKey; +import com.volmit.vanilla.StructureFit; +import com.volmit.vanilla.TerrainAdaptation; + +import java.util.ArrayList; +import java.util.List; + +/** A start the platform places in the chunk, with the fit {@code iris:structure} gives it, its pieces in world heights. */ +final class FitStart { + private final StructureFit.Start start; + private final NativeStructureFit fit; + private final List pieces; + + FitStart(StructureFit.Start start, NativeStructureFit fit, int bottomY) { + this.start = start; + this.fit = fit; + List converted = new ArrayList<>(start.pieces().size()); + for (StructureFit.Piece piece : start.pieces()) { + converted.add(new FitPiece(piece, bottomY)); + } + this.pieces = List.copyOf(converted); + } + + StructureFit.Start start() { + return start; + } + + String structureId() { + return start.structure().toString(); + } + + NativeStructureFit fit() { + return fit; + } + + StructureTerrain terrain() { + return fit.resolvedTerrain(); + } + + TerrainAdaptation adaptation() { + return start.adaptation(); + } + + DecorationStep step() { + return start.step(); + } + + int chunkX() { + return start.chunkX(); + } + + int chunkZ() { + return start.chunkZ(); + } + + List pieces() { + return pieces; + } + + /** The box around every piece of the start. */ + Box contentBounds() { + Box bounds = pieces.getFirst().box(); + for (FitPiece piece : pieces) { + bounds = bounds.encapsulating(piece.box()); + } + return bounds; + } + + StartKey key() { + return start.key(); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FoundationStilts.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FoundationStilts.java new file mode 100644 index 000000000..f2ef96888 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/FoundationStilts.java @@ -0,0 +1,156 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.structure.fit; + +import art.arcane.iris.builtin.structure.StructureStilts; +import com.volmit.block.BlockState; +import com.volmit.block.PaletteSpec; + +import java.util.ArrayList; +import java.util.BitSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.IntBinaryOperator; + +/** + * Foundation columns under a placed start: in every column of the start's foundation envelope (the pieces' lowest + * layers up to one above their ground), from the lowest solid block placed there down to the first block that can + * carry it, the terrain's surface for a surface structure, at most {@code maxDepth} blocks deep. Sparse stilts keep + * only the columns on their spacing grid. + * + *

These are the vanilla structures' stilts. Objects grow theirs from their own bottom layer instead + * ({@code iris:stilt}): repeated object blocks, eroded or organic tips and a ceiling hang have no counterpart here, and + * these columns have no counterpart there, so the two stay separate. + */ +final class FoundationStilts { + private static final int FOUNDATION_VERTICAL_TOLERANCE = 1; + + private FoundationStilts() { + } + + static void placeStilts(FitBlocks blocks, Box area, FitStart start, StructureStilts settings, long seed, + FitPalettes palettes, IntBinaryOperator surfaceHeight, boolean surfaceStructure) { + Objects.requireNonNull(surfaceHeight, "Structure stilts require an Iris terrain height resolver"); + Optional palette = settings.palette(); + long paletteSeed = seed ^ start.structureId().hashCode(); + for (FoundationColumn column : foundationEnvelope(area, start)) { + if (!isStiltColumn(column.x(), column.z(), settings.spacing())) { + continue; + } + int foundationY = findFoundationY(blocks, column); + if (foundationY == Integer.MIN_VALUE) { + continue; + } + int terrainY = surfaceStructure + ? Math.max(area.minY(), Math.min(area.maxY(), surfaceHeight.applyAsInt(column.x(), column.z()))) + : area.minY() - 1; + int anchorY = findStiltAnchorY(blocks, column.x(), column.z(), foundationY, + Math.max(1, settings.maxDepth()), terrainY, area.minY()); + if (anchorY == Integer.MIN_VALUE) { + continue; + } + for (int y = foundationY - 1; y > anchorY; y--) { + BlockState stilt = palette.isEmpty() + ? FitBlocks.COBBLESTONE + : Objects.requireNonNull(palettes.at(palette.get(), paletteSeed, column.x(), y, column.z()), + "Stilt palette returned no block for " + start.structureId() + " at " + + column.x() + "," + y + "," + column.z()); + blocks.set(column.x(), y, column.z(), stilt); + } + } + } + + static boolean isStiltColumn(int x, int z, int spacing) { + int resolvedSpacing = Math.max(1, spacing); + return resolvedSpacing == 1 || Math.floorMod(x, resolvedSpacing) == 0 && Math.floorMod(z, resolvedSpacing) == 0; + } + + static int findStiltAnchorY(FitBlocks blocks, int x, int z, int foundationY, int maxDepth, int terrainY, + int areaMinY) { + int minimumAnchorY = Math.max(areaMinY, Math.max(terrainY, foundationY - maxDepth - 1)); + for (int y = foundationY - 1; y >= minimumAnchorY; y--) { + BlockState state = blocks.get(x, y, z); + if (!blocks.isTaggedVegetation(state) && blocks.sturdyTop(x, y, z)) { + return y; + } + } + return Integer.MIN_VALUE; + } + + private static List foundationEnvelope(Box area, FitStart start) { + Box structure = start.contentBounds(); + int minX = Math.max(area.minX(), structure.minX()); + int minZ = Math.max(area.minZ(), structure.minZ()); + int maxX = Math.min(area.maxX(), structure.maxX()); + int maxZ = Math.min(area.maxZ(), structure.maxZ()); + if (minX > maxX || minZ > maxZ) { + return List.of(); + } + List columns = new ArrayList<>((maxX - minX + 1) * (maxZ - minZ + 1)); + BitSet envelope = new BitSet(area.ySpan()); + for (int z = minZ; z <= maxZ; z++) { + for (int x = minX; x <= maxX; x++) { + envelope.clear(); + markFoundationEnvelope(envelope, start, area, x, z); + int cellCount = envelope.cardinality(); + if (cellCount == 0) { + continue; + } + int[] ys = new int[cellCount]; + int cell = 0; + for (int bit = envelope.nextSetBit(0); bit >= 0; bit = envelope.nextSetBit(bit + 1)) { + ys[cell++] = area.minY() + bit; + } + columns.add(new FoundationColumn(x, z, ys)); + } + } + return List.copyOf(columns); + } + + private static void markFoundationEnvelope(BitSet envelope, FitStart start, Box area, int x, int z) { + for (FitPiece piece : start.pieces()) { + Box bounds = piece.box(); + if (x < bounds.minX() || x > bounds.maxX() || z < bounds.minZ() || z > bounds.maxZ()) { + continue; + } + int groundY = piece.groundY(); + if (piece.isJigsaw() && groundY < bounds.minY()) { + continue; + } + int minY = Math.max(area.minY(), bounds.minY()); + int maxY = Math.min(area.maxY(), Math.min(bounds.maxY(), groundY + FOUNDATION_VERTICAL_TOLERANCE)); + if (minY <= maxY) { + envelope.set(minY - area.minY(), maxY - area.minY() + 1); + } + } + } + + private static int findFoundationY(FitBlocks blocks, FoundationColumn column) { + for (int y : column.ys()) { + if (blocks.isSolid(blocks.get(column.x(), y, column.z()))) { + return y; + } + } + return Integer.MIN_VALUE; + } + + private record FoundationColumn(int x, int z, int[] ys) { + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/RigidSupport.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/RigidSupport.java new file mode 100644 index 000000000..95a8df136 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/RigidSupport.java @@ -0,0 +1,270 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.structure.fit; + +import com.volmit.block.BlockState; +import com.volmit.vanilla.StartKey; +import com.volmit.vanilla.TemplateCells; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Closes the short gaps between two rigid pieces of one surface start whose ground planes are one or two blocks apart: + * where the upper piece's lowest solid base sits two blocks over the lower piece's ground, the gap is filled with the + * terrain under the lower piece, so steps and terraces stand on ground instead of air. Only the chunk's own blocks are + * filled, never across starts, and nothing at all when the work would exceed its budget. + */ +final class RigidSupport { + private static final int MAX_BATCH_CELLS = 524_288; + private static final int MAX_BRIDGE_SPAN = 2; + + private RigidSupport() { + } + + static Set bridgeRigidPieceSupport(FitBlocks blocks, Box area, List starts) { + if (starts.isEmpty()) { + return Set.of(); + } + Map planned; + try { + BatchCellBudget budget = new BatchCellBudget(); + List requests = new ArrayList<>(); + Set seenStarts = new HashSet<>(); + for (FitStart start : starts) { + if (!SurfaceFitting.requiresSurfaceTerrain(start) || !seenStarts.add(start.key())) { + continue; + } + collectStartRequests(blocks, area, start, budget, requests); + } + planned = planWrites(blocks, area, requests, budget); + } catch (BatchBudgetExceeded ignored) { + return Set.of(); + } + if (planned.isEmpty()) { + return Set.of(); + } + List> ordered = new ArrayList<>(planned.entrySet()); + ordered.sort(Map.Entry.comparingByKey()); + Set written = new HashSet<>(); + for (Map.Entry entry : ordered) { + int x = TemplateFootprint.packedX(entry.getKey()); + int y = TemplateFootprint.packedY(entry.getKey()); + int z = TemplateFootprint.packedZ(entry.getKey()); + BlockState existing = blocks.get(x, y, z); + if (!blocks.isSolid(existing) && !blocks.isTree(existing) && !blocks.holdsFluid(existing)) { + blocks.set(x, y, z, entry.getValue()); + written.add(entry.getKey()); + } + } + return Set.copyOf(written); + } + + private static void collectStartRequests(FitBlocks blocks, Box area, FitStart start, BatchCellBudget budget, + List requests) { + List anchors = rigidAnchors(start); + if (anchors.size() < 2) { + return; + } + for (RigidAnchor upper : anchors) { + Map lowerMeets = candidateLowerMeets(area, upper, anchors, budget); + if (lowerMeets.isEmpty()) { + continue; + } + TemplateCells cells = upper.piece().cells(area); + budget.consume(cells.readBlocks()); + if (!cells.resolved()) { + continue; + } + for (Map.Entry entry + : lowestBridgeableCells(cells, upper.piece(), area, lowerMeets).entrySet()) { + TemplateFootprint.Cell cell = entry.getValue(); + Integer lowerMeet = lowerMeets.get(entry.getKey()); + if (lowerMeet == null || cell.blocker() || !blocks.isSolidBase(cell.state()) + || cell.y() - lowerMeet < 2 || cell.y() - lowerMeet > MAX_BRIDGE_SPAN) { + continue; + } + budget.consume(1); + requests.add(new SupportRequest(cell.x(), cell.z(), lowerMeet, cell.y())); + } + } + } + + /** + * The lowest cell of each column over a lower piece's ground, among the cells no higher than the widest bridge + * above that ground: the cells the support could stand under. + */ + private static Map lowestBridgeableCells(TemplateCells cells, FitPiece piece, Box area, + Map lowerMeets) { + Map lowest = new HashMap<>(); + for (int cell = 0; cell < cells.size(); cell++) { + int x = cells.x(cell); + int y = piece.cellY(cells, cell); + int z = cells.z(cell); + long column = TemplateFootprint.columnKey(x, z); + Integer lowerMeet = lowerMeets.get(column); + if (!area.contains(x, y, z) || lowerMeet == null || y > lowerMeet + MAX_BRIDGE_SPAN) { + continue; + } + TemplateFootprint.Cell current = lowest.get(column); + if (current == null || y < current.y()) { + lowest.put(column, new TemplateFootprint.Cell(x, y, z, cells.state(cell))); + } + } + return lowest; + } + + private static List rigidAnchors(FitStart start) { + List anchors = new ArrayList<>(); + for (FitPiece piece : start.pieces()) { + if (!piece.isRigid()) { + continue; + } + anchors.add(new RigidAnchor(piece, piece.box(), piece.groundY() - 1)); + } + return List.copyOf(anchors); + } + + private static Map candidateLowerMeets(Box area, RigidAnchor upper, List anchors, + BatchCellBudget budget) { + Map lowerMeets = new HashMap<>(); + for (RigidAnchor lower : anchors) { + budget.consume(1); + int span = upper.meetY() - lower.meetY(); + if (lower.piece() == upper.piece() || span < 1 || span > MAX_BRIDGE_SPAN + || lower.meetY() < area.minY() || lower.meetY() > area.maxY()) { + continue; + } + int minimumX = Math.max(area.minX(), Math.max(upper.bounds().minX(), lower.bounds().minX())); + int maximumX = Math.min(area.maxX(), Math.min(upper.bounds().maxX(), lower.bounds().maxX())); + int minimumZ = Math.max(area.minZ(), Math.max(upper.bounds().minZ(), lower.bounds().minZ())); + int maximumZ = Math.min(area.maxZ(), Math.min(upper.bounds().maxZ(), lower.bounds().maxZ())); + if (minimumX > maximumX || minimumZ > maximumZ) { + continue; + } + for (int x = minimumX; x <= maximumX; x++) { + for (int z = minimumZ; z <= maximumZ; z++) { + budget.consume(1); + lowerMeets.merge(TemplateFootprint.columnKey(x, z), lower.meetY(), Math::max); + } + } + } + return lowerMeets; + } + + private static Map planWrites(FitBlocks blocks, Box area, List requests, + BatchCellBudget budget) { + List eligible = new ArrayList<>(); + Set materialKeys = new HashSet<>(); + for (SupportRequest request : requests) { + BlockState lowerTerrain = blocks.get(request.x(), request.lowerMeetY(), request.z()); + if (!isTerrainSupport(blocks, lowerTerrain) || !gapIsClear(blocks, area, request, budget)) { + continue; + } + eligible.add(request); + materialKeys.add(new MaterialKey(request.x(), request.z(), request.lowerMeetY())); + } + Map materials = new HashMap<>(); + for (MaterialKey key : materialKeys) { + materials.put(key, resolveSupportState(blocks, key.x(), key.z(), key.lowerMeetY(), budget)); + } + Map planned = new HashMap<>(); + Set conflicts = new HashSet<>(); + eligible.sort(Comparator.comparingInt(SupportRequest::x) + .thenComparingInt(SupportRequest::z) + .thenComparingInt(SupportRequest::lowerMeetY) + .thenComparingInt(SupportRequest::baseY)); + for (SupportRequest request : eligible) { + BlockState material = materials.get(new MaterialKey(request.x(), request.z(), request.lowerMeetY())); + for (int y = request.lowerMeetY() + 1; y < request.baseY(); y++) { + budget.consume(1); + long positionKey = TemplateFootprint.packedPosition(request.x(), y, request.z()); + if (conflicts.contains(positionKey)) { + continue; + } + BlockState existing = planned.putIfAbsent(positionKey, material); + if (existing != null && !existing.equals(material)) { + planned.remove(positionKey); + conflicts.add(positionKey); + } + } + } + return planned; + } + + private static boolean gapIsClear(FitBlocks blocks, Box area, SupportRequest request, BatchCellBudget budget) { + for (int y = request.lowerMeetY() + 1; y < request.baseY(); y++) { + budget.consume(1); + if (!area.contains(request.x(), y, request.z())) { + return false; + } + BlockState state = blocks.get(request.x(), y, request.z()); + if (blocks.isSolid(state) || blocks.isTree(state) || blocks.holdsFluid(state)) { + return false; + } + } + return true; + } + + private static BlockState resolveSupportState(FitBlocks blocks, int x, int z, int lowerMeetY, BatchCellBudget budget) { + budget.consume(1); + BlockState below = blocks.get(x, lowerMeetY - 1, z); + if (isTerrainSupport(blocks, below)) { + return below; + } + return blocks.get(x, lowerMeetY, z); + } + + private static boolean isTerrainSupport(FitBlocks blocks, BlockState state) { + return blocks.isSolid(state) && !blocks.isTree(state) && !blocks.holdsFluid(state); + } + + private record RigidAnchor(FitPiece piece, Box bounds, int meetY) { + } + + private record SupportRequest(int x, int z, int lowerMeetY, int baseY) { + } + + private record MaterialKey(int x, int z, int lowerMeetY) { + } + + private static final class BatchCellBudget { + private int consumed; + + private void consume(int amount) { + if (amount < 0 || consumed > MAX_BATCH_CELLS - amount) { + throw BatchBudgetExceeded.INSTANCE; + } + consumed += amount; + } + } + + private static final class BatchBudgetExceeded extends RuntimeException { + private static final BatchBudgetExceeded INSTANCE = new BatchBudgetExceeded(); + + private BatchBudgetExceeded() { + super(null, null, false, false); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/StartLayouts.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/StartLayouts.java new file mode 100644 index 000000000..ad7b5a12f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/StartLayouts.java @@ -0,0 +1,112 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.structure.fit; + +import art.arcane.iris.builtin.structure.StructureTerrain; +import art.arcane.iris.builtin.structure.StructureYBand; +import art.arcane.iris.engine.framework.structure.NativeStructureFit; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.geometry.BlockBox; +import com.volmit.vanilla.PlatformStart; +import com.volmit.vanilla.StartReach; + +/** + * Where the platform's own starts sit and how far {@code iris:structure} changes the terrain around a start. A start + * that keeps the platform's height only takes its shift; a band moves the start's middle into it, chosen per start + * chunk; an underground start is buried under the lowest terrain column above it; anything else takes its shift. A + * structure the host aligns itself only takes its shift on top of that alignment. + */ +public final class StartLayouts { + private static final int MAX_BURIAL_COLUMNS = 2_000_000; + private static final int UNDERGROUND_SURFACE_CLEARANCE = 1; + private static final long BAND_IDENTITY_X = 341873128712L; + private static final long BAND_IDENTITY_Z = 132897987541L; + + private StartLayouts() { + } + + /** How far {@code start} moves up (negative: down) under {@code fit}, before the host keeps it inside the world. */ + public static int shift(PlatformStart start, NativeStructureFit fit) { + if (start.aligned() || fit.keepsSourceY()) { + return fit.yShift(); + } + if (fit.yBand() != null) { + return bandShift(start, fit.yBand()); + } + if (start.underground()) { + return burialShift(start, fit.yShift()); + } + return fit.yShift(); + } + + /** How far around its pieces a start with {@code terrain} changes the terrain. */ + public static StartReach reach(StructureTerrain terrain) { + return switch (terrain.resolvedMode()) { + case SOURCE -> StartReach.PLATFORM; + case PRESERVE -> StartReach.blocks(0); + case VACUUM -> StartReach.blocks(SurfaceFitting.surfaceTerrainRadius()); + case BORE, FORCE_CARVE, ENCASE -> StartReach.blocks(Math.max(0, terrain.horizontalPadding())); + }; + } + + private static int bandShift(PlatformStart start, StructureYBand band) { + BlockBox bounds = start.bounds(); + int minY = bounds.minY() + start.minWorldY(); + int maxY = bounds.maxY() - 1 + start.minWorldY(); + int target = bandTargetMidpointY(minY, maxY, band.resolvedMin(), band.resolvedMax(), start.chunkX(), start.chunkZ()); + return Math.subtractExact(target, minY + (maxY - minY) / 2); + } + + /** The world height the middle of a start from {@code maxY - minY} high moves to, inside the band, per start chunk. */ + static int bandTargetMidpointY(int minY, int maxY, int bandMin, int bandMax, int chunkX, int chunkZ) { + int height = Math.subtractExact(maxY, minY); + int lowest = Math.addExact(bandMin, height / 2); + int highest = Math.subtractExact(bandMax, height - height / 2); + if (lowest > highest) { + // The band is shorter than the structure, so only its midpoint can be honoured. + return Math.floorDiv(Math.addExact(bandMin, bandMax), 2); + } + int span = highest - lowest + 1; + if (span == 1) { + return lowest; + } + long identity = (long) chunkX * BAND_IDENTITY_X ^ (long) chunkZ * BAND_IDENTITY_Z; + return lowest + new RNG(identity).nextInt(span); + } + + /** At most {@code requestedShift}, and low enough that the start's top stays a block under every terrain column. */ + private static int burialShift(PlatformStart start, int requestedShift) { + BlockBox bounds = start.bounds(); + long width = (long) bounds.maxX() - bounds.minX(); + long depth = (long) bounds.maxZ() - bounds.minZ(); + if (width <= 0L || depth <= 0L || width > MAX_BURIAL_COLUMNS / depth) { + throw new IllegalStateException("Underground native structure burial footprint is invalid or exceeds " + + MAX_BURIAL_COLUMNS + " columns"); + } + int topY = bounds.maxY() - 1; + int maximumShift = requestedShift; + for (int x = bounds.minX(); x < bounds.maxX(); x++) { + for (int z = bounds.minZ(); z < bounds.maxZ(); z++) { + int allowedTopY = start.surfaceY(x, z) - UNDERGROUND_SURFACE_CLEARANCE; + maximumShift = Math.min(maximumShift, allowedTopY - topY); + } + } + return maximumShift; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java new file mode 100644 index 000000000..925946720 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java @@ -0,0 +1,723 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.structure.fit; + +import art.arcane.iris.builtin.structure.StructureTerrainMode; +import com.volmit.ModuleLog; +import com.volmit.block.BlockState; +import com.volmit.vanilla.DecorationStep; +import com.volmit.vanilla.StartKey; +import com.volmit.vanilla.TemplateCells; +import com.volmit.vanilla.TerrainAdaptation; +import com.volmit.geometry.BlockPosition; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.IntBinaryOperator; + +/** + * Fits the surface around the platform's surface structures before their pieces are placed. SOURCE replays the + * platform's beard adaptation: the terrain within 12 blocks of the structure's ground planes bends toward them, never + * more than 6 blocks. VACUUM raises the terrain to meet the processed solid foundations of rigid pieces, again over 12 + * blocks, without ever lowering it, and after the pieces are placed fills the gaps left under their bases + * ({@link #repairVacuumFoundations}). + */ +final class SurfaceFitting { + private static final double SURFACE_TERRAIN_FALLOFF = 2.0; + private static final long SURFACE_TERRAIN_INFLUENCE_SCALE = 1_000_000L; + private static final int SURFACE_TERRAIN_RADIUS = 12; + private static final int MAX_SOURCE_SURFACE_DELTA = 6; + static final int MAX_SURFACE_TEMPLATE_CELLS = 4_194_304; + private static final int FOUNDATION_ANCHOR_STRENGTH = 2; + private static final int JUNCTION_ANCHOR_STRENGTH = 1; + private static final Set WARNED_SOURCE_BUDGET = ConcurrentHashMap.newKeySet(); + private static final Set WARNED_VACUUM_BUDGET = ConcurrentHashMap.newKeySet(); + + private SurfaceFitting() { + } + + /** The radius of the surface falloff, which a VACUUM start reaches beyond its pieces. */ + static int surfaceTerrainRadius() { + return SURFACE_TERRAIN_RADIUS; + } + + static VacuumFoundationPlan prepareSurfaceStructures(FitBlocks blocks, Box area, List starts, + IntBinaryOperator surfaceHeight, int maximumTemplateCells, + ModuleLog log) { + if (starts.isEmpty()) { + return VacuumFoundationPlan.EMPTY; + } + Objects.requireNonNull(surfaceHeight, "Surface structure terrain fitting requires an Iris height resolver"); + List anchors = collectSourceSurfaceAnchors(blocks, area, starts, maximumTemplateCells, log); + if (!anchors.isEmpty()) { + fitSurfaceTerrain(blocks, area, anchors, surfaceHeight); + } + VacuumFootprint vacuum = collectVacuumFootprint(blocks, area, starts, maximumTemplateCells, log); + if (!vacuum.anchors().isEmpty()) { + fitVacuumTerrain(blocks, area, vacuum, surfaceHeight); + } + return VacuumFoundationPlan.create(vacuum.foundationBases(), vacuum.occupiedCells(), area); + } + + static void repairVacuumFoundations(FitBlocks blocks, Box area, VacuumFoundationPlan plan) { + if (plan == null || plan.foundationBases.isEmpty()) { + return; + } + for (long packedBase : plan.foundationBases) { + int baseX = TemplateFootprint.packedX(packedBase); + int baseY = TemplateFootprint.packedY(packedBase); + int baseZ = TemplateFootprint.packedZ(packedBase); + if (!area.contains(baseX, baseY, baseZ)) { + continue; + } + if (!blocks.isSolidBase(blocks.get(baseX, baseY, baseZ))) { + continue; + } + int supportY = findVacuumFoundationSupport(blocks, area, baseX, baseY - 1, baseZ); + if (supportY == Integer.MIN_VALUE || supportY == baseY - 1) { + continue; + } + if (intersectsVacuumOccupancy(plan.occupiedCells, baseX, baseZ, supportY + 1, baseY - 1)) { + continue; + } + BlockState fill = resolveSurfaceMaterials(blocks, baseX, baseZ, supportY, area.minY()).subsurface(); + for (int y = supportY + 1; y < baseY; y++) { + BlockState existing = blocks.get(baseX, y, baseZ); + if (blocks.isAir(existing) || blocks.holdsFluid(existing)) { + blocks.set(baseX, y, baseZ, fill); + } + } + } + } + + static boolean shouldPrepareSurfaceTerrain(TerrainAdaptation adaptation, DecorationStep step) { + return step == DecorationStep.SURFACE_STRUCTURES + && (adaptation == TerrainAdaptation.BEARD_THIN || adaptation == TerrainAdaptation.BEARD_BOX); + } + + static int resolveSurfaceTarget(List anchors, int worldX, int worldZ, int originalY) { + return resolveSurface(anchors, worldX, worldZ, originalY).targetY(); + } + + /** How far {@code value} lies outside {@code [low, high]}; 0 inside. Iris's vacuum measures footprints the same way. */ + private static int outset(int value, int low, int high) { + if (value < low) { + return low - value; + } + if (value > high) { + return value - high; + } + return 0; + } + + private static SurfaceResolution resolveSurface(List anchors, int worldX, int worldZ, int originalY) { + int localTargetY = originalY; + SurfaceAnchor selectedLocal = null; + long totalInfluence = 0L; + long weightedTargetY = 0L; + long maximumInfluence = 0L; + for (SurfaceAnchor anchor : anchors) { + int outX = outset(worldX, anchor.minX(), anchor.maxX()); + int outZ = outset(worldZ, anchor.minZ(), anchor.maxZ()); + boolean containsColumn = outX == 0 && outZ == 0; + long distanceSquared = (long) outX * outX + (long) outZ * outZ; + long radiusSquared = (long) SURFACE_TERRAIN_RADIUS * SURFACE_TERRAIN_RADIUS; + if (distanceSquared > radiusSquared) { + continue; + } + double distance = Math.sqrt(distanceSquared); + double factor = Math.pow(1D - distance / SURFACE_TERRAIN_RADIUS, SURFACE_TERRAIN_FALLOFF); + if (factor <= 0D) { + continue; + } + int boundedTargetY = boundedSurfaceTarget(originalY, anchor.meetY()); + if (containsColumn) { + if (precedes(anchor, selectedLocal)) { + localTargetY = boundedTargetY; + selectedLocal = anchor; + } + continue; + } + long influence = Math.round(factor * SURFACE_TERRAIN_INFLUENCE_SCALE); + if (influence <= 0L) { + continue; + } + long weightedInfluence = influence * Math.max(1, anchor.strength()); + totalInfluence += weightedInfluence; + weightedTargetY += weightedInfluence * boundedTargetY; + maximumInfluence = Math.max(maximumInfluence, influence); + } + if (selectedLocal != null) { + return new SurfaceResolution(localTargetY, + selectedLocal.strength() > 1 && localTargetY == selectedLocal.meetY()); + } + if (totalInfluence == 0L) { + return new SurfaceResolution(originalY, false); + } + double blendedTargetY = weightedTargetY / (double) totalInfluence; + double factor = maximumInfluence / (double) SURFACE_TERRAIN_INFLUENCE_SCALE; + return new SurfaceResolution(blendSurfaceTarget(originalY, blendedTargetY, factor), false); + } + + private static int boundedSurfaceTarget(int originalY, int meetY) { + int delta = Math.max(-MAX_SOURCE_SURFACE_DELTA, Math.min(MAX_SOURCE_SURFACE_DELTA, meetY - originalY)); + return originalY + delta; + } + + private static int blendSurfaceTarget(int originalY, double targetY, double factor) { + double delta = (targetY - originalY) * factor; + int magnitude = (int) Math.round(Math.abs(delta)); + return originalY + (delta < 0D ? -magnitude : magnitude); + } + + private static boolean precedes(SurfaceAnchor candidate, SurfaceAnchor selected) { + if (selected == null) { + return true; + } + if (candidate.strength() != selected.strength()) { + return candidate.strength() > selected.strength(); + } + if (candidate.meetY() != selected.meetY()) { + return candidate.meetY() < selected.meetY(); + } + if (candidate.minX() != selected.minX()) { + return candidate.minX() < selected.minX(); + } + if (candidate.minZ() != selected.minZ()) { + return candidate.minZ() < selected.minZ(); + } + if (candidate.maxX() != selected.maxX()) { + return candidate.maxX() < selected.maxX(); + } + if (candidate.maxZ() != selected.maxZ()) { + return candidate.maxZ() < selected.maxZ(); + } + return false; + } + + private static List collectSourceSurfaceAnchors(FitBlocks blocks, Box area, List starts, + int maximumTemplateCells, ModuleLog log) { + Box influenceArea = area.widened(SURFACE_TERRAIN_RADIUS); + List anchors = new ArrayList<>(); + Set seenStarts = new HashSet<>(); + for (FitStart start : starts) { + if (!requiresSourceSurfaceTerrain(start) || !seenStarts.add(start.key())) { + continue; + } + TemplateCellBudget budget = new TemplateCellBudget(maximumTemplateCells); + boolean budgetExceeded = false; + for (FitPiece piece : start.pieces()) { + if (piece.isJigsaw()) { + if (!budgetExceeded && piece.box().intersectsHorizontally(influenceArea)) { + try { + List pieceAnchors = new ArrayList<>(); + addProcessedSurfaceAnchors(blocks, influenceArea, piece, budget, pieceAnchors); + anchors.addAll(pieceAnchors); + } catch (TemplateBudgetExceeded ignored) { + budgetExceeded = true; + warnBudget(WARNED_SOURCE_BUDGET, start, "SOURCE", + "skipping remaining processed footprints for this start", log); + } + } + for (BlockPosition junction : piece.junctions()) { + anchors.add(new SurfaceAnchor(junction.x(), junction.x(), junction.z(), junction.z(), + junction.y() - 1, JUNCTION_ANCHOR_STRENGTH)); + } + continue; + } + Box bounds = piece.box(); + anchors.add(surfaceAnchor(bounds, bounds.minY(), FOUNDATION_ANCHOR_STRENGTH)); + } + } + return List.copyOf(anchors); + } + + private static void addProcessedSurfaceAnchors(FitBlocks blocks, Box influenceArea, FitPiece piece, + TemplateCellBudget budget, List anchors) { + TemplateCells cells = piece.cells(influenceArea); + budget.consume(cells.readBlocks()); + if (!cells.resolved()) { + return; + } + int maximumFoundationY = piece.groundY(); + for (TemplateFootprint.Cell cell : TemplateFootprint.lowestSolidCells(cells, piece, blocks).values()) { + budget.consume(1); + if (piece.isRigid() && cell.y() > maximumFoundationY) { + continue; + } + int groundY = piece.isRigid() ? maximumFoundationY : cell.y(); + Box column = new Box(cell.x(), groundY, cell.z(), cell.x(), groundY, cell.z()); + anchors.add(surfaceAnchor(column, groundY, FOUNDATION_ANCHOR_STRENGTH)); + } + } + + private static void warnBudget(Set warned, FitStart start, String mode, String consequence, ModuleLog log) { + if (warned.add(start.structureId())) { + log.warn("Native structure " + mode + " fitting for '" + start.structureId() + + "' exceeded its bounded template budget; " + consequence); + } + } + + private static VacuumFootprint collectVacuumFootprint(FitBlocks blocks, Box area, List starts, + int maximumTemplateCells, ModuleLog log) { + Box influenceArea = area.widened(SURFACE_TERRAIN_RADIUS); + Map anchors = new HashMap<>(); + Map columnCaps = new HashMap<>(); + Set foundationBases = new HashSet<>(); + Set occupiedCells = new HashSet<>(); + Set seenStarts = new HashSet<>(); + for (FitStart start : starts) { + if (start.terrain().resolvedMode() != StructureTerrainMode.VACUUM || !seenStarts.add(start.key())) { + continue; + } + Map targetAnchors = new HashMap<>(); + Map targetCaps = new HashMap<>(); + Set targetFoundationBases = new HashSet<>(); + Set targetOccupiedCells = new HashSet<>(); + TemplateCellBudget budget = new TemplateCellBudget(maximumTemplateCells); + try { + for (FitPiece piece : start.pieces()) { + if (!piece.box().intersectsHorizontally(influenceArea) || !piece.isRigid()) { + continue; + } + addVacuumJunctionAnchors(anchors, influenceArea, piece); + TemplateCells cells = piece.cells(influenceArea); + budget.consume(cells.readBlocks()); + if (!cells.resolved()) { + continue; + } + for (int cell = 0; cell < cells.size(); cell++) { + targetOccupiedCells.add(TemplateFootprint.packedPosition( + cells.x(cell), piece.cellY(cells, cell), cells.z(cell))); + } + int groundY = piece.groundY() - 1; + for (TemplateFootprint.Cell cell : TemplateFootprint.lowestCells(cells, piece).values()) { + budget.consume(1); + long column = TemplateFootprint.columnKey(cell.x(), cell.z()); + targetCaps.merge(column, Math.min(cell.y(), groundY), Math::min); + if (cell.blocker() || cell.y() > groundY + 1 || !blocks.isSolidBase(cell.state())) { + continue; + } + addVacuumAnchor(targetAnchors, cell.x(), cell.z(), + new VacuumAnchor(cell.y() - 1, FOUNDATION_ANCHOR_STRENGTH)); + targetFoundationBases.add(TemplateFootprint.packedPosition(cell.x(), cell.y(), cell.z())); + } + } + } catch (TemplateBudgetExceeded ignored) { + warnBudget(WARNED_VACUUM_BUDGET, start, "VACUUM", "using jigsaw junction smoothing for oversized starts", log); + continue; + } + targetAnchors.forEach((column, anchor) -> anchors.merge(column, anchor, SurfaceFitting::preferredVacuumAnchor)); + targetCaps.forEach((column, cap) -> columnCaps.merge(column, cap, Math::min)); + foundationBases.addAll(targetFoundationBases); + occupiedCells.addAll(targetOccupiedCells); + } + return new VacuumFootprint(Map.copyOf(anchors), Map.copyOf(columnCaps), + Set.copyOf(foundationBases), Set.copyOf(occupiedCells)); + } + + private static void addVacuumJunctionAnchors(Map anchors, Box influenceArea, FitPiece piece) { + for (BlockPosition junction : piece.junctions()) { + if (junction.x() < influenceArea.minX() || junction.x() > influenceArea.maxX() + || junction.z() < influenceArea.minZ() || junction.z() > influenceArea.maxZ()) { + continue; + } + addVacuumAnchor(anchors, junction.x(), junction.z(), + new VacuumAnchor(junction.y() - 1, JUNCTION_ANCHOR_STRENGTH)); + } + } + + private static void addVacuumAnchor(Map anchors, int x, int z, VacuumAnchor candidate) { + anchors.merge(TemplateFootprint.columnKey(x, z), candidate, SurfaceFitting::preferredVacuumAnchor); + } + + private static VacuumAnchor preferredVacuumAnchor(VacuumAnchor first, VacuumAnchor second) { + if (first.strength() != second.strength()) { + return first.strength() > second.strength() ? first : second; + } + return first.surfaceY() <= second.surfaceY() ? first : second; + } + + static SurfaceAnchor surfaceAnchor(Box bounds, int groundY, int strength) { + return new SurfaceAnchor(bounds.minX(), bounds.maxX(), bounds.minZ(), bounds.maxZ(), groundY - 1, strength); + } + + /** Whether the start's pieces need the surface fitted around them: VACUUM, or SOURCE with a beard adaptation. */ + static boolean requiresSurfaceTerrain(FitStart start) { + return start.terrain().resolvedMode() == StructureTerrainMode.VACUUM || requiresSourceSurfaceTerrain(start); + } + + private static boolean requiresSourceSurfaceTerrain(FitStart start) { + return start.terrain().resolvedMode() == StructureTerrainMode.SOURCE + && shouldPrepareSurfaceTerrain(start.adaptation(), start.step()); + } + + private static void fitSurfaceTerrain(FitBlocks blocks, Box area, List anchors, + IntBinaryOperator surfaceHeight) { + int width = area.xSpan(); + int depth = area.zSpan(); + int[] originalHeights = new int[width * depth]; + int[] targetHeights = new int[width * depth]; + boolean[] rigidBaseSupport = new boolean[width * depth]; + for (int z = area.minZ(); z <= area.maxZ(); z++) { + for (int x = area.minX(); x <= area.maxX(); x++) { + int column = area.columnIndex(x, z); + int originalY = Math.max(area.minY(), Math.min(area.maxY(), surfaceHeight.applyAsInt(x, z))); + SurfaceResolution resolution = resolveSurface(anchors, x, z, originalY); + originalHeights[column] = originalY; + targetHeights[column] = Math.max(area.minY(), Math.min(area.maxY(), resolution.targetY())); + rigidBaseSupport[column] = resolution.rigidBaseSupport(); + } + } + for (int z = area.minZ(); z <= area.maxZ(); z++) { + for (int x = area.minX(); x <= area.maxX(); x++) { + int column = area.columnIndex(x, z); + applySurfaceColumn(blocks, x, z, originalHeights[column], targetHeights[column], area.minY(), area.maxY(), + rigidBaseSupport[column]); + } + } + } + + private static void fitVacuumTerrain(FitBlocks blocks, Box area, VacuumFootprint footprint, + IntBinaryOperator surfaceHeight) { + int width = area.xSpan(); + int depth = area.zSpan(); + int[] originalHeights = new int[width * depth]; + int[] targetHeights = new int[width * depth]; + boolean[] rigidBaseSupport = new boolean[width * depth]; + for (int z = area.minZ(); z <= area.maxZ(); z++) { + for (int x = area.minX(); x <= area.maxX(); x++) { + int column = area.columnIndex(x, z); + int nominalY = Math.max(area.minY(), Math.min(area.maxY(), surfaceHeight.applyAsInt(x, z))); + long columnKey = TemplateFootprint.columnKey(x, z); + VacuumAnchor local = footprint.anchors().get(columnKey); + Integer cap = footprint.columnCaps().get(columnKey); + boolean suppressed = local != null && local.strength() > 1 && cap != null && cap < local.surfaceY(); + int scanStartY = local != null && local.strength() > 1 && !suppressed + ? Math.max(area.minY(), Math.min(area.maxY(), local.surfaceY())) + : nominalY; + int originalY = resolveVacuumSurfaceHeight(blocks, x, z, scanStartY, area.minY()); + SurfaceResolution resolution = resolveVacuumSurface(footprint, x, z, originalY); + originalHeights[column] = originalY; + targetHeights[column] = Math.max(originalY, Math.min(area.maxY(), resolution.targetY())); + rigidBaseSupport[column] = resolution.rigidBaseSupport() && targetHeights[column] > originalY; + } + } + for (int z = area.minZ(); z <= area.maxZ(); z++) { + for (int x = area.minX(); x <= area.maxX(); x++) { + int column = area.columnIndex(x, z); + applySurfaceColumn(blocks, x, z, originalHeights[column], targetHeights[column], area.minY(), area.maxY(), + rigidBaseSupport[column]); + } + } + } + + private static int resolveVacuumSurfaceHeight(FitBlocks blocks, int x, int z, int nominalY, int worldMinY) { + for (int y = nominalY; y >= worldMinY; y--) { + if (blocks.isTerrain(blocks.get(x, y, z))) { + return y; + } + } + return nominalY; + } + + private static int findVacuumFoundationSupport(FitBlocks blocks, Box area, int x, int startY, int z) { + if (startY < area.minY()) { + return Integer.MIN_VALUE; + } + int maximumY = Math.min(area.maxY(), startY); + for (int y = maximumY; y >= area.minY(); y--) { + BlockState state = blocks.get(x, y, z); + if (blocks.isTerrain(state)) { + return y; + } + if (!blocks.isAir(state) && !blocks.holdsFluid(state)) { + return Integer.MIN_VALUE; + } + } + return Integer.MIN_VALUE; + } + + private static boolean intersectsVacuumOccupancy(Set occupiedCells, int x, int z, int minimumY, int maximumY) { + for (int y = minimumY; y <= maximumY; y++) { + if (occupiedCells.contains(TemplateFootprint.packedPosition(x, y, z))) { + return true; + } + } + return false; + } + + private static SurfaceResolution resolveVacuumSurface(VacuumFootprint footprint, int worldX, int worldZ, int originalY) { + long column = TemplateFootprint.columnKey(worldX, worldZ); + Integer cap = footprint.columnCaps().get(column); + VacuumAnchor local = footprint.anchors().get(column); + if (local != null && local.strength() > 1) { + int localTargetY = cap == null ? local.surfaceY() : Math.min(local.surfaceY(), cap); + if (localTargetY <= originalY) { + return new SurfaceResolution(originalY, false); + } + return new SurfaceResolution(localTargetY, localTargetY == local.surfaceY()); + } + long totalInfluence = 0L; + long weightedSurfaceY = 0L; + long maximumInfluence = 0L; + int radiusSquared = SURFACE_TERRAIN_RADIUS * SURFACE_TERRAIN_RADIUS; + for (int offsetX = -SURFACE_TERRAIN_RADIUS; offsetX <= SURFACE_TERRAIN_RADIUS; offsetX++) { + for (int offsetZ = -SURFACE_TERRAIN_RADIUS; offsetZ <= SURFACE_TERRAIN_RADIUS; offsetZ++) { + int horizontalDistanceSquared = offsetX * offsetX + offsetZ * offsetZ; + if (horizontalDistanceSquared > radiusSquared) { + continue; + } + VacuumAnchor anchor = footprint.anchors().get( + TemplateFootprint.columnKey(worldX + offsetX, worldZ + offsetZ)); + if (anchor == null || anchor.surfaceY() <= originalY) { + continue; + } + int verticalDistance = Math.abs(anchor.surfaceY() + 1 - originalY); + long distanceSquared = horizontalDistanceSquared + (long) verticalDistance * verticalDistance; + double factor = 0D; + if (distanceSquared <= radiusSquared) { + factor = surfaceFactor(Math.sqrt(distanceSquared)); + } + if (anchor.strength() > 1 && verticalDistance > SURFACE_TERRAIN_RADIUS) { + double rescueProgress = Math.min(1D, + (verticalDistance - SURFACE_TERRAIN_RADIUS) / (double) SURFACE_TERRAIN_RADIUS); + double rescueWeight = rescueProgress * rescueProgress * (3D - 2D * rescueProgress); + factor = Math.max(factor, surfaceFactor(Math.sqrt(horizontalDistanceSquared)) * rescueWeight); + } + long influence = Math.round(factor * SURFACE_TERRAIN_INFLUENCE_SCALE); + if (influence <= 0L) { + continue; + } + long weightedInfluence = influence * Math.max(1, anchor.strength()); + totalInfluence += weightedInfluence; + weightedSurfaceY += weightedInfluence * anchor.surfaceY(); + maximumInfluence = Math.max(maximumInfluence, influence); + } + } + if (totalInfluence == 0L) { + return new SurfaceResolution(originalY, false); + } + double blendedSurfaceY = weightedSurfaceY / (double) totalInfluence; + double factor = maximumInfluence / (double) SURFACE_TERRAIN_INFLUENCE_SCALE; + int targetY = (int) Math.round(originalY + ((blendedSurfaceY - originalY) * factor)); + if (cap != null) { + targetY = Math.min(targetY, cap); + } + return new SurfaceResolution(Math.max(originalY, targetY), false); + } + + private static double surfaceFactor(double distance) { + return Math.pow(1D - distance / SURFACE_TERRAIN_RADIUS, SURFACE_TERRAIN_FALLOFF); + } + + static void applySurfaceColumn(FitBlocks blocks, int x, int z, int originalY, int targetY, int worldMinY, + int worldMaxY, boolean requireRigidBaseSupport) { + if (targetY == originalY) { + if (requireRigidBaseSupport) { + ensureRigidBaseTerrain(blocks, x, z, targetY, worldMinY); + } + return; + } + SurfaceMaterials materials = resolveSurfaceMaterials(blocks, x, z, originalY, worldMinY); + if (targetY < originalY) { + BlockState clearedState = clearSurfaceDecorationAndResolveFill(blocks, x, z, originalY, worldMaxY); + for (int y = originalY; y > targetY; y--) { + blocks.set(x, y, z, clearedState); + } + blocks.set(x, targetY, z, materials.surface()); + if (requireRigidBaseSupport) { + ensureRigidBaseTerrain(blocks, x, z, targetY, worldMinY, materials); + } + return; + } + for (int y = originalY + 1; y < targetY; y++) { + if (!blocks.isTree(blocks.get(x, y, z))) { + blocks.set(x, y, z, materials.subsurface()); + } + } + if (!blocks.isTree(blocks.get(x, targetY, z))) { + blocks.set(x, targetY, z, materials.surface()); + } + if (requireRigidBaseSupport) { + ensureRigidBaseTerrain(blocks, x, z, targetY, worldMinY, materials); + } + } + + private static void ensureRigidBaseTerrain(FitBlocks blocks, int x, int z, int targetY, int worldMinY) { + int supportY = targetY - 1; + boolean targetIsTerrain = blocks.isTerrain(blocks.get(x, targetY, z)); + boolean supportIsTerrain = supportY < worldMinY || blocks.isTerrain(blocks.get(x, supportY, z)); + if (targetIsTerrain && supportIsTerrain) { + return; + } + SurfaceMaterials materials = resolveSurfaceMaterials(blocks, x, z, targetY, worldMinY); + ensureRigidBaseTerrain(blocks, x, z, targetY, worldMinY, materials); + } + + private static void ensureRigidBaseTerrain(FitBlocks blocks, int x, int z, int targetY, int worldMinY, + SurfaceMaterials materials) { + int supportY = targetY - 1; + if (!blocks.isTerrain(blocks.get(x, targetY, z))) { + blocks.set(x, targetY, z, materials.surface()); + } + if (supportY < worldMinY) { + return; + } + if (!blocks.isTerrain(blocks.get(x, supportY, z))) { + blocks.set(x, supportY, z, materials.subsurface()); + } + } + + private static BlockState clearSurfaceDecorationAndResolveFill(FitBlocks blocks, int x, int z, int originalY, + int worldMaxY) { + for (int y = originalY + 1; y <= worldMaxY; y++) { + BlockState state = blocks.get(x, y, z); + if (blocks.isAir(state)) { + return FitBlocks.AIR; + } + if (blocks.holdsFluid(state)) { + BlockState fluid = blocks.fluidOf(state); + if (!state.equals(fluid)) { + blocks.set(x, y, z, fluid); + } + return fluid; + } + if (blocks.isSolid(state) || blocks.isTree(state)) { + return FitBlocks.AIR; + } + blocks.set(x, y, z, FitBlocks.AIR); + } + return FitBlocks.AIR; + } + + private static SurfaceMaterials resolveSurfaceMaterials(FitBlocks blocks, int x, int z, int originalY, int worldMinY) { + BlockState surface = blocks.get(x, originalY, z); + BlockState subsurface = null; + for (int y = originalY - 1; y >= worldMinY; y--) { + BlockState candidate = blocks.get(x, y, z); + if (blocks.isTerrain(candidate)) { + subsurface = candidate; + break; + } + } + if (subsurface == null) { + subsurface = blocks.isTerrain(surface) ? surface : FitBlocks.STONE; + } + if (!blocks.isTerrain(surface)) { + surface = subsurface; + } + return new SurfaceMaterials(surface, subsurface); + } + + record SurfaceAnchor(int minX, int maxX, int minZ, int maxZ, int meetY, int strength) { + } + + private record SurfaceMaterials(BlockState surface, BlockState subsurface) { + } + + private record SurfaceResolution(int targetY, boolean rigidBaseSupport) { + } + + private record VacuumFootprint(Map anchors, Map columnCaps, + Set foundationBases, Set occupiedCells) { + } + + private record VacuumAnchor(int surfaceY, int strength) { + } + + /** The foundation bases VACUUM raised the terrain to, kept until the pieces are placed for the repair. */ + static final class VacuumFoundationPlan { + static final VacuumFoundationPlan EMPTY = new VacuumFoundationPlan(List.of(), Set.of()); + + private final List foundationBases; + private final Set occupiedCells; + + private VacuumFoundationPlan(List foundationBases, Set occupiedCells) { + this.foundationBases = foundationBases; + this.occupiedCells = occupiedCells; + } + + private static VacuumFoundationPlan create(Set packedBases, Set packedOccupancy, Box area) { + if (packedBases.isEmpty()) { + return EMPTY; + } + List bases = new ArrayList<>(packedBases.size()); + Set columns = new HashSet<>(); + for (long packedBase : packedBases) { + int x = TemplateFootprint.packedX(packedBase); + int z = TemplateFootprint.packedZ(packedBase); + if (!area.contains(x, TemplateFootprint.packedY(packedBase), z)) { + continue; + } + bases.add(packedBase); + columns.add(TemplateFootprint.columnKey(x, z)); + } + if (bases.isEmpty()) { + return EMPTY; + } + bases.sort((first, second) -> { + int yOrder = Integer.compare(TemplateFootprint.packedY(first), TemplateFootprint.packedY(second)); + return yOrder == 0 ? Long.compare(first, second) : yOrder; + }); + Set occupancy = new HashSet<>(); + for (long packedCell : packedOccupancy) { + if (columns.contains(TemplateFootprint.columnKey( + TemplateFootprint.packedX(packedCell), TemplateFootprint.packedZ(packedCell)))) { + occupancy.add(packedCell); + } + } + return new VacuumFoundationPlan(List.copyOf(bases), Set.copyOf(occupancy)); + } + } + + /** Bounds the template blocks one start may read for one fitting. */ + static final class TemplateCellBudget { + private final int maximum; + private int consumed; + + TemplateCellBudget(int maximum) { + if (maximum < 0) { + throw new IllegalArgumentException("Native structure surface template budget cannot be negative"); + } + this.maximum = maximum; + } + + void consume(int amount) { + if (amount < 0 || consumed > maximum - amount) { + throw TemplateBudgetExceeded.INSTANCE; + } + consumed += amount; + } + } + + static final class TemplateBudgetExceeded extends RuntimeException { + static final TemplateBudgetExceeded INSTANCE = new TemplateBudgetExceeded(); + + private TemplateBudgetExceeded() { + super(null, null, false, false); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/TemplateFootprint.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/TemplateFootprint.java new file mode 100644 index 000000000..8d6b107e8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/TemplateFootprint.java @@ -0,0 +1,98 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.structure.fit; + +import com.volmit.block.BlockState; +import com.volmit.vanilla.TemplateCells; + +import java.util.HashMap; +import java.util.Map; + +/** The lowest template cell of each column of a piece, the cells a structure stands on. */ +final class TemplateFootprint { + private static final int PACKED_HORIZONTAL_BITS = 26; + private static final int PACKED_VERTICAL_BITS = 12; + private static final long PACKED_HORIZONTAL_MASK = (1L << PACKED_HORIZONTAL_BITS) - 1L; + private static final long PACKED_VERTICAL_MASK = (1L << PACKED_VERTICAL_BITS) - 1L; + private static final int PACKED_X_OFFSET = PACKED_VERTICAL_BITS + PACKED_HORIZONTAL_BITS; + private static final int PACKED_Z_OFFSET = PACKED_VERTICAL_BITS; + + private TemplateFootprint() { + } + + /** The lowest cell of every column, removed blocks included. */ + static Map lowestCells(TemplateCells cells, FitPiece piece) { + Map lowest = new HashMap<>(); + for (int cell = 0; cell < cells.size(); cell++) { + keepLowest(lowest, cells, piece, cell); + } + return lowest; + } + + /** The lowest cell of every column that a structure can stand on. */ + static Map lowestSolidCells(TemplateCells cells, FitPiece piece, FitBlocks blocks) { + Map lowest = new HashMap<>(); + for (int cell = 0; cell < cells.size(); cell++) { + if (cells.removed(cell) || !blocks.isSolidBase(cells.state(cell))) { + continue; + } + keepLowest(lowest, cells, piece, cell); + } + return lowest; + } + + private static void keepLowest(Map lowest, TemplateCells cells, FitPiece piece, int cell) { + int y = piece.cellY(cells, cell); + long column = columnKey(cells.x(cell), cells.z(cell)); + Cell current = lowest.get(column); + if (current == null || y < current.y()) { + lowest.put(column, new Cell(cells.x(cell), y, cells.z(cell), cells.state(cell))); + } + } + + static long columnKey(int x, int z) { + return (long) x << 32 ^ z & 0xffffffffL; + } + + /** A block position packed the way the platform packs positions, so sets of them sort the platform's way. */ + static long packedPosition(int x, int y, int z) { + return ((long) x & PACKED_HORIZONTAL_MASK) << PACKED_X_OFFSET + | ((long) y & PACKED_VERTICAL_MASK) + | ((long) z & PACKED_HORIZONTAL_MASK) << PACKED_Z_OFFSET; + } + + static int packedX(long packed) { + return (int) (packed << (64 - PACKED_X_OFFSET - PACKED_HORIZONTAL_BITS) >> (64 - PACKED_HORIZONTAL_BITS)); + } + + static int packedY(long packed) { + return (int) (packed << (64 - PACKED_VERTICAL_BITS) >> (64 - PACKED_VERTICAL_BITS)); + } + + static int packedZ(long packed) { + return (int) (packed << (64 - PACKED_Z_OFFSET - PACKED_HORIZONTAL_BITS) >> (64 - PACKED_HORIZONTAL_BITS)); + } + + /** A template cell at its world position; no state for a block the processors removed. */ + record Cell(int x, int y, int z, BlockState state) { + boolean blocker() { + return state == null; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java b/module/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java new file mode 100644 index 000000000..b97e597ed --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java @@ -0,0 +1,64 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.vanillafeatures; + +import art.arcane.iris.builtin.RegistryKeyFamily; +import art.arcane.iris.modules.vanillafeatures.ImportedFeaturesSettings; +import com.volmit.resource.ResourceId; +import com.volmit.service.VanillaFeatures; +import com.volmit.vanilla.DecorationStep; +import com.volmit.world.PackWorld; + +import java.util.Optional; + +/** + * What a dimension's {@link ImportedFeaturesSettings} say about the platform's own placed features: whether they run, + * and which decoration steps and features they leave out. A dimension without the settings runs none. + */ +public final class ImportedFeatures implements VanillaFeatures { + private static final ImportedFeaturesSettings NONE = new ImportedFeaturesSettings(); + + @Override + public boolean generates(PackWorld world) { + return settings(world).enabled(); + } + + /** A step the API does not name is allowed unless the dimension narrowed generation to listed steps. */ + @Override + public boolean generatesStep(PackWorld world, Optional step) { + ImportedFeaturesSettings settings = settings(world); + if (step.isEmpty()) { + return settings.steps().isEmpty(); + } + if (!settings.steps().isEmpty() && !settings.steps().contains(step.get())) { + return false; + } + return !settings.disabledSteps().contains(step.get()); + } + + @Override + public boolean generatesFeature(PackWorld world, ResourceId feature) { + String key = feature.toString(); + return settings(world).disabled().stream().noneMatch(pattern -> RegistryKeyFamily.matches(pattern, key)); + } + + private static ImportedFeaturesSettings settings(PackWorld world) { + return world.settings().declared(ImportedFeaturesSettings.class).dimension().orElse(NONE); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java b/module/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java new file mode 100644 index 000000000..74fe3ea30 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java @@ -0,0 +1,47 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework.vanillafeatures; + +import art.arcane.iris.modules.vanillafeatures.ImportedFeaturesSettings; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.service.VanillaFeatures; + +/** + * Module {@code iris:vanilla-features}: whether the platform's own placed features (ores, trees, plants, springs) run + * over a dimension's terrain, and which steps and features they leave out, decided from the dimension's + * {@code importedFeatures} settings and answered through {@link VanillaFeatures} ({@link ImportedFeatures}). The + * platform runs the feature pass itself; the module has no stages. + */ +public final class VanillaFeaturesModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:vanilla-features", "Vanilla features", VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + var registry = setup.registry(); + registry.registerSettings(ImportedFeaturesSettings.class); + registry.registerService(VanillaFeatures.class, new ImportedFeatures()); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/loot/BlockBiomes.java b/module/src/main/java/art/arcane/iris/engine/loot/BlockBiomes.java new file mode 100644 index 000000000..40d1748f8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/loot/BlockBiomes.java @@ -0,0 +1,52 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import com.volmit.IrisFeature; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.world.RunningWorld; +import com.volmit.world.TerrainSampler; + +import java.util.Optional; + +/** + * The biome of a block in a running world, as block drops and ambient effects read it: the cave biome where the block + * lies at least two blocks under the column's highest solid block, the surface biome everywhere else. + */ +public final class BlockBiomes { + private static final int CAVE_DEPTH_BELOW_HIGHEST_BLOCK = 2; + + private BlockBiomes() { + } + + public static ResourceId biomeAt(RunningWorld running, int x, int y, int z) { + TerrainSampler layout = running.layout(); + ResourceId surface = layout.surfaceBiome(x, z); + if (!layout.bounds().contains(x, y, z) || y > running.highest(x, z, true) - CAVE_DEPTH_BELOW_HIGHEST_BLOCK) { + return surface; + } + return layout.caveBiome(x, y, z).orElse(surface); + } + + /** The settings the biome of the block declares; empty when it declares none. */ + public static Optional declaredAt(RunningWorld running, Class type, BlockPosition at) { + return running.settings().declaredBy(biomeAt(running, at.x(), at.y(), at.z()), type); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java b/module/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java new file mode 100644 index 000000000..6f0e4caf8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java @@ -0,0 +1,96 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.modules.loot.BlockDrop; +import art.arcane.iris.modules.loot.BlockDropSettings; +import art.arcane.iris.builtin.loot.LootEntry; +import art.arcane.iris.builtin.loot.LootResolver; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.item.ItemDrop; +import com.volmit.service.BlockDrops; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * How {@code iris:loot} drops items for broken blocks: the block drops of the biome, the region and the dimension, the + * biome's first and the biome able to keep the others from dropping. + */ +public final class BlockDropping implements BlockDrops { + @Override + public Result drops(PackWorld world, Broken broken) { + RunningWorld running = world.running().orElseThrow(); + String brokenKey = world.resources().blocks().find(broken.block().key()).orElse(broken.block()).key(); + ResolvedDrops resolved = world.state(ResolvedDrops.class, ignored -> new ResolvedDrops()); + SettingsStack column = running.settings().at(BlockDropSettings.class, broken.position().x(), broken.position().z()); + + List providers = dropsFor(BlockBiomes.declaredAt(running, BlockDropSettings.class, broken.position()), brokenKey, resolved, world); + if (providers.stream().noneMatch(provider -> provider.drop().skipParents())) { + providers.addAll(dropsFor(column.level(Level.REGION), brokenKey, resolved, world)); + providers.addAll(dropsFor(column.dimension(), brokenKey, resolved, world)); + } + + LootItems items = new LootItems(world.resources().items(), false, world.log()); + List drops = new ArrayList<>(); + providers.forEach(provider -> fillDrops(provider.drop(), items, drops)); + return new Result(drops, providers.stream().anyMatch(provider -> provider.drop().replaceVanillaDrops())); + } + + /** Adds the items of the drops that pass their rarity to {@code into}. */ + private static void fillDrops(BlockDrop drop, LootItems items, List into) { + for (LootEntry entry : drop.drops()) { + if (!LootResolver.oneIn(RNG.r, entry.rarity())) { + continue; + } + ItemDrop given = items.give(entry, RNG.r); + if (given != null) { + into.add(given); + } + } + } + + private static List dropsFor(Optional declared, String brokenKey, ResolvedDrops resolved, + PackWorld world) { + List matching = new ArrayList<>(); + for (BlockDrop drop : declared.map(BlockDropSettings::drops).orElse(List.of())) { + ResolvedBlockDrop candidate = resolved.of(drop, world); + if (candidate.dropsFor(brokenKey)) { + matching.add(candidate); + } + } + return matching; + } + + /** The drops of the world with their blocks resolved, once per drop. */ + private static final class ResolvedDrops { + private final ConcurrentMap byDrop = new ConcurrentHashMap<>(); + + private ResolvedBlockDrop of(BlockDrop drop, PackWorld world) { + return byDrop.computeIfAbsent(drop, key -> ResolvedBlockDrop.of(key, world.resources().blocks())); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/module/src/main/java/art/arcane/iris/engine/loot/LootGiving.java new file mode 100644 index 000000000..32c715e73 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -0,0 +1,95 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.builtin.loot.LootResolver; +import art.arcane.iris.builtin.loot.LootTable; +import art.arcane.iris.engine.loot.PlacedObjectLoot.ObjectLoots; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.item.ItemDrop; +import com.volmit.resource.ResourceId; +import com.volmit.service.Loot; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.OptionalLong; + +/** + * How {@code iris:loot} fills containers: the tables of the object placed around a container, then those of the + * dimension, region and biomes at its column, and the items each table gives. Draws are deterministic per container, so + * a container always holds the same loot. + */ +public final class LootGiving implements Loot { + @Override + public List tables(PackWorld world, Site site) { + int x = site.position().x(); + int z = site.position().z(); + int relativeY = site.position().y(); + int worldY = relativeY + world.minWorldY(); + RNG rng = LootResolver.containerRng(lootSeed(world), x, worldY, z); + + List sources = new ArrayList<>(); + boolean objectLootDefined = site.nativeLootDefined(); + Optional objectLoots = site.container().isEmpty() ? Optional.empty() + : PlacedObjectLoot.at(world, x, relativeY, z); + if (objectLoots.isPresent()) { + objectLootDefined = objectLootDefined || objectLoots.get().defined(); + Source picked = placementLoot(world).pick(objectLoots.get().platformTables(), objectLoots.get().packTables(), + site.container().get(), rng, x, worldY, z); + if (picked != null) { + sources.add(picked); + if (objectLoots.get().overridesGlobalLoot()) { + return sources; + } + } + } + + LootTables.resolveEnvironmentSources(sources, world, rng, x, relativeY, z, objectLootDefined, + key -> new Table(world.resources().idOf(key))); + return sources; + } + + @Override + public List items(PackWorld world, Site site, ResourceId tableId) { + LootTable table = LootResources.table(world.resources(), tableId); + if (table == null) { + return List.of(); + } + int worldY = site.position().y() + world.minWorldY(); + return new LootItems(world.resources().items(), site.debug(), world.log()) + .draw(tableId, table, lootSeed(world), site.position().x(), worldY, site.position().z()); + } + + @Override + public OptionalLong shuffleSeed(PackWorld world, Site site) { + int worldY = site.position().y() + world.minWorldY(); + return OptionalLong.of(LootResolver.containerSeed(lootSeed(world), site.position().x(), worldY, site.position().z())); + } + + private static PlacementLoot placementLoot(PackWorld world) { + return new PlacementLoot(world.resources(), () -> world.running().orElseThrow().platformLootTables(), lootSeed(world), world.log()); + } + + private static long lootSeed(PackWorld world) { + return world.seed(IrisSeedPurposes.LOOT); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/loot/LootItems.java b/module/src/main/java/art/arcane/iris/engine/loot/LootItems.java new file mode 100644 index 000000000..c83373b2d --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/loot/LootItems.java @@ -0,0 +1,185 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.builtin.loot.ItemAttributeModifier; +import art.arcane.iris.builtin.loot.LootEnchantment; +import art.arcane.iris.builtin.loot.LootEntry; +import art.arcane.iris.builtin.loot.LootSlot; +import art.arcane.iris.builtin.loot.LootTable; +import art.arcane.iris.builtin.loot.LootResolver; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.item.ItemAttribute; +import com.volmit.item.ItemDrop; +import com.volmit.item.ItemEnchantment; +import com.volmit.item.ItemRegistry; +import com.volmit.resource.ContentKey; +import com.volmit.resource.ResourceId; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.OptionalDouble; +import java.util.OptionalInt; + +/** + * Turns loot entries into the items they give: every random choice is made here, in the order Iris always made them + * (amount, enchantments, attribute modifiers, damage), so that a container's loot stays what it was. What the platform + * must do with the result is the host's. + */ +public final class LootItems { + private static final ContentKey AIR = new ContentKey.Registered(ResourceId.parse("minecraft:air")); + private static final int MIN_AMOUNT = 1; + + private final ItemRegistry items; + private final boolean debug; + private final ModuleLog log; + + /** + * @param debug whether the items say where they came from + * @param log hears of keys that name nothing the platform could have + */ + public LootItems(ItemRegistry items, boolean debug, ModuleLog log) { + this.items = items; + this.debug = debug; + this.log = log; + } + + /** + * The items {@code table}, which the pack names {@code tableKey}, gives at the spot {@code x}, {@code y}, {@code z} + * (world coordinates): picks entries from the table's own random stream until it has the number of items the table + * asks for or runs out of tries. + */ + public List draw(String tableKey, LootTable table, long lootSeed, int x, int y, int z) { + return draw(tableKey, Optional.empty(), table, lootSeed, x, y, z); + } + + /** As {@link #draw(String, LootTable, long, int, int, int)} for the pack table {@code tableId}, which the items name as their source. */ + public List draw(ResourceId tableId, LootTable table, long lootSeed, int x, int y, int z) { + return draw(tableId.path(), Optional.of(tableId), table, lootSeed, x, y, z); + } + + private List draw(String tableKey, Optional tableId, LootTable table, long lootSeed, int x, int y, int z) { + List drops = new ArrayList<>(); + List entries = table.loot(); + if (entries.isEmpty() || table.maxTries() <= 0) { + return drops; + } + + String identity = LootTables.identity(tableKey); + RNG rng = LootTables.rng(lootSeed, identity, x, y, z); + int wanted = Math.max(0, LootResolver.inclusive(rng, table.minPicked(), table.maxPicked())); + int tries = 0; + while (drops.size() < wanted && tries++ < table.maxTries()) { + int index = rng.nextInt(entries.size()); + LootEntry entry = entries.get(index); + if (entry == null || entry.slotTypes() != LootSlot.STORAGE) { + continue; + } + ItemDrop drop = drawEntry(entry, table, tableId, identity, rng, lootSeed, index, x, y, z); + if (drop != null) { + drops.add(drop); + } + } + return drops; + } + + /** The item {@code entry} gives when nothing else decides whether it does, such as a block's drop or a mob's equipment; null for no item. */ + public ItemDrop give(LootEntry entry, RNG rng) { + return resolve(entry, rng, null, Optional.empty()); + } + + /** The attribute modifiers that pass their chances, with their amounts drawn, as for an item or an entity. */ + public List attributes(List modifiers, RNG rng) { + List attributes = new ArrayList<>(); + for (ItemAttributeModifier modifier : modifiers) { + if (rng.nextDouble() >= modifier.chance()) { + continue; + } + String attribute = modifier.attribute(); + if (attribute == null || attribute.isBlank()) { + continue; + } + double amount = rng.d(modifier.minAmount(), modifier.maxAmount()); + PlatformKeys.id(attribute, log).ifPresent(id -> attributes.add( + new ItemAttribute(id, modifier.name(), PlatformKeys.operation(modifier.operation()), amount))); + } + return attributes; + } + + private ItemDrop drawEntry(LootEntry entry, LootTable table, Optional tableId, String identity, RNG rng, long lootSeed, + int index, int x, int y, int z) { + long combinedRarity = LootResolver.combinedRarity(entry.rarity(), table.rarity()); + if (!LootTables.spatialOneIn(lootSeed, identity, index, x, y, z, combinedRarity)) { + return null; + } + return resolve(entry, rng, table, tableId); + } + + private ItemDrop resolve(LootEntry entry, RNG rng, LootTable table, Optional tableId) { + Optional item = PlatformKeys.item(entry.type(), log); + if (item.isEmpty() || item.get().equals(AIR)) { + return null; + } + OptionalInt maxDurability = items.maxDurability(item.get()); + if (maxDurability.isEmpty()) { + return null; + } + + int amount = Math.max(MIN_AMOUNT, LootResolver.inclusive(rng, entry.minAmount(), entry.maxAmount())); + List enchantments = drawEnchantments(entry, rng); + List attributes = attributes(entry.attributes(), rng); + OptionalDouble damage = maxDurability.getAsInt() > 0 + ? OptionalDouble.of(1D - rng.d(entry.minDurability(), entry.maxDurability())) + : OptionalDouble.empty(); + return new ItemDrop(item.get(), amount, lookOf(entry), enchantments, attributes, new ItemDrop.Wear(entry.unbreakable(), damage), + new ItemDrop.PlatformExtras(entry.itemFlags(), Objects.requireNonNullElse(entry.customNbt(), Map.of())), + debug ? Optional.of(sourceOf(entry, table, tableId)) : Optional.empty()); + } + + private ItemDrop.Look lookOf(LootEntry entry) { + Integer customModel = entry.customModel(); + return new ItemDrop.Look(Optional.ofNullable(entry.displayName()), entry.lore(), + customModel == null ? OptionalInt.empty() : OptionalInt.of(customModel), + PlatformKeys.rgb(entry.leatherColor(), log), PlatformKeys.dye(entry.dyeColor(), log)); + } + + private List drawEnchantments(LootEntry entry, RNG rng) { + List enchantments = new ArrayList<>(); + for (LootEnchantment enchantment : entry.enchantments()) { + String key = enchantment.enchantment(); + if (key == null || key.isBlank() || rng.nextDouble() >= enchantment.chance()) { + continue; + } + int level = Math.max(1, LootResolver.inclusive(rng, enchantment.minLevel(), enchantment.maxLevel())); + PlatformKeys.id(key, log).ifPresent(id -> enchantments.add(new ItemEnchantment(id, level))); + } + return enchantments; + } + + private static ItemDrop.Source sourceOf(LootEntry entry, LootTable table, Optional tableId) { + if (table == null) { + return new ItemDrop.Source(Optional.empty(), 0, entry.rarity()); + } + return new ItemDrop.Source(tableId, table.rarity(), entry.rarity()); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/loot/LootModule.java b/module/src/main/java/art/arcane/iris/engine/loot/LootModule.java new file mode 100644 index 000000000..4ede6484f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/loot/LootModule.java @@ -0,0 +1,53 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.modules.loot.BlockDropSettings; +import art.arcane.iris.builtin.loot.LootSettings; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.service.BlockDrops; +import com.volmit.service.Loot; + +/** + * Module {@code iris:loot}: the loot tables of the pack ({@link LootResources}), the {@link LootSettings} and + * {@link BlockDropSettings} that dimensions, regions and biomes declare, and the items they give. It checks the tables + * and the references to them ({@link LootValidator}). It has no generation stage; Iris asks it through {@link Loot} when + * a container is filled and through {@link BlockDrops} when a player breaks a block. + */ +public final class LootModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:loot", "Loot", VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + var registry = setup.registry(); + registry.registerSettings(LootSettings.class); + registry.registerSettings(BlockDropSettings.class); + LootResources.kinds().forEach(registry::registerResourceKind); + registry.registerValidator(new LootValidator()); + registry.registerService(Loot.class, new LootGiving()); + registry.registerService(BlockDrops.class, new BlockDropping()); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/loot/LootResources.java b/module/src/main/java/art/arcane/iris/engine/loot/LootResources.java new file mode 100644 index 000000000..226380a25 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/loot/LootResources.java @@ -0,0 +1,67 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.builtin.loot.LootTable; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; + +import java.util.List; + +/** + * The resource kind of module {@code iris:loot}, which keeps the folder and files Iris packs have always used, and + * lookups by pack key for code that still names loot tables by key. Every lookup goes through the pack's + * {@link com.volmit.resource.PackResources}, so it sees the pack's current snapshot. + *

+ * Lookups answer null where Iris's loader did: for a blank key, a key the pack has no file for, and a file that fails + * to load, which was reported when it was read. + */ +public final class LootResources { + /** Loot tables, in {@code loot/}. */ + public static final ResourceKind TABLES = ResourceKind.of("iris:loot/table", "loot", LootTable.class); + + private LootResources() { + } + + /** Every resource kind of the loot module. */ + public static List> kinds() { + return List.of(TABLES); + } + + public static LootTable table(PackResources resources, String key) { + if (key == null || key.isBlank()) { + return null; + } + return table(resources, resources.idOf(key)); + } + + public static LootTable table(PackResources resources, ResourceId id) { + try { + return resources.find(TABLES, id).orElse(null); + } catch (IllegalStateException failedToLoad) { + return null; + } + } + + /** The key of every loot table of the pack, in key order. */ + public static List tableKeys(PackResources resources) { + return resources.ids(TABLES).stream().map(ResourceId::path).toList(); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/loot/LootTables.java b/module/src/main/java/art/arcane/iris/engine/loot/LootTables.java new file mode 100644 index 000000000..b82a8a6b7 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/loot/LootTables.java @@ -0,0 +1,158 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.builtin.loot.LootMode; +import art.arcane.iris.builtin.loot.LootResolver; +import art.arcane.iris.builtin.loot.LootSettings; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; +import com.volmit.world.TerrainSampler; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Function; + +/** + * Which loot tables a place in the world draws from, and the random streams that draw from them: the part of loot + * that reads the pack's tables, loot settings and layout. The streams themselves are {@link LootResolver}'s; here a + * table is named by its {@linkplain #identity identity}, the key the pack names it by. + */ +public final class LootTables { + private static final String VANILLA_IDENTITY_PREFIX = "Vanilla "; + + private LootTables() { + } + + /** What names a table in the random streams: the key a pack table is named by. */ + public static String identity(String tableKey) { + return tableKey; + } + + /** What names a table of the platform in the random streams. */ + public static String platformIdentity(String platformKey) { + return VANILLA_IDENTITY_PREFIX + platformKey; + } + + public static RNG rng(long lootSeed, String identity, int x, int y, int z) { + return LootResolver.tableRng(lootSeed, identity, x, y, z); + } + + public static long seed(long lootSeed, String identity, int x, int y, int z) { + return LootResolver.tableSeed(lootSeed, identity, x, y, z); + } + + public static boolean spatialOneIn(long lootSeed, String identity, int entryIndex, int x, int y, int z, long rarity) { + return LootResolver.spatialOneIn(lootSeed, identity, entryIndex, x, y, z, rarity); + } + + /** The declared loot settings; the defaults, which add nothing, when none are declared. */ + private static LootSettings orDefaults(Optional declared) { + return declared.orElseGet(LootSettings::new); + } + + /** The cave biome of a block under the terrain's surface, when it is not the column's surface biome. */ + private static Optional distinctCaveBiome(TerrainSampler layout, int x, int relativeY, int z) { + if (relativeY >= layout.surfaceY(x, z) || !layout.bounds().contains(x, relativeY, z)) { + return Optional.empty(); + } + ResourceId surface = layout.surfaceBiome(x, z); + return layout.caveBiome(x, relativeY, z).filter(cave -> !cave.equals(surface)); + } + + /** + * Adds the tables of the dimension, the region, the surface biome and (below the surface) the cave biome at a + * column to {@code sources}, as their loot settings say, then scales their number by the areas' multipliers. + * {@code mapper} turns the key of a table into the caller's own source; a null result skips it. + */ + public static void resolveEnvironmentSources( + List sources, + PackWorld world, + RNG rng, + int x, + int relativeY, + int z, + boolean objectLootDefined, + Function mapper + ) { + RunningWorld running = world.running().orElseThrow(); + Optional distinctCaveBiome = distinctCaveBiome(running.layout(), x, relativeY, z); + SettingsStack column = running.settings().at(LootSettings.class, x, z); + + LootSettings dimensionLoot = orDefaults(column.dimension()); + LootSettings regionLoot = orDefaults(column.level(Level.REGION)); + LootSettings surfaceLoot = orDefaults(column.level(Level.BIOME)); + double multiplier = dimensionLoot.multiplier() * regionLoot.multiplier() * surfaceLoot.multiplier(); + LootSettings contextualLoot = distinctCaveBiome + .map(cave -> orDefaults(running.settings().declaredBy(cave, LootSettings.class))) + .orElse(null); + if (contextualLoot != null) { + multiplier *= contextualLoot.multiplier(); + } + + boolean fallback = !objectLootDefined; + injectReference(sources, dimensionLoot, world, mapper, fallback); + injectReference(sources, regionLoot, world, mapper, fallback); + injectReference(sources, surfaceLoot, world, mapper, fallback); + if (contextualLoot != null) { + injectReference(sources, contextualLoot, world, mapper, fallback); + } + LootResolver.scaleSources(sources, multiplier, rng); + } + + /** Adds {@code additions} to {@code sources} the way {@code mode} says; {@code fallback} is whether nothing else defined a table. */ + public static void injectSources( + List sources, + List additions, + LootMode mode, + boolean fallback + ) { + if (mode == LootMode.FALLBACK && !fallback) { + return; + } + if (mode == LootMode.CLEAR) { + sources.clear(); + return; + } + if (mode == LootMode.REPLACE) { + sources.clear(); + } + sources.addAll(additions); + } + + private static void injectReference( + List sources, + LootSettings loot, + PackWorld world, + Function mapper, + boolean fallback + ) { + List additions = loot.tables().stream() + .filter(key -> LootResources.table(world.resources(), key) != null) + .map(mapper) + .filter(Objects::nonNull) + .toList(); + injectSources(sources, additions, loot.mode(), fallback); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/loot/LootValidator.java b/module/src/main/java/art/arcane/iris/engine/loot/LootValidator.java new file mode 100644 index 000000000..2bac6afc5 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/loot/LootValidator.java @@ -0,0 +1,227 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.builtin.loot.LootEnchantment; +import art.arcane.iris.builtin.loot.LootEntry; +import art.arcane.iris.builtin.loot.LootMode; +import art.arcane.iris.builtin.loot.LootSettings; +import art.arcane.iris.builtin.loot.LootTable; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.validation.Problem; +import com.volmit.validation.Subject; +import com.volmit.validation.ValidationContext; +import com.volmit.validation.Validator; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import java.util.function.BiFunction; + +/** + * Module {@code iris:loot}'s check of a pack: every loot table has sane picks, tries and entries, and every loot + * reference of a dimension, region or biome names a table the pack has. It checks the tables and settings as they + * decoded; a file that is not valid JSON, or holds a value of the wrong type, fails to load, and the check reports why. + */ +public final class LootValidator implements Validator { + private static final String JSON_EXTENSION = ".json"; + private static final String LEVEL_FOLDER_SEPARATOR = "/"; + + @Override + public void validate(ValidationContext pack) { + checkTables(pack.resources()).forEach(pack::report); + checkReferences(pack).forEach(pack::report); + } + + private static List checkTables(PackResources resources) { + List problems = new ArrayList<>(); + for (ResourceId id : resources.ids(LootResources.TABLES)) { + String lootKey = id.path(); + List errors = new ArrayList<>(); + LootTable table = readTable(resources, id, lootKey, errors); + if (table != null) { + validateLootTable(lootKey, table, errors); + } + report(problems, Problem::error, Subject.file(LootResources.TABLES.folder() + "/" + lootKey + JSON_EXTENSION), errors); + } + return problems; + } + + private static List checkReferences(ValidationContext pack) { + Set lootIds = Set.copyOf(pack.resources().ids(LootResources.TABLES)); + List problems = new ArrayList<>(); + List> declared = new ArrayList<>(pack.settings().declared(LootSettings.class).entries()); + declared.sort(Comparator.comparing(Entry::level).thenComparing(Entry::source)); + for (Entry entry : declared) { + String resourceKey = keyOf(entry); + List errors = new ArrayList<>(); + List warnings = new ArrayList<>(); + validateLootReference(pack.resources(), hostType(entry.level()), resourceKey, entry.value(), lootIds, errors, warnings); + Subject subject = Subject.file(folderOf(entry.level()) + "/" + resourceKey + JSON_EXTENSION); + report(problems, Problem::error, subject, errors); + report(problems, Problem::warning, subject, warnings); + } + return problems; + } + + private static void report(List problems, BiFunction severity, + Subject subject, List messages) { + for (String message : messages) { + problems.add(severity.apply(subject, message)); + } + } + + private static LootTable readTable(PackResources resources, ResourceId id, String key, List errors) { + try { + return resources.find(LootResources.TABLES, id).orElse(null); + } catch (IllegalStateException failedToLoad) { + errors.add("Loot table '" + key + "' cannot be read: " + failedToLoad.getMessage()); + return null; + } + } + + /** The key of the dimension, region or biome that declared {@code entry}: its source id is {@code :/}. */ + private static String keyOf(Entry entry) { + String path = entry.source().path(); + return path.substring(path.indexOf(LEVEL_FOLDER_SEPARATOR) + 1); + } + + private static String hostType(Level level) { + return switch (level) { + case DIMENSION -> "Dimension"; + case REGION -> "Region"; + case BIOME -> "Biome"; + case PLACEMENT -> "Resource"; + }; + } + + private static String folderOf(Level level) { + return switch (level) { + case DIMENSION -> "dimensions"; + case REGION -> "regions"; + case BIOME -> "biomes"; + case PLACEMENT -> "placements"; + }; + } + + private static void validateLootTable(String lootKey, LootTable table, List blockingErrors) { + String path = "Loot table '" + lootKey + "'"; + requireMinimum(path + ".rarity", table.rarity(), 1, blockingErrors); + requireMinimum(path + ".minPicked", table.minPicked(), 0, blockingErrors); + requireMinimum(path + ".maxPicked", table.maxPicked(), 1, blockingErrors); + requireMinimum(path + ".maxTries", table.maxTries(), 1, blockingErrors); + requireMaximum(path + ".minPicked", table.minPicked(), LootTable.MAX_PICKED, blockingErrors); + requireMaximum(path + ".maxPicked", table.maxPicked(), LootTable.MAX_PICKED, blockingErrors); + requireMaximum(path + ".maxTries", table.maxTries(), LootTable.MAX_TRIES, blockingErrors); + requireOrdered(path + ".minPicked", table.minPicked(), path + ".maxPicked", table.maxPicked(), blockingErrors); + + List entries = table.loot(); + if (entries.isEmpty()) { + blockingErrors.add(path + ".loot must be a non-empty array."); + return; + } + for (int entryIndex = 0; entryIndex < entries.size(); entryIndex++) { + validateLootEntry(path + ".loot[" + entryIndex + "]", entries.get(entryIndex), blockingErrors); + } + } + + private static void validateLootEntry(String entryPath, LootEntry entry, List blockingErrors) { + if (entry == null) { + blockingErrors.add(entryPath + " must be an object."); + return; + } + if (entry.type().trim().isEmpty()) { + blockingErrors.add(entryPath + ".type must not be blank."); + } + requireMinimum(entryPath + ".rarity", entry.rarity(), 1, blockingErrors); + requireMinimum(entryPath + ".minAmount", entry.minAmount(), 1, blockingErrors); + requireMinimum(entryPath + ".maxAmount", entry.maxAmount(), 1, blockingErrors); + requireMaximum(entryPath + ".minAmount", entry.minAmount(), LootEntry.MAX_AMOUNT, blockingErrors); + requireMaximum(entryPath + ".maxAmount", entry.maxAmount(), LootEntry.MAX_AMOUNT, blockingErrors); + requireOrdered(entryPath + ".minAmount", entry.minAmount(), entryPath + ".maxAmount", entry.maxAmount(), blockingErrors); + + List enchantments = entry.enchantments(); + for (int enchantmentIndex = 0; enchantmentIndex < enchantments.size(); enchantmentIndex++) { + validateEnchantment(entryPath + ".enchantments[" + enchantmentIndex + "]", enchantments.get(enchantmentIndex), blockingErrors); + } + } + + private static void validateEnchantment(String enchantmentPath, LootEnchantment enchantment, List blockingErrors) { + if (enchantment == null) { + blockingErrors.add(enchantmentPath + " must be an object."); + return; + } + String name = enchantment.enchantment(); + if (name == null || name.isBlank()) { + blockingErrors.add(enchantmentPath + ".enchantment must not be blank."); + } + requireMinimum(enchantmentPath + ".minLevel", enchantment.minLevel(), 1, blockingErrors); + requireMinimum(enchantmentPath + ".maxLevel", enchantment.maxLevel(), 1, blockingErrors); + requireOrdered(enchantmentPath + ".minLevel", enchantment.minLevel(), + enchantmentPath + ".maxLevel", enchantment.maxLevel(), blockingErrors); + double chance = enchantment.chance(); + if (!Double.isFinite(chance) || chance < 0D || chance > 1D) { + blockingErrors.add(enchantmentPath + ".chance must be a finite number from 0 to 1."); + } + } + + private static void validateLootReference(PackResources resources, String resourceType, String resourceKey, LootSettings reference, + Set lootIds, List blockingErrors, List warnings) { + String path = resourceType + " '" + resourceKey + "'.loot"; + double multiplier = reference.multiplier(); + if (!Double.isFinite(multiplier) || multiplier < 0D || multiplier > LootSettings.MAX_MULTIPLIER) { + blockingErrors.add(path + ".multiplier must be a finite number from 0 to " + (int) LootSettings.MAX_MULTIPLIER + "."); + } + List tables = reference.tables(); + if (reference.mode() == LootMode.CLEAR && !tables.isEmpty()) { + warnings.add(path + " uses mode CLEAR and lists " + tables.size() + + " table(s); CLEAR clears parent tables and contributes no tables of its own, so these entries are dead. Use REPLACE to substitute them."); + } + for (int tableIndex = 0; tableIndex < tables.size(); tableIndex++) { + String tableKey = tables.get(tableIndex); + if (tableKey == null || tableKey.isBlank()) { + blockingErrors.add(path + ".tables[" + tableIndex + "] must name a loot table."); + } else if (!lootIds.contains(resources.idOf(tableKey))) { + blockingErrors.add(path + ".tables[" + tableIndex + "] references missing loot table '" + tableKey + "'."); + } + } + } + + private static void requireMinimum(String fieldPath, int value, int minimum, List blockingErrors) { + if (value < minimum) { + blockingErrors.add(fieldPath + " must be at least " + minimum + "."); + } + } + + private static void requireMaximum(String fieldPath, int value, int maximum, List blockingErrors) { + if (value > maximum) { + blockingErrors.add(fieldPath + " must be at most " + maximum + "."); + } + } + + private static void requireOrdered(String minimumPath, int minimum, String maximumPath, int maximum, List blockingErrors) { + if (minimum > maximum) { + blockingErrors.add(minimumPath + " must not exceed " + maximumPath + "."); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java b/module/src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java new file mode 100644 index 000000000..baba31c0f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java @@ -0,0 +1,107 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.builtin.loot.ObjectLoot; +import art.arcane.iris.builtin.loot.ObjectVanillaLoot; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.structure.StructureHost; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.placement.PlacementRecord; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * The loot of the object placed at a block, found from the placement the world recorded there: a structure piece gives + * its structure's tables; any other object the tables of the first placement of the column's region, then of its + * surface biome, that places it. Procedural objects give none. + */ +final class PlacedObjectLoot { + private static final String PROCEDURAL_PREFIX = "procedural/"; + private static final int STRUCTURE_TABLE_WEIGHT = 1; + + private PlacedObjectLoot() { + } + + /** + * The loot an object placement gives its containers. + * + * @param packTables tables of the pack + * @param platformTables tables of the platform + * @param overridesGlobalLoot whether the placement's tables replace those of the dimension, region and biomes + */ + record ObjectLoots(List packTables, List platformTables, boolean overridesGlobalLoot) { + ObjectLoots { + packTables = List.copyOf(packTables); + platformTables = List.copyOf(platformTables); + } + + /** Whether the placement names any table. */ + boolean defined() { + return !packTables.isEmpty() || !platformTables.isEmpty(); + } + } + + /** The loot of the object placed at the block; empty when no object placement covers the block. Y is above the dimension's bottom. */ + static Optional at(PackWorld world, int x, int y, int z) { + RunningWorld running = world.running().orElseThrow(); + Optional recorded = running.placementAt(x, y, z); + if (recorded.isEmpty() || recorded.get().object().path().startsWith(PROCEDURAL_PREFIX)) { + return Optional.empty(); + } + ResourceId object = recorded.get().object(); + Optional placement = recorded.get().structure().isPresent() + ? structurePlacement(world, recorded.get().structure().get(), object) + : columnPlacement(world.resources(), running.settings().at(ObjectSettings.class, x, z), object); + return placement.map(found -> new ObjectLoots(found.loot(), found.vanillaLoot(), found.overrideGlobalLoot())); + } + + /** A structure piece's object gives every table its structure names, each once. */ + private static Optional structurePlacement(PackWorld world, ResourceId structure, ResourceId object) { + Optional> tables = world.extension(StructureHost.class).orElseThrow().lootTables(structure); + if (tables.isEmpty() || world.resources().objects().object(object).isEmpty()) { + return Optional.empty(); + } + List loot = new ArrayList<>(); + for (String table : tables.get()) { + loot.add(new ObjectLoot(table, STRUCTURE_TABLE_WEIGHT)); + } + return Optional.of(ObjectPlacement.builder().place(List.of(object.path())).loot(loot).build()); + } + + private static Optional columnPlacement(PackResources resources, SettingsStack declared, + ResourceId object) { + Optional fromRegion = declared.level(Level.REGION).flatMap(settings -> placing(resources, settings, object)); + return fromRegion.isPresent() ? fromRegion : declared.level(Level.BIOME).flatMap(settings -> placing(resources, settings, object)); + } + + private static Optional placing(PackResources resources, ObjectSettings settings, ResourceId object) { + return settings.objects().stream() + .filter(placement -> placement.place().stream().anyMatch(key -> resources.idOf(key).equals(object))) + .findFirst(); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java b/module/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java new file mode 100644 index 000000000..4ddb14bea --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java @@ -0,0 +1,163 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.builtin.loot.LootResolver; +import art.arcane.iris.builtin.loot.ObjectLootEntry; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.service.Loot; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * The loot table an object placement gives to one of its containers: the placement's tables and the platform's own, + * each with the blocks it applies to and a weight. A table that names the container's exact block wins over one that + * names the container's kind of block, which wins over one that names no blocks; among equals the weights pick. + */ +final class PlacementLoot { + private static final String VANILLA_NAMESPACE = "minecraft:"; + private static final char NAMESPACE_SEPARATOR = ':'; + private static final char PROPERTIES_START = '['; + + private final PackResources resources; + private final Supplier> platformTables; + private final long lootSeed; + private final ModuleLog log; + + /** @param platformTables the ids of the loot tables the platform has, asked for only when a placement names one */ + PlacementLoot(PackResources resources, Supplier> platformTables, long lootSeed, ModuleLog log) { + this.resources = resources; + this.platformTables = platformTables; + this.lootSeed = lootSeed; + this.log = log; + } + + /** + * The table a placement, whose platform tables are {@code platformLoot} and whose pack tables are {@code packLoot}, + * gives {@code container}, a storage chest, at the spot {@code x}, {@code worldY}, {@code z}; null when it gives + * it none. + */ + Loot.Source pick(List platformLoot, List packLoot, BlockState container, + RNG rng, int x, int worldY, int z) { + Candidates candidates = new Candidates(resources.blocks().find(container.key()).orElse(container)); + add(candidates, platformLoot, name -> platformSource(name, x, worldY, z)); + add(candidates, packLoot, this::packSource); + List pool = candidates.pool(); + Candidate picked = LootResolver.pickWeighted(pool, Candidate::weight, rng); + return picked == null ? null : picked.source(); + } + + private void add(Candidates candidates, List entries, Function sourceOf) { + for (ObjectLootEntry entry : entries) { + if (entry == null || entry.weight() <= 0) { + continue; + } + Loot.Source source = sourceOf.apply(entry.name()); + if (source == null) { + log.warn("Couldn't find loot table " + entry.name()); + continue; + } + candidates.add(entry, resources, new Candidate(source, entry.weight())); + } + } + + private Loot.Source packSource(String key) { + return LootResources.table(resources, key) == null ? null : new Loot.Table(resources.idOf(key)); + } + + private Loot.Source platformSource(String name, int x, int worldY, int z) { + String key = platformKey(name); + ResourceId table = key == null ? null : platformTableId(key); + if (table == null || !platformTables.get().contains(table)) { + return null; + } + return new Loot.PlatformTable(table, LootTables.seed(lootSeed, LootTables.platformIdentity(key), x, worldY, z)); + } + + /** The id of the platform table the key names, or null for a key that is no id, which names no table. */ + private static ResourceId platformTableId(String key) { + try { + return ResourceId.parse(key); + } catch (IllegalArgumentException notAnId) { + return null; + } + } + + /** A placement's name for a platform table as the platform's key for it, or null for a name that cannot be one. */ + static String platformKey(String name) { + if (name == null || name.isBlank()) { + return null; + } + return name.indexOf(NAMESPACE_SEPARATOR) < 0 ? VANILLA_NAMESPACE + name : name; + } + + private record Candidate(Loot.Source source, int weight) { + } + + /** The candidates for one container, in the groups the placement gives them. */ + private static final class Candidates { + private final String containerKey; + private final String containerMaterial; + private final List exact = new ArrayList<>(); + private final List basic = new ArrayList<>(); + private final List global = new ArrayList<>(); + + private Candidates(BlockState container) { + this.containerKey = container.key(); + this.containerMaterial = materialOf(containerKey); + } + + void add(ObjectLootEntry entry, PackResources resources, Candidate candidate) { + List filter = entry.filter(); + if (filter.isEmpty()) { + global.add(candidate); + return; + } + for (BlockSpec filterSpec : filter) { + String filterKey = resources.blocks().resolve(filterSpec).key(); + if (entry.exact() && filterKey.equals(containerKey)) { + exact.add(candidate); + } else if (!entry.exact() && materialOf(filterKey).equals(containerMaterial)) { + basic.add(candidate); + } + } + } + + List pool() { + if (!exact.isEmpty()) { + return exact; + } + return basic.isEmpty() ? global : basic; + } + + private static String materialOf(String blockKey) { + int properties = blockKey.indexOf(PROPERTIES_START); + return properties < 0 ? blockKey : blockKey.substring(0, properties); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/loot/PlatformKeys.java b/module/src/main/java/art/arcane/iris/engine/loot/PlatformKeys.java new file mode 100644 index 000000000..82972017d --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/loot/PlatformKeys.java @@ -0,0 +1,130 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import com.volmit.ModuleLog; +import com.volmit.item.ItemAttribute; +import com.volmit.item.DyeColor; +import com.volmit.resource.ContentKey; +import com.volmit.resource.ResourceId; + +import java.util.Locale; +import java.util.Optional; +import java.util.OptionalInt; + +/** + * The platform things packs name, as they write them, turned into what IrisApi hands the host: ids, items and mobs, + * attribute operations and colours. A blank key names nothing; a key that names nothing the host could look up is left + * out with a warning, once per key. + */ +public final class PlatformKeys { + private static final String PLATFORM_NAMESPACE = "minecraft"; + private static final char NAMESPACE_SEPARATOR = ':'; + private static final String WARNING_KEY = "iris:platform-key/"; + + private PlatformKeys() { + } + + /** {@code key} as an id, such as {@code minecraft:sharpness} for {@code Sharpness}; see {@link ResourceId#ofPlatformKey}. */ + public static Optional id(String key, ModuleLog log) { + if (key == null || key.isBlank()) { + return Optional.empty(); + } + try { + return Optional.of(ResourceId.ofPlatformKey(key)); + } catch (IllegalArgumentException invalid) { + log.warnOnce(WARNING_KEY + key, "Ignoring '" + key + "': it names nothing the platform could have"); + return Optional.empty(); + } + } + + /** + * The item {@code key} names. A key of the platform's own namespace, or of none, is a registered item; so is a key of + * another namespace an id can hold as written, such as {@code itemsadder:ruby}, which the host routes to its owner. + * Any other namespaced key is a provider's item, kept as written. + */ + public static Optional item(String key, ModuleLog log) { + if (key == null || key.isBlank()) { + return Optional.empty(); + } + String written = key.trim(); + int separator = written.indexOf(NAMESPACE_SEPARATOR); + if (separator < 0 || PLATFORM_NAMESPACE.equalsIgnoreCase(written.substring(0, separator))) { + return id(written, log).map(ContentKey.Registered::new); + } + try { + return Optional.of(new ContentKey.Registered(ResourceId.parse(written))); + } catch (IllegalArgumentException notAnId) { + return provided(written, log); + } + } + + /** A provider's mob or item, written {@code provider:name}, such as {@code mythicmobs:SkeletonKing}. */ + public static Optional provided(String key, ModuleLog log) { + if (key == null || key.isBlank()) { + return Optional.empty(); + } + String written = key.trim(); + int separator = written.indexOf(NAMESPACE_SEPARATOR); + if (separator <= 0 || separator == written.length() - 1) { + log.warnOnce(WARNING_KEY + key, "Ignoring '" + key + "': a provider's content is written provider:name"); + return Optional.empty(); + } + return Optional.of(new ContentKey.Provided(written.substring(0, separator), written.substring(separator + 1))); + } + + /** + * The attribute operation packs name by Bukkit's names, {@code ADD_NUMBER}, {@code ADD_SCALAR} and + * {@code MULTIPLY_SCALAR_1}, or by the platform's own; adding the amount for a name it does not know. + */ + public static ItemAttribute.Operation operation(String name) { + String normalized = name == null ? "" : name.trim().toUpperCase(Locale.ROOT); + return switch (normalized) { + case "ADD_SCALAR", "ADD_MULTIPLIED_BASE" -> ItemAttribute.Operation.ADD_MULTIPLIED_BASE; + case "MULTIPLY_SCALAR_1", "ADD_MULTIPLIED_TOTAL" -> ItemAttribute.Operation.ADD_MULTIPLIED_TOTAL; + default -> ItemAttribute.Operation.ADD_VALUE; + }; + } + + /** The colour {@code text} writes, {@code #rrggbb}, {@code 0xrrggbb} or a number; empty, with a warning, for anything else. */ + public static OptionalInt rgb(String text, ModuleLog log) { + if (text == null || text.isBlank()) { + return OptionalInt.empty(); + } + try { + return OptionalInt.of(Integer.decode(text.trim()) & 0xFFFFFF); + } catch (NumberFormatException notAColour) { + log.warnOnce(WARNING_KEY + text, "Ignoring the colour '" + text + "': write it as #rrggbb"); + return OptionalInt.empty(); + } + } + + /** The dye colour {@code name} names, such as {@code RED} or {@code light_blue}; empty, with a warning, for anything else. */ + public static Optional dye(String name, ModuleLog log) { + if (name == null || name.isBlank()) { + return Optional.empty(); + } + try { + return Optional.of(DyeColor.valueOf(name.trim().toUpperCase(Locale.ROOT))); + } catch (IllegalArgumentException unknown) { + log.warnOnce(WARNING_KEY + name, "Ignoring the dye colour '" + name + "', which is none of the sixteen dyes"); + return Optional.empty(); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java b/module/src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java new file mode 100644 index 000000000..64eec7bc3 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java @@ -0,0 +1,67 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.modules.loot.BlockDrop; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockSpec; + +import java.util.LinkedHashSet; +import java.util.Set; + +/** A {@link BlockDrop} with the blocks it names resolved to the platform's: which broken blocks it drops for. */ +final class ResolvedBlockDrop { + private static final char PROPERTIES_START = '['; + + private final BlockDrop drop; + private final boolean exact; + private final Set blocks; + + private ResolvedBlockDrop(BlockDrop drop, Set blocks) { + this.drop = drop; + this.exact = drop.exactBlocks(); + this.blocks = blocks; + } + + /** @param blocks the pack's blocks, which the drop's block specs resolve against */ + static ResolvedBlockDrop of(BlockDrop drop, BlockRegistry blocks) { + Set keys = new LinkedHashSet<>(); + for (BlockSpec spec : drop.blocks()) { + keys.add(comparable(blocks.resolve(spec).key(), drop.exactBlocks())); + } + return new ResolvedBlockDrop(drop, keys); + } + + BlockDrop drop() { + return drop; + } + + /** Whether the drop applies to {@code brokenKey}, the platform's key for the broken block: its exact state, or just its kind of block. */ + boolean dropsFor(String brokenKey) { + return blocks.contains(comparable(brokenKey, exact)); + } + + private static String comparable(String key, boolean exact) { + if (exact) { + return key; + } + int properties = key.indexOf(PROPERTIES_START); + return properties < 0 ? key : key.substring(0, properties); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CarveOrphanSweep.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CarveOrphanSweep.java new file mode 100644 index 000000000..82a1468f9 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/CarveOrphanSweep.java @@ -0,0 +1,264 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; + +import java.util.Arrays; + +public final class CarveOrphanSweep { + private static final int CHUNK_SIZE = 16; + private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; + private static final int BAND_FLOOR_MARGIN = 4; + private static final int MAX_ORPHAN_CELLS = 16; + private static final ThreadLocal SCRATCH = ThreadLocal.withInitial(SweepScratch::new); + + public interface CarveAccess { + boolean isCarved(int localX, int y, int localZ); + + void markCarved(int localX, int y, int localZ); + + default boolean isProtected(int localX, int y, int localZ) { + return false; + } + } + + private CarveOrphanSweep() { + } + + /** Sweeps the chunk whose first block is {@code originX}, {@code originZ}. */ + static int sweepChunk( + MantleLayer voids, + int originX, + int originZ, + int[] surfaceHeights, + int maxSurfaceBreakDepth, + int worldCeilingY, + int[] surfaceFluidBoundaryStartY, + int fluidHeight + ) { + return sweep(surfaceHeights, maxSurfaceBreakDepth, 0, worldCeilingY, + new MantleCarveAccess(voids, originX, originZ, surfaceFluidBoundaryStartY, fluidHeight)); + } + + public static int sweep(int[] surfaceHeights, int maxSurfaceBreakDepth, int worldFloorY, int worldCeilingY, CarveAccess access) { + if (surfaceHeights == null || surfaceHeights.length < CHUNK_AREA || access == null) { + return 0; + } + + int minSurfaceY = Integer.MAX_VALUE; + int maxSurfaceY = Integer.MIN_VALUE; + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + int surfaceY = surfaceHeights[columnIndex]; + if (surfaceY < minSurfaceY) { + minSurfaceY = surfaceY; + } + if (surfaceY > maxSurfaceY) { + maxSurfaceY = surfaceY; + } + } + + int bandTop = Math.min(worldCeilingY, maxSurfaceY); + int bandFloor = Math.max(worldFloorY + 1, minSurfaceY - Math.max(0, maxSurfaceBreakDepth) - BAND_FLOOR_MARGIN); + if (bandTop < bandFloor) { + return 0; + } + + int bandHeight = bandTop - bandFloor + 1; + int cellCount = bandHeight * CHUNK_AREA; + SweepScratch scratch = SCRATCH.get(); + scratch.prepare(cellCount); + long[] solid = scratch.solid; + long[] visited = scratch.visited; + int[] stack = scratch.stack; + int[] component = scratch.component; + + boolean carvedPresent = false; + for (int y = bandFloor; y <= bandTop; y++) { + int layer = (y - bandFloor) * CHUNK_AREA; + for (int localX = 0; localX < CHUNK_SIZE; localX++) { + for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + if (y > surfaceHeights[columnIndex]) { + continue; + } + if (access.isCarved(localX, y, localZ)) { + carvedPresent = true; + continue; + } + + setBit(solid, layer + columnIndex); + } + } + } + + if (!carvedPresent) { + return 0; + } + + int marked = 0; + for (int rootIndex = 0; rootIndex < cellCount; rootIndex++) { + if (!getBit(solid, rootIndex) || getBit(visited, rootIndex)) { + continue; + } + + setBit(visited, rootIndex); + stack[0] = rootIndex; + int stackSize = 1; + int componentSize = 0; + boolean anchored = false; + + while (stackSize > 0) { + int current = stack[--stackSize]; + int columnIndex = current & (CHUNK_AREA - 1); + int localX = columnIndex >>> 4; + int localZ = columnIndex & (CHUNK_SIZE - 1); + int y = bandFloor + (current / CHUNK_AREA); + + if (!anchored) { + if (access.isProtected(localX, y, localZ)) { + anchored = true; + } else if (localX == 0 || localX == CHUNK_SIZE - 1 || localZ == 0 || localZ == CHUNK_SIZE - 1) { + anchored = true; + } else if (y == bandFloor && isSolidBelowBand(access, surfaceHeights, columnIndex, localX, localZ, bandFloor - 1, worldFloorY)) { + anchored = true; + } else if (componentSize >= MAX_ORPHAN_CELLS) { + anchored = true; + } else { + component[componentSize++] = current; + } + } + + if (y > bandFloor) { + stackSize = push(solid, visited, stack, stackSize, current - CHUNK_AREA); + } + if (y < bandTop) { + stackSize = push(solid, visited, stack, stackSize, current + CHUNK_AREA); + } + if (localX > 0) { + stackSize = push(solid, visited, stack, stackSize, current - CHUNK_SIZE); + } + if (localX < CHUNK_SIZE - 1) { + stackSize = push(solid, visited, stack, stackSize, current + CHUNK_SIZE); + } + if (localZ > 0) { + stackSize = push(solid, visited, stack, stackSize, current - 1); + } + if (localZ < CHUNK_SIZE - 1) { + stackSize = push(solid, visited, stack, stackSize, current + 1); + } + } + + if (anchored) { + continue; + } + + for (int index = 0; index < componentSize; index++) { + int cell = component[index]; + int columnIndex = cell & (CHUNK_AREA - 1); + access.markCarved(columnIndex >>> 4, bandFloor + (cell / CHUNK_AREA), columnIndex & (CHUNK_SIZE - 1)); + marked++; + } + } + + return marked; + } + + private static int push(long[] solid, long[] visited, int[] stack, int stackSize, int neighbor) { + if (!getBit(solid, neighbor) || getBit(visited, neighbor)) { + return stackSize; + } + + setBit(visited, neighbor); + stack[stackSize] = neighbor; + return stackSize + 1; + } + + private static boolean isSolidBelowBand(CarveAccess access, int[] surfaceHeights, int columnIndex, int localX, int localZ, int belowY, int worldFloorY) { + if (belowY < worldFloorY || belowY > surfaceHeights[columnIndex]) { + return false; + } + + return !access.isCarved(localX, belowY, localZ); + } + + private static boolean getBit(long[] bits, int index) { + return (bits[index >>> 6] & (1L << (index & 63))) != 0L; + } + + private static void setBit(long[] bits, int index) { + bits[index >>> 6] |= 1L << (index & 63); + } + + private static final class MantleCarveAccess implements CarveAccess { + private final MantleLayer voids; + private final int originX; + private final int originZ; + private final int[] surfaceFluidBoundaryStartY; + private final int fluidHeight; + + private MantleCarveAccess(MantleLayer voids, int originX, int originZ, int[] surfaceFluidBoundaryStartY, int fluidHeight) { + this.voids = voids; + this.originX = originX; + this.originZ = originZ; + this.surfaceFluidBoundaryStartY = surfaceFluidBoundaryStartY; + this.fluidHeight = fluidHeight; + } + + @Override + public boolean isCarved(int localX, int y, int localZ) { + return voids.get(originX + localX, y, originZ + localZ) != null; + } + + @Override + public void markCarved(int localX, int y, int localZ) { + voids.set(originX + localX, y, originZ + localZ, CarvedVoid.OPEN); + } + + @Override + public boolean isProtected(int localX, int y, int localZ) { + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + return SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, columnIndex, y, fluidHeight); + } + } + + private static final class SweepScratch { + private final int[] component = new int[MAX_ORPHAN_CELLS]; + private long[] solid = new long[0]; + private long[] visited = new long[0]; + private int[] stack = new int[0]; + + private void prepare(int cellCount) { + int words = (cellCount + 63) >>> 6; + if (solid.length < words) { + solid = new long[words]; + visited = new long[words]; + } else { + Arrays.fill(solid, 0, words, 0L); + Arrays.fill(visited, 0, words, 0L); + } + + if (stack.length < cellCount) { + stack = new int[cellCount]; + } + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CarveWorld.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CarveWorld.java new file mode 100644 index 000000000..2d04b7cd0 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/CarveWorld.java @@ -0,0 +1,29 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import com.volmit.noise.NoiseFactory; + +/** + * What the cave carvers need to know about one world that does not change while it runs: the noise the world's pack builds, + * the carve seed, the dimension's height, its fluid and cave-lava heights (above the dimension's bottom) and the platform's Y of + * its bottom, which converts the absolute world Y of a cave biome band. + */ +public record CarveWorld(NoiseFactory noise, long carveSeed, int height, int fluidHeight, int lavaHeight, int minHeight) { +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java new file mode 100644 index 000000000..babf46536 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java @@ -0,0 +1,228 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.carve.CaveAnchorMode; +import art.arcane.iris.modules.objects.CarvedSpace; +import art.arcane.volmlib.util.cache.CacheKey; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.mantle.CarvedVoid; +import com.volmit.resource.ResourceId; +import com.volmit.world.BiomeSample; +import com.volmit.world.TerrainSampler; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** Finds the places in the carved caves of a chunk where a cave object may be anchored, remembering what it scanned. */ +final class CaveAnchors { + private static final int BEDROCK_CLEARANCE = 6; + private static final int SOLID_NEIGHBOR_REACH_BLOCKS = 3; + private static final int MAX_PACKED_SETTING = 65535; + + private final CarvedSpace carved; + private final TerrainSampler terrain; + private final int worldHeight; + private final int caveLavaHeight; + private final Map>> anchorsBySetting = new HashMap<>(); + private final Map carvedColumns = new HashMap<>(); + private final Map surfaceHeights = new HashMap<>(); + + CaveAnchors(CarvedSpace carved, TerrainSampler terrain, int worldHeight, int caveLavaHeight) { + this.carved = carved; + this.terrain = terrain; + this.worldHeight = worldHeight; + this.caveLavaHeight = caveLavaHeight; + } + + /** A position to anchor a cave object at. */ + record Anchor(int x, int y, int z) { + } + + /** How a cave placement looks for its anchor. */ + record Search(CaveAnchorMode mode, int scanStep, int minDepthBelowSurface, int attempts) { + } + + /** + * Looks for an anchor in the chunk whose first block is {@code minX}, {@code minZ}: a column picked at random, a height in + * it picked among those the mode accepts, tried up to the search's attempts. + * + * @param expectedCaveBiome the cave biome the anchor has to be in, or null for any + * @return the anchor, or null when no attempt found one + */ + Anchor find(RNG rng, int minX, int minZ, Search search, ResourceId expectedCaveBiome, boolean underwater) { + for (int attempt = 0; attempt < search.attempts(); attempt++) { + int candidateX = rng.i(minX, minX + 16); + int candidateZ = rng.i(minZ, minZ + 16); + int candidateY = anchorY(rng, candidateX, candidateZ, search); + if (candidateY < 0 + || biomeConflicts(candidateX, candidateY, candidateZ, expectedCaveBiome) + || !acceptsFluid(underwater, carved.voidAt(candidateX, candidateY, candidateZ), candidateY, caveLavaHeight)) { + continue; + } + return new Anchor(candidateX, candidateY, candidateZ); + } + return null; + } + + static boolean acceptsFluid(boolean underwater, Optional carvedVoid, int y, int lavaHeight) { + if (carvedVoid.isEmpty()) { + return false; + } + if (underwater || carvedVoid.get().fill() == CarvedVoid.Fill.AIR) { + return true; + } + return carvedVoid.get().fill() == CarvedVoid.Fill.OPEN && y > lavaHeight; + } + + /** One above the highest height an anchor may sit at, or 0 when none may. */ + static int scanUpperBound(int worldHeight, int surfaceY, int minDepthBelowSurface) { + int maxAnchorY = maxBuriedY(worldHeight, surfaceY, minDepthBelowSurface); + if (maxAnchorY <= 1) { + return 0; + } + return maxAnchorY + 1; + } + + /** The highest height a cave object may reach: no deeper than {@code minDepthBelowSurface} under the surface. */ + static int maxBuriedY(int worldHeight, int surfaceY, int minDepthBelowSurface) { + return Math.min(worldHeight - 1, surfaceY - Math.max(0, minDepthBelowSurface)); + } + + /** Whether the cave biome at the position is not the one expected, nor the surface biome the cave sits under. */ + private boolean biomeConflicts(int x, int y, int z, ResourceId expectedCaveBiome) { + if (expectedCaveBiome == null) { + return false; + } + BiomeSample sample = terrain.biome(x, y, z); + return biomeConflicts(sample.caveBiome().orElse(null), sample.surfaceBiome(), expectedCaveBiome); + } + + static boolean biomeConflicts(ResourceId at, ResourceId surface, ResourceId expectedCaveBiome) { + if (expectedCaveBiome == null || at == null) { + return false; + } + if (at.equals(expectedCaveBiome)) { + return false; + } + return surface == null || !at.equals(surface); + } + + private int anchorY(RNG rng, int x, int z, Search search) { + List anchors = anchorsAt(x, z, search); + if (anchors.isEmpty()) { + return -1; + } + if (anchors.size() == 1) { + return anchors.get(0); + } + return anchors.get(rng.i(anchors.size())); + } + + private List anchorsAt(int x, int z, Search search) { + if (search.scanStep() > MAX_PACKED_SETTING || search.minDepthBelowSurface() > MAX_PACKED_SETTING) { + return scanColumn(x, z, search); + } + long settingKey = ((long) search.mode().ordinal() << 32) | ((long) search.scanStep() << 16) | search.minDepthBelowSurface(); + Map> columns = anchorsBySetting.computeIfAbsent(settingKey, key -> new HashMap<>()); + long columnKey = CacheKey.key(x, z); + List anchors = columns.get(columnKey); + if (anchors != null) { + return anchors; + } + anchors = scanColumn(x, z, search); + columns.put(columnKey, anchors); + return anchors; + } + + private List scanColumn(int x, int z, Search search) { + int step = Math.max(1, search.scanStep()); + int surfaceY = surfaceHeight(x, z); + int maxAnchorExclusive = scanUpperBound(worldHeight, surfaceY, search.minDepthBelowSurface()); + if (maxAnchorExclusive == 0) { + return new ArrayList<>(); + } + int carvedHeight = Math.min(worldHeight, maxAnchorExclusive + 3); + byte[] carvedColumn = carvedColumn(x, z, carvedHeight); + return scanRange(search.mode(), step, carvedHeight, maxAnchorExclusive, carvedColumn); + } + + private List scanRange(CaveAnchorMode mode, int step, int height, int maxAnchorY, byte[] carvedColumn) { + List anchors = new ArrayList<>(); + for (int y = BEDROCK_CLEARANCE; y < maxAnchorY; y += step) { + if (!isCarved(carvedColumn, y)) { + continue; + } + boolean solidBelow = hasSolidNeighbor(carvedColumn, y, height, -1); + boolean solidAbove = hasSolidNeighbor(carvedColumn, y, height, 1); + if (matches(mode, solidBelow, solidAbove)) { + anchors.add(y); + } + } + return anchors; + } + + private static boolean isCarved(byte[] carvedColumn, int y) { + return y >= 0 && y < carvedColumn.length && carvedColumn[y] == 1; + } + + private static boolean hasSolidNeighbor(byte[] carvedColumn, int y, int height, int direction) { + for (int distance = 1; distance <= SOLID_NEIGHBOR_REACH_BLOCKS; distance++) { + int neighbor = y + (direction * distance); + if (neighbor < 0 || neighbor >= height || !isCarved(carvedColumn, neighbor)) { + return true; + } + } + return false; + } + + private static boolean matches(CaveAnchorMode mode, boolean solidBelow, boolean solidAbove) { + return switch (mode) { + case PROFILE_DEFAULT, FLOOR -> solidBelow; + case CEILING -> solidAbove; + case CENTER -> !solidBelow && !solidAbove; + case ANY -> true; + }; + } + + private byte[] carvedColumn(int x, int z, int height) { + long columnKey = CacheKey.key(x, z); + byte[] column = carvedColumns.get(columnKey); + if (column != null && column.length == height) { + return column; + } + column = carved.column(x, z, height); + carvedColumns.put(columnKey, column); + return column; + } + + private int surfaceHeight(int x, int z) { + long columnKey = CacheKey.key(x, z); + Integer known = surfaceHeights.get(columnKey); + if (known != null) { + return known; + } + int surfaceY = terrain.surfaceHeight(x, z); + surfaceHeights.put(columnKey, surfaceY); + return surfaceY; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java new file mode 100644 index 000000000..80042c2a7 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java @@ -0,0 +1,69 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import com.volmit.mantle.CarvedVoid; + +final class CaveCarveScratch { + final int[] columnMaxY = new int[256]; + final int[] fluidMaxY = new int[256]; + final int[] surfaceBreakFloorY = new int[256]; + final boolean[] surfaceBreakColumn = new boolean[256]; + final boolean[] surfaceCeilingColumn = new boolean[256]; + final double[] columnThreshold = new double[256]; + final double[] passThreshold = new double[256]; + final double[] fullWeights = new double[256]; + final double[] clampedColumnWeights = new double[256]; + final int[] activeColumnIndices = new int[256]; + final int[] activeColumnTopY = new int[256]; + final int[] planeColumnIndices = new int[256]; + final double[] planeThresholdLimit = new double[256]; + final boolean[] planeCarve = new boolean[256]; + final double[] adaptivePlaneDensity = new double[81]; + final double[] adaptivePlanePrediction = new double[256]; + final double[] adaptivePlaneAmbiguity = new double[256]; + final int[] adaptivePlaneSampleBounds = new int[4]; + final int[] adaptiveCellX = new int[256]; + final int[] adaptiveCellZ = new int[256]; + final int[] adaptiveRow0 = new int[256]; + final int[] adaptiveRow1 = new int[256]; + final double[] adaptiveTx = new double[256]; + final double[] adaptiveTz = new double[256]; + final boolean[] warpCacheSet = new boolean[256]; + final int[] warpCacheX = new int[256]; + final int[] warpCacheY = new int[256]; + final int[] warpCacheZ = new int[256]; + final double[] warpCacheA = new double[256]; + final double[] warpCacheB = new double[256]; + final int[] tileIndices = new int[4]; + final int[] tileLocalX = new int[4]; + final int[] tileLocalZ = new int[4]; + final int[] tileTopY = new int[4]; + CaveFieldModuleState[] activeModules = new CaveFieldModuleState[0]; + double[] activeModuleRemainingMin = new double[0]; + double[] activeModuleRemainingMax = new double[0]; + int activeModulesY = Integer.MIN_VALUE; + int activeModuleCount; + double[] verticalEdgeFade = new double[0]; + double[] surfaceClosureThreshold = new double[0]; + CarvedVoid[] voidByY = new CarvedVoid[0]; + int adaptiveGeometryStep = -1; + int adaptiveGeometryAxisCells = -1; + boolean fullWeightsInitialized; +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java new file mode 100644 index 000000000..9054e62e2 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java @@ -0,0 +1,621 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.modules.carve.CaveProfile; +import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; +import art.arcane.iris.engine.object.terrain.carving.DeclaredCaveProfiles; +import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import com.volmit.config.Range; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; +import com.volmit.resource.ResourceId; +import com.volmit.world.BiomeSample; +import com.volmit.world.PackBiome; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; + +/** + * Plans one chunk's caves into the mantle for {@link art.arcane.iris.engine.modifier.CarveModule}: the cave + * profiles of the dimension's carving entries and of the regions and biomes around the chunk, blended over + * their borders. One per engine runtime, keeping a carver per cave profile. + */ +public class CaveCarving { + private static final int CHUNK_SIZE = 16; + private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; + private static final int BLEND_RADIUS = 3; + /** A column's cave biome is the one the world places this far below its surface (at least at height 1). */ + private static final int CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS = 56; + private static final int FIELD_SIZE = CHUNK_SIZE + (BLEND_RADIUS * 2); + private static final double MIN_WEIGHT = 0.08D; + private static final double THRESHOLD_PENALTY = 0.24D; + private static final int MAX_BLENDED_PROFILE_PASSES = 2; + private static final int KERNEL_WIDTH = (BLEND_RADIUS * 2) + 1; + private static final int KERNEL_SIZE = KERNEL_WIDTH * KERNEL_WIDTH; + private static final int[] KERNEL_DX = new int[KERNEL_SIZE]; + private static final int[] KERNEL_DZ = new int[KERNEL_SIZE]; + private static final double[] KERNEL_WEIGHT = new double[KERNEL_SIZE]; + private static final ThreadLocal BLEND_SCRATCH = ThreadLocal.withInitial(BlendScratch::new); + + private final CarveWorld world; + private final DeclaredCaveProfiles declaredProfiles; + private final CarvingResolver resolver; + private final FluidColumns fluidColumns; + private final boolean upperDimensionCarving; + private final Object profileCarverLock = new Object(); + private volatile Map profileCarvers = new IdentityHashMap<>(); + + static { + int kernelIndex = 0; + for (int offsetX = -BLEND_RADIUS; offsetX <= BLEND_RADIUS; offsetX++) { + for (int offsetZ = -BLEND_RADIUS; offsetZ <= BLEND_RADIUS; offsetZ++) { + KERNEL_DX[kernelIndex] = offsetX; + KERNEL_DZ[kernelIndex] = offsetZ; + int edgeDistance = Math.max(Math.abs(offsetX), Math.abs(offsetZ)); + KERNEL_WEIGHT[kernelIndex] = (BLEND_RADIUS + 1D) - edgeDistance; + kernelIndex++; + } + } + } + + /** Whether the dimension's fluid palette gives a column a fluid, which caves near it blend towards. */ + @FunctionalInterface + public interface FluidColumns { + boolean hasFluid(int worldX, int worldZ); + } + + public CaveCarving(PackWorld packWorld, CarveWorld world, boolean upperDimensionCarving, FluidColumns fluidColumns) { + this.world = world; + this.declaredProfiles = DeclaredCaveProfiles.of(packWorld); + this.resolver = CarvingResolver.of(packWorld); + this.fluidColumns = fluidColumns; + this.upperDimensionCarving = upperDimensionCarving; + } + + /** Carves the caves of the chunk at chunk coordinates {@code x}, {@code z} into {@code voids}, reading the terrain around it from {@code terrain}. */ + public void carve(MantleLayer voids, TerrainSampler terrain, int x, int z) { + BlendScratch blendScratch = BLEND_SCRATCH.get(); + int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, terrain, blendScratch.chunkSurfaceHeights); + List weightedProfiles = resolveWeightedProfiles(x, z, terrain); + int fluidHeight = world.fluidHeight(); + int[] surfaceFluidBoundaryStartY = blendScratch.surfaceFluidBoundaryStartY; + SurfaceFluidBoundaryPlan.fill( + chunkSurfaceHeights, + blendScratch.fieldSurfaceHeights, + blendScratch.fieldHasFluid, + FIELD_SIZE, + BLEND_RADIUS, + fluidHeight, + surfaceFluidBoundaryStartY + ); + CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); + for (WeightedProfile weightedProfile : weightedProfiles) { + carveProfile(weightedProfile, voids, x, z, chunkSurfaceHeights, surfaceFluidBoundaryStartY, fluidSupportPlan); + } + + if (upperDimensionCarving && hasUpperDimension(terrain, x, z)) { + carveUpperTerrain(terrain, weightedProfiles, voids, x, z, fluidSupportPlan); + } + fluidSupportPlan.resolve(voids, PowerOfTwoCoordinates.chunkToBlock(x), PowerOfTwoCoordinates.chunkToBlock(z), world.height()); + + if (!weightedProfiles.isEmpty()) { + CarveOrphanSweep.sweepChunk( + voids, + PowerOfTwoCoordinates.chunkToBlock(x), + PowerOfTwoCoordinates.chunkToBlock(z), + chunkSurfaceHeights, + maxSurfaceBreakDepth(weightedProfiles), + world.height() - 1, + surfaceFluidBoundaryStartY, + fluidHeight + ); + } + } + + private static boolean hasUpperDimension(TerrainSampler terrain, int chunkX, int chunkZ) { + return terrain.upperDimensionY(PowerOfTwoCoordinates.chunkToBlock(chunkX), PowerOfTwoCoordinates.chunkToBlock(chunkZ)).isPresent(); + } + + private static int maxSurfaceBreakDepth(List weightedProfiles) { + int maxDepth = 0; + for (WeightedProfile weightedProfile : weightedProfiles) { + maxDepth = Math.max(maxDepth, Math.max(0, weightedProfile.profile.surfaceBreakDepth())); + } + return maxDepth; + } + + private void carveProfile(WeightedProfile weightedProfile, MantleLayer voids, int cx, int cz, + int[] chunkSurfaceHeights, int[] surfaceFluidBoundaryStartY, + CaveFluidSupportPlan fluidSupportPlan) { + IrisCaveCarver3D carver = getCarver(weightedProfile.profile); + carver.carve(voids, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, + weightedProfile.worldYRange, chunkSurfaceHeights, surfaceFluidBoundaryStartY, null, fluidSupportPlan); + } + + private void carveUpperTerrain(TerrainSampler terrain, List normalProfiles, + MantleLayer voids, int cx, int cz, + CaveFluidSupportPlan fluidSupportPlan) { + int chunkHeight = world.height(); + int worldMinHeight = world.minHeight(); + int baseX = PowerOfTwoCoordinates.chunkToBlock(cx); + int baseZ = PowerOfTwoCoordinates.chunkToBlock(cz); + + int minUpperSurfaceY = chunkHeight; + for (int localX = 0; localX < CHUNK_SIZE; localX++) { + int worldX = baseX + localX; + for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { + int worldZ = baseZ + localZ; + int upperY = terrain.upperDimensionY(worldX, worldZ).getAsInt(); + if (upperY < minUpperSurfaceY) { + minUpperSurfaceY = upperY; + } + } + } + + if (minUpperSurfaceY >= chunkHeight - 2) { + return; + } + + Range upperYRange = Range.of( + minUpperSurfaceY + worldMinHeight, + chunkHeight - 1 + worldMinHeight + ); + Range fullVerticalRange = Range.of(0, chunkHeight); + + int[] ceilingSurfaceHeights = new int[CHUNK_AREA]; + Arrays.fill(ceilingSurfaceHeights, chunkHeight - 1); + + for (WeightedProfile weightedProfile : normalProfiles) { + Range constrainedRange; + if (weightedProfile.worldYRange != null) { + double min = Math.max(weightedProfile.worldYRange.min(), upperYRange.min()); + double max = Math.min(weightedProfile.worldYRange.max(), upperYRange.max()); + if (min >= max) { + continue; + } + constrainedRange = Range.of(min, max); + } else { + constrainedRange = upperYRange; + } + IrisCaveCarver3D carver = getCarver(weightedProfile.profile); + carver.carve(voids, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, + constrainedRange, ceilingSurfaceHeights, null, fullVerticalRange, fluidSupportPlan); + } + } + + private List resolveWeightedProfiles(int chunkX, int chunkZ, TerrainSampler terrain) { + BlendScratch blendScratch = BLEND_SCRATCH.get(); + CaveProfile[] profileField = blendScratch.profileField; + Map columnProfileWeights = blendScratch.columnProfileWeights; + IdentityHashMap activeProfiles = blendScratch.activeProfiles; + List profileOrder = blendScratch.profileOrder; + CaveProfile[] kernelProfiles = blendScratch.kernelProfiles; + double[] kernelProfileWeights = blendScratch.kernelProfileWeights; + activeProfiles.clear(); + profileOrder.clear(); + fillProfileField(profileField, chunkX, chunkZ, terrain, blendScratch); + + for (int localX = 0; localX < CHUNK_SIZE; localX++) { + for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { + int profileCount = 0; + int centerX = localX + BLEND_RADIUS; + int centerZ = localZ + BLEND_RADIUS; + double totalKernelWeight = 0D; + + for (int kernelIndex = 0; kernelIndex < KERNEL_SIZE; kernelIndex++) { + int sampleX = centerX + KERNEL_DX[kernelIndex]; + int sampleZ = centerZ + KERNEL_DZ[kernelIndex]; + CaveProfile profile = profileField[(sampleX * FIELD_SIZE) + sampleZ]; + if (!isProfileEnabled(profile)) { + continue; + } + + double kernelWeight = KERNEL_WEIGHT[kernelIndex]; + int existingIndex = findProfileIndex(kernelProfiles, profileCount, profile); + if (existingIndex >= 0) { + kernelProfileWeights[existingIndex] += kernelWeight; + } else { + kernelProfiles[profileCount] = profile; + kernelProfileWeights[profileCount] = kernelWeight; + profileCount++; + } + totalKernelWeight += kernelWeight; + } + + if (totalKernelWeight <= 0D || profileCount == 0) { + continue; + } + + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + for (int profileIndex = 0; profileIndex < profileCount; profileIndex++) { + CaveProfile profile = kernelProfiles[profileIndex]; + double kernelWeight = kernelProfileWeights[profileIndex]; + kernelProfiles[profileIndex] = null; + kernelProfileWeights[profileIndex] = 0D; + + double columnWeight = clampWeight(kernelWeight / totalKernelWeight); + if (columnWeight < MIN_WEIGHT) { + continue; + } + + double[] weights = columnProfileWeights.get(profile); + if (weights == null) { + weights = new double[CHUNK_AREA]; + columnProfileWeights.put(profile, weights); + } else if (!activeProfiles.containsKey(profile)) { + Arrays.fill(weights, 0D); + } + if (activeProfiles.put(profile, Boolean.TRUE) == null) { + profileOrder.add(profile); + } + weights[columnIndex] = columnWeight; + } + } + } + + List columnWeightedProfiles = new ArrayList<>(); + for (CaveProfile profile : profileOrder) { + double[] weights = columnProfileWeights.get(profile); + if (weights == null) { + continue; + } + + // averageWeight ranks and orders carve passes, so it must be bit-identical across + // installations: kernels.sum reassociates FP addition under the vector kernel, + // making profile order depend on a JVM flag. max() is order-independent and safe. + double maxWeight = maxOf(weights); + + if (maxWeight < MIN_WEIGHT) { + continue; + } + + double averageWeight = computeAverageWeight(weights); + columnWeightedProfiles.add(new WeightedProfile(profile, weights, averageWeight, null, columnWeightedProfiles.size())); + } + + List blendedProfiles = limitAndMergeBlendedProfiles(columnWeightedProfiles, MAX_BLENDED_PROFILE_PASSES, CHUNK_AREA); + List resolvedProfiles = resolveDimensionCarvingProfiles(chunkX, chunkZ, blendScratch); + resolvedProfiles.addAll(blendedProfiles); + return resolvedProfiles; + } + + private List resolveDimensionCarvingProfiles(int chunkX, int chunkZ, BlendScratch blendScratch) { + List weightedProfiles = new ArrayList<>(); + List entries = resolver.entries(); + if (entries.isEmpty()) { + return weightedProfiles; + } + + Map dimensionColumnPlans = blendScratch.dimensionColumnPlans; + dimensionColumnPlans.clear(); + + for (ResolvedCarvingEntry entry : entries) { + if (!entry.enabled()) { + continue; + } + + PackBiome rootBiome = resolver.entryBiome(entry); + if (rootBiome == null) { + continue; + } + + ResolvedCarvingEntry[] columnPlan = dimensionColumnPlans.computeIfAbsent(entry, key -> new ResolvedCarvingEntry[CHUNK_AREA]); + buildDimensionColumnPlan(columnPlan, chunkX, chunkZ, entry); + + Map rootProfileColumnWeights = new IdentityHashMap<>(); + List rootProfileOrder = new ArrayList<>(); + Range worldYRange = entry.worldYRange(); + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + ResolvedCarvingEntry resolvedEntry = columnPlan[columnIndex]; + PackBiome resolvedBiome = resolver.entryBiome(resolvedEntry); + if (resolvedBiome == null) { + continue; + } + + CaveProfile profile = declaredProfiles.ofBiome(resolvedBiome.id()); + if (!isProfileEnabled(profile)) { + continue; + } + + double[] columnWeights = rootProfileColumnWeights.get(profile); + if (columnWeights == null) { + columnWeights = new double[CHUNK_AREA]; + rootProfileColumnWeights.put(profile, columnWeights); + rootProfileOrder.add(profile); + } + columnWeights[columnIndex] = 1D; + } + + for (CaveProfile profile : rootProfileOrder) { + weightedProfiles.add(new WeightedProfile(profile, rootProfileColumnWeights.get(profile), -1D, worldYRange, weightedProfiles.size())); + } + } + + return weightedProfiles; + } + + private void buildDimensionColumnPlan(ResolvedCarvingEntry[] columnPlan, int chunkX, int chunkZ, ResolvedCarvingEntry entry) { + int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + for (int localX = 0; localX < CHUNK_SIZE; localX++) { + int worldX = baseX + localX; + for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { + int worldZ = baseZ + localZ; + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + columnPlan[columnIndex] = resolver.resolveFromRoot(entry, worldX, worldZ); + } + } + } + + private void fillProfileField(CaveProfile[] profileField, int chunkX, int chunkZ, TerrainSampler terrain, BlendScratch blendScratch) { + int startX = PowerOfTwoCoordinates.chunkToBlock(chunkX) - BLEND_RADIUS; + int startZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ) - BLEND_RADIUS; + prefillFieldHeightsAndFluid(terrain, startX, startZ, blendScratch); + + for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { + int worldX = startX + fieldX; + for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { + int worldZ = startZ + fieldZ; + int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ; + profileField[fieldIndex] = resolveColumnProfile(terrain, worldX, worldZ, blendScratch.fieldSurfaceHeights[fieldIndex]); + } + } + } + + private int findProfileIndex(CaveProfile[] profiles, int size, CaveProfile profile) { + for (int index = 0; index < size; index++) { + if (profiles[index] == profile) { + return index; + } + } + + return -1; + } + + /** + * The profile that carves a column: the dimension's, replaced by the region's, the surface biome's and the cave biome's + * wherever they declare an enabled one. The cave biome is the one the world places at the depth below the surface this + * column's caves start at ({@link #CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS}), after the dimension's carving bands. + */ + private CaveProfile resolveColumnProfile(TerrainSampler terrain, int worldX, int worldZ, double surfaceHeight) { + CaveProfile resolved = null; + CaveProfile dimensionProfile = declaredProfiles.ofDimension(); + if (isProfileEnabled(dimensionProfile)) { + resolved = dimensionProfile; + } + + int roundedSurfaceY = (int) Math.round(surfaceHeight); + int sampleY = Math.max(1, roundedSurfaceY - CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS); + BiomeSample sample = terrain.biome(worldX, sampleY, worldZ); + + CaveProfile regionProfile = declaredProfiles.ofRegion(sample.region()); + if (isProfileEnabled(regionProfile)) { + resolved = regionProfile; + } + + CaveProfile surfaceProfile = declaredProfiles.ofBiome(sample.surfaceBiome()); + if (isProfileEnabled(surfaceProfile)) { + resolved = surfaceProfile; + } + + if (sample.caveBiome().isPresent()) { + CaveProfile caveProfile = declaredProfiles.ofBiome(sample.caveBiome().get()); + if (isProfileEnabled(caveProfile)) { + resolved = caveProfile; + } + } + + return resolved; + } + + private void prefillFieldHeightsAndFluid(TerrainSampler terrain, int startX, int startZ, BlendScratch blendScratch) { + for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { + int worldX = startX + fieldX; + for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { + int worldZ = startZ + fieldZ; + int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ; + blendScratch.fieldSurfaceHeights[fieldIndex] = terrain.surfaceY(worldX, worldZ); + blendScratch.fieldHasFluid[fieldIndex] = fluidColumns.hasFluid(worldX, worldZ); + } + } + } + + private IrisCaveCarver3D getCarver(CaveProfile profile) { + IrisCaveCarver3D carver = profileCarvers.get(profile); + if (carver != null) { + return carver; + } + + IrisCaveCarver3D createdCarver = new IrisCaveCarver3D(world, profile); + synchronized (profileCarverLock) { + IrisCaveCarver3D published = profileCarvers.get(profile); + if (published != null) { + return published; + } + + Map updated = new IdentityHashMap<>(profileCarvers); + updated.put(profile, createdCarver); + profileCarvers = updated; + return createdCarver; + } + } + + private boolean isProfileEnabled(CaveProfile profile) { + return profile != null && profile.enabled(); + } + + private int[] prepareChunkSurfaceHeights(int chunkX, int chunkZ, TerrainSampler terrain, int[] scratch) { + int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + for (int localX = 0; localX < CHUNK_SIZE; localX++) { + int worldX = baseX + localX; + for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + scratch[columnIndex] = terrain.surfaceHeight(worldX, baseZ + localZ); + } + } + return scratch; + } + + private static double maxOf(double[] values) { + double max = Double.NEGATIVE_INFINITY; + for (double value : values) { + max = Math.max(max, value); + } + return max; + } + + private static List limitAndMergeBlendedProfiles(List blendedProfiles, int maxProfiles) { + return limitAndMergeBlendedProfiles(blendedProfiles, maxProfiles, CHUNK_AREA); + } + + private static List limitAndMergeBlendedProfiles(List blendedProfiles, int maxProfiles, int areaSize) { + if (blendedProfiles == null || blendedProfiles.isEmpty()) { + return new ArrayList<>(); + } + + int clampedLimit = Math.max(1, maxProfiles); + List rankedProfiles = new ArrayList<>(blendedProfiles); + rankedProfiles.sort(CaveCarving::compareBySelectionRank); + List keptProfiles = new ArrayList<>(); + int keptCount = Math.min(clampedLimit, rankedProfiles.size()); + for (int index = 0; index < keptCount; index++) { + keptProfiles.add(rankedProfiles.get(index)); + } + + if (rankedProfiles.size() > keptCount) { + for (int columnIndex = 0; columnIndex < areaSize; columnIndex++) { + int dominantIndex = 0; + double dominantWeight = Double.NEGATIVE_INFINITY; + for (int keptIndex = 0; keptIndex < keptProfiles.size(); keptIndex++) { + double keptWeight = keptProfiles.get(keptIndex).columnWeights[columnIndex]; + if (keptWeight > dominantWeight) { + dominantWeight = keptWeight; + dominantIndex = keptIndex; + } + } + + double droppedWeight = 0D; + for (int droppedIndex = keptCount; droppedIndex < rankedProfiles.size(); droppedIndex++) { + droppedWeight += rankedProfiles.get(droppedIndex).columnWeights[columnIndex]; + } + if (droppedWeight <= 0D) { + continue; + } + + WeightedProfile dominantProfile = keptProfiles.get(dominantIndex); + double mergedWeight = dominantProfile.columnWeights[columnIndex] + droppedWeight; + dominantProfile.columnWeights[columnIndex] = clampWeight(mergedWeight); + } + } + + List mergedProfiles = new ArrayList<>(); + for (WeightedProfile keptProfile : keptProfiles) { + double averageWeight = computeAverageWeight(keptProfile.columnWeights, areaSize); + mergedProfiles.add(new WeightedProfile(keptProfile.profile, keptProfile.columnWeights, averageWeight, keptProfile.worldYRange, keptProfile.sequence)); + } + mergedProfiles.sort(CaveCarving::compareByCarveOrder); + return mergedProfiles; + } + + private static int compareBySelectionRank(WeightedProfile a, WeightedProfile b) { + int weightOrder = Double.compare(b.averageWeight, a.averageWeight); + if (weightOrder != 0) { + return weightOrder; + } + return Integer.compare(a.sequence, b.sequence); + } + + private static int compareByCarveOrder(WeightedProfile a, WeightedProfile b) { + int weightOrder = Double.compare(a.averageWeight, b.averageWeight); + if (weightOrder != 0) { + return weightOrder; + } + return Integer.compare(a.sequence, b.sequence); + } + + private static double computeAverageWeight(double[] weights) { + return computeAverageWeight(weights, CHUNK_AREA); + } + + private static double computeAverageWeight(double[] weights, int areaSize) { + if (weights == null || weights.length == 0) { + return 0D; + } + double sum = 0D; + for (double weight : weights) { + sum += weight; + } + return sum / Math.max(1, areaSize); + } + + private static double clampWeight(double value) { + if (Double.isNaN(value) || Double.isInfinite(value)) { + return 0D; + } + if (value <= 0D) { + return 0D; + } + if (value >= 1D) { + return 1D; + } + return value; + } + + private static final class WeightedProfile { + private final CaveProfile profile; + private final double[] columnWeights; + private final double averageWeight; + private final Range worldYRange; + private final int sequence; + + private WeightedProfile(CaveProfile profile, double[] columnWeights, double averageWeight, Range worldYRange, int sequence) { + this.profile = profile; + this.columnWeights = columnWeights; + this.averageWeight = averageWeight; + this.worldYRange = worldYRange; + this.sequence = sequence; + } + + private double averageWeight() { + return averageWeight; + } + } + + private static final class BlendScratch { + private final CaveProfile[] profileField = new CaveProfile[FIELD_SIZE * FIELD_SIZE]; + private final CaveProfile[] kernelProfiles = new CaveProfile[KERNEL_SIZE]; + private final double[] kernelProfileWeights = new double[KERNEL_SIZE]; + private final IdentityHashMap columnProfileWeights = new IdentityHashMap<>(); + private final IdentityHashMap dimensionColumnPlans = new IdentityHashMap<>(); + private final IdentityHashMap activeProfiles = new IdentityHashMap<>(); + private final List profileOrder = new ArrayList<>(); + private final double[] fieldSurfaceHeights = new double[FIELD_SIZE * FIELD_SIZE]; + private final boolean[] fieldHasFluid = new boolean[FIELD_SIZE * FIELD_SIZE]; + private final int[] chunkSurfaceHeights = new int[CHUNK_AREA]; + private final int[] surfaceFluidBoundaryStartY = new int[CHUNK_AREA]; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java new file mode 100644 index 000000000..392ac27ce --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java @@ -0,0 +1,58 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.carve.CaveFieldModule; +import com.volmit.config.Range; +import com.volmit.noise.NoiseSampler; + +final class CaveFieldModuleState { + final NoiseSampler density; + final int minY; + final int maxY; + final double weight; + final double threshold; + final boolean invert; + final double minContribution; + final double maxContribution; + + CaveFieldModuleState(CaveFieldModule module, NoiseSampler density) { + Range range = module.verticalRange(); + this.density = density; + this.minY = (int) Math.floor(range.min()); + this.maxY = (int) Math.ceil(range.max()); + this.weight = module.weight(); + this.threshold = module.threshold(); + this.invert = module.invert(); + double rawMin = invert ? threshold - 1D : -1D - threshold; + double rawMax = invert ? threshold + 1D : 1D - threshold; + this.minContribution = rawMin * weight; + this.maxContribution = rawMax * weight; + } + + double sample(double x, int y, double z) { + double sampled = density.signed(x, y, z); + return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; + } + + double sample(double x, double y, double z) { + double sampled = density.signed(x, y, z); + return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFloorMarking.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFloorMarking.java new file mode 100644 index 000000000..201d4c7eb --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFloorMarking.java @@ -0,0 +1,120 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; +import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementTerrain; +import com.volmit.world.TerrainSampler; + +import java.util.BitSet; + +/** + * Marks the floors of the caves {@link CaveCarving} planned in a chunk, which the host's cave spawning reads: the lowest + * block of each vertical run of at least three carved blocks, one floor in sixteen. The runs are those the chunk stage + * cuts, minus the blocks it leaves alone: under a dimension stacked above that carving does not go through, and open voids + * the terrain holds fluid in. The roll is seed-derived and keyed by position alone, never random, because the markers + * persist in the mantle: the same seed marks the same floors on every run. + */ +public final class CaveFloorMarking { + static final String CAVE_FLOOR_MARKER = "cave_floor"; + private static final int CHUNK_SIZE = 16; + private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; + private static final int MIN_RUN_LENGTH = 3; + private static final long FLOOR_MARKER_SALT = 0xC2B2AE3D27D4EB4FL; + private static final long ROLL_MASK = 15L; + private static final ThreadLocal COLUMNS = ThreadLocal.withInitial(() -> { + BitSet[] columns = new BitSet[CHUNK_AREA]; + for (int index = 0; index < CHUNK_AREA; index++) { + columns[index] = new BitSet(); + } + return columns; + }); + + private final CarveWorld world; + private final boolean upperDimensionCarving; + + public CaveFloorMarking(CarveWorld world, boolean upperDimensionCarving) { + this.world = world; + this.upperDimensionCarving = upperDimensionCarving; + } + + /** Marks the floors of the chunk at chunk coordinates {@code chunkX}, {@code chunkZ} in {@code placement}. */ + public void mark(MantleLayer voids, TerrainSampler terrain, PlacementTerrain placement, int chunkX, int chunkZ) { + int originX = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int originZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + BitSet[] carvedColumns = COLUMNS.get(); + fillCarvedColumns(carvedColumns, voids, terrain, originX, originZ); + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + markColumn(carvedColumns[columnIndex], placement, originX + PowerOfTwoCoordinates.unpackLocal16X(columnIndex), + originZ + (columnIndex & (CHUNK_SIZE - 1))); + } + } + + private void fillCarvedColumns(BitSet[] carvedColumns, MantleLayer voids, TerrainSampler terrain, int originX, int originZ) { + int[] surfaceHeights = new int[CHUNK_AREA]; + int[] upperSurfaceHeights = upperDimensionCarving || terrain.upperDimensionY(originX, originZ).isEmpty() ? null : new int[CHUNK_AREA]; + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + carvedColumns[columnIndex].clear(); + int worldX = originX + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int worldZ = originZ + (columnIndex & (CHUNK_SIZE - 1)); + surfaceHeights[columnIndex] = terrain.surfaceHeight(worldX, worldZ); + if (upperSurfaceHeights != null) { + upperSurfaceHeights[columnIndex] = terrain.upperDimensionY(worldX, worldZ).getAsInt(); + } + } + + int fluidHeight = terrain.fluidHeight(); + voids.visit(new BlockBox(originX, 0, originZ, originX + CHUNK_SIZE, world.height(), originZ + CHUNK_SIZE), (x, y, z, carvedVoid) -> { + int columnIndex = PowerOfTwoCoordinates.packLocal16(x - originX, z - originZ); + if (y <= 0 || upperSurfaceHeights != null && y >= upperSurfaceHeights[columnIndex]) { + return; + } + boolean terrainHoldsFluid = y > surfaceHeights[columnIndex] && y <= fluidHeight; + if (carvedVoid.fill() == CarvedVoid.Fill.OPEN && terrainHoldsFluid) { + return; + } + carvedColumns[columnIndex].set(y); + }); + } + + private void markColumn(BitSet carvedColumn, PlacementTerrain placement, int worldX, int worldZ) { + int floor = carvedColumn.nextSetBit(0); + while (floor >= 0) { + int ceiling = carvedColumn.nextClearBit(floor) - 1; + if (ceiling - floor + 1 >= MIN_RUN_LENGTH && floorRoll(worldX, floor, worldZ)) { + placement.mark(new PlacedMarker.PackMarker(new BlockPosition(worldX, floor, worldZ), CAVE_FLOOR_MARKER)); + } + floor = carvedColumn.nextSetBit(ceiling + 1); + } + } + + /** One in sixteen, from a SplitMix64 finalizer over the carve seed, the position and a salt. */ + private boolean floorRoll(int x, int y, int z) { + long hash = (world.carveSeed() + FLOOR_MARKER_SALT) ^ art.arcane.volmlib.util.math.BlockPosition.toLong(x, y, z); + hash = (hash ^ (hash >>> 30)) * 0xBF58476D1CE4E5B9L; + hash = (hash ^ (hash >>> 27)) * 0x94D049BB133111EBL; + hash ^= hash >>> 31; + return (hash & ROLL_MASK) == 0L; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java new file mode 100644 index 000000000..da3cebfad --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java @@ -0,0 +1,90 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; + +import java.util.BitSet; + +/** The fluid voids a carver planned in one chunk, to be drained back to open voids where no solid cup holds them. */ +final class CaveFluidSupportPlan { + private static final int MIN_SUPPORTED_NEIGHBOURS = 4; + private static final int CHUNK_WIDTH = 16; + private static final int COLUMN_BITS = 8; + private static final int COLUMN_MASK = (1 << COLUMN_BITS) - 1; + + private final BitSet fluidPositions = new BitSet(); + + void add(int localX, int y, int localZ) { + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + fluidPositions.set((y << COLUMN_BITS) | columnIndex); + } + + /** Turns every planned fluid void of the chunk at block origin {@code originX}, {@code originZ} that is no longer fluid or has no cup under it into an open void. */ + void resolve(MantleLayer voids, int originX, int originZ, int worldHeight) { + for (int position = fluidPositions.nextSetBit(0); position >= 0; position = fluidPositions.nextSetBit(position + 1)) { + int y = position >>> COLUMN_BITS; + int columnIndex = position & COLUMN_MASK; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & (CHUNK_WIDTH - 1); + int x = originX + localX; + int z = originZ + localZ; + if (voids.get(x, y, z) != CarvedVoid.FLUID || hasCupSupport(voids, originX, originZ, localX, y, localZ, worldHeight)) { + continue; + } + voids.set(x, y, z, CarvedVoid.OPEN); + } + fluidPositions.clear(); + } + + private static boolean hasCupSupport(MantleLayer voids, int originX, int originZ, int localX, int y, int localZ, int worldHeight) { + if (localX <= 0 || localX >= CHUNK_WIDTH - 1 || localZ <= 0 || localZ >= CHUNK_WIDTH - 1 + || y <= 1 || !isSolid(voids, originX, originZ, localX, y - 1, localZ, worldHeight) + || !isSolid(voids, originX, originZ, localX, y - 2, localZ, worldHeight)) { + return false; + } + + int support = 0; + if (isSolid(voids, originX, originZ, localX + 1, y, localZ, worldHeight)) { + support++; + } + if (isSolid(voids, originX, originZ, localX - 1, y, localZ, worldHeight)) { + support++; + } + if (isSolid(voids, originX, originZ, localX, y, localZ + 1, worldHeight)) { + support++; + } + if (isSolid(voids, originX, originZ, localX, y, localZ - 1, worldHeight)) { + support++; + } + if (isSolid(voids, originX, originZ, localX, y + 1, localZ, worldHeight)) { + support++; + } + return support >= MIN_SUPPORTED_NEIGHBOURS; + } + + private static boolean isSolid(MantleLayer voids, int originX, int originZ, int localX, int y, int localZ, int worldHeight) { + if (localX < 0 || localX >= CHUNK_WIDTH || localZ < 0 || localZ >= CHUNK_WIDTH) { + return false; + } + return y >= worldHeight || voids.get(originX + localX, y, originZ + localZ) == null; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveRejects.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveRejects.java new file mode 100644 index 000000000..cdfcc382b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveRejects.java @@ -0,0 +1,68 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.objects.ObjectPlacement; +import com.volmit.object.PlaceableObject; +import com.volmit.ModuleLog; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +/** Debug lines for cave objects that were not placed, at most one per kind of rejection every few seconds. */ +final class CaveRejects { + private static final long THROTTLE_MILLIS = 5000L; + private static final Map STATES = new ConcurrentHashMap<>(); + + private CaveRejects() { + } + + static void log(ModuleLog log, String scope, String reason, int chunkX, int chunkZ, ObjectPlacement placement, + PlaceableObject object, int densityIndex, int density, CaveAnchors.Search search, Integer anchorY, Throwable error) { + if (!log.debugging()) { + return; + } + String placementKeys = placement == null ? "none" : String.join(",", placement.place()); + String objectKey = object == null ? "null" : object.name(); + String throttleKey = scope + "|" + reason + "|" + placementKeys + "|" + objectKey; + State state = STATES.computeIfAbsent(throttleKey, key -> new State()); + long now = System.currentTimeMillis(); + long last = state.lastLogMillis.get(); + if ((now - last) < THROTTLE_MILLIS || !state.lastLogMillis.compareAndSet(last, now)) { + state.suppressed.incrementAndGet(); + return; + } + int suppressed = state.suppressed.getAndSet(0); + String errorText = error == null ? "none" : error.getClass().getSimpleName() + ":" + error.getMessage(); + log.debug("Cave object reject: scope=" + scope + " reason=" + reason + " chunk=" + chunkX + "," + chunkZ + " object=" + objectKey + + " placements=" + placementKeys + " densityIndex=" + densityIndex + " density=" + density + + " anchorMode=" + search.mode() + " anchorSearchAttempts=" + search.attempts() + " anchorScanStep=" + search.scanStep() + + " minDepthBelowSurface=" + search.minDepthBelowSurface() + " anchorY=" + (anchorY == null ? "none" : anchorY) + + " forcePlace=" + (placement != null && placement.forcePlace()) + + " carvingSupport=" + (placement == null ? "none" : placement.carvingSupport()) + + " suppressed=" + suppressed + " error=" + errorText); + } + + private static final class State { + private final AtomicLong lastLogMillis = new AtomicLong(0L); + private final AtomicInteger suppressed = new AtomicInteger(0); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java new file mode 100644 index 000000000..a62b89d82 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java @@ -0,0 +1,88 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.carve.CaveAnchorMode; +import art.arcane.iris.modules.carve.CaveProfile; +import art.arcane.iris.builtin.objects.ObjectPlacement; + +/** What a cave object placement takes from the cave profile that applies to it. */ +final class CaveSettings { + private static final CaveProfile DEFAULT_PROFILE = new CaveProfile(); + private static final int DEFAULT_SCAN_STEP = 1; + private static final int DEFAULT_MIN_DEPTH_BELOW_SURFACE = 6; + private static final int DEFAULT_SEARCH_ATTEMPTS = 6; + + private final CaveProfile dimensionProfile; + + CaveSettings(CaveProfile dimensionProfile) { + this.dimensionProfile = dimensionProfile; + } + + /** The profile of the first of {@code preferred} and {@code secondary} that is enabled, else the dimension's, else the default one. */ + CaveProfile resolve(CaveProfile preferred, CaveProfile secondary) { + if (preferred != null && preferred.enabled()) { + return preferred; + } + if (secondary != null && secondary.enabled()) { + return secondary; + } + if (dimensionProfile != null) { + return dimensionProfile; + } + return DEFAULT_PROFILE; + } + + /** How the placement looks for its anchor in caves: its own mode, else the profile's, else the floor; turned upside down, the ceiling. */ + CaveAnchors.Search searchFor(ObjectPlacement placement, CaveProfile profile) { + CaveAnchorMode mode = anchorMode(placement, profile); + if (placement.mode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { + mode = CaveAnchorMode.CEILING; + } + return new CaveAnchors.Search(mode, scanStep(profile), minDepthBelowSurface(profile), searchAttempts(profile)); + } + + private static CaveAnchorMode anchorMode(ObjectPlacement placement, CaveProfile profile) { + CaveAnchorMode placementMode = placement.caveAnchorMode(); + if (placementMode != null && !placementMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) { + return placementMode; + } + if (profile == null) { + return CaveAnchorMode.FLOOR; + } + CaveAnchorMode profileMode = profile.defaultObjectAnchor(); + if (profileMode == null || profileMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) { + return CaveAnchorMode.FLOOR; + } + return profileMode; + } + + private static int scanStep(CaveProfile profile) { + return profile == null ? DEFAULT_SCAN_STEP : Math.max(1, profile.anchorScanStep()); + } + + private static int minDepthBelowSurface(CaveProfile profile) { + return profile == null ? DEFAULT_MIN_DEPTH_BELOW_SURFACE : Math.max(0, profile.objectMinDepthBelowSurface()); + } + + private static int searchAttempts(CaveProfile profile) { + return profile == null ? DEFAULT_SEARCH_ATTEMPTS : Math.max(1, profile.anchorSearchAttempts()); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java new file mode 100644 index 000000000..d54dcc9aa --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -0,0 +1,590 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; +import art.arcane.iris.modules.carve.CaveProfile; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; +import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; +import art.arcane.iris.builtin.objects.UpperObjectsForceSettings; +import art.arcane.iris.builtin.objects.UpperObjectsSettings; +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; +import art.arcane.iris.modules.objects.CavePlacement; +import art.arcane.iris.modules.objects.TerrainTransaction; +import art.arcane.iris.modules.objects.ObjectPool; +import art.arcane.iris.modules.objects.ObjectSeparation; +import art.arcane.iris.modules.objects.PlacementChanges; +import art.arcane.iris.modules.objects.PlacementTags; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.IrisFeature; +import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.ResourceId; +import com.volmit.stage.MantleStageContext; +import com.volmit.placement.PlacementRecord; +import com.volmit.world.TerrainSampler; + +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; + +/** + * Places what the objects of one chunk's region and biomes say: the objects of its surface, caves and the terrain stacked + * above, in that order, all drawing from the one random of the chunk. + */ +final class ChunkObjectPlacing { + /** Objects read their chunk's settings at local 8, 8 as Iris always did, not at the API's centre column (local 7, 7): moving it would move objects. */ + private static final int OBJECT_COLUMN_OFFSET_BLOCKS = 8; + private static final int CHUNK_WIDTH_BLOCKS = 16; + private static final double CHANCE_JITTER = 0.005; + private static final int[] CAVE_BIOME_SAMPLE_DEPTHS = {48, 80, 112}; + private static final int LEGACY_CAVE_SAMPLE_DEPTH = 48; + private static final int UPPER_SURFACE_MARGIN_BLOCKS = 2; + private static final int MINIMUM_UPPER_ANCHOR_Y = 1; + private static final int DIAGNOSTIC_CHUNK_MASK = 31; + private static final int DIAGNOSTIC_SURFACE_MARGIN = 14; + private static final String TREE_FOLDER = "trees/"; + private static final String REGEN_THREAD_PREFIX = "Iris-Regen-"; + + private final ObjectPool objects; + private final ObjectSeparation separation; + private final ModuleLog log; + private final MantleStageContext context; + private final ObjectChunk chunk; + private final TerrainSampler terrain; + private final int chunkX; + private final int chunkZ; + private final int centerX; + private final int centerZ; + private final RNG rng; + private final boolean traceRegen; + private final boolean golden; + private final EffectivePlacements effective; + private final CaveSettings caves; + private final int worldHeight; + private final int caveLavaHeight; + + ChunkObjectPlacing(ObjectPool objects, ModuleLog log, MantleStageContext context) { + this.objects = objects; + this.separation = ObjectSeparation.of(context.world()); + this.log = log; + this.context = context; + this.chunk = new ObjectChunk(context, log); + this.terrain = context.terrain(); + this.chunkX = context.chunkX(); + this.chunkZ = context.chunkZ(); + this.centerX = context.originX() + OBJECT_COLUMN_OFFSET_BLOCKS; + this.centerZ = context.originZ() + OBJECT_COLUMN_OFFSET_BLOCKS; + this.rng = objects.chunkRandom(chunkX, chunkZ); + this.traceRegen = Thread.currentThread().getName().startsWith(REGEN_THREAD_PREFIX) && log.debugging(); + this.golden = chunk.goldenDebug(chunkX, chunkZ); + this.worldHeight = context.mantle().bounds().maxY(); + this.caveLavaHeight = Optional.ofNullable(dimensionLevel(CaveLavaHeightSettings.class)).orElseGet(CaveLavaHeightSettings::new).height(); + this.effective = new EffectivePlacements(dimensionRequiresSurfaceSupport(), dimensionSurfaceSupportBuffer()); + this.caves = new CaveSettings(dimensionLevel(CaveProfile.class)); + } + + /** Places what originates in this chunk. */ + void place() { + Column column = readColumn(); + if (log.debugging() && (chunkX & DIAGNOSTIC_CHUNK_MASK) == 0 && (chunkZ & DIAGNOSTIC_CHUNK_MASK) == 0) { + logCaveDiagnostics(column); + } + if (traceRegen) { + logLayerStart(column); + } + Tally tally = placeObjects(column); + if (upperObjectsEnabled()) { + placeUpperObjects(column); + } + if (traceRegen) { + logLayerDone(tally); + } + } + + /** The region and biomes at the chunk's centre and what each declares. */ + private Column readColumn() { + ResourceId region = terrain.biome(centerX, terrain.bounds().minY(), centerZ).region(); + ResourceId surface = terrain.surfaceBiome(centerX, centerZ); + int surfaceY = terrain.surfaceHeight(centerX, centerZ); + ResourceId cave = resolveCaveObjectBiome(surfaceY, surface); + return new Column(region, surface, cave, surfaceY, objectsOf(cave, region, surface), profilesOf(cave, region, surface)); + } + + private ResourceId resolveCaveObjectBiome(int surfaceY, ResourceId surfaceBiome) { + ResourceId legacy = caveBiomeAt(Math.max(1, surfaceY - LEGACY_CAVE_SAMPLE_DEPTH)).orElse(surfaceBiome); + ResourceId ladderChoice = null; + for (int depth : CAVE_BIOME_SAMPLE_DEPTHS) { + Optional sampled = caveBiomeAt(Math.max(1, surfaceY - depth)); + if (sampled.isEmpty() || sampled.get().equals(surfaceBiome)) { + continue; + } + if (hasCarvingObjects(context.settings().declaredBy(sampled.get(), ObjectSettings.class))) { + ladderChoice = sampled.get(); + } + } + return ladderChoice != null ? ladderChoice : legacy; + } + + private Optional caveBiomeAt(int y) { + return terrain.biome(centerX, y, centerZ).caveBiome(); + } + + private static boolean hasCarvingObjects(Optional settings) { + return settings.isPresent() && !carvingObjects(settings.get()).isEmpty(); + } + + private ColumnObjects objectsOf(ResourceId cave, ResourceId region, ResourceId surface) { + SettingsStack declared = context.settings().at(ObjectSettings.class, centerX, centerZ); + return new ColumnObjects(levelValue(declared, Level.BIOME), caveSettings(cave, surface, declared, ObjectSettings.class), + levelValue(declared, Level.REGION)); + } + + private ColumnProfiles profilesOf(ResourceId cave, ResourceId region, ResourceId surface) { + SettingsStack declared = context.settings().at(CaveProfile.class, centerX, centerZ); + return new ColumnProfiles(levelValue(declared, Level.BIOME), caveSettings(cave, surface, declared, CaveProfile.class), + levelValue(declared, Level.REGION)); + } + + private F caveSettings(ResourceId cave, ResourceId surface, SettingsStack declared, Class type) { + if (cave.equals(surface)) { + return levelValue(declared, Level.BIOME); + } + return context.settings().declaredBy(cave, type).orElse(null); + } + + private F dimensionLevel(Class type) { + return levelValue(context.settings().at(type, centerX, centerZ), Level.DIMENSION); + } + + /** The value {@code level} declares, or null: the column records below hold null for a level that declares nothing. */ + private static F levelValue(SettingsStack declared, Level level) { + return declared.level(level).orElse(null); + } + + private boolean dimensionRequiresSurfaceSupport() { + RequireSurfaceSupportSettings settings = dimensionLevel(RequireSurfaceSupportSettings.class); + return settings == null ? new RequireSurfaceSupportSettings().require() : settings.require(); + } + + private int dimensionSurfaceSupportBuffer() { + SurfaceSupportBufferSettings settings = dimensionLevel(SurfaceSupportBufferSettings.class); + return settings == null ? new SurfaceSupportBufferSettings().buffer() : settings.buffer(); + } + + private boolean upperObjectsEnabled() { + UpperObjectsSettings settings = dimensionLevel(UpperObjectsSettings.class); + return settings != null && settings.enabled() && terrain.upperDimensionY(centerX, centerZ).isPresent(); + } + + private boolean upperObjectsForced() { + UpperObjectsForceSettings settings = dimensionLevel(UpperObjectsForceSettings.class); + return settings != null && settings.force(); + } + + private static List surfaceObjects(ObjectSettings settings) { + return settings == null ? List.of() : settings.objects().stream().filter(p -> p.carvingSupport().supportsSurface()).toList(); + } + + private static List carvingObjects(ObjectSettings settings) { + return settings == null ? List.of() : settings.objects().stream().filter(p -> p.carvingSupport().supportsCarving()).toList(); + } + + private CaveAnchors newAnchors() { + return new CaveAnchors(chunk.carved(), terrain, worldHeight, caveLavaHeight); + } + + private Tally placeObjects(Column column) { + Tally tally = new Tally(); + CaveProfile biomeCaveProfile = caves.resolve(column.profiles().cave(), column.profiles().region()); + CaveProfile regionCaveProfile = caves.resolve(column.profiles().region(), column.profiles().cave()); + CaveAnchors anchors = newAnchors(); + placeSurfaceScope(tally, "biome-surface", surfaceObjects(column.objects().surface()), column.surface().toString()); + placeCaveScope(tally, "biome-cave", carvingObjects(column.objects().cave()), biomeCaveProfile, column.cave(), column.cave().toString(), anchors); + placeSurfaceScope(tally, "region-surface", surfaceObjects(column.objects().region()), column.region().toString()); + placeCaveScope(tally, "region-cave", carvingObjects(column.objects().region()), regionCaveProfile, null, column.region().toString(), anchors); + return tally; + } + + private void placeSurfaceScope(Tally tally, String scope, List placements, String ownerName) { + for (ObjectPlacement placement : placements) { + tally.checked(scope); + try { + if (placement.isSeparated()) { + placeSeparatedObject(tally, placement, scope); + continue; + } + boolean passes = rng.chance(separation.chanceAt(placement, centerX, centerZ) + rng.d(-CHANCE_JITTER, CHANCE_JITTER)); + traceChance(scope, passes, placement); + if (!passes) { + continue; + } + tally.triggered(scope); + placeObject(tally, placement, scope); + } catch (Throwable failure) { + tally.errors++; + logPlacementFailure("Failed to place objects in the following " + ownerKind(scope) + ": " + ownerName, placement, failure); + } + } + } + + /** Places the one object the chunk's candidate stands for, when no closer candidate of a lower rank outranks it. */ + private void placeSeparatedObject(Tally tally, ObjectPlacement placement, String scope) { + Optional kept = separation.keptCandidate(chunkX, chunkZ, placement, context.settings()); + traceChance(scope, kept.isPresent(), placement); + if (kept.isEmpty()) { + return; + } + tally.triggered(scope); + ObjectSeparation.Candidate candidate = kept.get(); + tally.attempts++; + Optional picked = objects.pickScaled(placement, candidate.rng()); + if (picked.isEmpty()) { + tally.nullObjects++; + traceNullObject(scope, 0, 1, placement); + return; + } + placeOnSurfaceAt(tally, placement, scope, picked.get(), candidate.x(), candidate.z(), candidate.rng(), 0, 1); + } + + private void placeCaveScope(Tally tally, String scope, List placements, CaveProfile profile, + ResourceId expectedCaveBiome, String ownerName, CaveAnchors anchors) { + for (ObjectPlacement placement : placements) { + tally.checked(scope); + boolean passes = rng.chance(placement.chance()); + traceChance(scope, passes, placement); + if (!passes) { + continue; + } + tally.triggered(scope); + try { + placeCaveObject(tally, placement, profile, scope, expectedCaveBiome, anchors); + } catch (Throwable failure) { + tally.errors++; + logPlacementFailure("Failed to place cave objects in the following " + ownerKind(scope) + ": " + ownerName, placement, failure); + } + } + } + + private static String ownerKind(String scope) { + return scope.startsWith("biome") ? "biome" : "region"; + } + + private void logPlacementFailure(String message, ObjectPlacement placement, Throwable failure) { + log.error(message, failure); + log.error("Object(s) " + String.join(", ", placement.place()) + " (" + failure.getClass().getSimpleName() + ").", null); + log.error("Are these objects missing?", null); + } + + private void placeObject(Tally tally, ObjectPlacement placement, String scope) { + int blockX = context.originX(); + int blockZ = context.originZ(); + int density = objects.density(placement, blockX, blockZ); + for (int i = 0; i < density; i++) { + tally.attempts++; + Optional picked = objects.pickScaled(placement, rng); + if (picked.isEmpty()) { + tally.nullObjects++; + traceNullObject(scope, i, density, placement); + continue; + } + int x = rng.i(blockX, blockX + CHUNK_WIDTH_BLOCKS); + int z = rng.i(blockZ, blockZ + CHUNK_WIDTH_BLOCKS); + placeOnSurfaceAt(tally, placement, scope, picked.get(), x, z, rng, i, density); + } + } + + private void placeOnSurfaceAt(Tally tally, ObjectPlacement placement, String scope, PlaceableObject object, int x, int z, + RNG placingRng, int densityIndex, int density) { + PlacementChanges changes = effective.forSurface(placement, object); + boolean treePlacement = isTreePlacement(object, placement); + int id = placingRng.i(0, Integer.MAX_VALUE); + String goldenTag = golden ? scope + "/" + object.name() : null; + if (golden) { + log.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + + " densityIndex=" + densityIndex + " xx=" + x + " zz=" + z + " mode=" + placement.mode()); + } + try { + PlacementTags tags = tags(object, id, "surface", treePlacement, placement); + int result = chunk.placeOnSurface(object, x, z, placement, changes, tags, goldenTag); + if (result >= 0) { + tally.placed++; + } else { + tally.rejected++; + } + traceObjectResult(scope, object, result, x, z, densityIndex, density); + } catch (Throwable failure) { + tally.errors++; + log.error("Regen object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + + " densityIndex=" + densityIndex + " density=" + density + " error=" + failure.getClass().getSimpleName() + ":" + failure.getMessage(), failure); + } + } + + private void placeCaveObject(Tally tally, ObjectPlacement placement, CaveProfile profile, String scope, + ResourceId expectedCaveBiome, CaveAnchors anchors) { + int minX = context.originX(); + int minZ = context.originZ(); + int density = objects.density(placement, minX, minZ); + CaveAnchors.Search search = caves.searchFor(placement, profile); + for (int i = 0; i < density; i++) { + tally.attempts++; + Optional picked = objects.pickScaled(placement, rng); + if (picked.isEmpty()) { + tally.nullObjects++; + traceNullObject(scope, i, density, placement); + CaveRejects.log(log,scope, "NULL_OBJECT", chunkX, chunkZ, placement, null, i, density, search, null, null); + continue; + } + PlaceableObject object = picked.get(); + CaveAnchors.Anchor anchor = anchors.find(rng, minX, minZ, search, expectedCaveBiome, placement.underwater()); + if (anchor == null) { + tally.rejected++; + CaveRejects.log(log,scope, "NO_ANCHOR", chunkX, chunkZ, placement, object, i, density, search, null, null); + continue; + } + int id = rng.i(0, Integer.MAX_VALUE); + PlacementChanges changes = effective.forCave(placement, object, profile); + try { + PlacementTags tags = tags(object, id, "cave", isTreePlacement(object, placement), placement); + CavePlacement contained = chunk.placeInCave(object, anchor.x(), anchor.y(), anchor.z(), placement, changes, + search.minDepthBelowSurface(), tags, null); + tallyCave(tally, contained, scope, object, placement, i, density, search, anchor); + } catch (Throwable failure) { + tally.errors++; + log.error("Regen cave object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + + " densityIndex=" + i + " density=" + density + " error=" + failure.getClass().getSimpleName() + ":" + failure.getMessage(), failure); + CaveRejects.log(log,scope, "EXCEPTION", chunkX, chunkZ, placement, object, i, density, search, anchor.y(), failure); + } + } + } + + private void tallyCave(Tally tally, CavePlacement contained, String scope, PlaceableObject object, ObjectPlacement placement, + int index, int density, CaveAnchors.Search search, CaveAnchors.Anchor anchor) { + if (contained.wroteBlocks()) { + tally.placed++; + } else { + tally.rejected++; + CaveRejects.log(log,scope, rejectReason(contained), chunkX, chunkZ, placement, object, index, density, search, anchor.y(), null); + } + if (traceRegen) { + log.debug("Regen cave object placement result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + + " resultY=" + contained.resultY() + " anchorY=" + anchor.y() + " px=" + anchor.x() + " pz=" + anchor.z() + + " wroteBlocks=" + contained.wroteBlocks() + " densityIndex=" + index + " density=" + density); + } + } + + private static String rejectReason(CavePlacement contained) { + if (contained.resultY() < 0) { + return "PLACE_NEGATIVE"; + } + return contained.commit() == TerrainTransaction.Commit.REJECTED ? "CONTAINMENT" : "NO_WRITES"; + } + + private void placeUpperObjects(Column column) { + SettingsStack upper = terrain.upperDimension() + .map(dimension -> dimension.settings().at(ObjectSettings.class, centerX, centerZ)) + .orElse(SettingsStack.empty()); + Optional> biome = levelEntry(upper, Level.BIOME); + Optional> region = levelEntry(upper, Level.REGION); + if (biome.isEmpty() && region.isEmpty()) { + return; + } + boolean forcePlace = upperObjectsForced(); + biome.ifPresent(declared -> placeUpperScope(declared, "upper-biome-surface", "biome", forcePlace)); + region.ifPresent(declared -> placeUpperScope(declared, "upper-region-surface", "region", forcePlace)); + } + + private static Optional> levelEntry(SettingsStack declared, Level level) { + return declared.entries().stream().filter(entry -> entry.level() == level).findFirst(); + } + + private void placeUpperScope(Entry declared, String scope, String kind, boolean forcePlace) { + String ownerKey = declared.source().toString(); + for (ObjectPlacement placement : surfaceObjects(declared.value())) { + if (!rng.chance(placement.chance() + rng.d(-CHANCE_JITTER, CHANCE_JITTER))) { + continue; + } + try { + placeUpperObject(placement, forcePlace, scope); + } catch (Throwable failure) { + log.error("Failed to place upper-dimension objects in " + kind + " " + ownerKey + ": " + String.join(", ", placement.place()) + + " (" + failure.getClass().getSimpleName() + ")", failure); + } + } + } + + private void placeUpperObject(ObjectPlacement placement, boolean forcePlace, String scope) { + int minX = context.originX(); + int minZ = context.originZ(); + int density = objects.density(placement, minX, minZ); + for (int i = 0; i < density; i++) { + Optional picked = objects.pickScaled(placement, rng); + if (picked.isEmpty()) { + continue; + } + PlaceableObject object = picked.get(); + int x = rng.i(minX, minX + CHUNK_WIDTH_BLOCKS); + int z = rng.i(minZ, minZ + CHUNK_WIDTH_BLOCKS); + OptionalInt upperSurface = terrain.upperDimensionY(x, z); + if (upperSurface.isEmpty() || upperSurface.getAsInt() >= worldHeight - UPPER_SURFACE_MARGIN_BLOCKS) { + continue; + } + int anchorY = upperSurface.getAsInt() - 1 - Math.floorDiv(object.height(), 2); + if (anchorY <= MINIMUM_UPPER_ANCHOR_Y) { + continue; + } + int id = rng.i(0, Integer.MAX_VALUE); + PlacementChanges changes = PlacementChanges.NONE.withPlace(List.of(String.valueOf(object.name()))) + .withMode(ObjectPlaceMode.CENTER_HEIGHT) + .withUpsideDown(true).withCarvingSupport(CarvingMode.ANYWHERE); + if (forcePlace) { + changes = changes.withForcePlace(true); + } + PlacementTags tags = tags(object, id, "upper", isTreePlacement(object, placement), placement); + int result = chunk.placeUpper(object, x, anchorY, z, placement, changes, tags); + if (traceRegen) { + log.debug("Upper object placement: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + " anchorY=" + + anchorY + " upperSurfaceY=" + upperSurface.getAsInt() + " resultY=" + result + " forcePlace=" + forcePlace); + } + } + } + + private PlacementTags tags(PlaceableObject object, int id, String context, boolean treePlacement, ObjectPlacement placement) { + boolean buriedTreasure = placement.isDolphinTarget() && placement.underwater(); + return new PlacementTags(placementMarker(object, id, context), treePlacement, buriedTreasure); + } + + private PlacementRecord placementMarker(PlaceableObject object, int id, String context) { + String key = object == null ? null : object.name(); + if (key == null || key.isEmpty() || key.equals("null")) { + String fingerprint = context + "|" + (object == null ? "" : object.getClass().getSimpleName()); + log.warnOnce(fingerprint, "Skipping placement marker write: the object has no loadKey (context=" + context + "). " + + "This would previously produce 'Couldn't find Object: null' warnings on chunk reload."); + return null; + } + return PlacementRecord.of(this.context.world().resources().idOf(key), id); + } + + /** Objects in {@code trees/} are trees, procedural ones in {@code procedural/trees/} too, and so is anything a placement grows from saplings. */ + private static boolean isTreePlacement(PlaceableObject object, ObjectPlacement placement) { + String key = object == null ? null : object.name(); + if (key != null && ProceduralObjectCatalog.isProceduralKey(key)) { + key = key.substring(ProceduralObjectCatalog.KEY_PREFIX.length()); + } + return (key != null && key.startsWith(TREE_FOLDER)) || (placement != null && !placement.trees().isEmpty()); + } + + private void traceChance(String scope, boolean passes, ObjectPlacement placement) { + if (!traceRegen) { + return; + } + log.debug("Regen object placer chance: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " chanceResult=" + passes + + " chanceBase=" + placement.chance() + " densityMid=" + placement.middleDensity() + " objects=" + placement.place().size()); + } + + private void traceNullObject(String scope, int index, int density, ObjectPlacement placement) { + if (!traceRegen) { + return; + } + log.debug("Regen object placement null object: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " densityIndex=" + index + + " density=" + density + " placementKeys=" + String.join(",", placement.place())); + } + + private void traceObjectResult(String scope, PlaceableObject object, int result, int x, int z, int index, int density) { + if (golden) { + log.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + + " resultY=" + result + " fallback=surface"); + } + if (traceRegen) { + log.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + + " resultY=" + result + " px=" + x + " pz=" + z + " fallback=surface densityIndex=" + index + " density=" + density); + } + } + + private void logCaveDiagnostics(Column column) { + int carvedBlocks = 0; + int maxY = Math.min(worldHeight - 1, column.surfaceY() - DIAGNOSTIC_SURFACE_MARGIN); + for (int y = 1; y < maxY; y++) { + if (chunk.carved().isCarved(centerX, y, centerZ)) { + carvedBlocks++; + } + } + log.debug("Cave object diag: chunk=" + chunkX + "," + chunkZ + " surfaceBiome=" + column.surface() + " caveBiome=" + column.cave() + + " surfaceY=" + column.surfaceY() + " maxAnchorY=" + maxY + " carvedAtCenter=" + carvedBlocks + + " biomeCarvingObjects=" + carvingObjects(column.objects().cave()).size() + + " regionCarvingObjects=" + carvingObjects(column.objects().region()).size() + + " sameBiome=" + column.cave().equals(column.surface())); + } + + private void logLayerStart(Column column) { + log.debug("Regen object layer start: chunk=" + chunkX + "," + chunkZ + " surfaceBiome=" + column.surface() + " caveBiome=" + column.cave() + + " region=" + column.region() + " biomeSurfacePlacers=" + surfaceObjects(column.objects().surface()).size() + + " biomeCavePlacers=" + carvingObjects(column.objects().cave()).size() + + " regionSurfacePlacers=" + surfaceObjects(column.objects().region()).size() + + " regionCavePlacers=" + carvingObjects(column.objects().region()).size()); + } + + private void logLayerDone(Tally tally) { + log.debug("Regen object layer done: chunk=" + chunkX + "," + chunkZ + " " + tally.describe() + + " objectAttempts=" + tally.attempts + " objectPlaced=" + tally.placed + " objectRejected=" + tally.rejected + + " objectNull=" + tally.nullObjects + " objectErrors=" + tally.errors); + } + + private record Column(ResourceId region, ResourceId surface, ResourceId cave, int surfaceY, ColumnObjects objects, + ColumnProfiles profiles) { + } + + private record ColumnObjects(ObjectSettings surface, ObjectSettings cave, ObjectSettings region) { + } + + private record ColumnProfiles(CaveProfile surface, CaveProfile cave, CaveProfile region) { + } + + /** What placing the objects of a chunk came to. */ + private static final class Tally { + private final java.util.Map scopes = new java.util.LinkedHashMap<>(); + private int attempts; + private int placed; + private int rejected; + private int nullObjects; + private int errors; + + void checked(String scope) { + scopes.computeIfAbsent(scope, key -> new int[2])[0]++; + } + + void triggered(String scope) { + scopes.computeIfAbsent(scope, key -> new int[2])[1]++; + } + + String describe() { + StringBuilder text = new StringBuilder(); + scopes.forEach((scope, counts) -> text.append(scope).append("PlacersChecked=").append(counts[0]) + .append(' ').append(scope).append("PlacersTriggered=").append(counts[1]).append(' ')); + return text.toString(); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java new file mode 100644 index 000000000..a192f25cd --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java @@ -0,0 +1,90 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.modules.carve.CaveProfile; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.modules.objects.PlacementChanges; +import com.volmit.object.PlaceableObject; + +import java.util.List; +import java.util.Locale; + +/** How a dimension and a cave profile change the placement an object is placed with. */ +final class EffectivePlacements { + private static final String IMPORTS_FOLDER = "imports/"; + + private final boolean dimensionRequiresSurfaceSupport; + private final int dimensionSurfaceSupportBuffer; + + EffectivePlacements(boolean dimensionRequiresSurfaceSupport, int dimensionSurfaceSupportBuffer) { + this.dimensionRequiresSurfaceSupport = dimensionRequiresSurfaceSupport; + this.dimensionSurfaceSupportBuffer = dimensionSurfaceSupportBuffer; + } + + /** The changes to make to {@code placement} to place {@code object} on the surface. */ + PlacementChanges forSurface(ObjectPlacement placement, PlaceableObject object) { + return withDimensionSurfaceSupport(placement, withImportedMode(placement, object, PlacementChanges.NONE)); + } + + /** The changes to make to {@code placement} to place {@code object} in a cave with the cave profile {@code caveProfile}. */ + PlacementChanges forCave(ObjectPlacement placement, PlaceableObject object, CaveProfile caveProfile) { + PlacementChanges changes = forSurface(placement, object); + ObjectPlaceMode mode = changes.mode() != null ? changes.mode() : placement.mode(); + if (mode != ObjectPlaceMode.CENTER_HEIGHT || caveProfile == null) { + return changes; + } + ObjectPlaceMode profileMode = caveProfile.defaultObjectPlaceMode().orElse(null); + if (profileMode == null) { + return changes; + } + String key = object.name(); + List place = key == null || key.isBlank() ? List.of() : List.of(key); + return changes.withPlace(place).withMode(profileMode); + } + + /** Imported objects are placed with the fast minimal stilt unless their mode finds its own height. */ + private static PlacementChanges withImportedMode(ObjectPlacement placement, PlaceableObject object, PlacementChanges changes) { + String key = object.name(); + if (key == null || key.isBlank() || !isImported(key)) { + return changes; + } + ObjectPlaceMode mode = placement.mode(); + if (mode.placeMode().has(PlaceTrait.FREE_HEIGHT) || mode == ObjectPlaceMode.FAST_MIN_STILT) { + return changes; + } + return changes.withPlace(List.of(key)).withMode(ObjectPlaceMode.FAST_MIN_STILT); + } + + private static boolean isImported(String key) { + return key.toLowerCase(Locale.ROOT).contains(IMPORTS_FOLDER); + } + + /** The dimension widens the buffer of a placement, never narrows it, and its support requirement applies on top of the placement's own: both have to want it. */ + private PlacementChanges withDimensionSurfaceSupport(ObjectPlacement placement, PlacementChanges changes) { + boolean require = placement.requireSurfaceSupport() && dimensionRequiresSurfaceSupport; + int buffer = Math.max(placement.surfaceSupportBuffer(), dimensionSurfaceSupportBuffer); + if (require == placement.requireSurfaceSupport() && buffer == placement.surfaceSupportBuffer()) { + return changes; + } + return changes.withSurfaceSupport(require, buffer); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java new file mode 100644 index 000000000..8560fcea7 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java @@ -0,0 +1,68 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.engine.object.terrain.floating.Column; +import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; +import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; +import art.arcane.iris.engine.object.terrain.floating.FloatingWorld; +import com.volmit.ModuleLog; +import com.volmit.resource.ResourceId; + +import java.util.HashMap; +import java.util.Map; + +/** The island samples of the columns one chunk's floating objects ask about, each sampled once; null where no island is. */ +final class FloatingIslandSampleResolver implements IslandFace.SampleProvider { + private final FloatingWorld world; + private final int worldHeight; + private final FloatingIslandBoundarySampler boundarySampler; + private final Map samples = new HashMap<>(); + private final ModuleLog log; + + FloatingIslandSampleResolver(FloatingWorld world, int worldHeight, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { + this.world = world; + this.worldHeight = worldHeight; + this.boundarySampler = boundarySampler; + this.log = log; + } + + @Override + public FloatingIslandSample sample(int x, int z) { + Column key = new Column(x, z); + if (samples.containsKey(key)) { + return samples.get(key); + } + FloatingIslandSample sample = resolve(x, z); + samples.put(key, sample); + return sample; + } + + private FloatingIslandSample resolve(int x, int z) { + ResourceId parent = parent(x, z); + if (parent == null || world.declaredBy(parent).isEmpty()) { + return null; + } + return FloatingIslandSample.sample(parent, x, z, worldHeight, world, boundarySampler, log); + } + + ResourceId parent(int x, int z) { + return boundarySampler.parent(x, z); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java new file mode 100644 index 000000000..648ebe491 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -0,0 +1,508 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.modules.floating.FloatingChildBiome; +import art.arcane.iris.modules.floating.FloatingChildSettings; +import art.arcane.iris.modules.floating.IslandFootprint; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; +import art.arcane.iris.modules.objects.ObjectPool; +import art.arcane.iris.modules.objects.ObjectSize; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; +import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; +import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; +import art.arcane.iris.engine.object.terrain.floating.FloatingWorld; +import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; +import art.arcane.volmlib.util.cache.CacheKey; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.config.PackSettings; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.PackWorld; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Places the objects of floating child biomes on and under their islands into the mantle for + * {@link art.arcane.iris.engine.modifier.FloatingModule}. One per world. Its reach is the largest placement reach of any + * floating object the dimension's biomes can place, at least 16 blocks. + */ +public final class FloatingObjectPlacing { + private static final int INVERTED_PICK_ATTEMPTS = 8; + private static final long CHUNK_RANDOM_SALT = 0x0FA710BEL; + private static final int CHUNK_COLUMNS = 256; + private static final int MIN_REACH_BLOCKS = 16; + private static final int LARGE_REACH_WARNING_BLOCKS = 128; + private static final int FLAT_TOLERANCE_BLOCKS = 2; + private static final int LOOSE_FLAT_TOLERANCE_BLOCKS = 4; + private static final int QUARTER_TURN_DEGREES = 90; + private static final int QUARTER_TURNS = 4; + private static final double CHANCE_JITTER = 0.005; + private static final String BIOME_PATH_PREFIX = "biome/"; + + private final FloatingWorld world; + private final ObjectPool objects; + private final FloatingPlacer placer; + private final long mantleSeed; + private final ModuleLog log; + + FloatingObjectPlacing(FloatingWorld world, ObjectPool objects, FloatingPlacer placer, long mantleSeed, ModuleLog log) { + this.world = world; + this.objects = objects; + this.placer = placer; + this.mantleSeed = mantleSeed; + this.log = log; + } + + /** The floating object placing of {@code world}. */ + public static FloatingObjectPlacing of(PackWorld world, ModuleLog log) { + return world.state(FloatingObjectPlacing.class, + generating -> new FloatingObjectPlacing(FloatingWorld.of(generating), ObjectPool.of(generating), + new FloatingPlacer(generating, log), generating.seed(IrisSeedPurposes.MANTLE), log)); + } + + /** Places what originates in the chunk of {@code context} into the mantle. */ + public void place(MantleStageContext context) { + int minX = context.originX(); + int minZ = context.originZ(); + BlockBox bounds = context.terrain().bounds(); + int worldHeight = bounds.maxY() - bounds.minY(); + RNG chunkRng = new RNG(CacheKey.key(context.chunkX(), context.chunkZ()) + mantleSeed + CHUNK_RANDOM_SALT); + FloatingIslandSampleResolver samples = new FloatingIslandSampleResolver(world, worldHeight, + new FloatingIslandBoundarySampler(world::surfaceBiome), log); + + FloatingIslandSample.clearChunkMemo(); + Chunk chunk = new Chunk(context, minX, minZ,worldHeight, chunkRng, samples, sampleColumns(samples, minX, minZ)); + + // The maps are lookup indices only. Iteration MUST follow the encounter order of the deterministic 0..255 column + // scan: identity-hash order changes per JVM run, and the shared chunk random makes placement output depend on order. + Map> entryColumns = new IdentityHashMap<>(); + Map> bottomEntryColumns = new IdentityHashMap<>(); + KList entryOrder = new KList<>(); + KList bottomEntryOrder = new KList<>(); + for (int i = 0; i < CHUNK_COLUMNS; i++) { + FloatingIslandSample sample = chunk.samples[i]; + if (sample == null || sample.entry == null) { + continue; + } + int column = i; + entryColumns.computeIfAbsent(sample.entry, entry -> { + entryOrder.add(entry); + return new KList<>(); + }).add(column); + ResolvedFloatingChild bottomEntry = sample.bottomEntry(); + if (bottomEntry != null) { + bottomEntryColumns.computeIfAbsent(bottomEntry, entry -> { + bottomEntryOrder.add(entry); + return new KList<>(); + }).add(column); + } + } + + for (ResolvedFloatingChild entry : entryOrder) { + placeOnTop(chunk, entry, entryColumns.get(entry)); + } + for (ResolvedFloatingChild entry : bottomEntryOrder) { + placeUnder(chunk, entry, bottomEntryColumns.get(entry)); + } + } + + private static FloatingIslandSample[] sampleColumns(FloatingIslandSampleResolver samples, int minX, int minZ) { + FloatingIslandSample[] sampled = new FloatingIslandSample[CHUNK_COLUMNS]; + for (int xf = 0; xf < 16; xf++) { + for (int zf = 0; zf < 16; zf++) { + sampled[(zf << 4) | xf] = samples.sample(minX + xf, minZ + zf); + } + } + return sampled; + } + + private void placeOnTop(Chunk chunk, ResolvedFloatingChild entry, KList columns) { + if (columns.isEmpty()) { + return; + } + ResourceId target = targetOf(chunk, entry, columns); + + for (ObjectPlacement placement : entry.settings().floatingObjects()) { + placeFloating(chunk, placement, columns, entry); + } + + KList surface = target != null ? entry.resolveTopObjects(target) : null; + List extras = entry.settings().extraObjects(); + boolean hasSurface = surface != null && !surface.isEmpty(); + if (!hasSurface && extras.isEmpty()) { + return; + } + KList interior = interiorColumns(chunk, columns, entry, IslandFace.Side.TOP); + if (hasSurface) { + for (ObjectPlacement placement : surface) { + placeAnchored(chunk, placement, columns, interior, entry); + } + } + for (ObjectPlacement placement : extras) { + placeAnchored(chunk, placement, columns, interior, entry); + } + } + + private void placeUnder(Chunk chunk, ResolvedFloatingChild entry, KList columns) { + if (columns.isEmpty()) { + return; + } + ResourceId target = targetOf(chunk, entry, columns); + KList bottom = target != null ? entry.resolveBottomObjects() : null; + if (bottom == null || bottom.isEmpty()) { + return; + } + KList interior = interiorColumns(chunk, columns, entry, IslandFace.Side.BOTTOM); + for (ObjectPlacement placement : bottom) { + placeInverted(chunk, placement, columns, interior, entry); + } + } + + /** The biome the child's objects come from, its parent taken at the first of its columns. */ + private ResourceId targetOf(Chunk chunk, ResolvedFloatingChild entry, KList columns) { + int firstKey = columns.get(0); + ResourceId parent = chunk.resolver.parent(chunk.minX + (firstKey & 15), chunk.minZ + (firstKey >> 4)); + return entry.realBiome(parent); + } + + private void placeFloating(Chunk chunk, ObjectPlacement placement, KList columns, ResolvedFloatingChild entry) { + RNG rng = chunk.rng; + int density = objects.density(placement, chunk.minX, chunk.minZ); + for (int i = 0; i < density; i++) { + Optional picked = pick(placement, entry, rng); + if (picked.isEmpty()) { + continue; + } + int key = columns.get(rng.i(columns.size())); + placer.placeFloating(chunk.context, picked.get(), chunk.minX + (key & 15), chunk.minZ + (key >> 4), placement, rng); + } + } + + private void placeAnchored(Chunk chunk, ObjectPlacement placement, KList columns, KList interior, + ResolvedFloatingChild entry) { + RNG rng = chunk.rng; + int density = objects.density(placement, chunk.minX, chunk.minZ); + for (int i = 0; i < density; i++) { + Optional picked = pick(placement, entry, rng); + if (picked.isEmpty()) { + continue; + } + PlaceableObject object = picked.get(); + IslandFootprint footprint = placer.footprint(object); + + KList pool = interior.isEmpty() ? columns : interior; + int pickedKey = pool.get(rng.i(pool.size())); + int pickedXf = pickedKey & 15; + int pickedZf = pickedKey >> 4; + FloatingIslandSample pickedSample = chunk.samples[(pickedZf << 4) | pickedXf]; + if (pickedSample == null) { + continue; + } + int pickTopY = pickedSample.topY(); + int pickedX = chunk.minX + pickedXf; + int pickedZ = chunk.minZ + pickedZf; + if (!isFootprintFlat(footprint, pickedX, pickedZ, pickTopY, chunk.resolver, entry, FLAT_TOLERANCE_BLOCKS) + && !isFootprintFlat(footprint, pickedX, pickedZ, pickTopY, chunk.resolver, entry, LOOSE_FLAT_TOLERANCE_BLOCKS)) { + continue; + } + + int x = pickedX - footprint.tallestX(); + int z = pickedZ - footprint.tallestZ(); + int y = pickTopY + 1 - footprint.lowestSolidY(); + placer.placeOnTop(chunk.context, object, x, y, z, placement, IslandFace.top(chunk.resolver, entry, pickTopY, chunk.worldHeight), rng); + } + } + + private void placeInverted(Chunk chunk, ObjectPlacement placement, KList columns, KList interior, + ResolvedFloatingChild entry) { + RNG rng = chunk.rng; + int density = objects.density(placement, chunk.minX, chunk.minZ); + for (int i = 0; i < density; i++) { + Optional picked = pick(placement, entry, rng); + if (picked.isEmpty()) { + continue; + } + PlaceableObject object = picked.get(); + IslandFootprint footprint = placer.footprint(object); + UndersideTurn turn = new UndersideTurn(rng.i(QUARTER_TURNS) * QUARTER_TURN_DEGREES); + + Optional anchor = pickBottomAnchor(chunk, footprint, turn, interior.isEmpty() ? columns : interior, entry); + if (anchor.isEmpty()) { + continue; + } + int pickedXf = anchor.get().xf(); + int pickedZf = anchor.get().zf(); + int pickBottomY = anchor.get().bottomY(); + int x = invertedBaseX(chunk.minX, pickedXf, footprint, turn); + int z = invertedBaseZ(chunk.minZ, pickedZf, footprint, turn); + int y = invertedBaseY(pickBottomY, footprint, turn); + placer.placeUnder(chunk.context, object, x, y, z, turn.yRotation(), placement, + IslandFace.bottom(chunk.resolver, entry, pickBottomY, chunk.worldHeight), rng); + } + } + + private Optional pickBottomAnchor(Chunk chunk, IslandFootprint footprint, UndersideTurn turn, KList pool, + ResolvedFloatingChild entry) { + for (int attempt = 0; attempt < INVERTED_PICK_ATTEMPTS; attempt++) { + int pickedKey = pool.get(chunk.rng.i(pool.size())); + int candidateXf = pickedKey & 15; + int candidateZf = pickedKey >> 4; + FloatingIslandSample candidate = chunk.samples[(candidateZf << 4) | candidateXf]; + if (candidate == null) { + continue; + } + int candidateBottomY = candidate.bottomY(); + if (candidateBottomY < 0) { + continue; + } + int candidateX = chunk.minX + candidateXf; + int candidateZ = chunk.minZ + candidateZf; + if (!isFootprintFlatBottom(footprint, turn, candidateX, candidateZ, candidateBottomY, chunk.resolver, entry, FLAT_TOLERANCE_BLOCKS) + && !isFootprintFlatBottom(footprint, turn, candidateX, candidateZ, candidateBottomY, chunk.resolver, entry, + LOOSE_FLAT_TOLERANCE_BLOCKS)) { + continue; + } + return Optional.of(new BottomAnchor(candidateXf, candidateZf, candidateBottomY)); + } + return Optional.empty(); + } + + /** One draw of the chance, then the object the placement picks, scaled, and shrunk as the island shrinks its objects. */ + private Optional pick(ObjectPlacement placement, ResolvedFloatingChild entry, RNG rng) { + if (!rng.chance(placement.chance() + rng.d(-CHANCE_JITTER, CHANCE_JITTER))) { + return Optional.empty(); + } + Optional scaled = objects.pickScaled(placement, rng); + if (scaled.isEmpty() || !entry.hasObjectShrink()) { + return scaled; + } + return Optional.of(objects.resized(scaled.get(), entry.shrinkFactor())); + } + + static boolean isFootprintFlatBottom(IslandFootprint footprint, UndersideTurn turn, int pickedX, int pickedZ, int pickBottomY, + IslandFace.SampleProvider samples, ResolvedFloatingChild entry, int tolerance) { + BlockPosition anchor = invertedFootprintAnchor(footprint, turn); + long[] cells = footprint.columns(); + if (cells.length == 0) { + return false; + } + for (long encoded : cells) { + BlockPosition cell = turn.turn(IslandFootprint.columnX(encoded), 0, IslandFootprint.columnZ(encoded)); + int columnX = pickedX + cell.x() - anchor.x(); + int columnZ = pickedZ + cell.z() - anchor.z(); + FloatingIslandSample sample = samples.sample(columnX, columnZ); + if (!IslandFace.matchesAnchor(sample, entry, IslandFace.Side.BOTTOM)) { + return false; + } + int bottomY = sample.bottomY(); + if (bottomY < 0 || Math.abs(bottomY - pickBottomY) > tolerance) { + return false; + } + } + return true; + } + + static int invertedBaseX(int minX, int pickedXf, IslandFootprint footprint, UndersideTurn turn) { + return minX + pickedXf - invertedFootprintAnchor(footprint, turn).x(); + } + + static int invertedBaseY(int pickBottomY, IslandFootprint footprint, UndersideTurn turn) { + return pickBottomY - 1 - invertedSolidAnchor(footprint, turn).y(); + } + + static int invertedBaseZ(int minZ, int pickedZf, IslandFootprint footprint, UndersideTurn turn) { + return minZ + pickedZf - invertedFootprintAnchor(footprint, turn).z(); + } + + private static BlockPosition invertedFootprintAnchor(IslandFootprint footprint, UndersideTurn turn) { + return turn.turn(footprint.tallestX(), 0, footprint.tallestZ()); + } + + private static BlockPosition invertedSolidAnchor(IslandFootprint footprint, UndersideTurn turn) { + return turn.turn(footprint.tallestX(), footprint.lowestSolidY(), footprint.tallestZ()); + } + + static boolean isFootprintFlat(IslandFootprint footprint, int pickedX, int pickedZ, int pickTopY, + IslandFace.SampleProvider samples, ResolvedFloatingChild entry, int tolerance) { + long[] cells = footprint.columns(); + if (cells.length == 0) { + return false; + } + for (long encoded : cells) { + int columnX = pickedX + (IslandFootprint.columnX(encoded) - footprint.tallestX()); + int columnZ = pickedZ + (IslandFootprint.columnZ(encoded) - footprint.tallestZ()); + FloatingIslandSample sample = samples.sample(columnX, columnZ); + if (!IslandFace.matchesAnchor(sample, entry, IslandFace.Side.TOP) || Math.abs(sample.topY() - pickTopY) > tolerance) { + return false; + } + } + return true; + } + + private static KList interiorColumns(Chunk chunk, KList columns, ResolvedFloatingChild entry, IslandFace.Side side) { + KList interior = new KList<>(); + for (int key : columns) { + int x = chunk.minX + (key & 15); + int z = chunk.minZ + (key >> 4); + if (IslandFace.matchesAnchor(chunk.resolver.sample(x + 1, z), entry, side) + && IslandFace.matchesAnchor(chunk.resolver.sample(x - 1, z), entry, side) + && IslandFace.matchesAnchor(chunk.resolver.sample(x, z + 1), entry, side) + && IslandFace.matchesAnchor(chunk.resolver.sample(x, z - 1), entry, side)) { + interior.add(key); + } + } + return interior; + } + + /** How far, in blocks along X and Z, the floating objects of the pack {@code settings} describe may write beyond their chunk. */ + public static int reach(PackSettings settings, ModuleLog log) { + Reach reach = new Reach(settings.resources(), biomeObjectsOf(settings), log); + int maxObjectExtent = MIN_REACH_BLOCKS; + try { + for (Entry declared : settings.declared(FloatingChildSettings.class)) { + if (declared.level() != Level.BIOME) { + continue; + } + ResourceId biome = biomeIdOf(declared.source()); + for (FloatingChildBiome child : declared.value().children()) { + maxObjectExtent = Math.max(maxObjectExtent, reach.of(child, biome)); + } + } + } catch (Throwable e) { + log.error("Failed to work out the reach of the floating biomes' objects", e); + } + return maxObjectExtent; + } + + /** A settings entry's source names a biome as {@code biome/}; the pack's resources name it by the key alone. */ + private static ResourceId biomeIdOf(ResourceId source) { + String path = source.path(); + return path.startsWith(BIOME_PATH_PREFIX) ? new ResourceId(source.namespace(), path.substring(BIOME_PATH_PREFIX.length())) : source; + } + + /** The object settings every biome of the pack declares, by the biome's id. */ + private static Map biomeObjectsOf(PackSettings settings) { + Map byBiome = new HashMap<>(); + for (Entry declared : settings.declared(ObjectSettings.class)) { + if (declared.level() == Level.BIOME) { + byBiome.putIfAbsent(biomeIdOf(declared.source()), declared.value()); + } + } + return byBiome; + } + + /** The reach of floating children's objects, each object sized once. */ + private static final class Reach { + private final PackResources resources; + private final ProceduralObjectCatalog procedural; + private final Map biomeObjects; + private final ModuleLog log; + private final Map> sizes = new HashMap<>(); + private final Set warnedLargeObjects = new HashSet<>(); + + private Reach(PackResources resources, Map biomeObjects, ModuleLog log) { + this.resources = resources; + this.procedural = ProceduralObjectCatalog.detached(resources, log); + this.biomeObjects = biomeObjects; + this.log = log; + } + + /** + * The surface objects a child inherits: those of the biome it names when that biome declares objects, else its + * parent's. A named biome the pack lacks inherits the parent's while placing; one that declares no objects + * inherits none, so counting the parent's for it only widens the reach. + */ + private List inheritedSurfaceObjects(FloatingChildBiome child, ResourceId parent) { + ResourceId named = child.biome().isBlank() ? parent : ResourceId.ofPackKey(parent.namespace(), child.biome()); + ObjectSettings declared = biomeObjects.getOrDefault(named, biomeObjects.get(parent)); + return FloatingWorld.surfaceObjects(Optional.ofNullable(declared)); + } + + int of(FloatingChildBiome child, ResourceId parent) { + int reach = 0; + reach = Math.max(reach, placementRadius(child.floatingObjects())); + reach = Math.max(reach, placementRadius(child.extraObjects())); + reach = Math.max(reach, placementRadius(child.topObjectOverrides())); + reach = Math.max(reach, placementRadius(child.bottomObjectOverrides())); + try { + List surface = child.inheritObjects() ? inheritedSurfaceObjects(child, parent) : List.of(); + reach = Math.max(reach, placementRadius(ResolvedFloatingChild.topObjects(child, surface))); + reach = Math.max(reach, placementRadius(ResolvedFloatingChild.bottomObjects(child))); + } catch (Throwable e) { + log.error("Failed to work out the reach of a floating biome's objects", e); + } + return reach; + } + + private int placementRadius(List placements) { + int radius = 0; + for (ObjectPlacement placement : placements) { + if (placement == null) { + continue; + } + for (String objectKey : placement.place()) { + radius = Math.max(radius, objectReach(objectKey, placement)); + } + } + return radius; + } + + private int objectReach(String objectKey, ObjectPlacement placement) { + try { + Optional size = sizes.computeIfAbsent(objectKey, key -> PlacementReach.sizeOf(resources, procedural, key)); + if (size.isEmpty()) { + return 0; + } + int reach = PlacementReach.of(size.get(), placement); + if (reach > LARGE_REACH_WARNING_BLOCKS && warnedLargeObjects.add(objectKey)) { + log.warn("Floating object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); + } + return reach; + } catch (Throwable e) { + log.error("Failed to size a floating object", e); + return 0; + } + } + } + + private record BottomAnchor(int xf, int zf, int bottomY) { + } + + /** What one chunk's placements share: where it is, its random, and its columns' island samples. */ + private record Chunk(MantleStageContext context, int minX, int minZ, int worldHeight, RNG rng, + FloatingIslandSampleResolver resolver, FloatingIslandSample[] samples) { + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/FloatingPlacer.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/FloatingPlacer.java new file mode 100644 index 000000000..1a2f61d87 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/FloatingPlacer.java @@ -0,0 +1,244 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectRun; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.modules.floating.IslandAnchor; +import art.arcane.iris.modules.floating.IslandFootprint; +import art.arcane.iris.modules.objects.ForwardingTerrain; +import art.arcane.iris.modules.objects.TerrainTransaction; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.object.ObjectBlock; +import com.volmit.object.PlaceableObject; +import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementRecord; +import com.volmit.placement.PlacementTerrain; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.PackWorld; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Places the objects of floating islands through the pack's placement stages into the mantle of the chunk being + * generated: floating free, or against an island's top or underside, where nothing is written unless every block lands + * where the island lets it. Each object's blocks are recorded as its placement. + */ +final class FloatingPlacer { + private static final ObjectRotation NO_ROTATION = ObjectRotation.of(0, 0, 0); + private static final int SAMPLED_HEIGHT = -1; + private static final Set AIR_MATERIALS = Set.of("minecraft:air", "minecraft:cave_air"); + + private final PackWorld world; + private final BlockRegistry blocks; + private final ModuleLog log; + + FloatingPlacer(PackWorld world, ModuleLog log) { + this.world = world; + this.blocks = world.resources().blocks(); + this.log = log; + } + + /** Where {@code object} stands: its solid columns, its tallest column and that column's lowest solid block. */ + IslandFootprint footprint(PlaceableObject object) { + Map columns = new HashMap<>(); + for (ObjectBlock block : object.geometry().blocks()) { + if (!blocks.hasTrait(block.state(), BlockTrait.SOLID)) { + continue; + } + BlockPosition position = block.position(); + int[] column = columns.computeIfAbsent(IslandFootprint.column(position.x(), position.z()), + ignored -> new int[]{position.y(), 0}); + column[0] = Math.min(column[0], position.y()); + column[1]++; + } + if (columns.isEmpty()) { + return new IslandFootprint(0, 0, object.center().y(), new long[0]); + } + long tallest = tallestColumn(columns); + long[] footprint = columns.keySet().stream().mapToLong(Long::longValue).toArray(); + return new IslandFootprint(IslandFootprint.columnX(tallest), IslandFootprint.columnZ(tallest), columns.get(tallest)[0], footprint); + } + + /** The column with the most solid blocks; the lowest bottom wins a tie. */ + private static long tallestColumn(Map columns) { + long best = 0L; + int tallestCount = 0; + int tallestLow = Integer.MAX_VALUE; + for (Map.Entry entry : columns.entrySet()) { + int low = entry.getValue()[0]; + int count = entry.getValue()[1]; + if (count > tallestCount || (count == tallestCount && low < tallestLow)) { + tallestCount = count; + tallestLow = low; + best = entry.getKey(); + } + } + return best; + } + + /** Places {@code object} floating free at the column, into the chunk {@code context} generates. */ + void placeFloating(MantleStageContext context, PlaceableObject object, int worldX, int worldZ, ObjectPlacement placement, + RNG random) { + ObjectPlacement floating = placement.toBuilder().place(List.of(object.name())).build(); + int id = random.i(0, Integer.MAX_VALUE); + try { + place(ObjectRun.of(object, floating, worldX, SAMPLED_HEIGHT, worldZ), context.placementTerrain(), object, id); + } catch (Throwable failure) { + log.error("Failed to place a floating object", failure); + } + } + + /** + * Places {@code object} on an island's top, its lowest block at {@code y}; nothing is written unless every block it + * writes is one {@code anchor} lets it write. + */ + void placeOnTop(MantleStageContext context, PlaceableObject object, int worldX, int y, int worldZ, ObjectPlacement placement, + IslandAnchor anchor, RNG random) { + placeAgainstIsland(context, object, worldX, y, worldZ, placement, NO_ROTATION, anchor, random, "anchored"); + } + + /** Places {@code object} upside down under an island, turned {@code yRotation} degrees about Y, as {@link #placeOnTop} does on top. */ + void placeUnder(MantleStageContext context, PlaceableObject object, int worldX, int y, int worldZ, int yRotation, + ObjectPlacement placement, IslandAnchor anchor, RNG random) { + placeAgainstIsland(context, object, worldX, y, worldZ, placement, ObjectRotation.xFlip180WithY(yRotation), anchor, random, + "inverted"); + } + + private void placeAgainstIsland(MantleStageContext context, PlaceableObject object, int worldX, int y, int worldZ, + ObjectPlacement placement, ObjectRotation rotation, IslandAnchor anchor, RNG random, String kind) { + ObjectPlacement anchored = placement.toBuilder() + .place(List.of(object.name())) + .mode(placement.mode().onFloatingIsland()) + .translate(new ObjectTranslate()) + .rotation(rotation) + .forcePlace(true) + .bottom(false) + .build(); + IslandTransaction transaction = new IslandTransaction(new IslandTerrain(context.placementTerrain(), anchor), anchor); + int id = random.i(0, Integer.MAX_VALUE); + try { + boolean placed = place(ObjectRun.of(object, anchored, worldX, y, worldZ), transaction, object, id); + if (placed) { + transaction.commit(); + } else { + transaction.discard(); + } + } catch (Throwable failure) { + transaction.discard(); + log.error("Failed to place an " + kind + " floating object", failure); + } + } + + /** Places the run and records the object's placement beside each block it wrote that is not air. */ + private boolean place(ObjectRun run, PlacementTerrain terrain, PlaceableObject object, int id) { + if (!run.placeIn(world, terrain).isPlaced()) { + return false; + } + PlacementRecord placement = PlacementRecord.of(world.resources().idOf(object.name()), id); + for (BlockPosition position : run.objectBlocks()) { + if (placesBlock(terrain.get(position.x(), position.y(), position.z()))) { + terrain.recordPlacement(position.x(), position.y(), position.z(), placement); + } + } + return true; + } + + private boolean placesBlock(BlockState state) { + return blocks.hasTrait(state, BlockTrait.CUSTOM) || !AIR_MATERIALS.contains(state.material().toString()); + } + + /** + * The mantle as an object placed against an island sees it: heights are the island face's, nothing is under water, + * and only the blocks the anchor lets the object write are written. + */ + private static final class IslandTerrain extends ForwardingTerrain { + private final IslandAnchor anchor; + + private IslandTerrain(PlacementTerrain delegate, IslandAnchor anchor) { + super(delegate); + this.anchor = anchor; + } + + @Override + public int highest(int x, int z, boolean ignoreFluid) { + return anchor.faceY(x, z); + } + + @Override + public boolean isUnderwater(int x, int z) { + return false; + } + + @Override + public void set(int x, int y, int z, BlockState state) { + if (anchor.writes(x, y, z)) { + delegate().set(x, y, z, state); + } + } + + @Override + public void set(int x, int y, int z, BlockState state, BlockEntityData blockEntity) { + if (anchor.writes(x, y, z)) { + delegate().set(x, y, z, state, blockEntity); + } + } + + @Override + public void recordPlacement(int x, int y, int z, PlacementRecord placement) { + if (anchor.writes(x, y, z)) { + delegate().recordPlacement(x, y, z, placement); + } + } + + @Override + public void mark(PlacedMarker marker) { + BlockPosition position = marker.position(); + if (anchor.writes(position.x(), position.y(), position.z())) { + delegate().mark(marker); + } + } + } + + /** Writes an object placed against an island only when the anchor lets it write every block. */ + private static final class IslandTransaction extends TerrainTransaction { + private final IslandAnchor anchor; + + private IslandTransaction(PlacementTerrain delegate, IslandAnchor anchor) { + super(delegate); + this.anchor = anchor; + } + + @Override + protected boolean accepts(int x, int y, int z) { + return anchor.writes(x, y, z); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugTerrain.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugTerrain.java new file mode 100644 index 000000000..519772a98 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugTerrain.java @@ -0,0 +1,99 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.modules.objects.ForwardingTerrain; +import com.volmit.ModuleLog; +import com.volmit.placement.PlacementTerrain; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; + +/** + * A terrain that logs the questions a placement asks of it, for the chunks the golden-debug switch names: the + * {@code iris.goldendebug} system property, or else {@code plugins/Iris/goldendebug.txt}, holding + * {@code chunkX,chunkZ[,radius]}. + */ +final class GoldenDebugTerrain extends ForwardingTerrain { + private static final String SWITCH_PROPERTY = "iris.goldendebug"; + private static final File SWITCH_FILE = new File("plugins/Iris/goldendebug.txt"); + private static final int[] TARGET = parseTarget(readSwitch()); + + private final String tag; + private final ModuleLog log; + + GoldenDebugTerrain(PlacementTerrain delegate, String tag, ModuleLog log) { + super(delegate); + this.tag = tag; + this.log = log; + } + + /** Whether the switch names the chunk. */ + static boolean isGoldenDebugChunk(int chunkX, int chunkZ) { + return TARGET != null + && Math.abs(TARGET[0] - chunkX) <= TARGET[2] + && Math.abs(TARGET[1] - chunkZ) <= TARGET[2]; + } + + @Override + public int highest(int x, int z, boolean ignoreFluid) { + int result = delegate().highest(x, z, ignoreFluid); + log.debug("Goldendebug query: tag=" + tag + " getHighest(" + x + "," + z + ",ignoreFluid=" + ignoreFluid + ")=" + result); + return result; + } + + @Override + public boolean isCarved(int x, int y, int z) { + boolean result = delegate().isCarved(x, y, z); + log.debug("Goldendebug query: tag=" + tag + " isCarved(" + x + "," + y + "," + z + ")=" + result); + return result; + } + + private static String readSwitch() { + String property = System.getProperty(SWITCH_PROPERTY); + if (property != null && !property.isBlank()) { + return property; + } + if (!SWITCH_FILE.isFile()) { + return null; + } + try { + return Files.readString(SWITCH_FILE.toPath()).trim(); + } catch (IOException | SecurityException unreadable) { + return null; + } + } + + private static int[] parseTarget(String raw) { + if (raw == null || raw.isBlank()) { + return null; + } + String[] parts = raw.split(","); + if (parts.length != 2 && parts.length != 3) { + return null; + } + try { + int radius = parts.length == 3 ? Integer.parseInt(parts[2].trim()) : 0; + return new int[]{Integer.parseInt(parts[0].trim()), Integer.parseInt(parts[1].trim()), radius}; + } catch (NumberFormatException malformed) { + return null; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java new file mode 100644 index 000000000..f59d5e366 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java @@ -0,0 +1,2268 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.carve.CaveFieldModule; +import art.arcane.iris.modules.carve.CaveProfile; +import art.arcane.volmlib.util.math.M; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import com.volmit.config.Range; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; +import com.volmit.noise.StyledRange; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class IrisCaveCarver3D { + private static final int LOCAL_MASK = 15; + private static final int ADAPTIVE_MIN_PLANE_COLUMNS = 16; + private static final int ADAPTIVE_DEEP_SAMPLE_STEP = 8; + private static final double ADAPTIVE_LOCAL_RANGE_SCALE = 0.125D; + private static final double ADAPTIVE_DEEP_MARGIN_BOOST = 0.015D; + private static final int SURFACE_CEILING_FADE_DEPTH = 12; + private static final double SURFACE_CEILING_SOLID_EPSILON = 0.000001D; + + private final CaveProfile profile; + private final NoiseSampler baseDensity; + private final NoiseSampler detailDensity; + private final NoiseSampler warpDensity; + private final NoiseSampler surfaceBreakDensity; + private final NoiseSampler thresholdNoise; + private final int lavaHeight; + private final CaveFieldModuleState[] modules; + private final double inverseNormalization; + private final double normalizationFactor; + private final double baseWeight; + private final double detailWeight; + private final double detailMinContribution; + private final double detailMaxContribution; + private final double warpStrength; + private final boolean hasWarp; + private final boolean hasModules; + private final int warpResolution; + private final boolean allowFluid; + private final boolean fluidRequiresFloor; + private final int fluidMinDepthBelowSurface; + private final int fluidHeight; + private final int aquiferCeilingY; + private final int minHeight; + private final int worldHeight; + private final ThreadLocal scratchCache = ThreadLocal.withInitial(CaveCarveScratch::new); + + public IrisCaveCarver3D(CarveWorld world, CaveProfile profile) { + this.profile = profile; + List moduleStates = new ArrayList<>(); + + long carveSeed = world.carveSeed(); + this.baseDensity = world.noise().sampler(profile.baseDensityStyle(), carveSeed + 934_447); + this.detailDensity = world.noise().sampler(profile.detailDensityStyle(), carveSeed + 612_991); + this.warpDensity = world.noise().sampler(profile.warpStyle(), carveSeed + 770_713); + this.surfaceBreakDensity = world.noise().sampler(profile.surfaceBreakStyle(), carveSeed + 341_219); + this.thresholdNoise = world.noise().sampler(profile.densityThreshold().style(), carveSeed + 489_112); + this.baseWeight = profile.baseWeight(); + this.detailWeight = profile.detailWeight(); + this.warpStrength = profile.warpStrength(); + this.hasWarp = this.warpStrength > 0D; + this.warpResolution = 2; + this.allowFluid = profile.allowFluid(); + this.fluidRequiresFloor = profile.fluidRequiresFloor(); + this.fluidMinDepthBelowSurface = Math.max(0, profile.fluidMinDepthBelowSurface()); + this.fluidHeight = world.fluidHeight(); + this.worldHeight = world.height(); + this.aquiferCeilingY = world.height() - 1; + this.lavaHeight = world.lavaHeight(); + this.minHeight = world.minHeight(); + + double weight = Math.abs(baseWeight) + Math.abs(detailWeight); + int index = 0; + for (CaveFieldModule module : profile.modules()) { + NoiseSampler moduleDensity = world.noise().sampler(module.style(), carveSeed + 1_000_003L + (index * 65_537L)); + CaveFieldModuleState state = new CaveFieldModuleState(module, moduleDensity); + moduleStates.add(state); + weight += Math.abs(state.weight); + index++; + } + + this.modules = moduleStates.toArray(new CaveFieldModuleState[0]); + double normalization = weight <= 0 ? 1 : weight; + normalizationFactor = normalization; + inverseNormalization = 1D / normalization; + hasModules = modules.length > 0; + detailMinContribution = -detailWeight; + detailMaxContribution = detailWeight; + } + + public int carve( + MantleLayer voids, + int chunkX, + int chunkZ, + double[] columnWeights, + double minWeight, + double thresholdPenalty, + Range worldYRange, + int[] surfaceHeights + ) { + return carve(voids, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, surfaceHeights, null); + } + + public int carve( + MantleLayer voids, + int chunkX, + int chunkZ, + double[] columnWeights, + double minWeight, + double thresholdPenalty, + Range worldYRange, + int[] surfaceHeights, + Range overrideVerticalRange + ) { + CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); + int carved = carve(voids, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, + worldYRange, surfaceHeights, null, overrideVerticalRange, fluidSupportPlan); + fluidSupportPlan.resolve(voids, PowerOfTwoCoordinates.chunkToBlock(chunkX), PowerOfTwoCoordinates.chunkToBlock(chunkZ), worldHeight); + return carved; + } + + /** {@code surfaceHeights} are the rounded heights of the chunk's columns, packed as {@link PowerOfTwoCoordinates#packLocal16}. */ + int carve( + MantleLayer voids, + int chunkX, + int chunkZ, + double[] columnWeights, + double minWeight, + double thresholdPenalty, + Range worldYRange, + int[] surfaceHeights, + int[] surfaceFluidBoundaryStartY, + Range overrideVerticalRange, + CaveFluidSupportPlan fluidSupportPlan + ) { + CaveCarveScratch scratch = scratchCache.get(); + if (columnWeights == null || columnWeights.length < 256) { + if (!scratch.fullWeightsInitialized) { + Arrays.fill(scratch.fullWeights, 1D); + scratch.fullWeightsInitialized = true; + } + columnWeights = scratch.fullWeights; + } + + double resolvedMinWeight = Math.max(0D, Math.min(1D, minWeight)); + double resolvedThresholdPenalty = Math.max(0D, thresholdPenalty); + Range effectiveVerticalRange = overrideVerticalRange != null ? overrideVerticalRange : profile.verticalRange(); + int minY = Math.max(0, (int) Math.floor(effectiveVerticalRange.min())); + int maxY = Math.min(worldHeight - 1, (int) Math.ceil(effectiveVerticalRange.max())); + if (worldYRange != null) { + int rangeMinY = (int) Math.floor(worldYRange.min() - minHeight); + int rangeMaxY = (int) Math.ceil(worldYRange.max() - minHeight); + minY = Math.max(minY, rangeMinY); + maxY = Math.min(maxY, rangeMaxY); + } + int sampleStep = Math.max(1, profile.sampleStep()); + boolean exactSampling = sampleStep <= 2; + boolean adaptiveSampling = exactSampling && profile.adaptiveSampling(); + int adaptiveSampleStep = Math.max(2, profile.adaptiveSampleStep()); + double adaptiveThresholdMargin = Math.max(0D, profile.adaptiveThresholdMargin()); + int surfaceClearance = Math.max(0, profile.surfaceClearance()); + int surfaceBreakDepth = Math.max(0, profile.surfaceBreakDepth()); + double surfaceBreakNoiseThreshold = profile.surfaceBreakNoiseThreshold(); + double surfaceBreakThresholdBoost = Math.max(0, profile.surfaceBreakThresholdBoost()); + boolean allowSurfaceBreak = profile.allowSurfaceBreak(); + if (maxY < minY) { + return 0; + } + + int x0 = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int z0 = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + int[] columnMaxY = scratch.columnMaxY; + int[] fluidMaxY = scratch.fluidMaxY; + int[] surfaceBreakFloorY = scratch.surfaceBreakFloorY; + boolean[] surfaceBreakColumn = scratch.surfaceBreakColumn; + boolean[] surfaceCeilingColumn = scratch.surfaceCeilingColumn; + double[] columnThreshold = scratch.columnThreshold; + double[] clampedWeights = scratch.clampedColumnWeights; + double[] verticalEdgeFade = prepareVerticalEdgeFadeTable(scratch, minY, maxY); + prepareSurfaceClosureThresholdTable(scratch, minY, maxY); + CarvedVoid[] voidByY = prepareVoidByYTable(scratch, minY, maxY); + + // The threshold noise is constant for the carver, so it is built once (in the constructor) and the + // min==max / flat-style short circuits are decided here, as Iris's styled range has always decided them. + StyledRange densityThreshold = profile.densityThreshold(); + double thresholdMin = densityThreshold.min(); + double thresholdMax = densityThreshold.max(); + double thresholdBias = profile.thresholdBias(); + NoiseSampler thresholdDensity = null; + double constantThreshold = 0D; + if (thresholdMin == thresholdMax) { + constantThreshold = thresholdMin; + } else if (NoiseStyle.FLAT.equals(densityThreshold.style().style())) { + constantThreshold = M.lerp(thresholdMin, thresholdMax, 0.5); + } else { + thresholdDensity = thresholdNoise; + } + + for (int lx = 0; lx < 16; lx++) { + int x = x0 + lx; + for (int lz = 0; lz < 16; lz++) { + int z = z0 + lz; + int index = PowerOfTwoCoordinates.packLocal16(lx, lz); + int columnSurfaceY; + columnSurfaceY = surfaceHeights[index]; + int unclampedClearanceTopY = columnSurfaceY - surfaceClearance; + int clearanceTopY = Math.min(maxY, Math.max(minY, unclampedClearanceTopY)); + boolean breakColumn = allowSurfaceBreak + && surfaceBreakDensity.signed(x, z) >= surfaceBreakNoiseThreshold; + int columnTopY = breakColumn + ? Math.min(maxY, Math.max(minY, columnSurfaceY)) + : clearanceTopY; + + columnMaxY[index] = columnTopY; + fluidMaxY[index] = allowFluid + ? Math.min(fluidHeight, columnSurfaceY - fluidMinDepthBelowSurface) + : Integer.MIN_VALUE; + surfaceBreakFloorY[index] = Math.max(minY, columnSurfaceY - surfaceBreakDepth); + surfaceBreakColumn[index] = breakColumn; + surfaceCeilingColumn[index] = !breakColumn && unclampedClearanceTopY <= maxY; + columnThreshold[index] = (thresholdDensity == null + ? constantThreshold + : thresholdMin + (thresholdDensity.sample(x, z) * (thresholdMax - thresholdMin))) - thresholdBias; + clampedWeights[index] = clampColumnWeight(columnWeights[index]); + } + } + + int carved; + if (exactSampling) { + if (adaptiveSampling) { + carved = carvePassAdaptive( + voids, + x0, + z0, + minY, + maxY, + adaptiveSampleStep, + adaptiveThresholdMargin, + surfaceBreakThresholdBoost, + columnMaxY, + fluidMaxY, + surfaceFluidBoundaryStartY, + surfaceBreakFloorY, + surfaceBreakColumn, + columnThreshold, + clampedWeights, + verticalEdgeFade, + voidByY, + fluidRequiresFloor ? fluidSupportPlan : null, + resolvedMinWeight, + resolvedThresholdPenalty, + 0D, + false + ); + } else { + carved = carvePassExact( + voids, + x0, + z0, + minY, + maxY, + surfaceBreakThresholdBoost, + columnMaxY, + fluidMaxY, + surfaceFluidBoundaryStartY, + surfaceBreakFloorY, + surfaceBreakColumn, + columnThreshold, + clampedWeights, + verticalEdgeFade, + voidByY, + fluidRequiresFloor ? fluidSupportPlan : null, + resolvedMinWeight, + resolvedThresholdPenalty, + 0D, + false + ); + } + } else { + int latticeStep = sampleStep; + carved = carvePassLattice( + voids, + x0, + z0, + minY, + maxY, + latticeStep, + surfaceBreakThresholdBoost, + columnMaxY, + fluidMaxY, + surfaceFluidBoundaryStartY, + surfaceBreakFloorY, + surfaceBreakColumn, + columnThreshold, + clampedWeights, + verticalEdgeFade, + voidByY, + fluidRequiresFloor ? fluidSupportPlan : null, + resolvedMinWeight, + resolvedThresholdPenalty, + 0D, + false + ); + if (carved == 0 && hasFallbackCandidates(columnMaxY, clampedWeights, minY, resolvedMinWeight)) { + carved += carvePassFallback( + voids, + x0, + z0, + minY, + maxY, + sampleStep, + surfaceBreakThresholdBoost, + columnMaxY, + fluidMaxY, + surfaceFluidBoundaryStartY, + surfaceBreakFloorY, + surfaceBreakColumn, + columnThreshold, + clampedWeights, + verticalEdgeFade, + voidByY, + fluidRequiresFloor ? fluidSupportPlan : null, + resolvedMinWeight, + resolvedThresholdPenalty, + 0D, + false + ); + } + } + + return carved; + } + + private int carvePassExact( + MantleLayer voids, + int x0, + int z0, + int minY, + int maxY, + double surfaceBreakThresholdBoost, + int[] columnMaxY, + int[] fluidMaxY, + int[] surfaceFluidBoundaryStartY, + int[] surfaceBreakFloorY, + boolean[] surfaceBreakColumn, + double[] columnThreshold, + double[] clampedWeights, + double[] verticalEdgeFade, + CarvedVoid[] voidByY, + CaveFluidSupportPlan fluidSupportPlan, + double minWeight, + double thresholdPenalty, + double thresholdBoost, + boolean skipExistingCarved + ) { + int carved = 0; + CaveCarveScratch scratch = scratchCache.get(); + double[] passThreshold = scratch.passThreshold; + int[] activeColumnIndices = scratch.activeColumnIndices; + int[] activeColumnTopY = scratch.activeColumnTopY; + int activeColumnCount = 0; + + for (int index = 0; index < 256; index++) { + double columnWeight = clampedWeights[index]; + if (columnWeight <= minWeight || columnMaxY[index] < minY) { + passThreshold[index] = Double.NaN; + continue; + } + + passThreshold[index] = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); + activeColumnIndices[activeColumnCount] = index; + activeColumnTopY[activeColumnCount] = columnMaxY[index]; + activeColumnCount++; + } + + if (activeColumnCount == 0) { + return 0; + } + + int[] planeColumnIndices = scratch.planeColumnIndices; + double[] planeThresholdLimit = scratch.planeThresholdLimit; + boolean[] planeCarve = scratch.planeCarve; + int minSection = PowerOfTwoCoordinates.floorDivPow2(minY, 4); + int maxSection = PowerOfTwoCoordinates.floorDivPow2(maxY, 4); + + for (int sectionIndex = minSection; sectionIndex <= maxSection; sectionIndex++) { + int sectionMinY = Math.max(minY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex)); + int sectionMaxY = Math.min(maxY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex) + 15); + + for (int y = sectionMinY; y <= sectionMaxY; y++) { + int planeCount = 0; + for (int activeIndex = 0; activeIndex < activeColumnCount; activeIndex++) { + if (activeColumnTopY[activeIndex] < y) { + continue; + } + + int columnIndex = activeColumnIndices[activeIndex]; + if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, columnIndex, y, fluidHeight)) { + continue; + } + planeColumnIndices[planeCount] = columnIndex; + double localThreshold = passThreshold[columnIndex]; + if (surfaceBreakColumn[columnIndex] && y >= surfaceBreakFloorY[columnIndex]) { + localThreshold += surfaceBreakThresholdBoost; + } + localThreshold -= verticalEdgeFade[y - minY]; + localThreshold = applySurfaceCeilingFade(scratch, localThreshold, columnIndex, y, minY); + planeThresholdLimit[planeCount] = localThreshold * normalizationFactor; + planeCount++; + } + + if (planeCount == 0) { + continue; + } + + classifyDensityPlane(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + int fadeIndex = y - minY; + CarvedVoid verticalVoid = voidByY[fadeIndex]; + + if (skipExistingCarved) { + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + if (!planeCarve[planeIndex]) { + continue; + } + + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + if (voids.get(x0 + localX, y, z0 + localZ) != null) { + continue; + } + + double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; + CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x0 + localX, y, z0 + localZ, + columnIndex, fluidMaxY, localThreshold); + writeVoid(voids, x0 + localX, y, z0 + localZ, carvedVoid, fluidSupportPlan); + carved++; + } + continue; + } + + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + if (!planeCarve[planeIndex]) { + continue; + } + + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; + CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x0 + localX, y, z0 + localZ, + columnIndex, fluidMaxY, localThreshold); + writeVoid(voids, x0 + localX, y, z0 + localZ, carvedVoid, fluidSupportPlan); + carved++; + } + } + } + + return carved; + } + + private int carvePassAdaptive( + MantleLayer voids, + int x0, + int z0, + int minY, + int maxY, + int adaptiveSampleStep, + double adaptiveThresholdMargin, + double surfaceBreakThresholdBoost, + int[] columnMaxY, + int[] fluidMaxY, + int[] surfaceFluidBoundaryStartY, + int[] surfaceBreakFloorY, + boolean[] surfaceBreakColumn, + double[] columnThreshold, + double[] clampedWeights, + double[] verticalEdgeFade, + CarvedVoid[] voidByY, + CaveFluidSupportPlan fluidSupportPlan, + double minWeight, + double thresholdPenalty, + double thresholdBoost, + boolean skipExistingCarved + ) { + int carved = 0; + CaveCarveScratch scratch = scratchCache.get(); + double[] passThreshold = scratch.passThreshold; + int[] activeColumnIndices = scratch.activeColumnIndices; + int[] activeColumnTopY = scratch.activeColumnTopY; + int activeColumnCount = 0; + + for (int index = 0; index < 256; index++) { + double columnWeight = clampedWeights[index]; + if (columnWeight <= minWeight || columnMaxY[index] < minY) { + passThreshold[index] = Double.NaN; + continue; + } + + passThreshold[index] = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); + activeColumnIndices[activeColumnCount] = index; + activeColumnTopY[activeColumnCount] = columnMaxY[index]; + activeColumnCount++; + } + + if (activeColumnCount == 0) { + return 0; + } + + int[] planeColumnIndices = scratch.planeColumnIndices; + double[] planeThresholdLimit = scratch.planeThresholdLimit; + boolean[] planeCarve = scratch.planeCarve; + int minSection = PowerOfTwoCoordinates.floorDivPow2(minY, 4); + int maxSection = PowerOfTwoCoordinates.floorDivPow2(maxY, 4); + int effectiveAdaptiveSampleStep = Math.max(adaptiveSampleStep, ADAPTIVE_DEEP_SAMPLE_STEP); + double effectiveAdaptiveThresholdMargin = resolveAdaptivePlaneThresholdMargin( + adaptiveThresholdMargin, + adaptiveSampleStep, + effectiveAdaptiveSampleStep + ); + + for (int sectionIndex = minSection; sectionIndex <= maxSection; sectionIndex++) { + int sectionMinY = Math.max(minY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex)); + int sectionMaxY = Math.min(maxY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex) + 15); + + for (int y = sectionMinY; y <= sectionMaxY; y++) { + int planeCount = 0; + for (int activeIndex = 0; activeIndex < activeColumnCount; activeIndex++) { + if (activeColumnTopY[activeIndex] < y) { + continue; + } + + int columnIndex = activeColumnIndices[activeIndex]; + if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, columnIndex, y, fluidHeight)) { + continue; + } + planeColumnIndices[planeCount] = columnIndex; + double localThreshold = passThreshold[columnIndex]; + if (surfaceBreakColumn[columnIndex] && y >= surfaceBreakFloorY[columnIndex]) { + localThreshold += surfaceBreakThresholdBoost; + } + localThreshold -= verticalEdgeFade[y - minY]; + localThreshold = applySurfaceCeilingFade(scratch, localThreshold, columnIndex, y, minY); + planeThresholdLimit[planeCount] = localThreshold * normalizationFactor; + planeCount++; + } + + if (planeCount == 0) { + continue; + } + + classifyDensityPlaneAdaptive( + scratch, + x0, + z0, + y, + planeColumnIndices, + planeThresholdLimit, + planeCount, + planeCarve, + effectiveAdaptiveSampleStep, + effectiveAdaptiveThresholdMargin + ); + int fadeIndex = y - minY; + CarvedVoid verticalVoid = voidByY[fadeIndex]; + + if (skipExistingCarved) { + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + if (!planeCarve[planeIndex]) { + continue; + } + + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + if (voids.get(x0 + localX, y, z0 + localZ) != null) { + continue; + } + + double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; + CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x0 + localX, y, z0 + localZ, + columnIndex, fluidMaxY, localThreshold); + writeVoid(voids, x0 + localX, y, z0 + localZ, carvedVoid, fluidSupportPlan); + carved++; + } + continue; + } + + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + if (!planeCarve[planeIndex]) { + continue; + } + + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; + CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x0 + localX, y, z0 + localZ, + columnIndex, fluidMaxY, localThreshold); + writeVoid(voids, x0 + localX, y, z0 + localZ, carvedVoid, fluidSupportPlan); + carved++; + } + } + } + + return carved; + } + + private double resolveAdaptivePlaneThresholdMargin( + double adaptiveThresholdMargin, + int adaptiveSampleStep, + int effectiveAdaptiveSampleStep + ) { + if (effectiveAdaptiveSampleStep <= adaptiveSampleStep) { + return adaptiveThresholdMargin; + } + + return adaptiveThresholdMargin + ((effectiveAdaptiveSampleStep - adaptiveSampleStep) * ADAPTIVE_DEEP_MARGIN_BOOST); + } + + private int carvePassLattice( + MantleLayer voids, + int x0, + int z0, + int minY, + int maxY, + int latticeStep, + double surfaceBreakThresholdBoost, + int[] columnMaxY, + int[] fluidMaxY, + int[] surfaceFluidBoundaryStartY, + int[] surfaceBreakFloorY, + boolean[] surfaceBreakColumn, + double[] columnThreshold, + double[] clampedWeights, + double[] verticalEdgeFade, + CarvedVoid[] voidByY, + CaveFluidSupportPlan fluidSupportPlan, + double minWeight, + double thresholdPenalty, + double thresholdBoost, + boolean skipExistingCarved + ) { + int carved = 0; + CaveCarveScratch scratch = scratchCache.get(); + double[] passThreshold = scratch.passThreshold; + int[] tileIndices = scratch.tileIndices; + int[] tileLocalX = scratch.tileLocalX; + int[] tileLocalZ = scratch.tileLocalZ; + int[] tileTopY = scratch.tileTopY; + + for (int index = 0; index < 256; index++) { + double columnWeight = clampedWeights[index]; + if (columnWeight <= minWeight || columnMaxY[index] < minY) { + passThreshold[index] = Double.NaN; + continue; + } + passThreshold[index] = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); + } + + for (int lx = 0; lx < 16; lx += 2) { + int x = x0 + lx; + int lx1 = lx + 1; + for (int lz = 0; lz < 16; lz += 2) { + int z = z0 + lz; + int lz1 = lz + 1; + int activeColumns = 0; + + int index00 = PowerOfTwoCoordinates.packLocal16(lx, lz); + if (!Double.isNaN(passThreshold[index00])) { + tileIndices[activeColumns] = index00; + tileLocalX[activeColumns] = lx; + tileLocalZ[activeColumns] = lz; + tileTopY[activeColumns] = columnMaxY[index00]; + activeColumns++; + } + + int index01 = PowerOfTwoCoordinates.packLocal16(lx, lz1); + if (!Double.isNaN(passThreshold[index01])) { + tileIndices[activeColumns] = index01; + tileLocalX[activeColumns] = lx; + tileLocalZ[activeColumns] = lz1; + tileTopY[activeColumns] = columnMaxY[index01]; + activeColumns++; + } + + int index10 = PowerOfTwoCoordinates.packLocal16(lx1, lz); + if (!Double.isNaN(passThreshold[index10])) { + tileIndices[activeColumns] = index10; + tileLocalX[activeColumns] = lx1; + tileLocalZ[activeColumns] = lz; + tileTopY[activeColumns] = columnMaxY[index10]; + activeColumns++; + } + + int index11 = PowerOfTwoCoordinates.packLocal16(lx1, lz1); + if (!Double.isNaN(passThreshold[index11])) { + tileIndices[activeColumns] = index11; + tileLocalX[activeColumns] = lx1; + tileLocalZ[activeColumns] = lz1; + tileTopY[activeColumns] = columnMaxY[index11]; + activeColumns++; + } + + if (activeColumns == 0) { + continue; + } + + int tileMaxY = minY; + for (int columnIndex = 0; columnIndex < activeColumns; columnIndex++) { + if (tileTopY[columnIndex] > tileMaxY) { + tileMaxY = tileTopY[columnIndex]; + } + } + if (tileMaxY < minY) { + continue; + } + + for (int y = minY; y <= tileMaxY; y += latticeStep) { + double density = sampleDensityOptimized(scratch, x, y, z); + int stampMaxY = Math.min(maxY, y + 1); + for (int yy = y; yy <= stampMaxY; yy++) { + CarvedVoid verticalVoid = voidByY[yy - minY]; + int fadeIndex = yy - minY; + for (int columnIndex = 0; columnIndex < activeColumns; columnIndex++) { + if (yy > tileTopY[columnIndex]) { + continue; + } + + int index = tileIndices[columnIndex]; + if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, index, yy, fluidHeight)) { + continue; + } + double localThreshold = passThreshold[index]; + if (surfaceBreakColumn[index] && yy >= surfaceBreakFloorY[index]) { + localThreshold += surfaceBreakThresholdBoost; + } + localThreshold -= verticalEdgeFade[fadeIndex]; + localThreshold = applySurfaceCeilingFade(scratch, localThreshold, index, yy, minY); + if (density > localThreshold) { + continue; + } + + int localX = tileLocalX[columnIndex]; + int localZ = tileLocalZ[columnIndex]; + int worldX = x0 + localX; + int worldZ = z0 + localZ; + CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, worldX, yy, worldZ, + index, fluidMaxY, localThreshold); + if (skipExistingCarved) { + if (voids.get(worldX, yy, worldZ) == null) { + writeVoid(voids, worldX, yy, worldZ, carvedVoid, fluidSupportPlan); + carved++; + } + continue; + } + + writeVoid(voids, worldX, yy, worldZ, carvedVoid, fluidSupportPlan); + carved++; + } + } + } + } + } + + return carved; + } + + private int carvePassFallback( + MantleLayer voids, + int x0, + int z0, + int minY, + int maxY, + int sampleStep, + double surfaceBreakThresholdBoost, + int[] columnMaxY, + int[] fluidMaxY, + int[] surfaceFluidBoundaryStartY, + int[] surfaceBreakFloorY, + boolean[] surfaceBreakColumn, + double[] columnThreshold, + double[] clampedWeights, + double[] verticalEdgeFade, + CarvedVoid[] voidByY, + CaveFluidSupportPlan fluidSupportPlan, + double minWeight, + double thresholdPenalty, + double thresholdBoost, + boolean skipExistingCarved + ) { + int carved = 0; + CaveCarveScratch scratch = scratchCache.get(); + + for (int lx = 0; lx < 16; lx++) { + int x = x0 + lx; + for (int lz = 0; lz < 16; lz++) { + int z = z0 + lz; + int index = PowerOfTwoCoordinates.packLocal16(lx, lz); + double columnWeight = clampedWeights[index]; + if (columnWeight <= minWeight) { + continue; + } + + int columnTopY = columnMaxY[index]; + if (columnTopY < minY) { + continue; + } + + boolean breakColumn = surfaceBreakColumn[index]; + int breakFloorY = surfaceBreakFloorY[index]; + double threshold = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); + + for (int y = minY; y <= columnTopY; y += sampleStep) { + double density = sampleDensityOptimized(scratch, x, y, z); + int carveMaxY = Math.min(columnTopY, y + sampleStep - 1); + for (int yy = y; yy <= carveMaxY; yy++) { + if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, index, yy, fluidHeight)) { + continue; + } + double localThreshold = threshold; + if (breakColumn && yy >= breakFloorY) { + localThreshold += surfaceBreakThresholdBoost; + } + localThreshold -= verticalEdgeFade[yy - minY]; + localThreshold = applySurfaceCeilingFade(scratch, localThreshold, index, yy, minY); + if (density > localThreshold) { + continue; + } + CarvedVoid verticalVoid = voidByY[yy - minY]; + CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x, yy, z, + index, fluidMaxY, localThreshold); + if (skipExistingCarved) { + if (voids.get(x, yy, z) == null) { + writeVoid(voids, x, yy, z, carvedVoid, fluidSupportPlan); + carved++; + } + continue; + } + + writeVoid(voids, x, yy, z, carvedVoid, fluidSupportPlan); + carved++; + } + } + } + } + + return carved; + } + + private boolean hasFallbackCandidates(int[] columnMaxY, double[] clampedWeights, int minY, double minWeight) { + for (int index = 0; index < 256; index++) { + if (clampedWeights[index] <= minWeight) { + continue; + } + + if (columnMaxY[index] >= minY) { + return true; + } + } + + return false; + } + + private double sampleDensityOptimized(int x, int y, int z) { + if (!hasWarp && !hasModules) { + return sampleDensityNoWarpNoModules(x, y, z); + } + + return sampleDensityOptimized(scratchCache.get(), x, y, z); + } + + private double sampleDensityOptimized(CaveCarveScratch scratch, int x, int y, int z) { + if (!hasWarp) { + if (!hasModules) { + return sampleDensityNoWarpNoModules(x, y, z); + } + + return sampleDensityNoWarpModules(scratch, x, y, z); + } + + if (!hasModules) { + return sampleDensityWarpOnly(scratch, x, y, z); + } + + return sampleDensityWarpModules(scratch, x, y, z); + } + + private void classifyDensityPlane(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { + if (!hasWarp) { + if (!hasModules) { + classifyDensityPlaneNoWarpNoModules(x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + return; + } + + classifyDensityPlaneNoWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + return; + } + + if (!hasModules) { + classifyDensityPlaneWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + return; + } + + classifyDensityPlaneWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + } + + private void classifyDensityPlaneAdaptive( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin + ) { + if (adaptiveSampleStep <= 1 || planeCount < ADAPTIVE_MIN_PLANE_COLUMNS) { + classifyDensityPlane(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + return; + } + + if (!hasWarp) { + if (!hasModules) { + classifyDensityPlaneAdaptiveNoWarpNoModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); + return; + } + + classifyDensityPlaneAdaptiveNoWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); + return; + } + + if (!hasModules) { + classifyDensityPlaneAdaptiveWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); + return; + } + + classifyDensityPlaneAdaptiveWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); + } + + private void classifyDensityPlaneNoWarpNoModules(int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int z = z0 + (columnIndex & 15); + planeCarve[planeIndex] = classifyDensityPointNoWarpNoModules(x, y, z, planeThresholdLimit[planeIndex]); + } + } + + private void classifyDensityPlaneNoWarpModules(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { + int activeModuleCount = prepareActiveModules(scratch, y); + if (activeModuleCount == 0) { + classifyDensityPlaneNoWarpNoModules(x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + return; + } + + CaveFieldModuleState[] localModules = scratch.activeModules; + double[] remainingMin = scratch.activeModuleRemainingMin; + double[] remainingMax = scratch.activeModuleRemainingMax; + + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int z = z0 + (columnIndex & 15); + planeCarve[planeIndex] = classifyDensityPointNoWarpModules( + x, + y, + z, + planeThresholdLimit[planeIndex], + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + } + } + + private void classifyDensityPlaneWarpOnly(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int z = z0 + (columnIndex & 15); + planeCarve[planeIndex] = classifyDensityPointWarpOnly(scratch, x, y, z, planeThresholdLimit[planeIndex]); + } + } + + private void classifyDensityPlaneWarpModules(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { + int activeModuleCount = prepareActiveModules(scratch, y); + if (activeModuleCount == 0) { + classifyDensityPlaneWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + return; + } + + CaveFieldModuleState[] localModules = scratch.activeModules; + double[] remainingMin = scratch.activeModuleRemainingMin; + double[] remainingMax = scratch.activeModuleRemainingMax; + + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int z = z0 + (columnIndex & 15); + planeCarve[planeIndex] = classifyDensityPointWarpModules( + scratch, + x, + y, + z, + planeThresholdLimit[planeIndex], + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + } + } + + private void classifyDensityPlaneAdaptiveNoWarpNoModules( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin + ) { + double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; + int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; + int axisSamples = axisCells + 1; + int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; + prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); + for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { + int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); + int x = x0 + sampleLocalX; + int rowOffset = sampleXIndex * axisSamples; + for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { + int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); + adaptivePlaneDensity[rowOffset + sampleZIndex] = sampleDensityNoWarpNoModules(x, y, z0 + sampleLocalZ); + } + } + + classifyAdaptivePlaneColumnsNoWarpNoModules( + scratch, + x0, + z0, + y, + planeColumnIndices, + planeThresholdLimit, + planeCount, + planeCarve, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples + ); + } + + private void classifyDensityPlaneAdaptiveNoWarpModules( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin + ) { + int activeModuleCount = prepareActiveModules(scratch, y); + if (activeModuleCount == 0) { + classifyDensityPlaneAdaptiveNoWarpNoModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); + return; + } + + CaveFieldModuleState[] localModules = scratch.activeModules; + double[] remainingMin = scratch.activeModuleRemainingMin; + double[] remainingMax = scratch.activeModuleRemainingMax; + double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; + int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; + int axisSamples = axisCells + 1; + int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; + prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); + for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { + int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); + int x = x0 + sampleLocalX; + int rowOffset = sampleXIndex * axisSamples; + for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { + int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); + adaptivePlaneDensity[rowOffset + sampleZIndex] = sampleDensityNoWarpNoModules(x, y, z0 + sampleLocalZ); + } + } + + classifyAdaptivePlaneColumnsNoWarpModules( + scratch, + x0, + z0, + y, + planeColumnIndices, + planeThresholdLimit, + planeCount, + planeCarve, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples, + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + } + + private void classifyDensityPlaneAdaptiveWarpOnly( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin + ) { + double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; + int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; + int axisSamples = axisCells + 1; + int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; + prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); + for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { + int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); + int x = x0 + sampleLocalX; + int rowOffset = sampleXIndex * axisSamples; + for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { + int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); + adaptivePlaneDensity[rowOffset + sampleZIndex] = sampleDensityWarpOnly(scratch, x, y, z0 + sampleLocalZ); + } + } + + classifyAdaptivePlaneColumnsWarpOnly( + scratch, + x0, + z0, + y, + planeColumnIndices, + planeThresholdLimit, + planeCount, + planeCarve, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples + ); + } + + private void classifyDensityPlaneAdaptiveWarpModules( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin + ) { + int activeModuleCount = prepareActiveModules(scratch, y); + if (activeModuleCount == 0) { + classifyDensityPlaneAdaptiveWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); + return; + } + + CaveFieldModuleState[] localModules = scratch.activeModules; + double[] remainingMin = scratch.activeModuleRemainingMin; + double[] remainingMax = scratch.activeModuleRemainingMax; + double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; + int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; + int axisSamples = axisCells + 1; + int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; + prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); + for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { + int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); + int x = x0 + sampleLocalX; + int rowOffset = sampleXIndex * axisSamples; + for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { + int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); + adaptivePlaneDensity[rowOffset + sampleZIndex] = sampleDensityWarpModules( + scratch, + x, + y, + z0 + sampleLocalZ, + localModules, + activeModuleCount + ); + } + } + + classifyAdaptivePlaneColumnsWarpModulesSampled( + scratch, + x0, + z0, + y, + planeColumnIndices, + planeThresholdLimit, + planeCount, + planeCarve, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples, + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + } + + private void classifyAdaptivePlaneColumnsNoWarpNoModules( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin, + double[] adaptivePlaneDensity, + int axisCells, + int axisSamples + ) { + double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; + double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; + prepareAdaptivePlaneColumns( + scratch, + planeColumnIndices, + planeCount, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples, + adaptivePlanePrediction, + adaptivePlaneAmbiguity + ); + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; + double predictedDensity = adaptivePlanePrediction[planeIndex]; + double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; + if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { + planeCarve[planeIndex] = predictedDensity <= threshold; + continue; + } + if (predictedDensity <= threshold - ambiguityMargin) { + planeCarve[planeIndex] = true; + continue; + } + if (predictedDensity > threshold + ambiguityMargin) { + planeCarve[planeIndex] = false; + continue; + } + if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { + planeCarve[planeIndex] = predictedDensity <= threshold; + continue; + } + + planeCarve[planeIndex] = classifyDensityPointNoWarpNoModules(x0 + localX, y, z0 + localZ, planeThresholdLimit[planeIndex]); + } + } + + private void classifyAdaptivePlaneColumnsNoWarpModules( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin, + double[] adaptivePlaneDensity, + int axisCells, + int axisSamples, + CaveFieldModuleState[] localModules, + int activeModuleCount, + double[] remainingMin, + double[] remainingMax + ) { + double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; + double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; + prepareAdaptivePlaneColumns( + scratch, + planeColumnIndices, + planeCount, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples, + adaptivePlanePrediction, + adaptivePlaneAmbiguity + ); + double minRemaining = remainingMin[0] * inverseNormalization; + double maxRemaining = remainingMax[0] * inverseNormalization; + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; + double predictedDensity = adaptivePlanePrediction[planeIndex]; + double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; + if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { + planeCarve[planeIndex] = classifyDensityPointNoWarpModulesFromExactDensity( + x0 + localX, + y, + z0 + localZ, + threshold, + predictedDensity, + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + continue; + } + if ((predictedDensity + maxRemaining) <= threshold - ambiguityMargin) { + planeCarve[planeIndex] = true; + continue; + } + if ((predictedDensity + minRemaining) > threshold + ambiguityMargin) { + planeCarve[planeIndex] = false; + continue; + } + if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { + planeCarve[planeIndex] = predictedDensity <= threshold; + continue; + } + + planeCarve[planeIndex] = classifyDensityPointNoWarpModules( + x0 + localX, + y, + z0 + localZ, + planeThresholdLimit[planeIndex], + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + } + } + + private void classifyAdaptivePlaneColumnsWarpOnly( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin, + double[] adaptivePlaneDensity, + int axisCells, + int axisSamples + ) { + double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; + double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; + prepareAdaptivePlaneColumns( + scratch, + planeColumnIndices, + planeCount, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples, + adaptivePlanePrediction, + adaptivePlaneAmbiguity + ); + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; + double predictedDensity = adaptivePlanePrediction[planeIndex]; + double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; + if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { + planeCarve[planeIndex] = predictedDensity <= threshold; + continue; + } + if (predictedDensity <= threshold - ambiguityMargin) { + planeCarve[planeIndex] = true; + continue; + } + if (predictedDensity > threshold + ambiguityMargin) { + planeCarve[planeIndex] = false; + continue; + } + if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { + planeCarve[planeIndex] = predictedDensity <= threshold; + continue; + } + + planeCarve[planeIndex] = classifyDensityPointWarpOnly(scratch, x0 + localX, y, z0 + localZ, planeThresholdLimit[planeIndex]); + } + } + + private void classifyAdaptivePlaneColumnsWarpModules( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin, + double[] adaptivePlaneDensity, + int axisCells, + int axisSamples, + CaveFieldModuleState[] localModules, + int activeModuleCount, + double[] remainingMin, + double[] remainingMax + ) { + double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; + double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; + prepareAdaptivePlaneColumns( + scratch, + planeColumnIndices, + planeCount, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples, + adaptivePlanePrediction, + adaptivePlaneAmbiguity + ); + double minRemaining = remainingMin[0] * inverseNormalization; + double maxRemaining = remainingMax[0] * inverseNormalization; + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; + double predictedDensity = adaptivePlanePrediction[planeIndex]; + double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; + if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { + planeCarve[planeIndex] = classifyDensityPointWarpModulesFromExactDensity( + scratch, + x0 + localX, + y, + z0 + localZ, + threshold, + predictedDensity, + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + continue; + } + if ((predictedDensity + maxRemaining) <= threshold - ambiguityMargin) { + planeCarve[planeIndex] = true; + continue; + } + if ((predictedDensity + minRemaining) > threshold + ambiguityMargin) { + planeCarve[planeIndex] = false; + continue; + } + + planeCarve[planeIndex] = classifyDensityPointWarpModules( + scratch, + x0 + localX, + y, + z0 + localZ, + planeThresholdLimit[planeIndex], + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + } + } + + private void classifyAdaptivePlaneColumnsWarpModulesSampled( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin, + double[] adaptivePlaneDensity, + int axisCells, + int axisSamples, + CaveFieldModuleState[] localModules, + int activeModuleCount, + double[] remainingMin, + double[] remainingMax + ) { + double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; + double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; + prepareAdaptivePlaneColumns( + scratch, + planeColumnIndices, + planeCount, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples, + adaptivePlanePrediction, + adaptivePlaneAmbiguity + ); + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; + double predictedDensity = adaptivePlanePrediction[planeIndex]; + double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; + if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { + planeCarve[planeIndex] = predictedDensity <= threshold; + continue; + } + if (predictedDensity <= threshold - ambiguityMargin) { + planeCarve[planeIndex] = true; + continue; + } + if (predictedDensity > threshold + ambiguityMargin) { + planeCarve[planeIndex] = false; + continue; + } + if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { + planeCarve[planeIndex] = predictedDensity <= threshold; + continue; + } + + planeCarve[planeIndex] = classifyDensityPointWarpModules( + scratch, + x0 + localX, + y, + z0 + localZ, + planeThresholdLimit[planeIndex], + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + } + } + + private boolean classifyDensityPointNoWarpNoModules(int x, int y, int z, double thresholdLimit) { + double density = baseDensity.signed(x, y, z) * baseWeight; + if ((density + detailMinContribution) > thresholdLimit) { + return false; + } + if ((density + detailMaxContribution) <= thresholdLimit) { + return true; + } + + density += detailDensity.signed(x, y, z) * detailWeight; + return density <= thresholdLimit; + } + + private boolean classifyDensityPointNoWarpModules( + int x, + int y, + int z, + double thresholdLimit, + CaveFieldModuleState[] localModules, + int activeModuleCount, + double[] remainingMin, + double[] remainingMax + ) { + if (activeModuleCount == 0) { + return classifyDensityPointNoWarpNoModules(x, y, z, thresholdLimit); + } + + double density = baseDensity.signed(x, y, z) * baseWeight; + if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) { + return false; + } + if ((density + detailMaxContribution + remainingMax[0]) <= thresholdLimit) { + return true; + } + + density += detailDensity.signed(x, y, z) * detailWeight; + if ((density + remainingMin[0]) > thresholdLimit) { + return false; + } + if ((density + remainingMax[0]) <= thresholdLimit) { + return true; + } + + for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { + density += localModules[moduleIndex].sample(x, y, z); + if ((density + remainingMin[moduleIndex + 1]) > thresholdLimit) { + return false; + } + if ((density + remainingMax[moduleIndex + 1]) <= thresholdLimit) { + return true; + } + } + + return density <= thresholdLimit; + } + + private int snapWarp(int c) { + int g = warpResolution; + if (g <= 1) { + return c; + } + if ((g & (g - 1)) == 0) { + return c & -g; + } + return Math.floorDiv(c, g) * g; + } + + private boolean classifyDensityPointWarpOnly(CaveCarveScratch scratch, int x, int y, int z, double thresholdLimit) { + int sx = snapWarp(x); + int sy = snapWarp(y); + int sz = snapWarp(z); + int warpSlot = prepareWarpSample(scratch, sx, sy, sz); + double warpA = scratch.warpCacheA[warpSlot]; + double warpB = scratch.warpCacheB[warpSlot]; + double warpedX = x + (warpA * warpStrength); + double warpedY = y + (warpB * warpStrength); + double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; + if ((density + detailMinContribution) > thresholdLimit) { + return false; + } + if ((density + detailMaxContribution) <= thresholdLimit) { + return true; + } + + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; + return density <= thresholdLimit; + } + + private boolean classifyDensityPointWarpModules( + CaveCarveScratch scratch, + int x, + int y, + int z, + double thresholdLimit, + CaveFieldModuleState[] localModules, + int activeModuleCount, + double[] remainingMin, + double[] remainingMax + ) { + if (activeModuleCount == 0) { + return classifyDensityPointWarpOnly(scratch, x, y, z, thresholdLimit); + } + + int sx = snapWarp(x); + int sy = snapWarp(y); + int sz = snapWarp(z); + int warpSlot = prepareWarpSample(scratch, sx, sy, sz); + double warpA = scratch.warpCacheA[warpSlot]; + double warpB = scratch.warpCacheB[warpSlot]; + double warpedX = x + (warpA * warpStrength); + double warpedY = y + (warpB * warpStrength); + double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; + if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) { + return false; + } + if ((density + detailMaxContribution + remainingMax[0]) <= thresholdLimit) { + return true; + } + + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; + if ((density + remainingMin[0]) > thresholdLimit) { + return false; + } + if ((density + remainingMax[0]) <= thresholdLimit) { + return true; + } + + for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { + density += localModules[moduleIndex].sample(warpedX, warpedY, warpedZ); + if ((density + remainingMin[moduleIndex + 1]) > thresholdLimit) { + return false; + } + if ((density + remainingMax[moduleIndex + 1]) <= thresholdLimit) { + return true; + } + } + + return density <= thresholdLimit; + } + + private boolean classifyDensityPointNoWarpModulesFromExactDensity( + int x, + int y, + int z, + double threshold, + double density, + CaveFieldModuleState[] localModules, + int activeModuleCount, + double[] remainingMin, + double[] remainingMax + ) { + if (activeModuleCount == 0) { + return density <= threshold; + } + + double minRemaining = remainingMin[0] * inverseNormalization; + double maxRemaining = remainingMax[0] * inverseNormalization; + if ((density + minRemaining) > threshold) { + return false; + } + if ((density + maxRemaining) <= threshold) { + return true; + } + + for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { + density += localModules[moduleIndex].sample(x, y, z) * inverseNormalization; + if ((density + (remainingMin[moduleIndex + 1] * inverseNormalization)) > threshold) { + return false; + } + if ((density + (remainingMax[moduleIndex + 1] * inverseNormalization)) <= threshold) { + return true; + } + } + + return density <= threshold; + } + + private boolean classifyDensityPointWarpModulesFromExactDensity( + CaveCarveScratch scratch, + int x, + int y, + int z, + double threshold, + double density, + CaveFieldModuleState[] localModules, + int activeModuleCount, + double[] remainingMin, + double[] remainingMax + ) { + if (activeModuleCount == 0) { + return density <= threshold; + } + + double minRemaining = remainingMin[0] * inverseNormalization; + double maxRemaining = remainingMax[0] * inverseNormalization; + if ((density + minRemaining) > threshold) { + return false; + } + if ((density + maxRemaining) <= threshold) { + return true; + } + + int sx = snapWarp(x); + int sy = snapWarp(y); + int sz = snapWarp(z); + int warpSlot = prepareWarpSample(scratch, sx, sy, sz); + double warpA = scratch.warpCacheA[warpSlot]; + double warpB = scratch.warpCacheB[warpSlot]; + double warpedX = x + (warpA * warpStrength); + double warpedY = y + (warpB * warpStrength); + double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); + for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { + density += localModules[moduleIndex].sample(warpedX, warpedY, warpedZ) * inverseNormalization; + if ((density + (remainingMin[moduleIndex + 1] * inverseNormalization)) > threshold) { + return false; + } + if ((density + (remainingMax[moduleIndex + 1] * inverseNormalization)) <= threshold) { + return true; + } + } + + return density <= threshold; + } + + private boolean isAdaptivePlaneSampleAligned(int localX, int localZ, int adaptiveSampleStep) { + if ((adaptiveSampleStep & (adaptiveSampleStep - 1)) == 0) { + int mask = adaptiveSampleStep - 1; + return (localX & mask) == 0 && (localZ & mask) == 0; + } + return localX % adaptiveSampleStep == 0 && localZ % adaptiveSampleStep == 0; + } + + private void prepareAdaptivePlaneSampleBounds( + CaveCarveScratch scratch, + int[] planeColumnIndices, + int planeCount, + int adaptiveSampleStep, + int[] adaptivePlaneSampleBounds, + int axisCells + ) { + prepareAdaptiveGeometry(scratch, adaptiveSampleStep, axisCells, axisCells + 1); + int[] adaptiveCellX = scratch.adaptiveCellX; + int[] adaptiveCellZ = scratch.adaptiveCellZ; + int minSampleX = axisCells; + int maxSampleX = 0; + int minSampleZ = axisCells; + int maxSampleZ = 0; + + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int sampleX = adaptiveCellX[columnIndex]; + int sampleZ = adaptiveCellZ[columnIndex]; + if (sampleX < minSampleX) { + minSampleX = sampleX; + } + if (sampleX + 1 > maxSampleX) { + maxSampleX = sampleX + 1; + } + if (sampleZ < minSampleZ) { + minSampleZ = sampleZ; + } + if (sampleZ + 1 > maxSampleZ) { + maxSampleZ = sampleZ + 1; + } + } + + adaptivePlaneSampleBounds[0] = minSampleX; + adaptivePlaneSampleBounds[1] = maxSampleX; + adaptivePlaneSampleBounds[2] = minSampleZ; + adaptivePlaneSampleBounds[3] = maxSampleZ; + } + + private void prepareAdaptivePlaneColumns( + CaveCarveScratch scratch, + int[] planeColumnIndices, + int planeCount, + int adaptiveSampleStep, + double adaptiveThresholdMargin, + double[] adaptivePlaneDensity, + int axisCells, + int axisSamples, + double[] adaptivePlanePrediction, + double[] adaptivePlaneAmbiguity + ) { + prepareAdaptiveGeometry(scratch, adaptiveSampleStep, axisCells, axisSamples); + int[] adaptiveCellZ = scratch.adaptiveCellZ; + int[] adaptiveRow0 = scratch.adaptiveRow0; + int[] adaptiveRow1 = scratch.adaptiveRow1; + double[] adaptiveTx = scratch.adaptiveTx; + double[] adaptiveTz = scratch.adaptiveTz; + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int cellZ = adaptiveCellZ[columnIndex]; + int row0 = adaptiveRow0[columnIndex]; + int row1 = adaptiveRow1[columnIndex]; + double tx = adaptiveTx[columnIndex]; + double tz = adaptiveTz[columnIndex]; + double d00 = adaptivePlaneDensity[row0 + cellZ]; + double d01 = adaptivePlaneDensity[row0 + cellZ + 1]; + double d10 = adaptivePlaneDensity[row1 + cellZ]; + double d11 = adaptivePlaneDensity[row1 + cellZ + 1]; + double dx0 = d00 + ((d10 - d00) * tx); + double dx1 = d01 + ((d11 - d01) * tx); + adaptivePlanePrediction[planeIndex] = dx0 + ((dx1 - dx0) * tz); + double minDensity = Math.min(Math.min(d00, d01), Math.min(d10, d11)); + double maxDensity = Math.max(Math.max(d00, d01), Math.max(d10, d11)); + adaptivePlaneAmbiguity[planeIndex] = adaptiveThresholdMargin + ((maxDensity - minDensity) * ADAPTIVE_LOCAL_RANGE_SCALE); + } + } + + private void prepareAdaptiveGeometry(CaveCarveScratch scratch, int adaptiveSampleStep, int axisCells, int axisSamples) { + if (scratch.adaptiveGeometryStep == adaptiveSampleStep && scratch.adaptiveGeometryAxisCells == axisCells) { + return; + } + + for (int columnIndex = 0; columnIndex < 256; columnIndex++) { + int localX = columnIndex >> 4; + int localZ = columnIndex & 15; + int cellX = Math.min(localX / adaptiveSampleStep, axisCells - 1); + int cellZ = Math.min(localZ / adaptiveSampleStep, axisCells - 1); + int x0 = cellX * adaptiveSampleStep; + int z0 = cellZ * adaptiveSampleStep; + int x1 = Math.min(x0 + adaptiveSampleStep, 16); + int z1 = Math.min(z0 + adaptiveSampleStep, 16); + scratch.adaptiveCellX[columnIndex] = cellX; + scratch.adaptiveCellZ[columnIndex] = cellZ; + scratch.adaptiveRow0[columnIndex] = cellX * axisSamples; + scratch.adaptiveRow1[columnIndex] = (cellX + 1) * axisSamples; + scratch.adaptiveTx[columnIndex] = x1 == x0 ? 0D : (localX - x0) / (double) (x1 - x0); + scratch.adaptiveTz[columnIndex] = z1 == z0 ? 0D : (localZ - z0) / (double) (z1 - z0); + } + + scratch.adaptiveGeometryStep = adaptiveSampleStep; + scratch.adaptiveGeometryAxisCells = axisCells; + } + + private double sampleDensityNoWarpNoModules(int x, int y, int z) { + double density = baseDensity.signed(x, y, z) * baseWeight; + density += detailDensity.signed(x, y, z) * detailWeight; + return density * inverseNormalization; + } + + private double sampleDensityNoWarpModules(CaveCarveScratch scratch, int x, int y, int z) { + int activeModuleCount = prepareActiveModules(scratch, y); + if (activeModuleCount == 0) { + return sampleDensityNoWarpNoModules(x, y, z); + } + + CaveFieldModuleState[] localModules = scratch.activeModules; + double density = baseDensity.signed(x, y, z) * baseWeight; + density += detailDensity.signed(x, y, z) * detailWeight; + for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { + CaveFieldModuleState module = localModules[moduleIndex]; + double moduleDensity = module.density.signed(x, y, z) - module.threshold; + if (module.invert) { + moduleDensity = -moduleDensity; + } + + density += moduleDensity * module.weight; + } + + return density * inverseNormalization; + } + + private double sampleDensityWarpOnly(CaveCarveScratch scratch, int x, int y, int z) { + int sx = snapWarp(x); + int sy = snapWarp(y); + int sz = snapWarp(z); + int warpSlot = prepareWarpSample(scratch, sx, sy, sz); + double warpA = scratch.warpCacheA[warpSlot]; + double warpB = scratch.warpCacheB[warpSlot]; + double warpedX = x + (warpA * warpStrength); + double warpedY = y + (warpB * warpStrength); + double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; + return density * inverseNormalization; + } + + private double sampleDensityWarpModules(CaveCarveScratch scratch, int x, int y, int z) { + int activeModuleCount = prepareActiveModules(scratch, y); + if (activeModuleCount == 0) { + return sampleDensityWarpOnly(scratch, x, y, z); + } + + CaveFieldModuleState[] localModules = scratch.activeModules; + return sampleDensityWarpModules(scratch, x, y, z, localModules, activeModuleCount); + } + + private double sampleDensityWarpModules(CaveCarveScratch scratch, int x, int y, int z, CaveFieldModuleState[] localModules, int activeModuleCount) { + int sx = snapWarp(x); + int sy = snapWarp(y); + int sz = snapWarp(z); + int warpSlot = prepareWarpSample(scratch, sx, sy, sz); + double warpA = scratch.warpCacheA[warpSlot]; + double warpB = scratch.warpCacheB[warpSlot]; + double warpedX = x + (warpA * warpStrength); + double warpedY = y + (warpB * warpStrength); + double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; + for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { + CaveFieldModuleState module = localModules[moduleIndex]; + double moduleDensity = module.density.signed(warpedX, warpedY, warpedZ) - module.threshold; + if (module.invert) { + moduleDensity = -moduleDensity; + } + + density += moduleDensity * module.weight; + } + + return density * inverseNormalization; + } + + private int prepareWarpSample(CaveCarveScratch scratch, int sx, int sy, int sz) { + int slot = mixWarpKey(sx, sy, sz) & (scratch.warpCacheX.length - 1); + if (scratch.warpCacheSet[slot] + && scratch.warpCacheX[slot] == sx + && scratch.warpCacheY[slot] == sy + && scratch.warpCacheZ[slot] == sz) { + return slot; + } + + scratch.warpCacheSet[slot] = true; + scratch.warpCacheX[slot] = sx; + scratch.warpCacheY[slot] = sy; + scratch.warpCacheZ[slot] = sz; + scratch.warpCacheA[slot] = warpDensity.signed(sx, sy, sz); + scratch.warpCacheB[slot] = warpDensity.signed(sx + 31.37D, sy - 17.21D, sz + 23.91D); + return slot; + } + + private static int mixWarpKey(int sx, int sy, int sz) { + int hash = sx * 73428767; + hash ^= sy * 91227153; + hash ^= sz * 43828939; + hash ^= hash >>> 16; + return hash; + } + + private int prepareActiveModules(CaveCarveScratch scratch, int y) { + CaveFieldModuleState[] configuredModules = modules; + int configuredCount = configuredModules.length; + if (configuredCount == 0) { + return 0; + } + + // Pure function of (y, modules). modules is final and the scratch is per carver per thread, + // so the band selection and the remaining-contribution prefix sums only change when y does. + if (scratch.activeModulesY == y) { + return scratch.activeModuleCount; + } + + if (scratch.activeModules.length < configuredCount) { + scratch.activeModules = new CaveFieldModuleState[configuredCount]; + } + + int activeCount = 0; + for (int moduleIndex = 0; moduleIndex < configuredCount; moduleIndex++) { + CaveFieldModuleState module = configuredModules[moduleIndex]; + if (y < module.minY || y > module.maxY) { + continue; + } + + scratch.activeModules[activeCount] = module; + activeCount++; + } + + if (scratch.activeModuleRemainingMin.length < activeCount + 1) { + scratch.activeModuleRemainingMin = new double[activeCount + 1]; + scratch.activeModuleRemainingMax = new double[activeCount + 1]; + } + + scratch.activeModuleRemainingMin[activeCount] = 0D; + scratch.activeModuleRemainingMax[activeCount] = 0D; + for (int moduleIndex = activeCount - 1; moduleIndex >= 0; moduleIndex--) { + CaveFieldModuleState module = scratch.activeModules[moduleIndex]; + scratch.activeModuleRemainingMin[moduleIndex] = scratch.activeModuleRemainingMin[moduleIndex + 1] + module.minContribution; + scratch.activeModuleRemainingMax[moduleIndex] = scratch.activeModuleRemainingMax[moduleIndex + 1] + module.maxContribution; + } + + scratch.activeModulesY = y; + scratch.activeModuleCount = activeCount; + return activeCount; + } + + private CarvedVoid[] prepareVoidByYTable(CaveCarveScratch scratch, int minY, int maxY) { + int size = Math.max(0, maxY - minY + 1); + if (scratch.voidByY.length < size) { + scratch.voidByY = new CarvedVoid[size]; + } + + CarvedVoid[] voidByY = scratch.voidByY; + boolean allowLava = profile.allowLava(); + + for (int y = minY; y <= maxY; y++) { + int offset = y - minY; + if (y > lavaHeight) { + voidByY[offset] = CarvedVoid.OPEN; + continue; + } + voidByY[offset] = allowLava ? CarvedVoid.LAVA : CarvedVoid.AIR; + } + + return voidByY; + } + + private CarvedVoid resolveVoid(CaveCarveScratch scratch, CarvedVoid verticalVoid, int x, int y, int z, + int columnIndex, int[] fluidMaxY, double localThreshold) { + if (verticalVoid != CarvedVoid.LAVA + && y <= fluidMaxY[columnIndex] + && isAquiferCandidate(scratch, x, y, z, localThreshold)) { + return CarvedVoid.FLUID; + } + return verticalVoid; + } + + private boolean isAquiferCandidate(CaveCarveScratch scratch, int x, int y, int z, double localThreshold) { + double depthFactor = Math.max(0D, Math.min(1.5D, (fluidHeight - y) / 48D)); + double cutoff = 0.35D + (depthFactor * 0.2D); + if (detailDensity.signed(x, y * 0.5D, z) <= cutoff) { + return false; + } + return !fluidRequiresFloor || hasAquiferCupSupport(scratch, x, y, z, localThreshold); + } + + private boolean isAquiferCandidate(int x, int y, int z, double localThreshold) { + return isAquiferCandidate(scratchCache.get(), x, y, z, localThreshold); + } + + private boolean hasAquiferCupSupport(CaveCarveScratch scratch, int x, int y, int z, double threshold) { + int floorY = Math.max(0, y - 1); + int deepFloorY = Math.max(0, y - 2); + int aboveY = Math.min(aquiferCeilingY, y + 1); + if (!isDensitySolid(scratch, x, floorY, z, threshold)) { + return false; + } + if (!isDensitySolid(scratch, x, deepFloorY, z, threshold - 0.05D)) { + return false; + } + + int support = 0; + if (isDensitySolid(scratch, x + 1, y, z, threshold)) { + support++; + } + if (isDensitySolid(scratch, x - 1, y, z, threshold)) { + support++; + } + if (isDensitySolid(scratch, x, y, z + 1, threshold)) { + support++; + } + if (isDensitySolid(scratch, x, y, z - 1, threshold)) { + support++; + } + if (isDensitySolid(scratch, x, aboveY, z, threshold)) { + support++; + } + return support >= 4; + } + + private boolean isDensitySolid(CaveCarveScratch scratch, int x, int y, int z, double threshold) { + return sampleDensityOptimized(scratch, x, y, z) > threshold; + } + + private void writeVoid(MantleLayer voids, int x, int y, int z, CarvedVoid carvedVoid, CaveFluidSupportPlan fluidSupportPlan) { + voids.set(x, y, z, carvedVoid); + if (fluidSupportPlan != null && carvedVoid == CarvedVoid.FLUID) { + fluidSupportPlan.add(x & LOCAL_MASK, y, z & LOCAL_MASK); + } + } + + private double clampColumnWeight(double weight) { + if (Double.isNaN(weight) || Double.isInfinite(weight)) { + return 0D; + } + + if (weight <= 0D) { + return 0D; + } + + if (weight >= 1D) { + return 1D; + } + + return weight; + } + + private double signed(double value) { + return (value * 2D) - 1D; + } + + private double applySurfaceCeilingFade( + CaveCarveScratch scratch, + double threshold, + int columnIndex, + int y, + int minY + ) { + if (!scratch.surfaceCeilingColumn[columnIndex]) { + return threshold; + } + + int ceilingDistance = scratch.columnMaxY[columnIndex] - y; + if (ceilingDistance < 0 || ceilingDistance >= SURFACE_CEILING_FADE_DEPTH) { + return threshold; + } + + double closureThreshold = scratch.surfaceClosureThreshold[y - minY]; + if (threshold <= closureThreshold) { + return threshold; + } + + double progress = ceilingDistance / (double) SURFACE_CEILING_FADE_DEPTH; + double smooth = progress * progress * (3D - (2D * progress)); + return closureThreshold + ((threshold - closureThreshold) * smooth); + } + + private void prepareSurfaceClosureThresholdTable(CaveCarveScratch scratch, int minY, int maxY) { + int size = Math.max(0, maxY - minY + 1); + if (scratch.surfaceClosureThreshold.length < size) { + scratch.surfaceClosureThreshold = new double[size]; + } + + double baseMinimum = -Math.abs(baseWeight) - Math.abs(detailWeight); + for (int y = minY; y <= maxY; y++) { + double minimumDensity = baseMinimum; + for (CaveFieldModuleState module : modules) { + if (y < module.minY || y > module.maxY) { + continue; + } + minimumDensity += Math.min(module.minContribution, module.maxContribution); + } + scratch.surfaceClosureThreshold[y - minY] = + (minimumDensity * inverseNormalization) - SURFACE_CEILING_SOLID_EPSILON; + } + } + + private double[] prepareVerticalEdgeFadeTable(CaveCarveScratch scratch, int minY, int maxY) { + int size = Math.max(0, maxY - minY + 1); + if (scratch.verticalEdgeFade.length < size) { + scratch.verticalEdgeFade = new double[size]; + } + + double[] verticalEdgeFade = scratch.verticalEdgeFade; + int fadeRange = Math.max(0, profile.verticalEdgeFade()); + double fadeStrength = Math.max(0D, profile.verticalEdgeFadeStrength()); + if (size <= 0 || fadeRange <= 0 || maxY <= minY || fadeStrength <= 0D) { + Arrays.fill(verticalEdgeFade, 0, size, 0D); + return verticalEdgeFade; + } + + for (int y = minY; y <= maxY; y++) { + int floorDistance = y - minY; + int ceilingDistance = maxY - y; + int edgeDistance = Math.min(floorDistance, ceilingDistance); + int offsetIndex = y - minY; + if (edgeDistance >= fadeRange) { + verticalEdgeFade[offsetIndex] = 0D; + continue; + } + + double t = Math.max(0D, Math.min(1D, edgeDistance / (double) fadeRange)); + double smooth = t * t * (3D - (2D * t)); + verticalEdgeFade[offsetIndex] = (1D - smooth) * fadeStrength; + } + + return verticalEdgeFade; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/IslandFace.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/IslandFace.java new file mode 100644 index 000000000..e0e31081d --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/IslandFace.java @@ -0,0 +1,141 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.modules.floating.IslandAnchor; +import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; +import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; + +/** + * The top or bottom face of one floating child's island, at the height an object is anchored: what Iris's placer asks + * about the island while it places the object, and which blocks the object may write. An object may overhang its anchor + * only where the same child's face lies near the anchor height within {@value #OVERHANG_RADIUS} blocks. + */ +final class IslandFace implements IslandAnchor { + private static final int OVERHANG_RADIUS = 2; + private static final int OVERHANG_HEIGHT_TOLERANCE = 4; + + private final SampleProvider samples; + private final ResolvedFloatingChild entry; + private final int anchorY; + private final Side side; + private final int worldHeight; + + private IslandFace(SampleProvider samples, ResolvedFloatingChild entry, int anchorY, Side side, int worldHeight) { + this.samples = samples; + this.entry = entry; + this.anchorY = anchorY; + this.side = side; + this.worldHeight = worldHeight; + } + + static IslandFace top(SampleProvider samples, ResolvedFloatingChild entry, int anchorY, int worldHeight) { + return new IslandFace(samples, entry, anchorY, Side.TOP, worldHeight); + } + + static IslandFace bottom(SampleProvider samples, ResolvedFloatingChild entry, int anchorY, int worldHeight) { + return new IslandFace(samples, entry, anchorY, Side.BOTTOM, worldHeight); + } + + @Override + public int faceY(int x, int z) { + FloatingIslandSample sample = samples.sample(x, z); + if (sample == null) { + return anchorY; + } + if (side == Side.TOP) { + return sample.topY(); + } + int bottomY = sample.bottomY(); + return bottomY < 0 ? anchorY : bottomY; + } + + @Override + public boolean hasIsland(int x, int z) { + return samples.sample(x, z) != null; + } + + @Override + public boolean islandSolid(int x, int y, int z) { + FloatingIslandSample sample = samples.sample(x, z); + if (sample == null) { + return false; + } + int index = y - sample.islandBaseY; + return index >= 0 && index < sample.solidMask.length && sample.solidMask[index]; + } + + @Override + public boolean writes(int x, int y, int z) { + return !skipsAirColumn(x, y, z); + } + + /** Whether {@code sample} is this face's child's island, by the face this anchor is on. */ + static boolean matchesAnchor(FloatingIslandSample sample, ResolvedFloatingChild entry, Side side) { + if (sample == null) { + return false; + } + return side == Side.TOP ? sample.entry == entry : sample.bottomEntry() == entry; + } + + private boolean skipsAirColumn(int x, int y, int z) { + if (y < 0 || y >= worldHeight) { + return true; + } + + FloatingIslandSample sample = samples.sample(x, z); + if (matchesAnchor(sample, entry, side) && isNearAnchorHeight(sample)) { + return side == Side.BOTTOM && y >= anchorY; + } + if (side == Side.TOP && y <= anchorY) { + return true; + } + if (side == Side.BOTTOM && y >= anchorY) { + return true; + } + return !hasNearbySupport(x, z); + } + + private boolean hasNearbySupport(int x, int z) { + for (int dz = -OVERHANG_RADIUS; dz <= OVERHANG_RADIUS; dz++) { + for (int dx = -OVERHANG_RADIUS; dx <= OVERHANG_RADIUS; dx++) { + FloatingIslandSample sample = samples.sample(x + dx, z + dz); + if (matchesAnchor(sample, entry, side) && isNearAnchorHeight(sample)) { + return true; + } + } + } + return false; + } + + private boolean isNearAnchorHeight(FloatingIslandSample sample) { + int faceY = side == Side.TOP ? sample.topY() : sample.bottomY(); + return faceY >= 0 && Math.abs(faceY - anchorY) <= OVERHANG_HEIGHT_TOLERANCE; + } + + enum Side { + TOP, + BOTTOM + } + + @FunctionalInterface + interface SampleProvider { + FloatingIslandSample sample(int x, int z); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java new file mode 100644 index 000000000..ce81407be --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java @@ -0,0 +1,167 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectRun; +import art.arcane.iris.modules.objects.CarvedSpace; +import art.arcane.iris.modules.objects.CavePlacement; +import art.arcane.iris.modules.objects.CaveTransaction; +import art.arcane.iris.modules.objects.EffectiveSettings; +import art.arcane.iris.modules.objects.ForwardingTerrain; +import art.arcane.iris.modules.objects.PlacementChanges; +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; +import art.arcane.iris.modules.objects.PlacementTags; +import art.arcane.iris.modules.objects.TerrainTransaction; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockTrait; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.PlaceableObject; +import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementOutcome; +import com.volmit.placement.PlacementTerrain; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.PackWorld; + +/** + * The chunk whose mantle {@code iris:objects} is placing into: the one place its objects are written. Every placement + * here runs the pack's placement stages ({@link com.volmit.placement.Placements}) over the chunk's mantle, then writes the + * placement's tags beside the object's own blocks. + */ +final class ObjectChunk { + private static final int REJECTED = -1; + private static final int SAMPLED_HEIGHT = -1; + + private final PackWorld world; + private final PlacementTerrain terrain; + private final CarvedSpace carved; + private final BlockRegistry blocks; + private final ModuleLog log; + private final int worldHeight; + + ObjectChunk(MantleStageContext context, ModuleLog log) { + this.world = context.world(); + this.terrain = context.placementTerrain(); + this.worldHeight = context.terrain().bounds().maxY(); + this.carved = new CarvedSpace(context.mantle().carved(), context.mantle().bounds()); + this.blocks = world.resources().blocks(); + this.log = log; + } + + /** The voids the cave carver planned around the chunk. */ + CarvedSpace carved() { + return carved; + } + + /** Whether the golden-debug switch is on for the chunk, which logs every decision of its placements. */ + boolean goldenDebug(int chunkX, int chunkZ) { + return GoldenDebugTerrain.isGoldenDebugChunk(chunkX, chunkZ); + } + + /** + * Places an object on the terrain, where it sits at the height its place mode finds. + * + * @param goldenTag logs the placement's questions under this tag, or null to leave them + * @return the height the object was placed at, negative when the placement rejected it + */ + int placeOnSurface(PlaceableObject object, int x, int z, ObjectPlacement placement, PlacementChanges changes, + PlacementTags tags, String goldenTag) { + PlacementTerrain placer = proceduralTerrain(terrain, object, goldenTag); + return place(ObjectRun.of(object, EffectiveSettings.withChanges(placement, changes), x, SAMPLED_HEIGHT, z), placer, tags); + } + + /** + * Places an object in a cave, anchored at {@code anchorY}, and writes it only when all of it lies inside the cave and + * no deeper than {@code minDepthBelowSurface} under the surface. + * + * @param goldenTag logs the placement's questions under this tag, or null to leave them + */ + CavePlacement placeInCave(PlaceableObject object, int x, int anchorY, int z, ObjectPlacement placement, PlacementChanges changes, + int minDepthBelowSurface, PlacementTags tags, String goldenTag) { + ObjectPlacement effective = EffectiveSettings.withChanges(placement, changes); + CaveTransaction transaction = new CaveTransaction(proceduralTerrain(terrain, object, goldenTag), worldHeight, anchorY, + minDepthBelowSurface); + int placeY = anchorY; + if (effective.mode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { + placeY = Math.max(1, transaction.caveCeiling(x, z) - 1 - Math.floorDiv(object.height(), 2)); + } + int result = place(ObjectRun.of(object, effective, x, placeY, z), transaction, tags); + if (result < 0) { + transaction.discard(); + return new CavePlacement(result, TerrainTransaction.Commit.EMPTY); + } + return new CavePlacement(result, transaction.commit()); + } + + /** Places an object at a given height, which the terrain stacked above uses for the objects hung from it. */ + int placeUpper(PlaceableObject object, int x, int anchorY, int z, ObjectPlacement placement, PlacementChanges changes, + PlacementTags tags) { + return place(ObjectRun.of(object, EffectiveSettings.withChanges(placement, changes), x, anchorY, z), terrain, tags); + } + + private int place(ObjectRun run, PlacementTerrain placer, PlacementTags tags) { + PlacementOutcome outcome = run.placeIn(world, placer); + if (!outcome.isPlaced()) { + return REJECTED; + } + writeTags(placer, run, tags); + return run.anchorY().orElse(REJECTED); + } + + /** + * A procedural variant's terrain: it keeps the leaf states the variant baked, persistent or decaying, and the + * golden-debug switch logs its questions. Pack objects use the chunk's terrain as it is. + */ + private PlacementTerrain proceduralTerrain(PlacementTerrain base, PlaceableObject object, String goldenTag) { + if (!ProceduralObjectCatalog.isProceduralKey(object.name())) { + return base; + } + PlacementTerrain keepingBakedLeaves = new DecayingTerrain(base); + return goldenTag == null ? keepingBakedLeaves : new GoldenDebugTerrain(keepingBakedLeaves, goldenTag, log); + } + + /** Writes the tags beside each of the object's own blocks. */ + private void writeTags(PlacementTerrain placer, ObjectRun run, PlacementTags tags) { + for (BlockPosition position : run.objectBlocks()) { + if (tags.marker() != null) { + placer.recordPlacement(position.x(), position.y(), position.z(), tags.marker()); + if (tags.treeMaterial()) { + placer.mark(new PlacedMarker.TreeMaterial(position)); + } + } + if (tags.buriedTreasure() && blocks.hasTrait(placer.get(position.x(), position.y(), position.z()), BlockTrait.STORAGE)) { + placer.mark(new PlacedMarker.BuriedTreasure(position)); + } + } + } + + /** A terrain that leaves non-persistent leaves as they are, so they decay like the real thing. */ + private static final class DecayingTerrain extends ForwardingTerrain { + private DecayingTerrain(PlacementTerrain delegate) { + super(delegate); + } + + @Override + public boolean preventsDecay() { + return false; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java new file mode 100644 index 000000000..6e6ca6c2a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java @@ -0,0 +1,73 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.modules.objects.Declaration; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import com.volmit.config.Level; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.service.ObjectsAt; +import com.volmit.world.PackWorld; + +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * How {@code iris:objects} tells Iris where its objects are: the objects the biome and region of a chunk would place, + * and the biomes and regions whose surface placements name an object. + */ +public final class ObjectLocating implements ObjectsAt { + @Override + public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { + return ObjectPlacing.of(world).guess(chunkX, chunkZ).stream() + .map(world.resources()::idOf) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + + @Override + public PlacedBy placedBy(PackWorld world, ResourceId object) { + PackResources resources = world.resources(); + Set biomes = new LinkedHashSet<>(); + Set regions = new LinkedHashSet<>(); + for (Declaration declaration : Declaration.allOf(world, ObjectSettings.class)) { + if (!placesObject(declaration.settings().objects(), resources, object)) { + continue; + } + (declaration.level() == Level.BIOME ? biomes : regions).add(declaration.id()); + } + return new PlacedBy(biomes, regions); + } + + private static boolean placesObject(List placements, PackResources resources, ResourceId object) { + for (ObjectPlacement placement : placements) { + if (placement != null && placement.carvingSupport().supportsSurface() && names(placement, resources, object)) { + return true; + } + } + return false; + } + + private static boolean names(ObjectPlacement placement, PackResources resources, ResourceId object) { + return placement.place().stream().anyMatch(key -> key != null && resources.idOf(key).equals(object)); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java new file mode 100644 index 000000000..7617a8129 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -0,0 +1,94 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; +import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; +import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; +import art.arcane.iris.modules.objects.PackObjectScenes; +import art.arcane.iris.modules.objects.ProceduralObjectScenes; +import art.arcane.iris.modules.objects.TreeGrowthSettings; +import art.arcane.iris.builtin.objects.UpperObjectsForceSettings; +import art.arcane.iris.builtin.objects.UpperObjectsSettings; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleLifecycle; +import com.volmit.ModuleLog; +import com.volmit.ModuleSetup; +import com.volmit.config.PackSettings; +import com.volmit.service.ObjectsAt; +import com.volmit.service.SaplingGrowth; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.PackWorld; + +import java.util.List; + +/** + * Module {@code iris:objects}: the objects the dimension's regions and biomes place, written into the mantle + * once the caves they may anchor in are planned. A port of what was Iris's object mantle component, its work + * done by {@link ObjectPlacing}, one per engine runtime, with the noise of its placements and the variants of the + * procedural objects they place ({@link ProceduralObjectCatalog}) built ahead of generation ({@link #warmUp}). Its + * reach is the pack's largest object placement. It tells + * Iris which objects a chunk would get and which biomes and regions place an object ({@link ObjectLocating}), for the + * object search and studio tools, grows the trees of saplings ({@link TreeGrowing}), and shows the pack's objects in + * the studio with every variant of its procedural objects ({@link PackObjectScenes}, {@link ProceduralObjectScenes}). + */ +public final class ObjectModule implements IrisModule, ModuleLifecycle { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:objects", "Objects", VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + ModuleLog log = setup.log(); + // Ordering only: iris:carve ships in the built-ins jar, which a pack may not have. + setup.stages().define(IrisStages.Objects.PLACE).softAfter(IrisStages.Carve.CAVES).reach(settings -> reach(settings, log)) + .run(ObjectModule::place); + var registry = setup.registry(); + registry.registerService(ObjectsAt.class, new ObjectLocating()); + registry.registerService(SaplingGrowth.class, new TreeGrowing()); + List.of(ObjectSettings.class, TreeGrowthSettings.class, RequireSurfaceSupportSettings.class, + SurfaceSupportBufferSettings.class, UpperObjectsSettings.class, UpperObjectsForceSettings.class) + .forEach(registry::registerSettings); + registry.registerResourceKind(ProceduralObjectCatalog.DEFINITIONS); + registry.registerPlacementType(ObjectPlacement.class, ObjectPlacement.jsonFields()); + registry.registerLifecycle(this); + setup.tooling().registerView(new PackObjectScenes()); + setup.tooling().registerView(new ProceduralObjectScenes()); + } + + @Override + public void warmUp(PackWorld world) { + new ObjectWarmUp(world).warm(); + } + + private static void place(MantleStageContext context) { + ObjectPlacing.of(context.world()).place(context); + } + + private static int reach(PackSettings settings, ModuleLog log) { + return new PlacementReach(settings.resources(), log).ofPack(settings); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java new file mode 100644 index 000000000..6ad7a402a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -0,0 +1,114 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.modules.objects.ObjectPool; +import art.arcane.iris.modules.objects.ObjectSeparation; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.object.PlaceableObject; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.PackWorld; + +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; + +/** + * Places the objects the dimension's regions and biomes declare, one chunk at a time, into the mantle of a world: the worker + * of {@link ObjectModule}, one per world. It also works out which objects a chunk would get, without placing them. + */ +public final class ObjectPlacing { + private static final int CHUNK_CENTER_OFFSET_BLOCKS = 8; + private static final int CHUNK_SHIFT = 4; + private static final double CHANCE_JITTER = 0.005; + /** A guess draws from the biome's objects before the region's, as placing does. */ + private static final Level[] GUESSED_LEVELS = {Level.BIOME, Level.REGION}; + + private final PackWorld world; + private final ObjectPool objects; + private final ObjectSeparation separation; + private final ModuleLog log; + + private ObjectPlacing(PackWorld world) { + this.world = world; + this.objects = ObjectPool.of(world); + this.separation = ObjectSeparation.of(world); + this.log = world.log(); + } + + /** The object placing of {@code world}. */ + public static ObjectPlacing of(PackWorld world) { + return world.state(ObjectPlacing.class, ObjectPlacing::new); + } + + /** Places what originates in the chunk {@code context} generates. */ + void place(MantleStageContext context) { + new ChunkObjectPlacing(objects, log, context).place(); + } + + /** The keys of the objects the chunk would get, as far as the chunk's surface objects go. */ + public Set guess(int chunkX, int chunkZ) { + RNG rng = objects.chunkRandom(chunkX, chunkZ); + int centerX = (chunkX << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; + int centerZ = (chunkZ << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; + FeatureSettings worldSettings = world.running().orElseThrow().settings(); + SettingsStack declared = worldSettings.at(ObjectSettings.class, centerX, centerZ); + Set keys = new HashSet<>(); + for (Level level : GUESSED_LEVELS) { + declared.level(level).ifPresent(settings -> guessFrom(settings, worldSettings, rng, chunkX, chunkZ, keys)); + } + return keys; + } + + private void guessFrom(ObjectSettings settings, FeatureSettings worldSettings, RNG rng, int chunkX, int chunkZ, Set keys) { + int centerX = (chunkX << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; + int centerZ = (chunkZ << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; + for (ObjectPlacement placement : settings.objects()) { + if (!placement.carvingSupport().supportsSurface()) { + continue; + } + if (placement.isSeparated()) { + guessSeparatedKey(chunkX, chunkZ, placement, worldSettings).ifPresent(keys::add); + } else if (rng.chance(separation.chanceAt(placement, centerX, centerZ) + rng.d(-CHANCE_JITTER, CHANCE_JITTER))) { + keys.addAll(guessPlacedKeys(rng, chunkX, chunkZ, placement)); + } + } + } + + private Optional guessSeparatedKey(int chunkX, int chunkZ, ObjectPlacement placement, FeatureSettings worldSettings) { + return separation.keptCandidate(chunkX, chunkZ, placement, worldSettings) + .flatMap(candidate -> objects.pickScaled(placement, candidate.rng())) + .map(PlaceableObject::name); + } + + private Set guessPlacedKeys(RNG rng, int x, int z, ObjectPlacement placement) { + Set keys = new HashSet<>(); + for (int i = 0; i < objects.density(placement, x, z); i++) { + Optional picked = objects.pickScaled(placement, rng); + picked.ifPresent(object -> keys.add(object.name())); + } + return keys; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java new file mode 100644 index 000000000..8e60aeaa1 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java @@ -0,0 +1,69 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.modules.objects.Declaration; +import art.arcane.iris.modules.objects.ObjectPool; +import com.volmit.config.Level; +import com.volmit.world.PackWorld; + +import java.util.Comparator; +import java.util.List; + +/** + * Builds what object placing would build on first use, for every object placement and procedural object the world's + * biomes and regions declare: the placement's density noise, and a procedural object's variants. The density noise is + * cached per seed and the variants are baked whatever picks one. + */ +final class ObjectWarmUp { + private static final Level[] WARMED_LEVELS = {Level.BIOME, Level.REGION}; + + private final PackWorld world; + private final ObjectPool objects; + + ObjectWarmUp(PackWorld world) { + this.world = world; + this.objects = ObjectPool.of(world); + } + + void warm() { + List> placements = byKey(Declaration.allOf(world, ObjectSettings.class)); + for (Level level : WARMED_LEVELS) { + for (Declaration declaration : placements) { + if (declaration.level() == level) { + warmPlacements(declaration.settings().objects()); + } + } + } + } + + private static List> byKey(List> declarations) { + return declarations.stream().sorted(Comparator.comparing(Declaration::id)).toList(); + } + + private void warmPlacements(List placements) { + for (ObjectPlacement placement : placements) { + if (placement != null) { + objects.warm(placement); + } + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java new file mode 100644 index 000000000..ec695f57b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java @@ -0,0 +1,165 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.anchor.PlaceMode; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.prepare.AxisRotationClamp; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; +import art.arcane.iris.engine.procedural.ProceduralVariants; +import art.arcane.iris.modules.objects.ObjectSize; +import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.PackSettings; +import com.volmit.geometry.BlockBox; +import com.volmit.resource.PackResources; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** How far, in blocks along X and Z, the objects a pack places may write beyond their chunk. */ +final class PlacementReach { + private static final int LARGE_REACH_WARNING_BLOCKS = 128; + private static final int MAX_VACUUM_RADIUS_BLOCKS = 128; + private static final double SCALE_PADDING_FACTOR = 2D; + + private final PackResources resources; + private final ProceduralObjectCatalog procedural; + private final ModuleLog log; + private final Map> sizes = new HashMap<>(); + private final Set warnedLargeObjects = new HashSet<>(); + + PlacementReach(PackResources resources, ModuleLog log) { + this.resources = resources; + this.procedural = ProceduralObjectCatalog.detached(resources, log); + this.log = log; + } + + /** The largest reach of any object placement the pack's regions and biomes declare. */ + int ofPack(PackSettings settings) { + int radius = 0; + for (Entry entry : settings.declared(ObjectSettings.class)) { + radius = Math.max(radius, ofPlacements(entry.value().objects())); + } + return radius; + } + + private int ofPlacements(List placements) { + int radius = 0; + for (ObjectPlacement placement : placements) { + if (placement == null) { + continue; + } + for (String objectKey : placement.place()) { + radius = Math.max(radius, ofObject(placement, objectKey)); + } + } + return radius; + } + + private int ofObject(ObjectPlacement placement, String objectKey) { + try { + Optional size = sizes.computeIfAbsent(objectKey, key -> sizeOf(resources, procedural, key)); + if (size.isEmpty()) { + return 0; + } + int reach = of(size.get(), placement); + if (reach > LARGE_REACH_WARNING_BLOCKS && warnedLargeObjects.add(objectKey)) { + log.warn("Object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); + } + return reach; + } catch (Throwable failure) { + log.error("Failed to work out the reach of an object placement", failure); + return 0; + } + } + + /** The size of the object {@code objectKey} names, for a procedural pool its largest variant; empty when the pack has none. */ + static Optional sizeOf(PackResources resources, ProceduralObjectCatalog procedural, String objectKey) { + if (ProceduralObjectCatalog.isProceduralKey(objectKey)) { + return procedural.variants(objectKey).map(ProceduralVariants::largestSize); + } + return resources.objects().sizeOf(resources.idOf(objectKey)).map(PlacementReach::sizeOf); + } + + private static ObjectSize sizeOf(BlockBox box) { + return new ObjectSize(box.maxX() - box.minX(), box.maxY() - box.minY(), box.maxZ() - box.minZ()); + } + + static int of(ObjectSize size, ObjectPlacement placement) { + return of(size, placement.mode().placeMode(), placement.scale().maxScale(), placement.rotation(), placement.translate(), + placement.warp() == null || placement.warp().isFlat() ? 0 : placement.warp().multiplier(), + placement.vacuumSettings().orElse(null)); + } + + private static int of(ObjectSize size, PlaceMode mode, Double maxScale, ObjectRotation rotation, ObjectTranslate translate, + Double warpMultiplier, VacuumSettings vacuum) { + double scale = maxScale == null ? 1D : Math.max(1D, maxScale); + int width = scaledDimension(size.width(), scale); + int height = scaledDimension(size.height(), scale); + int depth = scaledDimension(size.depth(), scale); + boolean rotateX = rotation != null && rotation.enabled() && rotation.xAxis() != null && rotation.xAxis().enabled(); + boolean rotateZ = rotation != null && rotation.enabled() && rotation.zAxis() != null && rotation.zAxis().enabled(); + int footprint = rotateX || rotateZ ? Math.max(width, Math.max(height, depth)) : Math.max(width, depth); + int translation = translationReach(translate, rotation, rotateX || rotateZ); + int warp = warpMultiplier == null ? 0 : (int) Math.ceil(Math.abs(warpMultiplier) / 2D); + int vacuumReach = mode.bendsTerrain() ? 2 * vacuumRadius(mode, vacuum) : 0; + long reach = (long) footprint + translation + warp + vacuumReach; + return reach > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) reach; + } + + private static int scaledDimension(int dimension, double scale) { + int absoluteDimension = Math.abs(dimension); + if (scale <= 1D) { + return absoluteDimension; + } + return (int) Math.ceil((absoluteDimension * scale) + (scale * SCALE_PADDING_FACTOR)); + } + + private static int translationReach(ObjectTranslate translate, ObjectRotation rotation, boolean rotateVertically) { + if (translate == null || (translate.x() == 0 && translate.y() == 0 && translate.z() == 0)) { + return 0; + } + double x = translate.x(); + double y = translate.y(); + double z = translate.z(); + if (rotateVertically) { + return (int) Math.ceil(Math.sqrt((x * x) + (y * y) + (z * z))); + } + AxisRotationClamp yAxis = rotation == null ? null : rotation.yAxis(); + boolean rotateY = rotation != null && rotation.enabled() && yAxis != null && yAxis.enabled(); + return rotateY ? (int) Math.ceil(Math.hypot(x, z)) : (int) Math.max(Math.abs(x), Math.abs(z)); + } + + private static int vacuumRadius(PlaceMode mode, VacuumSettings settings) { + int radius = mode.vacuum().defaultRadiusBlocks(); + if (settings != null && settings.radius() > 0) { + radius = settings.radius(); + } + return Math.max(0, Math.min(MAX_VACUUM_RADIUS_BLOCKS, radius)); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java new file mode 100644 index 000000000..17d8d5eae --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -0,0 +1,66 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.structure.StructureHost; +import art.arcane.iris.builtin.structure.StructurePlacementSettings; +import art.arcane.iris.builtin.structure.StructureSettings; +import art.arcane.iris.engine.framework.structure.StructureResources; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.config.PackSettings; +import com.volmit.stage.MantleStageContext; + +/** + * Module {@code iris:structure}: the jigsaw structures, pools and pieces of a pack (its resource kinds), the structure + * placements a pack declares, and the mantle stage that places the structures starting in each chunk. Iris builds and + * places the structures ({@link StructureHost}); their validation, the locator and the platform structure answers are + * Iris's own module {@code iris:structure-model}. + *

+ * It is not in the built-ins jar: Iris registers it with its own modules, because Iris's jigsaw studio, importers and + * exporters read the resources it registers as the same classes. + */ +public final class StructureModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:structure", "Structures", VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + setup.stages().define(IrisStages.Structure.PLACE).softAfter(IrisStages.Objects.PLACE, IrisStages.Floating.OBJECTS) + .reach(StructureModule::reach).run(StructureModule::place); + var registry = setup.registry(); + StructureResources.kinds().forEach(registry::registerResourceKind); + registry.registerSettings(StructureSettings.class); + registry.registerSettings(StructurePlacementSettings.class); + } + + private static void place(MantleStageContext context) { + context.world().extension(StructureHost.class).orElseThrow().placeChunk(context); + } + + private static int reach(PackSettings settings) { + return settings.extension(StructureHost.class).orElseThrow().reach(); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/SurfaceFluidBoundaryPlan.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/SurfaceFluidBoundaryPlan.java new file mode 100644 index 000000000..ec0cf02e9 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/SurfaceFluidBoundaryPlan.java @@ -0,0 +1,94 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; + +final class SurfaceFluidBoundaryPlan { + static final int NO_BOUNDARY = Integer.MAX_VALUE; + private static final int CHUNK_SIZE = 16; + private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; + + private SurfaceFluidBoundaryPlan() { + } + + static void fill( + int[] chunkSurfaceHeights, + double[] fieldSurfaceHeights, + boolean[] fieldHasFluid, + int fieldSize, + int padding, + int fluidHeight, + int[] boundaryStartY + ) { + if (chunkSurfaceHeights == null || chunkSurfaceHeights.length < CHUNK_AREA + || boundaryStartY == null || boundaryStartY.length < CHUNK_AREA + || padding < 1 || fieldSize < CHUNK_SIZE + (padding * 2) + || fieldSurfaceHeights == null || fieldSurfaceHeights.length < fieldSize * fieldSize + || fieldHasFluid == null || fieldHasFluid.length < fieldSize * fieldSize) { + throw new IllegalArgumentException("Surface fluid boundary fields do not cover a padded chunk"); + } + + for (int localX = 0; localX < CHUNK_SIZE; localX++) { + int fieldX = localX + padding; + for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { + int fieldZ = localZ + padding; + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + int boundaryY = NO_BOUNDARY; + int surfaceY = chunkSurfaceHeights[columnIndex]; + int fieldIndex = (fieldX * fieldSize) + fieldZ; + if (fieldHasFluid[fieldIndex] && surfaceY < fluidHeight) { + boundaryY = surfaceY; + } + + boundaryY = lowerBoundary(boundaryY, fieldSurfaceHeights, fieldHasFluid, + ((fieldX - 1) * fieldSize) + fieldZ, fluidHeight); + boundaryY = lowerBoundary(boundaryY, fieldSurfaceHeights, fieldHasFluid, + ((fieldX + 1) * fieldSize) + fieldZ, fluidHeight); + boundaryY = lowerBoundary(boundaryY, fieldSurfaceHeights, fieldHasFluid, + (fieldX * fieldSize) + fieldZ - 1, fluidHeight); + boundaryY = lowerBoundary(boundaryY, fieldSurfaceHeights, fieldHasFluid, + (fieldX * fieldSize) + fieldZ + 1, fluidHeight); + boundaryStartY[columnIndex] = boundaryY; + } + } + } + + static boolean protects(int[] boundaryStartY, int columnIndex, int y, int fluidHeight) { + return boundaryStartY != null + && columnIndex >= 0 + && columnIndex < boundaryStartY.length + && y >= boundaryStartY[columnIndex] + && y <= fluidHeight; + } + + private static int lowerBoundary( + int currentBoundaryY, + double[] fieldSurfaceHeights, + boolean[] fieldHasFluid, + int fieldIndex, + int fluidHeight + ) { + int neighborSurfaceY = (int) Math.round(fieldSurfaceHeights[fieldIndex]); + if (!fieldHasFluid[fieldIndex] || neighborSurfaceY >= fluidHeight) { + return currentBoundaryY; + } + return Math.min(currentBoundaryY, neighborSurfaceY + 1); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java new file mode 100644 index 000000000..766fbd70f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -0,0 +1,266 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectRun; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; +import art.arcane.iris.modules.objects.TreeGrowthSettings; +import art.arcane.iris.modules.objects.TreeMode; +import art.arcane.iris.engine.loot.BlockBiomes; +import art.arcane.iris.modules.objects.Declaration; +import art.arcane.iris.modules.objects.ObjectPool; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.config.Level; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.object.PlaceableObject; +import com.volmit.placement.PlacedBlock; +import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementRecord; +import com.volmit.placement.PlacementTerrain; +import com.volmit.placement.StructureVolumes; +import com.volmit.resource.ResourceId; +import com.volmit.service.SaplingGrowth; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * How {@code iris:objects} grows trees: when a sapling grows, the tree comes from the tree placements of the biome and + * region at the sapling (the region's too when the dimension uses all of them), placed like any object but into a list + * of blocks the host then places. The same placements tell which objects are trees. + */ +public final class TreeGrowing implements SaplingGrowth { + private static final int SAPLING_WIDTH = 1; + private static final int SAPLING_DEPTH = 1; + private static final String PROCEDURAL_TREE_FOLDER = ProceduralObjectCatalog.KEY_PREFIX + "trees/"; + + @Override + public Optional grow(PackWorld world, Sapling sapling, Surroundings surroundings) { + RunningWorld running = world.running().orElseThrow(); + BlockPosition at = sapling.at(); + TreeGrowthSettings growth = treeGrowth(running, at); + if (!growth.enabled()) { + return Optional.empty(); + } + Optional placement = pickPlacement(running, growth, sapling); + if (placement.isEmpty()) { + return Optional.empty(); + } + List keys = placement.get().place(); + Optional tree = ObjectPool.of(world).object(keys.get(RNG.r.i(keys.size())), RNG.r); + if (tree.isEmpty()) { + return Optional.empty(); + } + PlaceableObject object = tree.get(); + GrowthTerrain terrain = new GrowthTerrain(surroundings, running.layout().fluidHeight(), world.resources().blocks()); + BlockPosition center = sapling.center(); + ObjectRun run = ObjectRun.of(object, placement.get(), center.x(), center.y() + object.height() / 2, center.z()); + run.placeIn(world, terrain); + return Optional.of(new Growth(world.resources().idOf(object.name()), terrain.placed())); + } + + @Override + public TreeObjects treeObjects(PackWorld world) { + Set objects = new HashSet<>(); + for (Declaration declaration : Declaration.allOf(world, ObjectSettings.class)) { + collectPlacements(declaration.settings().objects(), objects); + } + return new TreeObjects(idsOf(world, placedNames(world, objects))); + } + + /** The names objects are placed under: a procedural pool's are its variants' own. */ + private static Set placedNames(PackWorld world, Set objectKeys) { + ProceduralObjectCatalog procedural = ProceduralObjectCatalog.of(world); + Set names = new HashSet<>(); + for (String key : objectKeys) { + if (ProceduralObjectCatalog.isProceduralKey(key)) { + procedural.placeable(key).forEach(variant -> names.add(variant.name())); + } else { + names.add(key); + } + } + return names; + } + + private static Set idsOf(PackWorld world, Set keys) { + return keys.stream().map(world.resources()::idOf).collect(Collectors.toSet()); + } + + private static TreeGrowthSettings treeGrowth(RunningWorld running, BlockPosition at) { + return running.settings().at(TreeGrowthSettings.class, at.x(), at.z()).dimension().orElseGet(TreeGrowthSettings::new); + } + + /** One placement, picked at random, of the tree placements that grow {@code sapling}'s species. */ + private static Optional pickPlacement(RunningWorld running, TreeGrowthSettings growth, Sapling sapling) { + List placements = new ArrayList<>(); + BlockPosition at = sapling.at(); + BlockBiomes.declaredAt(running, ObjectSettings.class, at).ifPresent(settings -> placements.addAll(matching(settings, sapling.species()))); + if (growth.mode() == TreeMode.ALL || placements.isEmpty()) { + running.settings().at(ObjectSettings.class, at.x(), at.z()).level(Level.REGION) + .ifPresent(settings -> placements.addAll(matching(settings, sapling.species()))); + } + if (placements.isEmpty()) { + return Optional.empty(); + } + return Optional.of(placements.get(RNG.r.i(placements.size()))); + } + + /** The placements whose trees override {@code species}, which packs name by the path of its id, ignoring case. */ + private static List matching(ObjectSettings settings, ResourceId species) { + List matches = new ArrayList<>(); + for (ObjectPlacement placement : settings.objects()) { + if (placement.trees().stream().anyMatch(tree -> tree.matches(SAPLING_WIDTH, SAPLING_DEPTH, species.path()))) { + matches.add(placement); + } + } + return matches; + } + + /** The objects of tree placements, and procedural objects in {@code procedural/trees/} wherever they are placed. */ + private static void collectPlacements(List placements, Set objectKeys) { + for (ObjectPlacement placement : placements) { + if (placement == null) { + continue; + } + for (String objectKey : placement.place()) { + if (objectKey != null && !objectKey.isBlank() && (!placement.trees().isEmpty() || isProceduralTree(objectKey))) { + objectKeys.add(objectKey); + } + } + } + } + + private static boolean isProceduralTree(String objectKey) { + return objectKey.startsWith(PROCEDURAL_TREE_FOLDER); + } + + /** + * The world around a sapling, read through the host, collecting what a tree writes into a list of blocks the host + * then places. Its leaves never decay; it has no caves, water, structures or placement records, and keeps no block + * entities or markers. + */ + private static final class GrowthTerrain implements PlacementTerrain { + private static final StructureVolumes NO_STRUCTURES = new StructureVolumes() { + @Override + public boolean isEmpty() { + return true; + } + + @Override + public boolean intersects(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { + return false; + } + + @Override + public boolean containsWithin(int x, int y, int z, int margin) { + return false; + } + }; + + private final Surroundings surroundings; + private final int fluidHeight; + private final BlockRegistry blocks; + private final List placed = new ArrayList<>(); + + private GrowthTerrain(Surroundings surroundings, int fluidHeight, BlockRegistry blocks) { + this.surroundings = surroundings; + this.fluidHeight = fluidHeight; + this.blocks = blocks; + } + + private List placed() { + return placed; + } + + @Override + public int highest(int x, int z, boolean ignoreFluid) { + return surroundings.highest(x, z, ignoreFluid); + } + + @Override + public BlockState get(int x, int y, int z) { + return surroundings.get(x, y, z); + } + + @Override + public void set(int x, int y, int z, BlockState state) { + placed.add(new PlacedBlock(new BlockPosition(x, y, z), state, Optional.empty())); + } + + @Override + public void set(int x, int y, int z, BlockState state, BlockEntityData blockEntity) { + set(x, y, z, state); + } + + @Override + public boolean isCarved(int x, int y, int z) { + return false; + } + + @Override + public boolean isSurfaceSolid(int x, int y, int z) { + return blocks.hasTrait(get(x, y, z), BlockTrait.SOLID); + } + + @Override + public boolean isUnderwater(int x, int z) { + return false; + } + + @Override + public int fluidHeight() { + return fluidHeight; + } + + @Override + public boolean preventsDecay() { + return true; + } + + @Override + public void recordPlacement(int x, int y, int z, PlacementRecord placement) { + } + + @Override + public Optional placementAt(int x, int y, int z) { + return Optional.empty(); + } + + @Override + public StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ) { + return NO_STRUCTURES; + } + + @Override + public void mark(PlacedMarker marker) { + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/UndersideTurn.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/UndersideTurn.java new file mode 100644 index 000000000..79c9c6f7c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/UndersideTurn.java @@ -0,0 +1,40 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import com.volmit.geometry.BlockPosition; + +/** + * How Iris turns an object it hangs under an island: upside down about X, then a quarter turn about Y of {@code yRotation} + * degrees (0, 90, 180 or 270), in the object's own block positions. + */ +record UndersideTurn(int yRotation) { + private static final int FULL_TURN_DEGREES = 360; + + BlockPosition turn(int x, int y, int z) { + int flippedY = -y; + int flippedZ = -z; + return switch (Math.floorMod(yRotation, FULL_TURN_DEGREES)) { + case 90 -> new BlockPosition(flippedZ, flippedY, -x); + case 180 -> new BlockPosition(-x, flippedY, -flippedZ); + case 270 -> new BlockPosition(-flippedZ, flippedY, x); + default -> new BlockPosition(x, flippedY, flippedZ); + }; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java b/module/src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java new file mode 100644 index 000000000..705ef99df --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java @@ -0,0 +1,111 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.decorant.DecorantSettings; +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.iris.modules.terrain.BiomeLayers; +import art.arcane.iris.modules.terrain.ColumnSlope; +import art.arcane.iris.modules.terrain.PaletteExplosion; +import art.arcane.iris.modules.terrain.TerrainPalettes; +import art.arcane.iris.engine.decorator.BiomeDecorators; +import art.arcane.iris.engine.decorator.DecoratedBiome; +import art.arcane.iris.engine.decorator.DecorationScene; +import art.arcane.iris.engine.decorator.IrisCeilingDecorator; +import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.resource.ResourceId; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.BiomeKind; +import com.volmit.world.TerrainSampler; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** A chunk's {@link CaveDressing} from the world's biome layers, terrain palettes and decorators, which carving shares with the terrain and decorant built-ins. */ +final class BuiltInCaveDressing implements CaveDressing { + private final BiomeLayers layers; + private final TerrainPalettes palettes; + private final FeatureSettings settings; + private final BlockRegistry blocks; + private final PaletteExplosion explosion; + private final ColumnSlope slope; + private final DecorationScene scene; + private final Map decoratedBiomes = new HashMap<>(); + + BuiltInCaveDressing(ChunkStageContext context) { + TerrainSampler terrain = context.terrain(); + this.layers = BiomeLayers.of(context.world()); + this.palettes = TerrainPalettes.of(context.world()); + this.settings = context.settings(); + this.blocks = context.world().resources().blocks(); + this.explosion = PaletteExplosion.of(settings, context.originX(), context.originZ()); + this.slope = (x, z) -> terrain.column((int) x, (int) z).slope(); + this.scene = DecorationScene.of(context); + } + + @Override + public BlockState fluidAt(int x, int z) { + return palettes.fluidAt(x, z); + } + + @Override + public BlockState wall(ResourceId biome, RNG rng, int x, int y, int z) { + return layers.wall(layers.biome(biome, settings)).get(rng, x, y, z); + } + + @Override + public List floorLayers(ResourceId biome, int x, int z, RNG rng, int depth, int floorY) { + return layers.generateLayers(layers.biome(biome, settings), explosion, x, z, rng, depth, floorY, slope); + } + + @Override + public List ceilingLayers(ResourceId biome, int x, int z, RNG rng, int depth) { + return layers.generateCeilingLayers(layers.biome(biome, settings), explosion, x, z, rng, depth); + } + + @Override + public boolean hasDecorators(ResourceId biome, DecorationPart part) { + return scene.decorators().hasDecorators(decorated(biome), part); + } + + @Override + public void decorateFloor(int localX, int localZ, int x, int z, ResourceId biome, int floorY, int airThickness) { + new IrisSurfaceDecorator(scene).decorate(localX, localZ, x, x, x, z, z, z, decorated(biome), floorY, airThickness); + } + + @Override + public void decorateCeiling(int localX, int localZ, int x, int z, ResourceId biome, int ceilingY, int airThickness) { + new IrisCeilingDecorator(scene).decorate(localX, localZ, x, x, x, z, z, z, decorated(biome), ceilingY, airThickness); + } + + @Override + public BlockState oreFor(BlockState rock, BlockState ore) { + return blocks.oreFor(rock, ore); + } + + /** The decorators' view of a cave biome: what it declares, under the key its settings come from, as other decorated biomes are. */ + private DecoratedBiome decorated(ResourceId biome) { + return decoratedBiomes.computeIfAbsent(biome, id -> new DecoratedBiome(BiomeDecorators.biomeKey(id), + settings.declaredBy(id, DecorantSettings.class).orElse(null), BiomeKind.CAVE)); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/CarveColumnMask.java b/module/src/main/java/art/arcane/iris/engine/modifier/CarveColumnMask.java new file mode 100644 index 000000000..58a3af38a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/CarveColumnMask.java @@ -0,0 +1,95 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import java.util.Arrays; + +final class CarveColumnMask { + private long[] words = new long[8]; + private int maxWord = -1; + + void add(int y) { + if (y < 0) { + return; + } + + int wordIndex = y >> 6; + if (wordIndex >= words.length) { + words = Arrays.copyOf(words, Math.max(words.length << 1, wordIndex + 1)); + } + + words[wordIndex] |= 1L << (y & 63); + if (wordIndex > maxWord) { + maxWord = wordIndex; + } + } + + int nextSetBit(int fromBit) { + if (maxWord < 0) { + return -1; + } + + int startBit = Math.max(0, fromBit); + int wordIndex = startBit >> 6; + if (wordIndex > maxWord) { + return -1; + } + + long word = words[wordIndex] & (-1L << (startBit & 63)); + while (true) { + if (word != 0L) { + return (wordIndex << 6) + Long.numberOfTrailingZeros(word); + } + + wordIndex++; + if (wordIndex > maxWord) { + return -1; + } + word = words[wordIndex]; + } + } + + boolean isEmpty() { + return maxWord < 0; + } + + boolean contains(int y) { + if (y < 0) { + return false; + } + + int wordIndex = y >> 6; + if (wordIndex > maxWord) { + return false; + } + + return (words[wordIndex] & (1L << (y & 63))) != 0L; + } + + void clear() { + if (maxWord < 0) { + return; + } + + for (int index = 0; index <= maxWord; index++) { + words[index] = 0L; + } + maxWord = -1; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/module/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java new file mode 100644 index 000000000..79f8808c2 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -0,0 +1,150 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.modules.carve.CarvingBiomeSettings; +import art.arcane.iris.modules.carve.CarvingEnabledSettings; +import art.arcane.iris.modules.carve.CarvingSettings; +import art.arcane.iris.modules.carve.CaveDepthSettings; +import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; +import art.arcane.iris.modules.carve.CaveProfile; +import art.arcane.iris.modules.carve.UpperDimensionCarvingSettings; +import art.arcane.iris.modules.terrain.TerrainPalettes; +import art.arcane.iris.engine.mantle.components.CarveWorld; +import art.arcane.iris.engine.mantle.components.CaveCarving; +import art.arcane.iris.engine.mantle.components.CaveFloorMarking; +import com.volmit.IrisFeature; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.generation.ChunkContext; +import com.volmit.hunk.Hunk; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.service.CaveBiomes; +import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; + +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +/** + * Module {@code iris:carve}: caves. A mantle stage plans them into the mantle, reaching one block into each + * neighboring chunk where blended cave walls cross the border; a chunk stage later cuts them out of the chunk's + * terrain. The mantle stage is a port of what was Iris's carving mantle component, its work done by + * {@link CaveCarving}, one per world. The chunk stage's work is done by {@link CaveApplying}. + */ +public final class CarveModule implements IrisModule { + private static final String VERSION = "built-in"; + /** Blended cave walls reach one block past the chunk. */ + private static final int CAVE_REACH_BLOCKS = 1; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:carve", "Caves", VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + var registry = setup.registry(); + List.of(CaveProfile.class, CarvingSettings.class, CarvingEnabledSettings.class, CarvingBiomeSettings.class, + CaveDepthSettings.class, CaveLavaHeightSettings.class, UpperDimensionCarvingSettings.class) + .forEach(registry::registerSettings); + registry.registerService(CaveBiomes.class, new CaveBiomeBands()); + + var graph = setup.stages(); + graph.define(IrisStages.Carve.CAVES).reach(CAVE_REACH_BLOCKS).run(CarveModule::planCaves); + graph.define(IrisStages.Carve.APPLY).requires(IrisStages.Terrain.SHAPE).run(CarveModule::applyCaves); + } + + private static void planCaves(MantleStageContext context) { + if (!carves(context)) { + return; + } + MantleLayer voids = context.mantle().carved(); + caveCarving(context).carve(voids, context.terrain(), context.chunkX(), context.chunkZ()); + caveFloorMarking(context).mark(voids, context.terrain(), context.placementTerrain(), context.chunkX(), context.chunkZ()); + } + + private static void applyCaves(ChunkStageContext context) { + Hunk blocks = context.blocks(); + caveApplying(context).apply(context.mantle().carved(), context.terrain(), context.chunkX(), context.chunkZ(), blocks, CaveDressing.of(context)); + } + + private static CaveFloorMarking caveFloorMarking(ChunkContext context) { + return context.world().state(CaveFloorMarking.class, generating -> new CaveFloorMarking(carveWorld(generating, context.terrain()), + upperDimensionCarving(context))); + } + + private static CaveCarving caveCarving(ChunkContext context) { + return context.world().state(CaveCarving.class, generating -> new CaveCarving(generating, carveWorld(generating, context.terrain()), + upperDimensionCarving(context), fluidColumns(generating))); + } + + private static CaveApplying caveApplying(ChunkContext context) { + return context.world().state(CaveApplying.class, generating -> new CaveApplying(generating, carveWorld(generating, context.terrain()), + upperDimensionCarving(context))); + } + + /** The columns the dimension's fluid palette fills with a fluid. */ + private static CaveCarving.FluidColumns fluidColumns(PackWorld world) { + TerrainPalettes palettes = TerrainPalettes.of(world); + BlockRegistry blocks = world.resources().blocks(); + return (worldX, worldZ) -> { + BlockState fluid = palettes.fluidAt(worldX, worldZ); + return fluid != null && blocks.hasTrait(fluid, BlockTrait.FLUID); + }; + } + + /** What the carvers need of the world, from the dimension's settings and the first terrain they see (constant for the world). */ + private static CarveWorld carveWorld(PackWorld world, TerrainSampler terrain) { + int lavaHeight = dimensionSetting(world, CaveLavaHeightSettings.class, CaveLavaHeightSettings::height, CaveLavaHeightSettings.DEFAULT_HEIGHT); + return new CarveWorld(world.resources().noise(), world.seed(IrisSeedPurposes.CARVE), + terrain.bounds().maxY(), terrain.fluidHeight(), lavaHeight, + world.minWorldY()); + } + + private static boolean upperDimensionCarving(ChunkContext context) { + return centreDimensionValue(context, UpperDimensionCarvingSettings.class).map(UpperDimensionCarvingSettings::enabled).orElse(false); + } + + /** + * A dimension turns carving off with {@code carvingEnabled}. Listing {@code iris:carve/caves} in {@code disabledComponents} + * also does: Iris then skips this stage's mantle pass like any disabled component. + */ + private static boolean carves(ChunkContext context) { + return centreDimensionValue(context, CarvingEnabledSettings.class).map(CarvingEnabledSettings::enabled).orElse(true); + } + + private static Optional centreDimensionValue(ChunkContext context, Class type) { + return context.settings().at(type, context.centreX(), context.centreZ()).dimension(); + } + + private static V dimensionSetting(PackWorld world, Class type, Function read, V fallback) { + return world.settings().declared(type).dimension().map(read).orElse(fallback); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/CarveWallBuffer.java b/module/src/main/java/art/arcane/iris/engine/modifier/CarveWallBuffer.java new file mode 100644 index 000000000..18e21c943 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/CarveWallBuffer.java @@ -0,0 +1,166 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import com.volmit.mantle.CarvedVoid; + +import java.util.Arrays; + +final class CarveWallBuffer { + private static final int EMPTY_KEY = -1; + private static final double LOAD_FACTOR = 0.75D; + + private int[] keys; + private CarvedVoid[] values; + private int mask; + private int resizeAt; + private int size; + + CarveWallBuffer(int expectedSize) { + int capacity = 1; + int minimumCapacity = Math.max(8, expectedSize); + while (capacity < minimumCapacity) { + capacity <<= 1; + } + + keys = new int[capacity]; + Arrays.fill(keys, EMPTY_KEY); + values = new CarvedVoid[capacity]; + mask = capacity - 1; + resizeAt = Math.max(1, (int) (capacity * LOAD_FACTOR)); + } + + void put(int x, int y, int z, CarvedVoid value) { + int key = pack(x, y, z); + int index = mix(key) & mask; + + while (true) { + int existingKey = keys[index]; + if (existingKey == EMPTY_KEY) { + keys[index] = key; + values[index] = value; + size++; + if (size >= resizeAt) { + resize(); + } + return; + } + + if (existingKey == key) { + values[index] = value; + return; + } + + index = (index + 1) & mask; + } + } + + CarvedVoid get(int x, int y, int z) { + int key = pack(x, y, z); + int index = mix(key) & mask; + while (true) { + int existingKey = keys[index]; + if (existingKey == EMPTY_KEY) { + return null; + } + if (existingKey == key) { + return values[index]; + } + index = (index + 1) & mask; + } + } + + void forEach(Consumer consumer) { + for (int index = 0; index < keys.length; index++) { + int key = keys[index]; + if (key == EMPTY_KEY) { + continue; + } + + CarvedVoid carvedVoid = values[index]; + if (carvedVoid != null) { + consumer.accept(unpackX(key), unpackY(key), unpackZ(key), carvedVoid); + } + } + } + + void clear() { + Arrays.fill(keys, EMPTY_KEY); + Arrays.fill(values, null); + size = 0; + } + + private void resize() { + int[] oldKeys = keys; + CarvedVoid[] oldValues = values; + int nextCapacity = oldKeys.length << 1; + keys = new int[nextCapacity]; + Arrays.fill(keys, EMPTY_KEY); + values = new CarvedVoid[nextCapacity]; + mask = nextCapacity - 1; + resizeAt = Math.max(1, (int) (nextCapacity * LOAD_FACTOR)); + size = 0; + + for (int index = 0; index < oldKeys.length; index++) { + int key = oldKeys[index]; + CarvedVoid value = oldValues[index]; + if (key != EMPTY_KEY && value != null) { + reinsert(key, value); + } + } + } + + private void reinsert(int key, CarvedVoid value) { + int index = mix(key) & mask; + while (keys[index] != EMPTY_KEY) { + index = (index + 1) & mask; + } + + keys[index] = key; + values[index] = value; + size++; + } + + private int pack(int x, int y, int z) { + return (y << 8) | PowerOfTwoCoordinates.packLocal16(x & 15, z & 15); + } + + private int unpackX(int key) { + return PowerOfTwoCoordinates.unpackLocal16X(key & 255); + } + + private int unpackY(int key) { + return key >> 8; + } + + private int unpackZ(int key) { + return PowerOfTwoCoordinates.unpackLocal16Z(key); + } + + private int mix(int value) { + int mixed = value * 0x9E3779B9; + return mixed ^ (mixed >>> 16); + } + + @FunctionalInterface + interface Consumer { + void accept(int x, int y, int z, CarvedVoid carvedVoid); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/module/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java new file mode 100644 index 000000000..d63226fa8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -0,0 +1,640 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.volmlib.util.math.BlockPosition; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.iris.engine.mantle.components.CarveWorld; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockBox; +import com.volmit.hunk.Hunk; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; +import lombok.Data; + +import java.util.List; +import java.util.Map; + +/** + * Applies the caves the mantle planned to a chunk's blocks for {@link CarveModule}: carves each cave zone, paints + * its floor and ceiling with the cave biomes' layers, fills fluids and lava and decorates the cave surfaces. + * One per world, holding the carve stream's random. + */ +public class CaveApplying { + private static final ThreadLocal SCRATCH = ThreadLocal.withInitial(IrisCarveScratch::new); + private static final int CAVE_BIOME_BLEND_RADIUS = 3; + private static final int CAVE_BIOME_BLEND_CENTER_WEIGHT = 4; + private static final int CAVE_BIOME_BLEND_TOTAL_WEIGHT = 8; + private static final int CAVE_BIOME_CACHE_SIZE = 2048; + private static final int CHUNK_SIZE = 16; + private static final int CHUNK_AREA = 256; + private static final int LAYER_DEPTH = 3; + + private final CarveWorld world; + private final PackResources resources; + private final BlockRegistry blocks; + private final boolean upperDimensionCarving; + private final RNG rng; + private final BlockState caveAir; + private final BlockState plainAir; + private final BlockState lava; + + public CaveApplying(PackWorld packWorld, CarveWorld world, boolean upperDimensionCarving) { + this.world = world; + this.resources = packWorld.resources(); + this.blocks = resources.blocks(); + this.upperDimensionCarving = upperDimensionCarving; + this.rng = new RNG(world.carveSeed()); + this.caveAir = blocks.find("minecraft:cave_air").orElseThrow(); + this.plainAir = blocks.find("minecraft:air").orElseThrow(); + this.lava = blocks.find("minecraft:lava").orElseThrow(); + } + + /** + * Applies the caves to the chunk at chunk coordinates {@code x}, {@code z}, whose blocks are {@code output}; the caves are in + * {@code voids}, which reads one block beyond the chunk to wall the caves that cross its border, {@code terrain} gives the + * heights and cave biomes around the chunk and {@code dressing} what its caves' walls, floors and ceilings get. + */ + public void apply(MantleLayer voids, TerrainSampler terrain, int x, int z, Hunk output, CaveDressing dressing) { + new Application(voids, terrain, x, z, output, dressing).run(); + } + + static boolean hasExplicitCarveIntent(CarvedVoid carvedVoid) { + return carvedVoid != null && carvedVoid.fill() != CarvedVoid.Fill.OPEN; + } + + static boolean isFluidIntent(CarvedVoid carvedVoid) { + return carvedVoid != null && carvedVoid.fill() == CarvedVoid.Fill.FLUID; + } + + static boolean shouldPreserveExistingFluid(CarvedVoid carvedVoid, boolean existingIsFluid) { + return existingIsFluid && !hasExplicitCarveIntent(carvedVoid); + } + + static boolean usesDefaultLava(int caveLavaHeight, int y) { + return y <= caveLavaHeight; + } + + static boolean isUnsupportedSurfaceOre(boolean surfaceIsOre, boolean belowIsSolid) { + return surfaceIsOre && !belowIsSolid; + } + + static BlockState resolveExplicitCarveState(CarvedVoid carvedVoid, BlockState fluid, BlockState lava, BlockState air) { + if (carvedVoid == null) { + return null; + } + return switch (carvedVoid.fill()) { + case FLUID -> fluid; + case LAVA -> lava; + case AIR -> air; + case OPEN -> null; + }; + } + + static boolean canReplaceCaveFloorLayer(Hunk output, int x, int y, int z, BlockState layer, CaveBlockClasses classes) { + return !classes.hasGravity(layer) || y > 0 && classes.isSolid(output.get(x, y - 1, z)); + } + + static boolean hasStableCaveFloorSupport(Hunk output, int x, int floorY, int z, CaveBlockClasses classes) { + if (floorY <= 0) { + return false; + } + BlockState support = output.get(x, floorY - 1, z); + if (!classes.isSolid(support)) { + return false; + } + return !classes.hasGravity(support) || floorY > 1 && classes.isSolid(output.get(x, floorY - 2, z)); + } + + /** One chunk's application: the chunk's blocks, mantle and the caches its passes share. */ + final class Application { + private final MantleLayer voids; + private final TerrainSampler terrain; + private final int chunkX; + private final int chunkZ; + private final int chunkBlockX; + private final int chunkBlockZ; + private final Hunk output; + private final CaveDressing dressing; + private final CaveBlockClasses classes = new CaveBlockClasses(blocks); + private final CaveBiomeCache caveBiomeCache = new CaveBiomeCache(CAVE_BIOME_CACHE_SIZE); + private final IrisCarveScratch scratch = SCRATCH.get(); + + Application(MantleLayer voids, TerrainSampler terrain, int chunkX, int chunkZ, Hunk output, + CaveDressing dressing) { + this.voids = voids; + this.terrain = terrain; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + this.chunkBlockX = PowerOfTwoCoordinates.chunkToBlock(chunkX); + this.chunkBlockZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + this.output = output; + this.dressing = dressing; + } + + void run() { + scratch.reset(); + CarveWallBuffer walls = scratch.walls; + CarveColumnMask[] columnMasks = scratch.columnMasks; + CarveColumnMask[] boundaryMasks = scratch.boundaryMasks; + int[] surfaceHeights = scratch.surfaceHeights; + Map customBiomeCache = scratch.customBiomeCache; + boolean protectUpper = !upperDimensionCarving && terrain.upperDimensionY(chunkBlockX, chunkBlockZ).isPresent(); + int[] upperSurfaceHeights = protectUpper ? scratch.getOrCreateUpperSurfaceHeights() : null; + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + int worldX = localX + chunkBlockX; + int worldZ = localZ + chunkBlockZ; + surfaceHeights[columnIndex] = terrain.surfaceHeight(worldX, worldZ); + if (protectUpper) { + upperSurfaceHeights[columnIndex] = terrain.upperDimensionY(worldX, worldZ).getAsInt(); + } + } + + int worldHeightSpan = world.height(); + int caveLavaHeight = world.lavaHeight(); + BlockBox ownColumns = new BlockBox(chunkBlockX, 0, chunkBlockZ, chunkBlockX + CHUNK_SIZE, worldHeightSpan, chunkBlockZ + CHUNK_SIZE); + voids.visit(ownColumns, (xx, yy, zz, carvedVoid) -> { + if (yy <= 0) { + return; + } + + int rx = xx - chunkBlockX; + int rz = zz - chunkBlockZ; + int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz); + + if (upperSurfaceHeights != null && yy >= upperSurfaceHeights[columnIndex]) { + return; + } + + BlockState current = output.get(rx, yy, rz); + boolean explicitCarveIntent = hasExplicitCarveIntent(carvedVoid); + + if (shouldPreserveExistingFluid(carvedVoid, classes.isFluid(current))) { + return; + } + + columnMasks[columnIndex].add(yy); + + if (carvedVoid.biome().isPresent()) { + scratch.customCaveBiomePresent = true; + } + + if (classes.isAir(current) && !explicitCarveIntent) { + return; + } + + if (explicitCarveIntent) { + // Only a fluid cavern consumes the fluid sample, so never take it per voxel. + BlockState fluid = isFluidIntent(carvedVoid) ? dressing.fluidAt(chunkBlockX + rx, chunkBlockZ + rz) : null; + BlockState carved = resolveExplicitCarveState(carvedVoid, fluid, lava, caveAir); + output.set(rx, yy, rz, carved == null ? plainAir : carved); + } else if (usesDefaultLava(caveLavaHeight, yy)) { + output.set(rx, yy, rz, lava); + } else { + output.set(rx, yy, rz, caveAir); + } + }); + if (scratch.customCaveBiomePresent) { + addInternalWallsFromMantle(walls, columnMasks); + } else { + addInternalWallsFromMasks(walls, columnMasks); + } + addCrossChunkBoundaryWalls(walls, boundaryMasks, surfaceHeights); + + walls.forEach((rx, yy, rz, carvedVoid) -> { + int worldX = rx + chunkBlockX; + int worldZ = rz + chunkBlockZ; + ResourceId biome = carvedVoid.biome().isEmpty() + ? resolveCaveBiome(worldX, yy, worldZ) + : resolveCustomBiome(customBiomeCache, carvedVoid.biome().get()); + + if (biome != null) { + BlockState data = dressing.wall(biome, rng, worldX, yy, worldZ); + int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz); + + if (data != null && classes.isSolid(output.get(rx, yy, rz)) && yy < surfaceHeights[columnIndex]) { + output.set(rx, yy, rz, data); + } + } + }); + + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + processColumnFromMask(columnMasks[columnIndex], columnIndex, customBiomeCache); + } + + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + if (boundaryMasks[columnIndex].isEmpty() || !columnMasks[columnIndex].isEmpty()) { + continue; + } + processBoundaryColumnFromMask(boundaryMasks[columnIndex], walls, columnIndex, customBiomeCache); + } + + // Surface-break carving must not leave an ore cap suspended across the opening. + for (int columnIndex = 0; columnIndex < surfaceHeights.length; columnIndex++) { + int surfaceY = surfaceHeights[columnIndex]; + if (surfaceY <= 0 || surfaceY >= output.height()) { + continue; + } + + int belowY = surfaceY - 1; + if (!columnMasks[columnIndex].contains(belowY) && !boundaryMasks[columnIndex].contains(belowY)) { + continue; + } + + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + BlockState surface = output.get(localX, surfaceY, localZ); + BlockState below = output.get(localX, belowY, localZ); + if (isUnsupportedSurfaceOre(classes.isOre(surface), classes.isSolid(below))) { + output.set(localX, surfaceY, localZ, caveAir); + } + } + } + + private void addInternalWallsFromMasks(CarveWallBuffer walls, CarveColumnMask[] columnMasks) { + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + CarveColumnMask columnMask = columnMasks[columnIndex]; + if (columnMask.isEmpty()) { + continue; + } + + int rx = columnIndex >> 4; + int rz = columnIndex & 15; + int yy = columnMask.nextSetBit(0); + while (yy >= 0) { + if (rz < 15 && !columnMasks[columnIndex + 1].contains(yy)) { + walls.put(rx, yy, rz + 1, CarvedVoid.OPEN); + } + if (rx < 15 && !columnMasks[columnIndex + 16].contains(yy)) { + walls.put(rx + 1, yy, rz, CarvedVoid.OPEN); + } + if (rz > 0 && !columnMasks[columnIndex - 1].contains(yy)) { + walls.put(rx, yy, rz - 1, CarvedVoid.OPEN); + } + if (rx > 0 && !columnMasks[columnIndex - 16].contains(yy)) { + walls.put(rx - 1, yy, rz, CarvedVoid.OPEN); + } + yy = columnMask.nextSetBit(yy + 1); + } + } + } + + private void addInternalWallsFromMantle(CarveWallBuffer walls, CarveColumnMask[] columnMasks) { + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + CarveColumnMask columnMask = columnMasks[columnIndex]; + if (columnMask.isEmpty()) { + continue; + } + + int rx = columnIndex >> 4; + int rz = columnIndex & 15; + int yy = columnMask.nextSetBit(0); + while (yy >= 0) { + CarvedVoid carvedVoid = ownVoid(rx, yy, rz); + if (carvedVoid != null) { + if (rz < 15 && ownVoid(rx, yy, rz + 1) == null) { + walls.put(rx, yy, rz + 1, carvedVoid); + } + if (rx < 15 && ownVoid(rx + 1, yy, rz) == null) { + walls.put(rx + 1, yy, rz, carvedVoid); + } + if (rz > 0 && ownVoid(rx, yy, rz - 1) == null) { + walls.put(rx, yy, rz - 1, carvedVoid); + } + if (rx > 0 && ownVoid(rx - 1, yy, rz) == null) { + walls.put(rx - 1, yy, rz, carvedVoid); + } + } + yy = columnMask.nextSetBit(yy + 1); + } + } + } + + private void addCrossChunkBoundaryWalls(CarveWallBuffer walls, CarveColumnMask[] boundaryMasks, int[] surfaceHeights) { + int maxSurfaceY = 0; + for (int index = 0; index < surfaceHeights.length; index++) { + if (surfaceHeights[index] > maxSurfaceY) { + maxSurfaceY = surfaceHeights[index]; + } + } + int maxY = Math.min(world.height() - 1, maxSurfaceY + 1); + if (maxY < 1) { + return; + } + + int westBlockX = chunkBlockX - 1; + int eastBlockX = chunkBlockX + CHUNK_SIZE; + int northBlockZ = chunkBlockZ - 1; + int southBlockZ = chunkBlockZ + CHUNK_SIZE; + for (int yy = 1; yy <= maxY; yy++) { + for (int offset = 0; offset < CHUNK_SIZE; offset++) { + tryAddBoundaryWall(walls, boundaryMasks, 0, yy, offset, westBlockX, chunkBlockZ + offset); + tryAddBoundaryWall(walls, boundaryMasks, CHUNK_SIZE - 1, yy, offset, eastBlockX, chunkBlockZ + offset); + tryAddBoundaryWall(walls, boundaryMasks, offset, yy, 0, chunkBlockX + offset, northBlockZ); + tryAddBoundaryWall(walls, boundaryMasks, offset, yy, CHUNK_SIZE - 1, chunkBlockX + offset, southBlockZ); + } + } + } + + private void tryAddBoundaryWall(CarveWallBuffer walls, CarveColumnMask[] boundaryMasks, + int localX, int yy, int localZ, int neighborBlockX, int neighborBlockZ) { + if (ownVoid(localX, yy, localZ) != null) { + return; + } + + CarvedVoid neighbor = voids.get(neighborBlockX, yy, neighborBlockZ); + if (neighbor == null) { + return; + } + + walls.put(localX, yy, localZ, neighbor); + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + boundaryMasks[columnIndex].add(yy); + } + + private void processColumnFromMask(CarveColumnMask columnMask, int columnIndex, Map customBiomeCache) { + if (columnMask == null || columnMask.isEmpty()) { + return; + } + + int firstHeight = columnMask.nextSetBit(0); + if (firstHeight < 0) { + return; + } + + int rx = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int rz = columnIndex & 15; + int worldX = rx + PowerOfTwoCoordinates.chunkToBlock(chunkX); + int worldZ = rz + PowerOfTwoCoordinates.chunkToBlock(chunkZ); + CaveZone zone = new CaveZone(); + zone.setFloor(firstHeight); + int buf = firstHeight - 1; + int y = firstHeight; + + while (y >= 0) { + if (y <= world.height()) { + if (y == buf + 1) { + buf = y; + zone.ceiling = buf; + } else { + if (zone.isValid(world.height())) { + processZone(zone, rx, rz, worldX, worldZ, customBiomeCache); + } + zone = new CaveZone(); + zone.setFloor(y); + buf = y; + } + } + + y = columnMask.nextSetBit(y + 1); + } + + if (zone.isValid(world.height())) { + processZone(zone, rx, rz, worldX, worldZ, customBiomeCache); + } + } + + private void processBoundaryColumnFromMask(CarveColumnMask boundaryMask, CarveWallBuffer walls, int columnIndex, + Map customBiomeCache) { + int firstHeight = boundaryMask.nextSetBit(0); + if (firstHeight < 0) { + return; + } + + int rx = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int rz = columnIndex & 15; + int worldX = rx + PowerOfTwoCoordinates.chunkToBlock(chunkX); + int worldZ = rz + PowerOfTwoCoordinates.chunkToBlock(chunkZ); + int zoneFloor = firstHeight; + int zoneCeiling = firstHeight; + int y = boundaryMask.nextSetBit(firstHeight + 1); + + while (y >= 0) { + if (y == zoneCeiling + 1) { + zoneCeiling = y; + } else { + paintBoundaryZone(walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, customBiomeCache); + zoneFloor = y; + zoneCeiling = y; + } + y = boundaryMask.nextSetBit(y + 1); + } + + paintBoundaryZone(walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, customBiomeCache); + } + + private void paintBoundaryZone(CarveWallBuffer walls, int rx, int rz, int worldX, int worldZ, int zoneFloor, int zoneCeiling, + Map customBiomeCache) { + ResourceId floorBiome = resolveCaveBoundaryBiome(walls.get(rx, zoneFloor, rz), worldX, zoneFloor, worldZ, customBiomeCache); + ResourceId ceilingBiome = resolveCaveBoundaryBiome(walls.get(rx, zoneCeiling, rz), worldX, zoneCeiling, worldZ, customBiomeCache); + if (floorBiome == null && ceilingBiome == null) { + return; + } + + if (floorBiome != null) { + paintFloorLayers(floorBiome, rx, rz, worldX, worldZ, zoneFloor); + } + + if (ceilingBiome != null) { + paintCeilingLayers(ceilingBiome, rx, rz, worldX, worldZ, zoneCeiling, world.height()); + } + } + + /** Replaces the solid blocks under {@code floorY} with the layers of {@code floorBiome}. */ + private void paintFloorLayers(ResourceId floorBiome, int rx, int rz, int worldX, int worldZ, int floorY) { + List floorLayers = dressing.floorLayers(floorBiome, worldX, worldZ, rng, LAYER_DEPTH, floorY); + for (int i = 0; i < floorY - 1; i++) { + if (i >= floorLayers.size()) { + break; + } + int y = floorY - i - 1; + BlockState layer = floorLayers.get(i); + BlockState existing = output.get(rx, y, rz); + if (layer == null || !classes.isSolid(existing) || !canReplaceCaveFloorLayer(output, rx, y, rz, layer, classes)) { + continue; + } + output.set(rx, y, rz, classes.isOre(existing) ? dressing.oreFor(existing, layer) : layer); + } + } + + /** Replaces the solid blocks over {@code ceilingY} with the cave ceiling layers of {@code ceilingBiome}, below {@code maxY}. */ + private void paintCeilingLayers(ResourceId ceilingBiome, int rx, int rz, int worldX, int worldZ, int ceilingY, int maxY) { + List ceilingLayers = dressing.ceilingLayers(ceilingBiome, worldX, worldZ, rng, LAYER_DEPTH); + for (int i = 0; i < ceilingLayers.size(); i++) { + int y = ceilingY + i + 1; + if (y >= maxY) { + break; + } + BlockState layer = ceilingLayers.get(i); + BlockState existing = output.get(rx, y, rz); + if (layer == null || !classes.isSolid(existing)) { + continue; + } + output.set(rx, y, rz, classes.isOre(existing) ? dressing.oreFor(existing, layer) : layer); + } + } + + private void processZone(CaveZone zone, int rx, int rz, int xx, int zz, Map customBiomeCache) { + int maxY = output.height(); + + if (zone.ceiling + 1 < maxY && classes.isDecorant(output.get(rx, zone.ceiling + 1, rz))) { + output.set(rx, zone.ceiling + 1, rz, caveAir); + } + + if (classes.isDecorant(output.get(rx, zone.ceiling, rz))) { + output.set(rx, zone.ceiling, rz, caveAir); + } + + ResourceId floorBiome = resolveCaveBoundaryBiome(rx, zone.floor, rz, xx, zz, customBiomeCache); + ResourceId ceilingBiome = resolveCaveBoundaryBiome(rx, zone.ceiling, rz, xx, zz, customBiomeCache); + if (floorBiome == null && ceilingBiome == null) { + return; + } + + if (floorBiome != null) { + paintFloorLayers(floorBiome, rx, rz, xx, zz, zone.floor); + } + + if (ceilingBiome != null) { + paintCeilingLayers(ceilingBiome, rx, rz, xx, zz, zone.ceiling, maxY); + } + + if (floorBiome != null && dressing.hasDecorators(floorBiome, DecorationPart.NONE) + && hasStableCaveFloorSupport(output, rx, zone.getFloor(), rz, classes)) { + dressing.decorateFloor(rx, rz, xx, zz, floorBiome, zone.getFloor() - 1, zone.airThickness()); + } + + if (ceilingBiome != null && dressing.hasDecorators(ceilingBiome, DecorationPart.CEILING) && zone.getCeiling() + 1 < maxY + && classes.isSolid(output.get(rx, zone.getCeiling() + 1, rz))) { + dressing.decorateCeiling(rx, rz, xx, zz, ceilingBiome, zone.getCeiling(), zone.airThickness()); + } + } + + ResourceId resolveCaveBoundaryBiome(int x, int y, int z, int worldX, int worldZ, Map customBiomeCache) { + return resolveCaveBoundaryBiome(ownVoid(x, y, z), worldX, y, worldZ, customBiomeCache); + } + + /** The void at a block of this chunk; null where nothing is carved, and above or below the dimension. */ + private CarvedVoid ownVoid(int localX, int y, int localZ) { + if (y < 0 || y >= world.height()) { + return null; + } + return voids.get(chunkBlockX + localX, y, chunkBlockZ + localZ); + } + + ResourceId resolveCaveBoundaryBiome(CarvedVoid carvedVoid, int worldX, int y, int worldZ, Map customBiomeCache) { + if (carvedVoid != null && carvedVoid.biome().isPresent()) { + return resolveCustomBiome(customBiomeCache, carvedVoid.biome().get()); + } + return resolveCaveBiome(worldX, y, worldZ); + } + + private ResourceId resolveCaveBiome(int x, int y, int z) { + ResourceId center = sampleCaveBiome(x, y, z); + if (center == null) { + return null; + } + + ResourceId xPos = sampleCaveBiome(x + CAVE_BIOME_BLEND_RADIUS, y, z); + ResourceId xNeg = sampleCaveBiome(x - CAVE_BIOME_BLEND_RADIUS, y, z); + ResourceId zPos = sampleCaveBiome(x, y, z + CAVE_BIOME_BLEND_RADIUS); + ResourceId zNeg = sampleCaveBiome(x, y, z - CAVE_BIOME_BLEND_RADIUS); + + if (xPos == center && xNeg == center && zPos == center && zNeg == center) { + return center; + } + + int roll = Math.floorMod(rng.nextParallelRNG(BlockPosition.toLong(x, y, z)).nextInt(), CAVE_BIOME_BLEND_TOTAL_WEIGHT); + if (roll < CAVE_BIOME_BLEND_CENTER_WEIGHT) { + return center; + } + roll -= CAVE_BIOME_BLEND_CENTER_WEIGHT; + if (roll == 0) { + return xPos != null ? xPos : center; + } + if (roll == 1) { + return xNeg != null ? xNeg : center; + } + if (roll == 2) { + return zPos != null ? zPos : center; + } + return zNeg != null ? zNeg : center; + } + + private ResourceId sampleCaveBiome(int x, int y, int z) { + long key = BlockPosition.toLong(x, y, z); + ResourceId cachedBiome = caveBiomeCache.get(key); + if (cachedBiome != null) { + return cachedBiome; + } + + ResourceId resolvedBiome = terrain.caveBiome(x, y, z).orElse(null); + if (resolvedBiome != null) { + caveBiomeCache.put(key, resolvedBiome); + } + return resolvedBiome; + } + + /** The pack's biome with this id; null when the pack has none or it cannot be loaded. */ + private ResourceId existingBiomeId(ResourceId id) { + try { + return resources.find(PackResources.BIOMES, id).isPresent() ? id : null; + } catch (IllegalStateException unreadable) { + return null; + } + } + + private ResourceId resolveCustomBiome(Map customBiomeCache, ResourceId customBiome) { + if (customBiomeCache.containsKey(customBiome)) { + return customBiomeCache.get(customBiome); + } + + ResourceId id = existingBiomeId(customBiome); + customBiomeCache.put(customBiome, id); + return id; + } + } + + @Data + public static class CaveZone { + private int ceiling = -1; + private int floor = -1; + + public int airThickness() { + return (ceiling - floor) - 1; + } + + public boolean isValid(int height) { + return floor < ceiling && ceiling - floor >= 1 && floor >= 0 && ceiling <= height && airThickness() > 0; + } + + public String toString() { + return floor + "-" + ceiling; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java b/module/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java new file mode 100644 index 000000000..49ede6917 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java @@ -0,0 +1,73 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.modules.carve.CaveDepthSettings; +import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; +import art.arcane.iris.engine.object.terrain.carving.DeclaredByLevel; +import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; +import com.volmit.resource.ResourceId; +import com.volmit.service.CaveBiomes; +import com.volmit.world.PackWorld; + +import java.util.Optional; + +/** + * What the carve module tells the host about cave biomes ({@link CaveBiomes}): the biome of the dimension's carving band at a + * position, and how far below the surface a biome's caves begin. + */ +public final class CaveBiomeBands implements CaveBiomes { + @Override + public Optional overriddenBiome(PackWorld world, int x, int y, int z) { + CarvingResolver resolver = CarvingResolver.of(world); + ResolvedCarvingEntry rootEntry = resolver.rootEntryAt(y); + if (rootEntry == null) { + return Optional.empty(); + } + ResolvedCarvingEntry entry = resolver.resolveFromRoot(rootEntry, x, z); + if (resolver.entryBiome(entry) == null) { + return Optional.empty(); + } + return Optional.of(world.resources().idOf(entry.biomeKey().trim())); + } + + @Override + public int minDepthBelowSurface(PackWorld world, ResourceId biome) { + return Depths.of(world).minDepthBelowSurface(biome); + } + + /** The minimum depths the world's biomes declare ({@code caveMinDepthBelowSurface}), found by biome id. */ + private static final class Depths { + private final DeclaredByLevel declared; + + private Depths(PackWorld world) { + this.declared = DeclaredByLevel.of(world, CaveDepthSettings.class); + } + + static Depths of(PackWorld world) { + return world.state(Depths.class, Depths::new); + } + + /** How many blocks below the surface the biome's caves begin, as its {@code caveMinDepthBelowSurface} says; 0 where it says none. */ + int minDepthBelowSurface(ResourceId biome) { + CaveDepthSettings depth = declared.ofBiome(biome); + return depth == null ? 0 : depth.depth(); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeCache.java b/module/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeCache.java new file mode 100644 index 000000000..5f32cab21 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeCache.java @@ -0,0 +1,99 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import com.volmit.resource.ResourceId; + +import java.util.Arrays; + +/** + * The cave biomes one chunk's caves have sampled so far, by block position (see {@link art.arcane.volmlib.util.math.BlockPosition#toLong}): + * a cave wall asks for the biome around it five times, and the next wall block asks again for most of them. Open addressing on + * longs, which spares the boxing a map of {@link Long} would do on this hot path; only biomes that exist are kept. + */ +final class CaveBiomeCache { + private static final double LOAD_FACTOR = 0.5D; + private static final long EMPTY_KEY = Long.MIN_VALUE; + + private long[] keys; + private ResourceId[] values; + private int mask; + private int size; + + CaveBiomeCache(int expectedSize) { + int capacity = 8; + while (capacity * LOAD_FACTOR < expectedSize) { + capacity <<= 1; + } + allocate(capacity); + } + + /** The biome kept for {@code key}; null where none is. */ + ResourceId get(long key) { + int index = slot(key); + while (keys[index] != EMPTY_KEY) { + if (keys[index] == key) { + return values[index]; + } + index = (index + 1) & mask; + } + return null; + } + + void put(long key, ResourceId biome) { + if ((size + 1) > keys.length * LOAD_FACTOR) { + grow(); + } + int index = slot(key); + while (keys[index] != EMPTY_KEY) { + if (keys[index] == key) { + values[index] = biome; + return; + } + index = (index + 1) & mask; + } + keys[index] = key; + values[index] = biome; + size++; + } + + private int slot(long key) { + long mixed = key * 0x9E3779B97F4A7C15L; + return (int) (mixed ^ (mixed >>> 32)) & mask; + } + + private void allocate(int capacity) { + keys = new long[capacity]; + Arrays.fill(keys, EMPTY_KEY); + values = new ResourceId[capacity]; + mask = capacity - 1; + size = 0; + } + + private void grow() { + long[] oldKeys = keys; + ResourceId[] oldValues = values; + allocate(oldKeys.length << 1); + for (int index = 0; index < oldKeys.length; index++) { + if (oldKeys[index] != EMPTY_KEY) { + put(oldKeys[index], oldValues[index]); + } + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/CaveBlockClasses.java b/module/src/main/java/art/arcane/iris/engine/modifier/CaveBlockClasses.java new file mode 100644 index 000000000..78d88e7c8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/CaveBlockClasses.java @@ -0,0 +1,89 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; + +import java.util.IdentityHashMap; +import java.util.Map; + +/** + * What the cave passes of one chunk ask about blocks, answered from memory. A chunk holds few distinct states and a cave pass asks + * about them per block, so each state instance (the hunk hands out one per distinct state) is classified once. + */ +final class CaveBlockClasses { + private static final int SOLID = 1; + private static final int FLUID = 2; + private static final int AIR = 4; + private static final int ORE = 8; + private static final int DECORATION = 16; + private static final int GRAVITY = 32; + + private final BlockRegistry blocks; + private final Map classes = new IdentityHashMap<>(); + + CaveBlockClasses(BlockRegistry blocks) { + this.blocks = blocks; + } + + boolean isSolid(BlockState state) { + return (classesOf(state) & SOLID) != 0; + } + + boolean isFluid(BlockState state) { + return (classesOf(state) & FLUID) != 0; + } + + boolean isAir(BlockState state) { + return (classesOf(state) & AIR) != 0; + } + + boolean isOre(BlockState state) { + return (classesOf(state) & ORE) != 0; + } + + boolean isDecorant(BlockState state) { + return (classesOf(state) & DECORATION) != 0; + } + + boolean hasGravity(BlockState state) { + return state != null && (classesOf(state) & GRAVITY) != 0; + } + + private int classesOf(BlockState state) { + Integer known = classes.get(state); + if (known != null) { + return known; + } + int computed = classify(state); + classes.put(state, computed); + return computed; + } + + private int classify(BlockState state) { + return flag(state, BlockTrait.SOLID, SOLID) | flag(state, BlockTrait.FLUID, FLUID) | flag(state, BlockTrait.AIR, AIR) + | flag(state, BlockTrait.ORE, ORE) | flag(state, BlockTrait.DECORATION, DECORATION) | flag(state, BlockTrait.GRAVITY, GRAVITY); + } + + private int flag(BlockState state, BlockTrait trait, int bit) { + return blocks.hasTrait(state, trait) ? bit : 0; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/CaveDressing.java b/module/src/main/java/art/arcane/iris/engine/modifier/CaveDressing.java new file mode 100644 index 000000000..2cc160d08 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/CaveDressing.java @@ -0,0 +1,55 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.resource.ResourceId; +import com.volmit.stage.ChunkStageContext; + +import java.util.List; + +/** + * What a cave's walls, floor and ceiling get in one chunk: its biome's layers and decorators and the dimension's fluid palette. + * {@link #of} answers with the terrain and decorant built-ins, which ship in the same jar; tests answer with fixed blocks. + */ +public interface CaveDressing { + /** The built-ins' dressing of the chunk {@code context} generates. */ + static CaveDressing of(ChunkStageContext context) { + return new BuiltInCaveDressing(context); + } + + BlockState fluidAt(int x, int z); + + /** The block of the biome's wall at the position; null when the biome declares no wall. */ + BlockState wall(ResourceId biome, RNG rng, int x, int y, int z); + + List floorLayers(ResourceId biome, int x, int z, RNG rng, int depth, int floorY); + + List ceilingLayers(ResourceId biome, int x, int z, RNG rng, int depth); + + boolean hasDecorators(ResourceId biome, DecorationPart part); + + void decorateFloor(int localX, int localZ, int x, int z, ResourceId biome, int floorY, int airThickness); + + void decorateCeiling(int localX, int localZ, int x, int z, ResourceId biome, int ceilingY, int airThickness); + + /** The ore that suits the {@code rock} it replaces, as the platform decides. */ + BlockState oreFor(BlockState rock, BlockState ore); +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/DepositClump.java b/module/src/main/java/art/arcane/iris/engine/modifier/DepositClump.java new file mode 100644 index 000000000..4f72c2a5a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/DepositClump.java @@ -0,0 +1,70 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.modifier; + +import art.arcane.volmlib.util.data.VectorMap; +import art.arcane.volmlib.util.math.IrisBlockVector; +import art.arcane.volmlib.util.math.Vector3i; +import com.volmit.block.BlockState; + +/** + * The blocks of one deposit clump, around its centre. Blocks are kept in a {@link VectorMap} of positions relative to the centre, + * which is how Iris always held a clump, so a clump's blocks come in the same order and a chunk's deposits draw the same random + * numbers. + */ +final class DepositClump { + private final int width; + private final int height; + private final int depth; + private final Vector3i center; + private final VectorMap blocks = new VectorMap<>(); + + DepositClump(int width, int height, int depth) { + this.width = width; + this.height = height; + this.depth = depth; + this.center = new Vector3i(width / 2, height / 2, depth / 2); + } + + /** How many blocks wide the clump's box is, along X. */ + int width() { + return width; + } + + Vector3i center() { + return center; + } + + /** The clump's blocks by their position relative to its centre. */ + VectorMap blocks() { + return blocks; + } + + /** Puts {@code block} at {@code x}, {@code y}, {@code z} counted from the corner of the clump's box. */ + void setFromCorner(int x, int y, int z, BlockState block) { + if (x >= width || y >= height || z >= depth) { + throw new IllegalArgumentException(x + " " + y + " " + z + " exceeds limit of " + width + " " + height + " " + depth); + } + blocks.put(new IrisBlockVector(x - center.getX(), y - center.getY(), z - center.getZ()), block); + } + + /** Puts {@code block} on the centre, which is where a one block clump has its block. */ + void setCentre(BlockState block) { + blocks.put(new IrisBlockVector(center.getX(), center.getY(), center.getZ()), block); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java b/module/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java new file mode 100644 index 000000000..c0634082b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java @@ -0,0 +1,78 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.modules.deposit.DepositGenerator; +import art.arcane.iris.modules.deposit.DepositSettings; +import art.arcane.iris.modules.deposit.DepositVariantSettings; +import art.arcane.iris.modules.deposit.OreFrequencySettings; +import art.arcane.iris.modules.deposit.OreSizeSettings; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.config.FeatureSettings; +import com.volmit.stage.ChunkStageContext; + +import java.util.List; + +/** + * Module {@code iris:deposit}: ores and other deposits. The dimension, a region and a biome each declare their + * own {@link DepositSettings}, and they stack: a chunk gets every level's deposits at its centre column, the + * dimension's first, then the region's, then the biome's. The stage runs where any column of the chunk has + * deposits, but places only what the centre column declares, so a chunk's deposits do not depend on which + * of its columns a biome border crosses. + */ +public final class DepositModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:deposit", "Deposits", VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + var registry = setup.registry(); + registry.registerSettings(DepositVariantSettings.class); + registry.registerSettings(OreFrequencySettings.class); + registry.registerSettings(OreSizeSettings.class); + + setup.stages().define(IrisStages.Deposit.ORES) + .when(DepositSettings.class) + .requires(IrisStages.Terrain.SHAPE) + .softAfter(IrisStages.Floating.SOLIDS) + .run(DepositModule::place); + } + + private static void place(ChunkStageContext context) { + List generators = generatorsAt(context.settings(), context.centreX(), context.centreZ()); + if (generators.isEmpty()) { + return; + } + DepositPlacer.of(context.world()).generate(context, generators); + } + + /** Every level's generators at the column {@code x}, {@code z}, in level order. */ + static List generatorsAt(FeatureSettings settings, int x, int z) { + return settings.at(DepositSettings.class, x, z).values().stream() + .flatMap(declared -> declared.generators().stream()) + .toList(); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java b/module/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java new file mode 100644 index 000000000..a4f464d2d --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -0,0 +1,433 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.modules.deposit.DepositGenerator; +import art.arcane.iris.modules.deposit.DepositHeightDistribution; +import art.arcane.iris.modules.deposit.DepositPlacementScope; +import art.arcane.iris.modules.deposit.DepositVariant; +import art.arcane.iris.modules.deposit.DepositVariantSettings; +import art.arcane.iris.modules.deposit.OreFrequencySettings; +import art.arcane.iris.modules.deposit.OreSizeSettings; +import art.arcane.iris.engine.modifier.ResolvedDeposit.BiomeIdentity; +import art.arcane.volmlib.util.math.IrisBlockVector; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.config.FeatureSettings; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.hunk.Hunk; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.BiomeSample; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; + +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Predicate; +import java.util.function.Supplier; + +/** + * Places deposit clumps into one chunk for {@link DepositModule}: one per world, holding the deposit stream's random and each + * generator made ready for this world ({@link ResolvedDeposit}: resolved blocks and clump shapes). Each generator gets its own + * random, derived from the chunk and its position in the list, and the generators of a chunk run one after the other. + */ +final class DepositPlacer { + private static final double UNCHANGED_ORE_MULTIPLIER = 1D; + private static final int CHUNK_WIDTH = 16; + private static final long CHUNK_X_SEED_FACTOR = 341873128712L; + private static final long CHUNK_Z_SEED_FACTOR = 132897987541L; + private static final int DEFAULT_SURFACE_CLEARANCE = 7; + private static final BlockState BEDROCK = new BlockState("minecraft:bedrock"); + + private final RNG rng; + private final BlockRegistry registry; + private final PackResources resources; + private final ModuleLog log; + private final boolean tunesOres; + private final boolean remapsOres; + private final Map resolved = new ConcurrentHashMap<>(); + private final Map variants = new ConcurrentHashMap<>(); + private final Map> biomeIdentities = new ConcurrentHashMap<>(); + + DepositPlacer(PackWorld world) { + this.rng = new RNG(world.seed(IrisSeedPurposes.DEPOSIT)); + this.resources = world.resources(); + this.registry = resources.blocks(); + this.log = world.log(); + this.tunesOres = declares(world, OreFrequencySettings.class) || declares(world, OreSizeSettings.class); + this.remapsOres = declares(world, DepositVariantSettings.class); + } + + /** The world's deposit placer, kept in its state store. */ + static DepositPlacer of(PackWorld world) { + return world.state(DepositPlacer.class, DepositPlacer::new); + } + + /** Whether any level of the pack declares {@code settings}; a world that declares none never asks a biome for them. */ + private static boolean declares(PackWorld world, Class settings) { + return !world.settings().declared(settings).isEmpty(); + } + + /** Runs {@code generators}, in order, on the chunk of {@code context}. */ + void generate(ChunkStageContext context, List generators) { + Placing placing = new Placing(context); + long seed = context.chunkX() * CHUNK_X_SEED_FACTOR + context.chunkZ() * CHUNK_Z_SEED_FACTOR; + long mask = 0; + for (DepositGenerator generator : generators) { + long finalSeed = seed * ++mask; + placing.generate(generator, rng.nextParallelRNG(finalSeed)); + } + } + + private ResolvedDeposit resolved(DepositGenerator generator) { + return resolved.computeIfAbsent(generator, ignored -> new ResolvedDeposit(generator, rng.getSeed(), registry)); + } + + private Optional identityOf(ResourceId biome) { + return biomeIdentities.computeIfAbsent(biome, id -> resources.find(PackResources.BIOMES, id) + .map(found -> new BiomeIdentity(id.path(), found.platformBiome().toString(), found.vanillaBiome().toString()))); + } + + /** Places deposits into one chunk, with the views of its invocation. */ + private final class Placing { + private final Hunk blocks; + private final TerrainSampler terrain; + private final FeatureSettings settings; + private final MantleLayer carvedVoids; + private final int originX; + private final int originZ; + private final int worldHeight; + private final int minWorldY; + private final int[] surfaceHeights = new int[CHUNK_WIDTH * CHUNK_WIDTH]; + private boolean surfaceKnown; + private final Map airStates = new IdentityHashMap<>(); + private final Map replaceableStates = new IdentityHashMap<>(); + private final Map> suitedOres = new IdentityHashMap<>(); + + Placing(ChunkStageContext context) { + this.blocks = context.blocks(); + this.terrain = context.terrain(); + this.settings = context.settings(); + this.carvedVoids = context.mantle().carved(); + this.originX = context.originX(); + this.originZ = context.originZ(); + this.worldHeight = blocks.height(); + this.minWorldY = terrain.minWorldY(); + } + + void generate(DepositGenerator k, RNG rng) { + ResolvedDeposit deposit = resolved(k); + if (k.spawnChance() < rng.d()) + return; + + for (int l = 0; l < rng.i(k.minPerChunk(), k.maxPerChunk() + 1); l++) { + if (k.perClumpSpawnChance() < rng.d()) + continue; + + DepositClump clump = deposit.clump(rng); + + int dim = clump.width(); + int min = dim / 2; + int max = (int) (16D - dim / 2D); + + if (min > max || min < 0 || max > 15) { + min = 6; + max = 9; + } + + int x = rng.i(min, max + 1); + int z = rng.i(min, max + 1); + int terrainSurface = terrainSurface(x, z); + int height = k.placementScope() == DepositPlacementScope.TERRAIN + ? depositSurfaceLimit(terrainSurface, k.surfaceClearance()) + : worldHeight - 1; + + if (height < 0) { + continue; + } + + int y = sampleHeight( + k.heightDistribution(), rng, k.minHeight(), k.maxHeight(), + Math.min(height, worldHeight - 1)); + if (y == Integer.MIN_VALUE) { + continue; + } + + boolean clippedHeight = k.heightDistribution() == DepositHeightDistribution.CLIPPED_UNIFORM; + if (clippedHeight && y > height - 2) + continue; + + int biomeY = Math.max(0, Math.min(worldHeight - 1, y)); + boolean oreDeposit = deposit.isOre(); + Supplier biomes = biomesAt(x, biomeY, z); + if (!deposit.matchesBiome(() -> identityOf(biomes.get().surfaceBiome()).orElse(null), + () -> biomes.get().caveBiome().flatMap(id -> identityOf(id)).orElse(null))) { + continue; + } + + if (oreDeposit && tunesOres) { + Optional caveBiome = biomes.get().caveBiome(); + if (caveBiome.isPresent()) { + double frequencyMultiplier = oreFrequencyMultiplier(caveBiome.get()); + if (frequencyMultiplier < 1D + && !passesOreFrequency(frequencyMultiplier, rng.d())) { + continue; + } + + double sizeMultiplier = oreSizeMultiplier(caveBiome.get()); + if (sizeMultiplier != 1D) { + DepositClump scaledClump = deposit.clump(rng, sizeMultiplier); + int scaledDimension = scaledClump.width(); + x = clampDepositCenter(x, scaledDimension, 16); + if (clippedHeight) { + y = clampDepositCenter(y, scaledDimension, worldHeight); + } + z = clampDepositCenter(z, scaledDimension, 16); + clump = scaledClump; + } + } + } + + placeClump(k, deposit, clump, rng, x, y, z); + } + } + + private void placeClump(DepositGenerator k, ResolvedDeposit deposit, DepositClump clump, RNG rng, int x, int y, int z) { + for (IrisBlockVector j : clump.blocks().keys()) { + int nx = j.getBlockX() + x; + int ny = j.getBlockY() + y; + int nz = j.getBlockZ() + z; + + if (nx > 15 || nx < 0 || ny >= worldHeight || ny < 0 || nz < 0 || nz > 15) { + continue; + } + int columnSurface = terrainSurface(nx, nz); + if (!placementSurfaceAllows( + k.placementScope(), ny, columnSurface, k.surfaceClearance())) { + continue; + } + + BlockState current = blocks.get(nx, ny, nz); + if (!canReplaceTarget(current)) { + continue; + } + if (!deposit.canReplace(current)) { + continue; + } + if (!k.replaceBedrock() && current.material().equals(BEDROCK.material())) { + continue; + } + if (shouldDiscardExposed( + k.discardChanceOnAirExposure(), rng.d(), isAdjacentToAir(blocks, nx, ny, nz, this::isAir))) { + continue; + } + + if (carvedVoids.get(originX + nx, ny, originZ + nz) == null) { + BlockState ore = clump.blocks().get(j); + BlockState remapped = remapped(nx, ny, nz, ore); + BlockState finalBlock = remapped != null + ? remapped + : oreSuiting(current, ore); + blocks.set(nx, ny, nz, finalBlock); + } + } + } + + /** Asks the host for the biomes of the column only if a filter or an ore tuning reads them, and only once. */ + private Supplier biomesAt(int localX, int y, int localZ) { + BiomeSample[] sample = new BiomeSample[1]; + return () -> { + if (sample[0] == null) { + sample[0] = terrain.biome(originX + localX, y, originZ + localZ); + } + return sample[0]; + }; + } + + /** {@code ore}, or the variant of it that suits the rock it replaces; the platform knows the variants, so each pair is asked once. */ + private BlockState oreSuiting(BlockState rock, BlockState ore) { + return suitedOres.computeIfAbsent(rock, known -> new IdentityHashMap<>()) + .computeIfAbsent(ore, known -> registry.oreFor(rock, known)); + } + + private boolean isAir(BlockState state) { + return airStates.computeIfAbsent(state, known -> registry.hasTrait(known, BlockTrait.AIR)); + } + + private boolean canReplaceTarget(BlockState state) { + return replaceableStates.computeIfAbsent(state, known -> canReplaceDepositTarget(registry, known)); + } + + /** The height of the terrain at a column of the chunk, as the stages before the deposits see it. */ + private int terrainSurface(int localX, int localZ) { + if (!surfaceKnown) { + for (int x = 0; x < CHUNK_WIDTH; x++) { + for (int z = 0; z < CHUNK_WIDTH; z++) { + surfaceHeights[x * CHUNK_WIDTH + z] = terrain.surfaceHeight(originX + x, originZ + z); + } + } + surfaceKnown = true; + } + return surfaceHeights[localX * CHUNK_WIDTH + localZ]; + } + + private BlockState remapped(int localX, int localY, int localZ, BlockState ore) { + if (!remapsOres) { + return null; + } + int worldX = originX + localX; + int worldZ = originZ + localZ; + int worldY = absoluteWorldY(minWorldY, localY); + + Optional caveBiome = terrain.biome(worldX, localY, worldZ).caveBiome(); + if (caveBiome.isPresent()) { + BlockState match = matchDepositVariant(settings.declaredBy(caveBiome.get(), DepositVariantSettings.class), ore, worldY); + if (match != null) { + return match; + } + } + + SettingsStack declared = settings.at(DepositVariantSettings.class, worldX, worldZ); + BlockState match = matchDepositVariant(declared.level(Level.REGION), ore, worldY); + if (match != null) { + return match; + } + + return matchDepositVariant(declared.dimension(), ore, worldY); + } + + private BlockState matchDepositVariant(Optional owner, BlockState ore, int y) { + for (DepositVariant declared : owner.map(DepositVariantSettings::variants).orElse(List.of())) { + ResolvedDepositVariant variant = variants.computeIfAbsent(declared, rule -> new ResolvedDepositVariant(rule, registry, log)); + if (!variant.appliesAt(y)) { + continue; + } + + BlockState swapped = variant.remapOrNull(ore); + if (swapped != null) { + return swapped; + } + } + + return null; + } + + private double oreFrequencyMultiplier(ResourceId caveBiome) { + return settings.declaredBy(caveBiome, OreFrequencySettings.class).map(OreFrequencySettings::multiplier).orElse(UNCHANGED_ORE_MULTIPLIER); + } + + private double oreSizeMultiplier(ResourceId caveBiome) { + return settings.declaredBy(caveBiome, OreSizeSettings.class).map(OreSizeSettings::multiplier).orElse(UNCHANGED_ORE_MULTIPLIER); + } + } + + static int depositSurfaceLimit(int surfaceY) { + return depositSurfaceLimit(surfaceY, DEFAULT_SURFACE_CLEARANCE); + } + + static int depositSurfaceLimit(int surfaceY, int surfaceClearance) { + return surfaceY - Math.max(0, surfaceClearance); + } + + static boolean placementSurfaceAllows( + DepositPlacementScope scope, int candidateY, int surfaceY, int surfaceClearance) { + int clearance = Math.max(0, surfaceClearance); + return switch (scope) { + case ABOVE_TERRAIN -> candidateY > surfaceY + clearance; + case FULL_HEIGHT -> true; + case TERRAIN -> candidateY <= surfaceY - clearance; + }; + } + + static int absoluteWorldY(int minHeight, int localY) { + return minHeight + localY; + } + + static boolean canReplaceDepositTarget(BlockRegistry registry, BlockState state) { + return state != null && !registry.hasTrait(state, BlockTrait.AIR) && !registry.hasTrait(state, BlockTrait.FLUID); + } + + static int sampleHeight( + DepositHeightDistribution distribution, RNG rng, + int configuredMinimum, int configuredMaximum, int clippedMaximum) { + int minimum = distribution == DepositHeightDistribution.CLIPPED_UNIFORM + ? Math.max(0, configuredMinimum) + : configuredMinimum; + int maximum = distribution == DepositHeightDistribution.CLIPPED_UNIFORM + ? Math.min(clippedMaximum, configuredMaximum) + : configuredMaximum; + if (minimum > maximum) { + return Integer.MIN_VALUE; + } + if (minimum == maximum) { + return minimum; + } + if (distribution != DepositHeightDistribution.TRIANGLE) { + return minimum + rng.nextInt(maximum - minimum + 1); + } + + int span = maximum - minimum; + int lowerHalf = span / 2; + int upperHalf = span - lowerHalf; + return minimum + rng.nextInt(upperHalf + 1) + rng.nextInt(lowerHalf + 1); + } + + static boolean shouldDiscardExposed(double chance, double sample, boolean adjacentToAir) { + return adjacentToAir && chance > 0D && sample < Math.min(1D, chance); + } + + static boolean isAdjacentToAir(Hunk data, int x, int y, int z, Predicate isAir) { + return isAirAt(data, x - 1, y, z, isAir) + || isAirAt(data, x + 1, y, z, isAir) + || isAirAt(data, x, y - 1, z, isAir) + || isAirAt(data, x, y + 1, z, isAir) + || isAirAt(data, x, y, z - 1, isAir) + || isAirAt(data, x, y, z + 1, isAir); + } + + private static boolean isAirAt(Hunk data, int x, int y, int z, Predicate isAir) { + if (x < 0 || x >= data.width() + || y < 0 || y >= data.height() + || z < 0 || z >= data.depth()) { + return false; + } + return isAir.test(data.get(x, y, z)); + } + + static boolean passesOreFrequency(double multiplier, double sample) { + return multiplier >= 1D || sample < Math.max(0D, multiplier); + } + + static int clampDepositCenter(int center, int dimension, int limit) { + int minimum = dimension / 2; + int maximum = (int) (limit - dimension / 2D); + return Math.max(minimum, Math.min(center, maximum)); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/module/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java new file mode 100644 index 000000000..82dcf9b44 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -0,0 +1,465 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.builtin.decorant.DecorantSettings; +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.iris.modules.floating.FloatingBottomPaletteMode; +import art.arcane.iris.builtin.prepare.SlopeClip; +import art.arcane.iris.modules.terrain.BiomeLayers; +import art.arcane.iris.modules.terrain.ColumnSlope; +import art.arcane.iris.modules.terrain.LayerNoise; +import art.arcane.iris.modules.terrain.PaletteExplosion; +import art.arcane.iris.builtin.terrain.PaletteLayer; +import art.arcane.iris.modules.terrain.ResolvedLayer; +import art.arcane.iris.engine.decorator.BiomeDecorators; +import art.arcane.iris.engine.decorator.DecoratedBiome; +import art.arcane.iris.engine.decorator.DecorationScene; +import art.arcane.iris.engine.decorator.FloatingDecorator; +import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; +import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; +import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; +import art.arcane.iris.engine.object.terrain.floating.FloatingWorld; +import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.hunk.Hunk; +import com.volmit.mantle.Mantle; +import com.volmit.resource.ResourceId; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.BiomeKind; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; + +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * Fills and decorates the floating islands of the dimension's floating child biomes for {@link FloatingModule}: + * the islands' solids (top layers, bottom palette, sea surface) and, later, the decoration on their tops. One + * per world, holding the islands' random. + */ +final class FloatingIslands { + private static final long ISLAND_RANDOM_SALT = 0x7EB0A73F1DCE514DL; + private static final int BOTTOM_PALETTE_SALT = 0xB0770B; + private static final int LAYER_RANDOM_SALT = 0x7A4E; + private static final int FIRST_LAYER_GENERATOR_SEED = 7235; + private static final int MIN_PALETTE_DEPTH = 4; + private static final int CHUNK_WIDTH = 16; + private static final BlockState BARRIER = new BlockState("minecraft:barrier"); + private static final BlockState FALLBACK_SOLID = new BlockState("minecraft:stone"); + private static final String DEFAULT_FLUID = "minecraft:water"; + private static final Runnable NOOP_DECORATION_MISS = () -> { + }; + + private final FloatingWorld world; + private final RNG rng; + private final BiomeLayers biomeLayers; + private final ModuleLog log; + + FloatingIslands(PackWorld world, ModuleLog log) { + this.world = FloatingWorld.of(world); + this.rng = new RNG(world.seed(IrisSeedPurposes.TERRAIN) ^ ISLAND_RANDOM_SALT); + this.biomeLayers = BiomeLayers.of(world); + this.log = log; + } + + /** The islands of {@code world}. */ + static FloatingIslands of(PackWorld world, ModuleLog log) { + return world.state(FloatingIslands.class, generating -> new FloatingIslands(generating, log)); + } + + /** Fills the islands' solids into the chunk of {@code context}. */ + void fillSolids(ChunkStageContext context) { + Chunk chunk = new Chunk(context); + FloatingIslandSample.clearChunkMemo(); + + for (int xf = 0; xf < CHUNK_WIDTH; xf++) { + for (int zf = 0; zf < CHUNK_WIDTH; zf++) { + fillColumn(chunk, xf, zf); + } + } + } + + private void fillColumn(Chunk chunk, int xf, int zf) { + int wx = chunk.originX + xf; + int wz = chunk.originZ + zf; + ResourceId parent = chunk.boundarySampler.parent(wx, wz); + if (parent == null || world.declaredBy(parent).isEmpty()) { + return; + } + FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunk.height, world, chunk.boundarySampler, log); + if (sample == null) { + return; + } + + long colSeed = FloatingIslandSample.columnSeed(world.baseSeed(), wx, wz); + int paletteDepth = Math.max(MIN_PALETTE_DEPTH, sample.solidCount + MIN_PALETTE_DEPTH); + Map paletteContexts = new IdentityHashMap<>(); + Map topDepthByEntry = new IdentityHashMap<>(); + int[] bottomDepths = bottomDepths(sample, chunk.height); + for (int k = sample.topIdx; k >= 0; k--) { + if (!sample.solidMask[k]) { + continue; + } + int y = sample.islandBaseY + k; + if (y < 0 || y >= chunk.height) { + continue; + } + ResolvedFloatingChild entry = sample.entryAt(k); + PaletteContext paletteContext = paletteContexts.computeIfAbsent(entry, + ignored -> createPaletteContext(chunk, parent, entry, wx, wz, colSeed, paletteDepth)); + int depth = topDepthByEntry.getOrDefault(entry, 0); + int bottomDepth = bottomDepths[k] < 0 ? depth : bottomDepths[k]; + BlockState block = selectPaletteBlock(entry, paletteContext.topBlocks(), paletteContext.bottomBlocks(), depth, bottomDepth); + if (block != null) { + chunk.output.set(xf, y, zf, block); + } + topDepthByEntry.put(entry, depth + 1); + } + + fillLocalFluid(chunk, sample, xf, zf); + paintSkyBiomes(chunk, parent, wx, wz, sample); + } + + private void fillLocalFluid(Chunk chunk, FloatingIslandSample sample, int xf, int zf) { + int localFluidHeight = sample.entry.settings().localFluidHeight().orElse(0); + if (localFluidHeight <= 0) { + return; + } + BlockState fluid = fluidOf(chunk.blocks, sample.entry.settings().fluidBlock()); + int fluidCap = Math.min(sample.thickness - 1, localFluidHeight); + for (int k = 1; k <= fluidCap; k++) { + if (sample.solidMask[k]) { + continue; + } + int y = sample.islandBaseY + k; + if (y < 0 || y >= chunk.height) { + continue; + } + if (hasSolidBelow(sample, k)) { + chunk.output.set(xf, y, zf, fluid); + } + } + } + + private static BlockState fluidOf(BlockRegistry blocks, String key) { + return blocks.find(key).or(() -> blocks.find(DEFAULT_FLUID)).orElseThrow(); + } + + private static boolean hasSolidBelow(FloatingIslandSample sample, int k) { + for (int kb = k - 1; kb >= 0; kb--) { + if (sample.solidMask[kb]) { + return true; + } + } + return false; + } + + /** Decorates the tops of the islands in the chunk of {@code context}. */ + void decorateColumns(ChunkStageContext context) { + Chunk chunk = new Chunk(context); + DecorationScene scene = DecorationScene.of(context); + + for (int xf = 0; xf < CHUNK_WIDTH; xf++) { + for (int zf = 0; zf < CHUNK_WIDTH; zf++) { + decorateColumn(chunk, scene, xf, zf); + } + } + } + + private void decorateColumn(Chunk chunk, DecorationScene scene, int xf, int zf) { + int wx = chunk.originX + xf; + int wz = chunk.originZ + zf; + ResourceId parent = chunk.boundarySampler.parent(wx, wz); + if (parent == null || world.declaredBy(parent).isEmpty()) { + return; + } + FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunk.height, world, chunk.boundarySampler, log); + if (sample == null) { + return; + } + ResolvedFloatingChild entry = sample.entry; + ResourceId target = entry.realBiome(parent); + if (!entry.settings().inheritDecorators() || target == null) { + return; + } + + DecoratedBiome decorated = decoratedBiome(chunk.settings, target); + decorateTop(chunk, scene, sample, decorated, xf, zf, wx, wz); + decorateLocalFluid(chunk, scene, sample, decorated, xf, zf, wx, wz); + } + + private void decorateTop(Chunk chunk, DecorationScene scene, FloatingIslandSample sample, DecoratedBiome decorated, + int xf, int zf, int wx, int wz) { + int topY = sample.topY(); + if (topY + 1 >= chunk.height) { + return; + } + BlockState above = chunk.output.get(xf, topY + 1, zf); + if (above != null && !scene.isAir(above)) { + return; + } + int max = Math.max(1, chunk.height - topY); + try { + RNG colRng = rng.nextParallelRNG((int) FloatingIslandSample.columnSeed(world.baseSeed(), wx, wz)); + FloatingDecorator.decorateColumn(scene, decorated, DecorationPart.NONE, xf, zf, wx, wz, topY, max, colRng, NOOP_DECORATION_MISS); + } catch (Throwable e) { + log.error("Failed to decorate the top of a floating island", e); + } + } + + private void decorateLocalFluid(Chunk chunk, DecorationScene scene, FloatingIslandSample sample, DecoratedBiome decorated, + int xf, int zf, int wx, int wz) { + int localFluidHeight = sample.entry.settings().localFluidHeight().orElse(0); + if (localFluidHeight <= 0) { + return; + } + int fluidCap = Math.min(sample.thickness - 1, localFluidHeight); + int fluidTopY = -1; + for (int k = 1; k <= fluidCap; k++) { + if (sample.solidMask[k]) { + continue; + } + int y = sample.islandBaseY + k; + if (y < 0 || y >= chunk.height) { + continue; + } + if (hasSolidBelow(sample, k) && y > fluidTopY) { + fluidTopY = y; + } + } + if (fluidTopY <= 0 || fluidTopY + 1 >= chunk.height) { + return; + } + BlockState above = chunk.output.get(xf, fluidTopY + 1, zf); + if (above != null && !scene.isAir(above)) { + return; + } + try { + new IrisSeaSurfaceDecorator(scene).decorate(xf, zf, wx, wx + 1, wx - 1, wz, wz + 1, wz - 1, decorated, fluidTopY, chunk.height); + } catch (Throwable e) { + log.error("Failed to decorate the sea surface of a floating island", e); + } + } + + /** The decorators' view of the island's biome, which always decorates as land. */ + private static DecoratedBiome decoratedBiome(FeatureSettings settings, ResourceId biome) { + return new DecoratedBiome(BiomeDecorators.biomeKey(biome), settings.declaredBy(biome, DecorantSettings.class).orElse(null), BiomeKind.LAND); + } + + private PaletteContext createPaletteContext(Chunk chunk, ResourceId parent, ResolvedFloatingChild entry, int wx, int wz, long colSeed, + int paletteDepth) { + ResourceId target = entry == null ? parent : entry.realBiome(parent); + int entrySeed = entry == null ? 0 : entry.settings().biome().hashCode(); + RNG layerRng = rng.nextParallelRNG((int) (colSeed ^ LAYER_RANDOM_SALT ^ entrySeed)); + KList topBlocks = target == null ? null : surfaceLayers(chunk, target, wx, wz, layerRng, paletteDepth); + if (topBlocks == null || topBlocks.isEmpty()) { + topBlocks = surfaceLayers(chunk, parent, wx, wz, layerRng, paletteDepth); + } + List bottomBlocks = generateBottomPaletteLayers(chunk, entry, wx, wz, layerRng, paletteDepth); + return new PaletteContext(topBlocks, bottomBlocks); + } + + private KList surfaceLayers(Chunk chunk, ResourceId biome, int wx, int wz, RNG layerRng, int paletteDepth) { + return biomeLayers.generateLayers(biomeLayers.biome(biome, chunk.settings), chunk.explosion, wx, wz, layerRng, paletteDepth, + paletteDepth, chunk.slope); + } + + private List generateBottomPaletteLayers(Chunk chunk, ResolvedFloatingChild entry, double wx, double wz, RNG random, + int paletteDepth) { + if (entry == null || entry.settings().bottomPaletteMode() != FloatingBottomPaletteMode.CUSTOM || entry.settings().bottomPalette().isEmpty()) { + return null; + } + return generatePaletteLayers(chunk, entry.settings().bottomPalette(), wx, wz, random.nextParallelRNG(BOTTOM_PALETTE_SALT), paletteDepth); + } + + private List generatePaletteLayers(Chunk chunk, List layers, double wx, double wz, RNG random, int maxDepth) { + List generated = new ArrayList<>(); + if (layers.isEmpty() || maxDepth <= 0) { + return generated; + } + + int generatorSeed = FIRST_LAYER_GENERATOR_SEED; + for (int i = 0; i < layers.size(); i++) { + ResolvedLayer layer = biomeLayers.resolve(layers.get(i)); + LayerNoise heightGenerator = layer.heightNoise(random.nextParallelRNG((generatorSeed++) * generatorSeed * generatorSeed * generatorSeed)); + if (heightGenerator == null) { + continue; + } + double layerDepth = heightGenerator.fit(layer.minHeight(), layer.maxHeight(), wx / layer.zoom(), wz / layer.zoom()); + SlopeClip slopeClip = layer.slopeCondition(); + + if (slopeClip != null && !slopeClip.isDefault() && !slopeClip.isValid(chunk.slope.at(wx, wz))) { + layerDepth = 0; + } + + if (layerDepth <= 0) { + continue; + } + + for (int j = 0; j < layerDepth; j++) { + if (generated.size() >= maxDepth) { + break; + } + + try { + generated.add(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.zoom(), j, (wz - j) / layer.zoom())); + } catch (Throwable e) { + log.error("Failed to pick a block of a floating island's palette", e); + } + } + + if (generated.size() >= maxDepth) { + break; + } + + if (chunk.explosion.exploded()) { + for (int j = 0; j < chunk.explosion.size(); j++) { + generated.add(BARRIER); + + if (generated.size() >= maxDepth) { + break; + } + } + } + } + + return generated; + } + + private static int[] bottomDepths(FloatingIslandSample sample, int chunkHeight) { + int[] bottomDepths = new int[sample.solidMask.length]; + java.util.Arrays.fill(bottomDepths, -1); + + Map depthByEntry = new IdentityHashMap<>(); + int max = Math.min(sample.topIdx, sample.solidMask.length - 1); + for (int k = 0; k <= max; k++) { + if (!sample.solidMask[k]) { + continue; + } + int y = sample.islandBaseY + k; + if (y < 0 || y >= chunkHeight) { + continue; + } + ResolvedFloatingChild entry = sample.entryAt(k); + int depth = depthByEntry.getOrDefault(entry, 0); + bottomDepths[k] = depth; + depthByEntry.put(entry, depth + 1); + } + + return bottomDepths; + } + + private static BlockState selectPaletteBlock(ResolvedFloatingChild entry, List topBlocks, List bottomBlocks, + int topDepth, int bottomDepth) { + FloatingBottomPaletteMode mode = entry == null ? FloatingBottomPaletteMode.DEPTH : entry.settings().bottomPaletteMode(); + if (mode == FloatingBottomPaletteMode.MIRROR_TOP) { + return paletteBlock(topBlocks, Math.min(topDepth, bottomDepth)); + } + if (mode == FloatingBottomPaletteMode.CUSTOM && bottomDepth < topDepth) { + if (bottomBlocks != null && !bottomBlocks.isEmpty()) { + return paletteBlock(bottomBlocks, bottomDepth); + } + return paletteBlock(topBlocks, bottomDepth); + } + return paletteBlock(topBlocks, topDepth); + } + + private static BlockState paletteBlock(List blocks, int depth) { + if (blocks == null || blocks.isEmpty()) { + return FALLBACK_SOLID; + } + BlockState block = depth >= 0 && depth < blocks.size() ? blocks.get(depth) : blocks.getLast(); + return block == null ? FALLBACK_SOLID : block; + } + + /** Paints, for each child the column's island is made of, its biome's sky biome into the child's solid blocks. */ + private void paintSkyBiomes(Chunk chunk, ResourceId parent, int wx, int wz, FloatingIslandSample sample) { + try { + Map> solidYsByEntry = new IdentityHashMap<>(); + for (int k = 0; k <= sample.topIdx; k++) { + if (!sample.solidMask[k]) { + continue; + } + int y = sample.islandBaseY + k; + if (y < 0 || y >= chunk.height) { + continue; + } + solidYsByEntry.computeIfAbsent(sample.entryAt(k), ignored -> new ArrayList<>()).add(y); + } + for (Map.Entry> solid : solidYsByEntry.entrySet()) { + ResolvedFloatingChild entry = solid.getKey(); + ResourceId target = entry == null ? parent : entry.realBiome(parent); + if (target == null) { + continue; + } + Optional skyBiome = chunk.terrain.skyBiome(target, wx, wz); + if (skyBiome.isEmpty()) { + continue; + } + for (int y : solid.getValue()) { + chunk.mantle.setPlatformBiome(wx, y, wz, skyBiome.get()); + } + } + } catch (Throwable e) { + log.error("Failed to write the sky biomes of a floating island", e); + } + } + + private record PaletteContext(List topBlocks, List bottomBlocks) { + } + + /** What one chunk's columns share: its views of the blocks, terrain and settings, and its island fields. */ + private final class Chunk { + final int originX; + final int originZ; + final Hunk output; + final int height; + final BlockRegistry blocks; + final FeatureSettings settings; + final PaletteExplosion explosion; + final ColumnSlope slope; + final FloatingIslandBoundarySampler boundarySampler; + final TerrainSampler terrain; + final Mantle mantle; + + Chunk(ChunkStageContext context) { + this.originX = context.originX(); + this.originZ = context.originZ(); + this.output = context.blocks(); + this.height = output.height(); + this.blocks = context.world().resources().blocks(); + this.settings = context.settings(); + this.explosion = PaletteExplosion.of(settings, context.centreX(), context.centreZ()); + this.terrain = context.terrain(); + this.mantle = context.mantle(); + this.slope = (x, z) -> terrain.column((int) x, (int) z).slope(); + this.boundarySampler = new FloatingIslandBoundarySampler(world::surfaceBiome); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java b/module/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java new file mode 100644 index 000000000..2e4eea9cf --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java @@ -0,0 +1,80 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.modules.floating.FloatingChildSettings; +import art.arcane.iris.modules.floating.MergeFloatingChildrenSettings; +import art.arcane.iris.engine.mantle.components.FloatingObjectPlacing; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleLog; +import com.volmit.ModuleSetup; +import com.volmit.config.PackSettings; +import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.MantleStageContext; + +/** + * Module {@code iris:floating}: the islands of floating child biomes, their objects in the mantle after the + * dimension's other objects, their solids after smoothing and their decoration after the chunk's own. The + * mantle stage's work is done by {@link FloatingObjectPlacing}, whose reach is the pack's largest floating object + * placement. The chunk stages' work is done by {@link FloatingIslands}. + */ +public final class FloatingModule implements IrisModule { + private static final String VERSION = "built-in"; + + private ModuleLog log; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:floating", "Floating islands", VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + log = setup.log(); + var registry = setup.registry(); + registry.registerSettings(FloatingChildSettings.class); + registry.registerSettings(MergeFloatingChildrenSettings.class); + + var graph = setup.stages(); + graph.define(IrisStages.Floating.OBJECTS).softAfter(IrisStages.Objects.PLACE).reach(this::objectReach) + .run(FloatingModule::objects); + // Ordering only: iris:post ships in the built-ins jar, which a pack may not have. + graph.define(IrisStages.Floating.SOLIDS).softAfter(IrisStages.Post.SMOOTH).run(FloatingModule::solids); + // Ordering only: iris:decorant ships in the built-ins jar, which a pack may not have. + graph.define(IrisStages.Floating.DECORATE).softAfter(IrisStages.Decorant.DECORATE).run(FloatingModule::decorate); + } + + private static void objects(MantleStageContext context) { + FloatingObjectPlacing.of(context.world(), context.log()).place(context); + } + + private int objectReach(PackSettings settings) { + return FloatingObjectPlacing.reach(settings, log); + } + + private static void solids(ChunkStageContext context) { + FloatingIslands.of(context.world(), context.log()).fillSolids(context); + } + + private static void decorate(ChunkStageContext context) { + FloatingIslands.of(context.world(), context.log()).decorateColumns(context); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java b/module/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java new file mode 100644 index 000000000..dc55fbd55 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java @@ -0,0 +1,58 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import com.volmit.resource.ResourceId; + +import java.util.HashMap; +import java.util.Map; + +final class IrisCarveScratch { + final CarveColumnMask[] columnMasks = new CarveColumnMask[256]; + final CarveColumnMask[] boundaryMasks = new CarveColumnMask[256]; + final int[] surfaceHeights = new int[256]; + final CarveWallBuffer walls = new CarveWallBuffer(512); + final Map customBiomeCache = new HashMap<>(); + int[] upperSurfaceHeights; + boolean customCaveBiomePresent; + + IrisCarveScratch() { + for (int index = 0; index < columnMasks.length; index++) { + columnMasks[index] = new CarveColumnMask(); + boundaryMasks[index] = new CarveColumnMask(); + } + } + + int[] getOrCreateUpperSurfaceHeights() { + if (upperSurfaceHeights == null) { + upperSurfaceHeights = new int[256]; + } + return upperSurfaceHeights; + } + + void reset() { + for (int index = 0; index < columnMasks.length; index++) { + columnMasks[index].clear(); + boundaryMasks[index].clear(); + } + walls.clear(); + customBiomeCache.clear(); + customCaveBiomePresent = false; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java b/module/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java new file mode 100644 index 000000000..7cdfd7591 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java @@ -0,0 +1,84 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.IrisStages; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.block.BlockState; +import com.volmit.hunk.Hunk; +import com.volmit.geometry.BlockBox; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.TerrainSampler; + +/** + * Module {@code iris:matter}: copies the blocks the mantle planned for the chunk, its objects and structures, + * into it (a dimension with {@code useMantle} off plans none). Where an upper dimension sits above, blocks at or + * above where it begins are left out. It orders itself after deposits without requiring them, since deposits run + * only where a level declares some. + */ +public final class MatterModule implements IrisModule { + private static final String VERSION = "built-in"; + private static final int CHUNK_WIDTH = 16; + private static final int NO_LIMIT = Integer.MAX_VALUE; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:matter", "Mantle blocks", VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + setup.stages().define(IrisStages.Matter.INSERT) + .requires(IrisStages.Floating.SOLIDS) + .softAfter(IrisStages.Deposit.ORES) + .run(MatterModule::insert); + } + + private static void insert(ChunkStageContext context) { + int originX = context.originX(); + int originZ = context.originZ(); + Hunk blocks = context.blocks(); + int[] limits = upperLimits(context.terrain(), originX, originZ); + BlockBox chunk = new BlockBox(originX, 0, originZ, originX + CHUNK_WIDTH, blocks.height(), originZ + CHUNK_WIDTH); + context.mantle().blocks().visit(chunk, (x, y, z, block) -> { + int localX = x - originX; + int localZ = z - originZ; + if (y < limits[column(localX, localZ)]) { + blocks.set(localX, y, localZ, block); + } + }); + } + + /** Per column, the height from which the upper dimension takes over, or no limit. */ + static int[] upperLimits(TerrainSampler terrain, int originX, int originZ) { + int[] limits = new int[CHUNK_WIDTH * CHUNK_WIDTH]; + for (int localX = 0; localX < CHUNK_WIDTH; localX++) { + for (int localZ = 0; localZ < CHUNK_WIDTH; localZ++) { + limits[column(localX, localZ)] = terrain.upperDimensionY(originX + localX, originZ + localZ).orElse(NO_LIMIT); + } + } + return limits; + } + + private static int column(int localX, int localZ) { + return localX * CHUNK_WIDTH + localZ; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java b/module/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java new file mode 100644 index 000000000..0c57ee111 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java @@ -0,0 +1,186 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.modules.terrain.HideOresSettings; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.hunk.Hunk; +import com.volmit.resource.ResourceId; +import com.volmit.stage.ChunkStageContext; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; + +/** + * Module {@code iris:perfection}: turns ores back into the stone around them when the + * dimension hides its ores, then removes decorations whose block below cannot hold them, again until none + * is left, since removing one can strand the one above. + */ +public final class PerfectionModule implements IrisModule { + private static final String VERSION = "built-in"; + private static final String HALF = "half"; + private static final BlockState AIR = new BlockState("minecraft:air"); + private static final Map ORE_BASES = oreBases(); + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:perfection", "Perfection", VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + setup.stages().define(IrisStages.Perfection.SURFACE).requires(IrisStages.Floating.DECORATE).run(PerfectionModule::perfect); + } + + private static void perfect(ChunkStageContext context) { + Hunk blocks = context.blocks(); + if (hidesOres(context)) { + hideOres(blocks, new IdentityHashMap<>()); + } + Surfaces surfaces = new Surfaces(blocks, context.world().resources().blocks(), new IdentityHashMap<>()); + boolean removed; + do { + removed = surfaces.removeUnsupportedDecorants(); + } while (removed); + } + + /** The dimension's {@code hideOresForHiddenOre}, which every column of the chunk shares. */ + private static boolean hidesOres(ChunkStageContext context) { + return context.settings().at(HideOresSettings.class, context.centreX(), context.centreZ()).dimension() + .map(HideOresSettings::hide).orElse(false); + } + + /** {@code hidden} remembers per state instance what it is hidden as, itself for a block that is no ore. */ + private static void hideOres(Hunk blocks, Map hidden) { + for (int x = 0; x < blocks.width(); x++) { + for (int z = 0; z < blocks.depth(); z++) { + for (int y = blocks.height() - 1; y >= 0; y--) { + BlockState block = blocks.get(x, y, z); + BlockState shown = hidden.computeIfAbsent(block, state -> ORE_BASES.getOrDefault(state.material(), state)); + if (shown != block) { + blocks.set(x, y, z, shown); + } + } + } + } + } + + /** + * The decorations of one chunk and the ground they stand on. Finding the surfaces asks about every block of the chunk, + * which holds few distinct states, so whether a state is solid is asked once per state instance. + */ + private record Surfaces(Hunk blocks, BlockRegistry registry, Map solidStates) { + /** One pass over every column; whether it removed anything. */ + boolean removeUnsupportedDecorants() { + boolean removed = false; + for (int x = 0; x < blocks.width(); x++) { + for (int z = 0; z < blocks.depth(); z++) { + for (int surface : surfaces(x, z)) { + removed |= removeIfUnsupported(x, surface, z); + } + } + } + return removed; + } + + /** The topmost solid block of a column and each solid block with open space above it below that. */ + private List surfaces(int x, int z) { + List surfaces = new ArrayList<>(); + int top = topSolid(x, z); + surfaces.add(top); + boolean inside = true; + for (int y = top; y >= 0; y--) { + boolean solid = isSolid(blocks.get(x, y, z)); + if (solid != inside) { + inside = solid; + if (inside) { + surfaces.add(y); + } + } + } + return surfaces; + } + + private boolean removeIfUnsupported(int x, int y, int z) { + BlockState tip = blocks.get(x, y, z); + if (!registry.hasTrait(tip, BlockTrait.DECORATION)) { + return false; + } + BlockState below = blockAt(x, y - 1, z); + if (below == null || !registry.canPlaceOn(tip, below)) { + blocks.set(x, y, z, AIR); + return true; + } + if (!below.properties().containsKey(HALF)) { + return false; + } + BlockState belowBelow = blockAt(x, y - 2, z); + if (belowBelow != null && registry.canPlaceOn(below, belowBelow)) { + return false; + } + blocks.set(x, y, z, AIR); + blocks.set(x, y - 1, z, AIR); + return true; + } + + private int topSolid(int x, int z) { + for (int y = blocks.height() - 1; y >= 0; y--) { + if (isSolid(blocks.get(x, y, z))) { + return y; + } + } + return 0; + } + + private boolean isSolid(BlockState block) { + return solidStates.computeIfAbsent(block, state -> !(registry.hasTrait(state, BlockTrait.AIR) || registry.hasTrait(state, BlockTrait.FLUID))); + } + + /** The block at {@code y}, or null below the chunk's bottom. */ + private BlockState blockAt(int x, int y, int z) { + return y < 0 ? null : blocks.get(x, y, z); + } + } + + private static Map oreBases() { + Map bases = new HashMap<>(); + BlockState stone = new BlockState("minecraft:stone"); + BlockState deepslate = new BlockState("minecraft:deepslate"); + BlockState netherrack = new BlockState("minecraft:netherrack"); + BlockState blackstone = new BlockState("minecraft:blackstone"); + for (String ore : List.of("coal", "copper", "iron", "gold", "redstone", "lapis", "diamond", "emerald")) { + bases.put(ResourceId.parse("minecraft:" + ore + "_ore"), stone); + bases.put(ResourceId.parse("minecraft:deepslate_" + ore + "_ore"), deepslate); + } + bases.put(ResourceId.parse("minecraft:nether_gold_ore"), netherrack); + bases.put(ResourceId.parse("minecraft:nether_quartz_ore"), netherrack); + bases.put(ResourceId.parse("minecraft:ancient_debris"), netherrack); + bases.put(ResourceId.parse("minecraft:gilded_blackstone"), blackstone); + return bases; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/PostModule.java b/module/src/main/java/art/arcane/iris/engine/modifier/PostModule.java new file mode 100644 index 000000000..18b3dea79 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/PostModule.java @@ -0,0 +1,47 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.modules.post.PostProcessingSettings; +import art.arcane.iris.modules.post.PostProcessingSlabsSettings; +import art.arcane.iris.modules.post.PostProcessingWallsSettings; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; + +/** Module {@code iris:post}: smooths the carved surface with {@link SurfaceSmoothing}. */ +public final class PostModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:post", "Post-processing", VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + var registry = setup.registry(); + registry.registerSettings(PostProcessingSettings.class); + registry.registerSettings(PostProcessingSlabsSettings.class); + registry.registerSettings(PostProcessingWallsSettings.class); + // Ordering only: iris:carve ships in the built-ins jar, which a pack may not have. + setup.stages().define(IrisStages.Post.SMOOTH).softAfter(IrisStages.Carve.APPLY).run(SurfaceSmoothing::smooth); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java b/module/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java new file mode 100644 index 000000000..79725a107 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java @@ -0,0 +1,402 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.modules.deposit.DepositBiomeScope; +import art.arcane.iris.modules.deposit.DepositGenerator; +import art.arcane.iris.modules.deposit.DepositShape; +import art.arcane.volmlib.util.collection.KSet; +import art.arcane.volmlib.util.math.BlockPosition; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.resource.ResourceId; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +/** + * One {@link DepositGenerator} made ready for one world: its palette resolved to blocks, whether it is an ore deposit, the blocks + * it may replace, and the clump shapes it places, built once per size. What the settings describe stays in the settings; + * everything that needs the pack or the world seed is here. + */ +final class ResolvedDeposit { + private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L; + private static final long FNV_PRIME = 0x100000001b3L; + private static final int MAX_CLUMP_DIMENSION = 11; + private static final int MAX_DEPOSIT_SIZE = 8192; + private static final int VARIANT_SEED_STEP = 2349; + private static final int VARIANT_SEED_OFFSET = 3598; + private static final int MAX_SCATTER_MAGNITUDE = 7; + private static final String MINECRAFT_NAMESPACE = "minecraft:"; + + private final DepositGenerator generator; + private final long depositSeed; + private final List palette; + private final boolean ore; + private final Set replaceableMaterials; + private final Map> clumps = new ConcurrentHashMap<>(); + + /** @param registry the pack's blocks, which resolve the generator's palette and the blocks it may replace */ + ResolvedDeposit(DepositGenerator generator, long depositSeed, BlockRegistry registry) { + this.generator = generator; + this.depositSeed = depositSeed; + this.palette = generator.palette().stream().map(registry::resolve).toList(); + this.ore = palette.stream().anyMatch(block -> registry.hasTrait(block, BlockTrait.ORE)); + this.replaceableMaterials = replaceableMaterials(registry, generator.replaceableBlocks()); + } + + DepositGenerator generator() { + return generator; + } + + /** Whether any block of the palette is an ore: ore deposits follow the cave biome's ore tuning. */ + boolean isOre() { + return ore; + } + + /** Whether the deposit may replace {@code state}: any block when it names none, otherwise only the named ones. */ + boolean canReplace(BlockState state) { + return generator.replaceableBlocks().isEmpty() || replaceableMaterials.contains(state.material()); + } + + /** + * Whether the biome the generator's scope picks passes its include and exclude filters. The biomes are asked for only when + * the generator has a filter, and a biome that is none (a dimension without cave biomes) matches no key. + */ + boolean matchesBiome(Supplier surfaceBiome, Supplier caveBiome) { + if (generator.includedBiomes().isEmpty() && generator.excludedBiomes().isEmpty()) { + return true; + } + BiomeIdentity selected = (generator.biomeScope() == DepositBiomeScope.SURFACE ? surfaceBiome : caveBiome).get(); + if (!generator.includedBiomes().isEmpty() && !matchesAnyBiome(selected, generator.includedBiomes())) { + return false; + } + return generator.excludedBiomes().isEmpty() || !matchesAnyBiome(selected, generator.excludedBiomes()); + } + + /** One clump to place, picked with {@code rng}. */ + DepositClump clump(RNG rng) { + return clump(rng, generator.minSize(), generator.maxSize(), 0L); + } + + /** One clump to place with every size scaled by {@code sizeMultiplier}, as a biome's ore size tuning asks. */ + DepositClump clump(RNG rng, double sizeMultiplier) { + if (sizeMultiplier == 1D) { + return clump(rng); + } + int minSize = scaledDepositSize(generator.minSize(), sizeMultiplier); + int maxSize = scaledDepositSize(generator.maxSize(), sizeMultiplier); + long sizeSeed = ((long) minSize << 32) ^ (maxSize & 0xffffffffL); + return clump(rng, minSize, maxSize, sizeSeed); + } + + private DepositClump clump(RNG rng, int minSize, int maxSize, long sizeSeed) { + if (generator.shape() != DepositShape.IRIS) { + return configuredClump(rng, minSize, maxSize); + } + List variants = clumps.computeIfAbsent(new ClumpSizes(minSize, maxSize), sizes -> { + RNG variantRng = new RNG(depositSeed + stableClumpSalt() + sizeSeed); + List built = new ArrayList<>(); + for (int i = 0; i < generator.varience(); i++) { + built.add(irisClump(variantRng.nextParallelRNG(VARIANT_SEED_STEP * i + VARIANT_SEED_OFFSET), sizes.minSize(), sizes.maxSize())); + } + return List.copyOf(built); + }); + return variants.get(rng.i(0, variants.size())); + } + + static int scaledDepositSize(int size, double multiplier) { + return Math.max(0, Math.min(MAX_DEPOSIT_SIZE, (int) Math.round(size * multiplier))); + } + + /** A hash of everything the generator describes and its resolved palette, so equal generators share clump shapes. */ + long stableClumpSalt() { + long hash = FNV_OFFSET_BASIS; + hash = mix(hash, generator.minHeight()); + hash = mix(hash, generator.maxHeight()); + hash = mixEnum(hash, generator.heightDistribution()); + hash = mixEnum(hash, generator.placementScope()); + hash = mix(hash, generator.surfaceClearance()); + hash = mix(hash, generator.minSize()); + hash = mix(hash, generator.maxSize()); + hash = mixEnum(hash, generator.shape()); + hash = mix(hash, generator.maxPerChunk()); + hash = mix(hash, generator.minPerChunk()); + hash = mix(hash, Double.doubleToLongBits(generator.spawnChance())); + hash = mix(hash, Double.doubleToLongBits(generator.perClumpSpawnChance())); + hash = mix(hash, Double.doubleToLongBits(generator.discardChanceOnAirExposure())); + hash = mix(hash, palette.size()); + for (BlockState block : palette) { + hash = mixString(hash, block == null ? null : block.key()); + } + hash = mix(hash, generator.varience()); + hash = mixStrings(hash, generator.replaceableBlocks()); + hash = mixEnum(hash, generator.biomeScope()); + hash = mixStrings(hash, generator.includedBiomes()); + hash = mixStrings(hash, generator.excludedBiomes()); + return mix(hash, generator.replaceBedrock() ? 1L : 0L); + } + + private static long mix(long hash, long value) { + return (hash ^ value) * FNV_PRIME; + } + + private static long mixEnum(long hash, Enum value) { + return mixString(hash, value == null ? null : value.name()); + } + + private static long mixString(long hash, String value) { + if (value == null) { + return mix(hash, -1L); + } + long mixed = mix(hash, value.length()); + for (int i = 0; i < value.length(); i++) { + mixed = mix(mixed, value.charAt(i)); + } + return mixed; + } + + private static long mixStrings(long hash, List values) { + long mixed = mix(hash, values.size()); + for (String value : values) { + mixed = mixString(mixed, value); + } + return mixed; + } + + private DepositClump configuredClump(RNG rng, int minSize, int maxSize) { + int size = rng.i(minSize, maxSize + 1); + return switch (generator.shape()) { + case VANILLA_ELLIPSOID -> vanillaEllipsoid(rng, size); + case VANILLA_SCATTERED -> vanillaScattered(rng, size); + case IRIS -> irisClump(rng, minSize, maxSize); + }; + } + + /** Minecraft's ordinary ore vein: a chain of overlapping ellipsoids whose reach grows with {@code size}. */ + DepositClump vanillaEllipsoid(RNG rng, int size) { + if (size <= 0) { + return new DepositClump(1, 1, 1); + } + + float angle = rng.nextFloat() * (float) Math.PI; + float reach = size / 8F; + double startX = Math.sin(angle) * reach; + double endX = -Math.sin(angle) * reach; + double startZ = Math.cos(angle) * reach; + double endZ = -Math.cos(angle) * reach; + double startY = rng.nextInt(3) - 2; + double endY = rng.nextInt(3) - 2; + double[] nodes = new double[size * 4]; + + for (int i = 0; i < size; i++) { + float progress = (float) i / size; + double radiusNoise = rng.nextDouble() * size / 16D; + nodes[i * 4] = startX + (endX - startX) * progress; + nodes[i * 4 + 1] = startY + (endY - startY) * progress; + nodes[i * 4 + 2] = startZ + (endZ - startZ) * progress; + nodes[i * 4 + 3] = ((Math.sin(Math.PI * progress) + 1D) * radiusNoise + 1D) / 2D; + } + + for (int i = 0; i < size - 1; i++) { + if (nodes[i * 4 + 3] <= 0D) { + continue; + } + for (int j = i + 1; j < size; j++) { + if (nodes[j * 4 + 3] <= 0D) { + continue; + } + double dx = nodes[i * 4] - nodes[j * 4]; + double dy = nodes[i * 4 + 1] - nodes[j * 4 + 1]; + double dz = nodes[i * 4 + 2] - nodes[j * 4 + 2]; + double dr = nodes[i * 4 + 3] - nodes[j * 4 + 3]; + if (dr * dr <= dx * dx + dy * dy + dz * dz) { + continue; + } + if (dr > 0D) { + nodes[j * 4 + 3] = -1D; + } else { + nodes[i * 4 + 3] = -1D; + } + } + } + + KSet cells = new KSet<>(); + for (int i = 0; i < size; i++) { + double radius = nodes[i * 4 + 3]; + if (radius < 0D) { + continue; + } + double centerX = nodes[i * 4]; + double centerY = nodes[i * 4 + 1]; + double centerZ = nodes[i * 4 + 2]; + int minX = (int) Math.floor(centerX - radius); + int maxX = Math.max((int) Math.floor(centerX + radius), minX); + int minY = (int) Math.floor(centerY - radius); + int maxY = Math.max((int) Math.floor(centerY + radius), minY); + int minZ = (int) Math.floor(centerZ - radius); + int maxZ = Math.max((int) Math.floor(centerZ + radius), minZ); + + for (int x = minX; x <= maxX; x++) { + double nx = (x + 0.5D - centerX) / radius; + if (nx * nx >= 1D) { + continue; + } + for (int y = minY; y <= maxY; y++) { + double ny = (y + 0.5D - centerY) / radius; + if (nx * nx + ny * ny >= 1D) { + continue; + } + for (int z = minZ; z <= maxZ; z++) { + double nz = (z + 0.5D - centerZ) / radius; + if (nx * nx + ny * ny + nz * nz < 1D) { + cells.add(new BlockPosition(x, y, z)); + } + } + } + } + } + + return clumpFromCells(cells, rng); + } + + /** Minecraft's scattered ore: up to {@code size} candidate offsets, the later ones further from the centre. */ + DepositClump vanillaScattered(RNG rng, int size) { + KSet cells = new KSet<>(); + int candidates = rng.nextInt(Math.max(0, size) + 1); + for (int i = 0; i < candidates; i++) { + int magnitude = Math.min(i, MAX_SCATTER_MAGNITUDE); + cells.add(new BlockPosition( + Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude), + Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude), + Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude))); + } + return clumpFromCells(cells, rng); + } + + private DepositClump clumpFromCells(KSet cells, RNG rng) { + if (cells.isEmpty()) { + return new DepositClump(1, 1, 1); + } + + int minX = Integer.MAX_VALUE; + int minY = Integer.MAX_VALUE; + int minZ = Integer.MAX_VALUE; + int maxX = Integer.MIN_VALUE; + int maxY = Integer.MIN_VALUE; + int maxZ = Integer.MIN_VALUE; + for (BlockPosition cell : cells) { + minX = Math.min(minX, cell.getX()); + minY = Math.min(minY, cell.getY()); + minZ = Math.min(minZ, cell.getZ()); + maxX = Math.max(maxX, cell.getX()); + maxY = Math.max(maxY, cell.getY()); + maxZ = Math.max(maxZ, cell.getZ()); + } + + int extentX = Math.max(Math.abs(minX), Math.abs(maxX)); + int extentY = Math.max(Math.abs(minY), Math.abs(maxY)); + int extentZ = Math.max(Math.abs(minZ), Math.abs(maxZ)); + DepositClump clump = new DepositClump(extentX * 2 + 1, extentY * 2 + 1, extentZ * 2 + 1); + for (BlockPosition cell : cells) { + clump.setFromCorner(cell.getX() + extentX, cell.getY() + extentY, cell.getZ() + extentZ, nextBlock(rng)); + } + return clump; + } + + /** The traditional Iris clump: a cube just large enough for the block count, filled at random cells. */ + private DepositClump irisClump(RNG rng, int minSize, int maxSize) { + int remaining = rng.i(minSize, maxSize + 1); + if (remaining == 1) { + DepositClump single = new DepositClump(1, 1, 1); + single.setCentre(nextBlock(rng)); + return single; + } + + int dimension = Math.min(MAX_CLUMP_DIMENSION, (int) Math.ceil(Math.cbrt(remaining))); + DepositClump clump = new DepositClump(dimension, dimension, dimension); + if (remaining >= dimension * dimension * dimension) { + fillCube(clump, dimension, rng); + return clump; + } + + KSet filled = new KSet<>(); + while (remaining > 0) { + BlockPosition cell = new BlockPosition(rng.i(0, dimension), rng.i(0, dimension), rng.i(0, dimension)); + if (!filled.add(cell)) { + continue; + } + remaining--; + clump.setFromCorner(cell.getX(), cell.getY(), cell.getZ(), nextBlock(rng)); + } + return clump; + } + + private void fillCube(DepositClump clump, int dimension, RNG rng) { + for (int z = 0; z < dimension; z++) { + for (int y = 0; y < dimension; y++) { + for (int x = 0; x < dimension; x++) { + clump.setFromCorner(x, y, z, nextBlock(rng)); + } + } + } + } + + private BlockState nextBlock(RNG rng) { + return palette.get(rng.i(0, palette.size())); + } + + /** The materials of the blocks the pack names that this platform knows; a block it does not know replaces nothing. */ + private static Set replaceableMaterials(BlockRegistry registry, List keys) { + Set materials = new HashSet<>(); + for (String key : keys) { + registry.find(key).ifPresent(block -> materials.add(block.material())); + } + return materials; + } + + private static boolean matchesAnyBiome(BiomeIdentity biome, List configuredBiomes) { + if (biome == null) { + return false; + } + for (String configured : configuredBiomes) { + String namespaced = configured.contains(":") ? configured : MINECRAFT_NAMESPACE + configured; + if (configured.equals(biome.key()) + || namespaced.equals(biome.platformBiome()) + || namespaced.equals(biome.vanillaBiome())) { + return true; + } + } + return false; + } + + /** The sizes one set of clump variants is built for: the generator's own, or scaled by a biome's ore tuning. */ + record ClumpSizes(int minSize, int maxSize) { + } + + /** What a deposit's biome filter compares: the pack key of a biome, the platform biome it is written as and the one vanilla sees. */ + record BiomeIdentity(String key, String platformBiome, String vanillaBiome) { + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java b/module/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java new file mode 100644 index 000000000..587aac973 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java @@ -0,0 +1,80 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.modules.deposit.DepositVariant; +import art.arcane.volmlib.util.cache.AtomicCache; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.resource.ResourceId; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +/** + * One {@link DepositVariant} made ready: its source and replacement block ids resolved to the platform's blocks, built once on + * first use. A rule whose source or replacement the platform does not know remaps nothing. + */ +final class ResolvedDepositVariant { + private final DepositVariant settings; + private final BlockRegistry registry; + private final ModuleLog log; + private final AtomicCache> remapped = new AtomicCache<>(); + + ResolvedDepositVariant(DepositVariant settings, BlockRegistry registry, ModuleLog log) { + this.settings = settings; + this.registry = registry; + this.log = log; + } + + boolean appliesAt(int worldY) { + return worldY >= settings.minHeight() && worldY <= settings.maxHeight(); + } + + /** The block {@code ore} is rewritten to, or null when the rule does not remap its material. */ + BlockState remapOrNull(BlockState ore) { + if (ore == null || settings.remap().isEmpty()) { + return null; + } + return remapped.aquire(this::resolveRemap).get(ore.material()); + } + + private Map resolveRemap() { + Map resolved = new HashMap<>(); + for (Map.Entry entry : settings.remap().entrySet()) { + Optional source = known(entry.getKey(), false); + Optional target = known(entry.getValue(), true); + if (source.isEmpty() || target.isEmpty()) { + continue; + } + resolved.put(source.get().material(), target.get()); + } + return resolved; + } + + /** The block the platform has under {@code key}; a replacement it lacks is reported once. */ + private Optional known(String key, boolean reportMissing) { + Optional block = registry.find(key); + if (block.isEmpty() && reportMissing) { + log.warnOnce("deposit-variant-block:" + key, "Deposit variant replaces ores with " + key + ", which this server does not have"); + } + return block; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java b/module/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java new file mode 100644 index 000000000..667f4be76 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java @@ -0,0 +1,369 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.modules.post.PostProcessingSlabsSettings; +import art.arcane.iris.modules.post.PostProcessingWallsSettings; +import art.arcane.iris.modules.terrain.LayerBlocks; +import art.arcane.iris.builtin.terrain.PaletteLayer; +import art.arcane.iris.modules.terrain.SlabSettings; +import art.arcane.iris.modules.terrain.WallSettings; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.IrisFeature; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.hunk.Hunk; +import com.volmit.config.FeatureSettings; +import com.volmit.resource.ResourceId; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.TerrainSampler; + +import java.util.List; +import java.util.function.Function; + +/** + * Smooths the carved surface of one chunk for {@link PostModule}: floating nibs, single-block bumps and potholes, + * walls under steep faces, slabs on steps, waterlogging and the foliage that lost its ground. + */ +final class SurfaceSmoothing { + private static final BlockState AIR = new BlockState("minecraft:air"); + private static final ResourceId AIR_ID = AIR.material(); + private static final ResourceId CAVE_AIR_ID = ResourceId.parse("minecraft:cave_air"); + private static final ResourceId WATER_ID = ResourceId.parse("minecraft:water"); + private static final ResourceId SNOW_ID = ResourceId.parse("minecraft:snow"); + private static final ResourceId DEAD_BUSH_ID = ResourceId.parse("minecraft:dead_bush"); + private static final String SLAB_SUFFIX = "_slab"; + private static final String WATERLOGGED = "waterlogged"; + private static final String TRUE = "true"; + /** A biome without a wall or slab picks no block. */ + private static final PaletteLayer NO_LAYER = PaletteLayer.withoutBlocks(); + /** Walls and slabs are picked once per column: the first signature of a layer's noise. */ + private static final int COLUMN_SIGNATURE = 0; + /** The face properties of a connecting block, such as a vine's, each with the neighbour it faces. */ + private static final List FACES = List.of(new Face("north", 0, 0, -1), new Face("east", 1, 0, 0), + new Face("south", 0, 0, 1), new Face("west", -1, 0, 0), new Face("up", 0, 1, 0), new Face("down", 0, -1, 0)); + + private final Hunk blocks; + private final BlockRegistry registry; + private final TerrainSampler terrain; + private final FeatureSettings settings; + private final LayerBlocks layerBlocks; + private final RNG postRandom; + private final int originX; + private final int originZ; + private final int planeWidth; + private final int[] heights; + private final boolean walls; + private final boolean slabs; + private final int fluidHeight; + + private SurfaceSmoothing(ChunkStageContext context) { + this.blocks = context.blocks(); + this.registry = context.world().resources().blocks(); + this.terrain = context.terrain(); + this.settings = context.settings(); + this.layerBlocks = LayerBlocks.of(context.world()); + this.postRandom = new RNG(context.world().seed(IrisSeedPurposes.POST)); + this.originX = context.originX(); + this.originZ = context.originZ(); + this.planeWidth = blocks.width() + 2; + this.heights = heightPlane(); + this.walls = enabled(context, PostProcessingWallsSettings.class, PostProcessingWallsSettings::enabled, PostProcessingWallsSettings.DEFAULT_ENABLED); + this.slabs = enabled(context, PostProcessingSlabsSettings.class, PostProcessingSlabsSettings::enabled, PostProcessingSlabsSettings.DEFAULT_ENABLED); + this.fluidHeight = terrain.fluidHeight(); + } + + /** Smooths the chunk of {@code context}. */ + static void smooth(ChunkStageContext context) { + new SurfaceSmoothing(context).smoothColumns(); + } + + private void smoothColumns() { + for (int i = 0; i < blocks.width(); i++) { + for (int j = 0; j < blocks.depth(); j++) { + post(i, j); + } + } + } + + /** + * Every column reads its own height plus its four neighbours, so adjacent columns would otherwise + * resolve the same height up to five times. Resolve the padded plane once instead. The four diagonal + * corners are never read, so they are left unresolved. + */ + /** A switch of the dimension, which every column of the chunk shares. */ + private static boolean enabled(ChunkStageContext context, Class type, Function enabled, boolean byDefault) { + return context.settings().at(type, context.centreX(), context.centreZ()).dimension().map(enabled).orElse(byDefault); + } + + /** The biome layer of the column's surface biome that {@code type} holds, or none. */ + private PaletteLayer biomeLayer(Class type, Function layer, int x, int z) { + return settings.at(type, x, z).mostSpecific().map(layer).orElse(NO_LAYER); + } + + /** The layer's block at the position, picked with the world's post-processing random, or null when it has none. */ + private BlockState pick(PaletteLayer layer, double x, double y, double z) { + int index = layerBlocks.pick(layer, postRandom, COLUMN_SIGNATURE, x, y, z); + return index == LayerBlocks.NONE ? null : layerBlocks.blocks(layer).get(index); + } + + private int[] heightPlane() { + int width = blocks.width(); + int depth = blocks.depth(); + int[] plane = new int[planeWidth * (depth + 2)]; + for (int j = -1; j <= depth; j++) { + boolean edge = j == -1 || j == depth; + int from = edge ? 0 : -1; + int to = edge ? width - 1 : width; + int row = (j + 1) * planeWidth; + for (int i = from; i <= to; i++) { + plane[row + i + 1] = surfaceHeight(originX + i, originZ + j); + } + } + return plane; + } + + private int surfaceHeight(int x, int z) { + return terrain.surfaceHeight(x, z); + } + + private void post(int localX, int localZ) { + int x = originX + localX; + int z = originZ + localZ; + int center = (localZ + 1) * planeWidth + localX + 1; + int h = heights[center]; + int ha = heights[center + 1]; + int hb = heights[center + planeWidth]; + int hc = heights[center - 1]; + int hd = heights[center - planeWidth]; + + if (h < 1) { + return; + } + + h = removeFloatingNib(x, z, h, ha, hb, hc, hd); + h = levelBumpOrPothole(x, z, h, ha, hb, hc, hd); + if (walls) { + paintWall(x, z, h, ha, hb, hc, hd); + } + if (slabs) { + h = placeSlab(x, z, h, ha, hb, hc, hd); + } + settleWaterlogging(x, z, h); + settleFoliage(x, z, h); + } + + private int removeFloatingNib(int x, int z, int h, int ha, int hb, int hc, int hd) { + int g = lower(ha, h - 1) + lower(hb, h - 1) + lower(hc, h - 1) + lower(hd, h - 1); + if (g != 4 || !isAir(x, h - 1, z)) { + return h; + } + set(x, h, z, AIR); + for (int i = h - 1; i > 0; i--) { + if (!isAir(x, i, z)) { + return i; + } + } + return h; + } + + private int levelBumpOrPothole(int x, int z, int h, int ha, int hb, int hc, int hd) { + int g = same(ha, h - 1) + same(hb, h - 1) + same(hc, h - 1) + same(hd, h - 1); + if (g >= 4) { + BlockState bump = get(x, h, z); + BlockState above = get(x, h + 1, z); + if (has(above, BlockTrait.OCCLUDING) && has(above, BlockTrait.SOLID) && has(bump, BlockTrait.SOLID)) { + set(x, h, z, above); + return h - 1; + } + return h; + } + g = same(ha, h + 1) + same(hb, h + 1) + same(hc, h + 1) + same(hd, h + 1); + if (g < 4) { + return h; + } + int solidSides = solid(get(x, ha, z)) + solid(get(x, hb, z)) + solid(get(x, hc, z)) + solid(get(x, hd, z)); + if (solidSides < 3) { + return h; + } + set(x, h + 1, z, get(x, h, z)); + return h + 1; + } + + private void paintWall(int x, int z, int h, int ha, int hb, int hc, int hd) { + if (ha >= h - 2 && hb >= h - 2 && hc >= h - 2 && hd >= h - 2) { + return; + } + PaletteLayer wall = biomeLayer(WallSettings.class, WallSettings::layer, x, z); + if (wall.palette().isEmpty()) { + return; + } + boolean brokeGround = false; + int max = Math.abs(Math.max(h - ha, Math.max(h - hb, Math.max(h - hc, h - hd)))); + for (int i = h; i > h - max; i--) { + BlockState block = pick(wall, x + i, i + h, z + i); + if (block == null) { + continue; + } + if (isAirOrWater(x, i, z)) { + if (brokeGround) { + break; + } + continue; + } + set(x, i, z, block); + brokeGround = true; + } + } + + private int placeSlab(int x, int z, int h, int ha, int hb, int hc, int hd) { + boolean step = (ha == h + 1 && isSolidNonSlab(x + 1, ha, z)) + || (hb == h + 1 && isSolidNonSlab(x, hb, z + 1)) + || (hc == h + 1 && isSolidNonSlab(x - 1, hc, z)) + || (hd == h + 1 && isSolidNonSlab(x, hd, z - 1)); + if (!step) { + return h; + } + PaletteLayer slab = biomeLayer(SlabSettings.class, SlabSettings::layer, x, z); + if (!slab.slopeCondition().isValid(terrain.column(x, z).slope())) { + return h; + } + BlockState block = pick(slab, x, h, z); + if (block == null) { + return h; + } + boolean cancel = has(block, BlockTrait.AIR) + || block.material().equals(SNOW_ID) && h + 1 <= fluidHeight + || isSnowLayer(x, h, z); + if (cancel || !isAirOrWater(x, h + 1, z)) { + return h; + } + set(x, h + 1, z, block); + return h + 1; + } + + private void settleWaterlogging(int x, int z, int h) { + BlockState block = get(x, h, z); + if (!block.properties().containsKey(WATERLOGGED)) { + return; + } + boolean waterlogged = h <= fluidHeight + 1 && (isWaterOrWaterlogged(x, h + 1, z) + || isWaterOrWaterlogged(x + 1, h, z) || isWaterOrWaterlogged(x - 1, h, z) + || isWaterOrWaterlogged(x, h, z + 1) || isWaterOrWaterlogged(x, h, z - 1)); + if (waterlogged != TRUE.equals(block.properties().get(WATERLOGGED))) { + set(x, h, z, block.withProperty(WATERLOGGED, String.valueOf(waterlogged))); + } + } + + private void settleFoliage(int x, int z, int h) { + BlockState block = get(x, h + 1, z); + if (has(block, BlockTrait.VINE)) { + connectVine(x, h + 1, z, block); + } + if (!has(block, BlockTrait.FOLIAGE) && !block.material().equals(DEAD_BUSH_ID)) { + return; + } + if (!registry.canPlaceOn(block, get(x, h, z)) && !has(block, BlockTrait.DECORATION)) { + set(x, h + 1, z, AIR); + } + } + + /** A vine faces each neighbour it can cling to, a block that is neither air nor another vine. */ + private void connectVine(int x, int y, int z, BlockState vine) { + BlockState connected = vine; + for (Face face : FACES) { + if (!vine.properties().containsKey(face.property())) { + continue; + } + BlockState neighbour = get(x + face.dx(), y + face.dy(), z + face.dz()); + connected = connected.withProperty(face.property(), String.valueOf(!has(neighbour, BlockTrait.AIR) && !has(neighbour, BlockTrait.VINE))); + } + if (!connected.equals(vine)) { + set(x, y, z, connected); + } + } + + private boolean isAir(int x, int y, int z) { + ResourceId material = get(x, y, z).material(); + return material.equals(AIR_ID) || material.equals(CAVE_AIR_ID); + } + + private boolean isSolidNonSlab(int x, int y, int z) { + BlockState block = get(x, y, z); + return has(block, BlockTrait.SOLID) && !block.material().path().endsWith(SLAB_SUFFIX); + } + + private boolean isAirOrWater(int x, int y, int z) { + ResourceId material = get(x, y, z).material(); + return material.equals(WATER_ID) || material.equals(AIR_ID) || material.equals(CAVE_AIR_ID); + } + + private boolean isSnowLayer(int x, int y, int z) { + return get(x, y, z).material().equals(SNOW_ID); + } + + private boolean isWaterOrWaterlogged(int x, int y, int z) { + BlockState block = get(x, y, z); + return block.material().equals(WATER_ID) || TRUE.equals(block.properties().get(WATERLOGGED)); + } + + private boolean has(BlockState block, BlockTrait trait) { + return registry.hasTrait(block, trait); + } + + private int solid(BlockState block) { + return has(block, BlockTrait.SOLID) ? 1 : 0; + } + + private static int lower(int neighbour, int than) { + return neighbour < than ? 1 : 0; + } + + private static int same(int neighbour, int as) { + return neighbour == as ? 1 : 0; + } + + /** Writes inside the chunk only; a step on a neighbour column outside it is left alone. */ + private void set(int x, int y, int z, BlockState block) { + int localX = x - originX; + int localZ = z - originZ; + if (localX < 0 || localZ < 0 || localX >= blocks.width() || localZ >= blocks.depth() || y < 0 || y >= blocks.height()) { + return; + } + blocks.set(localX, y, localZ, block); + } + + /** + * Neighbour columns can sit one block outside this chunk, and the blocks of an adjacent chunk are not + * available while generating this one. Clamp to the nearest block of the chunk instead of wrapping to the + * opposite edge. + */ + private BlockState get(int x, int y, int z) { + return blocks.get(clamp(x - originX, blocks.width()), clamp(y, blocks.height()), clamp(z - originZ, blocks.depth())); + } + + private static int clamp(int value, int size) { + return value < 0 ? 0 : Math.min(value, size - 1); + } + + private record Face(String property, int dx, int dy, int dz) { + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/KeyedResource.java b/module/src/main/java/art/arcane/iris/engine/object/KeyedResource.java new file mode 100644 index 000000000..b42699e90 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/KeyedResource.java @@ -0,0 +1,41 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object; + +/** + * A resource of Iris's pack object model read from one file of a pack. Iris sets its key, the file's path below the + * folder without {@code .json}, when it reads the file; the folder and type name are what studio and load reports show. + */ +public abstract class KeyedResource { + private transient String loadKey; + + public String getLoadKey() { + return loadKey; + } + + public void setLoadKey(String loadKey) { + this.loadKey = loadKey; + } + + /** The folder below the pack root that holds resources of this type. */ + public abstract String getFolderName(); + + /** The name studio and load reports give a resource of this type, such as {@code Structure}. */ + public abstract String getTypeName(); +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/annotations/ArrayType.java b/module/src/main/java/art/arcane/iris/engine/object/annotations/ArrayType.java new file mode 100644 index 000000000..8c07ecbe1 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/annotations/ArrayType.java @@ -0,0 +1,35 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Retention(RUNTIME) +@Target({PARAMETER, TYPE, FIELD}) +public @interface ArrayType { + Class type(); + + int min() default 0; +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/annotations/Desc.java b/module/src/main/java/art/arcane/iris/engine/object/annotations/Desc.java new file mode 100644 index 000000000..20f7887e0 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/annotations/Desc.java @@ -0,0 +1,33 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Retention(RUNTIME) +@Target({PARAMETER, TYPE, FIELD}) +public @interface Desc { + String value(); +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/annotations/MaxNumber.java b/module/src/main/java/art/arcane/iris/engine/object/annotations/MaxNumber.java new file mode 100644 index 000000000..a50844724 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/annotations/MaxNumber.java @@ -0,0 +1,31 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Retention(RUNTIME) +@Target({FIELD}) +public @interface MaxNumber { + double value(); +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/annotations/MinNumber.java b/module/src/main/java/art/arcane/iris/engine/object/annotations/MinNumber.java new file mode 100644 index 000000000..1e286d941 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/annotations/MinNumber.java @@ -0,0 +1,31 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Retention(RUNTIME) +@Target({FIELD}) +public @interface MinNumber { + double value(); +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListResource.java b/module/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListResource.java new file mode 100644 index 000000000..24f1568b0 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListResource.java @@ -0,0 +1,34 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Retention(RUNTIME) +@Target({PARAMETER, TYPE, FIELD}) +public @interface RegistryListResource { + /** The class pack resources of the kind are read into: an Iris resource or the class of a module resource kind. */ + Class value(); +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructure.java b/module/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructure.java new file mode 100644 index 000000000..7768b6818 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructure.java @@ -0,0 +1,32 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Retention(RUNTIME) +@Target({PARAMETER, TYPE, FIELD}) +public @interface RegistryListVanillaStructure { +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/annotations/Required.java b/module/src/main/java/art/arcane/iris/engine/object/annotations/Required.java new file mode 100644 index 000000000..a449f470c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/annotations/Required.java @@ -0,0 +1,33 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Retention(RUNTIME) +@Target({PARAMETER, TYPE, FIELD}) +public @interface Required { + +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/annotations/Snippet.java b/module/src/main/java/art/arcane/iris/engine/object/annotations/Snippet.java new file mode 100644 index 000000000..980e818bd --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/annotations/Snippet.java @@ -0,0 +1,31 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Retention(RUNTIME) +@Target({TYPE}) +public @interface Snippet { + String value(); +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java b/module/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java new file mode 100644 index 000000000..2d527b99b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java @@ -0,0 +1,171 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.builtin.anchor.AnchorHeight; +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.objects.ObjectRun; +import art.arcane.iris.builtin.prepare.TransformedBounds; +import art.arcane.iris.modules.placement.ObjectShape; +import art.arcane.iris.modules.placement.PlacementSettings; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; +import art.arcane.iris.modules.placement.StageTerrain; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.stage.PlacementStageContext; + +import java.util.Optional; + +/** + * Module {@code iris:anchor}: the height an object is placed at, requested by the caller, counted from the + * bottom of the world, or sampled from the terrain the way the placement mode says. A surface-anchored + * placement rejects a height its carving support forbids. + */ +public final class AnchorModule implements IrisModule { + private static final String CARVING_ANCHOR = "carving-anchor"; + private static final int CARVING_CLEARANCE_BLOCKS = 4; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:anchor", "Placement anchor", PlacementModules.VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + var graph = setup.stages(); + graph.define(PlacementStages.Anchor.HEIGHT) + .requires(PlacementStages.Prepare.TRANSFORMS) + .produce(AnchorModule::height); + graph.define(PlacementStages.Anchor.FINAL) + .requires(PlacementStages.Anchor.HEIGHT, PlacementStages.Validate.COLLISIONS) + .produce(AnchorModule::finalHeight); + } + + private static AnchorHeight height(PlacementStageContext context) { + RunningPlacement placement = context.output(PlacementStages.Prepare.TRANSFORMS).placement(); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + PlacementSettings settings = prepared.settings(); + boolean structurePiece = prepared.mode().has(PlaceTrait.RAW_STAMP); + if (!settings.fromBottom() && placement.requestedY() < 0) { + return new AnchorHeight(sampled(context, placement, prepared)); + } + ObjectShape object = placement.object(); + int y = settings.fromBottom() ? object.height() + 1 + prepared.rotatedCenterY() : placement.requestedY(); + if (!settings.forcePlace() && !structurePiece && rejectsCarvingAnchor(prepared, placement.x(), y, placement.z())) { + context.reject(CARVING_ANCHOR); + return null; + } + if (placement.requestedY() < 0 || !settings.bottom() || structurePiece) { + return new AnchorHeight(y); + } + y += Math.floorDiv(object.height(), 2); + if (!settings.forcePlace() && settings.carvingSupport() != CarvingMode.CARVING_ONLY + && rejectsCarvingAnchor(prepared, placement.x(), y, placement.z())) { + context.reject(CARVING_ANCHOR); + return null; + } + return new AnchorHeight(y); + } + + private static AnchorHeight finalHeight(PlacementStageContext context) { + int y = context.output(PlacementStages.Anchor.HEIGHT).y() + context.output(PlacementStages.Prepare.TRANSFORMS).randomY(); + context.output(PlacementStages.Prepare.TRANSFORMS).placement().anchoredAt(y); + return new AnchorHeight(y); + } + + private static int sampled(PlacementStageContext context, RunningPlacement placement, PreparedPlacement prepared) { + return switch (prepared.mode().anchor()) { + case CENTER -> checked(context, prepared, placement.x(), centerSurface(placement, prepared), placement.z()); + case SURFACE -> checked(context, prepared, placement.x(), surface(prepared, placement.x(), placement.z()), placement.z()); + case HIGHEST -> extremeSurface(context, placement, prepared, true, false); + case HIGHEST_CORNER -> extremeSurface(context, placement, prepared, true, true); + case LOWEST -> extremeSurface(context, placement, prepared, false, false); + case LOWEST_CORNER -> extremeSurface(context, placement, prepared, false, true); + case TRANSLATION -> prepared.rotatedCenterY(); + case REQUESTED -> placement.requestedY(); + }; + } + + /** The floor of the cave the object is placed in, otherwise the surface at its center. */ + private static int centerSurface(RunningPlacement placement, PreparedPlacement prepared) { + Optional cave = placement.cave(); + if (cave.isPresent()) { + return cave.get().surface() + prepared.rotatedCenterY(); + } + return surface(prepared, placement.x(), placement.z()); + } + + private static int surface(PreparedPlacement prepared, int x, int z) { + return prepared.terrain().highest(x, z, prepared.settings().underwater()) + prepared.rotatedCenterY(); + } + + private static int checked(PlacementStageContext context, PreparedPlacement prepared, int x, int y, int z) { + if (!prepared.settings().forcePlace() && rejectsCarvingAnchor(prepared, x, y, z)) { + context.reject(CARVING_ANCHOR); + } + return y; + } + + /** The highest or lowest surface under the object's columns, or under its four corners only. */ + private static int extremeSurface(PlacementStageContext context, RunningPlacement placement, PreparedPlacement prepared, + boolean highest, boolean cornersOnly) { + TransformedBounds bounds = prepared.bounds(); + int minX = placement.x() + bounds.minX(); + int maxX = placement.x() + bounds.maxX(); + int minZ = placement.z() + bounds.minZ(); + int maxZ = placement.z() + bounds.maxZ(); + int xStep = cornersOnly ? Math.max(0, (maxX - minX) / 2) + 1 : 1; + int zStep = cornersOnly ? Math.max(0, (maxZ - minZ) / 2) + 1 : 1; + int y = highest ? -1 : Integer.MAX_VALUE; + for (int x = minX; x <= maxX; x += xStep) { + for (int z = minZ; z <= maxZ; z += zStep) { + int column = surface(prepared, x, z); + if (!prepared.settings().forcePlace() && rejectsCarvingAnchor(prepared, x, column, z)) { + context.reject(CARVING_ANCHOR); + return y; + } + y = highest ? Math.max(y, column) : Math.min(y, column); + } + } + return y; + } + + /** Whether the placement's carving support forbids anchoring at this block. */ + private static boolean rejectsCarvingAnchor(PreparedPlacement prepared, int x, int y, int z) { + StageTerrain terrain = prepared.terrain(); + return switch (prepared.settings().carvingSupport()) { + case SURFACE_ONLY -> terrain.isCarved(x, y, z); + case CARVING_ONLY -> !carvedWithin(terrain, x, y, z); + case ANYWHERE -> false; + }; + } + + private static boolean carvedWithin(StageTerrain terrain, int x, int y, int z) { + for (int depth = 0; depth < CARVING_CLEARANCE_BLOCKS; depth++) { + if (terrain.isCarved(x, y - depth, z)) { + return true; + } + } + return false; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/module/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java new file mode 100644 index 000000000..d9d4b36a3 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -0,0 +1,265 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.blocks.WrittenBlocks; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.spawn.SpawnMarker; +import art.arcane.iris.engine.spawn.SpawnResources; +import art.arcane.iris.modules.blocks.SmartBoreDebugSettings; +import art.arcane.iris.modules.placement.MarkerRule; +import art.arcane.iris.modules.placement.PlacementSettings; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; +import art.arcane.iris.modules.placement.StageTerrain; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.object.BlockEntityData; +import com.volmit.object.ObjectBlock; +import com.volmit.placement.PlacedMarker; +import com.volmit.stage.BlockStageContext; +import com.volmit.stage.PlacementStageContext; +import com.volmit.geometry.BlockPosition; + +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Module {@code iris:blocks}: writes the object's blocks where the placement puts them, then its markers. + * Each block is turned with the object, edited, warped, painted onto its column when the mode paints, + * waterlogged in water and attached to the faces vines can hang from. Air is not written, except by + * structure pieces, and neither is a vine into a solid block, leaves onto a log or a melded block into open space. + */ +public final class BlocksModule implements IrisModule { + private static final Set AIR_MATERIALS = Set.of("minecraft:air", "minecraft:cave_air"); + private static final BlockState VOID_AIR = new BlockState("minecraft:void_air"); + private static final BlockState VOID_AIR_DEBUG = new BlockState("minecraft:cobweb"); + private static final String DISTANCE = "distance"; + private static final String PERSISTENT = "persistent"; + static final String WATERLOGGED = "waterlogged"; + static final String TRUE = "true"; + private static final String FALSE = "false"; + private static final int MARKER_HEADROOM_BLOCKS = 2; + private static final Map FACE_OFFSETS = Map.of( + "north", new int[]{0, 0, -1}, "east", new int[]{1, 0, 0}, "south", new int[]{0, 0, 1}, + "west", new int[]{-1, 0, 0}, "up", new int[]{0, 1, 0}, "down", new int[]{0, -1, 0}); + private static final String[] FACE_PROPERTIES = {"north", "east", "south", "west", "up", "down"}; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:blocks", "Object blocks", PlacementModules.VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + setup.registry().registerSettings(SmartBoreDebugSettings.class); + var graph = setup.stages(); + graph.define(PlacementStages.Blocks.WRITE) + .requires(PlacementStages.Prepare.TRANSFORMS, PlacementStages.Anchor.FINAL, PlacementStages.Bore.CLEAR) + .accumulate(WrittenBlocks::new, BlocksModule::write); + graph.define(PlacementStages.Blocks.MARKERS) + .requires(PlacementStages.Blocks.WRITE, PlacementStages.Prepare.TRANSFORMS) + .run(BlocksModule::placeMarkers); + graph.define(PlacementStages.Blocks.COMPLETE) + .requires(PlacementStages.Blocks.WRITE, PlacementStages.Blocks.MARKERS) + .run(context -> { + }); + } + + private static void write(BlockStageContext context, WrittenBlocks written) { + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + RunningPlacement placement = prepared.placement(); + PlacementSettings settings = prepared.settings(); + PlacementWorld world = new PlacementWorld(context.access(), prepared.traits()); + ObjectBlock block = context.block(); + BlockPosition offset = prepared.transform(block.position()); + int anchorY = context.output(PlacementStages.Anchor.FINAL).y(); + BlockState data = sourceState(block, placement, prepared); + Optional blockEntity = block.blockEntity(); + if (!settings.edit().isEmpty()) { + ObjectEdits.Edited edited = ObjectEdits.apply(settings.edit(), data, blockEntity, new RNG(context.random().nextLong()), + offset.x() + placement.x(), offset.y() + anchorY, offset.z() + placement.z(), + ResolvedReplaces.of(context), placement); + data = edited.data(); + blockEntity = edited.blockEntity(); + } + data = prepared.rotate(data); + int x = placement.x() + offset.x(); + int y = anchorY + offset.y(); + int z = placement.z() + offset.z(); + if (prepared.isWarped()) { + x += prepared.warpOffset(offset.x() + placement.x(), y, offset.z() + placement.z()); + z += prepared.warpOffset(offset.z() + placement.z(), y, offset.x() + placement.x()); + } + if (WorldVolume.isPainted(placement, prepared) && !world.has(data, BlockTrait.VINE)) { + y = offset.y() + Math.floorDiv(placement.object().height(), 2) + + prepared.terrain().highest(x, z, settings.underwater()); + } + boolean structurePiece = prepared.mode().has(PlaceTrait.RAW_STAMP); + if (settings.meld() && !structurePiece && !world.isSolid(x, y, z)) { + return; + } + if (data.properties().containsKey(WATERLOGGED) && shouldWaterlog(world, settings, placement.requestedY(), x, y, z)) { + data = data.withProperty(WATERLOGGED, TRUE); + } + if (world.has(data, BlockTrait.VINE)) { + data = attachVineFaces(world, data, x, y, z); + } + if (!shouldWrite(world, data, x, y, z, structurePiece)) { + return; + } + world.set(x, y, z, data, blockEntity); + BlockPosition position = new BlockPosition(x, y, z); + placement.objectBlockWritten(position); + written.add(position, data); + } + + /** The object block as Iris places it: debug air shows where smart boring bored, and leaves never decay where the placer prevents it. */ + private static BlockState sourceState(ObjectBlock block, RunningPlacement placement, PreparedPlacement prepared) { + BlockState data = block.state(); + StageTerrain terrain = prepared.terrain(); + if (placement.matches(data, VOID_AIR) && terrain.debugsSmartBore(placement.x(), placement.z())) { + data = VOID_AIR_DEBUG; + } + if (terrain.preventsDecay() && data.properties().containsKey(DISTANCE) + && FALSE.equals(data.properties().get(PERSISTENT))) { + data = data.withProperty(PERSISTENT, TRUE); + } + return data; + } + + private static boolean shouldWrite(PlacementWorld world, BlockState data, int x, int y, int z, boolean structurePiece) { + if (world.has(data, BlockTrait.CUSTOM)) { + return true; + } + return shouldPlaceObjectBlock(structurePiece, AIR_MATERIALS.contains(data.material().toString()), keepsExisting(world, data, x, y, z)); + } + + /** + * A vine never replaces a solid block, and leaves never cut a log another object already placed, as in vanilla + * trees: the log above the cut would float. + */ + private static boolean keepsExisting(PlacementWorld world, BlockState data, int x, int y, int z) { + if (world.has(data, BlockTrait.VINE)) { + return world.isSolid(x, y, z); + } + return world.has(data, BlockTrait.LEAVES) && world.has(world.get(x, y, z), BlockTrait.LOG); + } + + /** Air is written only by structure pieces, and nothing is written where the existing block is kept. */ + static boolean shouldPlaceObjectBlock(boolean structurePiece, boolean air, boolean keepsExisting) { + return !keepsExisting && (structurePiece || !air); + } + + /** Whether a waterloggable block lands in water a waterloggable or underwater placement keeps. */ + static boolean shouldWaterlog(PlacementWorld world, PlacementSettings settings, int requestedY, int x, int y, int z) { + if (!(settings.waterloggable() || settings.underwater())) { + return false; + } + if (requestedY >= 0 && settings.carvingSupport() == CarvingMode.CARVING_ONLY) { + return false; + } + BlockState existing = world.get(x, y, z); + return world.has(existing, BlockTrait.WATER) || TRUE.equals(existing.properties().get(WATERLOGGED)); + } + + /** {@code vine} hanging from each neighboring solid block it has a face property for. */ + static BlockState attachVineFaces(PlacementWorld world, BlockState vine, int x, int y, int z) { + BlockState attached = vine; + for (String face : FACE_PROPERTIES) { + if (!vine.properties().containsKey(face)) { + continue; + } + int[] offset = FACE_OFFSETS.get(face); + BlockState facing = world.get(x + offset[0], y + offset[1], z + offset[2]); + if (world.has(facing, BlockTrait.SOLID) && !world.has(facing, BlockTrait.VINE)) { + attached = attached.withProperty(face, TRUE); + } + } + return attached; + } + + /** + * Each marker of the placement marks up to its maximum of the written blocks it targets, picked at random, + * where the marker either allows anything above or finds two blocks of air. + */ + private static void placeMarkers(PlacementStageContext context) { + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + RunningPlacement placement = prepared.placement(); + PlacementSettings settings = prepared.settings(); + if (settings.markers().isEmpty() || !prepared.terrain().hasWorld()) { + return; + } + WrittenBlocks written = context.output(PlacementStages.Blocks.WRITE); + PlacementWorld world = new PlacementWorld(context.access(), prepared.traits()); + RNG markerRandom = new RNG(context.random().nextLong()); + int salt = 0; + for (MarkerRule rule : settings.markers()) { + Optional marker = Optional.ofNullable(SpawnResources.marker(placement.resources(), rule.marker())); + int markerSalt = salt++; + if (marker.isEmpty()) { + continue; + } + KList candidates = candidates(written, rule, placement); + int remaining = rule.maximum(); + for (BlockPosition position : candidates.shuffleCopy(markerRandom.nextParallelRNG(markerSalt))) { + if (remaining <= 0) { + break; + } + if (!marker.get().emptyAbove() || hasAirAbove(world, position)) { + context.access().marker(new PlacedMarker.PackMarker(position, rule.marker())); + remaining--; + } + } + } + } + + private static KList candidates(WrittenBlocks written, MarkerRule rule, RunningPlacement placement) { + KList candidates = new KList<>(); + written.forEach((position, state) -> { + if (rule.targets().stream().anyMatch(target -> marks(placement, rule, target, state))) { + candidates.add(position); + } + }); + return candidates; + } + + private static boolean marks(RunningPlacement placement, MarkerRule rule, BlockState target, BlockState state) { + return rule.exact() + ? placement.matches(target, state) + : target.material().equals(state.material()); + } + + private static boolean hasAirAbove(PlacementWorld world, BlockPosition position) { + for (int above = 1; above <= MARKER_HEADROOM_BLOCKS; above++) { + if (!world.has(world.get(position.x(), position.y() + above, position.z()), BlockTrait.AIR)) { + return false; + } + } + return true; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java b/module/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java new file mode 100644 index 000000000..a403f8c2d --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java @@ -0,0 +1,64 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.modules.placement.PlacementSettings; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.block.BlockState; +import com.volmit.stage.PlacementStageContext; + +/** Module {@code iris:bore}: fills the object's volume with air, extended up and down as configured. */ +public final class BoreModule implements IrisModule { + private static final BlockState AIR = new BlockState("minecraft:cave_air"); + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:bore", "Bore", PlacementModules.VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + setup.stages().define(PlacementStages.Bore.CLEAR) + .requires(PlacementStages.Anchor.FINAL, PlacementStages.Validate.COLLISIONS) + .run(BoreModule::clear); + } + + private static void clear(PlacementStageContext context) { + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + PlacementSettings settings = prepared.settings(); + if (!settings.bore()) { + return; + } + RunningPlacement placement = prepared.placement(); + WorldVolume volume = WorldVolume.of(placement, prepared, context.output(PlacementStages.Anchor.FINAL).y()); + PlacementWorld world = new PlacementWorld(context.access(), prepared.traits()); + for (int x = volume.minX(); x <= volume.maxX(); x++) { + for (int y = volume.minY() - settings.boreExtendMinY(); y <= volume.maxY() + settings.boreExtendMaxY(); y++) { + for (int z = volume.minZ(); z <= volume.maxZ(); z++) { + world.set(x, y, z, AIR); + } + } + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java b/module/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java new file mode 100644 index 000000000..e0337d45a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java @@ -0,0 +1,133 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.builtin.anchor.VacuumProfile; +import art.arcane.iris.builtin.vacuum.VacuumSettings; + +public final class IrisObjectVacuum { + private static final double DEFAULT_WAVE_AMPLITUDE = 3.0; + private static final double DEFAULT_WAVE_SCALE = 5.0; + /** The widest bend, as the settings allow it; placements prepare this much around every object. */ + public static final int MAX_RADIUS_BLOCKS = 128; + + private IrisObjectVacuum() { + } + + public static int resolveRadius(VacuumProfile vacuum, VacuumSettings settings) { + int radius = vacuum.defaultRadiusBlocks(); + if (settings != null && settings.radius() > 0) { + radius = settings.radius(); + } + return Math.max(0, Math.min(MAX_RADIUS_BLOCKS, radius)); + } + + public static double resolveFalloff(VacuumSettings settings) { + return settings != null ? Math.max(0.25, settings.falloff()) : 2.0; + } + + public static double resolveWaveAmplitude(VacuumSettings settings) { + if (settings == null) { + return DEFAULT_WAVE_AMPLITUDE; + } + return Math.max(0, settings.waveAmplitude()); + } + + public static double resolveWaveScale(VacuumSettings settings) { + if (settings == null) { + return DEFAULT_WAVE_SCALE; + } + double scale = settings.waveScale(); + return scale > 0 ? scale : DEFAULT_WAVE_SCALE; + } + + public static int footprintLow(int dimension) { + int size = Math.abs(dimension); + return -(size / 2); + } + + public static int footprintHigh(int dimension) { + int size = Math.abs(dimension); + if (size <= 0) { + return 0; + } + return size - (size / 2) - 1; + } + + public static int outset(int delta, int low, int high) { + if (delta < low) { + return low - delta; + } + if (delta > high) { + return delta - high; + } + return 0; + } + + /** The lowest height vacuum may target, one above the dimension's bottom (placer heights start at 0 there). */ + public static final int LOWEST_TARGET_Y = 1; + + public static int clampTargetY(int targetY, int lowestY, int highestY) { + return Math.max(lowestY, Math.min(highestY, targetY)); + } + + public static int columnTargetY(int dx, int dz, int lowX, int highX, int lowZ, int highZ, + double effectiveRadius, double falloff, int originalY, int meetY) { + double factor = columnInfluence( + dx, dz, lowX, highX, lowZ, highZ, effectiveRadius, falloff); + return (int) Math.round(originalY + (((double) meetY - originalY) * factor)); + } + + public static double columnInfluence(int dx, int dz, int lowX, int highX, int lowZ, int highZ, + double effectiveRadius, double falloff) { + int outX = outset(dx, lowX, highX); + int outZ = outset(dz, lowZ, highZ); + double distance = Math.sqrt((double) outX * outX + (double) outZ * outZ); + if (effectiveRadius <= 0) { + return distance <= 0 ? 1.0 : 0.0; + } + if (distance >= effectiveRadius) { + return 0.0; + } + double t = 1.0 - (distance / effectiveRadius); + if (t <= 0) { + return 0.0; + } + return Math.pow(t, Math.max(0.25, falloff)); + } + + public static int waveOffset(double distance, double effectiveRadius, double signedNoise, double amplitude) { + if (amplitude <= 0 || effectiveRadius <= 0) { + return 0; + } + if (distance <= 0 || distance >= effectiveRadius) { + return 0; + } + double envelope = Math.sin(Math.PI * (distance / effectiveRadius)); + return (int) Math.round(signedNoise * amplitude * envelope); + } + + public static int carveFloorY(int targetY, int objectTopY, boolean insideFootprint) { + int floor = targetY + 1; + if (insideFootprint) { + floor = Math.max(floor, objectTopY + 1); + } + return floor; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java b/module/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java new file mode 100644 index 000000000..fcc552afd --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java @@ -0,0 +1,215 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.modules.placement.StageTerrain; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectSpinKernel; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.volmlib.util.math.IrisBlockVector; + +import java.util.Arrays; +import java.util.List; + +/** + * Hard gate for surface-anchored object and tree placement: every column under the object's lowest solid + * layer, plus a buffer ring, must be solid un-carved ground for the required depth. Anything else floats + * over or bridges a carved hole, so the placement is skipped. + */ +public final class IrisSurfaceSupport { + private static final int MAX_STENCIL_CELLS = 1 << 22; + private static final ThreadLocal STENCIL = ThreadLocal.withInitial(Stencil::new); + + private IrisSurfaceSupport() { + } + + public static boolean isUnsupported(StageTerrain terrain, int x, int z, + ObjectTranslate translate, ObjectRotation rotation, + int spinX, int spinY, int spinZ, + List supportOffsets, int buffer, int minSolidDepth) { + Stencil stencil = STENCIL.get(); + Transform transform = new Transform(translate, new ObjectSpinKernel(rotation, spinX, spinY, spinZ)); + if (!stencil.build(supportOffsets, transform, Math.max(0, buffer))) { + return true; + } + return stencil.anyColumnUnsupported(terrain, x, z, Math.max(1, minSolidDepth)); + } + + /** The placement's rotation and translation, as they move a support offset. */ + private static final class Transform { + private final ObjectSpinKernel spin; + private final IrisBlockVector translation; + + private Transform(ObjectTranslate translate, ObjectSpinKernel spin) { + this.spin = spin; + if (translate.canTranslate()) { + translation = new IrisBlockVector(translate.x(), translate.y(), translate.z()); + spin.rotate(translation); + } else { + translation = null; + } + } + + private IrisBlockVector apply(IrisBlockVector offset) { + IrisBlockVector transformed = offset.clone(); + spin.rotate(transformed); + if (translation != null) { + transformed.add(translation); + } + return transformed; + } + } + + /** + * Rasterized footprint reused per thread. Overlapping support offsets collapse into one cell here so + * each unique column is sampled once no matter how large the buffer is. + */ + private static final class Stencil { + private int[] offsetX = new int[64]; + private int[] offsetZ = new int[64]; + private boolean[] cells = new boolean[0]; + private boolean[] dilateScratch = new boolean[0]; + private int minX; + private int minZ; + private int width; + private int depth; + private int centerX; + private int centerZ; + + private boolean build(List supportOffsets, Transform transform, int buffer) { + boolean originOnly = supportOffsets == null || supportOffsets.isEmpty(); + int count = originOnly ? 1 : supportOffsets.size(); + if (offsetX.length < count) { + offsetX = new int[count]; + offsetZ = new int[count]; + } + + int lowX = Integer.MAX_VALUE; + int highX = Integer.MIN_VALUE; + int lowZ = Integer.MAX_VALUE; + int highZ = Integer.MIN_VALUE; + for (int i = 0; i < count; i++) { + IrisBlockVector source = originOnly ? new IrisBlockVector(0, 0, 0) : supportOffsets.get(i); + IrisBlockVector transformed = transform.apply(source); + int transformedX = transformed.getBlockX(); + int transformedZ = transformed.getBlockZ(); + offsetX[i] = transformedX; + offsetZ[i] = transformedZ; + lowX = Math.min(lowX, transformedX); + highX = Math.max(highX, transformedX); + lowZ = Math.min(lowZ, transformedZ); + highZ = Math.max(highZ, transformedZ); + } + + minX = lowX - buffer; + minZ = lowZ - buffer; + width = (highX - lowX + 1) + (buffer * 2); + depth = (highZ - lowZ + 1) + (buffer * 2); + long area = (long) width * (long) depth; + if (area <= 0L || area > MAX_STENCIL_CELLS) { + return false; + } + + int size = (int) area; + if (cells.length < size) { + cells = new boolean[size]; + dilateScratch = new boolean[size]; + } + Arrays.fill(cells, 0, size, false); + for (int i = 0; i < count; i++) { + cells[((offsetX[i] - minX) * depth) + (offsetZ[i] - minZ)] = true; + } + if (buffer > 0) { + dilate(buffer, size); + } + + int anchorX = -minX; + int anchorZ = -minZ; + centerX = anchorX >= 0 && anchorX < width ? anchorX : width / 2; + centerZ = anchorZ >= 0 && anchorZ < depth ? anchorZ : depth / 2; + return true; + } + + /** Chebyshev dilation, run as two separable passes so a wide buffer stays linear in footprint size. */ + private void dilate(int buffer, int size) { + Arrays.fill(dilateScratch, 0, size, false); + for (int sourceX = 0; sourceX < width; sourceX++) { + int base = sourceX * depth; + int fromX = Math.max(0, sourceX - buffer); + int toX = Math.min(width - 1, sourceX + buffer); + for (int sourceZ = 0; sourceZ < depth; sourceZ++) { + if (!cells[base + sourceZ]) { + continue; + } + for (int targetX = fromX; targetX <= toX; targetX++) { + dilateScratch[(targetX * depth) + sourceZ] = true; + } + } + } + + Arrays.fill(cells, 0, size, false); + for (int sourceX = 0; sourceX < width; sourceX++) { + int base = sourceX * depth; + for (int sourceZ = 0; sourceZ < depth; sourceZ++) { + if (!dilateScratch[base + sourceZ]) { + continue; + } + int fromZ = Math.max(0, sourceZ - buffer); + int toZ = Math.min(depth - 1, sourceZ + buffer); + for (int targetZ = fromZ; targetZ <= toZ; targetZ++) { + cells[base + targetZ] = true; + } + } + } + } + + /** Centre-outward so the common failure, a hole right under the anchor, costs one column. */ + private boolean anyColumnUnsupported(StageTerrain terrain, int x, int z, int minSolidDepth) { + int maxRing = Math.max( + Math.max(centerX, width - 1 - centerX), + Math.max(centerZ, depth - 1 - centerZ)); + for (int ring = 0; ring <= maxRing; ring++) { + if (ring == 0) { + if (isColumnUnsupported(terrain, x, z, centerX, centerZ, minSolidDepth)) { + return true; + } + continue; + } + + int lowX = centerX - ring; + int highX = centerX + ring; + int lowZ = centerZ - ring; + int highZ = centerZ + ring; + for (int sx = lowX; sx <= highX; sx++) { + if (isColumnUnsupported(terrain, x, z, sx, lowZ, minSolidDepth) + || isColumnUnsupported(terrain, x, z, sx, highZ, minSolidDepth)) { + return true; + } + } + for (int sz = lowZ + 1; sz < highZ; sz++) { + if (isColumnUnsupported(terrain, x, z, lowX, sz, minSolidDepth) + || isColumnUnsupported(terrain, x, z, highX, sz, minSolidDepth)) { + return true; + } + } + } + return false; + } + + private boolean isColumnUnsupported(StageTerrain terrain, int x, int z, + int stencilX, int stencilZ, int minSolidDepth) { + if (stencilX < 0 || stencilX >= width || stencilZ < 0 || stencilZ >= depth + || !cells[(stencilX * depth) + stencilZ]) { + return false; + } + + int columnX = x + minX + stencilX; + int columnZ = z + minZ + stencilZ; + int surfaceY = terrain.highest(columnX, columnZ, true); + for (int below = 0; below < minSolidDepth; below++) { + if (terrain.isCarved(columnX, surfaceY - below, columnZ)) { + return true; + } + } + return !terrain.isSurfaceSolid(columnX, surfaceY, columnZ); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java b/module/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java new file mode 100644 index 000000000..1d4f0022d --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java @@ -0,0 +1,80 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.builtin.blocks.ObjectReplace; +import art.arcane.iris.modules.placement.RunningPlacement; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.object.BlockEntityData; + +import java.util.List; +import java.util.Optional; + +/** + * A placement's block replacements ({@code edit}): each replacement, by its chance, swaps the blocks it + * finds for its palette's block at the block's position, keeping the old block's properties when the + * material stays the same. + */ +final class ObjectEdits { + private ObjectEdits() { + } + + /** The result's block entity is the last replacement's, if it has one. */ + static Edited apply(List edits, BlockState data, Optional blockEntity, RNG rng, + double x, double y, double z, ResolvedReplaces replaces, RunningPlacement placement) { + BlockState edited = data; + Optional editedEntity = blockEntity; + for (ObjectReplace settings : edits) { + ResolvedReplace replace = replaces.of(settings); + if (!rng.chance(replace.chance())) { + continue; + } + for (BlockState find : replace.find()) { + if (!finds(placement, replace, find, edited)) { + continue; + } + edited = replaced(placement, edited, replace.replacement(rng, x, y, z)); + Optional picked = replace.tile(rng); + if (picked.isPresent()) { + editedEntity = picked; + } + } + } + return new Edited(edited, editedEntity); + } + + private static boolean finds(RunningPlacement placement, ResolvedReplace replace, BlockState find, BlockState data) { + return replace.exact() + ? placement.matches(find, data) + : find.material().equals(data.material()); + } + + private static BlockState replaced(RunningPlacement placement, BlockState data, BlockState replacement) { + boolean sameMaterial = replacement.material().equals(data.material()); + if (sameMaterial && !placement.hasTrait(replacement, BlockTrait.CUSTOM) && !placement.hasTrait(data, BlockTrait.CUSTOM)) { + return placement.merge(data, replacement); + } + return replacement; + } + + record Edited(BlockState data, Optional blockEntity) { + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/PlacementModules.java b/module/src/main/java/art/arcane/iris/engine/object/placement/PlacementModules.java new file mode 100644 index 000000000..72be39ff6 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/PlacementModules.java @@ -0,0 +1,27 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +/** What Iris's built-in object placement modules share: the version they report. The modules ship in the built-ins jar. */ +final class PlacementModules { + static final String VERSION = "built-in"; + + private PlacementModules() { + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java b/module/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java new file mode 100644 index 000000000..56f71a811 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java @@ -0,0 +1,65 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.modules.placement.BlockTraits; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.object.BlockEntityData; +import com.volmit.placement.PlacedBlock; +import com.volmit.placement.PlacementAccess; +import com.volmit.geometry.BlockPosition; + +import java.util.Optional; + +/** A placement stage's buffered world: reads see the placement's earlier writes, writes wait for the placement to commit. */ +final class PlacementWorld { + private final PlacementAccess access; + private final BlockTraits traits; + + PlacementWorld(PlacementAccess access, BlockTraits traits) { + this.access = access; + this.traits = traits; + } + + BlockState get(int x, int y, int z) { + return access.get(x, y, z); + } + + boolean has(BlockState state, BlockTrait trait) { + return traits.has(state, trait); + } + + boolean isSolid(int x, int y, int z) { + return has(get(x, y, z), BlockTrait.SOLID); + } + + void set(int x, int y, int z, BlockState state) { + access.set(x, y, z, state); + } + + /** A block entity needs the record; a plain block takes the write that allocates nothing. */ + void set(int x, int y, int z, BlockState state, Optional blockEntity) { + if (blockEntity.isEmpty()) { + access.set(x, y, z, state); + return; + } + access.set(new PlacedBlock(new BlockPosition(x, y, z), state, blockEntity)); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java b/module/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java new file mode 100644 index 000000000..5689a5e1e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java @@ -0,0 +1,185 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.prepare.AxisRotationClamp; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectSpinKernel; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.builtin.prepare.TransformedBounds; +import art.arcane.iris.modules.placement.BlockTraits; +import art.arcane.iris.modules.placement.ObjectShape; +import art.arcane.iris.modules.placement.PlacementSettings; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; +import art.arcane.iris.modules.placement.StageTerrain; +import art.arcane.iris.modules.placement.SurfaceWarp; +import art.arcane.volmlib.util.math.IrisBlockVector; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.stage.PlacementStageContext; + +import java.util.Optional; + +/** + * Module {@code iris:prepare}: checks the slope, turns the object downhill when asked, and chooses the + * placement's rotation, translation and random height offset. + */ +public final class PrepareModule implements IrisModule { + private static final int SPIN_DIVISOR = 1000; + private static final double NORTH = 0; + private static final double EAST = 90; + private static final double SOUTH = 180; + private static final double WEST = 270; + private static final double QUARTER_TURN = 90; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:prepare", "Placement preparation", PlacementModules.VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + var graph = setup.stages(); + graph.define(PlacementStages.Prepare.SLOPE).produce(PrepareModule::slope); + graph.define(PlacementStages.Prepare.TRANSFORMS) + .requires(PlacementStages.Prepare.SLOPE) + .produce(PrepareModule::transforms); + } + + private static ObjectRotation slope(PlacementStageContext context) { + RunningPlacement placement = RunningPlacement.of(context); + PlacementSettings settings = placement.settings(); + ObjectRotation requested = settings.rotation(); + boolean checksSlope = !settings.forcePlace() && !settings.slopeCondition().isDefault(); + if (!checksSlope && !settings.rotateTowardsSlope()) { + return requested; + } + if (!placement.terrain().hasWorld()) { + throw new IllegalStateException("Object placement requires an active Iris engine for slope settings."); + } + if (checksSlope && !settings.slopeCondition().isValid(placement.terrain().slopeAt(placement.x(), placement.z()))) { + context.reject("slope"); + return null; + } + return settings.rotateTowardsSlope() ? turnedDownhill(placement, requested) : requested; + } + + /** A copy of {@code requested} whose Y rotation faces the lowest side of the rectangle around the object. */ + private static ObjectRotation turnedDownhill(RunningPlacement placement, ObjectRotation requested) { + StageTerrain terrain = placement.terrain(); + ObjectShape object = placement.object(); + int x = placement.x(); + int z = placement.z(); + double north = terrain.heightAt(x, z + ((float) object.depth()) / 2); + double east = terrain.heightAt(x + ((float) object.width()) / 2, z); + double south = terrain.heightAt(x, z - ((float) object.depth()) / 2); + double west = terrain.heightAt(x - ((float) object.width()) / 2, z); + double lowest = Math.min(Math.min(north, east), Math.min(south, west)); + double downhill = lowest == north ? NORTH : lowest == east ? EAST : lowest == south ? SOUTH : WEST; + + double turn = requested.yAxis().min() + downhill; + if (turn == 0) { + return ObjectRotation.of(requested.canRotateX() || requested.canRotateZ(), requested.xAxis(), + AxisRotationClamp.of(false, false, 0, 0, QUARTER_TURN), requested.zAxis()); + } + return ObjectRotation.of(true, requested.xAxis(), AxisRotationClamp.of(true, false, turn, turn, QUARTER_TURN), + requested.zAxis()); + } + + private static PreparedPlacement transforms(PlacementStageContext context) { + RunningPlacement placement = RunningPlacement.of(context); + PlacementSettings settings = placement.settings(); + ObjectRotation rotation = context.output(PlacementStages.Prepare.SLOPE); + ObjectShape object = placement.object(); + RNG rng = new RNG(context.random().nextLong()); + StageTerrain terrain = placement.terrainFor(rng); + int spinX = rng.imax() / SPIN_DIVISOR; + int spinY = rng.imax() / SPIN_DIVISOR; + int spinZ = rng.imax() / SPIN_DIVISOR; + ObjectTranslate translate = settings.translate(); + ObjectSpinKernel spin = new ObjectSpinKernel(rotation, spinX, spinY, spinZ); + IrisBlockVector rotatedCenter = new IrisBlockVector(0, object.centerY(), 0); + spin.rotate(rotatedCenter); + IrisBlockVector translation = translate.canTranslate() ? rotated(spin, translate) : null; + IrisBlockVector translatedCenter = new IrisBlockVector(0, object.centerY(), 0); + if (translation != null) { + translatedCenter = (IrisBlockVector) translatedCenter.clone().add(translation); + } + int randomY = randomHeightOffset(translate.yRandom(), rng); + Optional surfaceWarp = placement.surfaceWarp(rng); + int warpMargin = surfaceWarp.map(warp -> (int) Math.ceil(Math.abs(warp.multiplier()) / 2D)).orElse(0); + TransformedBounds bounds = transformedBounds(object, spin, translation, settings.mode().placeMode().has(PlaceTrait.UPSIDE_DOWN), warpMargin); + return new PreparedPlacement(placement, rotation, new BlockTraits(context.world().resources().blocks()), terrain, spin, + spinX, spinY, spinZ, translation, rotatedCenter.getBlockY(), translatedCenter.getBlockY(), randomY, + warpMargin, bounds, surfaceWarp.orElse(null)); + } + + private static IrisBlockVector rotated(ObjectSpinKernel spin, ObjectTranslate translate) { + IrisBlockVector shift = new IrisBlockVector(translate.x(), translate.y(), translate.z()); + spin.rotate(shift); + return shift; + } + + /** Within {@code range} of zero, on the side its sign gives. */ + private static int randomHeightOffset(int range, RNG rng) { + if (range > 0) { + return rng.i(0, range); + } + return range < 0 ? rng.i(range, 0) : 0; + } + + private static TransformedBounds transformedBounds(ObjectShape object, ObjectSpinKernel spin, IrisBlockVector translation, + boolean ceilingHang, int margin) { + int[] sourceX = {-object.centerX(), object.width() - object.centerX() - 1}; + int[] sourceY = {-object.centerY(), object.height() - object.centerY() - 1}; + int[] sourceZ = {-object.centerZ(), object.depth() - object.centerZ() - 1}; + int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE; + int minY = Integer.MAX_VALUE, maxY = Integer.MIN_VALUE; + int minZ = Integer.MAX_VALUE, maxZ = Integer.MIN_VALUE; + for (int x : sourceX) { + for (int y : sourceY) { + for (int z : sourceZ) { + IrisBlockVector corner = new IrisBlockVector(x, y, z); + spin.rotate(corner); + if (ceilingHang) { + corner.setY(-corner.getBlockY()); + } + if (translation != null) { + corner.add(translation); + } + int cornerX = (int) Math.round(corner.getX()); + int cornerY = (int) Math.round(corner.getY()); + int cornerZ = (int) Math.round(corner.getZ()); + minX = Math.min(minX, cornerX); + maxX = Math.max(maxX, cornerX); + minY = Math.min(minY, cornerY); + maxY = Math.max(maxY, cornerY); + minZ = Math.min(minZ, cornerZ); + maxZ = Math.max(maxZ, cornerZ); + } + } + } + return new TransformedBounds(minX - margin, maxX + margin, minY, maxY, minZ - margin, maxZ + margin); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplace.java b/module/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplace.java new file mode 100644 index 000000000..928a17015 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplace.java @@ -0,0 +1,87 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.builtin.blocks.ObjectReplace; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.PaletteSpec; +import com.volmit.object.BlockEntityData; + +import java.util.List; +import java.util.Optional; + +/** + * One {@link ObjectReplace} made ready for a pack: the blocks it finds resolved through the pack's block registry, its + * palette picked through the registry with the seed of the {@link RNG} the placement hands in, and the tile data of the + * palette's entries resolved once. The old settings class cached the same things on itself. + */ +final class ResolvedReplace { + private final List find; + private final boolean exact; + private final float chance; + private final PaletteSpec replace; + private final BlockRegistry blocks; + private final List> entryTiles; + private final int weightedSize; + + ResolvedReplace(List find, boolean exact, float chance, PaletteSpec replace, BlockRegistry blocks) { + this.find = List.copyOf(find); + this.exact = exact; + this.chance = chance; + this.replace = replace; + this.blocks = blocks; + this.entryTiles = replace.palette().stream().map(blocks::blockEntity).toList(); + this.weightedSize = replace.palette().stream().mapToInt(spec -> Math.max(0, spec.weight())).sum(); + } + + static ResolvedReplace of(ObjectReplace settings, BlockRegistry blocks) { + List find = settings.find().stream().map(blocks::resolve).toList(); + return new ResolvedReplace(find, settings.exact(), settings.chance(), settings.replace(), blocks); + } + + float chance() { + return chance; + } + + boolean exact() { + return exact; + } + + List find() { + return find; + } + + BlockState replacement(RNG rng, double x, double y, double z) { + return blocks.palette(replace, rng.getSeed()).at(x, y, z); + } + + /** The tile data of the entry picked for {@code rng}: the first entry when the palette's weights add up to one, else a uniform pick. */ + Optional tile(RNG rng) { + if (weightedSize == 0) { + return Optional.empty(); + } + return entryTiles.get(weightedSize == 1 ? 0 : pickedEntry(rng)); + } + + private int pickedEntry(RNG rng) { + return entryTiles.size() == 1 ? 0 : rng.nextInt(entryTiles.size()); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java b/module/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java new file mode 100644 index 000000000..4ea3d2723 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java @@ -0,0 +1,45 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.builtin.blocks.ObjectReplace; +import com.volmit.block.BlockRegistry; +import com.volmit.stage.PlacementStageContext; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** The {@link ResolvedReplace}s of one pack's block registry, one per decoded {@link ObjectReplace}, built when a placement first uses it. */ +final class ResolvedReplaces { + private final BlockRegistry blocks; + private final Map resolved = new ConcurrentHashMap<>(); + + ResolvedReplaces(BlockRegistry blocks) { + this.blocks = blocks; + } + + /** The replacements of the world {@code context} places in. */ + static ResolvedReplaces of(PlacementStageContext context) { + return context.world().state(ResolvedReplaces.class, world -> new ResolvedReplaces(world.resources().blocks())); + } + + ResolvedReplace of(ObjectReplace settings) { + return resolved.computeIfAbsent(settings, replace -> ResolvedReplace.of(replace, blocks)); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java b/module/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java new file mode 100644 index 000000000..ba03e286e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java @@ -0,0 +1,87 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.builtin.blocks.WrittenBlocks; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.block.BlockState; +import com.volmit.stage.PlacementStageContext; +import com.volmit.geometry.BlockPosition; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.stream.IntStream; + +/** + * Module {@code iris:snow}: a random depth of snow on top of each column of the object, deeper the more + * snow the placement asks for. Only the object's own written blocks carry snow. + */ +public final class SnowModule implements IrisModule { + private static final int LAYERS_PER_UNIT_OF_SNOW = 7; + private static final BlockState[] SNOW_LAYERS = IntStream.rangeClosed(1, 8) + .mapToObj(layers -> new BlockState("minecraft:snow").withProperty("layers", Integer.toString(layers))) + .toArray(BlockState[]::new); + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:snow", "Snow", PlacementModules.VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + setup.stages().define(PlacementStages.Snow.COVER) + .requires(PlacementStages.Blocks.WRITE, PlacementStages.Blocks.COMPLETE, PlacementStages.Prepare.TRANSFORMS) + .softAfter(PlacementStages.Stilt.FILL, PlacementStages.Vacuum.TERRAIN) + .run(SnowModule::cover); + } + + private static void cover(PlacementStageContext context) { + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + double snow = prepared.settings().snow(); + WrittenBlocks written = context.output(PlacementStages.Blocks.WRITE); + if (!(snow > 0) || written.isEmpty()) { + return; + } + PlacementWorld world = new PlacementWorld(context.access(), prepared.traits()); + RNG rng = new RNG(context.random().nextLong()); + int maxLayer = SNOW_LAYERS.length - 1; + for (BlockPosition top : columnTops(written).values()) { + int layer = rng.i(0, (int) (snow * LAYERS_PER_UNIT_OF_SNOW)); + world.set(top.x(), top.y() + 1, top.z(), SNOW_LAYERS[Math.max(Math.min(layer, maxLayer), 0)]); + } + } + + /** The highest written block of each column, columns in the order they were first written. */ + private static Map columnTops(WrittenBlocks written) { + Map tops = new LinkedHashMap<>(); + for (BlockPosition position : written.positions()) { + tops.merge(columnKey(position), position, (current, next) -> next.y() > current.y() ? next : current); + } + return tops; + } + + private static long columnKey(BlockPosition position) { + return ((long) position.x() << Integer.SIZE) | (position.z() & 0xFFFFFFFFL); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java b/module/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java new file mode 100644 index 000000000..2ac6363e0 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java @@ -0,0 +1,291 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.builtin.anchor.StiltShape; +import art.arcane.iris.builtin.stilt.StiltLayers; +import art.arcane.iris.builtin.stilt.StiltSettings; +import art.arcane.iris.modules.placement.PlacementSettings; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.object.ObjectBlock; +import com.volmit.stage.BlockStageContext; +import com.volmit.stage.PlacementStageContext; +import com.volmit.geometry.BlockPosition; + +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** + * Module {@code iris:stilt}: once the object is written, repeats its bottom layer down to the ground, or + * for a ceiling hang its top layer up into the ceiling. Straight stilts reach the surface, eroded ones taper + * toward the edges, organic ones stop at the first solid block with a ragged, broken tip. + */ +public final class StiltModule implements IrisModule { + private static final Set SOIL_MATERIALS = Set.of("minecraft:grass_block", "minecraft:mycelium", + "minecraft:podzol", "minecraft:dirt_path"); + private static final BlockState SOIL_REPLACEMENT = new BlockState("minecraft:dirt"); + private static final Set NO_STILT_SUFFIXES = Set.of("_stairs", "_slab"); + private static final String PATH_MATERIAL = "minecraft:dirt_path"; + private static final long HASH_X = 341873128712L; + private static final long HASH_Y = 132897987541L; + private static final long HASH_Z = 735791245321L; + private static final int HASH_BUCKETS = 1000; + private static final double SKIP_CHANCE_SCALE = 0.7; + private static final int DEFAULT_ORGANIC_MAX_SCAN = 48; + private static final int DEFAULT_ORGANIC_JITTER = 3; + private static final double DEFAULT_ORGANIC_SCRATCH = 0.55; + private static final int UNANCHORED_ORGANIC_DEPTH = 8; + private static final double ERODE_SOLID_FRACTION = 0.4; + private static final double ERODE_TAPER_EXPONENT = 1.5; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:stilt", "Stilts", PlacementModules.VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + var graph = setup.stages(); + graph.define(PlacementStages.Stilt.LAYERS) + .requires(PlacementStages.Prepare.TRANSFORMS) + // Ordered after boring only so it shares the block pass that writes the object. + .softAfter(PlacementStages.Bore.CLEAR) + .accumulate(StiltLayers::new, StiltModule::collectLayer); + graph.define(PlacementStages.Stilt.FILL) + .requires(PlacementStages.Stilt.LAYERS, PlacementStages.Anchor.FINAL, PlacementStages.Blocks.COMPLETE) + .run(StiltModule::fill); + } + + private static void collectLayer(BlockStageContext context, StiltLayers layers) { + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + if (prepared.mode().stilt() == StiltShape.NONE) { + return; + } + ObjectBlock block = context.block(); + if (!shouldStilt(prepared, block.state())) { + return; + } + layers.include(new ObjectBlock(prepared.transform(block.position()), block.state(), block.blockEntity())); + } + + /** Whether the block is solid ground a stilt can repeat: not a stair, a slab or a path. */ + private static boolean shouldStilt(PreparedPlacement prepared, BlockState state) { + if (!prepared.traits().has(state, BlockTrait.OCCLUDING)) { + return false; + } + String material = state.material().toString(); + return NO_STILT_SUFFIXES.stream().noneMatch(material::endsWith) && !material.equals(PATH_MATERIAL); + } + + private static void fill(PlacementStageContext context) { + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + StiltShape shape = prepared.mode().stilt(); + StiltLayers layers = context.output(PlacementStages.Stilt.LAYERS); + if (shape == StiltShape.NONE || layers.isEmpty()) { + return; + } + StiltColumns columns = new StiltColumns(context, prepared, layers); + List layer = shape == StiltShape.CEILING ? layers.top() : layers.bottom(); + for (ObjectBlock block : layer) { + columns.grow(block); + } + } + + /** One placement's stilt, grown column by column under (or above) the blocks of its repeated layer. */ + private static final class StiltColumns { + private final RunningPlacement placement; + private final PreparedPlacement prepared; + private final PlacementSettings config; + private final StiltSettings settings; + private final BlockState palette; + private final StiltShape shape; + private final PlacementWorld world; + private final PlacementStageContext context; + private final RNG rng; + private final int anchorY; + private final int layerY; + private final ErodeShape erode; + + private StiltColumns(PlacementStageContext context, PreparedPlacement prepared, StiltLayers layers) { + this.placement = context.output(PlacementStages.Prepare.TRANSFORMS).placement(); + this.prepared = prepared; + this.context = context; + this.config = prepared.settings(); + this.settings = config.stilt().orElse(null); + this.shape = prepared.mode().stilt(); + this.world = new PlacementWorld(context.access(), prepared.traits()); + this.rng = new RNG(context.random().nextLong()); + this.anchorY = context.output(PlacementStages.Anchor.FINAL).y(); + this.palette = settings == null ? null : paletteBlock(settings); + this.layerY = shape == StiltShape.CEILING ? layers.topY() : layers.bottomY(); + this.erode = shape == StiltShape.ERODE ? ErodeShape.of(layers.bottom()) : null; + } + + /** The block the settings' palette picks for this placement, the same for every column; null without a palette. */ + private BlockState paletteBlock(StiltSettings stilt) { + return stilt.palette() + .map(spec -> context.world().resources().blocks().palette(spec, rng.getSeed())) + .map(picker -> picker.at(placement.x(), anchorY, placement.z())) + .orElse(null); + } + + private void grow(ObjectBlock block) { + BlockPosition offset = block.position(); + BlockState state = stiltState(block, offset); + if (!world.has(state, BlockTrait.OCCLUDING)) { + return; + } + int x = placement.x() + offset.x(); + int z = placement.z() + offset.z(); + if (prepared.isWarped()) { + x += prepared.warpOffset(offset.x() + placement.x(), offset.y() + anchorY, offset.z() + placement.z()); + z += prepared.warpOffset(offset.z() + placement.z(), offset.y() + anchorY, offset.x() + placement.x()); + } + switch (shape) { + case ORGANIC -> growOrganic(state, x, z, -1); + case CEILING -> growOrganic(state, x, z, 1); + case STRAIGHT, ERODE -> growToSurface(state, offset, x, z); + case NONE -> { + } + } + } + + /** The block the stilt repeats: the palette's when the settings have one, soil turned to dirt, edited and turned with the object. */ + private BlockState stiltState(ObjectBlock block, BlockPosition offset) { + BlockState state = block.state(); + if (palette != null) { + state = palette; + } else if (SOIL_MATERIALS.contains(state.material().toString())) { + state = SOIL_REPLACEMENT; + } + state = prepared.rotate(state); + if (config.edit().isEmpty()) { + return state; + } + return ObjectEdits.apply(config.edit(), state, Optional.empty(), rng, offset.x() + placement.x(), offset.y() + anchorY, + offset.z() + placement.z(), ResolvedReplaces.of(context), placement).data(); + } + + private void growToSurface(BlockState state, BlockPosition offset, int x, int z) { + int top = layerY + anchorY; + int highest = prepared.terrain().highest(x, z, true); + if (state.properties().containsKey(BlocksModule.WATERLOGGED) + && BlocksModule.shouldWaterlog(world, config, placement.requestedY(), x, highest, z)) { + state = state.withProperty(BlocksModule.WATERLOGGED, BlocksModule.TRUE); + } + int lowerBound = highest - 1; + if (settings != null) { + lowerBound -= settings.overStilt() - rng.i(0, settings.yRand()); + if (settings.yMax() != 0) { + lowerBound -= Math.min(settings.yMax() - (top - highest), 0); + } + } + if (erode != null) { + lowerBound = top - erode.depth(offset, top - lowerBound); + } + for (int y = top; y > lowerBound; y--) { + if (world.has(world.get(x, y, z), BlockTrait.FLUID)) { + return; + } + if (erode != null && erode.breaksAt(x, y, z, top - y, top - lowerBound)) { + continue; + } + if (world.has(state, BlockTrait.VINE)) { + state = BlocksModule.attachVineFaces(world, state, x, y, z); + } + world.set(x, y, z, state); + } + } + + /** Grows from the layer toward the first solid block in {@code direction}, -1 down or 1 up. */ + private void growOrganic(BlockState state, int x, int z, int direction) { + int maxScan = settings != null ? Math.max(1, settings.organicMaxScan()) : DEFAULT_ORGANIC_MAX_SCAN; + int jitterMax = settings != null ? Math.max(0, settings.organicJitter()) : DEFAULT_ORGANIC_JITTER; + double scratch = settings != null ? Math.max(0, Math.min(1, settings.organicScratch())) : DEFAULT_ORGANIC_SCRATCH; + long columnHash = ((long) x * HASH_X) ^ ((long) z * HASH_Y); + int jitter = jitterMax > 0 ? (int) (Math.abs(columnHash) % (jitterMax + 1)) : 0; + int start = layerY + anchorY; + int scanned = 0; + int solidY = start + direction; + while (scanned < maxScan && !world.isSolid(x, solidY, z)) { + solidY += direction; + scanned++; + } + int end = (scanned < maxScan ? solidY - direction : start + direction * Math.min(maxScan, UNANCHORED_ORGANIC_DEPTH)) + - direction * jitter; + int length = (end - start) * direction; + for (int step = 0; step <= length; step++) { + int y = start + step * direction; + if (scratch > 0 && length > 0 && isScratched(x, y, z, (double) step / length, scratch)) { + continue; + } + world.set(x, y, z, state); + } + } + + /** Whether the broken tip skips this block: more often the deeper it lies in the scratched fraction. */ + private static boolean isScratched(int x, int y, int z, double depthRatio, double scratch) { + if (depthRatio <= 1.0 - scratch) { + return false; + } + double skipChance = (depthRatio - (1.0 - scratch)) / scratch; + return hashFraction(x, y, z) < skipChance * SKIP_CHANCE_SCALE; + } + } + + /** An eroded stilt: deepest under the layer's centroid, shallower toward its edge, broken up at depth. */ + private record ErodeShape(double centroidX, double centroidZ, double maxDistance) { + static ErodeShape of(List bottom) { + double centroidX = bottom.stream().mapToInt(block -> block.position().x()).average().orElse(0); + double centroidZ = bottom.stream().mapToInt(block -> block.position().z()).average().orElse(0); + double maxDistance = bottom.stream() + .mapToDouble(block -> Math.hypot(block.position().x() - centroidX, block.position().z() - centroidZ)) + .max().orElse(1); + return new ErodeShape(centroidX, centroidZ, Math.max(1, maxDistance)); + } + + int depth(BlockPosition offset, int fullDepth) { + double distance = Math.min(1.0, Math.hypot(offset.x() - centroidX, offset.z() - centroidZ) / maxDistance); + return (int) (fullDepth * Math.pow(1.0 - distance, ERODE_TAPER_EXPONENT)); + } + + boolean breaksAt(int x, int y, int z, int depth, int fullDepth) { + double depthRatio = fullDepth > 0 ? (double) depth / fullDepth : 0; + if (depthRatio <= ERODE_SOLID_FRACTION) { + return false; + } + double skipChance = (depthRatio - ERODE_SOLID_FRACTION) / (1.0 - ERODE_SOLID_FRACTION); + return hashFraction(x, y, z) < skipChance * SKIP_CHANCE_SCALE; + } + } + + private static double hashFraction(int x, int y, int z) { + long hash = ((long) x * HASH_X) ^ ((long) y * HASH_Y) ^ ((long) z * HASH_Z); + return (Math.abs(hash) % HASH_BUCKETS) / (double) HASH_BUCKETS; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/module/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java new file mode 100644 index 000000000..690b8cf13 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -0,0 +1,178 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.builtin.anchor.VacuumProfile; +import art.arcane.iris.builtin.blocks.WrittenBlocks; +import art.arcane.iris.builtin.prepare.TransformedBounds; +import art.arcane.iris.modules.placement.EdgeSimplex; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; +import art.arcane.iris.modules.placement.StageTerrain; +import art.arcane.iris.modules.terrain.TerrainPalettes; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.stage.PlacementStageContext; +import com.volmit.geometry.BlockPosition; + +/** + * Module {@code iris:vacuum}: bends the terrain around an object of a vacuum mode so it meets the object's + * base, raising columns with rock and carving them down, fading out across the bend's radius. + */ +public final class VacuumModule implements IrisModule { + private static final long WAVE_SEED = 7392113L; + private static final int DEFAULT_ORGANIC_JITTER = 4; + private static final long HASH_X = 341873128712L; + private static final long HASH_Z = 132897987541L; + private static final int HASH_BUCKETS = 1000; + private static final double HALF = 0.5; + private static final BlockState STONE = new BlockState("minecraft:stone"); + private static final BlockState AIR = new BlockState("minecraft:cave_air"); + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:vacuum", "Vacuum", PlacementModules.VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + setup.stages().define(PlacementStages.Vacuum.TERRAIN) + .requires(PlacementStages.Blocks.WRITE, PlacementStages.Blocks.COMPLETE, PlacementStages.Prepare.TRANSFORMS) + .reach(IrisObjectVacuum.MAX_RADIUS_BLOCKS) + .run(VacuumModule::bendTerrain); + } + + private static void bendTerrain(PlacementStageContext context) { + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + WrittenBlocks written = context.output(PlacementStages.Blocks.WRITE); + if (!prepared.mode().bendsTerrain() || written.isEmpty() || !prepared.terrain().hasWorld()) { + return; + } + int baseY = written.positions().stream().mapToInt(BlockPosition::y).min().orElseThrow(); + int topY = written.positions().stream().mapToInt(BlockPosition::y).max().orElseThrow(); + new Bend(context, prepared).apply(baseY, topY); + } + + /** One placement's terrain bend over the columns within its radius of the object's footprint. */ + private static final class Bend { + private final RunningPlacement placement; + private final PreparedPlacement prepared; + private final StageTerrain terrain; + private final PlacementWorld world; + private final PlacementStageContext context; + private final int radius; + private final int step; + private final double falloff; + private final int jitter; + private final double waveAmplitude; + private final double waveScale; + private final EdgeSimplex waves; + private final int lowestY; + private final int highestY; + + private Bend(PlacementStageContext context, PreparedPlacement prepared) { + VacuumProfile vacuum = prepared.mode().vacuum(); + this.placement = prepared.placement(); + this.prepared = prepared; + this.terrain = prepared.terrain(); + this.world = new PlacementWorld(context.access(), prepared.traits()); + this.context = context; + VacuumSettings settings = prepared.settings().vacuum().orElse(null); + this.radius = IrisObjectVacuum.resolveRadius(vacuum, settings); + this.step = vacuum.columnStepBlocks(); + this.falloff = IrisObjectVacuum.resolveFalloff(settings); + this.jitter = settings != null ? Math.max(0, settings.organicJitter()) : DEFAULT_ORGANIC_JITTER; + this.waveAmplitude = IrisObjectVacuum.resolveWaveAmplitude(settings); + this.waveScale = IrisObjectVacuum.resolveWaveScale(settings); + this.waves = vacuum.edge() == VacuumProfile.Edge.WAVY && waveAmplitude > 0 ? new EdgeSimplex(WAVE_SEED) : null; + this.lowestY = IrisObjectVacuum.LOWEST_TARGET_Y; + this.highestY = terrain.worldHeight() - 1; + } + + private void apply(int baseY, int topY) { + TransformedBounds bounds = prepared.bounds(); + for (int dx = bounds.minX() - radius; dx <= bounds.maxX() + radius; dx += step) { + for (int dz = bounds.minZ() - radius; dz <= bounds.maxZ() + radius; dz += step) { + bendColumn(bounds, dx, dz, baseY - 1, topY); + } + } + } + + private void bendColumn(TransformedBounds bounds, int dx, int dz, int meetY, int topY) { + int x = placement.x() + dx; + int z = placement.z() + dz; + double effectiveRadius = effectiveRadius(x, z); + int originalY = terrain.highest(x, z, true); + int targetY = IrisObjectVacuum.columnTargetY(dx, dz, bounds.minX(), bounds.maxX(), bounds.minZ(), bounds.maxZ(), + effectiveRadius, falloff, originalY, meetY) + waveOffset(bounds, dx, dz, x, z, effectiveRadius); + if (targetY == originalY) { + return; + } + targetY = IrisObjectVacuum.clampTargetY(targetY, lowestY, highestY); + if (targetY > originalY) { + raise(x, z, originalY, targetY); + } else if (targetY < originalY) { + boolean inside = IrisObjectVacuum.outset(dx, bounds.minX(), bounds.maxX()) == 0 + && IrisObjectVacuum.outset(dz, bounds.minZ(), bounds.maxZ()) == 0; + carve(x, z, originalY, IrisObjectVacuum.carveFloorY(targetY, topY, inside)); + } + } + + /** The radius, perturbed per column for the organic mode. */ + private double effectiveRadius(int x, int z) { + if (prepared.mode().vacuum().edge() != VacuumProfile.Edge.JITTERED || jitter <= 0) { + return radius; + } + long hash = ((long) x * HASH_X) ^ ((long) z * HASH_Z); + double noise = ((Math.abs(hash) % HASH_BUCKETS) / (double) HASH_BUCKETS) - HALF; + return Math.max(1.0, radius + (noise * 2.0 * jitter)); + } + + private int waveOffset(TransformedBounds bounds, int dx, int dz, int x, int z, double effectiveRadius) { + if (waves == null) { + return 0; + } + int outX = IrisObjectVacuum.outset(dx, bounds.minX(), bounds.maxX()); + int outZ = IrisObjectVacuum.outset(dz, bounds.minZ(), bounds.maxZ()); + double distance = Math.sqrt((double) (outX * outX) + (double) (outZ * outZ)); + return IrisObjectVacuum.waveOffset(distance, effectiveRadius, waves.signed(x * waveScale, z * waveScale), waveAmplitude); + } + + private void raise(int x, int z, int fromY, int toY) { + BlockState fill = TerrainPalettes.of(context.world()).rockAt(x, z); + if (fill == null || world.has(fill, BlockTrait.AIR)) { + fill = STONE; + } + for (int y = fromY + 1; y <= toY; y++) { + world.set(x, y, z, fill); + } + } + + private void carve(int x, int z, int fromY, int floorY) { + for (int y = fromY; y >= floorY; y--) { + world.set(x, y, z, AIR); + } + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/module/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java new file mode 100644 index 000000000..321e20eb4 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -0,0 +1,249 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.objects.ObjectRun; +import art.arcane.iris.builtin.terrain.BedrockSettings; +import art.arcane.iris.modules.placement.ObjectShape; +import art.arcane.iris.modules.placement.PlacementSettings; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; +import art.arcane.iris.modules.placement.StageTerrain; +import com.volmit.placement.StructureVolumes; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleLog; +import com.volmit.ModuleSetup; +import com.volmit.block.BlockState; +import com.volmit.object.ObjectBlock; +import com.volmit.resource.ResourceId; +import com.volmit.stage.PlacementStageContext; +import com.volmit.geometry.BlockPosition; +import com.volmit.world.PackWorld; + +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Module {@code iris:validate}: the checks that reject a placement before anything is written. Forced + * placements skip all but the native structure check, which only structure pieces skip. + */ +public final class ValidateModule implements IrisModule { + private static final long IMPLAUSIBLE_BEDROCK_WARN_THROTTLE_MS = 5000L; + private static final int BEDROCK_ROW = 1; + private static final Set AIR_MATERIALS = Set.of("minecraft:air", "minecraft:cave_air"); + private static final ConcurrentHashMap IMPLAUSIBLE_BEDROCK_WARNS = new ConcurrentHashMap<>(); + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:validate", "Placement checks", PlacementModules.VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + var graph = setup.stages(); + graph.define(PlacementStages.Validate.SURFACE) + .requires(PlacementStages.Anchor.HEIGHT) + .run(ValidateModule::checkSurface); + graph.define(PlacementStages.Validate.LIMITS) + .requires(PlacementStages.Validate.SURFACE, PlacementStages.Anchor.HEIGHT) + .run(ValidateModule::checkLimits); + graph.define(PlacementStages.Validate.STRUCTURES) + .requires(PlacementStages.Validate.LIMITS, PlacementStages.Anchor.HEIGHT) + .run(ValidateModule::checkNativeStructures); + graph.define(PlacementStages.Validate.COLLISIONS) + .requires(PlacementStages.Validate.STRUCTURES, PlacementStages.Anchor.HEIGHT) + .run(ValidateModule::checkCollisions); + } + + private static void checkSurface(PlacementStageContext context) { + RunningPlacement placement = context.output(PlacementStages.Prepare.TRANSFORMS).placement(); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + PlacementSettings settings = prepared.settings(); + if (settings.forcePlace() || settings.fromBottom() || prepared.mode().has(PlaceTrait.FREE_HEIGHT)) { + return; + } + int y = context.output(PlacementStages.Anchor.HEIGHT).y(); + boolean sampled = placement.requestedY() < 0; + if (sampled && settings.carvingSupport().supportsSurface() && isOnBedrock(context, prepared, y)) { + warnImplausibleBedrockPlacement(placement, settings, y, context.log()); + context.reject("bedrock-anchor"); + return; + } + boolean surfaceAnchored = sampled ? settings.carvingSupport().supportsSurface() + : settings.carvingSupport() == CarvingMode.SURFACE_ONLY; + if (surfaceAnchored && !settings.underwater() && !settings.onwater() && settings.requireSurfaceSupport() + && lacksSurfaceSupport(placement, prepared)) { + context.reject("surface-support"); + } + } + + private static boolean isOnBedrock(PlacementStageContext context, PreparedPlacement prepared, int y) { + return y <= BEDROCK_ROW && prepared.terrain().hasWorld() && hasBedrock(context.world()); + } + + private static boolean hasBedrock(PackWorld world) { + return world.settings().declared(BedrockSettings.class).dimension().map(BedrockSettings::bedrock).orElse(true); + } + + private static boolean lacksSurfaceSupport(RunningPlacement placement, PreparedPlacement prepared) { + PlacementSettings settings = prepared.settings(); + return IrisSurfaceSupport.isUnsupported(prepared.terrain(), placement.x(), placement.z(), settings.translate(), + prepared.rotation(), prepared.spinX(), prepared.spinY(), prepared.spinZ(), + placement.object().surfaceSupportOffsets(), settings.surfaceSupportBuffer(), settings.surfaceSupportDepth()); + } + + private static void checkLimits(PlacementStageContext context) { + RunningPlacement placement = context.output(PlacementStages.Prepare.TRANSFORMS).placement(); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + PlacementSettings settings = prepared.settings(); + if (settings.forcePlace() || prepared.mode().has(PlaceTrait.RAW_STAMP)) { + return; + } + int y = context.output(PlacementStages.Anchor.HEIGHT).y(); + int rotated = prepared.rotatedCenterY(); + int translated = prepared.translatedCenterY(); + Optional cave = placement.cave(); + if (placement.requestedY() < 0 && !prepared.mode().has(PlaceTrait.FREE_HEIGHT) && !settings.underwater() + && !settings.onwater() && prepared.terrain().isUnderwater(placement.x(), placement.z())) { + context.reject("underwater-anchor"); + } else if (cave.isPresent() + && Math.max(0, placement.object().height() + prepared.randomY() + translated) + 1 >= cave.get().height()) { + context.reject("cave-clearance"); + } else if (settings.underwater() && y + rotated + translated >= prepared.terrain().fluidHeight()) { + context.reject("fluid-height"); + } else if (!settings.clamp().canPlace(y + rotated + translated, y - rotated + translated)) { + context.reject("height-clamp"); + } + } + + private static void checkNativeStructures(PlacementStageContext context) { + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + if (prepared.mode().has(PlaceTrait.RAW_STAMP)) { + return; + } + int y = context.output(PlacementStages.Anchor.HEIGHT).y() + prepared.randomY(); + if (meetsNativeStructure(context, context.output(PlacementStages.Prepare.TRANSFORMS).placement(), prepared, y)) { + context.reject("native-structure"); + } + } + + private static boolean meetsNativeStructure(PlacementStageContext context, RunningPlacement placement, + PreparedPlacement prepared, int y) { + StageTerrain terrain = prepared.terrain(); + if (!terrain.hasWorld()) { + return false; + } + int x = placement.x(); + int z = placement.z(); + int margin = nativeStructureMargin(placement.object(), prepared); + StructureVolumes volumes = terrain.structureVolumes(x - margin, z - margin, x + margin, z + margin); + if (volumes.isEmpty()) { + return false; + } + boolean painted = WorldVolume.isPainted(placement, prepared); + int envelopeMinY = painted ? Integer.MIN_VALUE : y - margin; + int envelopeMaxY = painted ? Integer.MAX_VALUE : y + margin; + if (!volumes.intersects(x - margin, envelopeMinY, z - margin, x + margin, envelopeMaxY, z + margin)) { + return false; + } + for (ObjectBlock block : context.request().object().blocks()) { + if (isAir(block.state())) { + continue; + } + BlockPosition offset = prepared.transform(block.position()); + int blockX = x + offset.x(); + int blockZ = z + offset.z(); + int blockY = painted + ? offset.y() + Math.floorDiv(placement.object().height(), 2) + + terrain.highest(blockX, blockZ, prepared.settings().underwater()) + : y + offset.y(); + if (volumes.containsWithin(blockX, blockY, blockZ, prepared.warpMargin())) { + return true; + } + } + return false; + } + + /** How far around the anchor any block of the transformed object can reach. */ + private static int nativeStructureMargin(ObjectShape object, PreparedPlacement prepared) { + int margin = (Math.max(object.width(), Math.max(object.height(), object.depth())) / 2) + 1 + prepared.warpMargin(); + if (prepared.translation() == null) { + return margin; + } + return margin + Math.max(Math.abs(prepared.translation().getBlockX()), + Math.max(Math.abs(prepared.translation().getBlockY()), Math.abs(prepared.translation().getBlockZ()))); + } + + private static boolean isAir(BlockState state) { + return AIR_MATERIALS.contains(state.material().toString()); + } + + private static void checkCollisions(PlacementStageContext context) { + RunningPlacement placement = context.output(PlacementStages.Prepare.TRANSFORMS).placement(); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + PlacementSettings settings = prepared.settings(); + if (settings.forcePlace() || prepared.mode().has(PlaceTrait.RAW_STAMP) + || (settings.allowedCollisions().isEmpty() && settings.forbiddenCollisions().isEmpty())) { + return; + } + WorldVolume volume = WorldVolume.of(placement, prepared, context.output(PlacementStages.Anchor.HEIGHT).y() + prepared.randomY()); + if (collidesWithForbiddenObject(prepared.terrain(), settings, volume)) { + context.reject("object-collision"); + } + } + + private static boolean collidesWithForbiddenObject(StageTerrain terrain, PlacementSettings settings, WorldVolume volume) { + Set forbidden = settings.forbiddenCollisions(); + Set allowed = settings.allowedCollisions(); + for (int x = volume.minX(); x <= volume.maxX(); x++) { + for (int y = volume.minY(); y <= volume.maxY(); y++) { + for (int z = volume.minZ(); z <= volume.maxZ(); z++) { + Optional placed = terrain.objectAt(x, y, z); + if (placed.isPresent() && forbidden.contains(placed.get()) && !allowed.contains(placed.get())) { + return true; + } + } + } + } + return false; + } + + private static void warnImplausibleBedrockPlacement(RunningPlacement placement, PlacementSettings settings, int y, ModuleLog log) { + String key = placement.object().id().map(ResourceId::toString).orElse(null); + String fingerprint = (key == null ? "" : key) + "|" + settings.mode(); + long now = System.currentTimeMillis(); + Long last = IMPLAUSIBLE_BEDROCK_WARNS.get(fingerprint); + if (last != null && now - last < IMPLAUSIBLE_BEDROCK_WARN_THROTTLE_MS) { + return; + } + IMPLAUSIBLE_BEDROCK_WARNS.put(fingerprint, now); + log.warn("Implausible object placement rejected: " + + (key == null ? "" : key) + + " resolved anchorY=" + y + " at (" + placement.x() + "," + placement.z() + ") mode=" + settings.mode() + + " carving=" + settings.carvingSupport() + + ". Surface-anchored placement should never land on the bedrock row. " + + "Height sampling returned a bogus value — not configured for floor placement " + + "(forcePlace=false, fromBottom=false, mode!=FLOATING). Skipping to protect bedrock."); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java b/module/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java new file mode 100644 index 000000000..46ef966e0 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java @@ -0,0 +1,58 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.builtin.anchor.AnchorSampling; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; +import art.arcane.iris.builtin.prepare.TransformedBounds; + +/** + * The world blocks a placed object occupies, inclusive: its transformed bounds around the anchor. A painted + * object follows the surface column by column, so its volume spans every surface height under it. + */ +record WorldVolume(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { + static WorldVolume of(RunningPlacement placement, PreparedPlacement prepared, int anchorY) { + TransformedBounds bounds = prepared.bounds(); + int minX = placement.x() + bounds.minX(); + int maxX = placement.x() + bounds.maxX(); + int minZ = placement.z() + bounds.minZ(); + int maxZ = placement.z() + bounds.maxZ(); + if (!isPainted(placement, prepared)) { + return new WorldVolume(minX, maxX, anchorY + bounds.minY(), anchorY + bounds.maxY(), minZ, maxZ); + } + int lowestSurface = Integer.MAX_VALUE; + int highestSurface = Integer.MIN_VALUE; + for (int x = minX; x <= maxX; x++) { + for (int z = minZ; z <= maxZ; z++) { + int surface = prepared.terrain().highest(x, z, prepared.settings().underwater()); + lowestSurface = Math.min(lowestSurface, surface); + highestSurface = Math.max(highestSurface, surface); + } + } + int paintOffset = Math.floorDiv(placement.object().height(), 2); + return new WorldVolume(minX, maxX, lowestSurface + bounds.minY() + paintOffset, + highestSurface + bounds.maxY() + paintOffset, minZ, maxZ); + } + + /** Whether each block of the placement follows the surface of its own column. */ + static boolean isPainted(RunningPlacement placement, PreparedPlacement prepared) { + return placement.requestedY() < 0 && prepared.mode().anchor() == AnchorSampling.SURFACE; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java b/module/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java new file mode 100644 index 000000000..a1e726548 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java @@ -0,0 +1,139 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.structure; + +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.blocks.ObjectReplace; +import art.arcane.iris.builtin.loot.LootTable; +import art.arcane.iris.engine.object.KeyedResource; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcell; +import art.arcane.iris.engine.object.value.IrisPosition; +import art.arcane.iris.engine.object.annotations.ArrayType; +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.MaxNumber; +import art.arcane.iris.engine.object.annotations.MinNumber; +import art.arcane.iris.engine.object.annotations.RegistryListResource; +import art.arcane.iris.engine.object.annotations.RegistryListVanillaStructure; +import art.arcane.iris.engine.object.annotations.Required; +import art.arcane.volmlib.util.collection.KList; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A jigsaw structure. Starting from a pool, the assembler places a start piece and recursively attaches more pieces through matching connectors until it reaches the max depth or size. Pieces are Iris objects, so they carry the full object placement and block-control feature set.") +@Data +@EqualsAndHashCode(callSuper = false) +public class IrisStructure extends KeyedResource { + @Required + @RegistryListResource(IrisJigsawPool.class) + @Desc("The pool the assembler draws the start piece from.") + private String startPool = ""; + + @MinNumber(1) + @MaxNumber(30) + @Desc("The maximum jigsaw recursion depth. Larger values allow larger structures (e.g. villages) at the cost of generation time.") + private int maxDepth = 7; + + @MinNumber(1) + @MaxNumber(32) + @Desc("The maximum radius of the structure in chunks from its start piece. Acts as a hard bound on assembly size and collision checks.") + private int maxSizeChunks = 8; + + @Desc("Assembly topology. SPATIAL_JIGSAW preserves the existing freeform connector graph; PLANAR_JIGSAW declares a cell-aligned planar graph.") + private IrisJigsawMode mode = IrisJigsawMode.SPATIAL_JIGSAW; + + @Desc("Target compatibility contract for this structure. IRIS_EXTENDED permits Iris-only metadata; VANILLA_PORTABLE requires a graph that can be represented by vanilla jigsaw resources.") + private IrisJigsawCompatibility compatibility = IrisJigsawCompatibility.IRIS_EXTENDED; + + @Desc("How unresolved optional connector branches affect assembly. FAIL_ASSEMBLY preserves strict Iris behavior; TERMINATE_BRANCH matches vanilla jigsaw branch termination.") + private IrisJigsawBranchFailurePolicy branchFailurePolicy = IrisJigsawBranchFailurePolicy.FAIL_ASSEMBLY; + + @Desc("Default Studio cell dimensions. Legacy planar structures use this value for every workcell when planarWorkcells is empty.") + private IrisPosition cellSize = new IrisPosition(15, 15, 15); + + @Desc("Optional author-facing name for the single spatial Jigsaw Studio workcell. Spatial is shown when this is blank.") + private String spatialWorkcellDisplayName = ""; + + @ArrayType(type = IrisJigsawWorkcell.class) + @Desc("The six persistent planar Studio workcells. Leave empty only for the legacy cellSize fallback.") + private KList planarWorkcells = new KList<>(); + + @ArrayType(type = IrisJigsawThemeSet.class, min = 1) + @Desc("Weighted themes available to an assembly. Leave empty for one implicit unthemed assembly path.") + private KList themeSets = new KList<>(); + + @Desc("Whether every open connector must close with a real terminal piece through a mandatory direct fallback.") + private boolean requireCaps = false; + + @Desc("The place mode used when stamping each piece object into the world.") + private ObjectPlaceMode placeMode = ObjectPlaceMode.STRUCTURE_PIECE; + + @ArrayType(min = 1, type = ObjectReplace.class) + @Desc("Find-and-replace block edits applied to every piece of this structure, using the exact same syntax as an object's 'edit'. For example, replace stone bricks with obsidian.") + private KList edit = new KList<>(); + + @ArrayType(type = String.class, min = 1) + @RegistryListResource(LootTable.class) + @Desc("Loot tables applied to containers placed by this structure's pieces.") + private KList loot = new KList<>(); + + @RegistryListVanillaStructure + @Desc("If this structure was generated by importing a vanilla or datapack structure, this is that structure's key (provenance). Empty for hand-authored structures.") + private String vanillaSource = ""; + + /** Whether the structure's pieces are stamped where the assembler put them, as a vanilla jigsaw places them. */ + public boolean stampsPiecesWhereAssembled() { + return placeMode != null && placeMode.placeMode().has(PlaceTrait.RAW_STAMP); + } + + public IrisJigsawMode resolvedMode() { + return mode == null ? IrisJigsawMode.SPATIAL_JIGSAW : mode; + } + + public IrisJigsawCompatibility resolvedCompatibility() { + return compatibility == null ? IrisJigsawCompatibility.IRIS_EXTENDED : compatibility; + } + + public IrisJigsawBranchFailurePolicy resolvedBranchFailurePolicy() { + return branchFailurePolicy == null + ? IrisJigsawBranchFailurePolicy.FAIL_ASSEMBLY + : branchFailurePolicy; + } + + @Override + public String getFolderName() { + return "structures"; + } + + @Override + public String getTypeName() { + return "Structure"; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawBranchFailurePolicy.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawBranchFailurePolicy.java new file mode 100644 index 000000000..09bfb0b92 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawBranchFailurePolicy.java @@ -0,0 +1,12 @@ +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls how an Iris jigsaw assembly handles an optional connector branch that exhausts its primary pool and direct fallback without attaching a piece.") +public enum IrisJigsawBranchFailurePolicy { + @Desc("Fails the complete assembly when an optional connector branch cannot attach before the maximum depth.") + FAIL_ASSEMBLY, + + @Desc("Ends only the unresolved optional connector branch, matching vanilla jigsaw placement behavior.") + TERMINATE_BRANCH +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawCompatibility.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawCompatibility.java new file mode 100644 index 000000000..b8563a4cc --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawCompatibility.java @@ -0,0 +1,12 @@ +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Declares the resource compatibility target of an Iris jigsaw structure.") +public enum IrisJigsawCompatibility { + @Desc("Allows Iris-specific connector metadata and placement behavior.") + IRIS_EXTENDED, + + @Desc("Restricts the graph to metadata that can be represented by vanilla jigsaw resources.") + VANILLA_PORTABLE +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java new file mode 100644 index 000000000..dc99b49cc --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java @@ -0,0 +1,96 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.value.IrisPosition; +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.RegistryListResource; +import art.arcane.iris.engine.object.annotations.Required; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.util.Objects; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A jigsaw connection point on a piece. When two connectors face each other and their names match, the assembler may join the pieces.") +@Data +public class IrisJigsawConnector { + public static IrisPosition canonicalPlanarPosition(IrisPosition cellSize, IrisDirection direction) { + IrisPosition dimensions = Objects.requireNonNull(cellSize, "Planar jigsaw cell size"); + IrisDirection face = Objects.requireNonNull(direction, "Planar jigsaw connector direction"); + if (dimensions.getX() < 1 || dimensions.getY() < 1 || dimensions.getZ() < 1) { + throw new IllegalArgumentException("Planar jigsaw cell dimensions must be positive"); + } + int centerX = dimensions.getX() / 2; + int centerY = dimensions.getY() / 2; + int centerZ = dimensions.getZ() / 2; + return switch (face) { + case NORTH_NEGATIVE_Z -> new IrisPosition(centerX, centerY, 0); + case EAST_POSITIVE_X -> new IrisPosition(dimensions.getX() - 1, centerY, centerZ); + case SOUTH_POSITIVE_Z -> new IrisPosition(centerX, centerY, dimensions.getZ() - 1); + case WEST_NEGATIVE_X -> new IrisPosition(0, centerY, centerZ); + case UP_POSITIVE_Y, DOWN_NEGATIVE_Y -> throw new IllegalArgumentException( + "Planar jigsaw connector direction must be horizontal"); + }; + } + + @Required + @Desc("The position of this connector relative to the piece object's origin (0,0,0 is the lowest-corner of the object).") + private IrisPosition position = new IrisPosition(); + + @Required + @Desc("The direction this connector faces. The connecting piece is placed on this side.") + private IrisDirection direction = IrisDirection.NORTH_NEGATIVE_Z; + + @Required + @Desc("The connector's authored top direction, used to preserve aligned vanilla jigsaw orientation.") + private IrisDirection top = IrisDirection.UP_POSITIVE_Y; + + @Required + @RegistryListResource(IrisJigsawPool.class) + @Desc("The jigsaw pool to draw the connecting piece from.") + private String pool = ""; + + @Desc("The identity exposed by this connector. Another connector can attach when its targetName equals this name, matching Minecraft's jigsaw target-to-name contract.") + private String name = ""; + + @Desc("The name this connector wants to connect to on the other piece.") + private String targetName = ""; + + @Desc("Optional Iris-only connection channel. Matching is exact, case-sensitive, and whitespace-sensitive; empty channels match only other empty channels.") + private String channel = ""; + + @Desc("How the connecting piece may be rotated relative to this connector.") + private JigsawJoint joint = JigsawJoint.ROLLABLE; + + @Required + @Desc("Block state placed where this jigsaw marker was authored after assembly. Used when exporting or capturing Mojang-style jigsaw templates.") + private String finalState = "minecraft:air"; + + @Desc("Signed priority for selecting this connector within its piece. Higher values are processed before lower values; equal priorities preserve authored order.") + private int selectionPriority = 0; + + @Desc("Signed priority assigned to a child piece attached through this connector. Higher-priority child pieces expand first; equal priorities preserve attachment order.") + private int placementPriority = 0; +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawMode.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawMode.java new file mode 100644 index 000000000..34b79faa5 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawMode.java @@ -0,0 +1,12 @@ +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls the topology used by an Iris jigsaw structure.") +public enum IrisJigsawMode { + @Desc("A cell-aligned planar jigsaw intended for villages, paths, and other two-dimensional layouts.") + PLANAR_JIGSAW, + + @Desc("A freeform spatial connector graph intended for multi-level and three-dimensional structures.") + SPATIAL_JIGSAW +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java new file mode 100644 index 000000000..b123f3a0f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java @@ -0,0 +1,94 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.KeyedResource; +import com.volmit.object.GeneratedObject; +import art.arcane.iris.engine.object.annotations.ArrayType; +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.RegistryListResource; +import art.arcane.iris.engine.object.annotations.Required; +import art.arcane.volmlib.util.collection.KList; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A jigsaw piece. A piece is a single Iris object plus the connection points (connectors) that let the assembler attach other pieces to it.") +@Data +@EqualsAndHashCode(callSuper = false) +public class IrisJigsawPiece extends KeyedResource { + @Desc("Optional author-facing name shown by Jigsaw Studio. The resource key is shown when this is blank.") + private String displayName = ""; + + @Required + @RegistryListResource(GeneratedObject.class) + @Desc("The object (schematic) that makes up this piece.") + private String object = ""; + + @ArrayType(type = IrisJigsawConnector.class, min = 1) + @Desc("The jigsaw connection points on this piece.") + private KList connectors = new KList<>(); + + @Desc("If true, this piece may be rotated around the Y axis when placed so the assembler can match its connectors. Disable for pieces that must keep a fixed orientation.") + private boolean rotatable = true; + + @Desc("If true, this piece's object bounds block overlapping jigsaw pieces. Disable for connector-only scaffolds whose stored volume is intentionally shared with physical pieces.") + private boolean collidable = true; + + @ArrayType(type = String.class, min = 1) + @Desc("Theme keys that may select this piece. An empty list makes the piece available to every selected theme.") + private KList themes = new KList<>(); + + @Desc("Deterministic depth, placement-count, and terminal-role rules for this piece.") + private IrisJigsawPieceRules rules = new IrisJigsawPieceRules(); + + public boolean supportsTheme(String selectedTheme) { + if (themes == null || themes.isEmpty()) { + return true; + } + if (selectedTheme == null || selectedTheme.isBlank()) { + return false; + } + for (String theme : themes) { + if (selectedTheme.equals(theme)) { + return true; + } + } + return false; + } + + public IrisJigsawPieceRules resolvedRules() { + return rules == null ? new IrisJigsawPieceRules() : rules; + } + + @Override + public String getFolderName() { + return "jigsaw-pieces"; + } + + @Override + public String getTypeName() { + return "Jigsaw Piece"; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java new file mode 100644 index 000000000..c022d4de8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java @@ -0,0 +1,66 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.MaxNumber; +import art.arcane.iris.engine.object.annotations.MinNumber; +import art.arcane.iris.engine.object.annotations.RegistryListResource; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A weighted reference to a jigsaw piece inside a jigsaw pool.") +@Data +public class IrisJigsawPieceEntry { + @RegistryListResource(IrisJigsawPiece.class) + @Desc("The jigsaw piece this entry refers to. Omit when empty is true.") + private String piece; + + @MinNumber(1) + @Desc("The relative weight of this piece within its pool. Higher weights are chosen more often.") + private int weight = 1; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The independent eligibility chance applied to this exact pool membership before weighted selection. Zero never passes and one always passes.") + private double chance = 1D; + + @Desc("When true, choosing this entry successfully terminates the current branch without placing a piece.") + private boolean empty = false; + + public IrisJigsawPieceEntry(String piece, int weight) { + this(piece, weight, 1D, false); + } + + public boolean requiresChanceRoll() { + return chance > 0D && chance < 1D; + } + + public boolean passesChance(double roll) { + if (!Double.isFinite(roll) || roll < 0D || roll >= 1D) { + throw new IllegalArgumentException("Jigsaw chance roll must be finite and within 0 inclusive and 1 exclusive"); + } + return chance >= 1D || chance > 0D && roll < chance; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceRules.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceRules.java new file mode 100644 index 000000000..214cc9a4e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceRules.java @@ -0,0 +1,52 @@ +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.MaxNumber; +import art.arcane.iris.engine.object.annotations.MinNumber; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Deterministic eligibility, placement-count, and terminal-role rules for one jigsaw piece.") +@Data +public class IrisJigsawPieceRules { + @MinNumber(0) + @MaxNumber(30) + @Desc("The shallowest assembly depth at which this piece may be placed. The start piece is depth zero.") + private int minimumDepth = 0; + + @MinNumber(0) + @MaxNumber(30) + @Desc("The deepest assembly depth at which this piece may be placed.") + private int maximumDepth = 30; + + @MinNumber(0) + @MaxNumber(512) + @Desc("The minimum number of placements required for this piece in a completed assembly.") + private int minimumPlacements = 0; + + @MinNumber(0) + @MaxNumber(512) + @Desc("The maximum number of placements allowed for this piece. Zero means unbounded within the structure safety cap.") + private int maximumPlacements = 0; + + @Desc("Whether this piece is a physical terminal cap. A terminal piece may consume a matching connector but must not continue expansion.") + private boolean terminal = false; + + public boolean allowsDepth(int depth) { + return depth >= minimumDepth && depth <= maximumDepth; + } + + public boolean allowsPlacement(int existingPlacements) { + return existingPlacements >= 0 + && (maximumPlacements == 0 || existingPlacements < maximumPlacements); + } + + public boolean requiresMorePlacements(int existingPlacements) { + return existingPlacements >= 0 && existingPlacements < minimumPlacements; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java new file mode 100644 index 000000000..bc66b71b2 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java @@ -0,0 +1,63 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.KeyedResource; +import art.arcane.iris.engine.object.annotations.ArrayType; +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.RegistryListResource; +import art.arcane.volmlib.util.collection.KList; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A jigsaw pool. A pool is a weighted set of pieces the assembler chooses from when a connector targets this pool.") +@Data +@EqualsAndHashCode(callSuper = false) +public class IrisJigsawPool extends KeyedResource { + @ArrayType(type = IrisJigsawPieceEntry.class, min = 1) + @Desc("The weighted pieces in this pool.") + private KList pieces = new KList<>(); + + @RegistryListResource(IrisJigsawPool.class) + @Desc("The direct fallback pool tried after this pool, or used alone at maximum depth. The fallback pool's own fallback is not part of the same selection. Leave empty to stop expanding at maximum depth.") + private String fallback = ""; + + @Desc("Whether failure to place from this pool must be resolved through its direct fallback even when the structure does not require every branch to be capped.") + private boolean mandatoryFallback = false; + + public boolean requiresFallback(boolean structureRequiresCaps) { + return structureRequiresCaps || mandatoryFallback; + } + + @Override + public String getFolderName() { + return "jigsaw-pools"; + } + + @Override + public String getTypeName() { + return "Jigsaw Pool"; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawThemeSet.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawThemeSet.java new file mode 100644 index 000000000..c9ea75085 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawThemeSet.java @@ -0,0 +1,24 @@ +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.MinNumber; +import art.arcane.iris.engine.object.annotations.Required; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A weighted structure-wide jigsaw theme. One declared theme is selected for an assembly, and pieces may opt into one or more themes.") +@Data +public class IrisJigsawThemeSet { + @Required + @Desc("The exact theme key referenced by jigsaw pieces.") + private String key = ""; + + @MinNumber(1) + @Desc("The relative weight used when selecting one theme for an assembly.") + private int weight = 1; +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java new file mode 100644 index 000000000..e998e142e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java @@ -0,0 +1,40 @@ +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.MaxNumber; +import art.arcane.iris.engine.object.annotations.MinNumber; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Data +@Desc("Persistent authoring bounds and runtime availability for one planar jigsaw workcell.") +public class IrisJigsawWorkcell { + @Desc("Optional author-facing name shown by Jigsaw Studio. The canonical archetype name is shown when this is blank.") + private String displayName = ""; + + @Desc("The orientation-independent planar connector shape configured by this workcell.") + private IrisJigsawWorkcellArchetype archetype = IrisJigsawWorkcellArchetype.BLANK; + + @MinNumber(3) + @MaxNumber(128) + @Desc("The maximum canonical variant width that this workcell can contain, in blocks.") + private int width = 16; + + @MinNumber(1) + @MaxNumber(192) + @Desc("The maximum variant height that this workcell can contain, in blocks.") + private int height = 16; + + @MinNumber(3) + @MaxNumber(128) + @Desc("The maximum canonical variant depth that this workcell can contain, in blocks.") + private int depth = 16; + + @Desc("Whether pieces with this planar connector shape participate in assembly and vanilla export.") + private boolean enabled = true; +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java new file mode 100644 index 000000000..4275be726 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java @@ -0,0 +1,88 @@ +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("The orientation-independent connector shape represented by a planar jigsaw workcell.") +public enum IrisJigsawWorkcellArchetype { + @Desc("Pieces with no horizontal connectors: sealed filler cells that terminate nothing and are excluded from the default piece pool.") + BLANK(0), + + @Desc("One-connector dead-end pieces; the Studio bay seeds a single north connector and new projects mark these as terminal caps.") + END(1), + + @Desc("Two-connector pass-through pieces with openings on opposite sides; the Studio bay seeds north and south connectors.") + STRAIGHT(5), + + @Desc("Two-connector right-angle pieces with openings on adjacent sides; the Studio bay seeds north and east connectors.") + CORNER(3), + + @Desc("Three-connector junction pieces; the Studio bay seeds north, east, and west connectors.") + TEE(11), + + @Desc("Four-connector pieces open on all sides; new projects use this archetype as the structure's start piece.") + CROSS(15); + + private final int canonicalMask; + + IrisJigsawWorkcellArchetype(int canonicalMask) { + this.canonicalMask = canonicalMask; + } + + public static IrisJigsawWorkcellArchetype fromPiece(IrisJigsawPiece piece) { + if (piece == null || piece.getConnectors() == null) { + return BLANK; + } + return fromMask(horizontalMask(piece)); + } + + public static IrisJigsawWorkcellArchetype fromMask(int mask) { + if (mask < 0 || mask > 15) { + throw new IllegalArgumentException("Planar jigsaw topology mask must be between 0 and 15"); + } + int connections = Integer.bitCount(mask); + return switch (connections) { + case 0 -> BLANK; + case 1 -> END; + case 2 -> mask == 5 || mask == 10 ? STRAIGHT : CORNER; + case 3 -> TEE; + case 4 -> CROSS; + default -> throw new IllegalStateException("Unreachable planar jigsaw topology"); + }; + } + + public static int horizontalMask(IrisJigsawPiece piece) { + if (piece == null || piece.getConnectors() == null) { + return 0; + } + int mask = 0; + for (IrisJigsawConnector connector : piece.getConnectors()) { + if (connector == null || connector.getDirection() == null) { + continue; + } + mask |= switch (connector.getDirection()) { + case NORTH_NEGATIVE_Z -> 1; + case EAST_POSITIVE_X -> 2; + case SOUTH_POSITIVE_Z -> 4; + case WEST_NEGATIVE_X -> 8; + case UP_POSITIVE_Y, DOWN_NEGATIVE_Y -> 0; + }; + } + return mask; + } + + public int sourceToCanonicalQuarterTurns(IrisJigsawPiece piece) { + int sourceMask = horizontalMask(piece); + if (fromMask(sourceMask) != this) { + throw new IllegalArgumentException("Jigsaw piece does not match workcell archetype " + name()); + } + for (int quarterTurns = 0; quarterTurns < 4; quarterTurns++) { + int rotated = quarterTurns == 0 + ? sourceMask + : ((sourceMask << quarterTurns) | (sourceMask >>> (4 - quarterTurns))) & 15; + if (rotated == canonicalMask) { + return quarterTurns; + } + } + throw new IllegalStateException("No canonical rotation exists for planar jigsaw piece"); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/JigsawJoint.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/JigsawJoint.java new file mode 100644 index 000000000..851d5a251 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/JigsawJoint.java @@ -0,0 +1,30 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("How a jigsaw connection may be rotated when matching two pieces together.") +public enum JigsawJoint { + @Desc("The connecting piece may rotate freely around the connection axis. Use this for vertical connectors (floors, ceilings) and any joint where roll does not matter.") + ROLLABLE, + + @Desc("The connecting piece's rotation is locked to face the connector. Use this for horizontal connectors where the attached piece must align to a specific facing (doorways, street ends).") + ALIGNED +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarveResult.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarveResult.java new file mode 100644 index 000000000..3549f586d --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarveResult.java @@ -0,0 +1,34 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.terrain.carving; + +import lombok.Value; + +@SuppressWarnings("ClassCanBeRecord") +@Value +public class CarveResult { + @SuppressWarnings("RedundantModifiersValueLombok") + private final int surface; + @SuppressWarnings("RedundantModifiersValueLombok") + private final int ceiling; + + public int getHeight() { + return ceiling - surface; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java new file mode 100644 index 000000000..4a598c434 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java @@ -0,0 +1,310 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.terrain.carving; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.modules.carve.CarvingEntry; +import art.arcane.iris.modules.carve.CarvingSettings; +import com.volmit.ModuleLog; +import com.volmit.config.Range; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.PackResources; +import com.volmit.world.PackBiome; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** + * What the carve module keeps for one world about the cave biome bands its dimension declares ({@link CarvingSettings}): the + * entries made ready ({@link ResolvedCarvingEntry}), in the order the dimension lists them and by id, and the picks among them. + * A pick is the dimension's last enabled root entry whose world Y band holds a height, then, through the entries' children, the + * one a noise pattern selects at a column. + */ +public final class CarvingResolver { + private static final int MAX_CHILD_DEPTH = 32; + private static final long CHILD_SEED_SALT = 0x9E3779B97F4A7C15L; + + private final PackResources resources; + private final ModuleLog log; + private final int minHeight; + private final long childSeed; + private final List entries; + private final Map index; + private final Map> rootEntriesByWorldY = new ConcurrentHashMap<>(); + private final Map selectionPlans = new ConcurrentHashMap<>(); + + CarvingResolver(PackWorld world, List declared) { + this.resources = world.resources(); + this.log = world.log(); + this.minHeight = world.minWorldY(); + this.childSeed = world.seed(IrisSeedPurposes.CARVE) ^ CHILD_SEED_SALT; + this.entries = declared.stream().filter(Objects::nonNull).map(ResolvedCarvingEntry::new).toList(); + this.index = indexById(entries); + } + + /** The bands of the world {@code world} generates now. */ + public static CarvingResolver of(PackWorld world) { + return world.state(CarvingResolver.class, generating -> new CarvingResolver(generating, dimensionEntries(generating))); + } + + private static List dimensionEntries(PackWorld world) { + return world.settings().declared(CarvingSettings.class).dimension().map(CarvingSettings::entries).orElse(List.of()); + } + + /** Every declared entry, enabled or not. */ + public List entries() { + return entries; + } + + /** The entries by their trimmed ids; entries without an id are not in it, and the last of several with one id is. */ + public Map index() { + return index; + } + + /** The root entry for a height above the dimension's bottom; null where no enabled entry with a biome holds it. */ + public ResolvedCarvingEntry rootEntryAt(int y) { + return rootEntryAtWorldY(y + minHeight); + } + + /** The root entry for a world Y as packs write them; null where no enabled entry with a biome holds it. */ + public ResolvedCarvingEntry rootEntryAtWorldY(int worldY) { + return rootEntriesByWorldY.computeIfAbsent(worldY, this::pickRootEntry).orElse(null); + } + + private Optional pickRootEntry(int worldY) { + ResolvedCarvingEntry resolved = null; + for (ResolvedCarvingEntry entry : entries) { + if (isRootCandidate(entry, worldY)) { + resolved = entry; + } + } + return Optional.ofNullable(resolved); + } + + public ResolvedCarvingEntry resolveFromRoot(ResolvedCarvingEntry rootEntry, int worldX, int worldZ) { + if (rootEntry == null) { + return null; + } + + PackBiome rootBiome = entryBiome(rootEntry); + if (rootBiome == null) { + return null; + } + + int remainingDepth = clampDepth(rootEntry.childRecursionDepth()); + if (remainingDepth <= 0) { + return rootEntry; + } + + ResolvedCarvingEntry current = rootEntry; + int depth = remainingDepth; + while (depth > 0) { + ResolvedCarvingEntry selected = selectChild(current, worldX, worldZ); + if (selected == null || selected == current) { + break; + } + + depth--; + int childDepthLimit = clampDepth(selected.childRecursionDepth()); + if (childDepthLimit < depth) { + depth = childDepthLimit; + } + current = selected; + } + + return current; + } + + /** The pack biome the entry names; null when it names none or the pack has no such biome. */ + public PackBiome entryBiome(ResolvedCarvingEntry entry) { + return entry == null ? null : entry.realBiome(resources, log); + } + + private boolean isRootCandidate(ResolvedCarvingEntry entry, int worldY) { + if (entry == null || !entry.enabled()) { + return false; + } + + Range worldYRange = entry.worldYRange(); + if (worldYRange != null && !worldYRange.contains(worldY)) { + return false; + } + + return entryBiome(entry) != null; + } + + private ResolvedCarvingEntry selectChild(ResolvedCarvingEntry parent, int worldX, int worldZ) { + List children = parent.children(); + if (children.isEmpty()) { + return parent; + } + + PackBiome parentBiome = entryBiome(parent); + if (parentBiome == null) { + return parent; + } + + ParentSelectionPlan selectionPlan = selectionPlans.computeIfAbsent(parent, key -> buildSelectionPlan(key, parentBiome)); + if (selectionPlan.parentOnly) { + return parent; + } + + NoiseSampler childGenerator = parent.childrenGenerator(childSeed, resources); + double sample = childGenerator.sample(worldX, worldZ); + int selectedIndex = (int) Math.round(sample * selectionPlan.maxIndex); + CarvingChoice selected = selectionPlan.get(selectedIndex); + if (selected == null || selected.entry == null) { + return parent; + } + + return selected.entry; + } + + private ParentSelectionPlan buildSelectionPlan(ResolvedCarvingEntry parent, PackBiome parentBiome) { + List options = new ArrayList<>(); + for (String childId : parent.children()) { + if (childId == null || childId.isBlank()) { + continue; + } + + ResolvedCarvingEntry child = index.get(childId.trim()); + if (child == null || !child.enabled()) { + continue; + } + + PackBiome childBiome = entryBiome(child); + if (childBiome == null) { + continue; + } + + options.add(new CarvingChoice(child, rarity(childBiome))); + } + + options.add(new CarvingChoice(parent, rarity(parentBiome))); + if (options.size() <= 1) { + return ParentSelectionPlan.parentOnly(); + } + + CarvingChoice[] mappedChoices = buildRarityMappedChoices(options); + if (mappedChoices.length == 0) { + return ParentSelectionPlan.parentOnly(); + } + + return new ParentSelectionPlan(mappedChoices); + } + + private static CarvingChoice[] buildRarityMappedChoices(List choices) { + int max = 1; + for (CarvingChoice choice : choices) { + if (choice.rarity > max) { + max = choice.rarity; + } + } + + max++; + List mapped = new ArrayList<>(); + boolean flip = false; + for (CarvingChoice choice : choices) { + int count = max - choice.rarity; + for (int index = 0; index < count; index++) { + flip = !flip; + if (flip) { + mapped.add(choice); + } else { + mapped.add(0, choice); + } + } + } + + return mapped.toArray(new CarvingChoice[0]); + } + + private static int rarity(PackBiome biome) { + if (biome == null) { + return 1; + } + + return Math.max(biome.rarity(), 1); + } + + private static int clampDepth(int depth) { + if (depth <= 0) { + return 0; + } + + return Math.min(depth, MAX_CHILD_DEPTH); + } + + private static Map indexById(List entries) { + Map index = new HashMap<>(); + for (ResolvedCarvingEntry entry : entries) { + if (!entry.id().isBlank()) { + index.put(entry.id().trim(), entry); + } + } + return Map.copyOf(index); + } + + private static final class ParentSelectionPlan { + private final CarvingChoice[] mappedChoices; + private final int maxIndex; + private final boolean parentOnly; + + private ParentSelectionPlan(CarvingChoice[] mappedChoices) { + this.mappedChoices = mappedChoices; + this.maxIndex = mappedChoices.length - 1; + this.parentOnly = false; + } + + private ParentSelectionPlan() { + this.mappedChoices = null; + this.maxIndex = -1; + this.parentOnly = true; + } + + private static ParentSelectionPlan parentOnly() { + return new ParentSelectionPlan(); + } + + private CarvingChoice get(int index) { + if (mappedChoices == null || mappedChoices.length == 0) { + return null; + } + + if (index < 0) { + return mappedChoices[0]; + } + + if (index >= mappedChoices.length) { + return mappedChoices[mappedChoices.length - 1]; + } + + return mappedChoices[index]; + } + } + + private record CarvingChoice(ResolvedCarvingEntry entry, int rarity) { + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java new file mode 100644 index 000000000..2ef0abc12 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java @@ -0,0 +1,178 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.terrain.carving; + +import art.arcane.iris.builtin.carve.CaveFieldModule; +import art.arcane.iris.modules.carve.CaveProfile; +import art.arcane.volmlib.util.math.M; +import com.volmit.config.Range; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; +import com.volmit.noise.StyledRange; + +import java.util.ArrayList; +import java.util.List; + +public final class CaveProfileSampler { + private static final double FLOATING_THRESHOLD_BIAS_SCALE = 0.2D; + + private final CaveProfile profile; + private final NoiseSampler baseDensity; + private final NoiseSampler detailDensity; + private final NoiseSampler warpDensity; + private final NoiseSampler thresholdNoise; + private final ModuleState[] modules; + private final double inverseNormalization; + private final double baseWeight; + private final double detailWeight; + private final double warpStrength; + private final boolean enabled; + private final boolean hasWarp; + private final boolean hasModules; + + public CaveProfileSampler(NoiseFactory noise, long carveSeed, CaveProfile profile) { + this.profile = profile; + List moduleStates = new ArrayList<>(); + this.baseDensity = noise.sampler(profile.baseDensityStyle(), carveSeed + 934_447); + this.detailDensity = noise.sampler(profile.detailDensityStyle(), carveSeed + 612_991); + this.warpDensity = noise.sampler(profile.warpStyle(), carveSeed + 770_713); + this.thresholdNoise = noise.sampler(profile.densityThreshold().style(), carveSeed + 489_112); + this.baseWeight = profile.baseWeight(); + this.detailWeight = profile.detailWeight(); + this.warpStrength = profile.warpStrength(); + this.hasWarp = warpStrength > 0D; + + double weight = Math.abs(baseWeight) + Math.abs(detailWeight); + int index = 0; + for (CaveFieldModule module : profile.modules()) { + NoiseSampler moduleDensity = noise.sampler(module.style(), carveSeed + 1_000_003L + (index * 65_537L)); + ModuleState state = new ModuleState(module, moduleDensity); + moduleStates.add(state); + weight += Math.abs(state.weight); + index++; + } + + this.modules = moduleStates.toArray(new ModuleState[0]); + double normalization = weight <= 0 ? 1D : weight; + this.inverseNormalization = 1D / normalization; + this.hasModules = modules.length > 0; + this.enabled = profile.enabled(); + } + + public boolean shouldCarve(int x, int y, int z, double floatingCarveThreshold) { + if (!enabled) { + return false; + } + + double threshold = thresholdAt(x, z) - profile.thresholdBias(); + threshold += floatingThresholdBias(floatingCarveThreshold); + return sampleDensity(x, y, z) <= threshold; + } + + /** The profile's density threshold at the column, as a styled range picks its value. */ + private double thresholdAt(int x, int z) { + StyledRange range = profile.densityThreshold(); + if (range.min() == range.max()) { + return range.min(); + } + if (NoiseStyle.FLAT.equals(range.style().style())) { + return M.lerp(range.min(), range.max(), 0.5); + } + return range.min() + (thresholdNoise.sample(x, z) * (range.max() - range.min())); + } + + double sampleDensity(int x, int y, int z) { + if (hasWarp) { + return sampleDensityWarped(x, y, z); + } + + return sampleDensityUnwarped(x, y, z); + } + + private double sampleDensityUnwarped(int x, int y, int z) { + double density = baseDensity.signed(x, y, z) * baseWeight; + density += detailDensity.signed(x, y, z) * detailWeight; + if (hasModules) { + for (ModuleState module : modules) { + if (!module.isActive(y)) { + continue; + } + + density += module.sample(x, y, z); + } + } + + return density * inverseNormalization; + } + + private double sampleDensityWarped(int x, int y, int z) { + double warpA = warpDensity.signed(x, y, z); + double warpB = warpDensity.signed(x + 31.37D, y - 17.21D, z + 23.91D); + double warpedX = x + (warpA * warpStrength); + double warpedY = y + (warpB * warpStrength); + double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; + if (hasModules) { + for (ModuleState module : modules) { + if (!module.isActive(y)) { + continue; + } + + density += module.sample(warpedX, warpedY, warpedZ); + } + } + + return density * inverseNormalization; + } + + private double floatingThresholdBias(double floatingCarveThreshold) { + double clamped = Math.max(0D, Math.min(1D, floatingCarveThreshold)); + return (1D - clamped) * FLOATING_THRESHOLD_BIAS_SCALE; + } + + private static final class ModuleState { + private final NoiseSampler density; + private final int minY; + private final int maxY; + private final double weight; + private final double threshold; + private final boolean invert; + + private ModuleState(CaveFieldModule module, NoiseSampler density) { + Range range = module.verticalRange(); + this.density = density; + this.minY = (int) Math.floor(range.min()); + this.maxY = (int) Math.ceil(range.max()); + this.weight = module.weight(); + this.threshold = module.threshold(); + this.invert = module.invert(); + } + + private boolean isActive(int y) { + return density != null && y >= minY && y <= maxY; + } + + private double sample(double x, double y, double z) { + double sampled = density.signed(x, y, z); + return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveResult.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveResult.java new file mode 100644 index 000000000..ecf7aaac3 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveResult.java @@ -0,0 +1,36 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.terrain.carving; + +import lombok.Data; + +@Data +public class CaveResult { + private int floor; + private int ceiling; + + public CaveResult(int floor, int ceiling) { + this.floor = floor; + this.ceiling = ceiling; + } + + public boolean isWithin(int v) { + return v > floor || v < ceiling; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java new file mode 100644 index 000000000..dd92f3c57 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java @@ -0,0 +1,82 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.terrain.carving; + +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.HashMap; +import java.util.Map; + +/** + * The settings of one type that a world's dimension, regions and biomes declare, found again by the id region and biome + * samples carry ({@code overworld:desert/dunes}), which is how the layout names the region or biome of a column. A settings + * entry names its source by kind ({@code overworld:biome/desert/dunes}), so the kind is taken off the id. + * + *

Only the regions and biomes the dimension reaches declare anything here ({@link com.volmit.config.PackSettings#declared}). + */ +public final class DeclaredByLevel { + private final F dimension; + private final Map regions; + private final Map biomes; + + private DeclaredByLevel(F dimension, Map regions, Map biomes) { + this.dimension = dimension; + this.regions = Map.copyOf(regions); + this.biomes = Map.copyOf(biomes); + } + + public static DeclaredByLevel of(PackWorld world, Class type) { + SettingsStack declared = world.settings().declared(type); + Map regions = new HashMap<>(); + Map biomes = new HashMap<>(); + for (Entry entry : declared) { + if (entry.level() == Level.REGION) { + regions.putIfAbsent(sampleId(entry.source()), entry.value()); + } else if (entry.level() == Level.BIOME) { + biomes.putIfAbsent(sampleId(entry.source()), entry.value()); + } + } + return new DeclaredByLevel<>(declared.dimension().orElse(null), regions, biomes); + } + + /** The dimension's declaration; null when it declares none. */ + public F ofDimension() { + return dimension; + } + + /** The declaration of the region with this id; null when it declares none. */ + public F ofRegion(ResourceId region) { + return regions.get(region); + } + + /** The declaration of the biome with this id; null when it declares none. */ + public F ofBiome(ResourceId biome) { + return biomes.get(biome); + } + + private static ResourceId sampleId(ResourceId source) { + String path = source.path(); + return new ResourceId(source.namespace(), path.substring(path.indexOf('/') + 1)); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java new file mode 100644 index 000000000..b0d132f78 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java @@ -0,0 +1,52 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.terrain.carving; + +import art.arcane.iris.modules.carve.CaveProfile; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +/** + * What the carve module keeps for one world: the cave profiles its dimension, regions and biomes declare ({@code caveProfile}). + * A profile that is not declared is as good as one that is not enabled, so the lookups answer null for it. + */ +public final class DeclaredCaveProfiles { + private final DeclaredByLevel declared; + + private DeclaredCaveProfiles(PackWorld world) { + this.declared = DeclaredByLevel.of(world, CaveProfile.class); + } + + /** The profiles of the world {@code world}. */ + public static DeclaredCaveProfiles of(PackWorld world) { + return world.state(DeclaredCaveProfiles.class, DeclaredCaveProfiles::new); + } + + public CaveProfile ofDimension() { + return declared.ofDimension(); + } + + public CaveProfile ofRegion(ResourceId region) { + return declared.ofRegion(region); + } + + public CaveProfile ofBiome(ResourceId biome) { + return declared.ofBiome(biome); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java new file mode 100644 index 000000000..d47f11e93 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java @@ -0,0 +1,104 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.terrain.carving; + +import art.arcane.iris.modules.carve.CarvingEntry; +import art.arcane.volmlib.util.cache.AtomicCache; +import com.volmit.ModuleLog; +import com.volmit.config.Range; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.PackResources; +import com.volmit.world.PackBiome; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * One {@link CarvingEntry} made ready for one world: the biome it names, found in the pack when first asked for, and the + * noise that splits it into child entries, built once per seed. What the entry describes stays in the settings. + */ +public final class ResolvedCarvingEntry { + private static final long CHILD_GENERATOR_SALT = 2137L; + private static final int CHILD_GENERATOR_SIGNATURE = 2137; + private static final double MIN_CHILD_SCALE = 0.0001D; + + private final CarvingEntry settings; + private final AtomicCache realBiome = new AtomicCache<>(true); + private final Map childGenerators = new ConcurrentHashMap<>(); + + ResolvedCarvingEntry(CarvingEntry settings) { + this.settings = settings; + } + + public String id() { + return settings.id(); + } + + public boolean enabled() { + return settings.enabled(); + } + + /** The biome key the entry names, as the pack wrote it. */ + public String biomeKey() { + return settings.biome(); + } + + public Range worldYRange() { + return settings.worldYRange(); + } + + public List children() { + return settings.children(); + } + + public int childRecursionDepth() { + return settings.childRecursionDepth(); + } + + /** The pack biome the entry names; null when it names none or the pack has no such biome. */ + public PackBiome realBiome(PackResources resources, ModuleLog log) { + return realBiome.aquire(() -> { + String biomeKey = settings.biome(); + if (biomeKey.isBlank()) { + return null; + } + + try { + return resources.find(PackResources.BIOMES, resources.idOf(biomeKey.trim())).orElse(null); + } catch (IllegalStateException unreadable) { + log.warnOnce("carving-biome:" + biomeKey, "The biome " + biomeKey + " of a carving entry cannot be loaded: " + unreadable.getMessage()); + return null; + } + }); + } + + /** The noise that picks between the entry and its children, seeded by {@code seed} and the entry's id. */ + public NoiseSampler childrenGenerator(long seed, PackResources resources) { + long idHash = settings.id().trim().hashCode(); + long generatorSeed = seed ^ (idHash << 32) ^ CHILD_GENERATOR_SALT; + return childGenerators.computeIfAbsent(generatorSeed, key -> { + NoiseSampler children = resources.noise().sampler(settings.childStyle(), key + CHILD_GENERATOR_SIGNATURE); + if (settings.childStyle().isSeeded()) { + return children; + } + return children.scaled(Math.max(MIN_CHILD_SCALE, settings.childShrinkFactor())); + }); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/Column.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/Column.java new file mode 100644 index 000000000..94cd6f352 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/Column.java @@ -0,0 +1,25 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.object.terrain.floating; + +/** + * A world column as a hash key. A long packing both coordinates would hash to {@code x ^ z} as a {@code Long}, which + * puts every diagonal of a chunk into one bucket. + */ +public record Column(int x, int z) { +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java new file mode 100644 index 000000000..02f5d9234 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java @@ -0,0 +1,624 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.terrain.floating; + +import art.arcane.volmlib.util.cache.CacheKey; +import art.arcane.volmlib.util.collection.KList; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.ResourceId; + +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; + +public final class FloatingIslandBoundarySampler { + static final int EDGE_TAPER_WIDTH = FloatingIslandEdgeProfile.DEFAULT_WIDTH; + static final int EDGE_FADE_RADIUS = EDGE_TAPER_WIDTH + 1; + private static final int CHUNK_SIZE = 16; + private static final int MIN_CORE_DISTANCE = 3; + + private final BiomeSampler source; + private final ConcurrentHashMap parentFields; + private final ConcurrentHashMap footprintFields; + private final ConcurrentHashMap ownershipFields; + + public FloatingIslandBoundarySampler(BiomeSampler source) { + this.source = Objects.requireNonNull(source); + this.parentFields = new ConcurrentHashMap<>(); + this.footprintFields = new ConcurrentHashMap<>(); + this.ownershipFields = new ConcurrentHashMap<>(); + } + + public ResourceId parent(int x, int z) { + return parentField(x, z, EDGE_TAPER_WIDTH).parent(x, z); + } + + public double edgeFade(ResourceId parent, int x, int z) { + return edgeFade(parent, x, z, EDGE_TAPER_WIDTH); + } + + public double edgeFade(ResourceId parent, int x, int z, int taperWidth) { + int boundaryDistance = edgeDistance(parent, x, z, taperWidth); + return edgeFadeForDistance(boundaryDistance, taperWidth); + } + + public int edgeDistance(ResourceId parent, int x, int z, int taperWidth) { + if (parent == null) { + return 0; + } + + return parentField(x, z, taperWidth).edgeDistance(parent, x, z); + } + + public FootprintSample footprint(NoiseSampler footprint, int x, int z, double signedCut) { + return footprint(footprint, x, z, signedCut, EDGE_TAPER_WIDTH); + } + + public FootprintSample footprint(NoiseSampler footprint, int x, int z, double signedCut, int taperWidth) { + int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); + int chunkX = Math.floorDiv(x, CHUNK_SIZE); + int chunkZ = Math.floorDiv(z, CHUNK_SIZE); + FootprintFieldKey key = new FootprintFieldKey( + footprint, chunkX, chunkZ, Double.doubleToLongBits(signedCut), width); + FootprintField field = footprintFields.computeIfAbsent(key, + ignored -> new FootprintField(footprint, chunkX, chunkZ, signedCut, width)); + return field.sample(x, z); + } + + public OwnershipSample ownership(KList entries, NoiseSampler picker, int x, int z) { + return ownership(entries, picker, x, z, EDGE_TAPER_WIDTH); + } + + public OwnershipSample ownership(KList entries, NoiseSampler picker, int x, int z, + int taperWidth) { + int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); + int chunkX = Math.floorDiv(x, CHUNK_SIZE); + int chunkZ = Math.floorDiv(z, CHUNK_SIZE); + OwnershipFieldKey key = new OwnershipFieldKey(entries, picker, chunkX, chunkZ, width); + OwnershipField field = ownershipFields.computeIfAbsent(key, + ignored -> new OwnershipField(entries, picker, chunkX, chunkZ, width)); + return field.sample(x, z); + } + + static double edgeFadeForDistance(int boundaryDistance) { + return edgeFadeForDistance(boundaryDistance, EDGE_TAPER_WIDTH); + } + + static double edgeFadeForDistance(int boundaryDistance, int taperWidth) { + int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); + double normalized = Math.max(0.0D, Math.min(1.0D, (boundaryDistance - 1.0D) / width)); + return normalized * normalized * (3.0D - (2.0D * normalized)); + } + + private ParentBoundaryField parentField(int x, int z, int taperWidth) { + int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); + int chunkX = Math.floorDiv(x, CHUNK_SIZE); + int chunkZ = Math.floorDiv(z, CHUNK_SIZE); + ParentFieldKey key = new ParentFieldKey(CacheKey.key(chunkX, chunkZ), width); + return parentFields.computeIfAbsent(key, + ignored -> new ParentBoundaryField(source, chunkX, chunkZ, width)); + } + + private static boolean sameBiome(ResourceId expected, ResourceId actual) { + if (actual == expected) { + return true; + } + if (expected == null || actual == null) { + return false; + } + return expected.equals(actual); + } + + public record FootprintSample(double signed, int cardinalSupport, int diagonalSupport, boolean accepted, + int boundaryDistance, double edgeFade) { + } + + public record OwnershipSample(ResolvedFloatingChild owner, int boundaryDistance, double edgeFade) { + } + + private record ParentFieldKey(long chunkKey, int taperWidth) { + } + + private static final class FootprintFieldKey { + private final NoiseSampler footprint; + private final int chunkX; + private final int chunkZ; + private final long signedCutBits; + private final int taperWidth; + + private FootprintFieldKey(NoiseSampler footprint, int chunkX, int chunkZ, long signedCutBits, int taperWidth) { + this.footprint = footprint; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + this.signedCutBits = signedCutBits; + this.taperWidth = taperWidth; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof FootprintFieldKey key)) { + return false; + } + return footprint == key.footprint && chunkX == key.chunkX && chunkZ == key.chunkZ + && signedCutBits == key.signedCutBits && taperWidth == key.taperWidth; + } + + @Override + public int hashCode() { + int result = System.identityHashCode(footprint); + result = (31 * result) + chunkX; + result = (31 * result) + chunkZ; + result = (31 * result) + Long.hashCode(signedCutBits); + return (31 * result) + taperWidth; + } + } + + private static final class OwnershipFieldKey { + private final KList entries; + private final NoiseSampler picker; + private final int chunkX; + private final int chunkZ; + private final int taperWidth; + + private OwnershipFieldKey(KList entries, NoiseSampler picker, int chunkX, int chunkZ, + int taperWidth) { + this.entries = entries; + this.picker = picker; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + this.taperWidth = taperWidth; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof OwnershipFieldKey key)) { + return false; + } + return entries == key.entries && picker == key.picker && chunkX == key.chunkX && chunkZ == key.chunkZ + && taperWidth == key.taperWidth; + } + + @Override + public int hashCode() { + int result = System.identityHashCode(entries); + result = (31 * result) + System.identityHashCode(picker); + result = (31 * result) + chunkX; + result = (31 * result) + chunkZ; + return (31 * result) + taperWidth; + } + } + + private static final class ParentBoundaryField { + private final FieldGeometry geometry; + private final int minX; + private final int minZ; + private final ResourceId[] parents; + private final byte[] distance; + private final boolean[] viable; + + private ParentBoundaryField(BiomeSampler source, int chunkX, int chunkZ, int taperWidth) { + this.geometry = FieldGeometry.forWidth(taperWidth); + this.minX = (chunkX * CHUNK_SIZE) - geometry.fadeRadius(); + this.minZ = (chunkZ * CHUNK_SIZE) - geometry.fadeRadius(); + this.parents = new ResourceId[geometry.area()]; + this.distance = new byte[geometry.area()]; + this.viable = new boolean[geometry.area()]; + build(source); + } + + private ResourceId parent(int x, int z) { + return parents[geometry.index(x - minX, z - minZ)]; + } + + private int edgeDistance(ResourceId expected, int x, int z) { + int index = geometry.index(x - minX, z - minZ); + if (!sameBiome(expected, parents[index]) || !viable[index]) { + return 0; + } + return Math.min(geometry.maxRenderableDistance(), Byte.toUnsignedInt(distance[index])); + } + + private void build(BiomeSampler source) { + int rawSize = geometry.fieldSize() + 2; + ResourceId[] raw = new ResourceId[rawSize * rawSize]; + int rawMinX = minX - 1; + int rawMinZ = minZ - 1; + for (int z = 0; z < rawSize; z++) { + for (int x = 0; x < rawSize; x++) { + raw[rawIndex(x, z, rawSize)] = source.sample(rawMinX + x, rawMinZ + z); + } + } + for (int z = 0; z < geometry.fieldSize(); z++) { + for (int x = 0; x < geometry.fieldSize(); x++) { + int index = geometry.index(x, z); + ResourceId parent = raw[rawIndex(x + 1, z + 1, rawSize)]; + parents[index] = parent; + distance[index] = (byte) (touchesDifferentBiome(raw, parent, x, z, rawSize) + ? 1 + : geometry.maxDistance()); + } + } + propagateDistanceField(distance, geometry); + markLabelCoreSupported(parents, distance, viable, geometry); + } + + private static boolean touchesDifferentBiome(ResourceId[] raw, ResourceId parent, int x, int z, + int rawSize) { + for (int dz = -1; dz <= 1; dz++) { + for (int dx = -1; dx <= 1; dx++) { + if (dx == 0 && dz == 0) { + continue; + } + if (!sameBiome(parent, raw[rawIndex(x + dx + 1, z + dz + 1, rawSize)])) { + return true; + } + } + } + return false; + } + + private static int rawIndex(int x, int z, int rawSize) { + return (z * rawSize) + x; + } + } + + private static final class FootprintField { + private final FieldGeometry geometry; + private final int occupancyMinX; + private final int occupancyMinZ; + private final double[] signed; + private final byte[] cardinalSupport; + private final byte[] diagonalSupport; + private final boolean[] accepted; + private final byte[] distance; + private final boolean[] viable; + + private FootprintField(NoiseSampler footprint, int chunkX, int chunkZ, double signedCut, int taperWidth) { + this.geometry = FieldGeometry.forWidth(taperWidth); + this.occupancyMinX = (chunkX * CHUNK_SIZE) - geometry.fadeRadius(); + this.occupancyMinZ = (chunkZ * CHUNK_SIZE) - geometry.fadeRadius(); + this.signed = new double[geometry.area()]; + this.cardinalSupport = new byte[geometry.area()]; + this.diagonalSupport = new byte[geometry.area()]; + this.accepted = new boolean[geometry.area()]; + this.distance = new byte[geometry.area()]; + this.viable = new boolean[geometry.area()]; + build(footprint, signedCut); + } + + private FootprintSample sample(int x, int z) { + int index = geometry.index(x - occupancyMinX, z - occupancyMinZ); + int inwardDistance = Byte.toUnsignedInt(distance[index]); + boolean renderable = accepted[index] && viable[index] && inwardDistance > 1; + int boundaryDistance = renderable + ? Math.min(geometry.maxRenderableDistance(), inwardDistance) + : 0; + double fade = edgeFadeForDistance(boundaryDistance, geometry.taperWidth()); + return new FootprintSample(signed[index], Byte.toUnsignedInt(cardinalSupport[index]), + Byte.toUnsignedInt(diagonalSupport[index]), renderable, boundaryDistance, fade); + } + + private void build(NoiseSampler footprint, double signedCut) { + double[] rawSigned = sampleRawFootprint(footprint); + buildOccupancy(rawSigned, signedCut); + buildDistanceField(); + } + + private double[] sampleRawFootprint(NoiseSampler footprint) { + int rawSize = geometry.fieldSize() + 2; + double[] rawSigned = new double[rawSize * rawSize]; + int rawMinX = occupancyMinX - 1; + int rawMinZ = occupancyMinZ - 1; + for (int z = 0; z < rawSize; z++) { + for (int x = 0; x < rawSize; x++) { + rawSigned[rawIndex(x, z, rawSize)] = signedFromUnit(footprint.sample(rawMinX + x, rawMinZ + z)); + } + } + return rawSigned; + } + + private void buildOccupancy(double[] rawSigned, double signedCut) { + int rawSize = geometry.fieldSize() + 2; + for (int z = 0; z < geometry.fieldSize(); z++) { + for (int x = 0; x < geometry.fieldSize(); x++) { + int index = geometry.index(x, z); + double value = rawSigned[rawIndex(x + 1, z + 1, rawSize)]; + int cardinal = 0; + int diagonal = 0; + for (int dx = -1; dx <= 1; dx++) { + for (int dz = -1; dz <= 1; dz++) { + if (dx == 0 && dz == 0) { + continue; + } + if (rawSigned[rawIndex(x + dx + 1, z + dz + 1, rawSize)] <= signedCut) { + continue; + } + if (Math.abs(dx) + Math.abs(dz) == 1) { + cardinal++; + } else { + diagonal++; + } + } + } + boolean solid = value > signedCut; + FloatingIslandSample.NeighborSupport support = new FloatingIslandSample.NeighborSupport(cardinal, diagonal); + boolean supported = support.hasSolidSupport(); + boolean repairedPinhole = FloatingIslandSample.isFootprintPinholeRepairable(support); + signed[index] = value; + cardinalSupport[index] = (byte) cardinal; + diagonalSupport[index] = (byte) diagonal; + accepted[index] = (solid && supported) || (!solid && repairedPinhole); + } + } + } + + private void buildDistanceField() { + fillDistanceField(accepted, distance, geometry); + markCoreSupported(accepted, distance, viable, geometry); + } + + private static int rawIndex(int x, int z, int rawSize) { + return (z * rawSize) + x; + } + + private static double signedFromUnit(double value) { + return (Math.max(0.0D, Math.min(1.0D, value)) * 2.0D) - 1.0D; + } + } + + private static final class OwnershipField { + private final FieldGeometry geometry; + private final int minX; + private final int minZ; + private final ResolvedFloatingChild[] owners; + private final IdentityHashMap distances; + + private OwnershipField(KList entries, NoiseSampler picker, int chunkX, int chunkZ, + int taperWidth) { + this.geometry = FieldGeometry.forWidth(taperWidth); + this.minX = (chunkX * CHUNK_SIZE) - geometry.fadeRadius(); + this.minZ = (chunkZ * CHUNK_SIZE) - geometry.fadeRadius(); + this.owners = new ResolvedFloatingChild[geometry.area()]; + this.distances = new IdentityHashMap<>(); + for (int z = 0; z < geometry.fieldSize(); z++) { + for (int x = 0; x < geometry.fieldSize(); x++) { + double value = Math.max(0.0D, Math.min(1.0D, picker.sample(minX + x, minZ + z))); + owners[geometry.index(x, z)] = pickByRarity(entries, value); + } + } + for (ResolvedFloatingChild entry : entries) { + if (entry != null && !distances.containsKey(entry)) { + distances.put(entry, buildDistanceField(entry)); + } + } + } + + private OwnershipSample sample(int x, int z) { + int index = geometry.index(x - minX, z - minZ); + ResolvedFloatingChild owner = owners[index]; + if (owner == null) { + return new OwnershipSample(null, 0, 0.0D); + } + ComponentDistanceField field = distances.get(owner); + if (field == null) { + return new OwnershipSample(null, 0, 0.0D); + } + int inwardDistance = Byte.toUnsignedInt(field.distance()[index]); + int boundaryDistance = field.viable()[index] + ? Math.min(geometry.maxRenderableDistance(), inwardDistance) + : 0; + double fade = edgeFadeForDistance(boundaryDistance, geometry.taperWidth()); + return new OwnershipSample(owner, boundaryDistance, fade); + } + + private ComponentDistanceField buildDistanceField(ResolvedFloatingChild owner) { + boolean[] owned = new boolean[owners.length]; + byte[] distance = new byte[owners.length]; + boolean[] viable = new boolean[owners.length]; + for (int i = 0; i < owners.length; i++) { + owned[i] = owners[i] == owner; + } + fillDistanceField(owned, distance, geometry); + markCoreSupported(owned, distance, viable, geometry); + return new ComponentDistanceField(distance, viable); + } + } + + private record ComponentDistanceField(byte[] distance, boolean[] viable) { + } + + /** The entry {@code noiseValue} (0..1) lands on when each entry takes a share of the range inverse to its rarity. */ + static ResolvedFloatingChild pickByRarity(List entries, double noiseValue) { + if (entries.isEmpty()) { + return null; + } + if (entries.size() == 1) { + return entries.getFirst(); + } + + double total = 0; + for (ResolvedFloatingChild entry : entries) { + total += 1d / rarityOf(entry); + } + + double threshold = total * noiseValue; + double buffer = 0; + for (ResolvedFloatingChild entry : entries) { + buffer += 1d / rarityOf(entry); + if (buffer >= threshold) { + return entry; + } + } + return entries.getLast(); + } + + private static int rarityOf(ResolvedFloatingChild entry) { + return Math.max(1, entry.rarity()); + } + + private record FieldGeometry(int taperWidth, int fadeRadius, int fieldSize, int maxDistance) { + private static FieldGeometry forWidth(int taperWidth) { + int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); + int radius = width + 1; + return new FieldGeometry(width, radius, CHUNK_SIZE + (radius * 2), radius + 1); + } + + private int area() { + return fieldSize * fieldSize; + } + + private int maxRenderableDistance() { + return fadeRadius; + } + + private int index(int x, int z) { + return (z * fieldSize) + x; + } + } + + private static void fillDistanceField(boolean[] inside, byte[] distance, FieldGeometry geometry) { + for (int i = 0; i < inside.length; i++) { + distance[i] = (byte) (inside[i] ? geometry.maxDistance() : 0); + } + for (int z = 0; z < geometry.fieldSize(); z++) { + for (int x = 0; x < geometry.fieldSize(); x++) { + if (!inside[geometry.index(x, z)]) { + continue; + } + setMinimumDistance(distance, x, z, x - 1, z, geometry); + setMinimumDistance(distance, x, z, x, z - 1, geometry); + setMinimumDistance(distance, x, z, x - 1, z - 1, geometry); + setMinimumDistance(distance, x, z, x + 1, z - 1, geometry); + } + } + for (int z = geometry.fieldSize() - 1; z >= 0; z--) { + for (int x = geometry.fieldSize() - 1; x >= 0; x--) { + if (!inside[geometry.index(x, z)]) { + continue; + } + setMinimumDistance(distance, x, z, x + 1, z, geometry); + setMinimumDistance(distance, x, z, x, z + 1, geometry); + setMinimumDistance(distance, x, z, x + 1, z + 1, geometry); + setMinimumDistance(distance, x, z, x - 1, z + 1, geometry); + } + } + } + + private static void propagateDistanceField(byte[] distance, FieldGeometry geometry) { + for (int z = 0; z < geometry.fieldSize(); z++) { + for (int x = 0; x < geometry.fieldSize(); x++) { + setMinimumDistance(distance, x, z, x - 1, z, geometry); + setMinimumDistance(distance, x, z, x, z - 1, geometry); + setMinimumDistance(distance, x, z, x - 1, z - 1, geometry); + setMinimumDistance(distance, x, z, x + 1, z - 1, geometry); + } + } + for (int z = geometry.fieldSize() - 1; z >= 0; z--) { + for (int x = geometry.fieldSize() - 1; x >= 0; x--) { + setMinimumDistance(distance, x, z, x + 1, z, geometry); + setMinimumDistance(distance, x, z, x, z + 1, geometry); + setMinimumDistance(distance, x, z, x + 1, z + 1, geometry); + setMinimumDistance(distance, x, z, x - 1, z + 1, geometry); + } + } + } + + private static void setMinimumDistance(byte[] distance, int x, int z, int neighborX, int neighborZ, + FieldGeometry geometry) { + if (neighborX < 0 || neighborX >= geometry.fieldSize() + || neighborZ < 0 || neighborZ >= geometry.fieldSize()) { + return; + } + int index = geometry.index(x, z); + int neighborDistance = Byte.toUnsignedInt(distance[geometry.index(neighborX, neighborZ)]); + int currentDistance = Byte.toUnsignedInt(distance[index]); + distance[index] = (byte) Math.min(currentDistance, neighborDistance + 1); + } + + private static void markCoreSupported(boolean[] inside, byte[] distance, boolean[] viable, + FieldGeometry geometry) { + for (int z = 0; z < geometry.fieldSize(); z++) { + for (int x = 0; x < geometry.fieldSize(); x++) { + int index = geometry.index(x, z); + if (!inside[index]) { + continue; + } + int inwardDistance = Byte.toUnsignedInt(distance[index]); + viable[index] = inwardDistance >= MIN_CORE_DISTANCE + || inwardDistance == MIN_CORE_DISTANCE - 1 + && hasCoreNeighbor(inside, distance, null, x, z, geometry); + } + } + } + + private static void markLabelCoreSupported(ResourceId[] labels, byte[] distance, boolean[] viable, + FieldGeometry geometry) { + for (int z = 0; z < geometry.fieldSize(); z++) { + for (int x = 0; x < geometry.fieldSize(); x++) { + int index = geometry.index(x, z); + int inwardDistance = Byte.toUnsignedInt(distance[index]); + viable[index] = inwardDistance >= MIN_CORE_DISTANCE + || inwardDistance == MIN_CORE_DISTANCE - 1 + && hasCoreNeighbor(null, distance, labels, x, z, geometry); + } + } + } + + private static boolean hasCoreNeighbor(boolean[] inside, byte[] distance, + ResourceId[] labels, int x, int z, FieldGeometry geometry) { + int index = geometry.index(x, z); + for (int dz = -1; dz <= 1; dz++) { + for (int dx = -1; dx <= 1; dx++) { + if (dx == 0 && dz == 0) { + continue; + } + int neighborX = x + dx; + int neighborZ = z + dz; + if (neighborX < 0 || neighborX >= geometry.fieldSize() + || neighborZ < 0 || neighborZ >= geometry.fieldSize()) { + continue; + } + int neighbor = geometry.index(neighborX, neighborZ); + if (Byte.toUnsignedInt(distance[neighbor]) < MIN_CORE_DISTANCE) { + continue; + } + if (inside != null && !inside[neighbor]) { + continue; + } + if (labels != null && !sameBiome(labels[index], labels[neighbor])) { + continue; + } + return true; + } + } + return false; + } + + @FunctionalInterface + public interface BiomeSampler { + ResourceId sample(int x, int z); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandEdgeProfile.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandEdgeProfile.java new file mode 100644 index 000000000..3f7e69776 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandEdgeProfile.java @@ -0,0 +1,91 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.terrain.floating; + +import com.volmit.noise.NoiseSampler; + +public final class FloatingIslandEdgeProfile { + public static final int DEFAULT_WIDTH = 10; + public static final int MIN_WIDTH = 2; + public static final int MAX_WIDTH = 32; + public static final double DEFAULT_EXPONENT = 1.0D; + public static final double MIN_EXPONENT = 0.25D; + public static final double MAX_EXPONENT = 4.0D; + public static final double MAX_VARIATION_AMPLITUDE = 8.0D; + public static final FloatingIslandEdgeProfile DEFAULT = new FloatingIslandEdgeProfile( + DEFAULT_WIDTH, DEFAULT_EXPONENT, 0.0D, null); + + private final int width; + private final double exponent; + private final double variationAmplitude; + private final NoiseSampler variation; + + public FloatingIslandEdgeProfile(int width, double exponent, double variationAmplitude, NoiseSampler variation) { + this.width = clampWidth(width); + this.exponent = clampExponent(exponent); + this.variationAmplitude = clampVariationAmplitude(variationAmplitude, this.width); + this.variation = variation; + } + + public int width() { + return width; + } + + public double exponent() { + return exponent; + } + + public double variationAmplitude() { + return variationAmplitude; + } + + public int fieldWidth() { + return Math.min(MAX_WIDTH, (int) Math.ceil(width + variationAmplitude)); + } + + public double fade(int boundaryDistance, int x, int z) { + if (boundaryDistance <= 1) { + return 0.0D; + } + double localWidth = width; + if (variation != null && variationAmplitude > 0.0D) { + double noise = Math.max(0.0D, Math.min(1.0D, variation.sample(x, z))); + double signedNoise = (noise * 2.0D) - 1.0D; + localWidth += signedNoise * variationAmplitude; + } + + double position = Math.max(0.0D, Math.min(1.0D, (boundaryDistance - 1.0D) / localWidth)); + double smooth = position * position * (3.0D - (2.0D * position)); + return exponent == DEFAULT_EXPONENT ? smooth : Math.pow(smooth, exponent); + } + + public static int clampWidth(int width) { + return Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, width)); + } + + public static double clampExponent(double exponent) { + return Math.max(MIN_EXPONENT, Math.min(MAX_EXPONENT, exponent)); + } + + public static double clampVariationAmplitude(double amplitude, int width) { + int clampedWidth = clampWidth(width); + double widthLimit = Math.min(clampedWidth - MIN_WIDTH, MAX_WIDTH - clampedWidth); + return Math.max(0.0D, Math.min(Math.min(MAX_VARIATION_AMPLITUDE, widthLimit), amplitude)); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java new file mode 100644 index 000000000..dc024227a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java @@ -0,0 +1,794 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.terrain.floating; + +import art.arcane.iris.modules.floating.FloatingChildBiome; +import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler; +import art.arcane.volmlib.util.collection.KList; +import com.volmit.ModuleLog; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.ResourceId; + +import java.util.Arrays; +import java.util.List; +import java.util.OptionalInt; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.concurrent.atomic.AtomicBoolean; + +public final class FloatingIslandSample { + public static final int REJECT_NONE = 0; + public static final int REJECT_NO_ENTRIES = 1; + public static final int REJECT_NO_SEED = 2; + public static final int REJECT_NO_PICK = 3; + public static final int REJECT_ABOVE_HEIGHT = 4; + public static final int REJECT_NO_THICKNESS = 5; + public static final int REJECT_NO_SOLID = 6; + public static final int REJECT_COUNT = 7; + public static final int REJECT_CLUSTER = REJECT_NO_SEED; + + private static final int PINHOLE_CARDINAL_FILL = 3; + private static final int PINHOLE_TOTAL_FILL = 7; + private static final int CARVE_CARDINAL_SUPPORT = 2; + private static final int CARVE_TOTAL_SUPPORT = 4; + private static final double CARVE_SHELL_FRACTION = 0.14D; + private static final double CARVE_MAX_VERTICAL_RUN_FRACTION = 0.18D; + private static final ThreadLocal LAST_REJECT = ThreadLocal.withInitial(() -> new int[1]); + private static final ThreadLocal LAST_DENSITY = ThreadLocal.withInitial(() -> new double[2]); + private static final ThreadLocal> CHUNK_MEMO = ThreadLocal.withInitial(HashMap::new); + private static final ThreadLocal>> FOOTPRINT_MEMO = ThreadLocal.withInitial(IdentityHashMap::new); + private static final int FOOTPRINT_MEMO_CAPACITY = 512; + private static final AtomicBoolean NULL_CNG_WARNED = new AtomicBoolean(false); + + public static int getLastReject() { + return LAST_REJECT.get()[0]; + } + + public static double getLastClusterValue() { + return LAST_DENSITY.get()[0]; + } + + public static double getLastClusterThreshold() { + return LAST_DENSITY.get()[1]; + } + + public static void clearThreadCaches() { + } + + public static void clearChunkMemo() { + CHUNK_MEMO.get().clear(); + FOOTPRINT_MEMO.get().clear(); + } + + public static FloatingIslandSample sampleMemoized(ResourceId parent, int wx, int wz, int chunkHeight, FloatingWorld world, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { + Column key = new Column(wx, wz); + HashMap memo = CHUNK_MEMO.get(); + if (memo.containsKey(key)) { + return memo.get(key); + } + FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, world, boundarySampler, log); + memo.put(key, result); + return result; + } + + private static FloatingIslandSample reject(int code) { + LAST_REJECT.get()[0] = code; + return null; + } + + private static void warnNullCng(String styleField, ResourceId parent, ModuleLog log) { + if (NULL_CNG_WARNED.compareAndSet(false, true)) { + String biomeKey = parent == null ? "" : parent.toString(); + log.warn("Floating child biome on " + biomeKey + " has no noise for " + styleField + + " (the noise factory failed or AtomicCache swallowed an exception); skipping floating sampling until pack is fixed"); + } + } + + public final ResolvedFloatingChild entry; + public final int islandBaseY; + public final int thickness; + public final int topIdx; + public final int solidCount; + public final boolean[] solidMask; + private final ResolvedFloatingChild[] entryMask; + private transient int cachedBottomIdx = -2; + + private FloatingIslandSample(ResolvedFloatingChild entry, int islandBaseY, int thickness, int topIdx, int solidCount, boolean[] solidMask) { + this(entry, islandBaseY, thickness, topIdx, solidCount, solidMask, null); + } + + private FloatingIslandSample(ResolvedFloatingChild entry, int islandBaseY, int thickness, int topIdx, int solidCount, boolean[] solidMask, ResolvedFloatingChild[] entryMask) { + this.entry = entry; + this.islandBaseY = islandBaseY; + this.thickness = thickness; + this.topIdx = topIdx; + this.solidCount = solidCount; + this.solidMask = solidMask; + this.entryMask = entryMask; + } + + static FloatingIslandSample constructForTest(int islandBaseY, int thickness, int topIdx, int solidCount, boolean[] solidMask) { + return new FloatingIslandSample(null, islandBaseY, thickness, topIdx, solidCount, solidMask); + } + + static FloatingIslandSample constructForTest(ResolvedFloatingChild entry, int islandBaseY, int thickness, int topIdx, int solidCount, boolean[] solidMask, ResolvedFloatingChild[] entryMask) { + return new FloatingIslandSample(entry, islandBaseY, thickness, topIdx, solidCount, solidMask, entryMask); + } + + public int topY() { + return islandBaseY + topIdx; + } + + public int bottomY() { + if (cachedBottomIdx == -2) { + cachedBottomIdx = -1; + for (int i = 0; i < solidMask.length; i++) { + if (solidMask[i]) { + cachedBottomIdx = i; + break; + } + } + } + return cachedBottomIdx == -1 ? -1 : islandBaseY + cachedBottomIdx; + } + + public ResolvedFloatingChild entryAt(int maskIndex) { + if (entryMask != null && maskIndex >= 0 && maskIndex < entryMask.length && entryMask[maskIndex] != null) { + return entryMask[maskIndex]; + } + + return entry; + } + + public ResolvedFloatingChild bottomEntry() { + int bottomY = bottomY(); + if (bottomY < 0) { + return entry; + } + + return entryAt(bottomY - islandBaseY); + } + + public boolean hasMergedEntries() { + return entryMask != null; + } + + public static long columnSeed(long baseSeed, int wx, int wz) { + return baseSeed ^ ((long) wx * 341873128712L) ^ ((long) wz * 132897987541L); + } + + private static int maximumEdgeFieldWidth(KList entries, ResourceId parent, ModuleLog log) { + int maximumWidth = FloatingIslandEdgeProfile.MIN_WIDTH; + for (ResolvedFloatingChild entry : entries) { + FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, parent, log); + maximumWidth = Math.max(maximumWidth, profile.fieldWidth()); + } + return maximumWidth; + } + + private static FloatingIslandEdgeProfile resolveEdgeProfile(ResolvedFloatingChild entry, ResourceId parent, ModuleLog log) { + FloatingIslandEdgeProfile profile = entry.edgeTaperProfile(); + if (profile != null) { + return profile; + } + warnNullCng("edgeTaperVariationStyle", parent, log); + return FloatingIslandEdgeProfile.DEFAULT; + } + + public static FloatingIslandSample sample(ResourceId parent, int wx, int wz, int chunkHeight, FloatingWorld world, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { + List settings = world.declaredBy(parent); + if (settings.isEmpty()) { + return reject(REJECT_NO_ENTRIES); + } + KList entries = new KList<>(world.resolve(settings)); + return sample(parent, entries, wx, wz, chunkHeight, world, boundarySampler, log); + } + + static FloatingIslandSample sample(ResourceId parent, KList entries, int wx, int wz, int chunkHeight, FloatingWorld world, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { + int boundaryFieldWidth = maximumEdgeFieldWidth(entries, parent, log); + int parentBoundaryDistance = boundarySampler.edgeDistance(parent, wx, wz, boundaryFieldWidth); + + if (world.merges(parent)) { + return sampleMerged(parent, entries, wx, wz, chunkHeight, world, boundarySampler, + parentBoundaryDistance, boundaryFieldWidth, log); + } + + ResolvedFloatingChild entry; + int ownershipBoundaryDistance = boundaryFieldWidth + 1; + if (entries.size() == 1) { + entry = entries.getFirst(); + } else { + ResolvedFloatingChild reference = entries.getFirst(); + NoiseSampler picker = reference.pickerNoise(); + if (picker == null) { + warnNullCng("pickerStyle", parent, log); + return reject(REJECT_NO_PICK); + } + FloatingIslandBoundarySampler.OwnershipSample ownership = boundarySampler.ownership( + entries, picker, wx, wz, boundaryFieldWidth); + entry = ownership.owner(); + if (entry == null) { + return reject(REJECT_NO_PICK); + } + ownershipBoundaryDistance = ownership.boundaryDistance(); + } + + return sampleEntry(parent, entry, wx, wz, chunkHeight, world, boundarySampler, + parentBoundaryDistance, ownershipBoundaryDistance, log); + } + + private static FloatingIslandSample sampleMerged(ResourceId parent, KList entries, + int wx, int wz, int chunkHeight, FloatingWorld world, + FloatingIslandBoundarySampler boundarySampler, + int parentBoundaryDistance, int boundaryFieldWidth, ModuleLog log) { + KList samples = new KList<>(); + int minY = Integer.MAX_VALUE; + int maxY = Integer.MIN_VALUE; + + for (ResolvedFloatingChild entry : entries) { + FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, world, + boundarySampler, parentBoundaryDistance, boundaryFieldWidth + 1, log); + if (sample == null) { + continue; + } + + int bottomY = sample.bottomY(); + if (bottomY < 0) { + continue; + } + + samples.add(sample); + if (bottomY < minY) { + minY = bottomY; + } + int topY = sample.topY(); + if (topY > maxY) { + maxY = topY; + } + } + + if (samples.isEmpty() || minY > maxY) { + return reject(REJECT_NO_SEED); + } + + int thickness = maxY - minY + 1; + boolean[] solidMask = new boolean[thickness]; + ResolvedFloatingChild[] entryMask = new ResolvedFloatingChild[thickness]; + int[] entryTopY = new int[thickness]; + Arrays.fill(entryTopY, Integer.MIN_VALUE); + int solidCount = 0; + + for (FloatingIslandSample sample : samples) { + int sampleTopY = sample.topY(); + for (int i = 0; i < sample.solidMask.length; i++) { + if (!sample.solidMask[i]) { + continue; + } + + int y = sample.islandBaseY + i; + int mergedIndex = y - minY; + if (!solidMask[mergedIndex]) { + solidMask[mergedIndex] = true; + solidCount++; + } + if (sampleTopY >= entryTopY[mergedIndex]) { + entryTopY[mergedIndex] = sampleTopY; + entryMask[mergedIndex] = sample.entryAt(i); + } + } + } + + int topIdx = highestSolidIndex(solidMask); + if (solidCount == 0 || topIdx < 0) { + return reject(REJECT_NO_SOLID); + } + + ResolvedFloatingChild topEntry = entryMask[topIdx] == null ? samples.getFirst().entry : entryMask[topIdx]; + LAST_REJECT.get()[0] = REJECT_NONE; + return new FloatingIslandSample(topEntry, minY, thickness, topIdx, solidCount, solidMask, entryMask); + } + + private static FloatingIslandSample sampleEntry(ResourceId parent, ResolvedFloatingChild entry, int wx, int wz, + int chunkHeight, FloatingWorld world, + FloatingIslandBoundarySampler boundarySampler, + int parentBoundaryDistance, int ownershipBoundaryDistance, ModuleLog log) { + FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, parent, log); + NoiseSampler footprintCng = entry.footprintNoise(); + if (footprintCng == null) { + warnNullCng("footprintStyle", parent, log); + return reject(REJECT_NO_SEED); + } + double threshold = Math.max(0, Math.min(1, entry.settings().footprintThreshold())); + double signedCut = (threshold * 2.0) - 1.0; + FloatingIslandBoundarySampler.FootprintSample footprint = boundarySampler.footprint( + footprintCng, wx, wz, signedCut, edgeProfile.fieldWidth()); + double signed = footprint.signed(); + + double[] diag = LAST_DENSITY.get(); + diag[0] = signed; + diag[1] = signedCut; + + NeighborSupport footprintSupport = new NeighborSupport(footprint.cardinalSupport(), footprint.diagonalSupport()); + if (!footprint.accepted()) { + return reject(REJECT_NO_SEED); + } + int boundaryDistance = Math.min(footprint.boundaryDistance(), + Math.min(parentBoundaryDistance, ownershipBoundaryDistance)); + double edgeFade = edgeProfile.fade(boundaryDistance, wx, wz); + if (edgeFade <= 0.0D) { + return reject(REJECT_NO_THICKNESS); + } + + NoiseSampler altitudeCng = entry.altitudeNoise(); + if (altitudeCng == null) { + warnNullCng("altitudeStyle", parent, log); + return reject(REJECT_NO_SEED); + } + double altNoise = altitudeCng.sample(wx, wz); + double altClamped = Math.max(0, Math.min(1, altNoise)); + int worldMin = world.minWorldY(); + int minAlt = Math.max(0, entry.settings().minHeightAboveSurface() - worldMin); + int maxAlt = Math.max(minAlt, entry.settings().maxHeightAboveSurface() - worldMin); + int baseY = minAlt + (int) Math.round(altClamped * (maxAlt - minAlt)); + + ResourceId target = entry.realBiome(parent); + int fullTopHeight = computeTopHeight(entry, target, world, wx, wz, log); + int topH = roundedEdgeHeight(fullTopHeight, edgeFade); + + NoiseSampler bottomCng = entry.bottomNoise(); + if (bottomCng == null) { + warnNullCng("bottomStyle", parent, log); + return reject(REJECT_NO_SEED); + } + double bottomNoise = bottomCng.sample(wx, wz); + double bottomClamped = Math.max(0, Math.min(1, bottomNoise)); + double bottomShaped = Math.pow(bottomClamped, Math.max(0.1, entry.settings().bottomExponent())); + int minDepth = Math.max(0, entry.settings().bottomDepthMin()); + int maxDepth = Math.max(minDepth, entry.settings().bottomDepthMax()); + int depth = roundedEdgeDepth(minDepth, maxDepth, bottomShaped, edgeFade); + if (topH == 0 && depth == 0) { + double fullDepth = minDepth + (bottomShaped * (maxDepth - minDepth)); + if (fullDepth > 0.0D) { + depth = 1; + } else if (fullTopHeight > 0) { + topH = 1; + } else { + return reject(REJECT_NO_THICKNESS); + } + } + int topY = baseY + topH; + int botY = baseY - depth; + + OptionalInt minAbsoluteY = entry.settings().minAbsoluteY(); + if (minAbsoluteY.isPresent() && botY < minAbsoluteY.getAsInt() - worldMin) { + botY = minAbsoluteY.getAsInt() - worldMin; + } + OptionalInt maxAbsoluteY = entry.settings().maxAbsoluteY(); + if (maxAbsoluteY.isPresent() && topY > maxAbsoluteY.getAsInt() - worldMin) { + topY = maxAbsoluteY.getAsInt() - worldMin; + } + + if (botY < 0) { + botY = 0; + } + if (topY >= chunkHeight) { + topY = chunkHeight - 1; + } + if (topY < botY) { + return reject(REJECT_ABOVE_HEIGHT); + } + + int thickness = topY - botY + 1; + int maxThickness = Math.max(1, entry.settings().maxThickness()); + if (thickness > maxThickness) { + botY = topY - maxThickness + 1; + if (botY < 0) { + botY = 0; + } + thickness = topY - botY + 1; + } + if (thickness <= 0) { + return reject(REJECT_NO_THICKNESS); + } + + boolean[] solidMask = new boolean[thickness]; + NoiseSampler wallWarp = entry.wallWarpNoise(); + double warpAmp = Math.max(0, entry.settings().wallWarpAmplitude()); + double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade); + CaveProfileSampler carvingProfileSampler = entry.carvingProfileSampler(); + NoiseSampler carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.carveNoise() : null; + double carveThreshold = entry.settings().carveThreshold(); + boolean useWarp = wallWarp != null && effectiveWarpAmp > 0; + boolean useProfileCarve = carvingProfileSampler != null; + boolean useCarve = directCarveEnabled(entry, carvingProfileSampler, carve, carveThreshold); + boolean[] lateralCarveMask = useProfileCarve || useCarve ? new boolean[thickness] : null; + boolean baseCarveInterior = lateralCarveMask != null && canCarveLaterally(edgeFade, footprintSupport); + + if (useWarp) { + for (int k = 0; k < thickness; k++) { + int wy = botY + k; + boolean layerSolid = layerFootprintSolid(footprintCng, wallWarp, true, effectiveWarpAmp, wx, wy, wz, signedCut); + NeighborSupport layerSupport = layerNeighborSupport(footprintCng, wallWarp, true, effectiveWarpAmp, wx, wy, wz, signedCut); + if (layerSolid && !layerSupport.hasSolidSupport()) { + continue; + } + if (!layerSolid && !layerSupport.canFillPinhole()) { + continue; + } + solidMask[k] = true; + if (lateralCarveMask != null) { + lateralCarveMask[k] = baseCarveInterior && layerSolid && layerSupport.isFullySurrounded(); + } + } + } else { + Arrays.fill(solidMask, true); + if (baseCarveInterior) { + Arrays.fill(lateralCarveMask, true); + } + } + + int solidCount = solidifyUncarvedInterior(solidMask); + if (useProfileCarve) { + solidCount = carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, carvingProfileSampler, carveThreshold); + } else if (useCarve) { + solidCount = carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, carve, carveThreshold); + } + int highestSolidIdx = highestSolidIndex(solidMask); + + if (solidCount == 0 || highestSolidIdx < 0) { + return reject(REJECT_NO_SOLID); + } + + int topIdx = highestSolidIdx; + + LAST_REJECT.get()[0] = REJECT_NONE; + return new FloatingIslandSample(entry, botY, thickness, topIdx, solidCount, solidMask); + } + + static int roundedEdgeHeight(int topHeight, double edgeFade) { + return Math.max(0, (int) Math.round(Math.max(0, topHeight) * Math.max(0, Math.min(1, edgeFade)))); + } + + static int roundedEdgeDepth(int minDepth, int maxDepth, double bottomShaped, double edgeFade) { + int min = Math.max(0, minDepth); + int max = Math.max(min, maxDepth); + double shaped = Math.max(0, Math.min(1, bottomShaped)); + double fade = Math.max(0, Math.min(1, edgeFade)); + double fullDepth = min + shaped * (max - min); + return (int) Math.round(fullDepth * fade); + } + + static double effectiveWallWarpAmplitude(double wallWarpAmplitude, double edgeFade) { + double amplitude = Math.max(0, wallWarpAmplitude); + double fade = Math.max(0, Math.min(1, edgeFade)); + return amplitude * fade; + } + + static boolean directCarveEnabled(ResolvedFloatingChild entry, CaveProfileSampler carvingProfileSampler, NoiseSampler carve, double carveThreshold) { + return carvingProfileSampler == null && (entry == null || !entry.hasCarvingReference()) && carve != null && carveThreshold < 1.0; + } + + static boolean canCarveLaterally(double edgeFade, NeighborSupport support) { + return edgeFade >= 1.0 && support.isFullySurrounded(); + } + + static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, NoiseSampler carve, double carveThreshold) { + return carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, (x, y, z) -> { + double carveNoise = carve.sample(x, y, z); + double carveClamped = Math.max(0, Math.min(1, carveNoise)); + return carveClamped > carveThreshold; + }); + } + + static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, CaveProfileSampler carve, double carveThreshold) { + return carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, (x, y, z) -> carve.shouldCarve(x, y, z, carveThreshold)); + } + + private static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, CarveSampler carve) { + int firstSolid = -1; + int lastSolid = -1; + for (int i = 0; i < solidMask.length; i++) { + if (!solidMask[i]) { + continue; + } + if (firstSolid < 0) { + firstSolid = i; + } + lastSolid = i; + } + if (firstSolid < 0) { + return 0; + } + int span = lastSolid - firstSolid + 1; + int shell = carveShellThickness(span); + int carveStart = firstSolid + shell; + int carveEnd = lastSolid - shell; + boolean[] carveMask = new boolean[solidMask.length]; + if (carveStart <= carveEnd) { + for (int i = carveStart; i <= carveEnd; i++) { + if (!solidMask[i] || !lateralCarveMask[i]) { + continue; + } + + int y = botY + i; + if (carve.shouldCarve(wx, y, wz) && hasCarveClusterSupport(carve, wx, y, wz)) { + carveMask[i] = true; + } + } + clampVerticalCarveRuns(carveMask, carveStart, carveEnd, maxVerticalCarveRun(span)); + for (int i = carveStart; i <= carveEnd; i++) { + if (carveMask[i]) { + solidMask[i] = false; + } + } + } + int count = 0; + for (boolean solid : solidMask) { + if (solid) { + count++; + } + } + return count; + } + + static int carveShellThickness(int solidSpan) { + if (solidSpan <= 4) { + return 1; + } + + int proportional = (int) Math.ceil(solidSpan * CARVE_SHELL_FRACTION); + return Math.max(2, Math.min(5, proportional)); + } + + static int maxVerticalCarveRun(int solidSpan) { + int proportional = (int) Math.round(solidSpan * CARVE_MAX_VERTICAL_RUN_FRACTION); + return Math.max(2, Math.min(6, proportional)); + } + + static void clampVerticalCarveRuns(boolean[] carveMask, int start, int end, int maxRun) { + int i = start; + while (i <= end) { + if (!carveMask[i]) { + i++; + continue; + } + + int runStart = i; + while (i <= end && carveMask[i]) { + i++; + } + int runEnd = i - 1; + int runLength = runEnd - runStart + 1; + if (runLength <= maxRun) { + continue; + } + + int keepStart = runStart + ((runLength - maxRun) / 2); + int keepEnd = keepStart + maxRun - 1; + for (int j = runStart; j <= runEnd; j++) { + carveMask[j] = j >= keepStart && j <= keepEnd; + } + } + } + + private static boolean hasCarveClusterSupport(CarveSampler carve, int wx, int wy, int wz) { + int cardinal = 0; + int diagonal = 0; + for (int dx = -1; dx <= 1; dx++) { + for (int dz = -1; dz <= 1; dz++) { + if (dx == 0 && dz == 0) { + continue; + } + if (!carve.shouldCarve(wx + dx, wy, wz + dz)) { + continue; + } + if (Math.abs(dx) + Math.abs(dz) == 1) { + cardinal++; + } else { + diagonal++; + } + } + } + return cardinal >= CARVE_CARDINAL_SUPPORT && cardinal + diagonal >= CARVE_TOTAL_SUPPORT; + } + + static boolean hasFootprintNeighborSupport(NoiseSampler footprintCng, int wx, int wz, double signedCut) { + return footprintNeighborSupport(footprintCng, wx, wz, signedCut).hasSolidSupport(); + } + + static boolean isFootprintPinholeRepairable(NeighborSupport support) { + return support.canFillPinhole(); + } + + static NeighborSupport footprintNeighborSupport(NoiseSampler footprintCng, int wx, int wz, double signedCut) { + int cardinal = 0; + int diagonal = 0; + for (int dx = -1; dx <= 1; dx++) { + for (int dz = -1; dz <= 1; dz++) { + if (dx == 0 && dz == 0) { + continue; + } + double signed = footprintSigned(footprintCng, wx + dx, wz + dz); + if (signed <= signedCut) { + continue; + } + if (Math.abs(dx) + Math.abs(dz) == 1) { + cardinal++; + } else { + diagonal++; + } + } + } + return new NeighborSupport(cardinal, diagonal); + } + + static NeighborSupport layerNeighborSupport(NoiseSampler footprintCng, NoiseSampler wallWarp, boolean useWarp, double warpAmp, int wx, int wy, int wz, double signedCut) { + int cardinal = 0; + int diagonal = 0; + for (int dx = -1; dx <= 1; dx++) { + for (int dz = -1; dz <= 1; dz++) { + if (dx == 0 && dz == 0) { + continue; + } + if (!layerFootprintSolid(footprintCng, wallWarp, useWarp, warpAmp, wx + dx, wy, wz + dz, signedCut)) { + continue; + } + if (Math.abs(dx) + Math.abs(dz) == 1) { + cardinal++; + } else { + diagonal++; + } + } + } + return new NeighborSupport(cardinal, diagonal); + } + + static boolean layerFootprintSolid(NoiseSampler footprintCng, NoiseSampler wallWarp, boolean useWarp, double warpAmp, int wx, int wy, int wz, double signedCut) { + double sx = wx; + double sz = wz; + if (useWarp) { + double wnX = wallWarp.sample(wx, wy, wz); + double signedWarpX = signedFromUnit(wnX); + sx = wx + signedWarpX * warpAmp; + double wnZ = wallWarp.sample(wx + 1987.3, wy, wz + 2341.1); + double signedWarpZ = signedFromUnit(wnZ); + sz = wz + signedWarpZ * warpAmp; + } + double layerFoot = footprintCng.sample(sx, sz); + return signedFromUnit(layerFoot) > signedCut; + } + + private static double footprintSigned(NoiseSampler footprintCng, int wx, int wz) { + HashMap memo = FOOTPRINT_MEMO.get().computeIfAbsent(footprintCng, ignored -> new HashMap<>(FOOTPRINT_MEMO_CAPACITY)); + Column key = new Column(wx, wz); + Double cached = memo.get(key); + if (cached != null) { + return cached; + } + + double signed = signedFromUnit(footprintCng.sample(wx, wz)); + memo.put(key, signed); + return signed; + } + + private static double signedFromUnit(double value) { + return (Math.max(0, Math.min(1, value)) * 2.0) - 1.0; + } + + static int solidifyUncarvedInterior(boolean[] solidMask) { + int firstSolid = -1; + int lastSolid = -1; + for (int i = 0; i < solidMask.length; i++) { + if (!solidMask[i]) { + continue; + } + if (firstSolid < 0) { + firstSolid = i; + } + lastSolid = i; + } + if (firstSolid < 0) { + return 0; + } + for (int i = firstSolid; i <= lastSolid; i++) { + solidMask[i] = true; + } + return lastSolid - firstSolid + 1; + } + + private static int highestSolidIndex(boolean[] solidMask) { + for (int i = solidMask.length - 1; i >= 0; i--) { + if (solidMask[i]) { + return i; + } + } + return -1; + } + + @FunctionalInterface + private interface CarveSampler { + boolean shouldCarve(int x, int y, int z); + } + + static final class NeighborSupport { + private final int cardinal; + private final int diagonal; + + NeighborSupport(int cardinal, int diagonal) { + this.cardinal = cardinal; + this.diagonal = diagonal; + } + + int cardinal() { + return cardinal; + } + + int diagonal() { + return diagonal; + } + + int total() { + return cardinal + diagonal; + } + + boolean hasSolidSupport() { + return cardinal > 0 || diagonal >= 2; + } + + boolean canFillPinhole() { + return cardinal >= PINHOLE_CARDINAL_FILL && total() >= PINHOLE_TOTAL_FILL; + } + + boolean isFullySurrounded() { + return cardinal == 4 && diagonal == 4; + } + } + + private static int computeTopHeight(ResolvedFloatingChild entry, ResourceId target, FloatingWorld world, int wx, int wz, ModuleLog log) { + int maxTopHeight = Math.max(0, entry.settings().maxTopHeight()); + if (maxTopHeight == 0) { + return 0; + } + return switch (entry.settings().topShapeMode()) { + case FLAT -> maxTopHeight; + case NOISE -> { + NoiseSampler topCng = entry.topShapeNoise(); + if (topCng == null) { + warnNullCng("topShapeStyle", null, log); + yield maxTopHeight / 2; + } + double n = topCng.sample(wx, wz); + double clamped = Math.max(0, Math.min(1, n)); + double amp = Math.max(0, Math.min(1, entry.settings().topShapeAmp())); + yield (int) Math.round(clamped * amp * maxTopHeight); + } + case BIOME -> { + if (target == null) { + yield maxTopHeight / 2; + } + double h = world.biomeHeight(target, wx, wz); + int rounded = (int) Math.round(h); + if (rounded < 0) { + yield 0; + } + yield Math.min(maxTopHeight, rounded); + } + }; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java new file mode 100644 index 000000000..70e90b23e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java @@ -0,0 +1,162 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.terrain.floating; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.modules.carve.CarvingEntry; +import art.arcane.iris.modules.carve.CarvingSettings; +import art.arcane.iris.modules.carve.CaveProfile; +import art.arcane.iris.modules.floating.FloatingChildBiome; +import art.arcane.iris.modules.floating.FloatingChildSettings; +import art.arcane.iris.modules.floating.MergeFloatingChildrenSettings; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import com.volmit.noise.NoiseFactory; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackBiome; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** + * What the floating islands of one world are made from: the world's layout, noise and seeds, the floating children + * each biome declares, and the {@link ResolvedFloatingChild} of every child met, one per decoded entry. One per world + * ({@link #of}). + */ +public final class FloatingWorld { + private static final long BASE_SEED_SALT = 0x5EED_F107_00F1B10CL; + + private final PackResources resources; + private final RunningWorld running; + private final long baseSeed; + private final long carveSeed; + private final int minWorldY; + private final List dimensionCarving; + private final Map resolved = new ConcurrentHashMap<>(); + + FloatingWorld(PackResources resources, RunningWorld running, long terrainSeed, + long carveSeed, int minWorldY, List dimensionCarving) { + this.resources = resources; + this.running = running; + this.baseSeed = terrainSeed ^ BASE_SEED_SALT; + this.carveSeed = carveSeed; + this.minWorldY = minWorldY; + this.dimensionCarving = List.copyOf(dimensionCarving); + } + + /** The floating islands of {@code world}. */ + public static FloatingWorld of(PackWorld world) { + return world.state(FloatingWorld.class, FloatingWorld::create); + } + + private static FloatingWorld create(PackWorld world) { + return new FloatingWorld(world.resources(), world.running().orElseThrow(), world.seed(IrisSeedPurposes.TERRAIN), + world.seed(IrisSeedPurposes.CARVE), world.minWorldY(), dimensionCarvingOf(world)); + } + + private static List dimensionCarvingOf(PackWorld world) { + return world.settings().declared(CarvingSettings.class).dimension() + .map(CarvingSettings::entries) + .orElse(List.of()); + } + + /** The height the terrain generators of {@code biome} give the column when shaped with {@link #baseSeed}. */ + public double biomeHeight(ResourceId biome, int worldX, int worldZ) { + return running.layout().biomeHeight(biome, worldX, worldZ, baseSeed); + } + + public NoiseFactory noise() { + return resources.noise(); + } + + /** The seed every island's noise and column random derive from. */ + public long baseSeed() { + return baseSeed; + } + + long carveSeed() { + return carveSeed; + } + + /** The Y in the world of the dimension's bottom block. */ + public int minWorldY() { + return minWorldY; + } + + /** The biome of the column's surface, the biome an island grows from; any column of the world. */ + public ResourceId surfaceBiome(int worldX, int worldZ) { + return running.layout().surfaceBiome(worldX, worldZ); + } + + /** The biome the pack names {@code key}; empty when the pack has none. */ + public Optional biome(String key) { + return resources.find(PackResources.BIOMES, resources.idOf(key)).map(PackBiome::id); + } + + /** The floating children {@code biome} declares, in the order it lists them; none when it declares none. */ + public List declaredBy(ResourceId biome) { + return running.settings().declaredBy(biome, FloatingChildSettings.class).map(FloatingChildSettings::children).orElse(List.of()); + } + + /** Whether {@code biome} samples every floating child on its own and unions their islands instead of picking one per column. */ + public boolean merges(ResourceId biome) { + return running.settings().declaredBy(biome, MergeFloatingChildrenSettings.class).map(MergeFloatingChildrenSettings::merge).orElse(false); + } + + public ResolvedFloatingChild resolve(FloatingChildBiome settings) { + return resolved.computeIfAbsent(settings, declared -> new ResolvedFloatingChild(declared, this)); + } + + public List resolve(List settings) { + return settings.stream().map(this::resolve).toList(); + } + + /** The surface object placements {@code biome} declares. */ + public List surfaceObjects(ResourceId biome) { + return surfaceObjects(running.settings().declaredBy(biome, ObjectSettings.class)); + } + + /** The surface object placements of the declared object settings; none when nothing is declared. */ + public static List surfaceObjects(Optional declared) { + return declared.map(ObjectSettings::objects).orElse(List.of()).stream() + .filter(placement -> placement.carvingSupport().supportsSurface()) + .toList(); + } + + /** The dimension's carving entry with this id (the last of several with one id); empty when it declares none. */ + Optional dimensionCarving(String id) { + CarvingEntry found = null; + for (CarvingEntry entry : dimensionCarving) { + if (entry != null && !entry.id().isBlank() && entry.id().trim().equals(id)) { + found = entry; + } + } + return Optional.ofNullable(found); + } + + /** The cave profile {@code biome} declares; null when it declares none. */ + CaveProfile caveProfile(ResourceId biome) { + return running.settings().declaredBy(biome, CaveProfile.class).orElse(null); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java new file mode 100644 index 000000000..e06cbb3e8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java @@ -0,0 +1,198 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.terrain.floating; + +import art.arcane.iris.modules.carve.CarvingEntry; +import art.arcane.iris.modules.carve.CaveProfile; +import art.arcane.iris.modules.floating.FloatingChildBiome; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler; +import art.arcane.volmlib.util.cache.AtomicCache; +import art.arcane.volmlib.util.collection.KList; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; +import com.volmit.resource.ResourceId; + +import java.util.List; +import java.util.Optional; + +/** + * A {@link FloatingChildBiome} made ready for one world: the noise its styles build (each from the world's floating seed), + * the edge taper profile, the biome it targets, the carving profile sampler and the objects it hosts. One per decoded entry + * ({@link FloatingWorld#resolve}). + */ +public final class ResolvedFloatingChild { + private static final long FOOTPRINT_SALT = 0xF007B17DL; + private static final long EDGE_VARIATION_SALT = 0xED6E7A9E5L; + private static final long PICKER_SALT = 0x91C4E72DL; + private static final long ALTITUDE_SALT = 0xA17DEBBL; + private static final long TOP_SHAPE_SALT = 0x70970601DEFL; + private static final long BOTTOM_SALT = 0xB0770075CAFEL; + private static final long WALL_WARP_SALT = 0xA117BA17E0FL; + private static final long CARVE_SALT = 0xCA5EC1EE5EL; + private static final double MIN_SHRINK_FACTOR = 0.01; + + private final FloatingChildBiome settings; + private final FloatingWorld world; + private final AtomicCache> namedBiome = new AtomicCache<>(); + private final AtomicCache footprintCache = new AtomicCache<>(); + private final AtomicCache edgeTaperProfileCache = new AtomicCache<>(); + private final AtomicCache pickerCache = new AtomicCache<>(); + private final AtomicCache altitudeCache = new AtomicCache<>(); + private final AtomicCache topShapeCache = new AtomicCache<>(); + private final AtomicCache bottomCache = new AtomicCache<>(); + private final AtomicCache wallWarpCache = new AtomicCache<>(); + private final AtomicCache carveCache = new AtomicCache<>(); + private final AtomicCache carvingProfileSamplerCache = new AtomicCache<>(true); + + ResolvedFloatingChild(FloatingChildBiome settings, FloatingWorld world) { + this.settings = settings; + this.world = world; + } + + public FloatingChildBiome settings() { + return settings; + } + + public int rarity() { + return settings.rarity(); + } + + public NoiseSampler footprintNoise() { + return footprintCache.aquire(() -> noise(settings.footprintStyle(), FOOTPRINT_SALT)); + } + + public FloatingIslandEdgeProfile edgeTaperProfile() { + return edgeTaperProfileCache.aquire(() -> { + int width = FloatingIslandEdgeProfile.clampWidth(settings.edgeTaperWidth()); + double amplitude = FloatingIslandEdgeProfile.clampVariationAmplitude(settings.edgeTaperVariationAmplitude(), width); + NoiseSampler variation = amplitude > 0.0D ? noise(settings.edgeTaperVariationStyle(), EDGE_VARIATION_SALT) : null; + return new FloatingIslandEdgeProfile(width, settings.edgeTaperExponent(), amplitude, variation); + }); + } + + public NoiseSampler pickerNoise() { + return pickerCache.aquire(() -> noise(settings.pickerStyle(), PICKER_SALT)); + } + + public NoiseSampler altitudeNoise() { + return altitudeCache.aquire(() -> noise(settings.altitudeStyle(), ALTITUDE_SALT)); + } + + public NoiseSampler topShapeNoise() { + return topShapeCache.aquire(() -> noise(settings.topShapeStyle(), TOP_SHAPE_SALT)); + } + + public NoiseSampler bottomNoise() { + return bottomCache.aquire(() -> noise(settings.bottomStyle(), BOTTOM_SALT)); + } + + public NoiseSampler wallWarpNoise() { + Optional style = settings.wallWarpStyle(); + return style.isEmpty() ? null : wallWarpCache.aquire(() -> noise(style.get(), WALL_WARP_SALT)); + } + + public NoiseSampler carveNoise() { + Optional style = settings.carveStyle(); + return style.isEmpty() ? null : carveCache.aquire(() -> noise(style.get(), CARVE_SALT)); + } + + private NoiseSampler noise(NoiseStyle style, long salt) { + return world.noise().sampler(style, world.baseSeed() ^ salt); + } + + public CaveProfileSampler carvingProfileSampler() { + if (!hasCarvingReference()) { + return null; + } + + return carvingProfileSamplerCache.aquire(() -> { + CaveProfile profile = carvingBiome().map(world::caveProfile).orElse(null); + if (profile == null || !profile.enabled()) { + return null; + } + + return new CaveProfileSampler(world.noise(), world.carveSeed(), profile); + }); + } + + public boolean hasCarvingReference() { + return !settings.carving().isBlank(); + } + + /** The biome whose cave profile carves the island: the biome of the dimension's carving entry the id names, or the biome the id names. */ + Optional carvingBiome() { + String carving = settings.carving(); + Optional entry = world.dimensionCarving(carving); + if (entry.isEmpty()) { + return world.biome(carving); + } + String biomeKey = entry.get().biome().trim(); + return biomeKey.isEmpty() ? Optional.empty() : world.biome(biomeKey); + } + + public KList resolveTopObjects(ResourceId target) { + List surface = settings.inheritObjects() && target != null ? world.surfaceObjects(target) : List.of(); + return topObjects(settings, surface); + } + + /** The placements on the island's top: the inherited {@code surfaceObjects}, the child's overrides, or both, as its mode says. */ + public static KList topObjects(FloatingChildBiome settings, List surfaceObjects) { + return switch (settings.topObjectMode()) { + case REPLACE -> new KList<>(settings.topObjectOverrides()); + case MERGE -> { + KList merged = new KList<>(); + merged.addAll(surfaceObjects); + merged.addAll(settings.topObjectOverrides()); + yield merged; + } + case INHERIT_ONLY -> new KList<>(surfaceObjects); + }; + } + + public KList resolveBottomObjects() { + return bottomObjects(settings); + } + + /** The placements hung under the island: the child's overrides, unless its mode only inherits, which hangs nothing. */ + public static KList bottomObjects(FloatingChildBiome settings) { + return switch (settings.bottomObjectMode()) { + case INHERIT_ONLY -> new KList<>(); + case MERGE, REPLACE -> new KList<>(settings.bottomObjectOverrides()); + }; + } + + public boolean hasObjectShrink() { + double shrink = settings.objectShrinkFactor(); + return shrink > 0 && shrink < 1.0; + } + + /** How much the island shrinks the objects it hosts. */ + public double shrinkFactor() { + return Math.max(MIN_SHRINK_FACTOR, Math.min(1.0, settings.objectShrinkFactor())); + } + + /** The biome the island's palette, decorators and objects come from: the biome the child names, or {@code parent}. */ + public ResourceId realBiome(ResourceId parent) { + if (settings.biome().isBlank()) { + return parent; + } + return namedBiome.aquire(() -> world.biome(settings.biome())).orElse(parent); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/value/IrisDirection.java b/module/src/main/java/art/arcane/iris/engine/object/value/IrisDirection.java new file mode 100644 index 000000000..07cd1b927 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/value/IrisDirection.java @@ -0,0 +1,87 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.value; + +import art.arcane.iris.engine.object.annotations.Desc; + +/** One of the six axis directions, named by its axis and sign as packs write it. */ +@Desc("A direction object") +public enum IrisDirection { + @Desc("0, 1, 0") + UP_POSITIVE_Y(0, 1, 0), + @Desc("0, -1, 0") + DOWN_NEGATIVE_Y(0, -1, 0), + @Desc("0, 0, -1") + NORTH_NEGATIVE_Z(0, 0, -1), + @Desc("0, 0, 1") + SOUTH_POSITIVE_Z(0, 0, 1), + @Desc("1, 0, 0") + EAST_POSITIVE_X(1, 0, 0), + @Desc("-1, 0, 0") + WEST_NEGATIVE_X(-1, 0, 0); + + private final int x; + private final int y; + private final int z; + + IrisDirection(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + + @Override + public String toString() { + return switch (this) { + case DOWN_NEGATIVE_Y -> "Down"; + case EAST_POSITIVE_X -> "East"; + case NORTH_NEGATIVE_Z -> "North"; + case SOUTH_POSITIVE_Z -> "South"; + case UP_POSITIVE_Y -> "Up"; + case WEST_NEGATIVE_X -> "West"; + }; + } + + public boolean isVertical() { + return this == DOWN_NEGATIVE_Y || this == UP_POSITIVE_Y; + } + + public IrisDirection reverse() { + return switch (this) { + case DOWN_NEGATIVE_Y -> UP_POSITIVE_Y; + case EAST_POSITIVE_X -> WEST_NEGATIVE_X; + case NORTH_NEGATIVE_Z -> SOUTH_POSITIVE_Z; + case SOUTH_POSITIVE_Z -> NORTH_NEGATIVE_Z; + case UP_POSITIVE_Y -> DOWN_NEGATIVE_Y; + case WEST_NEGATIVE_X -> EAST_POSITIVE_X; + }; + } + + public int x() { + return x; + } + + public int y() { + return y; + } + + public int z() { + return z; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/value/IrisPosition.java b/module/src/main/java/art/arcane/iris/engine/object/value/IrisPosition.java new file mode 100644 index 000000000..c660b9ed1 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/value/IrisPosition.java @@ -0,0 +1,69 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.value; + +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.Snippet; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("position-3d") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents a position") +@Data +public class IrisPosition { + @Desc("The x position") + private int x = 0; + + @Desc("The y position") + private int y = 0; + + @Desc("The z position") + private int z = 0; + + public IrisPosition(double x, double y, double z) { + this((int) x, (int) y, (int) z); + } + + + public IrisPosition add(IrisPosition relativePosition) { + return new IrisPosition(relativePosition.x + x, relativePosition.y + y, relativePosition.z + z); + } + + public IrisPosition sub(IrisPosition relativePosition) { + return new IrisPosition(x - relativePosition.x, y - relativePosition.y, z - relativePosition.z); + } + + public IrisPosition copy() { + return new IrisPosition(x, y, z); + } + + @Override + public String toString() { + return "[" + getX() + "," + getY() + "," + getZ() + "]"; + } + + public boolean isLongerThan(IrisPosition s, int maxLength) { + return Math.abs(Math.pow(s.x - x, 2) + Math.pow(s.y - y, 2) + Math.pow(s.z - z, 2)) > maxLength * maxLength; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/BakeProfile.java b/module/src/main/java/art/arcane/iris/engine/procedural/BakeProfile.java new file mode 100644 index 000000000..75e37ba1c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/BakeProfile.java @@ -0,0 +1,85 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural; + +/** + * How long baking a pool of variants took, stage by stage, added up over every variant. {@link #NONE} times nothing, + * so world generation bakes at full speed. + */ +public class BakeProfile { + public static final BakeProfile NONE = new BakeProfile() { + @Override + public void startVariant() { + } + + @Override + public void lap(Stage stage) { + } + }; + + /** The steps a variant is baked in, in order. */ + public enum Stage { + PARTS("Parts"), + PAINT("Paint"), + DECORATE("Decorate"), + LEAVES("Leaves"), + BUILD("Build"); + + private final String label; + + Stage(String label) { + this.label = label; + } + + public String label() { + return label; + } + } + + private final long[] nanosByStage = new long[Stage.values().length]; + private long lapStartNanos; + private int variantCount; + + public void startVariant() { + variantCount++; + lapStartNanos = System.nanoTime(); + } + + /** Adds the time since the variant started, or since the last lap, to {@code stage}. */ + public void lap(Stage stage) { + long now = System.nanoTime(); + nanosByStage[stage.ordinal()] += now - lapStartNanos; + lapStartNanos = now; + } + + public long nanos(Stage stage) { + return nanosByStage[stage.ordinal()]; + } + + public long totalNanos() { + long total = 0L; + for (long nanos : nanosByStage) { + total += nanos; + } + return total; + } + + public int variantCount() { + return variantCount; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/IrisProceduralBlocks.java b/module/src/main/java/art/arcane/iris/engine/procedural/IrisProceduralBlocks.java new file mode 100644 index 000000000..8328b8d65 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/IrisProceduralBlocks.java @@ -0,0 +1,100 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.procedural; + +import art.arcane.volmlib.util.math.Vector3i; +import com.volmit.block.BlockState; +import com.volmit.block.PaletteSpec; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.ObjectBlock; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +/** + * Block helpers for baking procedural objects: reading a state's properties, and assembling a raw block map into a + * shape centered on x and z with its lowest layer one block above the anchor. + */ +public final class IrisProceduralBlocks { + /** The distance vanilla gives a leaf with no wood near enough to keep it. */ + public static final int UNREACHED_LEAF_DISTANCE = 7; + + private IrisProceduralBlocks() { + } + + /** Whether {@code state} is a leaf baked with no wood near enough for vanilla to keep it. */ + public static boolean isLeafTooFarFromWood(BlockState state) { + return hasProperty(state, "persistent") && String.valueOf(UNREACHED_LEAF_DISTANCE).equals(propertyValue(state, "distance")); + } + + public static boolean paletteSet(PaletteSpec palette) { + return palette != null && !palette.palette().isEmpty(); + } + + public static boolean hasProperty(BlockState state, String property) { + return state.properties().containsKey(property); + } + + public static String propertyValue(BlockState state, String property) { + return state.properties().get(property); + } + + /** The blocks centered on x and z, with their lowest layer one block above the anchor; null when there are none. */ + public static ProceduralShape assemble(Map blocks) { + if (blocks == null || blocks.isEmpty()) { + return null; + } + + Anchor anchor = Anchor.of(blocks.keySet()); + List placed = new ArrayList<>(blocks.size()); + for (Map.Entry entry : blocks.entrySet()) { + placed.add(new ObjectBlock(anchor.place(entry.getKey()), entry.getValue())); + } + + return new ProceduralShape(anchor.width(), anchor.height(), anchor.depth(), placed); + } + + /** Where {@link #assemble} moves each block of a set: centered on x and z, its lowest layer one block above the anchor. */ + public record Anchor(int minX, int minZ, int width, int height, int depth) { + public static Anchor of(Collection positions) { + int minX = Integer.MAX_VALUE; + int minY = Integer.MAX_VALUE; + int minZ = Integer.MAX_VALUE; + int maxX = Integer.MIN_VALUE; + int maxY = Integer.MIN_VALUE; + int maxZ = Integer.MIN_VALUE; + for (Vector3i v : positions) { + minX = Math.min(minX, v.getBlockX()); + minY = Math.min(minY, v.getBlockY()); + minZ = Math.min(minZ, v.getBlockZ()); + maxX = Math.max(maxX, v.getBlockX()); + maxY = Math.max(maxY, v.getBlockY()); + maxZ = Math.max(maxZ, v.getBlockZ()); + } + return new Anchor(minX, minZ, maxX - minX + 1, maxY - minY + 1, maxZ - minZ + 1); + } + + public BlockPosition place(Vector3i position) { + return new BlockPosition(position.getBlockX() - minX - width / 2, position.getBlockY() - height / 2 + 1, + position.getBlockZ() - minZ - depth / 2); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/ProceduralObjectCatalog.java b/module/src/main/java/art/arcane/iris/engine/procedural/ProceduralObjectCatalog.java new file mode 100644 index 000000000..6cd8dd9a2 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/ProceduralObjectCatalog.java @@ -0,0 +1,142 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.procedural; + +import art.arcane.iris.engine.procedural.part.ProceduralObject; +import art.arcane.iris.engine.procedural.part.ResolvedProceduralObject; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The pack's procedural objects, each read from {@code procedural/.json} and placed from any object placement + * as {@code procedural/}, or one variant as {@code procedural/#}. Variants are baked on first use. + */ +public final class ProceduralObjectCatalog { + /** The definitions, in {@code procedural/}; a placement's key for one is its file path, like {@code procedural/trees/oak}. */ + public static final ResourceKind DEFINITIONS = + ResourceKind.of("iris:objects/procedural", "procedural", ProceduralObject.class); + public static final String KEY_PREFIX = DEFINITIONS.folder() + "/"; + public static final char VARIANT_SEPARATOR = '#'; + + private final PackResources resources; + private final ModuleLog log; + private final Map> variantsByPath = new ConcurrentHashMap<>(); + + private ProceduralObjectCatalog(PackResources resources, ModuleLog log) { + this.resources = resources; + this.log = log; + } + + /** The catalog {@code world} keeps, so each definition bakes once per world. */ + public static ProceduralObjectCatalog of(PackWorld world) { + return world.state(ProceduralObjectCatalog.class, generating -> new ProceduralObjectCatalog(generating.resources(), generating.log())); + } + + /** A catalog of its own, for work outside any world such as working out the pack's reach; it bakes anew. */ + public static ProceduralObjectCatalog detached(PackResources resources, ModuleLog log) { + return new ProceduralObjectCatalog(resources, log); + } + + /** Whether {@code key} names a procedural object rather than a pack object. */ + public static boolean isProceduralKey(String key) { + return key != null && key.startsWith(KEY_PREFIX); + } + + /** The variant {@code key} pins, or for a key naming the whole pool the one {@code rng} picks; empty when none. */ + public Optional object(String key, RNG rng) { + ObjectKey parsed = ObjectKey.parse(key); + return variantsNamedBy(parsed).flatMap(variants -> parsed.isPinned() ? variants.variant(parsed.variantIndex()) : variants.variant(rng)); + } + + /** + * The variant {@code key} pins, or for a key naming the whole pool its first variant, so a caller without a random + * stream still gets the same object every time; empty when none. + */ + public Optional object(String key) { + ObjectKey parsed = ObjectKey.parse(key); + return variantsNamedBy(parsed).flatMap(variants -> parsed.isPinned() + ? variants.variant(parsed.variantIndex()) + : variants.variants().stream().findFirst()); + } + + /** The variants {@code key} names, pinned to one or not; empty when the pack has no such object. */ + public Optional variants(String key) { + return variantsNamedBy(ObjectKey.parse(key)); + } + + /** Every variant {@code key} may place: the one it pins, or the whole pool. */ + public List placeable(String key) { + ObjectKey parsed = ObjectKey.parse(key); + return variantsNamedBy(parsed).map(variants -> parsed.isPinned() + ? variants.variant(parsed.variantIndex()).stream().toList() + : variants.variants()).orElse(List.of()); + } + + private Optional variantsNamedBy(ObjectKey key) { + return variantsByPath.computeIfAbsent(key.path(), this::resolve); + } + + private Optional resolve(String path) { + ResourceId id = resources.idOf(path); + Optional definition; + try { + definition = resources.find(DEFINITIONS, id); + } catch (IllegalStateException failedToLoad) { + log.warnOnce("procedural-unreadable:" + path, "Couldn't read procedural object " + KEY_PREFIX + path + ": " + failedToLoad.getMessage()); + return Optional.empty(); + } + if (definition.isEmpty()) { + log.warnOnce("procedural-missing:" + path, "Couldn't find procedural object " + KEY_PREFIX + path); + return Optional.empty(); + } + return Optional.of(new ResolvedProceduralObject(path, definition.get(), resources)); + } + + /** A procedural object key split into the definition's path and, when it pins one, a variant index. */ + private record ObjectKey(String path, int variantIndex) { + private static final int UNPINNED = -1; + + static ObjectKey parse(String key) { + String path = key.substring(KEY_PREFIX.length()); + int separator = path.lastIndexOf(VARIANT_SEPARATOR); + if (separator < 0) { + return new ObjectKey(path, UNPINNED); + } + try { + return new ObjectKey(path.substring(0, separator), Integer.parseInt(path.substring(separator + 1))); + } catch (NumberFormatException notAnIndex) { + return new ObjectKey(path, UNPINNED); + } + } + + boolean isPinned() { + return variantIndex != UNPINNED; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/ProceduralShape.java b/module/src/main/java/art/arcane/iris/engine/procedural/ProceduralShape.java new file mode 100644 index 000000000..65876b4bf --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/ProceduralShape.java @@ -0,0 +1,27 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.procedural; + +import com.volmit.object.ObjectBlock; + +import java.util.List; + +/** A procedural object's blocks around its anchor, in the order they were made, and the size of the box they fill. */ +public record ProceduralShape(int width, int height, int depth, List blocks) { +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/ProceduralVariants.java b/module/src/main/java/art/arcane/iris/engine/procedural/ProceduralVariants.java new file mode 100644 index 000000000..bd4332160 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/ProceduralVariants.java @@ -0,0 +1,157 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.procedural; + +import art.arcane.iris.modules.objects.ObjectBuilder; +import art.arcane.iris.modules.objects.ObjectSize; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * The pool of variants one procedural definition bakes, placed through the object key {@code procedural/}: a + * placement picks one variant per object it places, or always the same one with {@code procedural/#}. + */ +public abstract class ProceduralVariants { + private static final long VARIANT_SEED_STRIDE = 7919L; + + private final String path; + private final long seed; + private final int variantCount; + private final PackResources resources; + private volatile List baked; + + protected ProceduralVariants(String path, long seed, int variantCount, PackResources resources) { + this.path = path; + this.seed = seed; + this.variantCount = Math.max(1, variantCount); + this.resources = resources; + } + + /** The shape variant {@code index} is baked as, from its own seeded stream; null when it has no blocks. */ + protected abstract ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks, BakeProfile profile); + + /** Where the pack keeps the definition, under {@code procedural/}, like {@code trees/oak}. */ + public String path() { + return path; + } + + /** The key placements name the whole pool by, like {@code procedural/trees/oak}. */ + public String key() { + return ProceduralObjectCatalog.KEY_PREFIX + path; + } + + /** The key variant {@code index} is placed under, like {@code procedural/trees/oak#0}. */ + public String variantKey(int index) { + return key() + ProceduralObjectCatalog.VARIANT_SEPARATOR + index; + } + + /** How many variants the definition asks for, known without baking; a variant may still bake no blocks. */ + public int variantCount() { + return variantCount; + } + + /** Every variant, baked on first use. */ + public List variants() { + List known = baked; + if (known != null) { + return known; + } + synchronized (this) { + if (baked == null) { + baked = List.copyOf(bake(newBuilder(), BakeProfile.NONE)); + } + return baked; + } + } + + /** Bakes every variant again the way world generation does, without keeping them, and times each stage. */ + public BakeProfile profileBake() { + BakeProfile profile = new BakeProfile(); + bake(newBuilder(), profile); + return profile; + } + + /** One of the variants, picked with {@code rng}; empty when none baked. */ + public Optional variant(RNG rng) { + List all = variants(); + return all.isEmpty() ? Optional.empty() : Optional.of(all.get(rng.i(all.size()))); + } + + /** The variant baked at {@code index}; empty when it baked no blocks or the definition asks for fewer. */ + public Optional variant(int index) { + String key = variantKey(index); + return variants().stream().filter(variant -> variant.name().equals(key)).findFirst(); + } + + /** The widest, tallest and deepest any variant reaches, each measured on its own. */ + public ObjectSize largestSize() { + int width = 0; + int height = 0; + int depth = 0; + for (PlaceableObject variant : variants()) { + width = Math.max(width, variant.width()); + height = Math.max(height, variant.height()); + depth = Math.max(depth, variant.depth()); + } + return new ObjectSize(width, height, depth); + } + + /** Bakes every variant; variant {@code i} is drawn from {@code seed + i * stride}. */ + private List bake(ObjectBuilder blocks, BakeProfile profile) { + List all = new ArrayList<>(); + for (int i = 0; i < variantCount; i++) { + profile.startVariant(); + ProceduralShape generated = generate(i, variantRng(i), blocks, profile); + if (generated == null || generated.blocks().isEmpty()) { + continue; + } + all.add(blocks.build(variantKey(i), generated.width(), generated.height(), generated.depth(), generated.blocks())); + profile.lap(BakeProfile.Stage.BUILD); + } + return all; + } + + protected final RNG variantRng(int index) { + return new RNG(seed + (index * VARIANT_SEED_STRIDE)); + } + + /** The index {@code variant} was baked at; -1 when it is not one of these variants. */ + protected final int bakeIndexOf(PlaceableObject variant) { + for (int index = 0; index < variantCount; index++) { + if (variantKey(index).equals(variant.name())) { + return index; + } + } + return -1; + } + + protected final ObjectBuilder newBuilder() { + return new ObjectBuilder(resources); + } + + /** The seed every variant is baked from. */ + public final long seed() { + return seed; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/BlobShape.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/BlobShape.java new file mode 100644 index 000000000..106884a81 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/BlobShape.java @@ -0,0 +1,160 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import art.arcane.volmlib.util.math.RNG; + +/** + * A blob: a volume around a center whose horizontal cross-section is scaled by a profile from its bottom to its top, + * an ellipsoid unless the pack shapes it, optionally hollowed into a shell. + */ +final class BlobShape implements PartShape { + private static final double LARGEST_RADIUS_BLOCKS = 96; + private static final double MINIMUM_RADIUS_BLOCKS = 0.05; + private static final int[][] SHELL_DIRECTIONS = {{1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}, {0, 1, 0}, {0, -1, 0}}; + private static final int[][] OPEN_SHELL_DIRECTIONS = {{1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}, {0, 1, 0}}; + + private final double[] center; + private final double radiusX; + private final double radiusZ; + private final double up; + private final double down; + private final ProceduralValue profile; + private final PartSection section; + private final double shell; + private final boolean open; + private final double outward; + + private BlobShape(double[] center, double radiusX, double radiusZ, double up, double down, ProceduralValue profile, + PartSection section, double shell, boolean open, double outward) { + this.center = center; + this.radiusX = radiusX; + this.radiusZ = radiusZ; + this.up = up; + this.down = down; + this.profile = profile; + this.section = section; + this.shell = shell; + this.open = open; + this.outward = outward; + } + + static BlobShape trace(PartBlob blob, PartSpot spot, RNG rng) { + double t = spot.parentT(); + double radius = clampRadius(blob.radius().sample(rng, t)); + double up = blob.height() == null ? radius : clampRadius(blob.height().sample(rng, t)); + double down = blob.depth() == null ? up : Math.max(0, Math.min(LARGEST_RADIUS_BLOCKS, blob.depth().sample(rng, t))); + double shell = Math.max(0, blob.shell().sample(rng, t)); + double outward = spot.hasOutward() ? spot.outward() : rng.d(0, 360); + return new BlobShape(spot.origin(), Math.max(MINIMUM_RADIUS_BLOCKS, radius * blob.stretchX()), + Math.max(MINIMUM_RADIUS_BLOCKS, radius * blob.stretchZ()), up, down, + blob.profile() == null ? null : blob.profile().fix(rng), blob.section(), shell, blob.open(), outward); + } + + void draw(PartFill fill, double roughness, double jitter) { + int reachX = (int) Math.ceil(radiusX * (1 + roughness) + 1); + int reachZ = (int) Math.ceil(radiusZ * (1 + roughness) + 1); + int cx = (int) Math.round(center[0]); + int cy = (int) Math.round(center[1]); + int cz = (int) Math.round(center[2]); + for (int y = cy - (int) Math.ceil(down) - 1; y <= cy + (int) Math.ceil(up) + 1; y++) { + for (int x = cx - reachX; x <= cx + reachX; x++) { + for (int z = cz - reachZ; z <= cz + reachZ; z++) { + drawBlock(fill, x, y, z, roughness, jitter); + } + } + } + } + + private void drawBlock(PartFill fill, int x, int y, int z, double roughness, double jitter) { + if (!inside(x, y, z, roughness, fill.seed())) { + return; + } + if (shell > 0 && !nearSurface(x, y, z, roughness, fill.seed())) { + return; + } + double dx = x - center[0]; + double dy = y - center[1]; + double dz = z - center[2]; + double edge = edge(dx, dy, dz); + if (jitter > 0 && edge > 1 - 1 / (Math.max(radiusX, radiusZ) + 1) && PartNoise.hash(x, y, z, fill.seed() + 77L) < jitter * 0.35) { + return; + } + double height = (dy + down + 0.5) / (up + down + 1); + double falloffEdge = Math.sqrt(sq(dx / (radiusX + 1)) + sq(dy / ((dy >= 0 ? up : down) + 1)) + sq(dz / (radiusZ + 1))); + fill.place(x, y, z, falloffEdge, height, PartCanvas.Axis.Y); + } + + private boolean inside(int x, int y, int z, double roughness, long seed) { + double wobble = roughness <= 0 ? 0 : (PartNoise.hash(x, y, z, seed + 4201L) - 0.5) * roughness * 1.2; + return edge(x - center[0], y - center[1], z - center[2]) <= 1 + wobble; + } + + /** Whether the outside lies within the shell's thickness, looking up and sideways, and down unless the shell is open. */ + private boolean nearSurface(int x, int y, int z, double roughness, long seed) { + int thickness = Math.max(1, (int) Math.round(shell)); + int[][] directions = open ? OPEN_SHELL_DIRECTIONS : SHELL_DIRECTIONS; + for (int step = 1; step <= thickness; step++) { + for (int[] direction : directions) { + if (!inside(x + direction[0] * step, y + direction[1] * step, z + direction[2] * step, roughness, seed)) { + return true; + } + } + } + return false; + } + + /** How far out a point is, where 1 is the surface; above 1 is outside. */ + private double edge(double dx, double dy, double dz) { + double vertical = dy >= 0 ? dy / (up + 0.5) : dy / (down + 0.5); + if (Math.abs(vertical) > 1) { + return Double.MAX_VALUE; + } + double width = profile == null + ? Math.sqrt(1 - vertical * vertical) + : Math.max(0, profile.at((dy + down + 0.5) / (up + down + 1))); + if (width <= 0) { + return Double.MAX_VALUE; + } + return Sections.norm(section, dx / radiusX, dz / radiusZ) / width; + } + + @Override + public PartSpot spotAt(double t) { + double y = center[1] - down + Math.max(0, Math.min(1, t)) * (up + down); + return new PartSpot(new double[]{center[0], y, center[2]}, Vectors.UP.clone(), t, up + down + 1, outward); + } + + @Override + public double length() { + return up + down + 1; + } + + @Override + public double defaultAt() { + return 1; + } + + private static double clampRadius(double radius) { + return Math.max(0, Math.min(LARGEST_RADIUS_BLOCKS, radius)); + } + + private static double sq(double value) { + return value * value; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/BlockChoice.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/BlockChoice.java new file mode 100644 index 000000000..77b1704c9 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/BlockChoice.java @@ -0,0 +1,45 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import art.arcane.iris.engine.procedural.IrisProceduralBlocks; +import art.arcane.iris.modules.objects.ObjectBuilder; +import com.volmit.block.PaletteSpec; +import com.volmit.block.BlockState; + +/** A block or a noise palette to take one from, optionally banded by height for strata. */ +record BlockChoice(String block, PaletteSpec palette, int bands) { + /** The block at the position; null when neither block nor palette names one. */ + BlockState at(ObjectBuilder blocks, long seed, int x, int y, int z) { + if (IrisProceduralBlocks.paletteSet(palette)) { + if (bands > 0) { + int band = Math.floorDiv(y, bands); + return blocks.pick(palette, seed + band * 31L, x, band, z); + } + return blocks.pick(palette, seed, x, y, z); + } + if (block == null || block.isEmpty()) { + return null; + } + return blocks.block(block); + } + + boolean isSet() { + return IrisProceduralBlocks.paletteSet(palette) || (block != null && !block.isEmpty()); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/BranchAzimuth.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/BranchAzimuth.java new file mode 100644 index 000000000..2342eaad0 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/BranchAzimuth.java @@ -0,0 +1,36 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; + +@Desc("Which way around its parent each new branch points.") +public enum BranchAzimuth { + @Desc("Any direction.") + RANDOM, + @Desc("Each branch turns the golden angle (about 137.5 degrees) from the last, so none line up.") + GOLDEN, + @Desc("Each branch points opposite the last.") + ALTERNATE, + @Desc("Branches come in rings of 'whorl' evenly spaced branches.") + WHORL, + @Desc("All branches are spread evenly around the parent.") + EVEN, + @Desc("Branches fan out side by side around the parent's own direction, 'fan' degrees apart.") + FAN +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/ClusterLayout.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/ClusterLayout.java new file mode 100644 index 000000000..6f9d99d50 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/ClusterLayout.java @@ -0,0 +1,32 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; + +@Desc("How the parts of a cluster are laid out around its center.") +public enum ClusterLayout { + @Desc("Anywhere inside the radius.") + RANDOM, + @Desc("Evenly spaced on a circle of the radius.") + RING, + @Desc("In a row across the radius.") + LINE, + @Desc("A sunflower spiral filling the radius evenly.") + GOLDEN +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/DecorationSpot.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/DecorationSpot.java new file mode 100644 index 000000000..578d10932 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/DecorationSpot.java @@ -0,0 +1,38 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; + +@Desc("Where a decoration is placed on the object.") +public enum DecorationSpot { + @Desc("On every block that is open above.") + ABOVE, + @Desc("Under every block that is open below; set length for hanging strands.") + BELOW, + @Desc("Against every open horizontal side.") + SIDE, + @Desc("On the highest block of each column.") + TOP, + @Desc("Under the lowest block of each column; set length for hanging strands.") + BOTTOM, + @Desc("Just past the end of every stem.") + TIPS, + @Desc("On the ground around where the object stands, out to the radius.") + GROUND +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/Decorator.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/Decorator.java new file mode 100644 index 000000000..a9c56cb5e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/Decorator.java @@ -0,0 +1,271 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import art.arcane.iris.engine.procedural.IrisProceduralBlocks; +import art.arcane.iris.modules.objects.ObjectBuilder; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.geometry.BlockFace; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +/** + * Places decorations against the painted object. A decoration attaches to the block it rests on: vines and lichen + * grow toward it, directional blocks face away from it and lanterns hang under it. + */ +final class Decorator { + private static final long DECORATION_SEED_STRIDE = 911L; + private static final BlockFace[] SIDES = {BlockFace.EAST, BlockFace.WEST, BlockFace.SOUTH, BlockFace.NORTH}; + + private final PartCanvas canvas; + private final Map painted; + private final ObjectBuilder blocks; + private final long paletteSeed; + private final int groundY; + + /** @param groundY the lowest height above the terrain; anything below it ends up buried, so nothing decorates there */ + Decorator(PartCanvas canvas, Map painted, ObjectBuilder blocks, long paletteSeed, int groundY) { + this.canvas = canvas; + this.painted = painted; + this.blocks = blocks; + this.paletteSeed = paletteSeed; + this.groundY = groundY; + } + + void decorate(List decorations, long seed) { + for (int index = 0; index < decorations.size(); index++) { + ProceduralDecoration decoration = decorations.get(index); + if (!decoration.choice().isSet()) { + continue; + } + long decorationSeed = seed + index * DECORATION_SEED_STRIDE; + RNG rng = new RNG(decorationSeed); + for (Spot spot : spots(decoration, rng)) { + if (spot.y() >= groundY && PartNoise.passes(decoration.pattern(), decoration.chance(), decoration.scale(), spot.x(), spot.y(), spot.z(), decorationSeed)) { + place(decoration, spot, rng); + } + } + } + } + + private void place(ProceduralDecoration decoration, Spot spot, RNG rng) { + boolean hangs = decoration.at() == DecorationSpot.BELOW || decoration.at() == DecorationSpot.BOTTOM; + int strand = hangs ? Math.max(1, (int) Math.round(decoration.length().sample(rng, 0))) : 1; + for (int step = 0; step < strand; step++) { + int y = spot.y() - step; + long key = PartCanvas.key(spot.x(), y, spot.z()); + if (y < groundY || painted.containsKey(key)) { + return; + } + BlockState state = decoration.choice().at(blocks, paletteSeed, spot.x(), y, spot.z()); + if (state == null || blocks.has(state, BlockTrait.AIR)) { + return; + } + painted.put(key, attached(state, spot.support())); + } + } + + private List spots(ProceduralDecoration decoration, RNG rng) { + List decorated = decoratedBlocks(decoration); + return switch (decoration.at()) { + case ABOVE -> besideEach(decorated, BlockFace.UP); + case BELOW -> besideEach(decorated, BlockFace.DOWN); + case SIDE -> besideEach(decorated, SIDES); + case TOP -> columnEnds(decorated, true); + case BOTTOM -> columnEnds(decorated, false); + case TIPS -> tips(decoration); + case GROUND -> ground(decoration.radius().sample(rng, 0)); + }; + } + + /** The painted blocks of the roles the decoration is for, in a stable order. */ + private List decoratedBlocks(ProceduralDecoration decoration) { + Set roles = new HashSet<>(); + for (String role : decoration.on()) { + roles.add(canvas.role(role)); + } + List decorated = new ArrayList<>(); + for (long key : painted.keySet()) { + PartCanvas.Cell cell = canvas.get(key); + if (cell != null && (roles.isEmpty() || roles.contains(cell.role()))) { + decorated.add(key); + } + } + decorated.sort(Long::compare); + return decorated; + } + + private List besideEach(List decorated, BlockFace... faces) { + List spots = new ArrayList<>(); + Set taken = new HashSet<>(); + for (long key : decorated) { + for (BlockFace face : faces) { + int[] step = stepToward(face); + int x = PartCanvas.x(key) + step[0]; + int y = PartCanvas.y(key) + step[1]; + int z = PartCanvas.z(key) + step[2]; + long spotKey = PartCanvas.key(x, y, z); + if (!painted.containsKey(spotKey) && taken.add(spotKey)) { + spots.add(new Spot(x, y, z, opposite(face))); + } + } + } + return spots; + } + + private List columnEnds(List decorated, boolean top) { + Map endByColumn = new HashMap<>(); + for (long key : decorated) { + long column = PartCanvas.key(PartCanvas.x(key), 0, PartCanvas.z(key)); + int y = PartCanvas.y(key); + endByColumn.merge(column, y, top ? Math::max : Math::min); + } + List spots = new ArrayList<>(); + endByColumn.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry -> { + int x = PartCanvas.x(entry.getKey()); + int z = PartCanvas.z(entry.getKey()); + int y = entry.getValue() + (top ? 1 : -1); + if (!painted.containsKey(PartCanvas.key(x, y, z))) { + spots.add(new Spot(x, y, z, top ? BlockFace.DOWN : BlockFace.UP)); + } + }); + return spots; + } + + private List tips(ProceduralDecoration decoration) { + Set roles = new HashSet<>(); + for (String role : decoration.on()) { + roles.add(canvas.role(role)); + } + List spots = new ArrayList<>(); + for (PartCanvas.Tip tip : canvas.tips()) { + if (!roles.isEmpty() && !roles.contains(tip.role())) { + continue; + } + int x = tip.x() + (int) Math.round(tip.heading()[0]); + int y = tip.y() + (int) Math.round(tip.heading()[1]); + int z = tip.z() + (int) Math.round(tip.heading()[2]); + if (!painted.containsKey(PartCanvas.key(x, y, z))) { + spots.add(new Spot(x, y, z, supportToward(tip.x() - x, tip.y() - y, tip.z() - z))); + } + } + return spots; + } + + /** Every open ground spot within the radius of where the object stands, so an arch gets plants around both feet. */ + private List ground(double radius) { + int reach = (int) Math.ceil(radius); + Set nearby = new TreeSet<>(); + for (long foot : footprint()) { + int footX = PartCanvas.x(foot); + int footZ = PartCanvas.z(foot); + for (int x = footX - reach; x <= footX + reach; x++) { + for (int z = footZ - reach; z <= footZ + reach; z++) { + if (Math.hypot(x - footX, z - footZ) <= radius) { + nearby.add(PartCanvas.key(x, groundY, z)); + } + } + } + } + List spots = new ArrayList<>(); + for (long key : nearby) { + int x = PartCanvas.x(key); + int z = PartCanvas.z(key); + if (!painted.containsKey(key) && !painted.containsKey(PartCanvas.key(x, groundY + 1, z))) { + spots.add(new Spot(x, groundY, z, BlockFace.DOWN)); + } + } + return spots; + } + + /** The columns where the object meets the ground, or its origin if it does not reach the ground. */ + private Set footprint() { + Set footprint = new TreeSet<>(); + for (long key : painted.keySet()) { + if (PartCanvas.y(key) == groundY) { + footprint.add(PartCanvas.key(PartCanvas.x(key), groundY, PartCanvas.z(key))); + } + } + if (footprint.isEmpty()) { + footprint.add(PartCanvas.key(0, groundY, 0)); + } + return footprint; + } + + private static BlockFace supportToward(int dx, int dy, int dz) { + if (dy > 0) { + return BlockFace.UP; + } + if (dy < 0) { + return BlockFace.DOWN; + } + if (Math.abs(dx) >= Math.abs(dz)) { + return dx >= 0 ? BlockFace.EAST : BlockFace.WEST; + } + return dz >= 0 ? BlockFace.SOUTH : BlockFace.NORTH; + } + + /** {@code state} turned to rest on the block toward {@code support}. */ + private BlockState attached(BlockState state, BlockFace support) { + String side = support.name().toLowerCase(); + if ("false".equals(IrisProceduralBlocks.propertyValue(state, side))) { + return blocks.withPropertyIfAccepted(state, side, "true"); + } + if (support == BlockFace.UP && IrisProceduralBlocks.hasProperty(state, "hanging")) { + return blocks.withPropertyIfAccepted(state, "hanging", "true"); + } + if (IrisProceduralBlocks.hasProperty(state, "facing")) { + return blocks.withPropertyIfAccepted(state, "facing",opposite(support).name().toLowerCase()); + } + return state; + } + + private static int[] stepToward(BlockFace face) { + return switch (face) { + case UP -> new int[]{0, 1, 0}; + case DOWN -> new int[]{0, -1, 0}; + case NORTH -> new int[]{0, 0, -1}; + case SOUTH -> new int[]{0, 0, 1}; + case EAST -> new int[]{1, 0, 0}; + case WEST -> new int[]{-1, 0, 0}; + }; + } + + private static BlockFace opposite(BlockFace face) { + return switch (face) { + case UP -> BlockFace.DOWN; + case DOWN -> BlockFace.UP; + case NORTH -> BlockFace.SOUTH; + case SOUTH -> BlockFace.NORTH; + case EAST -> BlockFace.WEST; + case WEST -> BlockFace.EAST; + }; + } + + /** An empty block a decoration may go in, and the side its support is on. */ + private record Spot(int x, int y, int z, BlockFace support) { + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/LeafDecay.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/LeafDecay.java new file mode 100644 index 000000000..dcfda1fff --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/LeafDecay.java @@ -0,0 +1,132 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.procedural.part; + +import art.arcane.iris.engine.procedural.IrisProceduralBlocks; +import art.arcane.iris.modules.objects.ObjectBuilder; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Gives leaves the state vanilla decay expects: every leaf is told its distance to wood. Leaves farther from wood than + * vanilla keeps are made persistent, so they stay; the pack's parts should keep wood near them instead. + */ +final class LeafDecay { + private static final int UNREACHED_DISTANCE = IrisProceduralBlocks.UNREACHED_LEAF_DISTANCE; + private static final int[][] NEIGHBORS = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; + + private final Map blocks; + private final ObjectBuilder builder; + private final Set leaves = new LinkedHashSet<>(); + + private LeafDecay(Map blocks, ObjectBuilder builder) { + this.blocks = blocks; + this.builder = builder; + List keys = new ArrayList<>(blocks.keySet()); + keys.sort(Long::compare); + for (long key : keys) { + if (isLeaf(blocks.get(key))) { + leaves.add(key); + } + } + } + + /** Leaves that decay naturally, except those too far from wood, which are kept persistent. */ + static void supportLeaves(Map blocks, ObjectBuilder builder) { + LeafDecay decay = new LeafDecay(blocks, builder); + if (decay.leaves.isEmpty()) { + return; + } + decay.markDistances(); + } + + /** Leaves that never decay. */ + static void persistLeaves(Map blocks, ObjectBuilder builder) { + LeafDecay decay = new LeafDecay(blocks, builder); + for (long leaf : decay.leaves) { + decay.setLeafState(leaf, true, 1); + } + } + + private void markDistances() { + Map distance = distances(); + for (long leaf : leaves) { + Integer d = distance.get(leaf); + if (d != null && d < UNREACHED_DISTANCE) { + setLeafState(leaf, false, Math.max(1, d)); + } else { + setLeafState(leaf, true, UNREACHED_DISTANCE); + } + } + } + + /** How many leaf steps each leaf is from wood, up to the farthest vanilla tracks. */ + private Map distances() { + Map distance = new HashMap<>(); + ArrayDeque queue = new ArrayDeque<>(); + for (long leaf : leaves) { + for (int[] n : NEIGHBORS) { + BlockState neighbor = blocks.get(PartCanvas.key(PartCanvas.x(leaf) + n[0], PartCanvas.y(leaf) + n[1], PartCanvas.z(leaf) + n[2])); + if (neighbor != null && builder.has(neighbor, BlockTrait.LOG)) { + distance.put(leaf, 1); + queue.add(leaf); + break; + } + } + } + while (!queue.isEmpty()) { + long leaf = queue.poll(); + int d = distance.get(leaf); + if (d >= UNREACHED_DISTANCE) { + continue; + } + for (int[] n : NEIGHBORS) { + long next = PartCanvas.key(PartCanvas.x(leaf) + n[0], PartCanvas.y(leaf) + n[1], PartCanvas.z(leaf) + n[2]); + BlockState state = blocks.get(next); + if (state == null || !isLeaf(state)) { + continue; + } + Integer known = distance.get(next); + if (known == null || known > d + 1) { + distance.put(next, d + 1); + queue.add(next); + } + } + } + return distance; + } + + private void setLeafState(long leaf, boolean persistent, int distance) { + BlockState state = blocks.get(leaf); + state = builder.withPropertyIfAccepted(state, "persistent", String.valueOf(persistent)); + blocks.put(leaf, builder.withPropertyIfAccepted(state, "distance", String.valueOf(distance))); + } + + private static boolean isLeaf(BlockState state) { + return IrisProceduralBlocks.hasProperty(state, "persistent") && IrisProceduralBlocks.hasProperty(state, "distance"); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/MaterialPainter.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/MaterialPainter.java new file mode 100644 index 000000000..b3be334d5 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/MaterialPainter.java @@ -0,0 +1,135 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import art.arcane.iris.engine.procedural.IrisProceduralBlocks; +import art.arcane.iris.modules.objects.ObjectBuilder; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** Turns the canvas into block data: each block takes its role's material, or the first of its rules that applies. */ +final class MaterialPainter { + private static final long RULE_SEED_STRIDE = 7907L; + private static final int[][] SIDES = {{1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}}; + + private final PartCanvas canvas; + private final Map materialByRole = new HashMap<>(); + private final ProceduralMaterial fallback; + private final ObjectBuilder blocks; + private final long paletteSeed; + private final long ruleSeed; + private final int lowestY; + private final int heightSpan; + + MaterialPainter(PartCanvas canvas, List materials, ObjectBuilder blocks, long paletteSeed, long ruleSeed) { + this.canvas = canvas; + this.blocks = blocks; + this.paletteSeed = paletteSeed; + this.ruleSeed = ruleSeed; + this.fallback = materials.isEmpty() ? null : materials.getFirst(); + for (ProceduralMaterial material : materials) { + materialByRole.putIfAbsent(canvas.role(material.role()), material); + } + int lowest = Integer.MAX_VALUE; + int highest = Integer.MIN_VALUE; + for (long key : canvas.cells().keySet()) { + lowest = Math.min(lowest, PartCanvas.y(key)); + highest = Math.max(highest, PartCanvas.y(key)); + } + this.lowestY = lowest; + this.heightSpan = Math.max(1, highest - lowest); + } + + /** The block of every claimed position, leaving out those a rule turned to air. */ + Map paint() { + Map painted = new HashMap<>(); + for (Map.Entry entry : canvas.cells().entrySet()) { + BlockState state = blockFor(entry.getKey(), entry.getValue()); + if (state != null && !blocks.has(state, BlockTrait.AIR)) { + painted.put(entry.getKey(), state); + } + } + return painted; + } + + private BlockState blockFor(long key, PartCanvas.Cell cell) { + ProceduralMaterial material = materialByRole.getOrDefault(cell.role(), fallback); + if (material == null) { + return null; + } + int x = PartCanvas.x(key); + int y = PartCanvas.y(key); + int z = PartCanvas.z(key); + BlockChoice choice = material.choice(); + List rules = material.rules(); + for (int index = 0; index < rules.size(); index++) { + if (applies(rules.get(index), index, x, y, z, cell)) { + choice = rules.get(index).choice(); + break; + } + } + BlockState state = choice.at(blocks, paletteSeed, x, y, z); + if (state == null || blocks.has(state, BlockTrait.AIR)) { + return state; + } + return alignedToAxis(state, cell.axis()); + } + + private boolean applies(MaterialRule rule, int index, int x, int y, int z, PartCanvas.Cell cell) { + double height = (y - lowestY) / (double) heightSpan; + if (rule.height() != null && !rule.height().contains(height)) { + return false; + } + if (rule.along() != null && !rule.along().contains(cell.along())) { + return false; + } + if (rule.face() != null && !open(rule.face(), x, y, z)) { + return false; + } + return PartNoise.passes(rule.pattern(), rule.chance().at(height), rule.scale(), x, y, z, ruleSeed + index * RULE_SEED_STRIDE); + } + + private boolean open(RuleFace face, int x, int y, int z) { + return switch (face) { + case UP -> !canvas.has(x, y + 1, z); + case DOWN -> !canvas.has(x, y - 1, z); + case SIDE -> openSide(x, y, z); + case ANY -> openSide(x, y, z) || !canvas.has(x, y + 1, z) || !canvas.has(x, y - 1, z); + }; + } + + private boolean openSide(int x, int y, int z) { + for (int[] side : SIDES) { + if (!canvas.has(x + side[0], y, z + side[2])) { + return true; + } + } + return false; + } + + private BlockState alignedToAxis(BlockState state, PartCanvas.Axis axis) { + if (axis == PartCanvas.Axis.NONE || !IrisProceduralBlocks.hasProperty(state, "axis")) { + return state; + } + return blocks.withPropertyIfAccepted(state, "axis",axis.name().toLowerCase()); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/MaterialRule.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/MaterialRule.java new file mode 100644 index 000000000..08cce07fe --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/MaterialRule.java @@ -0,0 +1,85 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; + +@Desc("Swaps a material's block where its conditions hold, such as moss on top faces or a cap on the highest blocks. Use minecraft:air to erode blocks away.") +public final class MaterialRule { + @Ref(Reference.BLOCK) + @Desc("The block to swap in. Ignored when palette is set.") + private String block; + + @Desc("A noise palette to swap in.") + private PaletteSpec palette; + + @MinNumber(0) + @Desc("If above 0, the palette changes every this many blocks of height, for strata.") + private int bands = 0; + + @Desc("The chance a block that meets the conditions is swapped. A curve runs from the bottom (0) to the top (1) of the object.") + private ProceduralValue chance = ProceduralValue.constant(1); + + @Desc("How the chance is spread over the blocks.") + private PartPattern pattern = PartPattern.RANDOM; + + @MinNumber(1) + @Desc("The size of the patches in blocks for the PATCHES pattern.") + private double scale = 3; + + @Desc("Only swaps blocks within this stretch of the object's height, from the bottom (0) to the top (1).") + private ProceduralSpan height; + + @Desc("Only swaps blocks within this stretch of their own part, from its base (0) to its tip (1).") + private ProceduralSpan along; + + @Desc("Only swaps blocks open to the air on this side.") + private RuleFace face; + + public BlockChoice choice() { + return new BlockChoice(block, palette, bands); + } + + public ProceduralValue chance() { + return chance == null ? ProceduralValue.constant(1) : chance; + } + + public PartPattern pattern() { + return pattern == null ? PartPattern.RANDOM : pattern; + } + + public double scale() { + return scale; + } + + public ProceduralSpan height() { + return height; + } + + public ProceduralSpan along() { + return along; + } + + public RuleFace face() { + return face; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/ObjectBaker.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/ObjectBaker.java new file mode 100644 index 000000000..b036ccefb --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/ObjectBaker.java @@ -0,0 +1,120 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import art.arcane.iris.engine.procedural.BakeProfile; +import com.volmit.geometry.BlockPosition; +import art.arcane.iris.engine.procedural.IrisProceduralBlocks; +import art.arcane.iris.modules.objects.ObjectBuilder; +import art.arcane.iris.engine.procedural.ProceduralShape; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.math.Vector3i; +import com.volmit.block.BlockState; + +import java.util.HashMap; +import java.util.Map; + +/** Bakes one variant of a procedural object: grows its parts, paints them, decorates them and settles the leaves. */ +final class ObjectBaker { + private static final long DECORATION_SEED_SALT = 77777L; + private static final long RULE_SEED_SALT = 4111L; + + private ObjectBaker() { + } + + static ProceduralShape bake(ProceduralObject definition, PartOutline outline, RNG rng, ObjectBuilder blocks, BakeProfile profile) { + BakedBlocks baked = bakeBlocks(definition, outline, rng, blocks, profile); + return baked == null ? null : IrisProceduralBlocks.assemble(baked.placed()); + } + + /** Bakes the variant {@code rng} draws, the same as {@link #bake}, and tells which part placed each of its blocks. */ + static PartTrace trace(ProceduralObject definition, PartOutline outline, RNG rng, ObjectBuilder blocks) { + BakedBlocks baked = bakeBlocks(definition, outline, rng, blocks, BakeProfile.NONE); + if (baked == null) { + return PartTrace.EMPTY; + } + IrisProceduralBlocks.Anchor anchor = IrisProceduralBlocks.Anchor.of(baked.placed().keySet()); + Map partsByBlock = new HashMap<>(); + for (long key : baked.painted().keySet()) { + PartCanvas.Cell cell = baked.canvas().get(key); + if (cell == null) { + continue; + } + BlockPosition position = anchor.place(baked.sunkPosition(key)); + partsByBlock.put(PartCanvas.key(position.x(), position.y(), position.z()), cell.part()); + } + return new PartTrace(partsByBlock); + } + + private static BakedBlocks bakeBlocks(ProceduralObject definition, PartOutline outline, RNG rng, ObjectBuilder blocks, + BakeProfile profile) { + PartCanvas canvas = new PartCanvas(); + long variantSeed = rng.nextLong(); + new PartGrower(canvas, definition.defaultRole(), outline).growRoots(definition.parts(), variantSeed); + profile.lap(BakeProfile.Stage.PARTS); + if (canvas.isEmpty()) { + return null; + } + + Map painted = new MaterialPainter(canvas, definition.materials(), blocks, definition.seed(), + variantSeed + RULE_SEED_SALT).paint(); + int sinkDepth = sinkDepth(painted, definition.sink()); + profile.lap(BakeProfile.Stage.PAINT); + new Decorator(canvas, painted, blocks, definition.seed(), sinkDepth).decorate(definition.decorations(), variantSeed + DECORATION_SEED_SALT); + profile.lap(BakeProfile.Stage.DECORATE); + if (definition.leafDecay()) { + LeafDecay.supportLeaves(painted, blocks); + } else { + LeafDecay.persistLeaves(painted, blocks); + } + if (definition.waterlogged()) { + waterlog(painted, blocks); + } + profile.lap(BakeProfile.Stage.LEAVES); + return new BakedBlocks(canvas, painted, sinkDepth); + } + + private static void waterlog(Map painted, ObjectBuilder blocks) { + painted.replaceAll((key, state) -> "false".equals(IrisProceduralBlocks.propertyValue(state, "waterlogged")) + ? blocks.withPropertyIfAccepted(state, "waterlogged", "true") : state); + } + + /** How far the object sinks: a fraction of its height. Heights below it end up underground. */ + private static int sinkDepth(Map painted, double sink) { + int lowest = Integer.MAX_VALUE; + int highest = Integer.MIN_VALUE; + for (long key : painted.keySet()) { + lowest = Math.min(lowest, PartCanvas.y(key)); + highest = Math.max(highest, PartCanvas.y(key)); + } + return (int) Math.round(Math.max(0, Math.min(1, sink)) * (highest - lowest + 1)); + } + + /** A variant's blocks before they are anchored: the parts' canvas, the painted blocks and how far they sink. */ + private record BakedBlocks(PartCanvas canvas, Map painted, int sinkDepth) { + Map placed() { + Map placed = new HashMap<>(); + painted.forEach((key, state) -> placed.put(sunkPosition(key), state)); + return placed; + } + + Vector3i sunkPosition(long key) { + return new Vector3i(PartCanvas.x(key), PartCanvas.y(key) - sinkDepth, PartCanvas.z(key)); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartBlob.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartBlob.java new file mode 100644 index 000000000..a67ba8348 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartBlob.java @@ -0,0 +1,108 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +@Desc("A rounded volume centered where the part sits: a leaf crown, boulder, cap, coral head or base. Values given as a curve run over where the blob sits on its parent.") +public final class PartBlob { + @Desc("The horizontal radius in blocks.") + private ProceduralValue radius = ProceduralValue.constant(2); + + @Desc("How far the blob reaches above its center, in blocks. Unset, it matches the radius.") + private ProceduralValue height; + + @Desc("How far the blob reaches below its center, in blocks. Unset, it matches the height; 0 makes a dome.") + private ProceduralValue depth; + + @MinNumber(0) + @Desc("Stretches the blob along east-west; 0.1 flattens it into a north-south fan.") + private double stretchX = 1; + + @MinNumber(0) + @Desc("Stretches the blob along north-south; 0.1 flattens it into an east-west fan.") + private double stretchZ = 1; + + @Desc("A multiplier on the radius from the bottom (0) to the top (1) of the blob. Unset, the blob is an ellipsoid; [[0, 1], [1, 0]] makes a cone, [[0, 1], [1, 1]] a cylinder.") + private ProceduralValue profile; + + @Desc("The horizontal cross-section of the blob.") + private PartSection section = PartSection.ROUND; + + @Desc("If above 0, the blob is hollow, keeping only the blocks this many blocks or fewer from its surface.") + private ProceduralValue shell = ProceduralValue.constant(0); + + @Desc("If true the shell has no floor: only the surface above and around counts, like a mushroom cap.") + private boolean open = false; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How lumpy the surface is, from 0 (smooth) to 1 (very lumpy).") + private double roughness = 0; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How many blocks along the surface are knocked off at random, from 0 to 1.") + private double jitter = 0; + + public ProceduralValue radius() { + return radius == null ? ProceduralValue.constant(2) : radius; + } + + public ProceduralValue height() { + return height; + } + + public ProceduralValue depth() { + return depth; + } + + public double stretchX() { + return stretchX; + } + + public double stretchZ() { + return stretchZ; + } + + public ProceduralValue profile() { + return profile; + } + + public PartSection section() { + return section == null ? PartSection.ROUND : section; + } + + public ProceduralValue shell() { + return shell == null ? ProceduralValue.constant(0) : shell; + } + + public boolean open() { + return open; + } + + public double roughness() { + return roughness; + } + + public double jitter() { + return jitter; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartBranches.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartBranches.java new file mode 100644 index 000000000..c2432bfad --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartBranches.java @@ -0,0 +1,107 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; + +@Desc("Grows copies of a part out of its parent: branches off a trunk, arms off a coral stalk, forks at a tip. Values given as a curve run from the parent's base (0) to its tip (1).") +public final class PartBranches { + @Desc("How many copies grow. Ignored when chance is set.") + private ProceduralValue count = ProceduralValue.constant(4); + + @Desc("If set, every block along the parent rolls this chance to grow a copy, such as {\"shape\": \"power\", \"exponent\": 2} for more toward the top.") + private ProceduralValue chance; + + @Desc("The stretch of the parent copies grow from; from 1 to 1 grows them all at the tip.") + private ProceduralSpan along = new ProceduralSpan(); + + @Desc("Which way around the parent each copy points.") + private BranchAzimuth azimuth = BranchAzimuth.RANDOM; + + @Desc("Turns every copy this many degrees further around the parent.") + private ProceduralValue azimuthOffset = ProceduralValue.constant(0); + + @MinNumber(1) + @Desc("How many copies make a ring for the WHORL azimuth.") + private int whorl = 4; + + @Desc("The degrees between copies for the FAN azimuth.") + private double fan = 40; + + @Desc("The angle in degrees above the horizon each copy grows toward; negative droops. With relative set, the angle is added to the parent's own.") + private ProceduralValue pitch = ProceduralValue.constant(0); + + @Desc("If true the copies point relative to the parent's direction instead of the compass, as forks and twigs do.") + private boolean relative = false; + + @MinNumber(1) + @MaxNumber(6) + @Desc("How many times branching repeats: 2 grows copies off the copies too, and so on.") + private int depth = 1; + + @Required + @Desc("The part each copy is made of.") + private ProceduralPart part; + + public ProceduralValue count() { + return count == null ? ProceduralValue.constant(4) : count; + } + + public ProceduralValue chance() { + return chance; + } + + public ProceduralSpan along() { + return along == null ? new ProceduralSpan() : along; + } + + public BranchAzimuth azimuth() { + return azimuth == null ? BranchAzimuth.RANDOM : azimuth; + } + + public ProceduralValue azimuthOffset() { + return azimuthOffset == null ? ProceduralValue.constant(0) : azimuthOffset; + } + + public int whorl() { + return Math.max(1, whorl); + } + + public double fan() { + return fan; + } + + public ProceduralValue pitch() { + return pitch == null ? ProceduralValue.constant(0) : pitch; + } + + public boolean relative() { + return relative; + } + + public int depth() { + return Math.max(1, Math.min(6, depth)); + } + + public ProceduralPart part() { + return part; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartCanvas.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartCanvas.java new file mode 100644 index 000000000..72e6a8d9f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartCanvas.java @@ -0,0 +1,140 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * The blocks the parts of one variant claim, before materials turn them into block data: each with the role of the + * part that placed it, how far along that part it sits, and the axis a log there would follow. + */ +final class PartCanvas { + /** Enough for any sensible object; a typo asking for more stops growing instead of baking for minutes. */ + static final int MAXIMUM_BLOCKS = 1_500_000; + + enum Axis { + NONE, X, Y, Z; + + /** The axis a log along {@code direction} lies on, leaning toward upright as trees do. */ + static Axis along(double[] direction) { + double x = Math.abs(direction[0]); + double y = Math.abs(direction[1]) * 1.8; + double z = Math.abs(direction[2]); + if (y >= x && y >= z) { + return Y; + } + return x >= z ? X : Z; + } + } + + /** @param part the {@link PartOutline} id of the part that placed the block */ + record Cell(int role, float along, Axis axis, int part) { + } + + /** The end of a stem, where tip decorations go. */ + record Tip(int x, int y, int z, double[] heading, int role) { + } + + private final Map cells = new HashMap<>(); + private final List tips = new ArrayList<>(); + private final List roles = new ArrayList<>(); + private boolean full; + + int role(String name) { + int index = roles.indexOf(name); + if (index >= 0) { + return index; + } + roles.add(name); + return roles.size() - 1; + } + + String roleName(int role) { + return roles.get(role); + } + + void place(int x, int y, int z, PartMode mode, Cell cell) { + long key = key(x, y, z); + switch (mode) { + case ADD -> { + if (!full || cells.containsKey(key)) { + cells.put(key, cell); + } + } + case FILL -> { + if (!full && !cells.containsKey(key)) { + cells.put(key, cell); + } + } + case CARVE -> cells.remove(key); + } + full = cells.size() >= MAXIMUM_BLOCKS; + } + + boolean has(int x, int y, int z) { + return cells.containsKey(key(x, y, z)); + } + + Cell get(long key) { + return cells.get(key); + } + + Map cells() { + return Collections.unmodifiableMap(cells); + } + + void addTip(Tip tip) { + tips.add(tip); + } + + List tips() { + return Collections.unmodifiableList(tips); + } + + boolean isEmpty() { + return cells.isEmpty(); + } + + boolean isFull() { + return full; + } + + static long key(int x, int y, int z) { + return ((long) (x & 0x1FFFFF)) | ((long) (y & 0x1FFFFF) << 21) | ((long) (z & 0x1FFFFF) << 42); + } + + static int x(long key) { + return signed((int) (key & 0x1FFFFF)); + } + + static int y(long key) { + return signed((int) ((key >>> 21) & 0x1FFFFF)); + } + + static int z(long key) { + return signed((int) ((key >>> 42) & 0x1FFFFF)); + } + + private static int signed(int value) { + return (value << 11) >> 11; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartCluster.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartCluster.java new file mode 100644 index 000000000..f2fd488d7 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartCluster.java @@ -0,0 +1,60 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; +import com.volmit.config.Required; + +@Desc("Places copies of a part around a center: columns in a causeway, peaks on an iceberg, shards on a crystal. Each copy leans away from the center unless its stem says otherwise.") +public final class PartCluster { + @Desc("How many copies to place.") + private ProceduralValue count = ProceduralValue.constant(5); + + @Desc("How far from the center copies are placed, in blocks.") + private ProceduralValue radius = ProceduralValue.constant(2); + + @Desc("How the copies are laid out.") + private ClusterLayout layout = ClusterLayout.RANDOM; + + @Desc("How far each copy tilts away from the center, in degrees from straight up. A range gives each copy its own tilt; a curve runs from the center (0) to the edge (1).") + private ProceduralValue tilt = ProceduralValue.constant(0); + + @Required + @Desc("The part each copy is made of.") + private ProceduralPart part; + + public ProceduralValue count() { + return count == null ? ProceduralValue.constant(5) : count; + } + + public ProceduralValue radius() { + return radius == null ? ProceduralValue.constant(2) : radius; + } + + public ClusterLayout layout() { + return layout == null ? ClusterLayout.RANDOM : layout; + } + + public ProceduralValue tilt() { + return tilt == null ? ProceduralValue.constant(0) : tilt; + } + + public ProceduralPart part() { + return part; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartFill.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartFill.java new file mode 100644 index 000000000..fff683b1f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartFill.java @@ -0,0 +1,41 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +/** How one part writes its blocks: the mode it combines with, and the density that thins it. */ +record PartFill(PartCanvas canvas, PartMode mode, int role, int partId, double density, PartPattern pattern, double scale, + double falloff, long seed) { + static PartFill of(PartCanvas canvas, ProceduralPart part, int partId, int role, long seed) { + return new PartFill(canvas, part.mode(), role, partId, part.density(), part.pattern(), part.scale(), part.falloff(), seed); + } + + /** + * Places the block if the density lets it; {@code edge} is how far toward the shape's edge it is, from 0 at the + * center to 1 at the edge, for the falloff. + */ + void place(int x, int y, int z, double edge, double along, PartCanvas.Axis axis) { + double chance = density; + if (falloff > 0) { + chance *= Math.pow(Math.max(0, 1 - edge), falloff); + } + if (!PartNoise.passes(pattern, chance, scale, x, y, z, seed)) { + return; + } + canvas.place(x, y, z, mode, new PartCanvas.Cell(role, (float) along, axis, partId)); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartGrower.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartGrower.java new file mode 100644 index 000000000..af93ea4e1 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartGrower.java @@ -0,0 +1,201 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import art.arcane.volmlib.util.math.RNG; + +import java.util.ArrayList; +import java.util.List; + +/** + * Grows a part tree onto a canvas: each part is drawn from where it sits on its parent, then its children grow from it. + * Every part draws from its own seed, taken from its parent's in order, so adding a part only changes what grows after it. + */ +final class PartGrower { + private static final double GOLDEN_ANGLE_DEGREES = 137.50776405003785; + private static final int MOST_COPIES = 256; + private static final int DEEPEST_NESTING = 24; + + private final PartCanvas canvas; + private final String defaultRole; + private final PartOutline outline; + + PartGrower(PartCanvas canvas, String defaultRole, PartOutline outline) { + this.canvas = canvas; + this.defaultRole = defaultRole; + this.outline = outline; + } + + void growRoots(List parts, long seed) { + RNG seeds = new RNG(seed); + for (ProceduralPart part : parts) { + growChild(part, PartShape.ROOT, canvas.role(defaultRole), seeds.nextLong(), 0); + } + } + + /** Grows a part that sits on its parent where its own 'at' and 'offset' say. */ + private void growChild(ProceduralPart part, PartShape parent, int parentRole, long seed, int nesting) { + if (part == null || canvas.isFull()) { + return; + } + RNG rng = new RNG(seed); + double at = part.at() == null ? parent.defaultAt() : part.at().sample(rng, 0); + PartSpot spot = parent.spotAt(at); + if (part.offset() != null) { + spot = spot.movedBy(part.offset().roll(rng)); + } + grow(part, parent, spot, parentRole, rng, List.of(), nesting); + } + + /** Grows a part at {@code spot}, then its children, then any branching it repeats from its own copy. */ + private void grow(ProceduralPart part, PartShape parent, PartSpot spot, int parentRole, RNG rng, + List repeats, int nesting) { + if (nesting > DEEPEST_NESTING || canvas.isFull()) { + return; + } + int role = part.role() == null || part.role().isBlank() ? parentRole : canvas.role(part.role()); + PartFill fill = PartFill.of(canvas, part, outline.idOf(part), role, rng.nextLong()); + PartShape shape = parent; + if (part.stem() != null) { + StemShape stem = StemShape.trace(part.stem(), spot, rng); + stem.draw(fill, part.stem().section(), part.stem().roughness(), part.stem().jitter()); + shape = stem; + } else if (part.blob() != null) { + BlobShape blob = BlobShape.trace(part.blob(), spot, rng); + blob.draw(fill, part.blob().roughness(), part.blob().jitter()); + shape = blob; + } else if (part.branches() != null) { + branch(part.branches(), parent, role, rng, part.branches().depth(), nesting); + } else if (part.cluster() != null) { + cluster(part.cluster(), spot, role, rng, nesting); + } + + for (ProceduralPart child : part.children()) { + growChild(child, shape, role, rng.nextLong(), nesting + 1); + } + for (Repeat repeat : repeats) { + branch(repeat.branches(), shape, role, rng, repeat.depthLeft(), nesting); + } + } + + private void branch(PartBranches branches, PartShape parent, int role, RNG rng, int depthLeft, int nesting) { + if (branches.part() == null || depthLeft <= 0) { + return; + } + List positions = branchPositions(branches, parent, rng); + List repeats = depthLeft > 1 ? List.of(new Repeat(branches, depthLeft - 1)) : List.of(); + double azimuthOffset = branches.azimuthOffset().sample(rng, 0); + for (int index = 0; index < positions.size(); index++) { + double t = positions.get(index); + PartSpot onParent = parent.spotAt(t); + double pitch = branches.pitch().sample(rng, t); + double[] heading = branchHeading(branches, onParent, index, positions.size(), azimuthOffset, pitch, rng); + PartSpot spot = new PartSpot(onParent.origin(), heading, t, parent.length(), Vectors.azimuth(heading)); + RNG copyRng = new RNG(rng.nextLong()); + ProceduralPart copy = branches.part(); + if (copy.offset() != null) { + spot = spot.movedBy(copy.offset().roll(copyRng)); + } + grow(copy, parent, spot, role, copyRng, repeats, nesting + 1); + } + } + + private static List branchPositions(PartBranches branches, PartShape parent, RNG rng) { + ProceduralSpan along = branches.along(); + List positions = new ArrayList<>(); + if (branches.chance() != null) { + double blocks = Math.max(1, parent.length()); + int first = (int) Math.ceil(along.from() * blocks); + int last = (int) Math.floor(along.to() * blocks); + for (int block = first; block <= last && positions.size() < MOST_COPIES; block++) { + double t = Math.min(1, block / blocks); + if (rng.nextDouble() < branches.chance().at(t)) { + positions.add(t); + } + } + return positions; + } + int count = Math.min(MOST_COPIES, Math.max(0, (int) Math.round(branches.count().sample(rng, 0)))); + for (int index = 0; index < count; index++) { + double fraction = along.to() - along.from() < 1e-9 ? 0 : (index + rng.d(0.25, 0.75)) / count; + positions.add(along.from() + (along.to() - along.from()) * fraction); + } + return positions; + } + + private static double[] branchHeading(PartBranches branches, PartSpot onParent, int index, int count, + double azimuthOffset, double pitch, RNG rng) { + double parentAzimuth = Vectors.isVertical(onParent.heading()) && onParent.hasOutward() + ? onParent.outward() : Vectors.azimuth(onParent.heading()); + double turn = switch (branches.azimuth()) { + case RANDOM -> rng.d(0, 360); + case GOLDEN -> index * GOLDEN_ANGLE_DEGREES; + case ALTERNATE -> (index % 2) * 180.0; + case WHORL -> (index % branches.whorl()) * (360.0 / branches.whorl()); + case EVEN -> index * (360.0 / Math.max(1, count)); + case FAN -> branches.fan() * (index - (count - 1) / 2.0); + }; + boolean relative = branches.relative() || branches.azimuth() == BranchAzimuth.FAN; + double azimuth = (relative ? parentAzimuth : 0) + turn + azimuthOffset; + double finalPitch = branches.relative() ? Vectors.pitch(onParent.heading()) + pitch : pitch; + return Vectors.direction(azimuth, Math.max(-90, Math.min(90, finalPitch))); + } + + private void cluster(PartCluster cluster, PartSpot spot, int role, RNG rng, int nesting) { + if (cluster.part() == null) { + return; + } + int count = Math.min(MOST_COPIES, Math.max(0, (int) Math.round(cluster.count().sample(rng, 0)))); + double radius = Math.max(0, cluster.radius().sample(rng, 0)); + double phase = rng.d(0, 360); + for (int index = 0; index < count; index++) { + Placed placed = placeInCluster(cluster.layout(), index, count, radius, phase, rng); + double[] origin = Vectors.add(spot.origin(), Vectors.scale(Vectors.direction(placed.azimuth(), 0), placed.distance())); + RNG copyRng = new RNG(rng.nextLong()); + double fromCenter = radius <= 0 ? 0 : Math.min(1, placed.distance() / radius); + double tilt = cluster.tilt().sample(copyRng, fromCenter); + double[] heading = tilt == 0 ? spot.heading().clone() : Vectors.tilted(spot.heading(), placed.azimuth(), tilt); + PartSpot copySpot = new PartSpot(origin, heading, fromCenter, Math.max(1, radius), placed.azimuth()); + ProceduralPart copy = cluster.part(); + if (copy.offset() != null) { + copySpot = copySpot.movedBy(copy.offset().roll(copyRng)); + } + grow(copy, PartShape.ROOT, copySpot, role, copyRng, List.of(), nesting + 1); + } + } + + private static Placed placeInCluster(ClusterLayout layout, int index, int count, double radius, double phase, RNG rng) { + return switch (layout) { + case RANDOM -> new Placed(rng.d(0, 360), radius * Math.sqrt(rng.nextDouble())); + case RING -> new Placed(phase + index * 360.0 / Math.max(1, count), radius); + case GOLDEN -> new Placed(phase + index * GOLDEN_ANGLE_DEGREES, radius * Math.sqrt((index + 0.5) / Math.max(1, count))); + case LINE -> { + double lane = count <= 1 ? 0 : -radius + 2 * radius * index / (count - 1.0); + yield new Placed(lane < 0 ? phase + 180 : phase, Math.abs(lane)); + } + }; + } + + /** A branching that repeats on the copies it grows, with how many more times it may. */ + private record Repeat(PartBranches branches, int depthLeft) { + } + + /** Where a cluster copy sits: which way from the center, and how far. */ + private record Placed(double azimuth, double distance) { + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartMode.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartMode.java new file mode 100644 index 000000000..83b978c04 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartMode.java @@ -0,0 +1,30 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; + +@Desc("How a part's blocks combine with the blocks already there.") +public enum PartMode { + @Desc("Places blocks, replacing whatever earlier parts put there.") + ADD, + @Desc("Places blocks only where nothing is yet, like leaves around wood.") + FILL, + @Desc("Removes the blocks earlier parts put inside this part's shape.") + CARVE +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartNoise.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartNoise.java new file mode 100644 index 000000000..1ba2ac509 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartNoise.java @@ -0,0 +1,98 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +/** Seeded noise for parts: a hash per block for speckle, and smooth value noise for patches and wandering. */ +final class PartNoise { + private static final double PATCH_CONTRAST = 1.8; + + private PartNoise() { + } + + /** A value from 0 to 1 that is the same for the same block and seed. */ + static double hash(int x, int y, int z, long seed) { + long h = mix(seed); + h = mix(h + x * 0x9E3779B97F4A7C15L); + h = mix(h + y * 0xC2B2AE3D27D4EB4FL); + h = mix(h + z * 0x165667B19E3779F9L); + return unit(h); + } + + /** Smooth value noise from 0 to 1 with features {@code scale} blocks across, stretched so thresholds split it evenly. */ + static double patches(double x, double y, double z, double scale, long seed) { + double size = Math.max(1, scale); + double value = smooth(x / size, y / size, z / size, seed); + return Math.max(0, Math.min(1, (value - 0.5) * PATCH_CONTRAST + 0.5)); + } + + /** Smooth value noise from 0 to 1 along a line. */ + static double line(double t, long seed) { + int cell = (int) Math.floor(t); + double blend = fade(t - cell); + double a = hash(cell, 0, 0, seed); + double b = hash(cell + 1, 0, 0, seed); + return a + (b - a) * blend; + } + + /** Whether a block passes a chance under a pattern. */ + static boolean passes(PartPattern pattern, double chance, double scale, int x, int y, int z, long seed) { + if (chance >= 1) { + return true; + } + if (chance <= 0) { + return false; + } + double roll = pattern == PartPattern.PATCHES ? patches(x, y, z, scale, seed) : hash(x, y, z, seed); + return roll < chance; + } + + private static double smooth(double x, double y, double z, long seed) { + int x0 = (int) Math.floor(x); + int y0 = (int) Math.floor(y); + int z0 = (int) Math.floor(z); + double fx = fade(x - x0); + double fy = fade(y - y0); + double fz = fade(z - z0); + double c00 = lerp(hash(x0, y0, z0, seed), hash(x0 + 1, y0, z0, seed), fx); + double c10 = lerp(hash(x0, y0 + 1, z0, seed), hash(x0 + 1, y0 + 1, z0, seed), fx); + double c01 = lerp(hash(x0, y0, z0 + 1, seed), hash(x0 + 1, y0, z0 + 1, seed), fx); + double c11 = lerp(hash(x0, y0 + 1, z0 + 1, seed), hash(x0 + 1, y0 + 1, z0 + 1, seed), fx); + return lerp(lerp(c00, c10, fy), lerp(c01, c11, fy), fz); + } + + private static double fade(double t) { + return t * t * (3 - 2 * t); + } + + private static double lerp(double a, double b, double t) { + return a + (b - a) * t; + } + + static long mix(long a) { + a ^= (a >>> 33); + a *= 0xff51afd7ed558ccdL; + a ^= (a >>> 33); + a *= 0xc4ceb9fe1a85ec53L; + a ^= (a >>> 33); + return a; + } + + private static double unit(long h) { + return (h >>> 11) * 0x1.0p-53; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartOffset.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartOffset.java new file mode 100644 index 000000000..d7a564cf0 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartOffset.java @@ -0,0 +1,41 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; +import art.arcane.volmlib.util.math.RNG; + +@Desc("A shift in blocks along each axis. Each axis takes a number or a [min, max] range.") +public final class PartOffset { + @Desc("Blocks east (negative is west).") + private ProceduralValue x; + + @Desc("Blocks up (negative is down).") + private ProceduralValue y; + + @Desc("Blocks south (negative is north).") + private ProceduralValue z; + + public double[] roll(RNG rng) { + return new double[]{roll(x, rng), roll(y, rng), roll(z, rng)}; + } + + private static double roll(ProceduralValue value, RNG rng) { + return value == null ? 0 : value.sample(rng, 0); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartOutline.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartOutline.java new file mode 100644 index 000000000..bd467f82a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartOutline.java @@ -0,0 +1,134 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; + +/** + * The part tree of a procedural object as a viewer lists it, with an id per node that {@link PartTrace} tags blocks + * with. A part that copies another, like branches, shares its node with the copied part, so the tree reads one level + * shallower than the settings. Ids number the nodes in order, so they stay the same across seeds and variants. + */ +public final class PartOutline { + public static final int NO_PART = -1; + + /** + * One row of the tree. + * + * @param shape what the part is, like {@code Branches ×12 · Stem} + * @param detail the role its blocks get, and whether it carves them away instead + */ + public record Node(int id, String shape, String detail, List children) { + } + + private final Map idsByPart = new IdentityHashMap<>(); + private final List roots; + private int nodeCount; + + private PartOutline(ProceduralObject definition) { + this.roots = nodesFor(definition.parts(), definition.defaultRole()); + } + + public static PartOutline of(ProceduralObject definition) { + return new PartOutline(definition); + } + + public List roots() { + return roots; + } + + public int nodeCount() { + return nodeCount; + } + + public int idOf(ProceduralPart part) { + return idsByPart.getOrDefault(part, NO_PART); + } + + private List nodesFor(List parts, String parentRole) { + List nodes = new ArrayList<>(); + for (ProceduralPart part : parts) { + if (part != null) { + nodes.add(nodeFor(part, parentRole)); + } + } + return nodes; + } + + // Children follow the order the grower draws them in: the copies' own children first, then the part's. + private Node nodeFor(ProceduralPart part, String parentRole) { + int id = nodeCount++; + idsByPart.put(part, id); + String role = roleOf(part, parentRole); + ProceduralPart copied = copiedPart(part); + List children = new ArrayList<>(); + String shape; + String detail; + if (copied != null && copiedPart(copied) == null) { + idsByPart.put(copied, id); + String copiedRole = roleOf(copied, role); + shape = copiesLabel(part) + " · " + shapeName(copied); + detail = detailOf(copied, copiedRole); + children.addAll(nodesFor(copied.children(), copiedRole)); + } else { + shape = copied != null ? copiesLabel(part) : shapeName(part); + detail = detailOf(part, role); + if (copied != null) { + children.add(nodeFor(copied, role)); + } + } + children.addAll(nodesFor(part.children(), role)); + return new Node(id, shape, detail, List.copyOf(children)); + } + + private static String roleOf(ProceduralPart part, String parentRole) { + return part.role() == null || part.role().isBlank() ? parentRole : part.role(); + } + + private static ProceduralPart copiedPart(ProceduralPart part) { + if (part.branches() != null) { + return part.branches().part(); + } + return part.cluster() != null ? part.cluster().part() : null; + } + + private static String copiesLabel(ProceduralPart part) { + if (part.branches() != null) { + return part.branches().chance() != null ? "Branches by chance" : "Branches ×" + part.branches().count().summary(); + } + return "Cluster ×" + part.cluster().count().summary(); + } + + private static String shapeName(ProceduralPart part) { + if (part.stem() != null) { + return "Stem"; + } + if (part.blob() != null) { + return "Blob"; + } + return "Group"; + } + + // Carving places no blocks, so it is named to explain why nothing lights up. + private static String detailOf(ProceduralPart part, String role) { + return part.mode() == PartMode.CARVE ? role + " · carve" : role; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartPattern.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartPattern.java new file mode 100644 index 000000000..a28c83017 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartPattern.java @@ -0,0 +1,28 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; + +@Desc("How a chance is spread over blocks.") +public enum PartPattern { + @Desc("Every block rolls on its own, for an even speckle.") + RANDOM, + @Desc("Smooth noise decides, so blocks come in patches the size of the scale.") + PATCHES +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartSection.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartSection.java new file mode 100644 index 000000000..ef53618e6 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartSection.java @@ -0,0 +1,32 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; + +@Desc("The cross-section of a stem or blob.") +public enum PartSection { + @Desc("A circle.") + ROUND, + @Desc("A square, like a vanilla trunk.") + SQUARE, + @Desc("A diamond (a square turned 45 degrees).") + DIAMOND, + @Desc("A hexagon, like a basalt column.") + HEX +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartShape.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartShape.java new file mode 100644 index 000000000..caed199d6 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartShape.java @@ -0,0 +1,48 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +/** A drawn part that others can grow from. */ +interface PartShape { + /** Where a child sitting at {@code t}, from the base (0) to the tip (1), starts. */ + PartSpot spotAt(double t); + + /** The length children measure against, in blocks. */ + double length(); + + /** Where children sit when they do not say. */ + double defaultAt(); + + /** The parent of the object's root parts: a single point at the base, pointing up. */ + PartShape ROOT = new PartShape() { + @Override + public PartSpot spotAt(double t) { + return PartSpot.root(); + } + + @Override + public double length() { + return 0; + } + + @Override + public double defaultAt() { + return 0; + } + }; +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartSpot.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartSpot.java new file mode 100644 index 000000000..b43384f90 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartSpot.java @@ -0,0 +1,36 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +/** + * Where a part starts: its position, the direction it grows, where it sits on its parent from base (0) to tip (1), + * how long that parent is, and the compass direction pointing away from the parent's center (NaN when there is none). + */ +record PartSpot(double[] origin, double[] heading, double parentT, double parentLength, double outward) { + static PartSpot root() { + return new PartSpot(new double[]{0, 0, 0}, Vectors.UP.clone(), 0, 0, Double.NaN); + } + + PartSpot movedBy(double[] offset) { + return new PartSpot(Vectors.add(origin, offset), heading, parentT, parentLength, outward); + } + + boolean hasOutward() { + return !Double.isNaN(outward); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartStem.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartStem.java new file mode 100644 index 000000000..da289a09e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartStem.java @@ -0,0 +1,170 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +@Desc("A line that grows from where the part sits: a trunk, branch, spire, stalk, root or shard. Values given as a curve run over where the stem sits on its parent, except taper, lean curve, bend curve and helix radius, which run from the stem's base (0) to its tip (1).") +public final class PartStem { + @Desc("How long the stem grows, in blocks.") + private ProceduralValue length = ProceduralValue.constant(8); + + @MinNumber(0) + @Desc("If above 0, the stem is this fraction of its parent stem's length instead, for branches that shrink as they split.") + private double lengthScale = 0; + + @Desc("The radius at the base in blocks. 0.5 is one block wide.") + private ProceduralValue radius = ProceduralValue.constant(0.5); + + @Desc("A multiplier on the radius from the base (0) to the tip (1), such as [[0, 1], [1, 0]] to taper to a point.") + private ProceduralValue taper; + + @Desc("The cross-section of the stem.") + private PartSection section = PartSection.ROUND; + + @Desc("The angle in degrees above the horizon the stem grows toward: 90 is straight up, -90 straight down. Unset, it carries on its parent's direction (up for a root part).") + private ProceduralValue pitch; + + @Desc("The compass direction in degrees the stem grows toward when pitch is set. Unset, it keeps its parent's direction, or grows toward its facing.") + private ProceduralValue azimuth; + + @Desc("The compass direction in degrees the stem leans and bends toward. Unset, it leans away from the center of its cluster or branch, or a random way.") + private ProceduralValue facing; + + @Desc("How far the stem leans, in degrees from its direction, by the time it reaches its tip.") + private ProceduralValue lean = ProceduralValue.constant(0); + + @Desc("How the lean builds up from base (0) to tip (1), from 0 to 1. Unset, it grows evenly.") + private ProceduralValue leanCurve; + + @Desc("How far the stem turns, in degrees, by its tip: 90 turns an upright stem sideways, 180 brings it back down like an arch.") + private ProceduralValue bend = ProceduralValue.constant(0); + + @Desc("How the bend builds up from base (0) to tip (1), from 0 to 1. Unset, it turns evenly.") + private ProceduralValue bendCurve; + + @Desc("How much the stem sags under its own weight, as a fraction of its length: 0.2 drops the tip a fifth of the length.") + private ProceduralValue droop = ProceduralValue.constant(0); + + @Desc("How far the stem wanders sideways at random, in blocks.") + private ProceduralValue sway = ProceduralValue.constant(0); + + @Desc("How far the stem waves from side to side, in blocks.") + private ProceduralValue wave = ProceduralValue.constant(0); + + @Desc("How many full waves the stem makes over its length.") + private ProceduralValue wavePeriods = ProceduralValue.constant(1); + + @Desc("The radius in blocks of a corkscrew the stem winds around, from base (0) to tip (1). It starts on the facing side, so copies facing apart wind as a double helix.") + private ProceduralValue helixRadius = ProceduralValue.constant(0); + + @Desc("How many full turns the corkscrew makes over the stem's length.") + private ProceduralValue helixTurns = ProceduralValue.constant(1); + + @MinNumber(0) + @MaxNumber(1) + @Desc("How rough the surface is, from 0 (smooth) to 1 (heavily pitted).") + private double roughness = 0; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How many blocks along the surface are knocked off at random, from 0 to 1.") + private double jitter = 0; + + public ProceduralValue length() { + return length == null ? ProceduralValue.constant(8) : length; + } + + public double lengthScale() { + return lengthScale; + } + + public ProceduralValue radius() { + return radius == null ? ProceduralValue.constant(0.5) : radius; + } + + public ProceduralValue taper() { + return taper; + } + + public PartSection section() { + return section == null ? PartSection.ROUND : section; + } + + public ProceduralValue pitch() { + return pitch; + } + + public ProceduralValue azimuth() { + return azimuth; + } + + public ProceduralValue facing() { + return facing; + } + + public ProceduralValue lean() { + return lean; + } + + public ProceduralValue leanCurve() { + return leanCurve; + } + + public ProceduralValue bend() { + return bend; + } + + public ProceduralValue bendCurve() { + return bendCurve; + } + + public ProceduralValue droop() { + return droop; + } + + public ProceduralValue sway() { + return sway; + } + + public ProceduralValue wave() { + return wave; + } + + public ProceduralValue wavePeriods() { + return wavePeriods; + } + + public ProceduralValue helixRadius() { + return helixRadius; + } + + public ProceduralValue helixTurns() { + return helixTurns; + } + + public double roughness() { + return roughness; + } + + public double jitter() { + return jitter; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartTrace.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartTrace.java new file mode 100644 index 000000000..c64ff5a2b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartTrace.java @@ -0,0 +1,39 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import java.util.Map; + +/** + * Which part placed each block of one baked variant, by the block's position in the variant's object. Decorations + * belong to no part. + */ +public final class PartTrace { + public static final PartTrace EMPTY = new PartTrace(Map.of()); + + private final Map partsByBlock; + + PartTrace(Map partsByBlock) { + this.partsByBlock = partsByBlock; + } + + /** The {@link PartOutline} id of the part that placed the block, or {@link PartOutline#NO_PART}. */ + public int partAt(int x, int y, int z) { + return partsByBlock.getOrDefault(PartCanvas.key(x, y, z), PartOutline.NO_PART); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralDecoration.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralDecoration.java new file mode 100644 index 000000000..1910823b5 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralDecoration.java @@ -0,0 +1,94 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; + +import java.util.Collections; +import java.util.List; + +@Desc("Blocks placed against the finished object, such as vines, moss, fruit or lanterns. Vines and lichen attach to the block they touch.") +public final class ProceduralDecoration { + @Ref(Reference.BLOCK) + @Desc("The block to place. Ignored when palette is set.") + private String block = "minecraft:vine"; + + @Desc("A noise palette to place.") + private PaletteSpec palette; + + @Desc("The roles to decorate. Empty decorates every block.") + private List on = List.of(); + + @Desc("Where on those blocks to place it.") + private DecorationSpot at = DecorationSpot.SIDE; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance each spot gets one.") + private double chance = 0.3; + + @Desc("How the chance is spread over the spots.") + private PartPattern pattern = PartPattern.RANDOM; + + @MinNumber(1) + @Desc("The size of the patches in blocks for the PATCHES pattern.") + private double scale = 3; + + @Desc("How many blocks long a strand hangs for BELOW and BOTTOM.") + private ProceduralValue length = ProceduralValue.constant(1); + + @Desc("How far from where the object stands GROUND decorations spread, in blocks.") + private ProceduralValue radius = ProceduralValue.constant(3); + + public BlockChoice choice() { + return new BlockChoice(block, palette, 0); + } + + public List on() { + return on == null ? List.of() : Collections.unmodifiableList(on); + } + + public DecorationSpot at() { + return at == null ? DecorationSpot.SIDE : at; + } + + public double chance() { + return chance; + } + + public PartPattern pattern() { + return pattern == null ? PartPattern.RANDOM : pattern; + } + + public double scale() { + return scale; + } + + public ProceduralValue length() { + return length == null ? ProceduralValue.constant(1) : length; + } + + public ProceduralValue radius() { + return radius == null ? ProceduralValue.constant(3) : radius; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralMaterial.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralMaterial.java new file mode 100644 index 000000000..8c65d50fa --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralMaterial.java @@ -0,0 +1,61 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; + +import java.util.Collections; +import java.util.List; + +@Desc("The blocks of one role. Logs are turned along the part they belong to, and leaves get decay distances.") +public final class ProceduralMaterial { + @Required + @Desc("The role the parts refer to, such as wood, leaves, rock or cap.") + private String role = "main"; + + @Ref(Reference.BLOCK) + @Desc("The block. Ignored when palette is set.") + private String block = "minecraft:stone"; + + @Desc("A noise palette mixing several blocks.") + private PaletteSpec palette; + + @MinNumber(0) + @Desc("If above 0, the palette changes every this many blocks of height, for strata.") + private int bands = 0; + + @Desc("Swaps for blocks that meet conditions; the first rule that applies wins.") + private List rules = List.of(); + + public String role() { + return role == null ? "main" : role; + } + + public BlockChoice choice() { + return new BlockChoice(block, palette, bands); + } + + public List rules() { + return rules == null ? List.of() : Collections.unmodifiableList(rules); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralObject.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralObject.java new file mode 100644 index 000000000..8e2721dd8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralObject.java @@ -0,0 +1,94 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +import java.util.Collections; +import java.util.List; + +@Desc("A procedural object built from parts: stems, blobs, branches and clusters, each placing blocks of a role. Anything from a tree to a rock arch to a crystal-studded boulder. Iris bakes a pool of variants from it once. Place it from any object placement as procedural/, or a single variant as procedural/#.") +public final class ProceduralObject { + @MinNumber(1) + @MaxNumber(64) + @Desc("How many different variants to bake. More means more variety for a little memory.") + private int variants = 6; + + @Desc("The seed every variant is baked from. The same seed and settings always bake the same variants.") + private long seed = 1337; + + + @Desc("The blocks of each role. A part whose role has no material uses the first one.") + private List materials = List.of(); + + @Desc("The parts the object grows from, each starting at the object's base.") + private List parts = List.of(); + + @Desc("Blocks placed against the finished object, such as vines, moss or fruit.") + private List decorations = List.of(); + + @Desc("If true leaves get the distances from wood vanilla needs to keep them. Leaves more than 6 blocks from wood are made persistent; the object view in /iris studio map shows them. If false all leaves are persistent.") + private boolean leafDecay = true; + + @Desc("If true every block that can hold water is waterlogged, so coral stays alive.") + private boolean waterlogged = false; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Sinks the object into the ground by this fraction of its height.") + private double sink = 0; + + public int variants() { + return variants; + } + + public long seed() { + return seed; + } + + public List materials() { + return materials == null ? List.of() : Collections.unmodifiableList(materials); + } + + /** The role of a root part that sets none: the first material's. */ + public String defaultRole() { + return materials().isEmpty() ? "main" : materials().getFirst().role(); + } + + public List parts() { + return parts == null ? List.of() : Collections.unmodifiableList(parts); + } + + public List decorations() { + return decorations == null ? List.of() : Collections.unmodifiableList(decorations); + } + + public boolean leafDecay() { + return leafDecay; + } + + public boolean waterlogged() { + return waterlogged; + } + + public double sink() { + return sink; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralPart.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralPart.java new file mode 100644 index 000000000..869e7aa91 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralPart.java @@ -0,0 +1,125 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +@Snippet("iris/objects/procedural-part") +@Desc("One piece of a procedural object. Set exactly one of stem, blob, branches or cluster; children grow from this part.") +public final class ProceduralPart { + @Desc("The role of the blocks this part places, matching a material's role, such as wood or leaves. Unset, it takes its parent's role.") + private String role; + + @Desc("Where on its parent this part sits, from the base (0) to the tip (1). Unset, it sits at the tip of a stem or the top of a blob.") + private ProceduralValue at; + + @Desc("Moves this part from where it sits, in blocks.") + private PartOffset offset; + + @Desc("How this part's blocks combine with the blocks earlier parts placed.") + private PartMode mode = PartMode.ADD; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The fraction of this part's blocks that are placed, for sparse leaves or eroded carving.") + private double density = 1; + + @Desc("How the density is spread over the blocks.") + private PartPattern pattern = PartPattern.RANDOM; + + @MinNumber(1) + @Desc("The size of the patches in blocks for the PATCHES pattern.") + private double scale = 3; + + @MinNumber(0) + @Desc("Thins the blocks toward the edge of the shape: 1 thins evenly, 2 keeps a dense core.") + private double falloff = 0; + + @Desc("A line that grows from here: a trunk, branch, spire, stalk or shard.") + private PartStem stem; + + @Desc("A rounded volume: a leaf crown, boulder, cap or coral head.") + private PartBlob blob; + + @Desc("Copies of a part grown out of this part's parent along its length.") + private PartBranches branches; + + @Desc("Copies of a part placed around this spot.") + private PartCluster cluster; + + @Desc("The parts that grow from this one.") + private List children = List.of(); + + public String role() { + return role; + } + + public ProceduralValue at() { + return at; + } + + public PartOffset offset() { + return offset; + } + + public PartMode mode() { + return mode == null ? PartMode.ADD : mode; + } + + public double density() { + return density; + } + + public PartPattern pattern() { + return pattern == null ? PartPattern.RANDOM : pattern; + } + + public double scale() { + return scale; + } + + public double falloff() { + return falloff; + } + + public PartStem stem() { + return stem; + } + + public PartBlob blob() { + return blob; + } + + public PartBranches branches() { + return branches; + } + + public PartCluster cluster() { + return cluster; + } + + public List children() { + return children == null ? List.of() : Collections.unmodifiableList(children); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralSpan.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralSpan.java new file mode 100644 index 000000000..417d46d19 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralSpan.java @@ -0,0 +1,55 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +@Desc("A stretch between two points from 0 to 1, such as from the base (0) to the tip (1) of a part.") +public final class ProceduralSpan { + @MinNumber(0) + @MaxNumber(1) + @Desc("Where the stretch starts.") + private double from = 0; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Where the stretch ends.") + private double to = 1; + + public ProceduralSpan() { + } + + public ProceduralSpan(double from, double to) { + this.from = from; + this.to = to; + } + + public double from() { + return Math.min(from, to); + } + + public double to() { + return Math.max(from, to); + } + + public boolean contains(double t) { + return t >= from() - 1e-9 && t <= to() + 1e-9; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralValue.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralValue.java new file mode 100644 index 000000000..1aa8688be --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralValue.java @@ -0,0 +1,299 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import art.arcane.volmlib.util.math.RNG; +import com.volmit.config.Desc; +import com.volmit.config.JsonForms; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * A number a pack author may write as a constant ({@code 5}), a random range ({@code [3, 8]} or + * {@code {"min": 3, "max": 8}}), a curve of keyframes ({@code [[0, 1], [0.6, 0.8], [1, 0.2]]}) or a named curve + * ({@code {"shape": "power", "exponent": 3, "from": 0, "to": 1}}). Each field says what a curve runs over. + */ +@Desc("A number, a [min, max] range rolled once per use, or a curve: [[t, value], ...] keyframes or {\"shape\": ..., \"from\": ..., \"to\": ...}.") +@JsonForms(ProceduralValue.Forms.class) +public final class ProceduralValue { + private final Object written; + private final Form form; + + private ProceduralValue(Object written, Form form) { + this.written = written; + this.form = form; + } + + public static ProceduralValue constant(double value) { + return new ProceduralValue(value, new Constant(value)); + } + + public static ProceduralValue range(double min, double max) { + return new ProceduralValue(List.of(min, max), new Range(min, max)); + } + + /** This value with any range rolled once, so a curve or constant is all that is left. */ + public ProceduralValue fix(RNG rng) { + if (form instanceof Range range) { + return constant(range.roll(rng)); + } + return this; + } + + /** The value at {@code t}, from 0 to 1; a range gives its middle, so fix it first to roll it. */ + public double at(double t) { + return form.at(Math.max(0, Math.min(1, t))); + } + + /** The value at {@code t}, with a range rolled with {@code rng}. */ + public double sample(RNG rng, double t) { + return fix(rng).at(t); + } + + public boolean isCurve() { + return form instanceof Keyframes || form instanceof Shape; + } + + /** A short reading of the value for labels: {@code 12}, {@code 4–9} or {@code curve}. */ + public String summary() { + return switch (form) { + case Constant constant -> shortNumber(constant.value()); + case Range range -> shortNumber(range.min()) + "–" + shortNumber(range.max()); + case Keyframes ignored -> "curve"; + case Shape ignored -> "curve"; + }; + } + + private static String shortNumber(double value) { + return value == Math.rint(value) ? Long.toString((long) value) : String.format(Locale.ROOT, "%.4g", value).replaceAll("\\.?0+$", ""); + } + + @Override + public String toString() { + return written.toString(); + } + + private sealed interface Form permits Constant, Range, Keyframes, Shape { + double at(double t); + } + + private record Constant(double value) implements Form { + @Override + public double at(double t) { + return value; + } + } + + private record Range(double min, double max) implements Form { + double roll(RNG rng) { + return min == max ? min : rng.d(Math.min(min, max), Math.max(min, max)); + } + + @Override + public double at(double t) { + return (min + max) / 2; + } + } + + private record Keyframes(double[] times, double[] values) implements Form { + @Override + public double at(double t) { + if (t <= times[0]) { + return values[0]; + } + for (int i = 1; i < times.length; i++) { + if (t <= times[i]) { + double span = times[i] - times[i - 1]; + double blend = span <= 0 ? 1 : (t - times[i - 1]) / span; + return values[i - 1] + (values[i] - values[i - 1]) * blend; + } + } + return values[values.length - 1]; + } + } + + private record Shape(CurveShape shape, double from, double to, Map parameters) implements Form { + @Override + public double at(double t) { + return from + (to - from) * shape.at(t, parameters); + } + } + + /** The named curves, each running from 0 at t = 0 toward 1, stretched between a value's from and to. */ + public enum CurveShape { + LINEAR(List.of()) { + @Override + double at(double t, Map p) { + return t; + } + }, + SMOOTH(List.of()) { + @Override + double at(double t, Map p) { + return t * t * (3 - 2 * t); + } + }, + POWER(List.of(new Parameter("exponent", 2))) { + @Override + double at(double t, Map p) { + return Math.pow(t, parameter(p, "exponent")); + } + }, + SIGMOID(List.of(new Parameter("steepness", 10), new Parameter("mid", 0.5))) { + @Override + double at(double t, Map p) { + return 1 / (1 + Math.exp(-parameter(p, "steepness") * (t - parameter(p, "mid")))); + } + }, + BELL(List.of(new Parameter("mid", 0.5), new Parameter("width", 0.15))) { + @Override + double at(double t, Map p) { + double spread = Math.max(1e-6, parameter(p, "width")); + return Math.exp(-0.5 * Math.pow((t - parameter(p, "mid")) / spread, 2)); + } + }, + PERIODIC(List.of(new Parameter("periods", 4), new Parameter("sharpness", 8))) { + @Override + double at(double t, Map p) { + double wave = Math.max(0, Math.sin(2 * Math.PI * t * parameter(p, "periods"))); + return Math.pow(wave, parameter(p, "sharpness")); + } + }, + SINE(List.of(new Parameter("periods", 1))) { + @Override + double at(double t, Map p) { + return 0.5 + 0.5 * Math.sin(2 * Math.PI * t * parameter(p, "periods")); + } + }; + + private final List parameters; + + CurveShape(List parameters) { + this.parameters = parameters; + } + + abstract double at(double t, Map parameters); + + /** What shapes this curve beyond its from and to, each with the value it has unless the curve sets it. */ + public List parameters() { + return parameters; + } + + /** As a value writes it, like {@code power}. */ + public String key() { + return name().toLowerCase(Locale.ROOT); + } + + final double parameter(Map written, String name) { + if (written.containsKey(name)) { + return Forms.number(written.get(name), name); + } + return parameters.stream().filter(parameter -> parameter.name().equals(name)).findFirst().orElseThrow().fallback(); + } + + public record Parameter(String name, double fallback) { + } + } + + /** Reads the forms a pack writes and writes a value back exactly as it was read. */ + static final class Forms implements JsonForms.Codec { + private static final String SHAPE = "shape"; + private static final String MIN = "min"; + private static final String MAX = "max"; + private static final String FROM = "from"; + private static final String TO = "to"; + private static final double DEFAULT_FROM = 0; + private static final double DEFAULT_TO = 1; + + @Override + public ProceduralValue read(Object json) { + return new ProceduralValue(json, formOf(json)); + } + + @Override + public Object write(ProceduralValue value) { + return value.written; + } + + private static Form formOf(Object json) { + return switch (json) { + case Number number -> new Constant(number.doubleValue()); + case List list -> listForm(list); + case Map object when object.containsKey(SHAPE) -> shapeForm(object); + case Map object when object.containsKey(MIN) && object.containsKey(MAX) -> + new Range(number(object.get(MIN), MIN), number(object.get(MAX), MAX)); + case Map object -> throw new IllegalArgumentException("A value needs min and max, or a shape: " + object); + default -> throw new IllegalArgumentException("A value is a number, a [min, max] range or a curve, not " + json); + }; + } + + private static Form listForm(List list) { + if (list.isEmpty()) { + throw new IllegalArgumentException("A value can not be an empty list"); + } + if (list.getFirst() instanceof Number) { + if (list.size() != 2) { + throw new IllegalArgumentException("A range is written [min, max]: " + list); + } + return new Range(number(list.get(0), MIN), number(list.get(1), MAX)); + } + return keyframes(list); + } + + private static Form keyframes(List list) { + List keys = new ArrayList<>(); + for (Object key : list) { + if (!(key instanceof List pair) || pair.size() != 2) { + throw new IllegalArgumentException("A keyframe is written [t, value]: " + key); + } + keys.add(new double[]{number(pair.get(0), "t"), number(pair.get(1), "value")}); + } + keys.sort((a, b) -> Double.compare(a[0], b[0])); + double[] times = new double[keys.size()]; + double[] values = new double[keys.size()]; + for (int i = 0; i < keys.size(); i++) { + times[i] = keys.get(i)[0]; + values[i] = keys.get(i)[1]; + } + return new Keyframes(times, values); + } + + private static Form shapeForm(Map object) { + String name = String.valueOf(object.get(SHAPE)).toUpperCase(Locale.ROOT); + CurveShape shape; + try { + shape = CurveShape.valueOf(name); + } catch (IllegalArgumentException unknown) { + throw new IllegalArgumentException("Unknown curve shape " + name.toLowerCase(Locale.ROOT)); + } + double from = object.containsKey(FROM) ? number(object.get(FROM), FROM) : DEFAULT_FROM; + double to = object.containsKey(TO) ? number(object.get(TO), TO) : DEFAULT_TO; + return new Shape(shape, from, to, object); + } + + static double number(Object written, String name) { + if (written instanceof Number number) { + return number.doubleValue(); + } + throw new IllegalArgumentException(name + " needs a number, not " + written); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/ResolvedProceduralObject.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/ResolvedProceduralObject.java new file mode 100644 index 000000000..6e5f5e0a4 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/ResolvedProceduralObject.java @@ -0,0 +1,56 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import art.arcane.iris.engine.procedural.BakeProfile; +import art.arcane.iris.engine.procedural.ProceduralShape; +import art.arcane.iris.engine.procedural.ProceduralVariants; +import art.arcane.iris.modules.objects.ObjectBuilder; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; + +/** The variants of a procedural object, baked by {@link ObjectBaker}. */ +public final class ResolvedProceduralObject extends ProceduralVariants { + private final ProceduralObject definition; + private final PartOutline outline; + + public ResolvedProceduralObject(String path, ProceduralObject definition, PackResources resources) { + super(path, definition.seed(), definition.variants(), resources); + this.definition = definition; + this.outline = PartOutline.of(definition); + } + + @Override + protected ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks, BakeProfile profile) { + return ObjectBaker.bake(definition, outline, rng, blocks, profile); + } + + public PartOutline outline() { + return outline; + } + + /** Which part placed each block of {@code variant}, baked again to find out; empty when it is not one of these. */ + public PartTrace trace(PlaceableObject variant) { + int index = bakeIndexOf(variant); + if (index < 0) { + return PartTrace.EMPTY; + } + return ObjectBaker.trace(definition, outline, variantRng(index), newBuilder()); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/RuleFace.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/RuleFace.java new file mode 100644 index 000000000..c4adeb49a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/RuleFace.java @@ -0,0 +1,32 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import com.volmit.config.Desc; + +@Desc("Which open side a block needs for a material rule to apply to it.") +public enum RuleFace { + @Desc("Any side open to the air.") + ANY, + @Desc("Open above.") + UP, + @Desc("Open below.") + DOWN, + @Desc("Open on a horizontal side.") + SIDE +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/Sections.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/Sections.java new file mode 100644 index 000000000..ef25078a8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/Sections.java @@ -0,0 +1,37 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +/** How far a point is from the center of a cross-section, in the section's own measure, so 1 is on its edge at radius 1. */ +final class Sections { + private static final double HEX_SLANT = Math.sqrt(3) / 2; + + private Sections() { + } + + static double norm(PartSection section, double u, double w) { + double au = Math.abs(u); + double aw = Math.abs(w); + return switch (section) { + case ROUND -> Math.sqrt(u * u + w * w); + case SQUARE -> Math.max(au, aw); + case DIAMOND -> au + aw; + case HEX -> Math.max(aw, au * HEX_SLANT + aw * 0.5); + }; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/StemShape.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/StemShape.java new file mode 100644 index 000000000..d9040a79e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/StemShape.java @@ -0,0 +1,243 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +import art.arcane.volmlib.util.math.RNG; + +/** + * A stem traced as a path of closely spaced samples, each with a center, a direction and a radius, then swept into + * blocks: one block per sample while it is thin, a slice of its cross-section once it is thicker. + */ +final class StemShape implements PartShape { + static final double LONGEST_BLOCKS = 256; + private static final double SAMPLE_SPACING_BLOCKS = 0.25; + private static final double THIN_RADIUS_BLOCKS = 0.5; + private static final double SWAY_FREQUENCY = 0.35; + + private final double length; + private final double[][] centers; + private final double[][] headings; + private final double[] radii; + private final double outward; + + private StemShape(double length, double[][] centers, double[][] headings, double[] radii, double outward) { + this.length = length; + this.centers = centers; + this.headings = headings; + this.radii = radii; + this.outward = outward; + } + + /** Traces the stem from {@code spot} without placing anything. */ + static StemShape trace(PartStem stem, PartSpot spot, RNG rng) { + double length = stemLength(stem, spot, rng); + double baseRadius = Math.max(0, stem.radius().sample(rng, spot.parentT())); + ProceduralValue taper = stem.taper() == null ? null : stem.taper().fix(rng); + double facing = stem.facing() != null ? stem.facing().sample(rng, spot.parentT()) + : spot.hasOutward() ? spot.outward() : rng.d(0, 360); + double[] heading = startHeading(stem, spot, facing, rng); + double[] toward = Vectors.across(heading, Vectors.direction(facing, 0)); + double[] beside = Vectors.normalize(Vectors.cross(heading, toward), toward); + + Bends bends = Bends.of(stem, spot, rng, length); + double pathLength = Math.max(0, length - 1); + int steps = Math.max(2, (int) Math.ceil(pathLength / SAMPLE_SPACING_BLOCKS)); + double step = pathLength / steps; + double[][] centers = new double[steps + 1][]; + double[] radii = new double[steps + 1]; + double[] base = spot.origin().clone(); + for (int i = 0; i <= steps; i++) { + double t = i / (double) steps; + if (i > 0) { + double middle = (i - 0.5) / steps; + base = Vectors.addScaled(base, bends.heading(heading, toward, middle), step); + } + centers[i] = Vectors.add(base, bends.offset(toward, beside, t, pathLength)); + radii[i] = baseRadius * (taper == null ? 1 : Math.max(0, taper.at(t))); + } + return new StemShape(length, centers, directions(centers, heading), radii, facing); + } + + /** Places the stem's blocks and records its tip. */ + void draw(PartFill fill, PartSection section, double roughness, double jitter) { + for (int i = 0; i < centers.length; i++) { + double t = i / (double) (centers.length - 1); + PartCanvas.Axis axis = PartCanvas.Axis.along(headings[i]); + if (radii[i] <= THIN_RADIUS_BLOCKS && roughness <= 0) { + fill.place(round(centers[i][0]), round(centers[i][1]), round(centers[i][2]), 0, t, axis); + continue; + } + sweepSlice(fill, i, t, axis, section, roughness, jitter); + } + double[] tip = centers[centers.length - 1]; + fill.canvas().addTip(new PartCanvas.Tip(round(tip[0]), round(tip[1]), round(tip[2]), headings[headings.length - 1], fill.role())); + } + + private void sweepSlice(PartFill fill, int index, double t, PartCanvas.Axis axis, PartSection section, double roughness, double jitter) { + double[] center = centers[index]; + double[] heading = headings[index]; + double radius = Math.max(THIN_RADIUS_BLOCKS, radii[index]); + double[] across = Vectors.across(heading, new double[]{1, 0, 0}); + double[] beside = Vectors.cross(heading, across); + double slab = SAMPLE_SPACING_BLOCKS * 0.5 + 0.5; + boolean first = index == 0; + boolean last = index == centers.length - 1; + int squareWidth = Math.max(1, (int) Math.round(radius * 2)); + double squareShift = section == PartSection.SQUARE && squareWidth % 2 == 0 ? 0.5 : 0; + int reach = (int) Math.ceil(radius * (1 + roughness) + 1.5); + int cx = round(center[0]); + int cy = round(center[1]); + int cz = round(center[2]); + for (int x = cx - reach; x <= cx + reach; x++) { + for (int y = cy - reach; y <= cy + reach; y++) { + for (int z = cz - reach; z <= cz + reach; z++) { + double[] offset = {x - center[0], y - center[1], z - center[2]}; + double axial = Vectors.dot(offset, heading); + if (Math.abs(axial) > slab || (first && axial < -0.5) || (last && axial > 0.5)) { + continue; + } + double[] radial = Vectors.addScaled(offset, heading, -axial); + double u = Vectors.dot(radial, across) - squareShift; + double w = Vectors.dot(radial, beside) - squareShift; + double limit = section == PartSection.SQUARE ? squareWidth / 2.0 : radius; + double edge = Sections.norm(section, u, w); + if (roughness > 0) { + limit += (PartNoise.hash(x, y, z, fill.seed() + 9001L) - 0.5) * roughness * (radius + 1); + } + boolean core = x == cx && y == cy && z == cz; + if (!core && edge > limit) { + continue; + } + if (!core && jitter > 0 && edge > limit - 1 && PartNoise.hash(x, y, z, fill.seed() + 77L) < jitter * 0.5) { + continue; + } + fill.place(x, y, z, Math.min(edge, limit) / (limit + 1), t, axis); + } + } + } + } + + @Override + public PartSpot spotAt(double t) { + double position = Math.max(0, Math.min(1, t)) * (centers.length - 1); + int index = (int) Math.floor(position); + int next = Math.min(centers.length - 1, index + 1); + double blend = position - index; + double[] center = Vectors.add(Vectors.scale(centers[index], 1 - blend), Vectors.scale(centers[next], blend)); + double[] heading = headings[index]; + double outwardHere = Vectors.isVertical(heading) ? outward : Vectors.azimuth(heading); + return new PartSpot(center, heading.clone(), t, length, outwardHere); + } + + @Override + public double length() { + return length; + } + + @Override + public double defaultAt() { + return 1; + } + + private static double stemLength(PartStem stem, PartSpot spot, RNG rng) { + double length = stem.lengthScale() > 0 && spot.parentLength() > 0 + ? spot.parentLength() * stem.lengthScale() + : stem.length().sample(rng, spot.parentT()); + return Math.max(1, Math.min(LONGEST_BLOCKS, length)); + } + + private static double[] startHeading(PartStem stem, PartSpot spot, double facing, RNG rng) { + if (stem.pitch() == null && stem.azimuth() == null) { + return spot.heading().clone(); + } + double pitch = stem.pitch() != null ? stem.pitch().sample(rng, spot.parentT()) : Vectors.pitch(spot.heading()); + double azimuth = stem.azimuth() != null ? stem.azimuth().sample(rng, spot.parentT()) + : Vectors.isVertical(spot.heading()) ? facing : Vectors.azimuth(spot.heading()); + return Vectors.direction(azimuth, pitch); + } + + /** The direction at each sample, from its neighbors, so offsets such as lean and corkscrew turn the slices too. */ + private static double[][] directions(double[][] centers, double[] fallback) { + double[][] headings = new double[centers.length][]; + for (int i = 0; i < centers.length; i++) { + double[] before = centers[Math.max(0, i - 1)]; + double[] after = centers[Math.min(centers.length - 1, i + 1)]; + headings[i] = Vectors.normalize(Vectors.subtract(after, before), i > 0 ? headings[i - 1] : fallback); + } + return headings; + } + + private static int round(double value) { + return (int) Math.round(value); + } + + /** Everything that pulls a stem off a straight line, rolled once per stem. */ + private record Bends(double leanTangent, ProceduralValue leanCurve, double bendRadians, ProceduralValue bendCurve, + double droop, double sway, double wave, double wavePeriods, double wavePhase, + ProceduralValue helixRadius, double helixTurns, long swaySeed) { + static Bends of(PartStem stem, PartSpot spot, RNG rng, double length) { + double t = spot.parentT(); + double lean = Math.max(-85, Math.min(85, sample(stem.lean(), rng, t))); + return new Bends(Math.tan(Math.toRadians(lean)), fixed(stem.leanCurve(), rng), + Math.toRadians(sample(stem.bend(), rng, t)), fixed(stem.bendCurve(), rng), + sample(stem.droop(), rng, t), sample(stem.sway(), rng, t), + sample(stem.wave(), rng, t), sample(stem.wavePeriods(), rng, t), rng.d(0, Math.PI * 2), + fixed(stem.helixRadius(), rng), sample(stem.helixTurns(), rng, t), rng.nextLong()); + } + + double[] heading(double[] start, double[] toward, double t) { + if (bendRadians == 0) { + return start; + } + double angle = bendRadians * progress(bendCurve, t); + return Vectors.add(Vectors.scale(start, Math.cos(angle)), Vectors.scale(toward, Math.sin(angle))); + } + + double[] offset(double[] toward, double[] beside, double t, double pathLength) { + double[] offset = Vectors.scale(toward, pathLength * leanTangent * progress(leanCurve, t)); + offset[1] -= droop * pathLength * t * t; + double helix = helixRadius == null ? 0 : helixRadius.at(t); + if (helix != 0) { + double angle = Math.PI * 2 * helixTurns * t; + offset = Vectors.addScaled(offset, toward, Math.cos(angle) * helix); + offset = Vectors.addScaled(offset, beside, Math.sin(angle) * helix); + } + if (wave != 0) { + offset = Vectors.addScaled(offset, beside, wave * Math.sin(Math.PI * 2 * wavePeriods * t + wavePhase)); + } + if (sway != 0) { + double along = t * pathLength * SWAY_FREQUENCY; + offset = Vectors.addScaled(offset, toward, sway * (PartNoise.line(along, swaySeed) * 2 - 1)); + offset = Vectors.addScaled(offset, beside, sway * (PartNoise.line(along, swaySeed + 1) * 2 - 1)); + } + return offset; + } + + private static double progress(ProceduralValue curve, double t) { + return curve == null ? t : curve.at(t); + } + + private static double sample(ProceduralValue value, RNG rng, double t) { + return value == null ? 0 : value.sample(rng, t); + } + + private static ProceduralValue fixed(ProceduralValue value, RNG rng) { + return value == null ? null : value.fix(rng); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/Vectors.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/Vectors.java new file mode 100644 index 000000000..06b044985 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/Vectors.java @@ -0,0 +1,96 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.engine.procedural.part; + +/** Small vector maths on {@code double[3]}, with compass azimuths measured from south (+z) toward east (+x). */ +final class Vectors { + static final double[] UP = {0, 1, 0}; + + private Vectors() { + } + + /** The unit direction {@code azimuth} degrees around the compass and {@code pitch} degrees above the horizon. */ + static double[] direction(double azimuth, double pitch) { + double a = Math.toRadians(azimuth); + double p = Math.toRadians(pitch); + return new double[]{Math.cos(p) * Math.sin(a), Math.sin(p), Math.cos(p) * Math.cos(a)}; + } + + static double azimuth(double[] direction) { + return Math.toDegrees(Math.atan2(direction[0], direction[2])); + } + + static double pitch(double[] direction) { + return Math.toDegrees(Math.asin(Math.max(-1, Math.min(1, direction[1])))); + } + + static boolean isVertical(double[] direction) { + return Math.abs(direction[1]) > 0.999; + } + + static double[] add(double[] a, double[] b) { + return new double[]{a[0] + b[0], a[1] + b[1], a[2] + b[2]}; + } + + static double[] subtract(double[] a, double[] b) { + return new double[]{a[0] - b[0], a[1] - b[1], a[2] - b[2]}; + } + + static double[] scale(double[] a, double factor) { + return new double[]{a[0] * factor, a[1] * factor, a[2] * factor}; + } + + static double[] addScaled(double[] a, double[] b, double factor) { + return new double[]{a[0] + b[0] * factor, a[1] + b[1] * factor, a[2] + b[2] * factor}; + } + + static double dot(double[] a, double[] b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + } + + static double[] cross(double[] a, double[] b) { + return new double[]{a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]}; + } + + static double length(double[] a) { + return Math.sqrt(dot(a, a)); + } + + /** {@code a} scaled to length 1; {@code fallback} when it has no length. */ + static double[] normalize(double[] a, double[] fallback) { + double length = length(a); + return length < 1e-9 ? fallback.clone() : scale(a, 1 / length); + } + + /** The unit vector across {@code axis} that points most toward {@code toward}; any across one when they line up. */ + static double[] across(double[] axis, double[] toward) { + double[] flattened = subtract(toward, scale(axis, dot(toward, axis))); + if (length(flattened) > 1e-6) { + return normalize(flattened, UP); + } + double[] reference = Math.abs(axis[0]) < 0.9 ? new double[]{1, 0, 0} : new double[]{0, 0, 1}; + return normalize(subtract(reference, scale(axis, dot(reference, axis))), UP); + } + + /** {@code direction} turned {@code degrees} toward {@code azimuth}, for leaning something away from where it points. */ + static double[] tilted(double[] direction, double azimuth, double degrees) { + double[] toward = across(direction, direction(azimuth, 0)); + double angle = Math.toRadians(degrees); + return normalize(add(scale(direction, Math.cos(angle)), scale(toward, Math.sin(angle))), direction); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java b/module/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java new file mode 100644 index 000000000..ecdaba34b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java @@ -0,0 +1,136 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.builtin.spawn.AmbientEffect; +import art.arcane.iris.builtin.spawn.EffectCommands; +import art.arcane.iris.modules.spawn.EffectSettings; +import art.arcane.iris.builtin.spawn.SpawnCommand; +import art.arcane.iris.engine.loot.BlockBiomes; +import art.arcane.iris.engine.loot.PlatformKeys; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.config.Level; +import com.volmit.entity.EntitySpec; +import com.volmit.resource.ResourceId; +import com.volmit.service.AmbientEffects; +import com.volmit.geometry.BlockPosition; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; +import com.volmit.world.RunningWorld.Sky; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * How {@code iris:spawn} plays the ambient effects of regions and biomes: the region's effects, then the biome's, each + * when its interval and chance say, with every random choice made here so the host only carries them out. + */ +public final class AmbientEffecting implements AmbientEffects { + @Override + public List due(PackWorld world, BlockPosition at) { + RunningWorld running = world.running().orElseThrow(); + EffectTimers timers = world.state(EffectTimers.class, ignored -> new EffectTimers()); + Optional sky = running.sky(); + + List due = new ArrayList<>(); + addDue(due, effectsOf(running.settings().at(EffectSettings.class, at.x(), at.z()).level(Level.REGION)), timers, sky, world.log()); + addDue(due, effectsOf(BlockBiomes.declaredAt(running, EffectSettings.class, at)), timers, sky, world.log()); + return due; + } + + private static List effectsOf(Optional declared) { + return declared.map(EffectSettings::effects).orElse(List.of()); + } + + private static void addDue(List due, List effects, EffectTimers timers, Optional sky, ModuleLog log) { + for (AmbientEffect effect : effects) { + if (timers.shouldPlayNow(effect)) { + due.add(play(effect, sky, log)); + } + } + } + + private static Effect play(AmbientEffect effect, Optional sky, ModuleLog log) { + Optional sound = PlatformKeys.id(effect.sound(), log).map(key -> soundOf(key, effect)); + Optional particles = PlatformKeys.id(effect.particleEffect(), log).map(key -> particlesOf(key, effect)); + return new Effect(sound, particles, commandsOf(effect.commandRegistry(), sky), potionOf(effect, log)); + } + + private static Sound soundOf(ResourceId key, AmbientEffect effect) { + int distance = effect.soundDistance(); + int offsetX = RNG.r.i(-distance, distance); + int offsetY = RNG.r.i(-distance, distance); + int offsetZ = RNG.r.i(-distance, distance); + float pitch = (float) RNG.r.d(effect.minPitch(), effect.maxPitch()); + return new Sound(key, offsetX, offsetY, offsetZ, (float) effect.volume(), pitch); + } + + private static Particles particlesOf(ResourceId key, AmbientEffect effect) { + double forward = RNG.r.i(effect.particleDistance()) + effect.particleAway(); + double sideways = RNG.r.d(-effect.particleDistanceWidth(), effect.particleDistanceWidth()); + Spot spot = new Spot(forward, sideways, RNG.r.d(), RNG.r.d(), RNG.r.i(effect.particleOffset())); + Spread spread = new Spread(randomized(effect.particleAltX(), effect.randomAltX()), + randomized(effect.particleAltY(), effect.randomAltY()), randomized(effect.particleAltZ(), effect.randomAltZ())); + return new Particles(key, spot, effect.particleCount(), spread, effect.extra()); + } + + private static List commandsOf(EffectCommands registry, Optional sky) { + List commands = new ArrayList<>(); + if (registry == null) { + return commands; + } + + double offsetX = commandOffset(registry.commandOffsetX(), registry.commandRandomAltX()); + double offsetY = commandOffset(registry.commandOffsetY(), registry.commandRandomAltY()); + double offsetZ = commandOffset(registry.commandOffsetZ(), registry.commandRandomAltZ()); + for (SpawnCommand command : registry.rawCommands()) { + if (sky.isPresent() && SpawnConditions.allow(command.timeBlock(), command.weather(), sky.get())) { + commands.add(new Command(new EntitySpec.Command(command.commands(), command.delay(), command.repeat(), + command.repeatDelay()), offsetX, offsetY, offsetZ)); + } + if (registry.commandAllRandomLocations()) { + offsetX = commandOffset(registry.commandOffsetX(), registry.commandRandomAltX()); + offsetY = commandOffset(registry.commandOffsetY(), registry.commandRandomAltY()); + offsetZ = commandOffset(registry.commandOffsetZ(), registry.commandRandomAltZ()); + } + } + return commands; + } + + private static Optional potionOf(AmbientEffect effect, ModuleLog log) { + if (effect.potionStrength() <= -1) { + return Optional.empty(); + } + + int shortest = Math.min(effect.potionTicksMax(), effect.potionTicksMin()); + int longest = Math.max(effect.potionTicksMax(), effect.potionTicksMin()); + int ticks = RNG.r.i(shortest, longest); + return PlatformKeys.id(effect.potionEffect(), log).map(key -> new Potion(key, effect.potionStrength(), ticks)); + } + + private static double commandOffset(double offset, boolean random) { + return randomized(offset, random); + } + + private static double randomized(double value, boolean random) { + return random ? RNG.r.d(-value, value) : value; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/spawn/EffectTimers.java b/module/src/main/java/art/arcane/iris/engine/spawn/EffectTimers.java new file mode 100644 index 000000000..e3aac1bcb --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/spawn/EffectTimers.java @@ -0,0 +1,40 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.builtin.spawn.AmbientEffect; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.scheduling.ChronoLatch; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * When the effects of a world play: an effect plays at most once per interval, and then only with its chance. The timers + * are the world's, shared by every player, like the effects themselves. + */ +final class EffectTimers { + private final ConcurrentMap latches = new ConcurrentHashMap<>(); + + /** Whether {@code effect} plays now; asking starts its interval over when it has elapsed. */ + boolean shouldPlayNow(AmbientEffect effect) { + ChronoLatch latch = latches.computeIfAbsent(effect, key -> new ChronoLatch(key.interval())); + return latch.flip() && RNG.r.nextInt(effect.chance()) == 0; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java b/module/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java new file mode 100644 index 000000000..f8be355bf --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java @@ -0,0 +1,156 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.builtin.loot.LootEntry; +import art.arcane.iris.builtin.spawn.AmbientEffect; +import art.arcane.iris.builtin.spawn.EntityDefinition; +import art.arcane.iris.builtin.spawn.SpawnCommand; +import art.arcane.iris.builtin.loot.LootResolver; +import art.arcane.iris.engine.loot.LootItems; +import art.arcane.iris.engine.loot.PlatformKeys; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.entity.EntitySpec; +import com.volmit.item.ItemAttribute; +import com.volmit.item.ItemDrop; +import com.volmit.resource.ContentKey; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.world.RunningWorld.Sky; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * Turns an entity of the pack into the {@link EntitySpec} the host spawns, making every random choice in the order Iris + * always made them: the passengers, the attribute modifiers, the leash holder and then the six pieces of equipment. An + * entity that names no type the host could spawn resolves to nothing, after its random choices, so that the ones after + * it stay what they were. + */ +final class EntityResolution { + private static final long PASSENGER_STREAM_BASE = 234858L; + private static final long LEASH_HOLDER_STREAM = 234548L; + + private final PackResources resources; + private final LootItems items; + private final Optional sky; + private final EffectTimers timers; + private final ModuleLog log; + + /** + * @param resources names the entity's loot tables by id + * @param sky the sky of the world the entity appears in, whose time and weather decide which of its commands run; none while the world has no platform world + * @param log hears of keys that name nothing the platform could have + */ + EntityResolution(PackResources resources, LootItems items, Optional sky, EffectTimers timers, ModuleLog log) { + this.resources = resources; + this.items = items; + this.sky = sky; + this.timers = timers; + this.log = log; + } + + Optional resolve(EntityDefinition entity, RNG rng) { + List passengers = new ArrayList<>(); + long passengerIndex = 0; + for (EntityDefinition passenger : entity.passengers()) { + resolve(passenger, rng.nextParallelRNG(PASSENGER_STREAM_BASE + passengerIndex++)).ifPresent(passengers::add); + } + + List attributes = items.attributes(entity.attributes(), rng); + List lootTables = entity.loot().tables().stream().map(resources::idOf).toList(); + long lootShuffleSeed = lootTables.isEmpty() ? 0L : rng.nextLong(); + Optional leashHolder = entity.leashHolder() == null + ? Optional.empty() + : resolve(entity.leashHolder(), rng.nextParallelRNG(LEASH_HOLDER_STREAM)); + EntitySpec.Equipment equipment = new EntitySpec.Equipment( + equip(entity.helmet(), rng), equip(entity.chestplate(), rng), equip(entity.leggings(), rng), + equip(entity.boots(), rng), equip(entity.mainHand(), rng), equip(entity.offHand(), rng)); + + return typeOf(entity).map(type -> new EntitySpec(type, appearanceOf(entity), behaviourOf(entity), equipment, attributes, + new EntitySpec.Company(passengers, leashHolder), new EntitySpec.Drops(lootTables, lootShuffleSeed), + arrivalOf(entity), entity.applySettingsToCustomMobAnyways())); + } + + /** The provider's mob when the pack names one, otherwise the entity type. */ + private Optional typeOf(EntityDefinition entity) { + Optional provided = textOf(entity.specialType()); + if (provided.isPresent()) { + return PlatformKeys.provided(provided.get(), log); + } + return PlatformKeys.id(entity.type(), log).map(ContentKey.Registered::new); + } + + /** A text the pack may leave out or blank, as absent then. */ + private static Optional textOf(String text) { + return text == null || text.isBlank() ? Optional.empty() : Optional.of(text); + } + + private static EntitySpec.Appearance appearanceOf(EntityDefinition entity) { + return new EntitySpec.Appearance(textOf(entity.customName()), entity.customNameVisible(), entity.glowing(), entity.baby(), + textOf(entity.pandaMainGene()), textOf(entity.pandaHiddenGene())); + } + + private EntitySpec.Arrival arrivalOf(EntityDefinition entity) { + return new EntitySpec.Arrival(spawnEffectOf(entity), commandsOf(entity), textOf(entity.reason()), + entity.spawnEffectRiseOutOfGround()); + } + + private static EntitySpec.Behaviour behaviourOf(EntityDefinition entity) { + return new EntitySpec.Behaviour(entity.aware(), entity.ai(), entity.gravity(), entity.invulnerable(), entity.silent(), + entity.pickupItems(), entity.removable(), entity.keepEntity()); + } + + private Optional equip(LootEntry piece, RNG rng) { + if (piece == null || !LootResolver.oneIn(rng, piece.rarity())) { + return Optional.empty(); + } + return Optional.ofNullable(items.give(piece, rng)); + } + + /** The entity's spawn effect when it shows this time: an effect only shows now and then, as its interval and chance say. */ + private Optional spawnEffectOf(EntityDefinition entity) { + AmbientEffect effect = entity.spawnEffect(); + if (effect == null || !timers.shouldPlayNow(effect)) { + return Optional.empty(); + } + Optional sound = PlatformKeys.id(effect.sound(), log).map(key -> + new EntitySpec.SpawnEffect.Sound(key, effect.soundDistance(), effect.minPitch(), effect.maxPitch(), effect.volume())); + Optional particles = PlatformKeys.id(effect.particleEffect(), log).map(key -> + new EntitySpec.SpawnEffect.Burst(key, effect.particleOffset(), effect.particleCount(), motionOf(effect), effect.extra())); + return Optional.of(new EntitySpec.SpawnEffect(sound, particles)); + } + + private static EntitySpec.SpawnEffect.Motion motionOf(AmbientEffect effect) { + return new EntitySpec.SpawnEffect.Motion(effect.particleAltX(), effect.particleAltY(), effect.particleAltZ(), + effect.randomAltX(), effect.randomAltY(), effect.randomAltZ()); + } + + private List commandsOf(EntityDefinition entity) { + List commands = new ArrayList<>(); + for (SpawnCommand command : entity.rawCommands()) { + if (sky.isPresent() && SpawnConditions.allow(command.timeBlock(), command.weather(), sky.get())) { + commands.add(new EntitySpec.Command(command.commands(), command.delay(), command.repeat(), command.repeatDelay())); + } + } + return commands; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/module/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java new file mode 100644 index 000000000..41d185490 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -0,0 +1,292 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.builtin.loot.LootResolver; +import art.arcane.iris.builtin.spawn.EntityDefinition; +import art.arcane.iris.builtin.spawn.EntitySpawn; +import art.arcane.iris.builtin.spawn.SpawnMarker; +import art.arcane.iris.builtin.spawn.SpawnSurface; +import art.arcane.iris.builtin.spawn.Spawner; +import art.arcane.iris.modules.spawn.SpawnerSettings; +import art.arcane.iris.engine.loot.LootItems; +import art.arcane.iris.engine.spawn.SpawnResources.KeyedSpawner; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.scheduling.ChronoLatch; +import com.volmit.config.Level; +import com.volmit.config.Range; +import com.volmit.config.SettingsStack; +import com.volmit.entity.EntitySpec; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.service.EntitySpawns; +import com.volmit.geometry.BlockPosition; +import com.volmit.world.BiomeKind; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * How {@code iris:spawn} spawns entities: the spawners of the dimension, region and surface biome that may fire in a + * chunk, or the spawners of a marker, each with the entities it spawns and the places it picks for them. What the + * platform decides (light, the surface, free space, the entity itself) is the host's, the plan only names it. + */ +public final class EntitySpawning implements EntitySpawns { + private static final int BLOCKS_TO_CHUNK_CENTRE = 8; + private static final int CHUNK_SIZE = 16; + private static final String CAVE_FLOOR_MARKER = "cave_floor"; + private static final int AIR_ABOVE_MARKER = 1; + private static final long COOLDOWN_CLEANUP_INTERVAL_MILLISECONDS = 60_000L; + + @Override + public Optional plan(PackWorld world, Site site) { + forgetExpiredCooldowns(world); + return switch (site) { + case Chunk chunk -> planChunk(world, chunk); + case Marker marker -> planMarker(world, marker); + }; + } + + @Override + public void spawned(PackWorld world, Plan plan, int count) { + if (count <= 0) { + return; + } + String spawnerKey = plan.spawner().path(); + Spawner spawner = SpawnResources.spawner(world.resources(), spawnerKey); + if (spawner != null) { + SpawnerGate.of(world).spawned(spawnerKey, spawner, plan.chunkX(), plan.chunkZ()); + } + } + + @Override + public Optional entity(PackWorld world, ResourceId id) { + EntityDefinition entity = SpawnResources.entity(world.resources(), id.path()); + if (entity == null) { + return Optional.empty(); + } + return resolution(world).resolve(entity, entityRandom(world).rng()); + } + + @Override + public Optional marker(PackWorld world, ResourceId tag) { + if (tag.path().equals(CAVE_FLOOR_MARKER)) { + return Optional.empty(); + } + SpawnMarker marker = SpawnResources.marker(world.resources(), tag.path()); + if (marker == null) { + return Optional.empty(); + } + + List spawners = new ArrayList<>(); + for (String key : marker.spawners()) { + if (SpawnResources.spawner(world.resources(), key) == null) { + world.log().error("Cannot load spawner: " + key + " for marker " + tag, null); + continue; + } + spawners.add(world.resources().idOf(key)); + } + return Optional.of(new MarkerRule(spawners, marker.emptyAbove(), marker.removeOnChange())); + } + + /** Drops the cooldowns that ran out, now and then: the world saves them across restarts. */ + private static void forgetExpiredCooldowns(PackWorld world) { + CooldownCleanup cleanup = world.state(CooldownCleanup.class, ignored -> new CooldownCleanup()); + if (!cleanup.due()) { + return; + } + PackResources resources = world.resources(); + SpawnCooldownBook.of(world).forgetExpired(key -> { + Spawner spawner = SpawnResources.spawner(resources, key); + return spawner == null ? -1L : spawner.maximumRate().interval(); + }); + } + + private Optional planChunk(PackWorld world, Chunk chunk) { + RunningWorld running = world.running().orElseThrow(); + SpawnerGate gate = SpawnerGate.of(world); + Predicate canSpawn = keyed -> gate.canSpawn(keyed.key(), keyed.spawner(), chunk.chunkX(), chunk.chunkZ()); + int blockX = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkX()); + int blockZ = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkZ()); + BiomeKind centreKind = running.layout().surfaceKind(blockX + BLOCKS_TO_CHUNK_CENTRE, blockZ + BLOCKS_TO_CHUNK_CENTRE); + SettingsStack column = running.settings().at(SpawnerSettings.class, blockX, blockZ); + + List candidates = Stream.concat( + shuffled(world, column.dimension()).stream() + .filter(canSpawn).filter(keyed -> SpawnerGate.suits(keyed.spawner(), centreKind)), + Stream.concat( + shuffled(world, column.level(Level.REGION)).stream().filter(canSpawn), + shuffled(world, column.level(Level.BIOME)).stream().filter(canSpawn))) + .filter(keyed -> chunk.livingEntities() < keyed.spawner().maxEntitiesPerChunk()) + .toList(); + + List spawns = candidates.stream().flatMap(keyed -> spawnsOf(keyed, chunk.initial())).collect(Collectors.toList()); + Candidate chosen = RarityWeighting.expand(spawns, Candidate::rarity).getRandom(); + if (chosen == null) { + return Optional.empty(); + } + return planChunkSpawn(world, running, chunk, chosen); + } + + private Optional planChunkSpawn(PackWorld world, RunningWorld running, Chunk chunk, Candidate chosen) { + EntitySpawn spawn = chosen.spawn(); + int count = LootResolver.inclusive(RNG.r, spawn.minSpawns(), spawn.maxSpawns()); + List attempts = new ArrayList<>(); + for (int i = 0; i < count; i++) { + int x = (chunk.chunkX() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE); + int z = (chunk.chunkZ() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE); + BlockPosition at = spawnPosition(running, chosen.spawner(), chunk.chunkX(), chunk.chunkZ(), x, z); + if (at != null) { + addAttempt(attempts, world, chosen, at, true); + } + } + return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(world.resources().idOf(chosen.key()), chunk.chunkX(), chunk.chunkZ(), false, attempts)); + } + + /** Where a spawner of its group puts an entity at the column; null when it has no place for one. */ + private static BlockPosition spawnPosition(RunningWorld running, Spawner spawner, int chunkX, int chunkZ, int x, int z) { + int height = running.highest(x, z, true); + int heightWithFluid = running.highest(x, z, false); + return switch (spawner.group()) { + case NORMAL -> new BlockPosition(x, heightWithFluid + 1, z); + case CAVE -> caveSpawnPosition(running, chunkX, chunkZ); + case UNDERWATER, BEACH -> new BlockPosition(x, RNG.r.i(height + 1, heightWithFluid), z); + }; + } + + static BlockPosition caveSpawnPosition(RunningWorld running, int chunkX, int chunkZ) { + KList floors = new KList<>(running.caveFloors(chunkX, chunkZ)); + BlockPosition floor = floors.getRandom(RNG.r); + return floor == null ? null : new BlockPosition(floor.x(), floor.y() + AIR_ABOVE_MARKER, floor.z()); + } + + private Optional planMarker(PackWorld world, Marker marker) { + String spawnerKey = marker.spawner().path(); + Spawner spawner = SpawnResources.spawner(world.resources(), spawnerKey); + SpawnMarker spawnMarker = SpawnResources.marker(world.resources(), marker.marker().path()); + if (spawner == null) { + return Optional.empty(); + } + + List candidates = marker.initial() ? spawner.initialSpawns() : spawner.spawns(); + if (candidates.isEmpty()) { + return Optional.empty(); + } + EntitySpawn spawn = RarityWeighting.expand(candidates, EntitySpawn::rarity).getRandom(); + + BlockPosition position = marker.position(); + int chunkX = PowerOfTwoCoordinates.blockToChunkFloor(position.x()); + int chunkZ = PowerOfTwoCoordinates.blockToChunkFloor(position.z()); + if (!SpawnerGate.of(world).canSpawn(spawnerKey, spawner, chunkX, chunkZ)) { + return Optional.empty(); + } + + int count = LootResolver.inclusive(RNG.r, spawn.minSpawns(), spawn.maxSpawns()); + if (count <= 0) { + return Optional.empty(); + } + boolean exhaustsMarker = spawnMarker != null && shouldExhaust(spawnMarker); + List attempts = new ArrayList<>(); + BlockPosition above = new BlockPosition(position.x(), position.y() + AIR_ABOVE_MARKER, position.z()); + for (int i = 0; i < count; i++) { + addAttempt(attempts, world, new Candidate(spawnerKey, spawner, spawn), above, false); + } + return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(marker.spawner(), chunkX, chunkZ, exhaustsMarker, attempts)); + } + + private static boolean shouldExhaust(SpawnMarker marker) { + return marker.exhaustionChance() > RNG.r.nextDouble(); + } + + private void addAttempt(List attempts, PackWorld world, Candidate candidate, BlockPosition at, boolean checkSurface) { + EntityDefinition entity = SpawnResources.entity(world.resources(), candidate.spawn().entity()); + if (entity == null) { + world.log().debug(" You are trying to spawn an entity that does not exist!"); + return; + } + + Range light = candidate.spawner().allowedLightLevels(); + resolution(world).resolve(entity, entityRandom(world).rng()).ifPresent(spec -> attempts.add(new Attempt(at, spec, + surfaceOf(entity.surface()), (int) Math.ceil(light.min()), (int) Math.floor(light.max()), checkSurface))); + } + + private static EntityResolution resolution(PackWorld world) { + RunningWorld running = world.running().orElseThrow(); + LootItems items = new LootItems(world.resources().items(), running.debug(), world.log()); + return new EntityResolution(world.resources(), items, running.sky(), world.state(EffectTimers.class, ignored -> new EffectTimers()), + world.log()); + } + + private static EntityRandom entityRandom(PackWorld world) { + return world.state(EntityRandom.class, EntityRandom::new); + } + + private static Surface surfaceOf(SpawnSurface surface) { + return Surface.valueOf(surface.name()); + } + + /** The spawners the dimension, region or surface biome at the column lists, in a random order. */ + private static List shuffled(PackWorld world, Optional declared) { + List keys = declared.map(SpawnerSettings::spawners).orElse(List.of()); + return new KList<>(SpawnResources.spawners(world.resources(), keys)).shuffleCopy(RNG.r); + } + + private static Stream spawnsOf(KeyedSpawner keyed, boolean initial) { + List spawns = initial ? keyed.spawner().initialSpawns() : keyed.spawner().spawns(); + return spawns.stream().map(spawn -> new Candidate(keyed.key(), keyed.spawner(), spawn)); + } + + /** A spawn of a spawner, which picks as often as the spawn's rarity says. */ + private record Candidate(String key, Spawner spawner, EntitySpawn spawn) { + int rarity() { + return spawn.rarity(); + } + } + + /** The random stream entities are made from, seeded from the world like Iris always seeded it; one per world. */ + private static final class EntityRandom { + private final RNG rng; + + private EntityRandom(PackWorld world) { + this.rng = new RNG(world.seed(IrisSeedPurposes.ENTITY)); + } + + private RNG rng() { + return rng; + } + } + + /** When the world's spawner cooldowns were last tidied. */ + private static final class CooldownCleanup { + private final ChronoLatch latch = new ChronoLatch(COOLDOWN_CLEANUP_INTERVAL_MILLISECONDS); + + private boolean due() { + return latch.flip(); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/spawn/RarityWeighting.java b/module/src/main/java/art/arcane/iris/engine/spawn/RarityWeighting.java new file mode 100644 index 000000000..6e700e3cf --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/spawn/RarityWeighting.java @@ -0,0 +1,53 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.volmlib.util.collection.KList; + +import java.util.List; +import java.util.function.ToIntFunction; + +/** + * Applies rarity to a pick: each possibility appears in the expansion as often as its rarity says, so picking one at + * random from the expansion picks the rarer ones less often. Spawner choices go through this once; rarity must never be + * applied a second time per spawn position. + */ +final class RarityWeighting { + private static final int MINIMUM_RARITY = 1; + + private RarityWeighting() { + } + + /** Each of {@code possibilities} repeated total/rarity times, where a rarity below 1 counts as 1. */ + static KList expand(List possibilities, ToIntFunction rarity) { + KList expanded = new KList<>(); + int totalRarity = 0; + for (T possibility : possibilities) { + totalRarity += rarityOf(possibility, rarity); + } + for (T possibility : possibilities) { + expanded.addMultiple(possibility, totalRarity / rarityOf(possibility, rarity)); + } + return expanded; + } + + private static int rarityOf(T possibility, ToIntFunction rarity) { + return Math.max(MINIMUM_RARITY, rarity.applyAsInt(possibility)); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java b/module/src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java new file mode 100644 index 000000000..8688584d7 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java @@ -0,0 +1,42 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.builtin.spawn.SpawnTimeBlock; +import art.arcane.iris.builtin.spawn.SpawnWeather; +import com.volmit.world.RunningWorld.Sky; + +/** The time of day and the weather a command or spawner of the pack asks for, checked against a world's sky. */ +final class SpawnConditions { + private static final double TICKS_PER_HOUR = 1000D; + private static final double HOURS_AT_TIME_ZERO = 6; + private static final double HOURS_PER_DAY = 24; + + private SpawnConditions() { + } + + static boolean allow(SpawnTimeBlock time, SpawnWeather weather, Sky sky) { + return time.contains(hourOf(sky)) && weather.matches(sky.storming(), sky.thundering()); + } + + /** The world's time of day as a clock hour: tick 0 is 6 in the morning. */ + static double hourOf(Sky sky) { + return ((sky.time() / TICKS_PER_HOUR) + HOURS_AT_TIME_ZERO) % HOURS_PER_DAY; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/spawn/SpawnCooldownBook.java b/module/src/main/java/art/arcane/iris/engine/spawn/SpawnCooldownBook.java new file mode 100644 index 000000000..6514e19e1 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/spawn/SpawnCooldownBook.java @@ -0,0 +1,175 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.volmlib.util.cache.CacheKey; +import com.volmit.data.SavedKey; +import com.volmit.data.StorageCodec; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.LongSupplier; +import java.util.function.ToLongFunction; + +/** + * When spawners last fired, in the world and in each chunk, which the host saves with the world so that a spawner's + * rates hold across restarts. Spawners count by the key the pack names them by. Safe for concurrent use. + */ +final class SpawnCooldownBook { + static final SavedKey SAVED = new SavedKey<>(ResourceId.parse("iris:spawn/cooldowns"), SpawnCooldownBook.class, + codec(System::currentTimeMillis), () -> new SpawnCooldownBook(System::currentTimeMillis)); + + private static final int FORMAT_VERSION = 1; + + private final LongSupplier clockMilliseconds; + private final Map worldFiredAt = new ConcurrentHashMap<>(); + private final Map> chunkFiredAt = new ConcurrentHashMap<>(); + + SpawnCooldownBook(LongSupplier clockMilliseconds) { + this.clockMilliseconds = clockMilliseconds; + } + + /** The book the world keeps. */ + static SpawnCooldownBook of(PackWorld world) { + return world.running().orElseThrow().saved(SAVED); + } + + /** How {@link #SAVED} is stored: the books read by this codec count time with {@code clockMilliseconds}. */ + static StorageCodec codec(LongSupplier clockMilliseconds) { + return new BookCodec(clockMilliseconds); + } + + /** Whether the spawner may fire in the world again, {@code intervalMilliseconds} after it last did. */ + boolean canSpawn(String spawner, long intervalMilliseconds) { + return hasElapsed(worldFiredAt.get(spawner), intervalMilliseconds); + } + + /** Notes that the spawner fired in the world now. */ + void spawned(String spawner) { + worldFiredAt.put(spawner, clockMilliseconds.getAsLong()); + } + + /** Whether the spawner may fire in the chunk again, {@code intervalMilliseconds} after it last did there. */ + boolean canSpawnInChunk(int chunkX, int chunkZ, String spawner, long intervalMilliseconds) { + Map spawnersOfChunk = chunkFiredAt.get(CacheKey.key(chunkX, chunkZ)); + return hasElapsed(spawnersOfChunk == null ? null : spawnersOfChunk.get(spawner), intervalMilliseconds); + } + + /** Notes that the spawner fired in the chunk now. */ + void spawnedInChunk(int chunkX, int chunkZ, String spawner) { + long firedAt = clockMilliseconds.getAsLong(); + chunkFiredAt.compute(CacheKey.key(chunkX, chunkZ), (chunk, spawnersOfChunk) -> { + Map kept = spawnersOfChunk == null ? new ConcurrentHashMap<>() : spawnersOfChunk; + kept.put(spawner, firedAt); + return kept; + }); + } + + /** + * Forgets the cooldowns that ran out and those of spawners the pack no longer has, so the saved data does not grow. + * + * @param intervalMilliseconds the interval of the world rate of a spawner by its key, or a negative number for a spawner the pack lacks + */ + void forgetExpired(ToLongFunction intervalMilliseconds) { + worldFiredAt.entrySet().removeIf(fired -> isForgotten(fired.getKey(), fired.getValue(), intervalMilliseconds)); + for (Long chunk : List.copyOf(chunkFiredAt.keySet())) { + chunkFiredAt.computeIfPresent(chunk, (key, spawnersOfChunk) -> { + spawnersOfChunk.entrySet().removeIf(fired -> isForgotten(fired.getKey(), fired.getValue(), intervalMilliseconds)); + return spawnersOfChunk.isEmpty() ? null : spawnersOfChunk; + }); + } + } + + private boolean isForgotten(String spawner, long firedAt, ToLongFunction intervalMilliseconds) { + long interval = intervalMilliseconds.applyAsLong(spawner); + return interval < 0 || hasElapsed(firedAt, interval); + } + + private boolean hasElapsed(Long firedAt, long intervalMilliseconds) { + return firedAt == null || clockMilliseconds.getAsLong() - firedAt > intervalMilliseconds; + } + + private record BookCodec(LongSupplier clockMilliseconds) implements StorageCodec { + @Override + public int version() { + return FORMAT_VERSION; + } + + @Override + public void write(DataOutput output, SpawnCooldownBook book) throws IOException { + writeFired(output, book.worldFiredAt); + List>> chunks = new ArrayList<>(book.chunkFiredAt.entrySet()); + output.writeInt(chunks.size()); + for (Map.Entry> chunk : chunks) { + output.writeLong(chunk.getKey()); + writeFired(output, chunk.getValue()); + } + } + + @Override + public SpawnCooldownBook read(DataInput input, int storedVersion) throws IOException { + if (storedVersion != FORMAT_VERSION) { + throw new IOException("Unsupported spawn cooldown format version " + storedVersion); + } + SpawnCooldownBook book = new SpawnCooldownBook(clockMilliseconds); + readFired(input, book.worldFiredAt); + int chunks = readCount(input); + for (int chunk = 0; chunk < chunks; chunk++) { + Map spawnersOfChunk = new ConcurrentHashMap<>(); + long key = input.readLong(); + readFired(input, spawnersOfChunk); + if (!spawnersOfChunk.isEmpty()) { + book.chunkFiredAt.put(key, spawnersOfChunk); + } + } + return book; + } + + private static void writeFired(DataOutput output, Map firedAt) throws IOException { + List> snapshot = new ArrayList<>(firedAt.entrySet()); + output.writeInt(snapshot.size()); + for (Map.Entry fired : snapshot) { + output.writeUTF(fired.getKey()); + output.writeLong(fired.getValue()); + } + } + + private static void readFired(DataInput input, Map firedAt) throws IOException { + int count = readCount(input); + for (int index = 0; index < count; index++) { + firedAt.put(input.readUTF(), input.readLong()); + } + } + + private static int readCount(DataInput input) throws IOException { + int count = input.readInt(); + if (count < 0) { + throw new IOException("Negative entry count " + count); + } + return count; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java b/module/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java new file mode 100644 index 000000000..9aafb7a16 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java @@ -0,0 +1,54 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.modules.spawn.EffectSettings; +import art.arcane.iris.modules.spawn.SpawnerSettings; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.service.AmbientEffects; +import com.volmit.service.EntitySpawns; + +/** + * Module {@code iris:spawn}: the spawners, entities and markers of the pack ({@link SpawnResources}), the + * {@link SpawnerSettings} that dimensions, regions and biomes list, the entities that appear in the world over time + * because of them, and the ambient effects ({@link EffectSettings}) that play around players. It has no generation + * stage; Iris asks it through {@link EntitySpawns} when it looks for something to spawn in a chunk or at a marker, and + * through {@link AmbientEffects} for the effects due around a player. + */ +public final class SpawnModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:spawn", "Spawn", VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + var registry = setup.registry(); + registry.registerSettings(SpawnerSettings.class); + registry.registerSettings(EffectSettings.class); + SpawnResources.kinds().forEach(registry::registerResourceKind); + registry.registerSaved(SpawnCooldownBook.SAVED); + registry.registerService(EntitySpawns.class, new EntitySpawning()); + registry.registerService(AmbientEffects.class, new AmbientEffecting()); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java b/module/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java new file mode 100644 index 000000000..9daa05eb6 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java @@ -0,0 +1,113 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.builtin.spawn.EntityDefinition; +import art.arcane.iris.builtin.spawn.SpawnMarker; +import art.arcane.iris.builtin.spawn.Spawner; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; + +import java.util.ArrayList; +import java.util.List; + +/** + * The resource kinds of module {@code iris:spawn}, which keep the folders and files Iris packs have always used, and + * lookups by pack key for code that still names spawners, entities and markers by key. Every lookup goes through the + * pack's {@link com.volmit.resource.PackResources}, so it sees the pack's current snapshot. + *

+ * Lookups answer null where Iris's loaders did: for a blank key, a key the pack has no file for, and a file that fails + * to load, which was reported when it was read. + */ +public final class SpawnResources { + /** Spawners, in {@code spawners/}. */ + public static final ResourceKind SPAWNERS = ResourceKind.of("iris:spawn/spawner", "spawners", Spawner.class); + /** Entities, in {@code entities/}. */ + public static final ResourceKind ENTITIES = ResourceKind.of("iris:spawn/entity", "entities", EntityDefinition.class); + /** Markers, in {@code markers/}. */ + public static final ResourceKind MARKERS = ResourceKind.of("iris:spawn/marker", "markers", SpawnMarker.class); + + private SpawnResources() { + } + + /** A spawner and the key the pack names it by. */ + public record KeyedSpawner(String key, Spawner spawner) { + } + + /** Every resource kind of the spawn module. */ + public static List> kinds() { + return List.of(SPAWNERS, ENTITIES, MARKERS); + } + + public static Spawner spawner(PackResources resources, String key) { + return find(resources, SPAWNERS, key); + } + + public static EntityDefinition entity(PackResources resources, String key) { + return find(resources, ENTITIES, key); + } + + public static SpawnMarker marker(PackResources resources, String key) { + return find(resources, MARKERS, key); + } + + /** The spawners of the pack named by {@code keys}, in order, without the ones the pack lacks. */ + public static List spawners(PackResources resources, List keys) { + List spawners = new ArrayList<>(); + for (String key : keys) { + Spawner spawner = spawner(resources, key); + if (spawner != null) { + spawners.add(new KeyedSpawner(key, spawner)); + } + } + return spawners; + } + + /** The key of every entity of the pack, in key order. */ + public static List entityKeys(PackResources resources) { + return keys(resources, ENTITIES); + } + + /** The key of every spawner of the pack, in key order. */ + public static List spawnerKeys(PackResources resources) { + return keys(resources, SPAWNERS); + } + + /** The key of every marker of the pack, in key order. */ + public static List markerKeys(PackResources resources) { + return keys(resources, MARKERS); + } + + private static T find(PackResources resources, ResourceKind kind, String key) { + if (key == null || key.isBlank()) { + return null; + } + try { + return resources.find(kind, resources.idOf(key)).orElse(null); + } catch (IllegalStateException failedToLoad) { + return null; + } + } + + /** A key's id has the key as its path, so the path names the resource again wherever a key is expected. */ + private static List keys(PackResources resources, ResourceKind kind) { + return resources.ids(kind).stream().map(ResourceId::path).toList(); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java b/module/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java new file mode 100644 index 000000000..6fa594297 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java @@ -0,0 +1,103 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.builtin.spawn.SpawnRate; +import art.arcane.iris.builtin.spawn.Spawner; +import com.volmit.world.BiomeKind; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld.Sky; + +import java.util.Optional; + +/** + * Whether a spawner may fire: in a biome of the kind its group wants, in the time and weather it asks for, and not + * more often than its rates allow. The rates count in the world's saved cooldowns, by the key the pack names the + * spawner by. + * + * @param sky the world's time and weather when the gate was made; empty while the platform has not loaded the world + * @param cooldowns when the world's spawners last fired + */ +record SpawnerGate(Optional sky, SpawnCooldownBook cooldowns) { + /** The gate of the running world, with its time and weather now. */ + static SpawnerGate of(PackWorld world) { + return new SpawnerGate(world.running().orElseThrow().sky(), SpawnCooldownBook.of(world)); + } + + /** Whether a spawner of this group fires in a biome of {@code kind}. */ + static boolean suits(Spawner spawner, BiomeKind kind) { + return switch (spawner.group()) { + case NORMAL -> switch (kind) { + case SHORE, SEA, CAVE -> false; + case LAND -> true; + }; + case CAVE -> true; + case UNDERWATER -> switch (kind) { + case SHORE, LAND, CAVE -> false; + case SEA -> true; + }; + case BEACH -> switch (kind) { + case SHORE -> true; + case LAND, CAVE, SEA -> false; + }; + }; + } + + /** Whether the world is in the time and weather the spawner asks for. */ + static boolean suits(Spawner spawner, Sky sky) { + return SpawnConditions.allow(spawner.timeBlock(), spawner.weather(), sky); + } + + /** Whether the spawner may fire in the chunk now. */ + boolean canSpawn(String key, Spawner spawner, int chunkX, int chunkZ) { + if (!canSpawn(key, spawner)) { + return false; + } + + SpawnRate rate = spawner.maximumRatePerChunk(); + return rate.isInfinite() || cooldowns.canSpawnInChunk(chunkX, chunkZ, key, rate.interval()); + } + + /** Counts a spawn of the spawner in the chunk against its rates. */ + void spawned(String key, Spawner spawner, int chunkX, int chunkZ) { + spawned(key, spawner); + if (spawner.maximumRatePerChunk().isInfinite()) { + return; + } + + cooldowns.spawnedInChunk(chunkX, chunkZ, key); + } + + private boolean canSpawn(String key, Spawner spawner) { + if (sky.isEmpty() || !suits(spawner, sky.get())) { + return false; + } + + SpawnRate rate = spawner.maximumRate(); + return rate.isInfinite() || cooldowns.canSpawn(key, rate.interval()); + } + + private void spawned(String key, Spawner spawner) { + if (spawner.maximumRate().isInfinite()) { + return; + } + + cooldowns.spawned(key); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/blocks/SmartBoreDebugSettings.java b/module/src/main/java/art/arcane/iris/modules/blocks/SmartBoreDebugSettings.java new file mode 100644 index 000000000..7568d1247 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/blocks/SmartBoreDebugSettings.java @@ -0,0 +1,39 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.blocks; + +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.Level; + +/** Whether a dimension shows the air smart boring writes as cobwebs, written as {@code "debugSmartBore": true}. */ +@Desc("Write the air that smart boring places as cobwebs, to see where it bored.") +@Feature(id = "iris:blocks/debug-smart-bore", name = "Debug smart bore", key = "debugSmartBore", root = "show", targets = Level.DIMENSION) +public final class SmartBoreDebugSettings implements IrisFeature { + @Desc("Write the air that smart boring places as cobwebs, to see where it bored.") + private boolean show = false; + + public SmartBoreDebugSettings() { + } + + public boolean show() { + return show; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CarvingBiomeSettings.java b/module/src/main/java/art/arcane/iris/modules/carve/CarvingBiomeSettings.java new file mode 100644 index 000000000..391208a09 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CarvingBiomeSettings.java @@ -0,0 +1,56 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.carve; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.ResourceRef; +import com.volmit.world.LinkedBiomes; +import com.volmit.world.PackBiome; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; + +import java.util.Set; + +/** A biome's {@code carvingBiome}, written as the biome key: it registers that biome with the pack's layout and is not applied as a substitute under carvings. */ +@Desc("Registers the referenced biome with this pack's reachable biome set. It is NOT applied as a substitute under carvings; cave biomes come from the region's caveBiomes list.") +@Feature(id = "iris:carve/biome", name = "Carving biome", key = "carvingBiome", root = "biome", targets = Level.BIOME) +public final class CarvingBiomeSettings implements IrisFeature, LinkedBiomes { + @ResourceRef(PackBiome.class) + @Desc("Registers the referenced biome with this pack's reachable biome set. It is NOT applied as a substitute under carvings; cave biomes come from the region's caveBiomes list.") + private String biome = ""; + + public CarvingBiomeSettings() { + } + + public CarvingBiomeSettings(String biome) { + this.biome = biome; + } + + public String biome() { + return biome == null ? "" : biome; + } + + @Override + public Set treeBiomes(PackResources pack) { + return biome().isBlank() ? Set.of() : Set.of(pack.idOf(biome())); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CarvingEnabledSettings.java b/module/src/main/java/art/arcane/iris/modules/carve/CarvingEnabledSettings.java new file mode 100644 index 000000000..eb5339324 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CarvingEnabledSettings.java @@ -0,0 +1,43 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.carve; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** A dimension's {@code carvingEnabled}, written as the bare boolean. */ +@Desc("Enable or disable all carving for this dimension") +@Feature(id = "iris:carve/enabled", name = "Carving enabled", key = "carvingEnabled", root = "enabled", targets = Level.DIMENSION) +public final class CarvingEnabledSettings implements IrisFeature { + @Desc("Enable or disable all carving for this dimension") + private boolean enabled = true; + + public CarvingEnabledSettings() { + } + + public CarvingEnabledSettings(boolean enabled) { + this.enabled = enabled; + } + + public boolean enabled() { + return enabled; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CarvingEntry.java b/module/src/main/java/art/arcane/iris/modules/carve/CarvingEntry.java new file mode 100644 index 000000000..bcca11714 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CarvingEntry.java @@ -0,0 +1,103 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.carve; + +import com.volmit.config.Desc; +import com.volmit.config.Range; +import com.volmit.config.ResourceRef; +import com.volmit.world.PackBiome; +import com.volmit.config.Snippet; +import com.volmit.noise.NoiseStyle; + +import java.util.Collections; +import java.util.List; + +/** + * One dimension-level cave biome override, an entry of {@code carving}: a pack biome that replaces the cave biome within a band + * of world Y, optionally split into child entries by a noise pattern. IrisApi types only; {@code CarvingResolver} picks + * the entry for a position. + */ +@Snippet("iris/carve/dimension-carving-entry") +@Desc("Dimension-level cave biome override with absolute world Y bounds.") +public final class CarvingEntry { + private static final double DEFAULT_WORLD_Y_MIN = -64; + private static final double DEFAULT_WORLD_Y_MAX = 320; + private static final double DEFAULT_CHILD_SHRINK_FACTOR = 1.5; + private static final int DEFAULT_CHILD_RECURSION_DEPTH = 3; + + @Desc("Stable id for this carving entry") + private String id = ""; + + @Desc("Enable or disable this carving entry") + private boolean enabled = true; + + @ResourceRef(PackBiome.class) + @Desc("Cave biome to apply when world Y falls within worldYRange") + private String biome = ""; + + @Desc("Absolute world Y bounds where this carving entry applies") + private Range worldYRange = Range.of(DEFAULT_WORLD_Y_MIN, DEFAULT_WORLD_Y_MAX); + + @Desc("If this carving entry has child carving entries, this controls how small those child carving patches are.") + private double childShrinkFactor = DEFAULT_CHILD_SHRINK_FACTOR; + + @Desc("If this carving entry has child carving entries, this controls the shape pattern used to pick them.") + private NoiseStyle childStyle = NoiseStyle.of("CELLULAR_IRIS_DOUBLE"); + + @Desc("Child carving entry ids. Child ids can point back to parent ids to create cycles; recursion is bounded by childRecursionDepth.") + private List children = List.of(); + + @Desc("Maximum recursion depth when resolving child carving entries from this entry.") + private int childRecursionDepth = DEFAULT_CHILD_RECURSION_DEPTH; + + public CarvingEntry() { + } + + public String id() { + return id == null ? "" : id; + } + + public boolean enabled() { + return enabled; + } + + public String biome() { + return biome == null ? "" : biome; + } + + public Range worldYRange() { + return worldYRange; + } + + public double childShrinkFactor() { + return childShrinkFactor; + } + + public NoiseStyle childStyle() { + return childStyle; + } + + public List children() { + return children == null ? List.of() : Collections.unmodifiableList(children); + } + + public int childRecursionDepth() { + return childRecursionDepth; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CarvingSettings.java b/module/src/main/java/art/arcane/iris/modules/carve/CarvingSettings.java new file mode 100644 index 000000000..04a5f235f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CarvingSettings.java @@ -0,0 +1,80 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.carve; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.PackSettings; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.world.LinkedBiomes; + +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * The cave biome overrides a dimension declares, written as {@code "carving": [...]}, the list of {@link CarvingEntry}s. + * The biome of every enabled entry takes part in the pack's layout like any biome the dimension reaches. + */ +@Desc("Dimension-level cave biome carving overrides with absolute world Y ranges") +@Feature(id = "iris:carve/bands", name = "Cave biome bands", key = "carving", root = "entries", targets = Level.DIMENSION) +public final class CarvingSettings implements IrisFeature, LinkedBiomes { + @Desc("Dimension-level cave biome carving overrides with absolute world Y ranges") + private List entries = List.of(); + + public CarvingSettings() { + } + + public CarvingSettings(List entries) { + this.entries = List.copyOf(entries); + } + + public List entries() { + return entries == null ? List.of() : Collections.unmodifiableList(entries); + } + + /** + * The biome key {@code reference} stands for: the biome of the entry with that id, ignoring surrounding blanks, or + * {@code reference} itself when no entry has the id. When several entries share an id the last one counts. + */ + public String biomeOf(String reference) { + CarvingEntry entry = null; + for (CarvingEntry candidate : entries()) { + if (candidate != null && !candidate.id().isBlank() && candidate.id().trim().equals(reference)) { + entry = candidate; + } + } + return entry == null ? reference : entry.biome(); + } + + @Override + public Set usedBiomes(PackResources pack, PackSettings dimension) { + Set biomes = new LinkedHashSet<>(); + for (CarvingEntry entry : entries()) { + if (entry != null && entry.enabled() && entry.biome() != null && !entry.biome().isBlank()) { + biomes.add(pack.idOf(entry.biome())); + } + } + return biomes; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveDepthSettings.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveDepthSettings.java new file mode 100644 index 000000000..10393858b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveDepthSettings.java @@ -0,0 +1,47 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.carve; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** A biome's {@code caveMinDepthBelowSurface}, written as the bare number of blocks. */ +@Desc("Minimum depth below terrain surface required before this cave biome can be selected.") +@Feature(id = "iris:carve/min-depth", name = "Cave minimum depth", key = "caveMinDepthBelowSurface", root = "depth", targets = Level.BIOME) +public final class CaveDepthSettings implements IrisFeature { + @MinNumber(0) + @MaxNumber(256) + @Desc("Minimum depth below terrain surface required before this cave biome can be selected.") + private int depth = 0; + + public CaveDepthSettings() { + } + + public CaveDepthSettings(int depth) { + this.depth = depth; + } + + public int depth() { + return depth; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveProfile.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveProfile.java new file mode 100644 index 000000000..4f57b7879 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveProfile.java @@ -0,0 +1,308 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.carve; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CaveAnchorMode; +import art.arcane.iris.builtin.carve.CaveFieldModule; +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Range; +import com.volmit.config.Snippet; +import com.volmit.noise.NoiseStyle; +import com.volmit.noise.StyledRange; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +/** + * A 3D cave profile as packs write it for a dimension, region or biome ({@code caveProfile}) or under + * {@code snippet/iris/carve/cave-profile/}: the noise fields that decide where caves are, how they meet the surface, where + * cave fluid may sit and how objects find anchors in them. A level that writes none has no profile, which is the + * same as one that is not {@code enabled}. IrisApi types only; the carving module builds the noise. + */ +@Snippet("iris/carve/cave-profile") +@Desc("Represents a configurable 3D cave profile.") +@Feature(id = "iris:carve/profile", name = "Cave profile", key = "caveProfile", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) +public final class CaveProfile implements IrisFeature { + @Desc("Enable profile-driven cave carving.") + private boolean enabled = false; + + @Desc("Global vertical bounds for profile cave carving, in engine-local Y where 0 is the bottom of the dimension, not world Y.") + private Range verticalRange = Range.of(0, 384); + + @MinNumber(0) + @MaxNumber(128) + @Desc("Vertical fade range applied near cave profile min/max bounds to avoid abrupt hard-stop ceilings/floors.") + private int verticalEdgeFade = 20; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Strength of the vertical edge fade at cave profile min/max bounds.") + private double verticalEdgeFadeStrength = 0.18; + + @Desc("Base density style for cave field generation.") + private NoiseStyle baseDensityStyle = NoiseStyle.of("CELLULAR_IRIS_DOUBLE"); + + @Desc("Detail density style blended into base caves.") + private NoiseStyle detailDensityStyle = NoiseStyle.of("SIMPLEX"); + + @Desc("Warp style used to distort cave coordinates.") + private NoiseStyle warpStyle = NoiseStyle.of("FLAT"); + + @MinNumber(0) + @Desc("Base cave field multiplier.") + private double baseWeight = 1; + + @MinNumber(0) + @Desc("Detail cave field multiplier.") + private double detailWeight = 0.35; + + @MinNumber(0) + @Desc("Coordinate warp strength for cave fields.") + private double warpStrength = 0; + + @Desc("Threshold range used for carve cutoff decisions.") + private StyledRange densityThreshold = StyledRange.of(-0.2, 0.2, NoiseStyle.of("CELLULAR_IRIS_DOUBLE")); + + @MinNumber(0) + @MaxNumber(1) + @Desc("Extra threshold bias subtracted from sampled threshold before carve tests.") + private double thresholdBias = 0.16; + + @MinNumber(1) + @MaxNumber(8) + @Desc("Vertical sample step used while evaluating cave density.") + private int sampleStep = 1; + + @Desc("Use adaptive cave density prediction so only threshold-adjacent cells fall back to full-resolution evaluation.") + private boolean adaptiveSampling = true; + + @MinNumber(2) + @MaxNumber(4) + @Desc("Horizontal adaptive predictor tuning. The carver always samples the predictor grid at a fixed step of 8; values below 8 only widen the ambiguity margin slightly and do not tighten the grid.") + private int adaptiveSampleStep = 2; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Additional adaptive ambiguity margin used before the cave predictor falls back to exact sampling.") + private double adaptiveThresholdMargin = 0.04; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Minimum solid clearance below terrain surface where carving may occur.") + private int surfaceClearance = 4; + + @Desc("Allow profile-driven cave carving to break through terrain surface in selected columns.") + private boolean allowSurfaceBreak = true; + + @Desc("Noise style used to decide where surface-breaking cave columns are allowed.") + private NoiseStyle surfaceBreakStyle = NoiseStyle.of("SIMPLEX").withZoom(0.08); + + @MinNumber(-1) + @MaxNumber(1) + @Desc("Minimum signed surface-break noise value required before near-surface carving is allowed.") + private double surfaceBreakNoiseThreshold = 0.62; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Near-surface depth window used for surface-break carve logic.") + private int surfaceBreakDepth = 18; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Additional threshold boost applied while carving in the surface-break depth window.") + private double surfaceBreakThresholdBoost = 0.2; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Minimum depth below terrain surface required for cave-only object anchor placement.") + private int objectMinDepthBelowSurface = 6; + + @Desc("Additional layered cave-density modules.") + private List modules = List.of(); + + @Desc("Default cave anchor mode for cave-only object placement.") + private CaveAnchorMode defaultObjectAnchor = CaveAnchorMode.FLOOR; + + @Desc("Default placement mode for cave objects. Only applies to placements that are still on the default CENTER_HEIGHT mode; an explicit mode on the placement always wins. Stilt modes tile the object base block down to the cave floor surface. FAST_MIN_STILT is recommended for cave objects to prevent floating.") + private ObjectPlaceMode defaultObjectPlaceMode; + + @MinNumber(1) + @MaxNumber(8) + @Desc("Vertical scan step used while searching cave anchors.") + private int anchorScanStep = 1; + + @MinNumber(1) + @MaxNumber(64) + @Desc("Maximum random column retries while searching a valid cave object anchor in the chunk.") + private int anchorSearchAttempts = 6; + + @Desc("Allow cave fluid placement from the dimension fluid palette below fluid level.") + private boolean allowFluid = true; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Minimum depth below terrain surface required before cave fluid may be placed.") + private int fluidMinDepthBelowSurface = 12; + + @Desc("Require solid floor support below cave fluid to reduce unsupported fluid flows.") + private boolean fluidRequiresFloor = true; + + @Desc("Allow cave lava placement based on lava height.") + private boolean allowLava = true; + + + public CaveProfile() { + } + + public boolean enabled() { + return enabled; + } + + public Range verticalRange() { + return verticalRange; + } + + public int verticalEdgeFade() { + return verticalEdgeFade; + } + + public double verticalEdgeFadeStrength() { + return verticalEdgeFadeStrength; + } + + public NoiseStyle baseDensityStyle() { + return baseDensityStyle; + } + + public NoiseStyle detailDensityStyle() { + return detailDensityStyle; + } + + public NoiseStyle warpStyle() { + return warpStyle; + } + + public double baseWeight() { + return baseWeight; + } + + public double detailWeight() { + return detailWeight; + } + + public double warpStrength() { + return warpStrength; + } + + public StyledRange densityThreshold() { + return densityThreshold; + } + + public double thresholdBias() { + return thresholdBias; + } + + public int sampleStep() { + return sampleStep; + } + + public boolean adaptiveSampling() { + return adaptiveSampling; + } + + public int adaptiveSampleStep() { + return adaptiveSampleStep; + } + + public double adaptiveThresholdMargin() { + return adaptiveThresholdMargin; + } + + public int surfaceClearance() { + return surfaceClearance; + } + + public boolean allowSurfaceBreak() { + return allowSurfaceBreak; + } + + public NoiseStyle surfaceBreakStyle() { + return surfaceBreakStyle; + } + + public double surfaceBreakNoiseThreshold() { + return surfaceBreakNoiseThreshold; + } + + public int surfaceBreakDepth() { + return surfaceBreakDepth; + } + + public double surfaceBreakThresholdBoost() { + return surfaceBreakThresholdBoost; + } + + public int objectMinDepthBelowSurface() { + return objectMinDepthBelowSurface; + } + + public List modules() { + return modules == null ? List.of() : Collections.unmodifiableList(modules); + } + + public CaveAnchorMode defaultObjectAnchor() { + return defaultObjectAnchor == null ? CaveAnchorMode.FLOOR : defaultObjectAnchor; + } + + /** The mode cave objects take where their placement has none of its own; empty when the profile sets none. */ + public Optional defaultObjectPlaceMode() { + return Optional.ofNullable(defaultObjectPlaceMode); + } + + public int anchorScanStep() { + return anchorScanStep; + } + + public int anchorSearchAttempts() { + return anchorSearchAttempts; + } + + public boolean allowFluid() { + return allowFluid; + } + + public int fluidMinDepthBelowSurface() { + return fluidMinDepthBelowSurface; + } + + public boolean fluidRequiresFloor() { + return fluidRequiresFloor; + } + + public boolean allowLava() { + return allowLava; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/UpperDimensionCarvingSettings.java b/module/src/main/java/art/arcane/iris/modules/carve/UpperDimensionCarvingSettings.java new file mode 100644 index 000000000..a9a18fd8a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/UpperDimensionCarvingSettings.java @@ -0,0 +1,43 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.carve; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** A dimension's {@code upperDimensionCarving}, written as the bare boolean. */ +@Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.") +@Feature(id = "iris:carve/upper-dimension", name = "Upper dimension carving", key = "upperDimensionCarving", root = "enabled", targets = Level.DIMENSION) +public final class UpperDimensionCarvingSettings implements IrisFeature { + @Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.") + private boolean enabled = false; + + public UpperDimensionCarvingSettings() { + } + + public UpperDimensionCarvingSettings(boolean enabled) { + this.enabled = enabled; + } + + public boolean enabled() { + return enabled; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/decorant/DecorateSettings.java b/module/src/main/java/art/arcane/iris/modules/decorant/DecorateSettings.java new file mode 100644 index 000000000..7d68745e5 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/decorant/DecorateSettings.java @@ -0,0 +1,38 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.modules.decorant; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** Whether a dimension decorates at all, written as {@code "decorate": false}. A dimension without the key decorates. */ +@Desc("Generate decorations or not") +@Feature(id = "iris:decorant/decorate", name = "Decorate", key = "decorate", root = "decorate", targets = Level.DIMENSION) +public final class DecorateSettings implements IrisFeature { + @Desc("Generate decorations or not") + private boolean decorate = true; + + public DecorateSettings() { + } + + public boolean decorate() { + return decorate; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/deposit/DepositBiomeScope.java b/module/src/main/java/art/arcane/iris/modules/deposit/DepositBiomeScope.java new file mode 100644 index 000000000..5997e9a93 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/deposit/DepositBiomeScope.java @@ -0,0 +1,29 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.deposit; + +import com.volmit.config.Desc; + +@Desc("Selects which biome identity is checked by a deposit's include and exclude filters.") +public enum DepositBiomeScope { + @Desc("Checks the surface biome selected for the deposit column.") + SURFACE, + @Desc("Checks the cave biome selected at the deposit origin.") + CAVE +} diff --git a/module/src/main/java/art/arcane/iris/modules/deposit/DepositGenerator.java b/module/src/main/java/art/arcane/iris/modules/deposit/DepositGenerator.java new file mode 100644 index 000000000..dcc45f779 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/deposit/DepositGenerator.java @@ -0,0 +1,227 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.deposit; + +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +/** + * One kind of deposit a dimension, region or biome generates, as packs write it in the {@code "deposits"} list or under + * {@code snippet/iris/deposit/deposit/}: how many clumps of which blocks, how large, at which heights and in which biomes. A value + * of IrisApi types only; the deposit module builds the clumps and resolves the blocks. + */ +@Snippet("iris/deposit/deposit") +@Desc("Creates ore & other block deposits underground") +public final class DepositGenerator { + private static final int MAX_CLUMP_DIMENSION = 11; + + @Required + @MinNumber(-8192) + @MaxNumber(8192) + @Desc("The inclusive minimum origin height in engine-local Y, where 0 is the bottom of the dimension. Negative values let an unclipped vanilla distribution taper into the world floor.") + private int minHeight = 1; + + @Required + @MinNumber(-8192) + @MaxNumber(8192) + @Desc("The inclusive maximum origin height in engine-local Y, where 0 is the bottom of the dimension.") + private int maxHeight = 75; + + @Desc("How origin heights are sampled. CLIPPED_UNIFORM preserves Iris behavior by clipping the band to terrain; UNIFORM and TRIANGLE sample the authored band first and discard cells outside terrain or build height.") + private DepositHeightDistribution heightDistribution = DepositHeightDistribution.CLIPPED_UNIFORM; + + @Desc("TERRAIN places below the generated surface. ABOVE_TERRAIN places only in existing solid hosts above it. FULL_HEIGHT permits existing solid hosts anywhere in the dimension.") + private DepositPlacementScope placementScope = DepositPlacementScope.TERRAIN; + + @MinNumber(0) + @MaxNumber(256) + @Desc("Solid blocks kept between a deposit and the terrain surface. Vanilla-like deposits use 0; the Iris default remains 7.") + private int surfaceClearance = 7; + + @Required + @MinNumber(0) + @MaxNumber(8192) + @Desc("The minimum Iris block count or vanilla configured vein size, selected according to shape.") + private int minSize = 0; + + @Required + @MinNumber(0) + @MaxNumber(8192) + @Desc("The maximum Iris block count or vanilla configured vein size, selected according to shape.") + private int maxSize = 128; + + @Desc("IRIS places a fixed-count cube clump. VANILLA_ELLIPSOID uses Minecraft's chained ellipsoid geometry. VANILLA_SCATTERED uses Minecraft's sparse candidate offsets.") + private DepositShape shape = DepositShape.IRIS; + + @Required + @MinNumber(0) + @MaxNumber(2048) + @Desc("The maximum amount of clumps per chunk") + private int maxPerChunk = 3; + + @Required + @MinNumber(0) + @MaxNumber(2048) + @Desc("The minimum amount of clumps per chunk") + private int minPerChunk = 0; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance of the deposit spawning in a chunk") + private double spawnChance = 1; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance of each individual clump spawning in a chunk") + private double perClumpSpawnChance = 1; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Chance to discard a candidate ore block when it touches air. This matches vanilla ore exposure reduction.") + private double discardChanceOnAirExposure = 0; + + @Required + @Desc("The palette of blocks to be used in this deposit generator. Each entry is picked uniformly; the per-entry weight field is ignored here.") + private List palette = List.of(); + + @MinNumber(1) + @MaxNumber(64) + @Desc("Ore varience is how many different objects clumps iris will create") + private int varience = 3; + + @Desc("Optional block ids this deposit may replace. An empty list retains Iris's any-solid behavior.") + private List replaceableBlocks = List.of(); + + @Desc("Chooses whether includedBiomes and excludedBiomes inspect the surface biome or the cave biome at the deposit origin.") + private DepositBiomeScope biomeScope = DepositBiomeScope.CAVE; + + @Desc("Optional Iris biome keys or vanilla derivative ids allowed for this deposit.") + private List includedBiomes = List.of(); + + @Desc("Optional Iris biome keys or vanilla derivative ids denied for this deposit.") + private List excludedBiomes = List.of(); + + @Desc("If set to true, this deposit will replace bedrock") + private boolean replaceBedrock = false; + + /** A generator with every option at its default, as packs get it from {@code {}}. */ + public DepositGenerator() { + } + + public int minHeight() { + return minHeight; + } + + public int maxHeight() { + return maxHeight; + } + + public DepositHeightDistribution heightDistribution() { + return heightDistribution == null ? DepositHeightDistribution.CLIPPED_UNIFORM : heightDistribution; + } + + public DepositPlacementScope placementScope() { + return placementScope == null ? DepositPlacementScope.TERRAIN : placementScope; + } + + public int surfaceClearance() { + return surfaceClearance; + } + + public int minSize() { + return minSize; + } + + public int maxSize() { + return maxSize; + } + + public DepositShape shape() { + return shape == null ? DepositShape.IRIS : shape; + } + + public int maxPerChunk() { + return maxPerChunk; + } + + public int minPerChunk() { + return minPerChunk; + } + + public double spawnChance() { + return spawnChance; + } + + public double perClumpSpawnChance() { + return perClumpSpawnChance; + } + + public double discardChanceOnAirExposure() { + return discardChanceOnAirExposure; + } + + public List palette() { + return listOrEmpty(palette); + } + + public int varience() { + return varience; + } + + public List replaceableBlocks() { + return listOrEmpty(replaceableBlocks); + } + + public DepositBiomeScope biomeScope() { + return biomeScope == null ? DepositBiomeScope.CAVE : biomeScope; + } + + public List includedBiomes() { + return listOrEmpty(includedBiomes); + } + + public List excludedBiomes() { + return listOrEmpty(excludedBiomes); + } + + public boolean replaceBedrock() { + return replaceBedrock; + } + + /** The edge of the cube an {@link DepositShape#IRIS} clump of {@link #maxSize()} blocks fills, at most 11. */ + public int maxDimension() { + return Math.min(MAX_CLUMP_DIMENSION, (int) Math.ceil(Math.cbrt(maxSize))); + } + + /** Whether the biome filters need the cave biome at the deposit's origin. */ + public boolean usesCaveBiomeFilter() { + return biomeScope() == DepositBiomeScope.CAVE && (!includedBiomes().isEmpty() || !excludedBiomes().isEmpty()); + } + + private static List listOrEmpty(List list) { + return list == null ? List.of() : Collections.unmodifiableList(list); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/deposit/DepositHeightDistribution.java b/module/src/main/java/art/arcane/iris/modules/deposit/DepositHeightDistribution.java new file mode 100644 index 000000000..4a9f2e433 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/deposit/DepositHeightDistribution.java @@ -0,0 +1,31 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.deposit; + +import com.volmit.config.Desc; + +@Desc("Controls how a deposit chooses its origin height within the configured vertical band.") +public enum DepositHeightDistribution { + @Desc("Samples uniformly after clipping the configured band to the terrain and build-height bounds.") + CLIPPED_UNIFORM, + @Desc("Samples uniformly from the configured band, then rejects origins outside the terrain or build-height bounds.") + UNIFORM, + @Desc("Samples toward the middle of the configured band with a triangular distribution, then rejects invalid origins.") + TRIANGLE +} diff --git a/module/src/main/java/art/arcane/iris/modules/deposit/DepositPlacementScope.java b/module/src/main/java/art/arcane/iris/modules/deposit/DepositPlacementScope.java new file mode 100644 index 000000000..e2303f0f6 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/deposit/DepositPlacementScope.java @@ -0,0 +1,31 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.deposit; + +import com.volmit.config.Desc; + +@Desc("Controls which vertical part of the world may contain a deposit origin.") +public enum DepositPlacementScope { + @Desc("Places in solid terrain below the generated surface while preserving the configured surface clearance.") + TERRAIN, + @Desc("Places only in existing solid hosts above the generated terrain surface.") + ABOVE_TERRAIN, + @Desc("Places in existing solid hosts anywhere within the dimension build height.") + FULL_HEIGHT +} diff --git a/module/src/main/java/art/arcane/iris/modules/deposit/DepositSettings.java b/module/src/main/java/art/arcane/iris/modules/deposit/DepositSettings.java new file mode 100644 index 000000000..3b2bd20dc --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/deposit/DepositSettings.java @@ -0,0 +1,49 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.deposit; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.List; + +/** + * The deposits one dimension, region or biome declares, written as {@code "deposits": [...]}, the list of generators. Levels stack: + * a chunk gets the deposits of its dimension, its centre column's region and that column's biome. IrisApi types only, + * like {@link DepositGenerator}. + */ +@Desc("Ores and other deposits generated in every chunk where this applies") +@Feature(id = "iris:deposit", name = "Deposits", key = "deposits", root = "generators", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) +public final class DepositSettings implements IrisFeature { + @Desc("Define deposit generators that this applies to chunks") + private List generators = List.of(); + + public DepositSettings() { + } + + public DepositSettings(List generators) { + this.generators = List.copyOf(generators); + } + + public List generators() { + return generators; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/deposit/DepositShape.java b/module/src/main/java/art/arcane/iris/modules/deposit/DepositShape.java new file mode 100644 index 000000000..8ac3d3654 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/deposit/DepositShape.java @@ -0,0 +1,31 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.deposit; + +import com.volmit.config.Desc; + +@Desc("Selects the geometry used to build each deposit clump.") +public enum DepositShape { + @Desc("Builds the traditional Iris fixed-block-count cube clump.") + IRIS, + @Desc("Builds a chain of overlapping ellipsoids matching Minecraft's ordinary ore-vein geometry.") + VANILLA_ELLIPSOID, + @Desc("Builds sparse candidate offsets matching Minecraft's scattered-ore geometry.") + VANILLA_SCATTERED +} diff --git a/module/src/main/java/art/arcane/iris/modules/deposit/DepositVariant.java b/module/src/main/java/art/arcane/iris/modules/deposit/DepositVariant.java new file mode 100644 index 000000000..c7a92ee52 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/deposit/DepositVariant.java @@ -0,0 +1,67 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.deposit; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.Map; + +/** + * One deposit ore remap rule, an entry of {@code depositVariants}: within a vertical band, ore blocks are rewritten to + * alternate blocks. A value of IrisApi types only; {@code ResolvedDepositVariant} resolves the blocks. + */ +@Snippet("iris/deposit/deposit-variant") +@Desc("Remaps ore block ids to alternate block ids within a vertical band. Ores declared at dimension, region, and biome scope can be rewritten at placement time (for example, iron_ore -> deepslate_iron_ore inside a deep carving band, or yourmod:iron -> yourmod:moon_iron inside a lunar biome).") +public final class DepositVariant { + @Required + @MinNumber(-2048) + @MaxNumber(8192) + @Desc("Inclusive minimum world Y this variant applies at.") + private int minHeight = 0; + + @Required + @MinNumber(-2048) + @MaxNumber(8192) + @Desc("Inclusive maximum world Y this variant applies at.") + private int maxHeight = 0; + + @Required + @Desc("Source block id (for example `minecraft:iron_ore`) -> replacement block id (for example `minecraft:deepslate_iron_ore`). Any block id the data loader resolves is accepted, including external/mod blocks. Source match is by material only, so block properties on the source key are ignored.") + private Map remap = Map.of(); + + public DepositVariant() { + } + + public int minHeight() { + return minHeight; + } + + public int maxHeight() { + return maxHeight; + } + + public Map remap() { + return remap == null ? Map.of() : Collections.unmodifiableMap(remap); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/deposit/DepositVariantSettings.java b/module/src/main/java/art/arcane/iris/modules/deposit/DepositVariantSettings.java new file mode 100644 index 000000000..45a751f9c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/deposit/DepositVariantSettings.java @@ -0,0 +1,50 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.deposit; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.Collections; +import java.util.List; + +/** + * The deposit ore remap rules one dimension, region or biome declares, written as {@code "depositVariants": [...]}, the list + * of {@link DepositVariant}s. The biome's rules apply first, then the region's, then the dimension's; the first matching rule wins. + */ +@Desc("Deposit ore remap rules. Each entry declares a vertical band and a source->replacement block id map. Applied biome first, then region, then dimension; first matching rule wins.") +@Feature(id = "iris:deposit/variants", name = "Deposit variants", key = "depositVariants", root = "variants", + targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) +public final class DepositVariantSettings implements IrisFeature { + @Desc("Deposit ore remap rules. Each entry declares a vertical band and a source->replacement block id map. Applied biome first, then region, then dimension; first matching rule wins.") + private List variants = List.of(); + + public DepositVariantSettings() { + } + + public DepositVariantSettings(List variants) { + this.variants = List.copyOf(variants); + } + + public List variants() { + return variants == null ? List.of() : Collections.unmodifiableList(variants); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/deposit/OreFrequencySettings.java b/module/src/main/java/art/arcane/iris/modules/deposit/OreFrequencySettings.java new file mode 100644 index 000000000..8576e8f86 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/deposit/OreFrequencySettings.java @@ -0,0 +1,49 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.deposit; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** A biome's {@code oreDepositFrequencyMultiplier}, written as the bare number. */ +@Desc("Multiplier applied to the frequency of every ore deposit whose center is inside this biome. A value of 0.4 keeps 40% of ore veins while leaving non-ore deposits unchanged.") +@Feature(id = "iris:deposit/ore-frequency", name = "Ore deposit frequency", key = "oreDepositFrequencyMultiplier", root = "multiplier", targets = Level.BIOME) +public final class OreFrequencySettings implements IrisFeature { + private static final double UNCHANGED = 1D; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Multiplier applied to the frequency of every ore deposit whose center is inside this biome. A value of 0.4 keeps 40% of ore veins while leaving non-ore deposits unchanged.") + private double multiplier = UNCHANGED; + + public OreFrequencySettings() { + } + + public OreFrequencySettings(double multiplier) { + this.multiplier = multiplier; + } + + public double multiplier() { + return multiplier; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/deposit/OreSizeSettings.java b/module/src/main/java/art/arcane/iris/modules/deposit/OreSizeSettings.java new file mode 100644 index 000000000..31052380c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/deposit/OreSizeSettings.java @@ -0,0 +1,49 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.deposit; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** A biome's {@code oreDepositSizeMultiplier}, written as the bare number. */ +@Desc("Multiplier applied to the block count of every ore deposit whose center is inside this biome. Non-ore deposits are unchanged.") +@Feature(id = "iris:deposit/ore-size", name = "Ore deposit size", key = "oreDepositSizeMultiplier", root = "multiplier", targets = Level.BIOME) +public final class OreSizeSettings implements IrisFeature { + private static final double UNCHANGED = 1D; + + @MinNumber(0.01) + @MaxNumber(16) + @Desc("Multiplier applied to the block count of every ore deposit whose center is inside this biome. Non-ore deposits are unchanged.") + private double multiplier = UNCHANGED; + + public OreSizeSettings() { + } + + public OreSizeSettings(double multiplier) { + this.multiplier = multiplier; + } + + public double multiplier() { + return multiplier; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/floating/FloatingBottomPaletteMode.java b/module/src/main/java/art/arcane/iris/modules/floating/FloatingBottomPaletteMode.java new file mode 100644 index 000000000..7421080b8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/floating/FloatingBottomPaletteMode.java @@ -0,0 +1,33 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.floating; + +import com.volmit.config.Desc; + +@Desc("Controls how floating-child island underside blocks choose their palette.") +public enum FloatingBottomPaletteMode { + @Desc("Use the normal top-down biome layer depth for the whole island column.") + DEPTH, + + @Desc("Use the target biome's top palette from both the island top and underside, meeting in the middle.") + MIRROR_TOP, + + @Desc("Use bottomPalette near the underside and the target biome's normal palette near the top.") + CUSTOM +} diff --git a/module/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java b/module/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java new file mode 100644 index 000000000..a0dd2ecd4 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java @@ -0,0 +1,390 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.floating; + +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.terrain.PaletteLayer; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.ResourceRef; +import com.volmit.config.Snippet; +import com.volmit.world.PackBiome; +import com.volmit.noise.NoiseStyle; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; + +/** + * A floating island above a biome's terrain, an entry of the biome's {@code floatingChildBiomes}: where its footprint + * is, how high it floats, how its top, underside and walls are shaped, and which objects, decorators and water it + * gets. + */ +@Snippet("iris/floating/floating-child-biome") +@Desc("Declares a floating biome layer above this biome's terrain. A 2D footprint noise decides which columns are part of the island (threshold + style control blankets, swirls, scattered blobs). The top profile is driven by the target biome's own terrain generators (so a mountains biome produces real peaks, desert produces real dunes). The bottom tail hanging below is a separately configurable noise (pick VASCULAR for drippy roots, FRACTAL_RM_SIMPLEX for crystalline spikes, PERLIN for smooth rounded bowls).") +public final class FloatingChildBiome { + public static final int DEFAULT_EDGE_TAPER_WIDTH = 10; + public static final double DEFAULT_EDGE_TAPER_EXPONENT = 1.0D; + private static final NoiseStyle DEFAULT_BOTTOM_STYLE = NoiseStyle.of("SIMPLEX"); + private static final NoiseStyle DEFAULT_TOP_SHAPE_STYLE = NoiseStyle.of("SIMPLEX"); + private static final NoiseStyle DEFAULT_ALTITUDE_STYLE = NoiseStyle.of("SIMPLEX"); + private static final NoiseStyle DEFAULT_PICKER_STYLE = NoiseStyle.of("SIMPLEX"); + private static final NoiseStyle DEFAULT_EDGE_TAPER_VARIATION_STYLE = NoiseStyle.of("SIMPLEX").withZoom(0.18D); + private static final NoiseStyle DEFAULT_FOOTPRINT_STYLE = NoiseStyle.of("SIMPLEX"); + + @ResourceRef(PackBiome.class) + @Desc("The target biome whose visual design (layers, palette, decorators, surface objects, derivative, and — when topShapeMode=BIOME — generator profile) drives the floating island. Leave empty to reuse the parent biome (self).") + private String biome = ""; + + @MinNumber(1) + @MaxNumber(512) + @Desc("Selection rarity when multiple floating child entries are defined on one parent biome. Lower is more common.") + private int rarity = 1; + + @Desc("2D noise that decides which columns are part of this island. Set feature size via the style's own zoom field (e.g. {\"style\":\"CELLULAR\",\"zoom\":0.3} for ~30-block shards, {\"style\":\"SIMPLEX\",\"zoom\":1.0} for ~100-block blobs). Pick SIMPLEX for smooth blobs, CELLULAR for angular shards, VASCULAR for vein/branch strips, FRACTAL_FBM_SIMPLEX for large irregular blanket regions. Fracture (domain warp) this to get swirly silhouettes.") + private NoiseStyle footprintStyle = DEFAULT_FOOTPRINT_STYLE; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Coverage threshold (0..1). Roughly the fraction of the world that is NOT island: 0.0 = every column becomes island, 0.5 ≈ 50% of columns, 0.8 ≈ sparse scattered ~20% coverage, 1.0 = no islands at all. Values near 0.5 feel most natural.") + private double footprintThreshold = 0.5; + + @MinNumber(2) + @MaxNumber(32) + @Desc("Width in blocks of the rounded transition from the floating island contour to its full thickness. Smaller values make a tighter edge; larger values make a broader rounded underside.") + private int edgeTaperWidth = DEFAULT_EDGE_TAPER_WIDTH; + + @MinNumber(0.25) + @MaxNumber(4) + @Desc("Shape exponent for the rounded edge. Values below 1 fill into a softer, fuller curve; values above 1 keep the rim thinner before rising into the island interior.") + private double edgeTaperExponent = DEFAULT_EDGE_TAPER_EXPONENT; + + @Desc("Broad 2D noise that organically varies the rounded edge without changing the island footprint. Low-frequency SIMPLEX or PERLIN styles give coherent natural contours; high-frequency or cellular styles can look speckled.") + private NoiseStyle edgeTaperVariationStyle = DEFAULT_EDGE_TAPER_VARIATION_STYLE; + + @MinNumber(0) + @MaxNumber(8) + @Desc("Maximum number of blocks by which edgeTaperVariationStyle locally widens or narrows the rounded transition. 0 disables variation. Runtime keeps the resulting local width between 2 and 32 blocks so every protected rim column remains connected.") + private double edgeTaperVariationAmplitude = 0.0D; + + @Desc("Picker noise used when multiple floating child entries exist. Samples once per column to deterministically choose which entry's footprint is tested there. Use a large style zoom (e.g. zoom: 4 for ~400-block regions) so each entry owns broad coherent areas.") + private NoiseStyle pickerStyle = DEFAULT_PICKER_STYLE; + + @Desc("Altitude noise — varies the base platform Y across one island so it isn't a flat plane. Use a large style zoom (e.g. zoom: 2 for ~200-block altitude patches) so an island sits at roughly one altitude.") + private NoiseStyle altitudeStyle = DEFAULT_ALTITUDE_STYLE; + + @MinNumber(0) + @MaxNumber(2032) + @Desc("Minimum absolute world Y where the island base can sit. Island altitude is independent of the parent biome's terrain height; altitudeStyle noise varies the base between min and max per column.") + private int minHeightAboveSurface = 160; + + @MinNumber(0) + @MaxNumber(2032) + @Desc("Maximum absolute world Y where the island base can sit. Island altitude is independent of the parent biome's terrain height; altitudeStyle noise varies the base between min and max per column.") + private int maxHeightAboveSurface = 210; + + @Desc("Optional absolute minimum world Y for the island base. When set, baseY is clamped upward so the tail bottom stays above this value.") + private Integer minAbsoluteY = null; + + @Desc("Optional absolute maximum world Y for the island top. When set, the top is clamped downward.") + private Integer maxAbsoluteY = null; + + @Desc("How the top profile of the island is shaped. BIOME = evaluate target biome's own generators (mountains biome -> real mountains). NOISE = use topShapeStyle as a user-controlled heightmap. FLAT = constant maxTopHeight slab.") + private TopShapeMode topShapeMode = TopShapeMode.BIOME; + + @MinNumber(0) + @MaxNumber(512) + @Desc("Maximum top profile height in blocks above the island base. Caps how tall the biome terrain can grow on top.") + private int maxTopHeight = 40; + + @Desc("Used only when topShapeMode=NOISE. 2D noise driving the top heightmap. Set feature scale via the style's zoom field (small zoom = rugged peaks, large zoom = broad rolling shapes).") + private NoiseStyle topShapeStyle = DEFAULT_TOP_SHAPE_STYLE; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Amplitude multiplier applied to the NOISE top profile. 0 = no top (flat at base), 1 = full maxTopHeight range.") + private double topShapeAmp = 1.0; + + @Desc("2D noise driving the bottom tail hanging below the island base. VASCULAR = drippy organic roots. FRACTAL_RM_SIMPLEX = crystalline spikes. CELLULAR = jagged chunks. PERLIN = smooth rounded bowl. SIMPLEX = gentle lobes. Set feature scale via the style's zoom field.") + private NoiseStyle bottomStyle = DEFAULT_BOTTOM_STYLE; + + @MinNumber(0) + @MaxNumber(512) + @Desc("Minimum blocks below the base where the tail extends.") + private int bottomDepthMin = 4; + + @MinNumber(0) + @MaxNumber(512) + @Desc("Maximum blocks below the base where the tail extends.") + private int bottomDepthMax = 20; + + @MinNumber(0.1) + @MaxNumber(8) + @Desc("Power curve applied to the bottom noise before mapping to depth. >1 = most columns shallow with occasional deeper spikes (sparse roots). <1 = most columns deep with occasional shallow spots (dense curtains). 1.0 = linear.") + private double bottomExponent = 1.0; + + @Desc("Controls the material palette near the island underside. DEPTH keeps the old top-down depth behavior. MIRROR_TOP uses the target biome's shallow/top palette from the underside upward. CUSTOM uses bottomPalette near the underside while keeping the target biome palette near the top.") + private FloatingBottomPaletteMode bottomPaletteMode = FloatingBottomPaletteMode.DEPTH; + + @Desc("Custom palette layers used near the underside when bottomPaletteMode=CUSTOM. The layer format is the same as normal biome layers.") + private List bottomPalette = List.of(); + + @MinNumber(1) + @MaxNumber(512) + @Desc("Hard cap on the total Y-extent (top minus bottom) of a single island column. Safety limit.") + private int maxThickness = 96; + + @Desc("Optional 3D noise that shifts the footprint's XZ sample position per Y layer — naturalizes the walls so they stop looking like a straight extrusion of the 2D footprint. Leave null to disable and keep straight vertical walls. Good defaults: {\"style\":\"SIMPLEX\",\"zoom\":0.25} for gentle undulation, {\"style\":\"FRACTAL_FBM_SIMPLEX\",\"zoom\":0.4} for craggier walls.") + private NoiseStyle wallWarpStyle; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Amplitude in blocks of the per-layer XZ shift applied when wallWarpStyle is set. 0 = no warp (straight walls). 4..8 = gentle naturalization. 16+ = heavily meandering walls. Ignored when wallWarpStyle is null.") + private double wallWarpAmplitude = 6.0; + + @Desc("Optional 3D noise that swiss-cheeses the island interior by marking individual blocks as air when the noise exceeds carveThreshold. Leave null to keep the island solid. Good defaults: {\"style\":\"CELLULAR\",\"zoom\":0.3} for bubble pockets, {\"style\":\"VASCULAR\",\"zoom\":0.25} for wormy tunnels.") + private NoiseStyle carveStyle; + + @Desc("Optional carving biome key or dimension carving entry id whose caveProfile drives floating-island internal air pockets. Dimension carving ids resolve first; biome keys such as carving/mushroom resolve second. When set, this overrides carveStyle while carveThreshold remains a final tuning bias.") + private String carving = ""; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Threshold (0..1) above which carveStyle noise carves air pockets. 1.0 = no direct-noise carving. 0.75 = sparse pockets. 0.55 = heavy swiss-cheese. 0.4 = shredded lattice. When carving is set, lower values add a final positive threshold bias to the referenced caveProfile.") + private double carveThreshold = 1.0; + + @Desc("Optional water surface height above the island base, in blocks. null = no internal water. Positive = water fills any dip in the top profile up to baseY + localFluidHeight (forms lakes/ponds in concavities of the biome-top heightmap).") + private Integer localFluidHeight = null; + + @Desc("Block used for the internal water pool when localFluidHeight is positive.") + @Ref(Reference.BLOCK) + private String fluidBlock = "minecraft:water"; + + @Desc("When true, the target biome's decorators apply to the island's top surface.") + private boolean inheritDecorators = true; + + @Desc("When true, the target biome's surface objects are placed on the island's top surface instead of the parent terrain.") + private boolean inheritObjects = true; + + @MinNumber(0.01) + @MaxNumber(1) + @Desc("Uniform shrink factor applied to every object placed on this floating island (inherited, extra, and free-floating). 1.0 = native size, 0.5 = half size, 0.25 = quarter. Useful for making small floating biomes feel believable.") + private double objectShrinkFactor = 1.0; + + @Desc("Additional object placements anchored to the island top.") + private List extraObjects = List.of(); + + @Desc("Additional object placements that float freely in air, independent of the island. Forced to ObjectPlaceMode.FLOATING.") + private List floatingObjects = List.of(); + + @Desc("Visualization color for this floating child in Iris Studio.") + private String color = null; + + @Desc("Controls how topObjectOverrides are combined with the inherited surface objects from the target biome. INHERIT_ONLY (default) = behaves identically to before this field was added. MERGE = appends overrides after inherited objects. REPLACE = uses only overrides, ignoring all inherited objects.") + private OverrideMode topObjectMode = OverrideMode.INHERIT_ONLY; + + @Desc("Controls how bottomObjectOverrides are combined. INHERIT_ONLY (default) = no bottom objects placed (there is no inherited bottom set). MERGE = same as REPLACE for bottom (no inherited source). REPLACE = uses bottomObjectOverrides list only.") + private OverrideMode bottomObjectMode = OverrideMode.INHERIT_ONLY; + + @Desc("Object placements that override or supplement the inherited surface objects on the island TOP. Behaviour depends on topObjectMode. INHERIT_ONLY = this list is ignored. MERGE = appended after inherited. REPLACE = used instead of inherited.") + private List topObjectOverrides = List.of(); + + @Desc("Object placements anchored to the island BOTTOM face. Each entry is auto-inverted 180 degrees around the X axis and placed flush against the lowest solid face of the island, so objects appear to hang upside-down from the underside. WARNING: directional blocks (stairs, doors, slabs) will not render correctly when flipped — use non-directional content (logs, leaves, stone, mycelium, ice, glass) for bottom placements.") + private List bottomObjectOverrides = List.of(); + + public FloatingChildBiome() { + } + + public String biome() { + return biome == null ? "" : biome; + } + + public int rarity() { + return rarity; + } + + public NoiseStyle footprintStyle() { + return footprintStyle == null ? DEFAULT_FOOTPRINT_STYLE : footprintStyle; + } + + public double footprintThreshold() { + return footprintThreshold; + } + + public int edgeTaperWidth() { + return edgeTaperWidth; + } + + public double edgeTaperExponent() { + return edgeTaperExponent; + } + + public NoiseStyle edgeTaperVariationStyle() { + return edgeTaperVariationStyle == null ? DEFAULT_EDGE_TAPER_VARIATION_STYLE : edgeTaperVariationStyle; + } + + public double edgeTaperVariationAmplitude() { + return edgeTaperVariationAmplitude; + } + + public NoiseStyle pickerStyle() { + return pickerStyle == null ? DEFAULT_PICKER_STYLE : pickerStyle; + } + + public NoiseStyle altitudeStyle() { + return altitudeStyle == null ? DEFAULT_ALTITUDE_STYLE : altitudeStyle; + } + + public int minHeightAboveSurface() { + return minHeightAboveSurface; + } + + public int maxHeightAboveSurface() { + return maxHeightAboveSurface; + } + + /** Empty where the pack sets none. */ + public OptionalInt minAbsoluteY() { + return minAbsoluteY == null ? OptionalInt.empty() : OptionalInt.of(minAbsoluteY); + } + + /** Empty where the pack sets none. */ + public OptionalInt maxAbsoluteY() { + return maxAbsoluteY == null ? OptionalInt.empty() : OptionalInt.of(maxAbsoluteY); + } + + public TopShapeMode topShapeMode() { + return topShapeMode == null ? TopShapeMode.BIOME : topShapeMode; + } + + public int maxTopHeight() { + return maxTopHeight; + } + + public NoiseStyle topShapeStyle() { + return topShapeStyle == null ? DEFAULT_TOP_SHAPE_STYLE : topShapeStyle; + } + + public double topShapeAmp() { + return topShapeAmp; + } + + public NoiseStyle bottomStyle() { + return bottomStyle == null ? DEFAULT_BOTTOM_STYLE : bottomStyle; + } + + public int bottomDepthMin() { + return bottomDepthMin; + } + + public int bottomDepthMax() { + return bottomDepthMax; + } + + public double bottomExponent() { + return bottomExponent; + } + + public FloatingBottomPaletteMode bottomPaletteMode() { + return bottomPaletteMode == null ? FloatingBottomPaletteMode.DEPTH : bottomPaletteMode; + } + + public List bottomPalette() { + return bottomPalette == null ? List.of() : Collections.unmodifiableList(bottomPalette); + } + + public int maxThickness() { + return maxThickness; + } + + /** Empty where the pack sets none. */ + public Optional wallWarpStyle() { + return Optional.ofNullable(wallWarpStyle); + } + + public double wallWarpAmplitude() { + return wallWarpAmplitude; + } + + /** Empty where the pack sets none. */ + public Optional carveStyle() { + return Optional.ofNullable(carveStyle); + } + + public String carving() { + return carving == null ? "" : carving; + } + + public double carveThreshold() { + return carveThreshold; + } + + /** Empty where the pack sets none. */ + public OptionalInt localFluidHeight() { + return localFluidHeight == null ? OptionalInt.empty() : OptionalInt.of(localFluidHeight); + } + + public String fluidBlock() { + return fluidBlock == null ? "" : fluidBlock; + } + + public boolean inheritDecorators() { + return inheritDecorators; + } + + public boolean inheritObjects() { + return inheritObjects; + } + + public double objectShrinkFactor() { + return objectShrinkFactor; + } + + public List extraObjects() { + return extraObjects == null ? List.of() : Collections.unmodifiableList(extraObjects); + } + + public List floatingObjects() { + return floatingObjects == null ? List.of() : Collections.unmodifiableList(floatingObjects); + } + + public String color() { + return color == null ? "" : color; + } + + public OverrideMode topObjectMode() { + return topObjectMode == null ? OverrideMode.INHERIT_ONLY : topObjectMode; + } + + public OverrideMode bottomObjectMode() { + return bottomObjectMode == null ? OverrideMode.INHERIT_ONLY : bottomObjectMode; + } + + public List topObjectOverrides() { + return topObjectOverrides == null ? List.of() : Collections.unmodifiableList(topObjectOverrides); + } + + public List bottomObjectOverrides() { + return bottomObjectOverrides == null ? List.of() : Collections.unmodifiableList(bottomObjectOverrides); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/floating/FloatingChildSettings.java b/module/src/main/java/art/arcane/iris/modules/floating/FloatingChildSettings.java new file mode 100644 index 000000000..4d0cb58a9 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/floating/FloatingChildSettings.java @@ -0,0 +1,76 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.floating; + +import art.arcane.iris.modules.carve.CarvingSettings; +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.PackSettings; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.world.LinkedBiomes; + +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * The floating child biomes one biome declares, written as {@code "floatingChildBiomes": [...]}, the list of + * {@link FloatingChildBiome}s. The target biome of every child, and the biome its {@code carving} names, take part in the + * pack's layout like any biome a dimension reaches. + */ +@Desc("Floating child biomes that procedurally generate above this biome's terrain. Each entry references a target biome whose layers, decorators, and objects drive the floating island's visual design, while the config here drives size, shape, altitude, rarity, and water level. Multiple entries are supported and selected by rarity per column unless mergeFloatingChildBiomes is enabled.") +@Feature(id = "iris:floating/children", name = "Floating child biomes", key = "floatingChildBiomes", root = "children", targets = Level.BIOME) +public final class FloatingChildSettings implements IrisFeature, LinkedBiomes { + @Desc("Floating child biomes that procedurally generate above this biome's terrain. Each entry references a target biome whose layers, decorators, and objects drive the floating island's visual design, while the config here drives size, shape, altitude, rarity, and water level. Multiple entries are supported and selected by rarity per column unless mergeFloatingChildBiomes is enabled.") + private List children = List.of(); + + public FloatingChildSettings() { + } + + public FloatingChildSettings(List children) { + this.children = List.copyOf(children); + } + + public List children() { + return children == null ? List.of() : Collections.unmodifiableList(children); + } + + @Override + public Set usedBiomes(PackResources pack, PackSettings dimension) { + CarvingSettings carving = dimension.declared(CarvingSettings.class).dimension().orElse(null); + Set biomes = new LinkedHashSet<>(); + for (FloatingChildBiome child : children()) { + if (child != null) { + addBiome(pack, biomes, child.biome()); + addBiome(pack, biomes, carving == null ? child.carving() : carving.biomeOf(child.carving())); + } + } + return biomes; + } + + private static void addBiome(PackResources pack, Set biomes, String key) { + if (key != null && !key.isBlank()) { + biomes.add(pack.idOf(key)); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/floating/IslandAnchor.java b/module/src/main/java/art/arcane/iris/modules/floating/IslandAnchor.java new file mode 100644 index 000000000..a8f2de170 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/floating/IslandAnchor.java @@ -0,0 +1,37 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.floating; + +/** + * The face of one island an object is placed against, as {@code iris:floating} samples it: how high the face is, which + * blocks of the island are solid, and where the object may write without hanging in the air beside the island. + */ +public interface IslandAnchor { + /** The height of the face at the column; the anchor's own height where the island does not reach. */ + int faceY(int worldX, int worldZ); + + /** Whether an island lies in the column; where none does, the world's blocks say what is solid. */ + boolean hasIsland(int worldX, int worldZ); + + /** Whether the island of the column fills the block. */ + boolean islandSolid(int worldX, int y, int worldZ); + + /** Whether the object may write the block. */ + boolean writes(int worldX, int y, int worldZ); +} diff --git a/module/src/main/java/art/arcane/iris/modules/floating/IslandFootprint.java b/module/src/main/java/art/arcane/iris/modules/floating/IslandFootprint.java new file mode 100644 index 000000000..de9b8133e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/floating/IslandFootprint.java @@ -0,0 +1,38 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.floating; + +/** + * Where an object stands, in its own block positions: the columns holding a solid block ({@link #column} packs each), the + * tallest of them (most solid blocks, the lowest bottom on a tie) and the lowest solid block of that column. + */ +public record IslandFootprint(int tallestX, int tallestZ, int lowestSolidY, long[] columns) { + /** The column {@code x}, {@code z} packed as {@link #columns} holds it. */ + public static long column(int x, int z) { + return ((long) x << 32) | (z & 0xFFFFFFFFL); + } + + public static int columnX(long column) { + return (int) (column >> 32); + } + + public static int columnZ(long column) { + return (int) (column & 0xFFFFFFFFL); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/floating/MergeFloatingChildrenSettings.java b/module/src/main/java/art/arcane/iris/modules/floating/MergeFloatingChildrenSettings.java new file mode 100644 index 000000000..3a6e030c8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/floating/MergeFloatingChildrenSettings.java @@ -0,0 +1,43 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.floating; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** A biome's {@code mergeFloatingChildBiomes}, written as the bare boolean. */ +@Desc("When true, every floating child entry is sampled independently and their solid masks are unioned, so multiple floating islands can stack, overlap, and collide instead of the picker choosing only one child per column.") +@Feature(id = "iris:floating/merge", name = "Merge floating child biomes", key = "mergeFloatingChildBiomes", root = "merge", targets = Level.BIOME) +public final class MergeFloatingChildrenSettings implements IrisFeature { + @Desc("When true, every floating child entry is sampled independently and their solid masks are unioned, so multiple floating islands can stack, overlap, and collide instead of the picker choosing only one child per column.") + private boolean merge = false; + + public MergeFloatingChildrenSettings() { + } + + public MergeFloatingChildrenSettings(boolean merge) { + this.merge = merge; + } + + public boolean merge() { + return merge; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/floating/OverrideMode.java b/module/src/main/java/art/arcane/iris/modules/floating/OverrideMode.java new file mode 100644 index 000000000..b308bc1e6 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/floating/OverrideMode.java @@ -0,0 +1,33 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.floating; + +import com.volmit.config.Desc; + +@Desc("Controls how an override list is combined with the inherited object set from the target biome.") +public enum OverrideMode { + @Desc("Ignore the override list entirely. Use only the inherited objects from the target biome (subject to inheritObjects).") + INHERIT_ONLY, + + @Desc("Append override list entries after the inherited objects from the target biome. Both sets are placed.") + MERGE, + + @Desc("Use only the override list. The inherited objects from the target biome are discarded regardless of inheritObjects.") + REPLACE +} diff --git a/module/src/main/java/art/arcane/iris/modules/floating/TopShapeMode.java b/module/src/main/java/art/arcane/iris/modules/floating/TopShapeMode.java new file mode 100644 index 000000000..0a0be2832 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/floating/TopShapeMode.java @@ -0,0 +1,33 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.floating; + +import com.volmit.config.Desc; + +@Desc("How the top profile of a floating-child island is shaped.") +public enum TopShapeMode { + @Desc("Evaluate the target biome's own terrain generators to build the island top. Mountains biome produces real peaks, desert produces dunes, plains is flat. Recommended default.") + BIOME, + + @Desc("Drive the top profile from topShapeStyle noise, independent of the target biome's generators. Amplitude controlled by topShapeAmp.") + NOISE, + + @Desc("Flat slab on top, topHeight blocks above the base. Ignores noise and biome generators.") + FLAT +} diff --git a/module/src/main/java/art/arcane/iris/modules/loot/BlockDrop.java b/module/src/main/java/art/arcane/iris/modules/loot/BlockDrop.java new file mode 100644 index 000000000..7555c1477 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/loot/BlockDrop.java @@ -0,0 +1,71 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.loot; + +import art.arcane.iris.builtin.loot.LootEntry; +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +@Snippet("iris/loot/block-drops") +@Desc("Represents a block drop list") +public final class BlockDrop { + @Required + @Desc("The blocks that drop loot") + private List blocks = List.of(); + + @Desc("If exact blocks is set to true, minecraft:barrel[axis=x] will only drop for that axis. When exact is false (default) any barrel will drop the defined drops.") + private boolean exactBlocks = false; + + @Desc("Add in specific items to drop") + private List drops = List.of(); + + @Desc("If this is in a biome, setting skipParents to true will ignore the drops in the region and dimension for this block type. The default (false) will allow all three nodes to fire and add to a list of drops.") + private boolean skipParents = false; + + @Desc("Removes the default vanilla block drops and only drops the given items & any parent loot tables specified for this block type.") + private boolean replaceVanillaDrops = false; + + public BlockDrop() { + } + + public List blocks() { + return blocks == null ? List.of() : Collections.unmodifiableList(blocks); + } + + public boolean exactBlocks() { + return exactBlocks; + } + + public List drops() { + return drops == null ? List.of() : Collections.unmodifiableList(drops); + } + + public boolean skipParents() { + return skipParents; + } + + public boolean replaceVanillaDrops() { + return replaceVanillaDrops; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/loot/BlockDropSettings.java b/module/src/main/java/art/arcane/iris/modules/loot/BlockDropSettings.java new file mode 100644 index 000000000..d8bff017b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/loot/BlockDropSettings.java @@ -0,0 +1,46 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.loot; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.Collections; +import java.util.List; + +/** + * The block drops one dimension, region or biome declares, written as {@code "blockDrops": [...]}, the list of + * {@link BlockDrop}s. A broken block drops those of its biome, then, unless one of them skips its parents, those of its + * region and dimension. + */ +@Desc("Define custom block drops for this area") +@Feature(id = "iris:loot/drops", name = "Block drops", key = "blockDrops", root = "drops", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) +public final class BlockDropSettings implements IrisFeature { + @Desc("Define custom block drops for this area") + private List drops = List.of(); + + public BlockDropSettings() { + } + + public List drops() { + return drops == null ? List.of() : Collections.unmodifiableList(drops); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/CarvedSpace.java b/module/src/main/java/art/arcane/iris/modules/objects/CarvedSpace.java new file mode 100644 index 000000000..286f6c075 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/CarvedSpace.java @@ -0,0 +1,64 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import com.volmit.geometry.BlockBox; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; + +import java.util.Optional; + +/** + * The voids the cave carver planned in the mantle around the chunk being placed, which cave objects anchor in. Heights + * are above the dimension's bottom; outside the mantle the invocation reaches nothing is carved. + */ +public final class CarvedSpace { + private final MantleLayer voids; + private final BlockBox reach; + + public CarvedSpace(MantleLayer voids, BlockBox reach) { + this.voids = voids; + this.reach = reach; + } + + /** Whether the position is carved. */ + public boolean isCarved(int x, int y, int z) { + return voidAt(x, y, z).isPresent(); + } + + /** Whether each height from 0 up to {@code height} is carved at the column, 1 for carved and 0 for not. */ + public byte[] column(int x, int z, int height) { + int cappedHeight = Math.min(Math.max(height, 0), reach.maxY()); + byte[] carvedColumn = new byte[cappedHeight]; + for (int y = 0; y < cappedHeight; y++) { + if (reach.contains(x, y, z) && voids.get(x, y, z) != null) { + carvedColumn[y] = 1; + } + } + return carvedColumn; + } + + /** The void at the position; empty where nothing was carved. */ + public Optional voidAt(int x, int y, int z) { + if (!reach.contains(x, y, z)) { + return Optional.empty(); + } + return Optional.ofNullable(voids.get(x, y, z)); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/CavePlacement.java b/module/src/main/java/art/arcane/iris/modules/objects/CavePlacement.java new file mode 100644 index 000000000..bf86622e7 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/CavePlacement.java @@ -0,0 +1,32 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +/** + * The outcome of placing an object in a cave. + * + * @param resultY the height the object was placed at, negative when the placement rejected it + * @param commit what became of the blocks the object wrote; {@link TerrainTransaction.Commit#EMPTY} for a rejected + * placement, {@link TerrainTransaction.Commit#REJECTED} when some block lay outside the cave + */ +public record CavePlacement(int resultY, TerrainTransaction.Commit commit) { + public boolean wroteBlocks() { + return commit == TerrainTransaction.Commit.COMMITTED; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/CaveTransaction.java b/module/src/main/java/art/arcane/iris/modules/objects/CaveTransaction.java new file mode 100644 index 000000000..e1c569a2a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/CaveTransaction.java @@ -0,0 +1,86 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import art.arcane.volmlib.util.cache.CacheKey; +import com.volmit.placement.PlacementTerrain; + +import java.util.HashMap; +import java.util.Map; + +/** + * Holds back what a cave object writes until all of it is known to lie inside the cave: in the world, no shallower than + * the burial depth under the surface and under the cave's ceiling at its column. + */ +public final class CaveTransaction extends TerrainTransaction { + private final int worldHeight; + private final int anchorY; + private final int minDepthBelowSurface; + private final Map surfaceHeights = new HashMap<>(); + private final Map caveCeilings = new HashMap<>(); + + /** @param worldHeight the dimension's height in blocks */ + public CaveTransaction(PlacementTerrain delegate, int worldHeight, int anchorY, int minDepthBelowSurface) { + super(delegate); + this.worldHeight = worldHeight; + this.anchorY = anchorY; + this.minDepthBelowSurface = Math.max(0, minDepthBelowSurface); + } + + /** The first height above the anchor that the cave does not reach at the column. */ + public int caveCeiling(int x, int z) { + return caveCeilings.computeIfAbsent(CacheKey.key(x, z), ignored -> findCaveCeiling(x, z)); + } + + /** The highest height an object buried {@code minDepthBelowSurface} under {@code surfaceY} may reach. */ + public static int maxBuriedY(int worldHeight, int surfaceY, int minDepthBelowSurface) { + return Math.min(worldHeight - 1, surfaceY - Math.max(0, minDepthBelowSurface)); + } + + @Override + protected boolean accepts(int x, int y, int z) { + if (y < 0 || y >= worldHeight) { + return false; + } + if (y > maxBuriedY(worldHeight, surfaceHeight(x, z), minDepthBelowSurface)) { + return false; + } + return y < caveCeiling(x, z); + } + + private int surfaceHeight(int x, int z) { + return surfaceHeights.computeIfAbsent(CacheKey.key(x, z), ignored -> delegate().highest(x, z, true)); + } + + private int findCaveCeiling(int x, int z) { + if (worldHeight <= 0 || anchorY < 0 || anchorY >= worldHeight) { + return 0; + } + if (!delegate().isCarved(x, anchorY, z)) { + return Math.min(worldHeight, anchorY + 1); + } + int scanLimit = Math.min(worldHeight - 1, Math.max(anchorY, surfaceHeight(x, z))); + for (int y = anchorY + 1; y <= scanLimit; y++) { + if (!delegate().isCarved(x, y, z)) { + return y; + } + } + return Math.min(worldHeight, scanLimit + 1); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/Declaration.java b/module/src/main/java/art/arcane/iris/modules/objects/Declaration.java new file mode 100644 index 000000000..73ae17e85 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/Declaration.java @@ -0,0 +1,53 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.List; + +/** + * One region's or biome's declaration of settings, named by the id a {@link com.volmit.world.BiomeSample} gives the + * region or biome ({@code overworld:desert/dunes}) rather than the source id of its settings entry + * ({@code overworld:biome/desert/dunes}). + */ +public record Declaration(Level level, ResourceId id, F settings) { + private static final char KIND_SEPARATOR = '/'; + + /** Every region and every reachable biome of {@code world}'s dimension that declares the settings, regions first. */ + public static List> allOf(PackWorld world, Class type) { + List> found = new ArrayList<>(); + for (Entry entry : world.settings().declared(type)) { + if (entry.level() == Level.REGION || entry.level() == Level.BIOME) { + found.add(new Declaration<>(entry.level(), sampleId(entry.source()), entry.value())); + } + } + return found; + } + + private static ResourceId sampleId(ResourceId source) { + String path = source.path(); + return new ResourceId(source.namespace(), path.substring(path.indexOf(KIND_SEPARATOR) + 1)); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/EffectiveSettings.java b/module/src/main/java/art/arcane/iris/modules/objects/EffectiveSettings.java new file mode 100644 index 000000000..68cb05bda --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/EffectiveSettings.java @@ -0,0 +1,69 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.prepare.AxisRotationClamp; +import art.arcane.iris.builtin.prepare.ObjectRotation; + +/** The object placement settings a placement is made with: its own, with the changes {@code iris:objects} makes for where it places them. */ +public final class EffectiveSettings { + private static final double UPSIDE_DOWN_TURN_DEGREES = 180D; + private static final double QUARTER_TURN_DEGREES = 90D; + + private EffectiveSettings() { + } + + /** {@code base} with {@code changes} made to a copy of it; {@code base} itself when there are none. */ + public static ObjectPlacement withChanges(ObjectPlacement base, PlacementChanges changes) { + if (changes.isNone()) { + return base; + } + ObjectPlacement.Builder changed = base.toBuilder(); + if (changes.place() != null) { + changed.place(changes.place()); + } + if (changes.mode() != null) { + changed.mode(changes.mode()); + } + if (changes.upsideDown() != null && changes.upsideDown()) { + changed.rotation(upsideDownRotation()); + } + if (changes.carvingSupport() != null) { + changed.carvingSupport(changes.carvingSupport()); + } + if (changes.requireSurfaceSupport() != null) { + changed.requireSurfaceSupport(changes.requireSurfaceSupport()); + } + if (changes.surfaceSupportBuffer() != null) { + changed.surfaceSupportBuffer(changes.surfaceSupportBuffer()); + } + if (changes.forcePlace() != null) { + changed.forcePlace(changes.forcePlace()); + } + return changed.build(); + } + + private static ObjectRotation upsideDownRotation() { + return ObjectRotation.of(true, + AxisRotationClamp.of(true, true, UPSIDE_DOWN_TURN_DEGREES, UPSIDE_DOWN_TURN_DEGREES, QUARTER_TURN_DEGREES), + AxisRotationClamp.of(true, false, 0D, 0D, QUARTER_TURN_DEGREES), + new AxisRotationClamp()); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java b/module/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java new file mode 100644 index 000000000..b3b5866ab --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java @@ -0,0 +1,107 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import com.volmit.block.BlockState; +import com.volmit.object.BlockEntityData; +import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementRecord; +import com.volmit.placement.PlacementTerrain; +import com.volmit.placement.StructureVolumes; + +import java.util.Objects; +import java.util.Optional; + +/** A terrain that answers everything as another does; subclasses change what they need. */ +public abstract class ForwardingTerrain implements PlacementTerrain { + private final PlacementTerrain delegate; + + protected ForwardingTerrain(PlacementTerrain delegate) { + this.delegate = Objects.requireNonNull(delegate, "delegate"); + } + + protected final PlacementTerrain delegate() { + return delegate; + } + + @Override + public int highest(int x, int z, boolean ignoreFluid) { + return delegate.highest(x, z, ignoreFluid); + } + + @Override + public BlockState get(int x, int y, int z) { + return delegate.get(x, y, z); + } + + @Override + public void set(int x, int y, int z, BlockState state) { + delegate.set(x, y, z, state); + } + + @Override + public void set(int x, int y, int z, BlockState state, BlockEntityData blockEntity) { + delegate.set(x, y, z, state, blockEntity); + } + + @Override + public boolean isCarved(int x, int y, int z) { + return delegate.isCarved(x, y, z); + } + + @Override + public boolean isSurfaceSolid(int x, int y, int z) { + return delegate.isSurfaceSolid(x, y, z); + } + + @Override + public boolean isUnderwater(int x, int z) { + return delegate.isUnderwater(x, z); + } + + @Override + public int fluidHeight() { + return delegate.fluidHeight(); + } + + @Override + public boolean preventsDecay() { + return delegate.preventsDecay(); + } + + @Override + public void recordPlacement(int x, int y, int z, PlacementRecord placement) { + delegate.recordPlacement(x, y, z, placement); + } + + @Override + public Optional placementAt(int x, int y, int z) { + return delegate.placementAt(x, y, z); + } + + @Override + public StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ) { + return delegate.structureVolumes(minX, minZ, maxX, maxZ); + } + + @Override + public void mark(PlacedMarker marker) { + delegate.mark(marker); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/ObjectBuilder.java b/module/src/main/java/art/arcane/iris/modules/objects/ObjectBuilder.java new file mode 100644 index 000000000..f110747f8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/ObjectBuilder.java @@ -0,0 +1,69 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.block.PaletteSpec; +import com.volmit.object.ObjectBlock; +import com.volmit.object.PackObjects; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; + +import java.util.List; + +/** + * Builds objects block by block for the procedural objects, with blocks as the platform has them: the registry keeps a + * content plugin's block itself when a property is set on it or the object is built ({@link BlockRegistry}). + */ +public final class ObjectBuilder { + private final BlockRegistry blocks; + private final PackObjects objects; + + public ObjectBuilder(PackResources resources) { + this.blocks = resources.blocks(); + this.objects = resources.objects(); + } + + /** The platform's state for {@code key}; null when the platform has no such block. */ + public BlockState block(String key) { + return blocks.find(key).orElse(null); + } + + /** The block {@code palette} gives at the position when its noise is seeded with {@code seed}. */ + public BlockState pick(PaletteSpec palette, long seed, int x, int y, int z) { + return blocks.palette(palette, seed).at(x, y, z); + } + + /** Whether the platform gives {@code state} the trait, such as a log or air. */ + public boolean has(BlockState state, BlockTrait trait) { + return blocks.hasTrait(state, trait); + } + + /** {@code state} with the property set, as the platform sets it; {@code state} itself when the block does not accept it. */ + public BlockState withPropertyIfAccepted(BlockState state, String name, String value) { + return blocks.withPropertyIfAccepted(state, name, value); + } + + /** The object of {@code blocks}, put in their order, {@code width} by {@code height} by {@code depth}, placeable like the pack's objects. */ + public PlaceableObject build(String name, int width, int height, int depth, List blocks) { + return objects.build(name, width, height, depth, blocks); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/ObjectPool.java b/module/src/main/java/art/arcane/iris/modules/objects/ObjectPool.java new file mode 100644 index 000000000..36cd79883 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/ObjectPool.java @@ -0,0 +1,153 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectScale; +import art.arcane.iris.builtin.objects.ScaleInterpolation; +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; +import art.arcane.volmlib.util.cache.CacheKey; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.noise.StyledRange; +import com.volmit.object.PackObjects; +import com.volmit.object.PlaceableObject; +import com.volmit.object.ScaleMethod; +import com.volmit.random.WorldRandom; +import com.volmit.resource.PackResources; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Optional; + +/** + * The pack's objects as object placements pick them: by key, scaled the way a placement scales them, and as many at a + * column as its density says, drawn from random streams and noise seeded by the world. + */ +public final class ObjectPool { + private static final double NO_SCALE = 1D; + private static final int MAX_SCALE_VARIANTS = 32; + + private final PackResources resources; + private final long chunkSeed; + private final long densitySeed; + private final ProceduralObjectCatalog procedural; + + private ObjectPool(PackResources resources, long chunkSeed, long densitySeed, ProceduralObjectCatalog procedural) { + this.resources = resources; + this.chunkSeed = chunkSeed; + this.densitySeed = densitySeed; + this.procedural = procedural; + } + + /** The objects of {@code world}'s pack, its procedural objects among them. */ + public static ObjectPool of(PackWorld world) { + return new ObjectPool(world.resources(), world.seed(IrisSeedPurposes.OBJECT_CHUNK), + world.seed(IrisSeedPurposes.OBJECT_DENSITY), ProceduralObjectCatalog.of(world)); + } + + /** The random a chunk's objects are placed with: the same for the same chunk of the same world. */ + public RNG chunkRandom(int chunkX, int chunkZ) { + return new RNG(new WorldRandom(chunkSeed + CacheKey.key(chunkX, chunkZ)).nextLong()); + } + + /** The pack object {@code key} names; for a procedural pool, the variant {@code rng} picks. */ + public Optional object(String key, RNG rng) { + if (ProceduralObjectCatalog.isProceduralKey(key)) { + return procedural.object(key, rng); + } + return objects().object(resources.idOf(key)); + } + + /** An object of the placement, picked with {@code rng} and scaled the way the placement scales it; empty when it has none. */ + public Optional pickScaled(ObjectPlacement placement, RNG rng) { + List keys = placement.place(); + if (keys.isEmpty()) { + return Optional.empty(); + } + return object(keys.get(rng.nextInt(keys.size())), rng).map(origin -> scaled(origin, placement.scale(), rng)); + } + + /** {@code origin} shrunk or grown by exactly {@code factor}, without filling between its blocks. */ + public PlaceableObject resized(PlaceableObject origin, double factor) { + return factor == NO_SCALE ? origin : objects().scaled(origin, factor, ScaleMethod.NONE); + } + + /** How many objects the placement places at the column, when its chance check passes: its fixed density, or what its density style gives there. */ + public int density(ObjectPlacement placement, double x, double z) { + Optional densityStyle = placement.densityStyle(); + if (densityStyle.isEmpty()) { + return placement.density(); + } + return (int) Math.round(densityStyle.get().at(resources.noise(), densitySeed, x, z)); + } + + /** Builds the noise the placement draws its density from and bakes its procedural objects, so the first chunk to place it does not wait. */ + public void warm(ObjectPlacement placement) { + density(placement, 0, 0); + placement.place().stream().filter(ProceduralObjectCatalog::isProceduralKey).forEach(procedural::placeable); + } + + private PlaceableObject scaled(PlaceableObject origin, ObjectScale scale, RNG rng) { + if (!shouldScale(scale)) { + return origin; + } + int variants = variantCount(scale); + int variant = variants == 1 ? 0 : rng.nextInt(variants); + return objects().scaled(origin, scaleAt(scale, variant, variants), methodOf(scale.interpolation())); + } + + private PackObjects objects() { + return resources.objects(); + } + + private static boolean shouldScale(ObjectScale scale) { + if (scale.size() != NO_SCALE) { + return true; + } + return scale.variations() > 0 && (scale.minimumScale() != NO_SCALE || scale.maximumScale() != NO_SCALE); + } + + /** How many evenly spread factors the scale picks from. */ + private static int variantCount(ObjectScale scale) { + if (scale.size() != NO_SCALE || scale.minimumScale() == scale.maximumScale()) { + return 1; + } + return Math.max(1, Math.min(scale.variations(), MAX_SCALE_VARIANTS)); + } + + private static double scaleAt(ObjectScale scale, int variant, int variants) { + if (scale.size() != NO_SCALE) { + return scale.size(); + } + if (scale.minimumScale() == scale.maximumScale()) { + return scale.minimumScale(); + } + return scale.minimumScale() + (((scale.maximumScale() - scale.minimumScale()) / variants) * variant); + } + + private static ScaleMethod methodOf(ScaleInterpolation interpolation) { + return switch (interpolation) { + case NONE -> ScaleMethod.NONE; + case TRILINEAR -> ScaleMethod.TRILINEAR; + case TRICUBIC -> ScaleMethod.TRICUBIC; + case TRIHERMITE -> ScaleMethod.TRIHERMITE; + }; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/ObjectSeparation.java b/module/src/main/java/art/arcane/iris/modules/objects/ObjectSeparation.java new file mode 100644 index 000000000..b3c130ea0 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/ObjectSeparation.java @@ -0,0 +1,140 @@ +package art.arcane.iris.modules.objects; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.config.FeatureSettings; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The chance and spacing of surface object placements in a world. + * + *

A separated placement rolls one candidate spot per chunk. The candidate stands only when no candidate of a lower rank, + * from a placement with the same objects, lies closer than the separation. Spots and ranks come from the world seed, the + * chunk and the objects alone, so every chunk agrees on them across chunk, biome and region borders, and objects never + * stand closer than the separation, whatever order chunks generate in. + */ +public final class ObjectSeparation { + private static final int CHUNK_WIDTH_BLOCKS = 16; + private static final int CHUNK_SHIFT = 4; + /** Placements read a chunk's settings at local 8, 8, as Iris always did. */ + private static final int SETTINGS_COLUMN_OFFSET_BLOCKS = 8; + /** A chunk places the biome's objects before the region's, so the biome's placement speaks for the chunk. */ + private static final List PLACING_LEVELS = List.of(Level.BIOME, Level.REGION); + + private final PackWorld world; + private final long seed; + private final Map chanceNoises = new ConcurrentHashMap<>(); + + private ObjectSeparation(PackWorld world) { + this.world = world; + this.seed = world.seed(IrisSeedPurposes.OBJECT_SEPARATION); + } + + /** The separation of {@code world}. */ + public static ObjectSeparation of(PackWorld world) { + return world.state(ObjectSeparation.class, ObjectSeparation::new); + } + + /** The chance to place at the block column: the placement's chance, multiplied by its chance noise when it has one. */ + public double chanceAt(ObjectPlacement placement, double x, double z) { + Optional style = placement.chanceStyle(); + if (style.isEmpty()) { + return placement.chance(); + } + double noise = chanceNoises.computeIfAbsent(style.get(), declared -> world.resources().noise().sampler(declared, seed)).sample(x, z); + return placement.chance() * Math.max(0D, Math.min(1D, noise)); + } + + /** + * The candidate the chunk places for the separated placement; empty when it rolled none or a lower ranked one is too + * close. {@code settings} tells which placements the neighbouring chunks declare. + */ + public Optional keptCandidate(int chunkX, int chunkZ, ObjectPlacement placement, FeatureSettings settings) { + Optional own = candidateOf(chunkX, chunkZ, placement); + if (own.isEmpty() || isOutranked(own.get(), chunkX, chunkZ, placement, settings)) { + return Optional.empty(); + } + return own; + } + + private boolean isOutranked(Candidate own, int chunkX, int chunkZ, ObjectPlacement placement, FeatureSettings settings) { + int reach = placement.separation(); + for (int x = Math.floorDiv(own.x() - reach, CHUNK_WIDTH_BLOCKS); x <= Math.floorDiv(own.x() + reach, CHUNK_WIDTH_BLOCKS); x++) { + for (int z = Math.floorDiv(own.z() - reach, CHUNK_WIDTH_BLOCKS); z <= Math.floorDiv(own.z() + reach, CHUNK_WIDTH_BLOCKS); z++) { + if (x == chunkX && z == chunkZ) { + continue; + } + int rivalX = x; + int rivalZ = z; + Optional rival = placementOfSameObjectsAt(rivalX, rivalZ, placement.place(), settings) + .flatMap(other -> candidateOf(rivalX, rivalZ, other)); + if (rival.isPresent() && rival.get().rank() < own.rank() && rival.get().isCloserThan(own, reach)) { + return true; + } + } + } + return false; + } + + private static Optional placementOfSameObjectsAt(int chunkX, int chunkZ, List objects, FeatureSettings settings) { + int x = (chunkX << CHUNK_SHIFT) + SETTINGS_COLUMN_OFFSET_BLOCKS; + int z = (chunkZ << CHUNK_SHIFT) + SETTINGS_COLUMN_OFFSET_BLOCKS; + SettingsStack declared = settings.at(ObjectSettings.class, x, z); + for (Level level : PLACING_LEVELS) { + Optional placing = declared.level(level).flatMap(placements -> separatedPlacing(placements, objects)); + if (placing.isPresent()) { + return placing; + } + } + return Optional.empty(); + } + + private static Optional separatedPlacing(ObjectSettings settings, List objects) { + return settings.objects().stream() + .filter(placement -> placement.isSeparated() && placement.carvingSupport().supportsSurface() && placement.place().equals(objects)) + .findFirst(); + } + + private Optional candidateOf(int chunkX, int chunkZ, ObjectPlacement placement) { + RNG rng = new RNG(chunkSeed(chunkX, chunkZ, placement.place().hashCode())); + int x = (chunkX << CHUNK_SHIFT) + rng.nextInt(CHUNK_WIDTH_BLOCKS); + int z = (chunkZ << CHUNK_SHIFT) + rng.nextInt(CHUNK_WIDTH_BLOCKS); + if (!rng.chance(chanceAt(placement, x, z))) { + return Optional.empty(); + } + return Optional.of(new Candidate(x, z, rng.nextLong(), rng)); + } + + // Each input is mixed in after the previous one: XORing scaled coordinates gave chunk x,z and -x,-z the same seed + // whenever both were odd. + private long chunkSeed(int chunkX, int chunkZ, int objectsHash) { + return splitMix(splitMix(splitMix(seed + objectsHash) + chunkX) + chunkZ); + } + + private static long splitMix(long value) { + long mixed = value + 0x9E3779B97F4A7C15L; + mixed = (mixed ^ (mixed >>> 30)) * 0xBF58476D1CE4E5B9L; + mixed = (mixed ^ (mixed >>> 27)) * 0x94D049BB133111EBL; + return mixed ^ (mixed >>> 31); + } + + /** Where a chunk would place, in block coordinates, with the random that picks and places the object there. */ + public record Candidate(int x, int z, long rank, RNG rng) { + boolean isCloserThan(Candidate other, int blocks) { + long dx = x - other.x; + long dz = z - other.z; + return dx * dx + dz * dz < (long) blocks * blocks; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/ObjectSize.java b/module/src/main/java/art/arcane/iris/modules/objects/ObjectSize.java new file mode 100644 index 000000000..178479646 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/ObjectSize.java @@ -0,0 +1,23 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +/** The size of an object, in blocks. */ +public record ObjectSize(int width, int height, int depth) { +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java b/module/src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java new file mode 100644 index 000000000..75a26153e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java @@ -0,0 +1,73 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import com.volmit.object.GeneratedObject; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.SceneEntry; +import com.volmit.tooling.SceneView; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Optional; + +/** The studio's Objects view: every object in the pack, one scene each, listed under the folders of its file. */ +public final class PackObjectScenes implements SceneView { + private static final ResourceId ID = ResourceId.parse("iris:objects"); + private static final char FOLDER_SEPARATOR = '/'; + + @Override + public ResourceId id() { + return ID; + } + + @Override + public String label() { + return "Objects"; + } + + @Override + public String description() { + return "Every object in the pack in 3D, with the blocks it is made of"; + } + + @Override + public List entries(PackWorld world) { + return world.resources().ids(PackResources.OBJECTS).stream() + .map(id -> entryOf(id.path())) + .toList(); + } + + @Override + public Optional scene(PackWorld world, String key, int variant) { + if (variant != 0) { + return Optional.empty(); + } + PackResources resources = world.resources(); + return resources.objects().object(resources.idOf(key)).map(PlaceableObject::geometry); + } + + private static SceneEntry entryOf(String key) { + int lastSeparator = key.lastIndexOf(FOLDER_SEPARATOR); + Optional folder = lastSeparator < 0 ? Optional.empty() : Optional.of(key.substring(0, lastSeparator)); + return new SceneEntry(key, key.substring(lastSeparator + 1), folder, 1); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/PlacementChanges.java b/module/src/main/java/art/arcane/iris/modules/objects/PlacementChanges.java new file mode 100644 index 000000000..a6c098223 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/PlacementChanges.java @@ -0,0 +1,69 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; + +import java.util.List; + +/** + * How a placement differs from the settings it was read from, when {@code iris:objects} places it: a field that is + * null is left as the settings have it. + * + * @param place the objects the placement names, replacing the settings' + * @param mode the place mode + * @param upsideDown whether the object is turned over, for the objects hung from the terrain stacked above + * @param carvingSupport where the placement may place + * @param requireSurfaceSupport whether a surface placement needs solid ground under it + * @param surfaceSupportBuffer the buffer of solid ground around the object's base + * @param forcePlace whether the placement ignores the placement restrictions + */ +public record PlacementChanges(List place, ObjectPlaceMode mode, Boolean upsideDown, CarvingMode carvingSupport, + Boolean requireSurfaceSupport, Integer surfaceSupportBuffer, Boolean forcePlace) { + public static final PlacementChanges NONE = new PlacementChanges(null, null, null, null, null, null, null); + + public boolean isNone() { + return this.equals(NONE); + } + + public PlacementChanges withPlace(List place) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } + + public PlacementChanges withMode(ObjectPlaceMode mode) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } + + public PlacementChanges withUpsideDown(boolean upsideDown) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } + + public PlacementChanges withCarvingSupport(CarvingMode carvingSupport) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } + + public PlacementChanges withSurfaceSupport(boolean required, int buffer) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, required, buffer, forcePlace); + } + + public PlacementChanges withForcePlace(boolean forcePlace) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/PlacementTags.java b/module/src/main/java/art/arcane/iris/modules/objects/PlacementTags.java new file mode 100644 index 000000000..71ab580e1 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/PlacementTags.java @@ -0,0 +1,31 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import com.volmit.placement.PlacementRecord; + +/** + * What a placement writes into the mantle besides the blocks, beside each block of the object. + * + * @param marker the placement to record beside every block the object places, or null for none + * @param treeMaterial whether the block is also written as the tree material the mantle keeps for felling and growth + * @param buriedTreasure whether storage chests among the blocks are marked as buried treasure + */ +public record PlacementTags(PlacementRecord marker, boolean treeMaterial, boolean buriedTreasure) { +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectGraph.java b/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectGraph.java new file mode 100644 index 000000000..a19dbad91 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectGraph.java @@ -0,0 +1,252 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import art.arcane.iris.engine.procedural.part.PartBlob; +import art.arcane.iris.engine.procedural.part.PartBranches; +import art.arcane.iris.engine.procedural.part.PartCluster; +import art.arcane.iris.engine.procedural.part.PartOutline; +import art.arcane.iris.engine.procedural.part.PartStem; +import art.arcane.iris.engine.procedural.part.ProceduralDecoration; +import art.arcane.iris.engine.procedural.part.ProceduralMaterial; +import art.arcane.iris.engine.procedural.part.ProceduralObject; +import art.arcane.iris.engine.procedural.part.ProceduralPart; +import com.volmit.tooling.GraphNode; +import com.volmit.tooling.GraphNode.Addition; +import com.volmit.tooling.GraphNode.Edits; +import com.volmit.tooling.GraphNode.Link; +import com.volmit.tooling.GraphNode.NodeSettings; +import com.volmit.tooling.JsonPath; +import com.volmit.tooling.JsonText; +import com.volmit.tooling.NodeGraph; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; +import java.util.Set; +import java.util.stream.Stream; + +/** + * A procedural object's file as nodes: the object, the parts growing from it, its materials and its decorations (v3e's + * node editor). Each part node is the part of the baked object it draws, so the studio can pick one from the other. + */ +final class ProceduralObjectGraph { + private static final String PARTS = "parts"; + private static final String CHILDREN = "children"; + private static final String COPIED_PART = "part"; + private static final String MATERIALS = "materials"; + private static final String DECORATIONS = "decorations"; + private static final String ROLE = "role"; + private static final String DECORATED_ROLES = "on"; + private static final String DEFAULT_MATERIAL_ROLE = "main"; + private static final String EACH_COPY = "each copy"; + private static final String GROWS = ""; + private static final Set OBJECT_NODES = Set.of(MATERIALS, PARTS, DECORATIONS); + private static final Set PART_NODES = Set.of(Shape.STEM.key, Shape.BLOB.key, Shape.BRANCHES.key, Shape.CLUSTER.key, CHILDREN); + private static final Set COPY_NODES = Set.of(COPIED_PART); + private static final Set NO_NODES = Set.of(); + + private final JsonText source; + private final PartOutline outline; + + private ProceduralObjectGraph(JsonText source, PartOutline outline) { + this.source = source; + this.outline = outline; + } + + /** + * @param read what the pack read from the file, so its parts line up with the file's; it may be older than + * {@code source}, and parts past what it read get no part id + * @throws IllegalArgumentException when the file does not hold an object + */ + static NodeGraph of(String name, JsonText source, ProceduralObject read) { + if (!(source.root() instanceof JsonText.Obj root)) { + throw new IllegalArgumentException("The file does not hold an object"); + } + return new ProceduralObjectGraph(source, PartOutline.of(read)).graph(name, root, read); + } + + private NodeGraph graph(String name, JsonText.Obj root, ProceduralObject read) { + JsonPath parts = JsonPath.ROOT.member(PARTS); + GraphNode object = new GraphNode("Object", name, JsonPath.ROOT, OptionalInt.empty(), List.of(), + List.of(new NodeSettings("Object", JsonPath.ROOT, ProceduralObject.class, OBJECT_NODES)), + parts(parts, root.get(PARTS), read.parts(), read.defaultRole()), + new Edits(Optional.of(parts), false, objectAdditions(parts))); + List roots = new ArrayList<>(); + roots.add(object); + roots.addAll(listed(MATERIALS, root.get(MATERIALS), NodeKind.MATERIAL, ProceduralMaterial.class)); + roots.addAll(listed(DECORATIONS, root.get(DECORATIONS), NodeKind.DECORATION, ProceduralDecoration.class)); + return new NodeGraph(roots); + } + + // The pack read the file's arrays element for element, so the definition's lists line up with them. + private List parts(JsonPath arrayPath, Optional array, List read, String parentRole) { + if (!(array.orElse(null) instanceof JsonText.Arr elements)) { + return List.of(); + } + List links = new ArrayList<>(); + for (int index = 0; index < elements.elements().size(); index++) { + ProceduralPart part = index < read.size() ? read.get(index) : null; + links.add(new Link(GROWS, part(arrayPath.element(index), elements.elements().get(index), part, parentRole, true))); + } + return links; + } + + private GraphNode part(JsonPath path, JsonText.Value json, ProceduralPart read, String parentRole, boolean movable) { + OptionalInt drawnPart = drawnPartOf(read); + if (!(json instanceof JsonText.Obj object)) { + return sharedPart(path, json, drawnPart, parentRole, movable); + } + String role = stringAt(object, ROLE).filter(written -> !written.isBlank()).orElse(parentRole); + List settings = new ArrayList<>(); + settings.add(new NodeSettings("Part", path, ProceduralPart.class, PART_NODES)); + List children = new ArrayList<>(); + NodeKind kind = NodeKind.GROUP; + for (Shape shape : Shape.values()) { + if (!(object.get(shape.key).orElse(null) instanceof JsonText.Obj shapeObject)) { + continue; + } + kind = kind == NodeKind.GROUP || shape.copiesAPart() ? shape.kind : kind; + JsonPath shapePath = path.member(shape.key); + settings.add(new NodeSettings(shape.kind.label, shapePath, shape.settings, shape.copiesAPart() ? COPY_NODES : NO_NODES)); + Optional copied = shapeObject.get(COPIED_PART); + if (shape.copiesAPart() && copied.isPresent()) { + children.add(new Link(EACH_COPY, part(shapePath.member(COPIED_PART), copied.get(), copiedPartOf(read, shape), role, false))); + } + } + JsonPath childList = path.member(CHILDREN); + children.addAll(parts(childList, object.get(CHILDREN), read == null ? List.of() : read.children(), role)); + return new GraphNode(kind.label, kind.label, path, drawnPart, List.of(role), settings, children, + new Edits(Optional.of(childList), movable, partAdditions(childList))); + } + + // A part written as the name of a snippet file, which is edited there. + private GraphNode sharedPart(JsonPath path, JsonText.Value json, OptionalInt drawnPart, String parentRole, boolean movable) { + String title = json instanceof JsonText.Literal literal && literal.string().isPresent() ? literal.string().get() : source.textOf(json); + return new GraphNode(NodeKind.SHARED_PART.label, title, path, drawnPart, List.of(parentRole), List.of(), List.of(), + new Edits(Optional.empty(), movable, List.of())); + } + + private OptionalInt drawnPartOf(ProceduralPart read) { + if (read == null) { + return OptionalInt.empty(); + } + int id = outline.idOf(read); + return id == PartOutline.NO_PART ? OptionalInt.empty() : OptionalInt.of(id); + } + + private static ProceduralPart copiedPartOf(ProceduralPart part, Shape shape) { + if (part == null) { + return null; + } + if (shape == Shape.BRANCHES) { + return part.branches() == null ? null : part.branches().part(); + } + return part.cluster() == null ? null : part.cluster().part(); + } + + private static List listed(String key, Optional array, NodeKind kind, Class settings) { + if (!(array.orElse(null) instanceof JsonText.Arr elements)) { + return List.of(); + } + List nodes = new ArrayList<>(); + for (int index = 0; index < elements.elements().size(); index++) { + if (!(elements.elements().get(index) instanceof JsonText.Obj element)) { + continue; + } + JsonPath path = JsonPath.ROOT.member(key).element(index); + nodes.add(new GraphNode(kind.label, kind.label, path, OptionalInt.empty(), rolesOf(kind, element), + List.of(new NodeSettings(kind.label, path, settings, NO_NODES)), List.of(), Edits.NONE)); + } + return nodes; + } + + private static List rolesOf(NodeKind kind, JsonText.Obj element) { + if (kind == NodeKind.MATERIAL) { + return List.of(stringAt(element, ROLE).orElse(DEFAULT_MATERIAL_ROLE)); + } + if (!(element.get(DECORATED_ROLES).orElse(null) instanceof JsonText.Arr roles)) { + return List.of(); + } + return roles.elements().stream() + .flatMap(role -> role instanceof JsonText.Literal literal ? literal.string().stream() : Stream.empty()) + .toList(); + } + + private static Optional stringAt(JsonText.Obj object, String key) { + return object.get(key).flatMap(value -> value instanceof JsonText.Literal literal ? literal.string() : Optional.empty()); + } + + /** What a new part starts as, so it bakes into something visible at once. */ + private static List partAdditions(JsonPath list) { + return List.of( + new Addition("Stem", list, "{\"stem\": {\"length\": 6}}"), + new Addition("Blob", list, "{\"blob\": {\"radius\": 2}}"), + new Addition("Branches", list, "{\"branches\": {\"count\": 4, \"part\": {\"stem\": {\"length\": 4}}}}"), + new Addition("Cluster", list, "{\"cluster\": {\"count\": 5, \"part\": {\"stem\": {\"length\": 3}}}}"), + new Addition("Group", list, "{}")); + } + + private static List objectAdditions(JsonPath parts) { + List additions = new ArrayList<>(partAdditions(parts)); + additions.add(new Addition("Material", JsonPath.ROOT.member(MATERIALS), "{\"role\": \"main\", \"block\": \"minecraft:stone\"}")); + additions.add(new Addition("Decoration", JsonPath.ROOT.member(DECORATIONS), "{\"block\": \"minecraft:vine\"}")); + return additions; + } + + private enum NodeKind { + STEM("Stem"), + BLOB("Blob"), + BRANCHES("Branches"), + CLUSTER("Cluster"), + GROUP("Group"), + SHARED_PART("Shared part"), + MATERIAL("Material"), + DECORATION("Decoration"); + + private final String label; + + NodeKind(String label) { + this.label = label; + } + } + + /** The shapes a part can take, each written as a member of the part holding its settings. */ + private enum Shape { + STEM("stem", NodeKind.STEM, PartStem.class), + BLOB("blob", NodeKind.BLOB, PartBlob.class), + BRANCHES("branches", NodeKind.BRANCHES, PartBranches.class), + CLUSTER("cluster", NodeKind.CLUSTER, PartCluster.class); + + private final String key; + private final NodeKind kind; + private final Class settings; + + Shape(String key, NodeKind kind, Class settings) { + this.key = key; + this.kind = kind; + this.settings = settings; + } + + boolean copiesAPart() { + return this == BRANCHES || this == CLUSTER; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java b/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java new file mode 100644 index 000000000..ea1c2dd29 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java @@ -0,0 +1,98 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; +import art.arcane.iris.engine.procedural.ProceduralVariants; +import art.arcane.iris.engine.procedural.part.ProceduralObject; +import com.volmit.object.GeneratedObject; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.EditableSceneView; +import com.volmit.tooling.JsonText; +import com.volmit.tooling.NodeGraph; +import com.volmit.tooling.SceneEntry; +import com.volmit.tooling.SceneFile; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Optional; + +/** + * The studio's Procedural view: every procedural object of the pack with each of its variants, baked as the world + * bakes them, so what the studio shows is what generation places. Each object's file can be edited as nodes. + */ +public final class ProceduralObjectScenes implements EditableSceneView { + private static final ResourceId ID = ResourceId.parse("iris:objects/procedural"); + private static final char FOLDER_SEPARATOR = '/'; + + @Override + public ResourceId id() { + return ID; + } + + @Override + public String label() { + return "Procedural"; + } + + @Override + public String description() { + return "Trees, rock formations and more that Iris generates from settings, every variant in 3D"; + } + + @Override + public List entries(PackWorld world) { + ProceduralObjectCatalog catalog = ProceduralObjectCatalog.of(world); + return world.resources().ids(ProceduralObjectCatalog.DEFINITIONS).stream() + .flatMap(id -> catalog.variants(ProceduralObjectCatalog.KEY_PREFIX + id.path()).stream()) + .map(ProceduralObjectScenes::entryOf) + .toList(); + } + + @Override + public Optional scene(PackWorld world, String key, int variant) { + return ProceduralObjectCatalog.of(world).variants(ProceduralObjectCatalog.KEY_PREFIX + key) + .flatMap(variants -> variants.variant(variant)) + .map(PlaceableObject::geometry); + } + + @Override + public Optional fileOf(PackWorld world, String key) { + ResourceId id = world.resources().idOf(key); + return world.resources().ids(ProceduralObjectCatalog.DEFINITIONS).contains(id) + ? Optional.of(new SceneFile(ProceduralObjectCatalog.DEFINITIONS, id)) + : Optional.empty(); + } + + // A file the pack could not read has no parts baked from it, so its nodes are drawn without part ids. + @Override + public NodeGraph graph(PackWorld world, String key, JsonText text) { + ProceduralObject read = world.resources().find(ProceduralObjectCatalog.DEFINITIONS, world.resources().idOf(key)) + .orElseGet(ProceduralObject::new); + return ProceduralObjectGraph.of(key.substring(key.lastIndexOf(FOLDER_SEPARATOR) + 1), text, read); + } + + private static SceneEntry entryOf(ProceduralVariants variants) { + String path = variants.path(); + int lastSeparator = path.lastIndexOf(FOLDER_SEPARATOR); + Optional folder = lastSeparator < 0 ? Optional.empty() : Optional.of(path.substring(0, lastSeparator)); + return new SceneEntry(path, path.substring(lastSeparator + 1), folder, variants.variantCount()); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/TerrainTransaction.java b/module/src/main/java/art/arcane/iris/modules/objects/TerrainTransaction.java new file mode 100644 index 000000000..932cabe6d --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/TerrainTransaction.java @@ -0,0 +1,162 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementRecord; +import com.volmit.placement.PlacementTerrain; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * Holds back what an object writes until all of it is known to be acceptable, then writes everything in the order it was + * written, or nothing. Reads see the held writes. Subclasses say which blocks are acceptable. + */ +public abstract class TerrainTransaction extends ForwardingTerrain { + private final List writes = new ArrayList<>(); + private final Map heldBlocks = new HashMap<>(); + private int blockWrites; + + public enum Commit { + /** Everything was written. */ + COMMITTED, + /** No block was written, so nothing was. */ + EMPTY, + /** Some write was not acceptable, so nothing was written. */ + REJECTED + } + + protected TerrainTransaction(PlacementTerrain delegate) { + super(delegate); + } + + /** Whether the transaction may write the block. */ + protected abstract boolean accepts(int x, int y, int z); + + public final Commit commit() { + if (blockWrites == 0) { + discard(); + return Commit.EMPTY; + } + for (Write write : writes) { + BlockPosition position = write.position(); + if (!accepts(position.x(), position.y(), position.z())) { + discard(); + return Commit.REJECTED; + } + } + for (Write write : writes) { + write.applyTo(delegate()); + } + discard(); + return Commit.COMMITTED; + } + + public final void discard() { + writes.clear(); + heldBlocks.clear(); + blockWrites = 0; + } + + @Override + public BlockState get(int x, int y, int z) { + BlockState held = heldBlocks.get(new BlockPosition(x, y, z)); + return held == null ? delegate().get(x, y, z) : held; + } + + @Override + public void set(int x, int y, int z, BlockState state) { + holdBlock(new BlockWrite(new BlockPosition(x, y, z), state, null)); + } + + @Override + public void set(int x, int y, int z, BlockState state, BlockEntityData blockEntity) { + holdBlock(new BlockWrite(new BlockPosition(x, y, z), state, blockEntity)); + } + + @Override + public void recordPlacement(int x, int y, int z, PlacementRecord placement) { + writes.add(new PlacementWrite(new BlockPosition(x, y, z), placement)); + } + + @Override + public Optional placementAt(int x, int y, int z) { + BlockPosition position = new BlockPosition(x, y, z); + for (int index = writes.size() - 1; index >= 0; index--) { + if (writes.get(index) instanceof PlacementWrite write && write.position().equals(position)) { + return Optional.of(write.placement()); + } + } + return delegate().placementAt(x, y, z); + } + + @Override + public void mark(PlacedMarker marker) { + writes.add(new MarkerWrite(marker)); + } + + private void holdBlock(BlockWrite write) { + writes.add(write); + heldBlocks.put(write.position(), write.state()); + blockWrites++; + } + + private sealed interface Write permits BlockWrite, PlacementWrite, MarkerWrite { + BlockPosition position(); + + void applyTo(PlacementTerrain terrain); + } + + private record BlockWrite(BlockPosition position, BlockState state, BlockEntityData blockEntity) implements Write { + @Override + public void applyTo(PlacementTerrain terrain) { + if (blockEntity == null) { + terrain.set(position.x(), position.y(), position.z(), state); + } else { + terrain.set(position.x(), position.y(), position.z(), state, blockEntity); + } + } + } + + private record PlacementWrite(BlockPosition position, PlacementRecord placement) implements Write { + @Override + public void applyTo(PlacementTerrain terrain) { + terrain.recordPlacement(position.x(), position.y(), position.z(), placement); + } + } + + private record MarkerWrite(PlacedMarker marker) implements Write { + @Override + public BlockPosition position() { + return marker.position(); + } + + @Override + public void applyTo(PlacementTerrain terrain) { + terrain.mark(marker); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/TreeGrowthSettings.java b/module/src/main/java/art/arcane/iris/modules/objects/TreeGrowthSettings.java new file mode 100644 index 000000000..0f58c7a26 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/TreeGrowthSettings.java @@ -0,0 +1,50 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +/** Whether a dimension's saplings grow the trees of its object placements, written as {@code "treeSettings": {...}}. */ +@Snippet("iris/objects/tree-settings") +@Desc("Tree growth override settings") +@Feature(id = "iris:objects/trees", name = "Tree growth", key = "treeSettings", targets = Level.DIMENSION) +public final class TreeGrowthSettings implements IrisFeature { + @Required + @Desc("Turn replacing on and off") + private boolean enabled = false; + + @Desc("Object picking modes") + private TreeMode mode = TreeMode.FIRST; + + public TreeGrowthSettings() { + } + + public boolean enabled() { + return enabled; + } + + public TreeMode mode() { + return mode == null ? TreeMode.FIRST : mode; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/TreeMode.java b/module/src/main/java/art/arcane/iris/modules/objects/TreeMode.java new file mode 100644 index 000000000..390ac5909 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/objects/TreeMode.java @@ -0,0 +1,30 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.objects; + +import com.volmit.config.Desc; + +@Desc("Sapling override object picking options") +public enum TreeMode { + @Desc("Check biome, then region, pick the first one that has options. Dimension placements are not consulted.") + FIRST, + + @Desc("Check biome, regions, and dimensions, and pick any option from the total list") + ALL +} diff --git a/module/src/main/java/art/arcane/iris/modules/placement/BlockTraits.java b/module/src/main/java/art/arcane/iris/modules/placement/BlockTraits.java new file mode 100644 index 000000000..49ba4e5df --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/placement/BlockTraits.java @@ -0,0 +1,60 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.placement; + +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; + +import java.util.IdentityHashMap; +import java.util.Map; + +/** + * The traits of the block states one placement handles, asked of the block registry once per state instance. A placement + * reads the same few states over and over and the platform looks every state up by its value, so the answers are kept by + * identity. For one placement on one thread. + */ +public final class BlockTraits { + private final BlockRegistry blocks; + private final Map answers = new IdentityHashMap<>(); + + public BlockTraits(BlockRegistry blocks) { + this.blocks = blocks; + } + + public boolean has(BlockState state, BlockTrait trait) { + return answers.computeIfAbsent(state, ignored -> new TraitAnswers()).has(blocks, state, trait); + } + + private static final class TraitAnswers { + private int asked; + private int held; + + boolean has(BlockRegistry blocks, BlockState state, BlockTrait trait) { + int flag = 1 << trait.ordinal(); + if ((asked & flag) == 0) { + if (blocks.hasTrait(state, trait)) { + held |= flag; + } + asked |= flag; + } + return (held & flag) != 0; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/placement/EdgeSimplex.java b/module/src/main/java/art/arcane/iris/modules/placement/EdgeSimplex.java new file mode 100644 index 000000000..272da3ed2 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/placement/EdgeSimplex.java @@ -0,0 +1,86 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.placement; + +import art.arcane.volmlib.util.math.RNG; + +/** + * Single-octave simplex noise over a plane that swings between -1 and 1, the rolling wave of a terrain bend's edge. It + * is a copy of the two-dimensional simplex of Iris's {@code SimplexNoise} and draws exactly what that draws for the same + * seed, so worlds bent before keep their edges; Iris pins the two against each other in a test. + */ +public final class EdgeSimplex { + private static final double FREQUENCY = 0.01; + private static final double F2 = 0.5 * (Math.sqrt(3.0) - 1.0); + private static final double G2 = (3.0 - Math.sqrt(3.0)) / 6.0; + private static final long X_PRIME = 1619; + private static final long Y_PRIME = 31337; + private static final long HASH_MULTIPLIER = 60493; + private static final double SCALE = 50; + private static final double[] GRADIENTS = {-1D, -1D, 1D, -1D, -1D, 1D, 1D, 1D, 0D, -1D, -1D, 0D, 0D, 1D, 1D, 0D}; + + private final long seed; + + public EdgeSimplex(long seed) { + this.seed = new RNG(seed).lmax(); + } + + public double signed(double x, double z) { + return simplex(x * FREQUENCY, z * FREQUENCY); + } + + private double simplex(double x, double y) { + double skew = (x + y) * F2; + long i = floor(x + skew); + long j = floor(y + skew); + double unskew = (i + j) * G2; + double x0 = x - (i - unskew); + double y0 = y - (j - unskew); + long i1 = x0 > y0 ? 1 : 0; + long j1 = x0 > y0 ? 0 : 1; + double x1 = x0 - i1 + G2; + double y1 = y0 - j1 + G2; + double x2 = x0 - 1 + (2 * G2); + double y2 = y0 - 1 + (2 * G2); + return SCALE * (corner(i, j, x0, y0) + corner(i + i1, j + j1, x1, y1) + corner(i + 1, j + 1, x2, y2)); + } + + private double corner(long cellX, long cellY, double x, double y) { + double falloff = 0.5 - x * x - y * y; + if (falloff < 0) { + return 0; + } + falloff *= falloff; + return falloff * falloff * gradient(cellX, cellY, x, y); + } + + private double gradient(long cellX, long cellY, double x, double y) { + long hash = seed; + hash ^= X_PRIME * cellX; + hash ^= Y_PRIME * cellY; + hash = hash * hash * hash * HASH_MULTIPLIER; + hash = (hash >> 13) ^ hash; + int index = ((int) hash & 7) << 1; + return (x * GRADIENTS[index]) + (y * GRADIENTS[index + 1]); + } + + private static long floor(double value) { + return value >= 0 ? (long) value : (long) value - 1; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/placement/MarkerRule.java b/module/src/main/java/art/arcane/iris/modules/placement/MarkerRule.java new file mode 100644 index 000000000..1258fc375 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/placement/MarkerRule.java @@ -0,0 +1,37 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.placement; + +import com.volmit.block.BlockState; + +import java.util.List; + +/** + * One marker of a placement, an entry of its {@code markers}, with its blocks resolved in the pack. + * + * @param marker the pack's marker to add + * @param targets the blocks to mark + * @param exact whether a block must match a target exactly; otherwise its material is enough + * @param maximum how many blocks to mark at most + */ +public record MarkerRule(String marker, List targets, boolean exact, int maximum) { + public MarkerRule { + targets = List.copyOf(targets); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/placement/ObjectShape.java b/module/src/main/java/art/arcane/iris/modules/placement/ObjectShape.java new file mode 100644 index 000000000..a7bf9451b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/placement/ObjectShape.java @@ -0,0 +1,73 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.placement; + +import art.arcane.volmlib.util.math.IrisBlockVector; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Optional; + +/** The object being placed as the placement stages see it: its declared size, the block its offsets count from, and where it must stand on solid ground. */ +public final class ObjectShape { + private final PlaceableObject object; + private final PackWorld world; + + ObjectShape(PlaceableObject object, PackWorld world) { + this.object = object; + this.world = world; + } + + public int width() { + return object.width(); + } + + public int height() { + return object.height(); + } + + public int depth() { + return object.depth(); + } + + /** The block the object's offsets count from, relative to its corner. */ + public int centerX() { + return object.center().x(); + } + + public int centerY() { + return object.center().y(); + } + + public int centerZ() { + return object.center().z(); + } + + /** The pack object this is, by the id the pack gives its name. */ + public Optional id() { + return Optional.of(world.resources().idOf(object.name())); + } + + /** The columns of the object's lowest solid layer, as offsets from its anchor before any transform; empty for the origin only. */ + public List surfaceSupportOffsets() { + return SurfaceSupportOffsets.of(world).of(object, world.resources().blocks()); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/placement/PlacementSettings.java b/module/src/main/java/art/arcane/iris/modules/placement/PlacementSettings.java new file mode 100644 index 000000000..efaa7fcb4 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/placement/PlacementSettings.java @@ -0,0 +1,169 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.placement; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.blocks.ObjectReplace; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.builtin.prepare.SlopeClip; +import art.arcane.iris.builtin.stilt.StiltSettings; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.builtin.validate.ObjectLimit; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +/** The settings of one object placement as the placement stages read them, its markers and collisions resolved in the pack. */ +public final class PlacementSettings { + private final ObjectPlacement config; + private final PackResources resources; + + public PlacementSettings(ObjectPlacement config, PackResources resources) { + this.config = config; + this.resources = resources; + } + + public boolean forcePlace() { + return config.forcePlace(); + } + + public SlopeClip slopeCondition() { + return config.slopeCondition(); + } + + public boolean rotateTowardsSlope() { + return config.rotateTowardsSlope(); + } + + public ObjectRotation rotation() { + return config.rotation(); + } + + public ObjectTranslate translate() { + return config.translate(); + } + + public ObjectPlaceMode mode() { + return config.mode(); + } + + public boolean fromBottom() { + return config.fromBottom(); + } + + /** Whether the object places from the ground up instead of by height checks. */ + public boolean bottom() { + return config.bottom(); + } + + public CarvingMode carvingSupport() { + return config.carvingSupport(); + } + + public boolean underwater() { + return config.underwater(); + } + + public boolean onwater() { + return config.onwater(); + } + + public boolean requireSurfaceSupport() { + return config.requireSurfaceSupport(); + } + + public int surfaceSupportBuffer() { + return config.surfaceSupportBuffer(); + } + + public int surfaceSupportDepth() { + return config.surfaceSupportDepth(); + } + + public ObjectLimit clamp() { + return config.clamp(); + } + + /** Whether air is placed before the object. */ + public boolean bore() { + return config.bore(); + } + + public int boreExtendMinY() { + return config.boreExtendMinY(); + } + + public int boreExtendMaxY() { + return config.boreExtendMaxY(); + } + + public List edit() { + return config.edit(); + } + + public boolean waterloggable() { + return config.waterloggable(); + } + + public boolean meld() { + return config.meld(); + } + + public List markers() { + return config.markers().stream() + .map(marker -> new MarkerRule(marker.marker(), marker.mark().stream().map(spec -> resources.blocks().resolve(spec)).toList(), + marker.exact(), marker.maximumMarkers())) + .toList(); + } + + public Optional stilt() { + return config.stiltSettings(); + } + + public Optional vacuum() { + return config.vacuumSettings(); + } + + /** The snow filter's depth, 0 for none. */ + public double snow() { + return config.snow(); + } + + /** The pack objects the placement may overlap even when {@link #forbiddenCollisions()} names them. */ + public Set allowedCollisions() { + return objectIds(config.allowedCollisions()); + } + + /** The pack objects the placement may not overlap. */ + public Set forbiddenCollisions() { + return objectIds(config.forbiddenCollisions()); + } + + private Set objectIds(List keys) { + return keys.stream().filter(Objects::nonNull).map(resources::idOf).collect(Collectors.toUnmodifiableSet()); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/placement/PlacementStages.java b/module/src/main/java/art/arcane/iris/modules/placement/PlacementStages.java new file mode 100644 index 000000000..a7c088427 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/placement/PlacementStages.java @@ -0,0 +1,121 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.placement; + +import art.arcane.iris.builtin.anchor.AnchorHeight; +import art.arcane.iris.builtin.blocks.WrittenBlocks; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.stilt.StiltLayers; +import com.volmit.stage.BlockStage; +import com.volmit.stage.PlacementStage; +import com.volmit.stage.Stage; + +/** + * The stages of Iris's built-in object placement modules, one nested class per module, in the order a placement runs + * them. The stage graph decides the actual order. + */ +public final class PlacementStages { + private PlacementStages() { + } + + /** Module {@code iris:prepare}: what a placement decides before it looks for its height. */ + public static final class Prepare { + /** The rotation the placement uses: the requested one, turned downhill when the settings ask to face the slope. Rejects {@code slope}. */ + public static final PlacementStage SLOPE = Stage.placement("iris:prepare/slope", ObjectRotation.class); + /** The random rotation, translation and height offset, chosen once per placement. */ + public static final PlacementStage TRANSFORMS = Stage.placement("iris:prepare/transforms", PreparedPlacement.class); + + private Prepare() { + } + } + + /** Module {@code iris:anchor}: the height an object is placed at. */ + public static final class Anchor { + /** The requested or sampled height the checks judge. Rejects {@code carving-anchor}. */ + public static final PlacementStage HEIGHT = Stage.placement("iris:anchor/height", AnchorHeight.class); + /** The height the object's blocks are written at: the checked height plus the random offset. */ + public static final PlacementStage FINAL = Stage.placement("iris:anchor/final", AnchorHeight.class); + + private Anchor() { + } + } + + /** Module {@code iris:validate}: the checks that reject a placement before anything is written, in this order. */ + public static final class Validate { + /** Rejects {@code bedrock-anchor} and {@code surface-support}. */ + public static final PlacementStage SURFACE = Stage.placement("iris:validate/surface"); + /** Rejects {@code underwater-anchor}, {@code cave-clearance}, {@code fluid-height} and {@code height-clamp}. */ + public static final PlacementStage LIMITS = Stage.placement("iris:validate/limits"); + /** Rejects {@code native-structure}, even for placements that force their way past the other checks. */ + public static final PlacementStage STRUCTURES = Stage.placement("iris:validate/structures"); + /** Rejects {@code object-collision}. */ + public static final PlacementStage COLLISIONS = Stage.placement("iris:validate/collisions"); + + private Validate() { + } + } + + /** Module {@code iris:bore}: clearing the object's volume before its blocks are written. */ + public static final class Bore { + public static final PlacementStage CLEAR = Stage.placement("iris:bore/clear"); + + private Bore() { + } + } + + /** Module {@code iris:blocks}: writing the object's blocks. */ + public static final class Blocks { + /** Writes each object block where the placement puts it. */ + public static final BlockStage WRITE = Stage.placementBlock("iris:blocks/write", WrittenBlocks.class); + /** Marks some written blocks with the placement's markers. */ + public static final PlacementStage MARKERS = Stage.placement("iris:blocks/markers"); + /** Milestone: stages requiring it run after the object and its markers are written. */ + public static final PlacementStage COMPLETE = Stage.placement("iris:blocks/complete"); + + private Blocks() { + } + } + + /** Module {@code iris:stilt}: the stilts of the stilt and ceiling placement modes. */ + public static final class Stilt { + /** Finds the layers to repeat. */ + public static final BlockStage LAYERS = Stage.placementBlock("iris:stilt/layers", StiltLayers.class); + /** Grows the stilt once the object is written. */ + public static final PlacementStage FILL = Stage.placement("iris:stilt/fill"); + + private Stilt() { + } + } + + /** Module {@code iris:vacuum}: bending the terrain to meet objects of the vacuum placement modes. */ + public static final class Vacuum { + public static final PlacementStage TERRAIN = Stage.placement("iris:vacuum/terrain"); + + private Vacuum() { + } + } + + /** Module {@code iris:snow}: snow on the object, after its stilt or terrain bend. */ + public static final class Snow { + public static final PlacementStage COVER = Stage.placement("iris:snow/cover"); + + private Snow() { + } + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/placement/PreparedPlacement.java b/module/src/main/java/art/arcane/iris/modules/placement/PreparedPlacement.java new file mode 100644 index 000000000..40e625caf --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/placement/PreparedPlacement.java @@ -0,0 +1,174 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.placement; + +import art.arcane.iris.builtin.anchor.PlaceMode; +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectSpinKernel; +import art.arcane.iris.builtin.prepare.TransformedBounds; +import art.arcane.volmlib.util.math.IrisBlockVector; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; + +/** + * What one placement chose before it is anchored: the placement it belongs to, the settings it uses, the rotation it + * ended up with, the terrain that answers its height, water and carving questions, its random spin and height offsets, + * and the bounds of the transformed object around its anchor. Object blocks are transformed by rotating them, flipping + * them for a ceiling hang and translating them. + */ +public final class PreparedPlacement { + private final RunningPlacement placement; + private final PlacementSettings settings; + private final PlaceMode mode; + private final ObjectRotation rotation; + private final BlockTraits traits; + private final StageTerrain terrain; + private final ObjectSpinKernel spin; + private final int spinX; + private final int spinY; + private final int spinZ; + private final IrisBlockVector translation; + private final int rotatedCenterY; + private final int translatedCenterY; + private final int randomY; + private final int warpMargin; + private final TransformedBounds bounds; + private final SurfaceWarp surfaceWarp; + + /** Everything the preparation worked out; {@code translation} and {@code surfaceWarp} are null when the placement has none. */ + public PreparedPlacement(RunningPlacement placement, ObjectRotation rotation, BlockTraits traits, StageTerrain terrain, + ObjectSpinKernel spin, int spinX, int spinY, int spinZ, IrisBlockVector translation, int rotatedCenterY, + int translatedCenterY, int randomY, int warpMargin, TransformedBounds bounds, SurfaceWarp surfaceWarp) { + this.placement = placement; + this.settings = placement.settings(); + this.mode = settings.mode().placeMode(); + this.rotation = rotation; + this.traits = traits; + this.terrain = terrain; + this.spin = spin; + this.spinX = spinX; + this.spinY = spinY; + this.spinZ = spinZ; + this.translation = translation; + this.rotatedCenterY = rotatedCenterY; + this.translatedCenterY = translatedCenterY; + this.randomY = randomY; + this.warpMargin = warpMargin; + this.bounds = bounds; + this.surfaceWarp = surfaceWarp; + } + + /** The placement being run. */ + public RunningPlacement placement() { + return placement; + } + + /** The settings the placement was asked for; the rotation may differ, see {@link #rotation()}. */ + public PlacementSettings settings() { + return settings; + } + + /** The rotation the placement uses, which may differ from the requested one. */ + public ObjectRotation rotation() { + return rotation; + } + + /** The traits of the block states this placement handles. */ + public BlockTraits traits() { + return traits; + } + + /** Answers height, water and carving questions; a heightmap placement answers heights from its noise. */ + public StageTerrain terrain() { + return terrain; + } + + public PlaceMode mode() { + return mode; + } + + public int spinX() { + return spinX; + } + + public int spinY() { + return spinY; + } + + public int spinZ() { + return spinZ; + } + + /** The rotated translation, or null when the placement does not translate. */ + public IrisBlockVector translation() { + return translation; + } + + /** The height of the object's center after rotation. */ + public int rotatedCenterY() { + return rotatedCenterY; + } + + /** The height of the object's center after translation. */ + public int translatedCenterY() { + return translatedCenterY; + } + + /** The random height offset added once the anchor is final. */ + public int randomY() { + return randomY; + } + + public int warpMargin() { + return warpMargin; + } + + public TransformedBounds bounds() { + return bounds; + } + + public boolean isWarped() { + return surfaceWarp != null; + } + + /** Moves a world column by the surface warp, along X for {@code x} and along Z for the swapped call. */ + public int warpOffset(double along, double y, double across) { + double half = surfaceWarp.multiplier() / 2D; + return (int) surfaceWarp.fit(-half, half, along, y, across); + } + + /** An object block's offset from the anchor after this placement's transforms. */ + public BlockPosition transform(BlockPosition local) { + IrisBlockVector offset = new IrisBlockVector(local.x(), local.y(), local.z()); + spin.rotate(offset); + if (mode().has(PlaceTrait.UPSIDE_DOWN)) { + offset.setY(-offset.getBlockY()); + } + if (translation != null) { + offset.add(translation); + } + return new BlockPosition((int) Math.round(offset.getX()), (int) Math.round(offset.getY()), (int) Math.round(offset.getZ())); + } + + /** A block state turned with the object, so stairs and logs face the way the object does. */ + public BlockState rotate(BlockState state) { + return placement.rotate(state, rotation, spinX, spinY, spinZ); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/placement/RunningPlacement.java b/module/src/main/java/art/arcane/iris/modules/placement/RunningPlacement.java new file mode 100644 index 000000000..d37650b2a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/placement/RunningPlacement.java @@ -0,0 +1,185 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.placement; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.builtin.objects.HeightmapNoise; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectRun; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.volmlib.util.math.IrisBlockVector; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.block.BlockTurn; +import com.volmit.geometry.BlockPosition; +import com.volmit.placement.PlacementContext; +import com.volmit.resource.PackResources; +import com.volmit.world.PackWorld; + +import java.util.Optional; + +/** + * The object placement being run, as Iris's built-in placement stages see it: what is placed and with which settings + * ({@link ObjectRun}, the run's input), the terrain it is placed on, and the block operations of the pack's registry. + * Heights are above the dimension's bottom. + */ +public final class RunningPlacement { + private static final double QUARTER_TURN_DEGREES = 90D; + private static final double FULL_TURN_DEGREES = 360D; + + private final PlacementContext context; + private final ObjectRun run; + private final ObjectShape object; + private final PlacementSettings settings; + private final StageTerrain terrain; + + private RunningPlacement(PlacementContext context, ObjectRun run) { + this.context = context; + this.run = run; + this.object = new ObjectShape(run.object(), context.world()); + this.settings = new PlacementSettings(run.settings(), context.world().resources()); + this.terrain = StageTerrain.of(context); + } + + /** The placement {@code context} runs. */ + public static RunningPlacement of(PlacementContext context) { + ObjectRun run = context.input(ObjectRun.class).orElseThrow(() -> new IllegalStateException( + "Iris's object placement stages place an object run, and this placement was started without one")); + return new RunningPlacement(context, run); + } + + public ObjectShape object() { + return object; + } + + /** The settings as the caller passed them; the stages derive what they change (the rotation) themselves. */ + public PlacementSettings settings() { + return settings; + } + + public int x() { + return run.x(); + } + + /** The height the caller asked for, negative when the placement samples it. */ + public int requestedY() { + return run.requestedY(); + } + + public int z() { + return run.z(); + } + + /** The cave the object is placed in; empty outside caves. */ + public Optional cave() { + return run.cave(); + } + + /** Answers the questions of the terrain the placement was asked to place on. */ + public StageTerrain terrain() { + return terrain; + } + + /** + * The terrain the placement anchors against: {@link #terrain()}, or, when the settings place on a heightmap, the same + * terrain with its heights from the heightmap's noise, seeded from {@code rng}. + */ + public StageTerrain terrainFor(RNG rng) { + Optional heightmapSettings = run.settings().heightmap(); + if (heightmapSettings.isEmpty()) { + return terrain; + } + long heightmapSeed = rng.nextLong() + run.requestedY() + run.z() - run.x(); + VirtualHeightmap heightmap = VirtualHeightmap.of(heightmapSettings.get(), world().resources().noise(), heightmapSeed); + return terrain.withHeights(heightmap::surface); + } + + /** + * The noise that warps the placement's columns; empty when the settings do not warp. A generated world seeds it from + * the world, so every placement of the world warps alike; a placement without one seeds it from {@code rng}. + */ + public Optional surfaceWarp(RNG rng) { + ObjectPlacement config = run.settings(); + if (!ObjectRun.warps(config.warp())) { + return Optional.empty(); + } + PackWorld world = world(); + long seed = world.running().isPresent() ? world.seed(IrisSeedPurposes.OBJECT_WARP) : rng.getSeed(); + return Optional.of(new SurfaceWarp(world.resources().noise().sampler(config.warp(), seed), config.warp().multiplier())); + } + + /** {@code state} turned with the object by {@code rotation}, as the platform turns stairs, logs and other facing blocks. */ + public BlockState rotate(BlockState state, ObjectRotation rotation, int spinX, int spinY, int spinZ) { + if (!rotation.canRotate()) { + return state; + } + int turnsX = wholeQuarterTurns(spinX); + int turnsY = wholeQuarterTurns(spinY); + int turnsZ = wholeQuarterTurns(spinZ); + BlockTurn turn = (x, y, z) -> { + IrisBlockVector turned = rotation.rotate(new IrisBlockVector(x, y, z), turnsX, turnsY, turnsZ); + return new BlockTurn.Direction(turned.getX(), turned.getY(), turned.getZ()); + }; + return blocks().rotate(state, turn); + } + + /** {@code update} laid over {@code base}: the platform's merge of two states of one block, else {@code update}. */ + public BlockState merge(BlockState base, BlockState update) { + return blocks().merge(base, update); + } + + /** Whether {@code state} matches {@code other} as the platform compares them. */ + public boolean matches(BlockState state, BlockState other) { + return blocks().matches(state, other); + } + + public boolean hasTrait(BlockState state, BlockTrait trait) { + return blocks().hasTrait(state, trait); + } + + /** The resources of the object's pack, where the placement's markers are found. */ + public PackResources resources() { + return world().resources(); + } + + /** Reports a buffered write as one of the object's own blocks, which the placing module reads once the object is placed. */ + public void objectBlockWritten(BlockPosition position) { + run.objectBlockWritten(position); + } + + /** Reports the height the object was anchored at, which the placement returns to its caller. */ + public void anchoredAt(int y) { + run.anchoredAt(y); + } + + private BlockRegistry blocks() { + return world().resources().blocks(); + } + + private PackWorld world() { + return context.world(); + } + + /** The spin in whole quarter turns, as the platform turns blocks: any part of a quarter turn counts as one. */ + private static int wholeQuarterTurns(int degrees) { + return (int) (QUARTER_TURN_DEGREES * Math.ceil(Math.abs((degrees % FULL_TURN_DEGREES) / QUARTER_TURN_DEGREES))); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/placement/StageTerrain.java b/module/src/main/java/art/arcane/iris/modules/placement/StageTerrain.java new file mode 100644 index 000000000..5fce7ac39 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/placement/StageTerrain.java @@ -0,0 +1,126 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.placement; + +import art.arcane.iris.modules.blocks.SmartBoreDebugSettings; +import com.volmit.placement.PlacementContext; +import com.volmit.placement.PlacementRecord; +import com.volmit.placement.PlacementTerrain; +import com.volmit.placement.StructureVolumes; +import com.volmit.resource.ResourceId; +import com.volmit.world.TerrainSampler; + +import java.util.Optional; +import java.util.function.IntBinaryOperator; + +/** + * What a placement stage asks of the terrain and the world around it: heights, carving and water at a column, the + * terrain's shape, and the world's own facts. A placement made without a world ({@link #hasWorld()} is false) answers + * its terrain questions from the placement's terrain alone. + */ +public final class StageTerrain { + private static final String PROCEDURAL_PREFIX = "procedural/"; + + private final PlacementTerrain terrain; + private final PlacementContext context; + private final IntBinaryOperator heightmap; + + private StageTerrain(PlacementTerrain terrain, PlacementContext context, IntBinaryOperator heightmap) { + this.terrain = terrain; + this.context = context; + this.heightmap = heightmap; + } + + static StageTerrain of(PlacementContext context) { + return new StageTerrain(context.placementTerrain(), context, null); + } + + /** This terrain with its heights from {@code heightmap}, for a placement that sits on a virtual heightmap. */ + StageTerrain withHeights(IntBinaryOperator heightmap) { + return new StageTerrain(terrain, context, heightmap); + } + + /** The surface height of the column, counting fluid unless {@code ignoreFluid}. */ + public int highest(int x, int z, boolean ignoreFluid) { + return heightmap != null ? heightmap.applyAsInt(x, z) : terrain.highest(x, z, ignoreFluid); + } + + public boolean isCarved(int x, int y, int z) { + return terrain.isCarved(x, y, z); + } + + /** Whether the block is real, solid ground; the height field alone cannot say at mantle time. */ + public boolean isSurfaceSolid(int x, int y, int z) { + return terrain.isSurfaceSolid(x, y, z); + } + + public boolean isUnderwater(int x, int z) { + return terrain.isUnderwater(x, z); + } + + /** The height up to which the dimension is filled with fluid. */ + public int fluidHeight() { + return terrain.fluidHeight(); + } + + /** Whether leaves the placement writes never decay. */ + public boolean preventsDecay() { + return terrain.preventsDecay(); + } + + /** Whether bored air is written as a visible block, to see where smart boring bored. */ + public boolean debugsSmartBore(int x, int z) { + return context.settings().at(SmartBoreDebugSettings.class, x, z).dimension().map(SmartBoreDebugSettings::show).orElse(false); + } + + /** Whether the placement is made in a world the host generates, rather than a tool's world. */ + public boolean hasWorld() { + return context.world().running().isPresent(); + } + + /** The terrain's slope at the column, as the dimension's slope field gives it. */ + public double slopeAt(int x, int z) { + return sampler().column(x, z).slope(); + } + + /** The terrain height at a position between columns: the height of the column the position lies in, counted toward zero. */ + public double heightAt(double x, double z) { + return sampler().surfaceY((int) x, (int) z); + } + + /** The dimension's height in blocks. */ + public int worldHeight() { + return sampler().bounds().maxY(); + } + + public StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ) { + return terrain.structureVolumes(minX, minZ, maxX, maxZ); + } + + /** The pack object placed at the block; empty when none was, or when a procedural object was. */ + public Optional objectAt(int x, int y, int z) { + return terrain.placementAt(x, y, z) + .map(PlacementRecord::object) + .filter(object -> !object.path().startsWith(PROCEDURAL_PREFIX)); + } + + private TerrainSampler sampler() { + return context.terrain(); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/placement/SurfaceSupportOffsets.java b/module/src/main/java/art/arcane/iris/modules/placement/SurfaceSupportOffsets.java new file mode 100644 index 000000000..a6927511d --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/placement/SurfaceSupportOffsets.java @@ -0,0 +1,113 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.placement; + +import art.arcane.volmlib.util.math.IrisBlockVector; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.ObjectBlock; +import com.volmit.object.PlaceableObject; +import com.volmit.world.PackWorld; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The columns of each object's lowest solid layer, worked out once per object of a world and kept while the object is: an + * object stands on these when its placement needs surface support. Foliage does not count as solid. + */ +final class SurfaceSupportOffsets { + private final ReferenceQueue collected = new ReferenceQueue<>(); + private final Map> offsets = new ConcurrentHashMap<>(); + + static SurfaceSupportOffsets of(PackWorld world) { + return world.state(SurfaceSupportOffsets.class, ignored -> new SurfaceSupportOffsets()); + } + + /** {@code blocks} tells which of the object's blocks are solid. */ + List of(PlaceableObject object, BlockRegistry blocks) { + forgetCollected(); + return offsets.computeIfAbsent(new ObjectKey(object, collected), ignored -> lowestSolidLayer(object, blocks)); + } + + private static List lowestSolidLayer(PlaceableObject object, BlockRegistry blocks) { + Map supporting = new HashMap<>(); + int lowestY = Integer.MAX_VALUE; + List layer = new ArrayList<>(); + for (ObjectBlock block : object.geometry().blocks()) { + if (!supporting.computeIfAbsent(block.state(), state -> supports(state, blocks))) { + continue; + } + BlockPosition position = block.position(); + if (position.y() < lowestY) { + lowestY = position.y(); + layer.clear(); + } + if (position.y() == lowestY) { + layer.add(new IrisBlockVector(position.x(), position.y(), position.z())); + } + } + return List.copyOf(layer); + } + + private static boolean supports(BlockState state, BlockRegistry blocks) { + return blocks.hasTrait(state, BlockTrait.SOLID) && !blocks.hasTrait(state, BlockTrait.FOLIAGE); + } + + private void forgetCollected() { + Object gone; + while ((gone = collected.poll()) != null) { + offsets.remove((ObjectKey) gone); + } + } + + /** An object by identity, held weakly so its entry goes once the object is collected. */ + private static final class ObjectKey extends WeakReference { + private final int hash; + + private ObjectKey(PlaceableObject object, ReferenceQueue queue) { + super(object, queue); + this.hash = System.identityHashCode(object); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof ObjectKey key)) { + return false; + } + PlaceableObject object = get(); + return object != null && object == key.get(); + } + + @Override + public int hashCode() { + return hash; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/placement/SurfaceWarp.java b/module/src/main/java/art/arcane/iris/modules/placement/SurfaceWarp.java new file mode 100644 index 000000000..ec234eeaf --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/placement/SurfaceWarp.java @@ -0,0 +1,33 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.placement; + +import com.volmit.noise.NoiseSampler; + +/** + * Noise that moves the columns of a placement sideways, so a square object warps like a flag. + * + * @param multiplier how far, in blocks, the warp may move a column in total + */ +public record SurfaceWarp(NoiseSampler noise, double multiplier) { + /** The noise at the position, fitted to the range from {@code min} to {@code max}. */ + public double fit(double min, double max, double x, double y, double z) { + return min + noise.sample(x, y, z) * (max - min); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/placement/VirtualHeightmap.java b/module/src/main/java/art/arcane/iris/modules/placement/VirtualHeightmap.java new file mode 100644 index 000000000..8a240f510 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/placement/VirtualHeightmap.java @@ -0,0 +1,111 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.placement; + +import art.arcane.iris.builtin.objects.HeightmapNoise; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseSampler; + +import java.util.ArrayList; +import java.util.List; + +/** + * The heights of an object placement's virtual heightmap: the noise of a {@link HeightmapNoise} and of the + * generators that fracture its coordinates, built once from API noise and seeded from one number. The setting + * {@code octaves} never changed Iris's values, so it is not read. + */ +public final class VirtualHeightmap { + private static final long GENERATOR_SEED_SALT = 33_955_677L; + private static final long FIRST_FRACTURE_SEED_OFFSET = 33L; + private static final long FRACTURE_SEED_STEP = 819L; + + private final HeightmapNoise settings; + private final NoiseSampler sampler; + private final List fractures; + + private VirtualHeightmap(HeightmapNoise settings, NoiseFactory noise, long seed) { + this.settings = settings; + this.sampler = settings.enabled() ? noise.sampler(settings.style(), seed + GENERATOR_SEED_SALT - settings.seed()) : null; + this.fractures = fracturesOf(settings, noise, seed); + } + + /** The heightmap {@code settings} describe, its noise seeded with {@code seed}. */ + public static VirtualHeightmap of(HeightmapNoise settings, NoiseFactory noise, long seed) { + return new VirtualHeightmap(settings, noise, seed); + } + + /** The height at the column, rounded to a whole block. */ + public int surface(int x, int z) { + return (int) Math.round(valueAt(x, z)); + } + + private static List fracturesOf(HeightmapNoise settings, NoiseFactory noise, long seed) { + List built = new ArrayList<>(); + long fractureOffset = FIRST_FRACTURE_SEED_OFFSET; + for (HeightmapNoise fracture : settings.fracture()) { + if (fracture.enabled()) { + built.add(new VirtualHeightmap(fracture, noise, seed + settings.seed() + fractureOffset)); + } + fractureOffset += FRACTURE_SEED_STEP; + } + return List.copyOf(built); + } + + private double valueAt(double columnX, double columnZ) { + if (!settings.enabled()) { + return settings.offsetY(); + } + double x = columnX; + double z = columnZ; + for (VirtualHeightmap fracture : fractures) { + double centre = fracture.settings.opacity() / 2D; + x += fracture.valueAt(columnX, columnZ) - centre; + z += fracture.valueAt(columnZ, columnX) - centre; + } + double sampleX = (x / settings.zoom()) + settings.offsetX(); + double sampleZ = (z / settings.zoom()) + settings.offsetZ(); + return shaped(sampler.sample(sampleX, sampleZ) * settings.opacity()); + } + + private double shaped(double sampled) { + double value = settings.negative() ? (-sampled + settings.opacity()) : sampled; + value = raised(value) + settings.offsetY(); + if (settings.parametric()) { + value = parametric(value); + } + if (settings.bezier()) { + value = value * value * (3D - 2D * value); + } + return settings.sinCentered() ? Math.sin(value * Math.PI) : value; + } + + private double raised(double value) { + double exponent = settings.exponent(); + if (exponent == 1D) { + return value; + } + return value < 0 ? -Math.pow(-value, exponent) : Math.pow(value, exponent); + } + + /** The parametric curve of alpha 1, which is what the setting has always applied. */ + private static double parametric(double value) { + double raised = Math.pow(value, 1D); + return raised / ((raised - Math.pow(value, 0D)) + 1D); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/post/PostProcessingSettings.java b/module/src/main/java/art/arcane/iris/modules/post/PostProcessingSettings.java new file mode 100644 index 000000000..17d0cbaaf --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/post/PostProcessingSettings.java @@ -0,0 +1,44 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.post; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** + * Whether a dimension is post processed, written as {@code "postProcessing": true}. Iris has never read this flag: surface smoothing runs + * whatever it says, so it is declared to keep the key valid in packs. + */ +@Desc("Use post processing or not") +@Feature(id = "iris:post/enabled", name = "Post processing", key = "postProcessing", root = "enabled", targets = Level.DIMENSION) +public final class PostProcessingSettings implements IrisFeature { + public static final boolean DEFAULT_ENABLED = true; + + @Desc("Use post processing or not") + private boolean enabled = DEFAULT_ENABLED; + + public PostProcessingSettings() { + } + + public boolean enabled() { + return enabled; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/post/PostProcessingSlabsSettings.java b/module/src/main/java/art/arcane/iris/modules/post/PostProcessingSlabsSettings.java new file mode 100644 index 000000000..636b77953 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/post/PostProcessingSlabsSettings.java @@ -0,0 +1,43 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.post; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** + * Whether post processing adds slabs on steps in a dimension, written as {@code "postProcessingSlabs": false}. A dimension without the key adds them. + */ +@Desc("Add slabs in post processing") +@Feature(id = "iris:post/slabs", name = "Post processing slabs", key = "postProcessingSlabs", root = "enabled", targets = Level.DIMENSION) +public final class PostProcessingSlabsSettings implements IrisFeature { + public static final boolean DEFAULT_ENABLED = true; + + @Desc("Add slabs in post processing") + private boolean enabled = DEFAULT_ENABLED; + + public PostProcessingSlabsSettings() { + } + + public boolean enabled() { + return enabled; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/post/PostProcessingWallsSettings.java b/module/src/main/java/art/arcane/iris/modules/post/PostProcessingWallsSettings.java new file mode 100644 index 000000000..d475ff1e7 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/post/PostProcessingWallsSettings.java @@ -0,0 +1,43 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.post; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** + * Whether post processing paints walls on steep faces in a dimension, written as {@code "postProcessingWalls": false}. A dimension without the key paints them. + */ +@Desc("Add painted walls in post processing") +@Feature(id = "iris:post/walls", name = "Post processing walls", key = "postProcessingWalls", root = "enabled", targets = Level.DIMENSION) +public final class PostProcessingWallsSettings implements IrisFeature { + public static final boolean DEFAULT_ENABLED = true; + + @Desc("Add painted walls in post processing") + private boolean enabled = DEFAULT_ENABLED; + + public PostProcessingWallsSettings() { + } + + public boolean enabled() { + return enabled; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/spawn/EffectSettings.java b/module/src/main/java/art/arcane/iris/modules/spawn/EffectSettings.java new file mode 100644 index 000000000..d8b545f50 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/spawn/EffectSettings.java @@ -0,0 +1,46 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.spawn; + +import art.arcane.iris.builtin.spawn.AmbientEffect; +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.Collections; +import java.util.List; + +/** + * The ambient effects one region or biome declares, written as {@code "effects": [...]}, the list of + * {@link AmbientEffect}s. They play around every player in the area. + */ +@Desc("Effects are ambient effects such as potion effects, random sounds, or even particles around each player. All of these effects are played via packets so two players won't see/hear each others effects.\nDue to performance reasons, effects will play arround the player even if where the effect was played is no longer in the biome the player is in.") +@Feature(id = "iris:spawn/effects", name = "Effects", key = "effects", root = "effects", targets = {Level.REGION, Level.BIOME}) +public final class EffectSettings implements IrisFeature { + @Desc("Effects are ambient effects such as potion effects, random sounds, or even particles around each player.") + private List effects = List.of(); + + public EffectSettings() { + } + + public List effects() { + return effects == null ? List.of() : Collections.unmodifiableList(effects); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/spawn/SpawnerSettings.java b/module/src/main/java/art/arcane/iris/modules/spawn/SpawnerSettings.java new file mode 100644 index 000000000..2b7921c03 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/spawn/SpawnerSettings.java @@ -0,0 +1,48 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.spawn; + +import art.arcane.iris.builtin.spawn.Spawner; +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.ResourceRef; + +import java.util.Collections; +import java.util.List; + +/** + * The spawners one dimension, region or biome lists, written as {@code "entitySpawners": [...]}, the keys of the + * {@link Spawner}s. A chunk may fire the spawners of its dimension, region and biome. + */ +@Desc("Entity spawners that fire in this area") +@Feature(id = "iris:spawn", name = "Entity spawners", key = "entitySpawners", root = "spawners", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) +public final class SpawnerSettings implements IrisFeature { + @ResourceRef(Spawner.class) + @Desc("Entity spawners to add to this area") + private List spawners = List.of(); + + public SpawnerSettings() { + } + + public List spawners() { + return spawners == null ? List.of() : Collections.unmodifiableList(spawners); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/BiomeLayers.java b/module/src/main/java/art/arcane/iris/modules/terrain/BiomeLayers.java new file mode 100644 index 000000000..73d49d60f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/BiomeLayers.java @@ -0,0 +1,375 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.modules.terrain; + +import art.arcane.iris.builtin.prepare.SlopeClip; +import art.arcane.iris.builtin.terrain.LayersSettings; +import art.arcane.iris.builtin.terrain.PaletteLayer; +import art.arcane.volmlib.util.cache.AtomicCache; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.noise.NoiseFactory; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +/** + * What the terrain module keeps for one world about the layers of its biomes: each layer made ready ({@link ResolvedLayer}) + * and the noise that sets the thickness of a biome's layers, and the blocks the layers of a biome stack up to at a column. + * A biome's layers are its {@link LayersSettings}, {@link SeaLayersSettings} and {@link CaveCeilingLayersSettings}; a biome + * that declares no layers has the one layer of grass the settings default to. + * + *

The noise of a biome's layers is built once, from the random of the first column asked for, as it always was. + */ +public final class BiomeLayers { + private static final int SURFACE_HEIGHT_SEED = 7235; + private static final int SEA_HEIGHT_SEED = 7735; + private static final int LOCKED_LAYERS_REFERENCE_HEIGHT = 512; + private static final LayersSettings DEFAULT_LAYERS = new LayersSettings(); + private static final PaletteLayer NO_LAYER = PaletteLayer.withoutBlocks(); + private static final BlockState BARRIER = new BlockState("minecraft:barrier"); + + private final Supplier layerBlocks; + private final Supplier noise; + private final ModuleLog log; + private final Map resolved = new ConcurrentHashMap<>(); + private final Map>> surfaceHeights = new ConcurrentHashMap<>(); + private final Map>> seaHeights = new ConcurrentHashMap<>(); + private final Map biomes = new ConcurrentHashMap<>(); + + /** The layers of {@code world}. */ + public static BiomeLayers of(PackWorld world) { + return world.state(BiomeLayers.class, generating -> new BiomeLayers(() -> LayerBlocks.of(generating), () -> generating.resources().noise(), generating.log())); + } + + /** The layers of a world whose layer blocks {@code layerBlocks} and noise {@code noise} give, asked for when a layer first needs them. */ + public BiomeLayers(Supplier layerBlocks, Supplier noise, ModuleLog log) { + this.layerBlocks = layerBlocks; + this.noise = noise; + this.log = log; + } + + /** {@code layer} ready for this world; its block picks are the world's {@link LayerBlocks}. */ + public ResolvedLayer resolve(PaletteLayer layer) { + return resolved.computeIfAbsent(layer, declared -> ResolvedLayer.of(declared, layerBlocks, noise)); + } + + /** What the biome {@code id} declares about its layers, read once from {@code settings}. */ + public LayeredBiome biome(ResourceId id, FeatureSettings settings) { + LayeredBiome known = biomes.get(id); + if (known != null) { + return known; + } + return biomes.computeIfAbsent(id, ignored -> new LayeredBiome( + settings.declaredBy(id, LayersSettings.class).orElse(null), + settings.declaredBy(id, SeaLayersSettings.class).orElse(null), + settings.declaredBy(id, CaveCeilingLayersSettings.class).orElse(null), + settings.declaredBy(id, LockLayersSettings.class).orElse(null), + settings.declaredBy(id, LockLayersMaxSettings.class).orElse(null), + settings.declaredBy(id, WallSettings.class).orElse(null))); + } + + /** The biome's wall, which places no block when the biome declares none. */ + public ResolvedLayer wall(LayeredBiome biome) { + PaletteLayer layer = biome.wall() == null ? NO_LAYER : biome.wall().layer(); + return resolve(layer); + } + + /** The blocks the biome's layers stack up to at the column, top first, at most {@code maxDepth} of them. */ + public KList generateLayers(LayeredBiome biome, PaletteExplosion explosion, double wx, double wz, RNG random, int maxDepth, int height, + ColumnSlope slope) { + if (isLocked(biome)) { + return generateLockedLayers(biome, wx, wz, random, maxDepth, height, slope); + } + + KList blocks = new KList<>(); + if (maxDepth <= 0) { + return blocks; + } + + LayersSettings settings = surfaceSettings(biome); + List layers = settings.layers(); + if (layers.isEmpty()) { + return blocks; + } + + KList heightNoises = surfaceHeightNoises(settings, random); + for (int i = 0; i < layers.size(); i++) { + ResolvedLayer layer = resolve(layers.get(i)); + double depth = layerDepth(layer, heightNoises.get(i), wx, wz, slope); + if (depth <= 0) { + continue; + } + + stackLayer(blocks, layer, i, depth, wx, wz, random, maxDepth); + if (blocks.size() >= maxDepth) { + break; + } + + separateLayers(blocks, explosion, maxDepth); + } + + return blocks; + } + + /** The blocks the biome's cave ceiling layers stack up to at the column, nearest the ceiling first, at most {@code maxDepth} of them. */ + public KList generateCeilingLayers(LayeredBiome biome, PaletteExplosion explosion, double wx, double wz, RNG random, int maxDepth) { + KList blocks = new KList<>(); + if (maxDepth <= 0) { + return blocks; + } + + List ceilingLayers = biome.ceilingLayers() == null ? List.of() : biome.ceilingLayers().layers(); + if (ceilingLayers.isEmpty()) { + return blocks; + } + + KList heightNoises = surfaceHeightNoises(surfaceSettings(biome), random); + // Ceiling layers reuse the surface-layer height noise, so entries beyond the surface layers have none; skip them. + int usableLayers = Math.min(ceilingLayers.size(), heightNoises.size()); + for (int i = 0; i < usableLayers; i++) { + ResolvedLayer layer = resolve(ceilingLayers.get(i)); + double depth = layerThickness(layer, heightNoises.get(i), wx, wz); + if (depth <= 0) { + continue; + } + + stackLayer(blocks, layer, i, depth, wx, wz, random, maxDepth); + if (blocks.size() >= maxDepth) { + break; + } + + separateLayers(blocks, explosion, maxDepth); + } + + return blocks; + } + + /** The blocks of the biome's sea layers at the column, from the water surface down, at most {@code maxDepth} of them. */ + public KList generateSeaLayers(LayeredBiome biome, double wx, double wz, RNG random, int maxDepth) { + KList blocks = new KList<>(); + SeaLayersSettings settings = biome.seaLayers(); + if (settings == null || settings.layers().isEmpty()) { + return blocks; + } + + List layers = settings.layers(); + KList heightNoises = seaHeightNoises(settings, random); + for (int i = 0; i < layers.size(); i++) { + ResolvedLayer layer = resolve(layers.get(i)); + int depth = heightNoises.get(i).fit(layer.minHeight(), layer.maxHeight(), wx / layer.zoom(), wz / layer.zoom()); + if (depth < 0) { + continue; + } + + stackLayer(blocks, layer, i, depth, wx, wz, random, maxDepth); + if (blocks.size() >= maxDepth) { + break; + } + } + + return blocks; + } + + /** The biome's surface layers, the one default layer when it declares none. */ + public List surfaceLayers(LayeredBiome biome) { + return surfaceSettings(biome).layers(); + } + + public List seaLayers(LayeredBiome biome) { + return biome.seaLayers() == null ? List.of() : biome.seaLayers().layers(); + } + + /** The biome's cave ceiling layers that place blocks: those with a surface layer at their place to borrow its thickness from. */ + public List ceilingLayers(LayeredBiome biome) { + List declared = biome.ceilingLayers() == null ? List.of() : biome.ceilingLayers().layers(); + return declared.subList(0, Math.min(declared.size(), surfaceLayers(biome).size())); + } + + /** + * Surface layer {@code index}'s block {@code depth} blocks below its top at the column, as {@link #generateLayers} picks + * it, leaving its slope condition aside; null where the layer is thinner there. + */ + public BlockState surfaceLayerBlock(LayeredBiome biome, int index, int depth, double wx, double wz, RNG random) { + LayersSettings settings = surfaceSettings(biome); + ResolvedLayer layer = resolve(settings.layers().get(index)); + double thickness = layerThickness(layer, surfaceHeightNoises(settings, random).get(index), wx, wz); + return blockAtDepth(layer, index, depth, thickness, wx, wz, random); + } + + /** Sea layer {@code index}'s block {@code depth} blocks below the water surface, as {@link #generateSeaLayers} picks it. */ + public BlockState seaLayerBlock(LayeredBiome biome, int index, int depth, double wx, double wz, RNG random) { + ResolvedLayer layer = resolve(seaLayers(biome).get(index)); + LayerNoise heightNoise = seaHeightNoises(biome.seaLayers(), random).get(index); + int thickness = heightNoise.fit(layer.minHeight(), layer.maxHeight(), wx / layer.zoom(), wz / layer.zoom()); + return blockAtDepth(layer, index, depth, thickness, wx, wz, random); + } + + /** Cave ceiling layer {@code index}'s block {@code depth} blocks below the ceiling, as {@link #generateCeilingLayers} picks it. */ + public BlockState ceilingLayerBlock(LayeredBiome biome, int index, int depth, double wx, double wz, RNG random) { + ResolvedLayer layer = resolve(ceilingLayers(biome).get(index)); + double thickness = layerThickness(layer, surfaceHeightNoises(surfaceSettings(biome), random).get(index), wx, wz); + return blockAtDepth(layer, index, depth, thickness, wx, wz, random); + } + + // The layer's blocks are stacked from its top, as generation stacks them, so the first pick seeds its noise as the world's did. + private BlockState blockAtDepth(ResolvedLayer layer, int index, int depth, double thickness, double wx, double wz, RNG random) { + if (depth >= thickness) { + return null; + } + KList stacked = new KList<>(); + stackLayer(stacked, layer, index, depth + 1, wx, wz, random, depth + 1); + return stacked.size() > depth ? stacked.get(depth) : null; + } + + private KList generateLockedLayers(LayeredBiome biome, double wx, double wz, RNG random, int maxDepthLimit, int height, ColumnSlope slope) { + KList stacked = new KList<>(); + KList locked = new KList<>(); + int maxDepth = Math.min(maxDepthLimit, lockedLayersMax(biome)); + if (maxDepth <= 0) { + return stacked; + } + + LayersSettings settings = surfaceSettings(biome); + List layers = settings.layers(); + if (!layers.isEmpty()) { + KList heightNoises = surfaceHeightNoises(settings, random); + for (int i = 0; i < layers.size(); i++) { + ResolvedLayer layer = resolve(layers.get(i)); + double depth = layerDepth(layer, heightNoises.get(i), wx, wz, slope); + if (depth <= 0) { + continue; + } + + stackLayerUnlimited(stacked, layer, i, depth, wx, wz, random); + } + } + + if (stacked.isEmpty()) { + return locked; + } + + for (int i = 0; i < maxDepth; i++) { + int offset = (LOCKED_LAYERS_REFERENCE_HEIGHT - height) - i; + locked.add(stacked.get(Math.max(offset % stacked.size(), 0))); + } + + return locked; + } + + private void stackLayer(KList blocks, ResolvedLayer layer, int index, double depth, double wx, double wz, RNG random, int maxDepth) { + for (int j = 0; j < depth; j++) { + if (blocks.size() >= maxDepth) { + break; + } + + addBlock(blocks, layer, index, j, wx, wz, random); + } + } + + private void stackLayerUnlimited(KList blocks, ResolvedLayer layer, int index, double depth, double wx, double wz, RNG random) { + for (int j = 0; j < depth; j++) { + addBlock(blocks, layer, index, j, wx, wz, random); + } + } + + /** Adds the layer's block {@code j} blocks down; a layer that fails to pick adds nothing. */ + private void addBlock(KList blocks, ResolvedLayer layer, int index, int j, double wx, double wz, RNG random) { + double blocksPerSample = layer.blocksPerSample(); + try { + blocks.add(layer.get(random, index + j, (wx + j) / blocksPerSample, j, (wz - j) / blocksPerSample)); + } catch (Throwable e) { + log.error("A biome layer failed to pick a block", e); + } + } + + /** The barrier blocks a dimension puts between layers to show them apart. */ + private void separateLayers(KList blocks, PaletteExplosion explosion, int maxDepth) { + if (!explosion.exploded()) { + return; + } + + for (int j = 0; j < explosion.size(); j++) { + blocks.add(BARRIER); + if (blocks.size() >= maxDepth) { + break; + } + } + } + + /** How thick the layer is at the column: nothing where the slope is outside the layer's limits. */ + private double layerDepth(ResolvedLayer layer, LayerNoise heightNoise, double wx, double wz, ColumnSlope slope) { + double depth = layerThickness(layer, heightNoise, wx, wz); + SlopeClip clip = layer.slopeCondition(); + if (!clip.isDefault() && !clip.isValid(slope.at(wx, wz))) { + return 0; + } + + return depth; + } + + private double layerThickness(ResolvedLayer layer, LayerNoise heightNoise, double wx, double wz) { + double zoom = layer.zoom(); + return heightNoise.fit(layer.minHeight(), layer.maxHeight(), wx / zoom, wz / zoom); + } + + private KList surfaceHeightNoises(LayersSettings settings, RNG rng) { + AtomicCache> cache = surfaceHeights.computeIfAbsent(settings, declared -> new AtomicCache<>()); + return heightNoises(cache, settings.layers(), SURFACE_HEIGHT_SEED, rng); + } + + private KList seaHeightNoises(SeaLayersSettings settings, RNG rng) { + AtomicCache> cache = seaHeights.computeIfAbsent(settings, declared -> new AtomicCache<>()); + return heightNoises(cache, settings.layers(), SEA_HEIGHT_SEED, rng); + } + + private KList heightNoises(AtomicCache> cache, List layers, int firstSeed, RNG rng) { + KList cached = cache.getIfPresent(); + if (cached != null) { + return cached; + } + + return cache.aquire(() -> { + KList noises = new KList<>(); + int seed = firstSeed; + for (PaletteLayer layer : layers) { + noises.add(resolve(layer).heightNoise(rng.nextParallelRNG((seed++) * seed * seed * seed))); + } + return noises; + }); + } + + private static LayersSettings surfaceSettings(LayeredBiome biome) { + return biome.layers() == null ? DEFAULT_LAYERS : biome.layers(); + } + + private static boolean isLocked(LayeredBiome biome) { + return biome.lock() != null && biome.lock().locked(); + } + + private static int lockedLayersMax(LayeredBiome biome) { + return biome.lockMax() == null ? LockLayersMaxSettings.DEFAULT_LAYERS : biome.lockMax().layers(); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java b/module/src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java new file mode 100644 index 000000000..b3acc26a7 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java @@ -0,0 +1,280 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.terrain; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.builtin.terrain.PaletteLayer; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.BlockPattern; +import com.volmit.tooling.PatternArea; +import com.volmit.tooling.PatternEntry; +import com.volmit.tooling.PatternView; +import com.volmit.world.PackBiome; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * The studio's Palettes view (v3e's palette explorer): each biome's layers, sea layers, cave ceiling layers, wall and + * slab, from above, the blocks each places at a depth as the world places them. Picks go through the world's own + * {@link BiomeLayers} with the random each stage uses, so asking first seeds a layer's noise as generation would. + */ +public final class BiomePalettes implements PatternView { + private static final ResourceId ID = ResourceId.parse("iris:terrain/palettes"); + private static final char KIND_SEPARATOR = '#'; + private static final char INDEX_SEPARATOR = '/'; + private static final String MINECRAFT_PREFIX = "minecraft:"; + // Walls and slabs are picked one block at a time with noise that changes with height. + private static final int SINGLE_BLOCK_DEPTHS = 1; + private static final int SINGLE_BLOCK_SIGNATURE = 0; + + @Override + public ResourceId id() { + return ID; + } + + @Override + public String label() { + return "Palettes"; + } + + @Override + public String description() { + return "Each biome's layers, wall and slab from above, the blocks they place at each depth"; + } + + @Override + public List entries(PackWorld world) { + Optional running = world.running(); + if (running.isEmpty()) { + return List.of(); + } + BiomeLayers layers = BiomeLayers.of(world); + FeatureSettings settings = running.get().settings(); + List biomes = biomesByName(world.resources()); + Map biomesByShownName = biomes.stream().collect(Collectors.groupingBy(PackBiome::name, Collectors.counting())); + List entries = new ArrayList<>(); + for (PackBiome biome : biomes) { + String group = biomesByShownName.get(biome.name()) > 1 ? biome.name() + " (" + biome.id().path() + ")" : biome.name(); + LayeredBiome layered = layers.biome(biome.id(), settings); + for (Kind kind : Kind.values()) { + List palettes = kind.palettesOf(layers, layered, settings, biome.id()); + for (int index = 0; index < palettes.size(); index++) { + entries.add(entryOf(biome, layered, kind, index, palettes.get(index), group)); + } + } + } + return entries; + } + + @Override + public Optional pattern(PackWorld world, String key, int depth, PatternArea area) { + Optional running = world.running(); + Optional ref = PaletteRef.parse(key, world.resources()); + if (running.isEmpty() || ref.isEmpty()) { + return Optional.empty(); + } + BiomeLayers layers = BiomeLayers.of(world); + FeatureSettings settings = running.get().settings(); + PaletteRef palette = ref.get(); + LayeredBiome biome = layers.biome(palette.biome(), settings); + List palettes = palette.kind().palettesOf(layers, biome, settings, palette.biome()); + if (palette.index() >= palettes.size() || depth < 0) { + return Optional.empty(); + } + ColumnPick pick = palette.kind().picker(world, layers, biome, palettes.get(palette.index()), palette.index(), + running.get().layout().fluidHeight()); + BlockState[] blocks = new BlockState[area.columns() * area.columns()]; + for (int row = 0; row < area.columns(); row++) { + for (int column = 0; column < area.columns(); column++) { + blocks[row * area.columns() + column] = pick.at(area.blockX(column), area.blockZ(row), depth); + } + } + return Optional.of(BlockPattern.of(area.columns(), blocks)); + } + + private static List biomesByName(PackResources resources) { + return resources.ids(PackResources.BIOMES).stream() + .map(id -> resources.find(PackResources.BIOMES, id)) + .flatMap(Optional::stream) + .sorted(Comparator.comparing(PackBiome::name).thenComparing(biome -> biome.id().toString())) + .toList(); + } + + private static PatternEntry entryOf(PackBiome biome, LayeredBiome layered, Kind kind, int index, PaletteLayer palette, String group) { + String key = biome.id() + String.valueOf(KIND_SEPARATOR) + kind.keyName + INDEX_SEPARATOR + index; + String name = kind.numbered ? kind.label + " " + (index + 1) : kind.label; + return new PatternEntry(key, name, Optional.of(group).filter(shown -> !shown.isBlank()), kind.depthsOf(palette), + kind.factsOf(palette, layered)); + } + + private static String blocksOf(PaletteLayer palette) { + Map weights = palette.palette().stream() + .collect(Collectors.groupingBy(spec -> shortName(spec.block()), LinkedHashMap::new, Collectors.summingInt(BlockSpec::weight))); + return weights.entrySet().stream() + .map(entry -> entry.getValue() > 1 ? entry.getKey() + " ×" + entry.getValue() : entry.getKey()) + .collect(Collectors.joining(", ")); + } + + private static String shortName(String block) { + return block.startsWith(MINECRAFT_PREFIX) ? block.substring(MINECRAFT_PREFIX.length()) : block; + } + + private static String thicknessOf(PaletteLayer palette) { + if (palette.minHeight() == palette.maxHeight()) { + return palette.maxHeight() + (palette.maxHeight() == 1 ? " block thick" : " blocks thick"); + } + return palette.minHeight() + " to " + palette.maxHeight() + " blocks thick"; + } + + /** The block a palette places at a column, {@code depth} blocks below its top, or null for none. */ + @FunctionalInterface + private interface ColumnPick { + BlockState at(int x, int z, int depth); + } + + private enum Kind { + LAYER("layer", "Layer", true), + SEA_LAYER("sea-layer", "Sea layer", true), + CEILING_LAYER("ceiling-layer", "Cave ceiling layer", true), + WALL("wall", "Wall", false), + SLAB("slab", "Slab", false); + + private final String keyName; + private final String label; + private final boolean numbered; + + Kind(String keyName, String label, boolean numbered) { + this.keyName = keyName; + this.label = label; + this.numbered = numbered; + } + + static Optional byKeyName(String keyName) { + for (Kind kind : values()) { + if (kind.keyName.equals(keyName)) { + return Optional.of(kind); + } + } + return Optional.empty(); + } + + // A biome without a wall or slab block has those palettes, just empty, so they aren't listed. + List palettesOf(BiomeLayers layers, LayeredBiome biome, FeatureSettings settings, ResourceId id) { + return switch (this) { + case LAYER -> layers.surfaceLayers(biome); + case SEA_LAYER -> layers.seaLayers(biome); + case CEILING_LAYER -> layers.ceilingLayers(biome); + case WALL -> placing(biome.wall() == null ? null : biome.wall().layer()); + case SLAB -> placing(settings.declaredBy(id, SlabSettings.class).map(SlabSettings::layer).orElse(null)); + }; + } + + private static List placing(PaletteLayer layer) { + return layer == null || layer.palette().isEmpty() ? List.of() : List.of(layer); + } + + int depthsOf(PaletteLayer palette) { + return numbered ? Math.max(1, palette.maxHeight()) : SINGLE_BLOCK_DEPTHS; + } + + List factsOf(PaletteLayer palette, LayeredBiome biome) { + List facts = new ArrayList<>(); + facts.add(blocksOf(palette)); + facts.add(numbered ? thicknessOf(palette) : "Picked at the fluid height; changes with height"); + facts.add(palette.style().style().toLowerCase(Locale.ROOT).replace('_', ' ') + " noise, zoom " + palette.zoom()); + if (!palette.slopeCondition().isDefault()) { + facts.add("Only on slopes from " + palette.slopeCondition().minimumSlope() + " to " + palette.slopeCondition().maximumSlope() + + "; shown everywhere here"); + } + if (this == LAYER && biome.layers() == null) { + facts.add("The biome declares no layers, so it gets this default one"); + } + if (this == LAYER && biome.lock() != null && biome.lock().locked()) { + facts.add("The biome locks its layers, which repeats them by height"); + } + return facts; + } + + // Each stage picks with its own random: the terrain's for surface and sea layers, the caves' for ceilings and + // walls, post processing's for slabs. The studio asks with the same one, so it seeds noise as generation does. + ColumnPick picker(PackWorld world, BiomeLayers layers, LayeredBiome biome, PaletteLayer palette, int index, int fluidHeight) { + return switch (this) { + case LAYER -> { + RNG terrain = new RNG(world.seed(IrisSeedPurposes.TERRAIN)); + yield (x, z, depth) -> layers.surfaceLayerBlock(biome, index, depth, x, z, terrain); + } + case SEA_LAYER -> { + RNG terrain = new RNG(world.seed(IrisSeedPurposes.TERRAIN)); + yield (x, z, depth) -> layers.seaLayerBlock(biome, index, depth, x, z, terrain); + } + case CEILING_LAYER -> { + RNG carve = new RNG(world.seed(IrisSeedPurposes.CARVE)); + yield (x, z, depth) -> layers.ceilingLayerBlock(biome, index, depth, x, z, carve); + } + case WALL -> singleBlocks(layers.resolve(palette), new RNG(world.seed(IrisSeedPurposes.CARVE)), fluidHeight); + case SLAB -> singleBlocks(layers.resolve(palette), new RNG(world.seed(IrisSeedPurposes.POST)), fluidHeight); + }; + } + + private static ColumnPick singleBlocks(ResolvedLayer layer, RNG random, int height) { + return (x, z, depth) -> depth == 0 ? layer.get(random, SINGLE_BLOCK_SIGNATURE, x, height, z) : null; + } + } + + private record PaletteRef(ResourceId biome, Kind kind, int index) { + static Optional parse(String key, PackResources resources) { + int kindStart = key.lastIndexOf(KIND_SEPARATOR); + int indexStart = key.lastIndexOf(INDEX_SEPARATOR); + if (kindStart < 1 || indexStart < kindStart) { + return Optional.empty(); + } + Optional kind = Kind.byKeyName(key.substring(kindStart + 1, indexStart)); + Optional index = wholeNumber(key.substring(indexStart + 1)); + Optional biome = resources.ids(PackResources.BIOMES).stream() + .filter(id -> id.toString().equals(key.substring(0, kindStart))) + .findFirst(); + if (kind.isEmpty() || index.isEmpty() || biome.isEmpty()) { + return Optional.empty(); + } + return Optional.of(new PaletteRef(biome.get(), kind.get(), index.get())); + } + + private static Optional wholeNumber(String text) { + try { + return Optional.of(Integer.parseInt(text)).filter(number -> number >= 0); + } catch (NumberFormatException notANumber) { + return Optional.empty(); + } + } + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/CaveCeilingLayersSettings.java b/module/src/main/java/art/arcane/iris/modules/terrain/CaveCeilingLayersSettings.java new file mode 100644 index 000000000..e4d7f490b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/CaveCeilingLayersSettings.java @@ -0,0 +1,44 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.terrain; + +import art.arcane.iris.builtin.terrain.PaletteLayer; +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.List; + +/** + * The layers of material on the ceilings of caves in a biome, written as {@code "caveCeilingLayers": [...]}, the list of layers. + */ +@Desc("Layers of materials placed on cave ceilings in this biome, indexed upward from the ceiling surface. Must not have more entries than layers, whose height generators it reuses. Omitting this leaves cave ceilings unchanged.") +@Feature(id = "iris:terrain/cave-ceiling-layers", name = "Cave ceiling layers", key = "caveCeilingLayers", root = "layers", targets = Level.BIOME) +public final class CaveCeilingLayersSettings implements IrisFeature { + @Desc("Layers of materials placed on cave ceilings in this biome, indexed upward from the ceiling surface. Must not have more entries than layers, whose height generators it reuses. Omitting this leaves cave ceilings unchanged.") + private List layers = List.of(); + + public CaveCeilingLayersSettings() { + } + + public List layers() { + return layers == null ? List.of() : layers; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/ColumnSlope.java b/module/src/main/java/art/arcane/iris/modules/terrain/ColumnSlope.java new file mode 100644 index 000000000..c09d1dc84 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/ColumnSlope.java @@ -0,0 +1,24 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.modules.terrain; + +/** The slope of the terrain at a column, asked only when a layer limits where it shows by slope. */ +@FunctionalInterface +public interface ColumnSlope { + double at(double worldX, double worldZ); +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/ExplodeBiomePaletteSizeSettings.java b/module/src/main/java/art/arcane/iris/modules/terrain/ExplodeBiomePaletteSizeSettings.java new file mode 100644 index 000000000..ebf9b7267 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/ExplodeBiomePaletteSizeSettings.java @@ -0,0 +1,44 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.modules.terrain; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** How many barrier blocks a dimension puts between layers when it explodes its biome palettes, written as {@code "explodeBiomePaletteSize": 3}. */ +@Desc("Customize the palette height explosion") +@Feature(id = "iris:terrain/explode-palette-size", name = "Explode biome palette size", key = "explodeBiomePaletteSize", root = "size", targets = Level.DIMENSION) +public final class ExplodeBiomePaletteSizeSettings implements IrisFeature { + public static final int DEFAULT_SIZE = 3; + + @MinNumber(1) + @MaxNumber(16) + @Desc("Customize the palette height explosion") + private int size = DEFAULT_SIZE; + + public ExplodeBiomePaletteSizeSettings() { + } + + public int size() { + return size; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/ExplodeBiomePalettesSettings.java b/module/src/main/java/art/arcane/iris/modules/terrain/ExplodeBiomePalettesSettings.java new file mode 100644 index 000000000..a1bfea78e --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/ExplodeBiomePalettesSettings.java @@ -0,0 +1,38 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.modules.terrain; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** Whether a dimension puts barrier blocks between the layers of its biomes to show them apart, written as {@code "explodeBiomePalettes": true}. */ +@Desc("Vertically split up the biome palettes with barrier blocks in between to visualize them. The gap size comes from explodeBiomePaletteSize.") +@Feature(id = "iris:terrain/explode-palettes", name = "Explode biome palettes", key = "explodeBiomePalettes", root = "explode", targets = Level.DIMENSION) +public final class ExplodeBiomePalettesSettings implements IrisFeature { + @Desc("Vertically split up the biome palettes with barrier blocks in between to visualize them. The gap size comes from explodeBiomePaletteSize.") + private boolean explode = false; + + public ExplodeBiomePalettesSettings() { + } + + public boolean explode() { + return explode; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/FluidPaletteSettings.java b/module/src/main/java/art/arcane/iris/modules/terrain/FluidPaletteSettings.java new file mode 100644 index 000000000..75c725ae3 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/FluidPaletteSettings.java @@ -0,0 +1,47 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.terrain; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.block.BlockSpec; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.List; + +/** + * The blocks that fill ocean columns and cave aquifers of a dimension, written as {@code "fluidPalette": {...}}, a palette. A dimension without the key is water. + */ +@Desc("The dimension fluid block palette used for ocean columns and cave aquifers.") +@Feature(id = "iris:terrain/fluid-palette", name = "Fluid palette", key = "fluidPalette", root = "palette", targets = Level.DIMENSION) +public final class FluidPaletteSettings implements IrisFeature { + private static final String DEFAULT_BLOCK = "water"; + + @Desc("The dimension fluid block palette used for ocean columns and cave aquifers.") + private PaletteSpec palette = PaletteSpec.of(List.of(BlockSpec.of(DEFAULT_BLOCK))); + + public FluidPaletteSettings() { + } + + public PaletteSpec palette() { + return palette == null ? PaletteSpec.of(List.of(BlockSpec.of(DEFAULT_BLOCK))) : palette; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/HideOresSettings.java b/module/src/main/java/art/arcane/iris/modules/terrain/HideOresSettings.java new file mode 100644 index 000000000..432d533eb --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/HideOresSettings.java @@ -0,0 +1,46 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.terrain; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** + * A dimension's {@code hideOresForHiddenOre}: whether every ore block the generator would place is replaced with its base + * material. Written as the bare boolean. + */ +@Desc("When true, every ore block the generator would place (terrain ores, deposits, ores inside objects) is replaced with its base material such as stone, deepslate or netherrack, so drop-control plugins like HiddenOre can manage ore rewards themselves") +@Feature(id = "iris:terrain/hide-ores", name = "Hide ores", key = "hideOresForHiddenOre", root = "hide", targets = Level.DIMENSION) +public final class HideOresSettings implements IrisFeature { + @Desc("When true, every ore block the generator would place (terrain ores, deposits, ores inside objects) is replaced with its base material such as stone, deepslate or netherrack, so drop-control plugins like HiddenOre can manage ore rewards themselves") + private boolean hide = false; + + public HideOresSettings() { + } + + public HideOresSettings(boolean hide) { + this.hide = hide; + } + + public boolean hide() { + return hide; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/LayerBlocks.java b/module/src/main/java/art/arcane/iris/modules/terrain/LayerBlocks.java new file mode 100644 index 000000000..3f61e66ca --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/LayerBlocks.java @@ -0,0 +1,130 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.terrain; + +import art.arcane.iris.builtin.terrain.PaletteLayer; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.PackResources; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * What the blocks of the biomes' palette layers ({@link PaletteLayer}) are in one world, and which of them a layer picks + * where. Terrain, caves and post processing all pick from the same layers (a biome's wall is painted in caves and on + * cliffs), and a layer's block noise is built once per world, from the random of whichever of them asks first, as layers + * always were. So the picks live here, in the world's state under this class, which the compiled-in built-ins and the + * built-ins jar both see: one place, one noise per layer, whichever module asks. + */ +public final class LayerBlocks { + /** A layer without blocks picks none. */ + public static final int NONE = -1; + + private final PackResources resources; + private final Map picks = new ConcurrentHashMap<>(); + + private LayerBlocks(PackResources resources) { + this.resources = resources; + } + + /** The layer blocks of {@code world}. */ + public static LayerBlocks of(PackWorld world) { + return world.state(LayerBlocks.class, created -> new LayerBlocks(created.resources())); + } + + /** The layer's blocks resolved for the world's pack, each repeated by its weight: what an index from {@link #pick} names. */ + public List blocks(PaletteLayer layer) { + return picksOf(layer).blocks(); + } + + /** + * The index into {@link #blocks(PaletteLayer)} the layer picks at the position, or {@link #NONE} when it has no block. + * The noise is seeded from {@code parent} and {@code signature} the first time anyone asks about this layer; a pick + * outside the palette falls back to its first block. + */ + public int pick(PaletteLayer layer, RNG parent, int signature, double x, double y, double z) { + Picks layerPicks = picksOf(layer); + int size = layerPicks.blocks().size(); + if (size <= 1) { + return size - 1; + } + NoiseSampler sampler = layerPicks.noise(parent, signature); + double noise = layer.style().isSeeded() ? sampler.sample(x, z) : sampler.sample(x / layer.zoom(), y / layer.zoom(), z / layer.zoom()); + int index = (int) Math.round(noise * (size - 1)); + return index < 0 || index >= size ? 0 : index; + } + + private Picks picksOf(PaletteLayer layer) { + Picks known = picks.get(layer); + if (known != null) { + return known; + } + return picks.computeIfAbsent(layer, declared -> new Picks(declared, weighted(resources.blocks(), declared.palette()), resources)); + } + + private static List weighted(BlockRegistry registry, List palette) { + List weighted = new ArrayList<>(); + for (BlockSpec spec : palette) { + BlockState block = registry.resolve(spec); + for (int n = 0; n < spec.weight(); n++) { + weighted.add(block); + } + } + return List.copyOf(weighted); + } + + /** One layer's blocks and its block noise, built by the first caller. */ + private static final class Picks { + private final PaletteLayer layer; + private final List blocks; + private final PackResources resources; + private volatile NoiseSampler noise; + + Picks(PaletteLayer layer, List blocks, PackResources resources) { + this.layer = layer; + this.blocks = blocks; + this.resources = resources; + } + + List blocks() { + return blocks; + } + + NoiseSampler noise(RNG parent, int signature) { + NoiseSampler built = noise; + if (built != null) { + return built; + } + synchronized (this) { + if (noise == null) { + long seed = parent.nextParallelRNG(signature).nextParallelRNG(layer.minHeight() + layer.maxHeight() + blocks.size()).getSeed(); + noise = resources.noise().sampler(layer.style(), seed); + } + return noise; + } + } + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/LayerNoise.java b/module/src/main/java/art/arcane/iris/modules/terrain/LayerNoise.java new file mode 100644 index 000000000..daf2180c1 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/LayerNoise.java @@ -0,0 +1,37 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.modules.terrain; + +import com.volmit.noise.NoiseSampler; + +/** The noise that sets how thick a layer is: a number between a layer's limits at every column. */ +public final class LayerNoise { + private final NoiseSampler noise; + + LayerNoise(NoiseSampler noise) { + this.noise = noise; + } + + /** The whole number between {@code min} and {@code max} the noise gives at the column. */ + public int fit(int min, int max, double x, double z) { + if (min == max) { + return min; + } + return (int) Math.round(min + noise.sample(x, z) * (max - min)); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/LayeredBiome.java b/module/src/main/java/art/arcane/iris/modules/terrain/LayeredBiome.java new file mode 100644 index 000000000..ab5185d14 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/LayeredBiome.java @@ -0,0 +1,31 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.modules.terrain; + +import art.arcane.iris.builtin.terrain.LayersSettings; + + +/** + * What a biome declares about the layers of its ground: the layers of its surface, of its sea floor and of its cave ceilings, whether + * they are locked to the highest height the biome reaches, and its wall. A setting the biome does not declare is null. + */ +public record LayeredBiome(LayersSettings layers, SeaLayersSettings seaLayers, CaveCeilingLayersSettings ceilingLayers, + LockLayersSettings lock, LockLayersMaxSettings lockMax, WallSettings wall) { + /** A biome that declares nothing about its layers: the one layer of grass the settings default to. */ + public static final LayeredBiome UNDECLARED = new LayeredBiome(null, null, null, null, null, null); +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/LockLayersMaxSettings.java b/module/src/main/java/art/arcane/iris/modules/terrain/LockLayersMaxSettings.java new file mode 100644 index 000000000..68d543355 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/LockLayersMaxSettings.java @@ -0,0 +1,41 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.terrain; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** How many layers a locked biome iterates below the surface, written as {@code "lockLayersMax": 7}. A biome without the key iterates seven. */ +@Desc("The max layers to iterate below the surface for locked layer biomes (mesa).") +@Feature(id = "iris:terrain/lock-layers-max", name = "Lock layers max", key = "lockLayersMax", root = "layers", targets = Level.BIOME) +public final class LockLayersMaxSettings implements IrisFeature { + public static final int DEFAULT_LAYERS = 7; + + @Desc("The max layers to iterate below the surface for locked layer biomes (mesa).") + private int layers = DEFAULT_LAYERS; + + public LockLayersMaxSettings() { + } + + public int layers() { + return layers; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/LockLayersSettings.java b/module/src/main/java/art/arcane/iris/modules/terrain/LockLayersSettings.java new file mode 100644 index 000000000..0d0fa56e1 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/LockLayersSettings.java @@ -0,0 +1,39 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.terrain; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** Whether a biome's layers are locked to its highest possible height, written as {@code "lockLayers": true}. A biome without the key is not locked. */ +@Desc("Layers no longer descend from the surface block, they descend from the max possible height the biome can produce (constant) creating mesa like layers.") +@Feature(id = "iris:terrain/lock-layers", name = "Lock layers", key = "lockLayers", root = "locked", targets = Level.BIOME) +public final class LockLayersSettings implements IrisFeature { + @Desc("Layers no longer descend from the surface block, they descend from the max possible height the biome can produce (constant) creating mesa like layers.") + private boolean locked = false; + + public LockLayersSettings() { + } + + public boolean locked() { + return locked; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/OreGenerator.java b/module/src/main/java/art/arcane/iris/modules/terrain/OreGenerator.java new file mode 100644 index 000000000..7893b323a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/OreGenerator.java @@ -0,0 +1,80 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.terrain; + +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Range; +import com.volmit.noise.NoiseStyle; + +import java.util.List; + +/** + * One ore generator of a dimension, region or biome, an entry of its {@code ores} list: single ore blocks scattered + * through the terrain by a noise field, in a vertical band. A value of IrisApi types only; the terrain module resolves + * its blocks and builds its noise ({@code ResolvedOre}). + */ +@Desc("Scatters single ore blocks through terrain by sampling a noise field at every block in a vertical band. Defined on dimensions, regions, or biomes; the most specific level wins.") +public final class OreGenerator { + private static final double DEFAULT_THRESHOLD = 0.5; + private static final double DEFAULT_RANGE_MIN = 30; + private static final double DEFAULT_RANGE_MAX = 80; + + @Desc("The ore blocks to place. An empty palette generates nothing, so this must be set for the generator to have any effect.") + private PaletteSpec palette = PaletteSpec.of(List.of()); + + @Desc("The noise style sampled per block to decide where ore appears. STATIC gives independent random speckle; smoother styles give veiny clusters.") + private NoiseStyle chanceStyle = NoiseStyle.of("STATIC"); + + @Desc("When true this generator also replaces surface-layer blocks (it runs before layers and fluid); when false it only replaces underground rock.") + private boolean generateSurface = false; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Noise cutoff: a block becomes ore when the sampled noise is at or below this value, so higher means more ore. 0 disables, 1 replaces everything in range.") + private double threshold = DEFAULT_THRESHOLD; + + @Desc("Vertical band (min, max) this ore can generate in, in engine-local Y where 0 is the bottom of the dimension, not world Y.") + private Range range = Range.of(DEFAULT_RANGE_MIN, DEFAULT_RANGE_MAX); + + public OreGenerator() { + } + + public PaletteSpec palette() { + return palette; + } + + public NoiseStyle chanceStyle() { + return chanceStyle; + } + + public boolean generateSurface() { + return generateSurface; + } + + public double threshold() { + return threshold; + } + + public Range range() { + return range; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/OreSettings.java b/module/src/main/java/art/arcane/iris/modules/terrain/OreSettings.java new file mode 100644 index 000000000..47fd2fde0 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/OreSettings.java @@ -0,0 +1,50 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.terrain; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.Collections; +import java.util.List; + +/** + * The ore generators one dimension, region or biome declares, written as {@code "ores": [...]}, the list of generators. + * Levels stack: a column's ores come from its biome first, then its region, then the dimension. IrisApi types only, + * like {@link OreGenerator}. + */ +@Desc("Collection of ores to be generated") +@Feature(id = "iris:terrain/ores", name = "Ores", key = "ores", root = "generators", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) +public final class OreSettings implements IrisFeature { + @Desc("Collection of ores to be generated") + private List generators = List.of(); + + public OreSettings() { + } + + public OreSettings(List generators) { + this.generators = List.copyOf(generators); + } + + public List generators() { + return generators == null ? List.of() : Collections.unmodifiableList(generators); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/PaletteBlocks.java b/module/src/main/java/art/arcane/iris/modules/terrain/PaletteBlocks.java new file mode 100644 index 000000000..0264da295 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/PaletteBlocks.java @@ -0,0 +1,43 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.modules.terrain; + +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; + +import java.util.ArrayList; +import java.util.List; + +/** A palette's blocks, the way terrain layers and palettes always picked from them. */ +final class PaletteBlocks { + private PaletteBlocks() { + } + + /** The block of each spec, each repeated by its weight. */ + static List weighted(BlockRegistry registry, List palette) { + List weighted = new ArrayList<>(); + for (BlockSpec spec : palette) { + BlockState state = registry.resolve(spec); + for (int n = 0; n < spec.weight(); n++) { + weighted.add(state); + } + } + return List.copyOf(weighted); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/PaletteExplosion.java b/module/src/main/java/art/arcane/iris/modules/terrain/PaletteExplosion.java new file mode 100644 index 000000000..08ca17cc8 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/PaletteExplosion.java @@ -0,0 +1,34 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.modules.terrain; + +import com.volmit.config.FeatureSettings; + +/** Whether a dimension separates the layers of its biomes with barrier blocks to show them apart, and how many barriers it puts between them. */ +public record PaletteExplosion(boolean exploded, int size) { + public static final PaletteExplosion NONE = new PaletteExplosion(false, ExplodeBiomePaletteSizeSettings.DEFAULT_SIZE); + + /** What the dimension at the column of {@code settings} declares. */ + public static PaletteExplosion of(FeatureSettings settings, int worldX, int worldZ) { + boolean exploded = settings.at(ExplodeBiomePalettesSettings.class, worldX, worldZ).dimension() + .map(ExplodeBiomePalettesSettings::explode).orElse(false); + int size = settings.at(ExplodeBiomePaletteSizeSettings.class, worldX, worldZ).dimension() + .map(ExplodeBiomePaletteSizeSettings::size).orElse(ExplodeBiomePaletteSizeSettings.DEFAULT_SIZE); + return new PaletteExplosion(exploded, size); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/ResolvedLayer.java b/module/src/main/java/art/arcane/iris/modules/terrain/ResolvedLayer.java new file mode 100644 index 000000000..669cf51d6 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/ResolvedLayer.java @@ -0,0 +1,118 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.modules.terrain; + +import art.arcane.iris.builtin.prepare.SlopeClip; +import art.arcane.iris.builtin.terrain.PaletteLayer; +import art.arcane.volmlib.util.cache.AtomicCache; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseStyle; + +import java.util.List; +import java.util.function.Supplier; + +/** + * One {@link PaletteLayer} made ready for one world: its blocks, and the noise that decides how thick it is here, built when first + * asked for. Which block it picks where is the world's {@link LayerBlocks}, shared with every other module that picks from the layer. + * + *

The thickness noise is built once, from the random of whoever asks first, as the layers of a biome always were. + */ +public final class ResolvedLayer { + /** The style of the noise that sets a layer's thickness: Iris's signature noise. */ + private static final NoiseStyle THICKNESS_STYLE = NoiseStyle.of("IRIS"); + + private final PaletteLayer settings; + private final Supplier layerBlocks; + private final Supplier noise; + private final AtomicCache> blocks = new AtomicCache<>(); + private final AtomicCache heightNoise = new AtomicCache<>(); + + private ResolvedLayer(PaletteLayer settings, Supplier layerBlocks, Supplier noise) { + this.settings = settings; + this.layerBlocks = layerBlocks; + this.noise = noise; + } + + /** {@code settings} ready for the world whose layer blocks {@code layerBlocks} gives, asked for when first needed. */ + static ResolvedLayer of(PaletteLayer settings, Supplier layerBlocks, Supplier noise) { + return new ResolvedLayer(settings, layerBlocks, noise); + } + + public PaletteLayer settings() { + return settings; + } + + public int minHeight() { + return settings.minHeight(); + } + + public int maxHeight() { + return settings.maxHeight(); + } + + public double zoom() { + return settings.zoom(); + } + + /** How many blocks one step of the layer's block noise spans: its zoom, or 1 for a seeded style, which is read flat. */ + public double blocksPerSample() { + return settings.style().isSeeded() ? 1 : settings.zoom(); + } + + public SlopeClip slopeCondition() { + return settings.slopeCondition(); + } + + /** Whether the layer lists any block, which is not the same as picking one: a listed block may have no weight. */ + public boolean hasPalette() { + return !settings.palette().isEmpty(); + } + + /** The noise that sets the layer's thickness, built from {@code rng} unless an earlier caller's is already kept. */ + public LayerNoise heightNoise(RNG rng) { + LayerNoise cached = heightNoise.getIfPresent(); + if (cached != null) { + return cached; + } + + return heightNoise.aquire(() -> new LayerNoise(noise.get().sampler(THICKNESS_STYLE, + rng.nextParallelRNG(settings.minHeight() * settings.maxHeight() + blocks().size()).getSeed()))); + } + + /** The layer's block at the position, picked as {@link LayerBlocks#pick} says, or null when the palette has no block. */ + public BlockState get(RNG parent, int signature, double x, double y, double z) { + int index = layerBlocks.get().pick(settings, parent, signature, x, y, z); + return index == LayerBlocks.NONE ? null : blocks().get(index); + } + + /** {@link #get(RNG, int, double, double, double)} for a layer asked once per column, such as a slab or a wall. */ + public BlockState get(RNG rng, double x, double y, double z) { + return get(rng, 0, x, y, z); + } + + private List blocks() { + List cached = blocks.getIfPresent(); + if (cached != null) { + return cached; + } + + return blocks.aquire(() -> layerBlocks.get().blocks(settings)); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/RockPaletteSettings.java b/module/src/main/java/art/arcane/iris/modules/terrain/RockPaletteSettings.java new file mode 100644 index 000000000..21cc14f94 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/RockPaletteSettings.java @@ -0,0 +1,47 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.terrain; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.block.BlockSpec; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.List; + +/** + * The blocks that fill terrain below the layers of a dimension, written as {@code "rockPalette": {...}}, a palette. A dimension without the key is stone. + */ +@Desc("The palette of blocks for 'stone'") +@Feature(id = "iris:terrain/rock-palette", name = "Rock palette", key = "rockPalette", root = "palette", targets = Level.DIMENSION) +public final class RockPaletteSettings implements IrisFeature { + private static final String DEFAULT_BLOCK = "stone"; + + @Desc("The palette of blocks for 'stone'") + private PaletteSpec palette = PaletteSpec.of(List.of(BlockSpec.of(DEFAULT_BLOCK))); + + public RockPaletteSettings() { + } + + public PaletteSpec palette() { + return palette == null ? PaletteSpec.of(List.of(BlockSpec.of(DEFAULT_BLOCK))) : palette; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/SeaLayersSettings.java b/module/src/main/java/art/arcane/iris/modules/terrain/SeaLayersSettings.java new file mode 100644 index 000000000..9354ca99f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/SeaLayersSettings.java @@ -0,0 +1,44 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.terrain; + +import art.arcane.iris.builtin.terrain.PaletteLayer; +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.List; + +/** + * The layers of material filling the water column of a sea biome, written as {@code "seaLayers": [...]}, the list of layers. + */ +@Desc("Layers of materials filling the water column of sea biomes, indexed downward from the water surface. Anything below the last layer is filled with the dimension fluid palette, not stone.") +@Feature(id = "iris:terrain/sea-layers", name = "Sea layers", key = "seaLayers", root = "layers", targets = Level.BIOME) +public final class SeaLayersSettings implements IrisFeature { + @Desc("Layers of materials filling the water column of sea biomes, indexed downward from the water surface. Anything below the last layer is filled with the dimension fluid palette, not stone.") + private List layers = List.of(); + + public SeaLayersSettings() { + } + + public List layers() { + return layers == null ? List.of() : layers; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/SlabSettings.java b/module/src/main/java/art/arcane/iris/modules/terrain/SlabSettings.java new file mode 100644 index 000000000..f5adfc3c0 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/SlabSettings.java @@ -0,0 +1,42 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.terrain; + +import art.arcane.iris.builtin.terrain.PaletteLayer; +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** + * The slab post processing places on steps in a biome, written as {@code "slab": {...}}, one layer. A biome without the key has no slab. + */ +@Desc("The default slab if iris decides to place a slab in this biome. Default is no slab.") +@Feature(id = "iris:terrain/slab", name = "Slab", key = "slab", root = "layer", targets = Level.BIOME) +public final class SlabSettings implements IrisFeature { + @Desc("The default slab if iris decides to place a slab in this biome. Default is no slab.") + private PaletteLayer layer = PaletteLayer.withoutBlocks(); + + public SlabSettings() { + } + + public PaletteLayer layer() { + return layer == null ? PaletteLayer.withoutBlocks() : layer; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/TerrainPalettes.java b/module/src/main/java/art/arcane/iris/modules/terrain/TerrainPalettes.java new file mode 100644 index 000000000..5f56d978d --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/TerrainPalettes.java @@ -0,0 +1,140 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.modules.terrain; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.volmlib.util.cache.AtomicCache; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.block.PaletteSpec; +import com.volmit.config.SettingsStack; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; +import com.volmit.world.UpperDimension; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * What the terrain module keeps for one world about the palettes that fill its terrain: the rock below the biomes' layers + * and the fluid of its oceans and aquifers, as a block for every column, and the rock of an upper dimension. They are the + * dimension's {@link RockPaletteSettings} and {@link FluidPaletteSettings}. + * + *

The noise of a palette is seeded from the world's complex seed and a signature of its own, as the complex always did, so + * a column's rock and fluid do not depend on who asks first. + */ +public final class TerrainPalettes { + private static final int ROCK_SIGNATURE = 45; + private static final int FLUID_SIGNATURE = 78; + /** The salt Iris's material palettes always added to the seed of the noise that picks their blocks. */ + private static final int PALETTE_NOISE_SALT = -23_498_896; + + /** A block for every column. */ + @FunctionalInterface + public interface ColumnBlocks { + /** The block at the column, or null when the palette has no block. */ + BlockState at(double x, double z); + } + + private final PackWorld world; + private final long complexSeed; + private final AtomicCache rock = new AtomicCache<>(); + private final AtomicCache fluid = new AtomicCache<>(); + private final Map upperRocks = new ConcurrentHashMap<>(); + + TerrainPalettes(PackWorld world) { + this.world = world; + this.complexSeed = world.seed(IrisSeedPurposes.COMPLEX); + } + + /** The palettes of {@code world}. */ + public static TerrainPalettes of(PackWorld world) { + return world.state(TerrainPalettes.class, TerrainPalettes::new); + } + + /** Builds the rock and fluid noise now instead of when first asked for. */ + public void warm() { + rock(); + fluid(); + } + + /** The rock at the column, below the biome's layers. */ + public BlockState rockAt(double x, double z) { + return rock().at(x, z); + } + + /** The fluid at the column, above the terrain up to the fluid height. */ + public BlockState fluidAt(double x, double z) { + return fluid().at(x, z); + } + + /** The rock at the column of the upper dimension: the world's own when the upper dimension is the dimension itself. */ + public BlockState upperRockAt(UpperDimension upper, double x, double z) { + return upperRocks.computeIfAbsent(upper.id(), id -> upperRock(upper, x, z)).at(x, z); + } + + private ColumnBlocks rock() { + return rock.aquireOrThrow(() -> columns(rockPalette(world.settings().declared(RockPaletteSettings.class)), complexRng().nextParallelRNG(ROCK_SIGNATURE), + world.resources())); + } + + private ColumnBlocks fluid() { + return fluid.aquireOrThrow(() -> columns(fluidPalette(world.settings().declared(FluidPaletteSettings.class)), complexRng().nextParallelRNG(FLUID_SIGNATURE), + world.resources())); + } + + private RNG complexRng() { + return new RNG(complexSeed); + } + + private ColumnBlocks upperRock(UpperDimension upper, double x, double z) { + if (upper.isThisDimension()) { + return rock(); + } + + // Iris seeded this from the dimension's key; the id's path is that key for every key an id can hold unchanged. + long seedOffset = upper.id().path().hashCode(); + RNG rng = new RNG(complexSeed ^ seedOffset); + SettingsStack declared = upper.settings().at(RockPaletteSettings.class, (int) x, (int) z); + return columns(rockPalette(declared), rng.nextParallelRNG(ROCK_SIGNATURE), upper.resources()); + } + + private static PaletteSpec rockPalette(SettingsStack declared) { + return declared.dimension().orElseGet(RockPaletteSettings::new).palette(); + } + + private static PaletteSpec fluidPalette(SettingsStack declared) { + return declared.dimension().orElseGet(FluidPaletteSettings::new).palette(); + } + + /** The palette's blocks over the columns, picked by its noise: the noise at a column, from 0 to 1, is how far down the weighted list the block is. */ + private static ColumnBlocks columns(PaletteSpec palette, RNG rng, PackResources resources) { + List blocks = PaletteBlocks.weighted(resources.blocks(), palette.palette()); + if (blocks.isEmpty()) { + return (x, z) -> null; + } + + long seed = rng.getSeed() + (PALETTE_NOISE_SALT + blocks.size()); + NoiseSampler noise = resources.noise().sampler(palette.style(), seed); + int last = blocks.size() - 1; + return (x, z) -> blocks.get((int) Math.round(noise.sample(x, z) * last)); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/terrain/WallSettings.java b/module/src/main/java/art/arcane/iris/modules/terrain/WallSettings.java new file mode 100644 index 000000000..06d5fa6a5 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/terrain/WallSettings.java @@ -0,0 +1,43 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.terrain; + +import art.arcane.iris.builtin.terrain.PaletteLayer; +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** + * The wall post processing paints on steep faces, and caves paint on their walls, in a biome, written as {@code "wall": {...}}, one layer. + * A biome without the key has no wall. + */ +@Desc("The default wall if iris decides to place a wall higher than 2 blocks (steep hills or possibly cliffs)") +@Feature(id = "iris:terrain/wall", name = "Wall", key = "wall", root = "layer", targets = Level.BIOME) +public final class WallSettings implements IrisFeature { + @Desc("The default wall if iris decides to place a wall higher than 2 blocks (steep hills or possibly cliffs)") + private PaletteLayer layer = PaletteLayer.withoutBlocks(); + + public WallSettings() { + } + + public PaletteLayer layer() { + return layer == null ? PaletteLayer.withoutBlocks() : layer; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/vanillafeatures/ImportedFeaturesSettings.java b/module/src/main/java/art/arcane/iris/modules/vanillafeatures/ImportedFeaturesSettings.java new file mode 100644 index 000000000..45d40f88f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/vanillafeatures/ImportedFeaturesSettings.java @@ -0,0 +1,76 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modules.vanillafeatures; + +import com.volmit.config.Level; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.vanilla.DecorationStep; + +import java.util.Collections; +import java.util.List; + +/** + * Whether a dimension runs the platform's own placed features over its terrain, written as + * {@code "importedFeatures": {"enabled": true, "disabledSteps": ["VEGETAL_DECORATION"]}}: the switch, and the features and + * decoration steps it leaves out. IrisApi types only. + */ +@Desc("Controls native vanilla, mod, and ingested datapack PLACED FEATURE generation for this dimension. Placed features are ores, trees, plants, springs, geodes and every other decoration entry a biome declares. This is OFF by default: with 'enabled' false Iris generates exactly the terrain it always has and no native feature runs. With it true, every placed feature the biome's vanilla derivative declares runs over Iris terrain, in vanilla step order, on the same worldgen thread vanilla uses. Carvers are never imported - Iris has no NoiseGeneratorSettings, so there is nothing for a carver to carve against. Family matching on 'disabled' uses namespace, slash, or underscore boundaries, so 'minecraft:ore' covers every vanilla ore feature without matching unrelated names.") +@Feature(id = "iris:vanilla-features", name = "Vanilla features", key = "importedFeatures", targets = Level.DIMENSION) +public final class ImportedFeaturesSettings implements IrisFeature { + @Desc("Master switch. False (the default) means no native placed feature generates and chunk output is identical to a pack without this block at all. True runs the vanilla decoration feature pass over Iris terrain.") + private boolean enabled = false; + + @Desc("Placed feature keys to deny explicitly, e.g. 'minecraft:ore_diamond'. A namespace:path prefix also matches, so 'minecraft:ore' denies every vanilla ore and 'minecraft:trees' denies every tree placement. Every key not matched here generates while 'enabled' is true.") + private List disabled = List.of(); + + @Desc("Restrict feature generation to these decoration steps only. Empty (the default) means every step is eligible. Use this to import ores without importing vegetation: set it to UNDERGROUND_ORES.") + private List steps = List.of(); + + @Desc("Decoration steps to deny. Applied after 'steps', so a step listed here never generates even if 'steps' allows it. VEGETAL_DECORATION is the usual entry for packs that grow their own trees.") + private List disabledSteps = List.of(); + + public ImportedFeaturesSettings() { + } + + /** Whether the platform's placed features run over the dimension's terrain. */ + public boolean enabled() { + return enabled; + } + + /** Family patterns of the placed features the dimension leaves out. */ + public List disabled() { + return listOrEmpty(disabled); + } + + /** The only decoration steps whose features generate; empty for every step. */ + public List steps() { + return listOrEmpty(steps); + } + + /** Decoration steps whose features never generate, whatever {@link #steps} says. */ + public List disabledSteps() { + return listOrEmpty(disabledSteps); + } + + private static List listOrEmpty(List list) { + return list == null ? List.of() : Collections.unmodifiableList(list); + } +}