mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-27 00:04:42 +00:00
Batch 5 of the API review: build the built-ins against the Iris API alone
IrisModule is a Gradle Java build of its own. Its compile classpath is com.volmit:iris-api (never iris-host), VolmLib (sibling checkout or the published coordinate, as Iris resolves it), Gson, Lombok and the JDK, all compileOnly, with Iris's compiler options and Lombok config. check compiles every source and builds build/libs/iris-builtins.jar from these classes with IrisApi's ModuleJarCheck; the jar is byte-identical to the one Iris built before. Iris consumes it through the capability art.arcane:iris-builtins. The 111 sources that need Iris itself move to Iris core: the layout model (biomes, regions, dimensions and their types, generators, noise styles, expressions, images and image maps), the pack's objects, blocks and matter objects, mods and compat filters, the structure model with its assembler, locator, fitting and placer (behind StructureHost), and the object placers behind ObjectHost and FloatingHost. Nothing left here reaches Iris core, engine, platform or util. source-patterns.txt and the tasks that ran Iris's build (checkBuiltins, packageBuiltinModulesInIris, builtinSourcesJar) are gone.
This commit is contained in:
1 parent
9b94eecae3
commit
136f57fa73
117 files changed
+228
-24528
No files matched your search
@@ -1,8 +1,8 @@
|
||||
# Iris default module
|
||||
|
||||
This project owns the built-in Iris feature and setting sources under
|
||||
`src/main/java/art/arcane/iris/engine`. The files retain their existing packages, pack fields and
|
||||
direct dependencies on Iris internals.
|
||||
`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`,
|
||||
@@ -145,34 +145,38 @@ Every built-in stage is a full port: the module owns its logic and per-engine st
|
||||
work out their reach from the pack when it loads. A dimension's `disabledComponents` turns a mantle stage off
|
||||
by its flag (`CARVED`, `OBJECT`, `FLOATING_OBJECT`, `JIGSAW`) or by its stage id.
|
||||
|
||||
Iris core and these sources still depend on each other. The Iris host build therefore compiles them
|
||||
together as one source set. This keeps the existing class names and platform artifacts while the
|
||||
features remain in a single physical source tree. It does not create an independent plugin artifact.
|
||||
## Building
|
||||
|
||||
`source-patterns.txt` records the module's source ownership. The host's
|
||||
`:core:verifyDefaultModuleOwnership` task rejects declared feature sources in core, undeclared Java
|
||||
files here, and missing source families. `:core:bukkitPurityRatchet` checks this tree alongside
|
||||
core against the existing allowlist.
|
||||
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=<path>` 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.
|
||||
|
||||
From this directory, run `./gradlew check` to invoke the Iris host's joint compilation and purity
|
||||
check and build the module sources archive. Run `./gradlew builtinSourcesJar` to build just the
|
||||
archive. The host project also provides `:core:defaultModuleSourcesJar` for the same source tree.
|
||||
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 model with its assembler, locator, fitting
|
||||
and placer (behind `StructureHost`), and the object placers behind `ObjectHost` and `FloatingHost`.
|
||||
|
||||
`./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
|
||||
|
||||
Iris builds the built-in modules as an ordinary pack module jar, `iris-builtins.jar`, and bundles it into the plugin:
|
||||
Iris's `:core:builtinModulesJar` packages it from core's compiled classes, so it always fits the Iris it ships with, and
|
||||
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`
|
||||
here runs that task and copies the jar to `build/libs/iris-builtins.jar`. `builtin-modules.txt` lists what goes in:
|
||||
`module <class>` lines (the jar's entry points, written to `META-INF/services/com.volmit.IrisModule`) and `include <pattern>`
|
||||
lines for further classes. The plugin's own classes leave those classes out; Iris's Bukkit artifact check fails the build if
|
||||
core still uses one of them.
|
||||
Before the jar is used, `ModuleJarCheck` of IrisApi runs the class checks of a pack load on it, with the packages Iris
|
||||
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 <class>` lines
|
||||
(the jar's entry points, written to `META-INF/services/com.volmit.IrisModule`) and `include <pattern>` 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); a listed class that uses Iris internals fails the task naming the class and what it uses. A VolmLib class that
|
||||
Iris's Bukkit jar strips (the list is Iris's `core/volmlib-left-out-of-bukkit-jar.txt`, which its shadowJar reads too) is on
|
||||
that classpath but missing on a server, so the check treats it as missing and fails the task naming it. `check` runs the task.
|
||||
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
|
||||
|
||||
+155
-38
@@ -1,62 +1,179 @@
|
||||
import org.gradle.jvm.tasks.Jar
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
plugins {
|
||||
base
|
||||
`java-base`
|
||||
`java-library`
|
||||
}
|
||||
|
||||
group = "art.arcane"
|
||||
version = "1.0-SNAPSHOT"
|
||||
|
||||
val irisRoot = rootDir.resolve("../Iris").canonicalFile
|
||||
val moduleSources = layout.projectDirectory.dir("src/main/java")
|
||||
|
||||
tasks.register<Jar>("builtinSourcesJar") {
|
||||
group = "build"
|
||||
description = "Packages the built-in Iris sources owned by this module."
|
||||
archiveBaseName.set("iris-default-module")
|
||||
archiveClassifier.set("sources")
|
||||
destinationDirectory.set(layout.buildDirectory.dir("libs"))
|
||||
inputs.dir(moduleSources)
|
||||
from(moduleSources)
|
||||
base {
|
||||
archivesName.set("iris-module")
|
||||
}
|
||||
|
||||
val checkBuiltins = tasks.register<Exec>("checkBuiltins") {
|
||||
group = "verification"
|
||||
description = "Compiles the built-ins with Iris and checks source ownership and Bukkit purity."
|
||||
workingDir(irisRoot)
|
||||
commandLine(
|
||||
"./gradlew",
|
||||
":core:compileJava",
|
||||
":core:bukkitPurityRatchet",
|
||||
"-PincludeModdedAdapters=false",
|
||||
"--console=plain",
|
||||
)
|
||||
java {
|
||||
toolchain.languageVersion.set(JavaLanguageVersion.of(25))
|
||||
withSourcesJar()
|
||||
}
|
||||
|
||||
// The built-ins as a pack module jar. Iris packages and checks it from its own compiled classes (core's builtinModulesJar,
|
||||
// which reads builtin-modules.txt) and bundles it into the plugin; this copies it to build/libs for other hosts and tools.
|
||||
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<JavaCompile>("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 <class>" (an entry point, with its nested classes) or "include <ant pattern>".
|
||||
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")
|
||||
|
||||
val packageBuiltinModulesInIris = tasks.register<Exec>("packageBuiltinModulesInIris") {
|
||||
description = "Runs Iris's :core:builtinModulesJar, which compiles Iris with the built-ins, packages and checks the jar."
|
||||
workingDir(irisRoot)
|
||||
val offline = if (gradle.startParameter.isOffline) listOf("--offline") else emptyList()
|
||||
commandLine(listOf("./gradlew", ":core:builtinModulesJar", "-PincludeModdedAdapters=false", "--console=plain") + offline)
|
||||
data class BuiltinModulesList(val moduleClasses: List<String>, val classPatterns: List<String>)
|
||||
|
||||
fun readBuiltinModulesList(): BuiltinModulesList {
|
||||
val moduleClasses = mutableListOf<String>()
|
||||
val classPatterns = mutableListOf<String>()
|
||||
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)
|
||||
}
|
||||
|
||||
tasks.register<Copy>("builtinModulesJar") {
|
||||
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<Jar>("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<JavaExec>("builtinModulesJar") {
|
||||
group = "build"
|
||||
description = "Copies the checked jar Iris built to build/libs/$builtinModulesJarName, the built-in modules as a pack module jar."
|
||||
dependsOn(packageBuiltinModulesInIris)
|
||||
from(irisRoot.resolve("core/build/builtin-modules/$builtinModulesJarName"))
|
||||
into(layout.buildDirectory.dir("libs"))
|
||||
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(checkBuiltins, "builtinSourcesJar", "builtinModulesJar")
|
||||
dependsOn(builtinModulesJar)
|
||||
}
|
||||
|
||||
tasks.named("assemble") {
|
||||
dependsOn("builtinSourcesJar")
|
||||
dependsOn(builtinModulesJar)
|
||||
}
|
||||
@@ -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
|
||||
+2
-3
@@ -1,6 +1,5 @@
|
||||
# These sources compile together with Iris core and must generate the same members, so this repeats
|
||||
# ../Iris/lombok.config, which Lombok never reaches from here: it looks upward from each source file.
|
||||
# Keep the two in sync; ../Iris/lombok.config explains each setting.
|
||||
# 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
|
||||
+40
-2
@@ -1,4 +1,42 @@
|
||||
rootProject.name = "IrisModule"
|
||||
|
||||
// Keep the public API discoverable when importing the default module.
|
||||
includeBuild("../IrisApi")
|
||||
// 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=<path> 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"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
art/arcane/iris/engine/actuator/**
|
||||
art/arcane/iris/engine/decorator/**
|
||||
art/arcane/iris/engine/modifier/**
|
||||
art/arcane/iris/engine/mantle/components/**
|
||||
art/arcane/iris/engine/object/**
|
||||
art/arcane/iris/engine/image/**
|
||||
art/arcane/iris/engine/framework/structure/**
|
||||
art/arcane/iris/engine/framework/vanillafeatures/**
|
||||
art/arcane/iris/engine/framework/StructureAssembler.java
|
||||
art/arcane/iris/engine/framework/IrisStructureLocator.java
|
||||
art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java
|
||||
art/arcane/iris/engine/framework/StructurePlacementScope.java
|
||||
art/arcane/iris/engine/framework/StructurePlacementGrid.java
|
||||
art/arcane/iris/engine/framework/StructureVerticalBounds.java
|
||||
art/arcane/iris/engine/framework/PlacedObject.java
|
||||
art/arcane/iris/engine/framework/PlacedStructurePiece.java
|
||||
art/arcane/iris/builtin/**
|
||||
art/arcane/iris/engine/loot/**
|
||||
art/arcane/iris/engine/spawn/**
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,37 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.framework;
|
||||
|
||||
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class PlacedObject {
|
||||
@Nullable
|
||||
private IrisObjectPlacement placement;
|
||||
@Nullable
|
||||
private IrisObject object;
|
||||
private int id;
|
||||
private int xx;
|
||||
private int zz;
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.framework;
|
||||
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObjectRotation;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class PlacedStructurePiece {
|
||||
private final IrisJigsawPiece piece;
|
||||
private final IrisObject object;
|
||||
private final int x;
|
||||
private final int y;
|
||||
private final int z;
|
||||
private final IrisObjectRotation rotation;
|
||||
private final int minX;
|
||||
private final int minY;
|
||||
private final int minZ;
|
||||
private final int maxX;
|
||||
private final int maxY;
|
||||
private final int maxZ;
|
||||
|
||||
public boolean intersects(PlacedStructurePiece o) {
|
||||
long maxExclusiveX = (long) maxX + 1L;
|
||||
long maxExclusiveY = (long) maxY + 1L;
|
||||
long maxExclusiveZ = (long) maxZ + 1L;
|
||||
long otherMaxExclusiveX = (long) o.maxX + 1L;
|
||||
long otherMaxExclusiveY = (long) o.maxY + 1L;
|
||||
long otherMaxExclusiveZ = (long) o.maxZ + 1L;
|
||||
return minX < otherMaxExclusiveX && maxExclusiveX > o.minX
|
||||
&& minY < otherMaxExclusiveY && maxExclusiveY > o.minY
|
||||
&& minZ < otherMaxExclusiveZ && maxExclusiveZ > o.minZ;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,360 +0,0 @@
|
||||
package art.arcane.iris.engine.framework;
|
||||
|
||||
import art.arcane.iris.builtin.carve.CaveLavaHeightSettings;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.builtin.structure.StructureAnchorMode;
|
||||
import art.arcane.iris.builtin.structure.StructurePlacement;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.volmlib.util.matter.MatterCavern;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.function.IntPredicate;
|
||||
|
||||
public final class StructureCaveAnchorResolver {
|
||||
private static final int CHUNK_COLUMN_COUNT = 256;
|
||||
private static final int MAX_ATTEMPTS = 64;
|
||||
private static final int MAX_SCAN_STEP = 16;
|
||||
private static final int MAX_CLEARANCE = 64;
|
||||
private static final int MAX_GENERIC_CENTER_SEARCH = 4096;
|
||||
private static final byte LIQUID_FORCED_AIR = 3;
|
||||
|
||||
private StructureCaveAnchorResolver() {
|
||||
}
|
||||
|
||||
public static Anchor resolve(Engine engine, StructurePlacement placement, int chunkX, int chunkZ, RNG rng) {
|
||||
Objects.requireNonNull(engine, "Cave structure anchor requires an engine");
|
||||
Objects.requireNonNull(placement, "Cave structure anchor requires a placement");
|
||||
Objects.requireNonNull(rng, "Cave structure anchor requires a random source");
|
||||
StructureAnchorMode mode = placement.resolvedAnchor();
|
||||
if (!mode.isCave() || engine.getMantle() == null || engine.getMantle().getMantle() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int worldMin = engine.getMinHeight() + 1;
|
||||
int worldMax = engine.getMinHeight() + engine.getHeight() - 2;
|
||||
int minimumY = Math.max(worldMin, Math.min(placement.minHeight(), placement.maxHeight()));
|
||||
int maximumY = Math.min(worldMax, Math.max(placement.minHeight(), placement.maxHeight()));
|
||||
if (minimumY > maximumY) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int attempts = Math.min(MAX_ATTEMPTS, Math.max(1, placement.caveAnchorAttempts()));
|
||||
int scanStep = Math.min(MAX_SCAN_STEP, Math.max(1, placement.caveAnchorScanStep()));
|
||||
int clearance = Math.min(MAX_CLEARANCE, Math.max(1, placement.caveMinimumClearance()));
|
||||
int chunkMinX = chunkX << 4;
|
||||
int chunkMinZ = chunkZ << 4;
|
||||
int[] candidateColumns = candidateColumnIndices(rng, attempts);
|
||||
for (int candidateColumn : candidateColumns) {
|
||||
int blockX = chunkMinX + (candidateColumn & 15);
|
||||
int blockZ = chunkMinZ + (candidateColumn >>> 4);
|
||||
List<Integer> anchors = anchorsInColumn(
|
||||
engine, placement, mode, blockX, blockZ,
|
||||
minimumY, maximumY, scanStep, clearance);
|
||||
if (!anchors.isEmpty()) {
|
||||
return new Anchor(blockX, anchors.get(rng.nextInt(anchors.size())), blockZ);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static int[] candidateColumnIndices(RNG rng, int attempts) {
|
||||
Objects.requireNonNull(rng, "Cave structure column selection requires a random source");
|
||||
int count = Math.min(MAX_ATTEMPTS, Math.max(1, attempts));
|
||||
int start = rng.nextInt(CHUNK_COLUMN_COUNT);
|
||||
int stride = (rng.nextInt(CHUNK_COLUMN_COUNT / 2) * 2) + 1;
|
||||
int[] columns = new int[count];
|
||||
for (int index = 0; index < count; index++) {
|
||||
columns[index] = (start + (index * stride)) & (CHUNK_COLUMN_COUNT - 1);
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
|
||||
static List<Integer> anchorsInColumn(
|
||||
Engine engine,
|
||||
StructurePlacement placement,
|
||||
StructureAnchorMode mode,
|
||||
int blockX,
|
||||
int blockZ,
|
||||
int minimumY,
|
||||
int maximumY,
|
||||
int scanStep,
|
||||
int clearance
|
||||
) {
|
||||
if (mode == StructureAnchorMode.CAVE_CENTER) {
|
||||
return centerAnchorsInColumn(
|
||||
engine, placement, blockX, blockZ,
|
||||
minimumY, maximumY, scanStep, clearance);
|
||||
}
|
||||
List<Integer> anchors = new ArrayList<>();
|
||||
int step = Math.max(1, scanStep);
|
||||
for (int worldY = minimumY; worldY <= maximumY; worldY += step) {
|
||||
int mantleY = toMantleY(worldY, engine.getMinHeight());
|
||||
if (!matchesGeometry(engine, mode, blockX, mantleY, blockZ, clearance)) {
|
||||
continue;
|
||||
}
|
||||
if (!matchesAnchorFluid(engine, placement, blockX, mantleY, blockZ)) {
|
||||
continue;
|
||||
}
|
||||
if (!matchesBiome(engine, placement, blockX, mantleY, blockZ)) {
|
||||
continue;
|
||||
}
|
||||
anchors.add(worldY);
|
||||
}
|
||||
return List.copyOf(anchors);
|
||||
}
|
||||
|
||||
private static List<Integer> centerAnchorsInColumn(
|
||||
Engine engine,
|
||||
StructurePlacement placement,
|
||||
int blockX,
|
||||
int blockZ,
|
||||
int minimumY,
|
||||
int maximumY,
|
||||
int scanStep,
|
||||
int clearance
|
||||
) {
|
||||
List<Integer> anchors = new ArrayList<>();
|
||||
int step = Math.max(1, scanStep);
|
||||
int worldOffset = engine.getMinHeight();
|
||||
int minimumMantleY = 0;
|
||||
int maximumMantleY = engine.getHeight() - 1;
|
||||
int processedThroughWorldY = Integer.MIN_VALUE;
|
||||
IntPredicate carved = y -> isCarved(engine, blockX, y, blockZ);
|
||||
for (int worldY = minimumY; worldY <= maximumY; worldY += step) {
|
||||
if (worldY <= processedThroughWorldY) {
|
||||
continue;
|
||||
}
|
||||
int mantleY = toMantleY(worldY, worldOffset);
|
||||
if (!carved.test(mantleY)) {
|
||||
continue;
|
||||
}
|
||||
int lower = cavernLowerBound(carved, mantleY, minimumMantleY);
|
||||
int upper = cavernUpperBound(carved, mantleY, maximumMantleY);
|
||||
processedThroughWorldY = upper + worldOffset;
|
||||
if ((long) upper - lower + 1L < Math.max(1, clearance)) {
|
||||
continue;
|
||||
}
|
||||
int lowerCenterWorldY = lower + Math.floorDiv(upper - lower, 2) + worldOffset;
|
||||
addCenterAnchor(
|
||||
anchors, engine, placement, blockX, blockZ,
|
||||
lowerCenterWorldY, minimumY, maximumY);
|
||||
int upperCenterWorldY = lower + Math.ceilDiv(upper - lower, 2) + worldOffset;
|
||||
if (upperCenterWorldY != lowerCenterWorldY) {
|
||||
addCenterAnchor(
|
||||
anchors, engine, placement, blockX, blockZ,
|
||||
upperCenterWorldY, minimumY, maximumY);
|
||||
}
|
||||
}
|
||||
return List.copyOf(anchors);
|
||||
}
|
||||
|
||||
private static void addCenterAnchor(
|
||||
List<Integer> anchors,
|
||||
Engine engine,
|
||||
StructurePlacement placement,
|
||||
int blockX,
|
||||
int blockZ,
|
||||
int worldY,
|
||||
int minimumY,
|
||||
int maximumY
|
||||
) {
|
||||
if (worldY < minimumY || worldY > maximumY) {
|
||||
return;
|
||||
}
|
||||
int mantleY = toMantleY(worldY, engine.getMinHeight());
|
||||
if (matchesAnchorFluid(engine, placement, blockX, mantleY, blockZ)
|
||||
&& matchesBiome(engine, placement, blockX, mantleY, blockZ)) {
|
||||
anchors.add(worldY);
|
||||
}
|
||||
}
|
||||
|
||||
static boolean matchesGeometry(
|
||||
Engine engine,
|
||||
StructureAnchorMode mode,
|
||||
int blockX,
|
||||
int mantleY,
|
||||
int blockZ,
|
||||
int clearance
|
||||
) {
|
||||
IntPredicate carved = y -> isCarved(engine, blockX, y, blockZ);
|
||||
if (mode == StructureAnchorMode.CAVE_CENTER) {
|
||||
return matchesCenterGeometry(
|
||||
carved, mantleY, Math.max(1, clearance), 0, engine.getHeight() - 1);
|
||||
}
|
||||
return matchesGeometry(carved, mode, mantleY, clearance);
|
||||
}
|
||||
|
||||
static boolean matchesGeometry(
|
||||
IntPredicate carved,
|
||||
StructureAnchorMode mode,
|
||||
int mantleY,
|
||||
int clearance
|
||||
) {
|
||||
if (!carved.test(mantleY)) {
|
||||
return false;
|
||||
}
|
||||
int required = Math.max(1, clearance);
|
||||
return switch (mode) {
|
||||
case CAVE_FLOOR -> !carved.test(mantleY - 1)
|
||||
&& carvedRun(carved, mantleY, 1, required);
|
||||
case CAVE_CEILING -> !carved.test(mantleY + 1)
|
||||
&& carvedRun(carved, mantleY, -1, required);
|
||||
case CAVE_CENTER -> matchesCenterGeometry(
|
||||
carved, mantleY, required,
|
||||
saturatedSubtract(mantleY, MAX_GENERIC_CENTER_SEARCH),
|
||||
saturatedAdd(mantleY, MAX_GENERIC_CENTER_SEARCH));
|
||||
case CAVE_ANY -> carvedRun(
|
||||
carved, mantleY - Math.floorDiv(required - 1, 2), 1, required);
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean matchesCenterGeometry(
|
||||
IntPredicate carved,
|
||||
int mantleY,
|
||||
int clearance,
|
||||
int minimumY,
|
||||
int maximumY
|
||||
) {
|
||||
if (!carved.test(mantleY)) {
|
||||
return false;
|
||||
}
|
||||
int lower = cavernLowerBound(carved, mantleY, minimumY);
|
||||
int upper = cavernUpperBound(carved, mantleY, maximumY);
|
||||
if ((long) upper - lower + 1L < clearance) {
|
||||
return false;
|
||||
}
|
||||
int lowerCenter = lower + Math.floorDiv(upper - lower, 2);
|
||||
int upperCenter = lower + Math.ceilDiv(upper - lower, 2);
|
||||
return mantleY == lowerCenter || mantleY == upperCenter;
|
||||
}
|
||||
|
||||
private static int cavernLowerBound(IntPredicate carved, int mantleY, int minimumY) {
|
||||
int lower = mantleY;
|
||||
while (lower > minimumY && carved.test(lower - 1)) {
|
||||
lower--;
|
||||
}
|
||||
return lower;
|
||||
}
|
||||
|
||||
private static int cavernUpperBound(IntPredicate carved, int mantleY, int maximumY) {
|
||||
int upper = mantleY;
|
||||
while (upper < maximumY && carved.test(upper + 1)) {
|
||||
upper++;
|
||||
}
|
||||
return upper;
|
||||
}
|
||||
|
||||
private static int saturatedSubtract(int value, int amount) {
|
||||
long result = (long) value - amount;
|
||||
return result < Integer.MIN_VALUE ? Integer.MIN_VALUE : (int) result;
|
||||
}
|
||||
|
||||
private static int saturatedAdd(int value, int amount) {
|
||||
long result = (long) value + amount;
|
||||
return result > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) result;
|
||||
}
|
||||
|
||||
private static boolean carvedRun(
|
||||
IntPredicate carved,
|
||||
int mantleY,
|
||||
int direction,
|
||||
int length
|
||||
) {
|
||||
for (int offset = 0; offset < length; offset++) {
|
||||
if (!carved.test(mantleY + (direction * offset))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean isCarved(Engine engine, int blockX, int mantleY, int blockZ) {
|
||||
if (mantleY < 0 || mantleY >= engine.getHeight()) {
|
||||
return false;
|
||||
}
|
||||
MatterCavern cavern = cavernAt(engine, blockX, mantleY, blockZ);
|
||||
return cavern != null && cavern.isCavern();
|
||||
}
|
||||
|
||||
private static boolean matchesAnchorFluid(
|
||||
Engine engine,
|
||||
StructurePlacement placement,
|
||||
int blockX,
|
||||
int mantleY,
|
||||
int blockZ
|
||||
) {
|
||||
MatterCavern cavern = cavernAt(engine, blockX, mantleY, blockZ);
|
||||
return acceptsAnchorFluid(
|
||||
placement.underwater(),
|
||||
cavern,
|
||||
mantleY,
|
||||
engine.getDimension().getModuleSettings().find(CaveLavaHeightSettings.class).map(CaveLavaHeightSettings::height).orElse(CaveLavaHeightSettings.DEFAULT_HEIGHT));
|
||||
}
|
||||
|
||||
static boolean acceptsAnchorFluid(
|
||||
boolean underwater,
|
||||
MatterCavern cavern,
|
||||
int mantleY,
|
||||
int defaultLavaHeight
|
||||
) {
|
||||
if (cavern == null || !cavern.isCavern()) {
|
||||
return false;
|
||||
}
|
||||
if (underwater) {
|
||||
return true;
|
||||
}
|
||||
if (cavern.getLiquid() == LIQUID_FORCED_AIR) {
|
||||
return true;
|
||||
}
|
||||
return cavern.isAir() && mantleY > defaultLavaHeight;
|
||||
}
|
||||
|
||||
private static MatterCavern cavernAt(Engine engine, int blockX, int mantleY, int blockZ) {
|
||||
return engine.getMantle().getMantle().get(blockX, mantleY, blockZ, MatterCavern.class);
|
||||
}
|
||||
|
||||
static int toMantleY(int worldY, int worldMinHeight) {
|
||||
return Math.subtractExact(worldY, worldMinHeight);
|
||||
}
|
||||
|
||||
private static boolean matchesBiome(
|
||||
Engine engine,
|
||||
StructurePlacement placement,
|
||||
int blockX,
|
||||
int mantleY,
|
||||
int blockZ
|
||||
) {
|
||||
if (placement.caveBiomes().isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
IrisBiome biome = engine.getCaveOrMantleBiome(blockX, mantleY, blockZ);
|
||||
if (biome == null || biome.getLoadKey() == null) {
|
||||
return false;
|
||||
}
|
||||
String actual = biome.getLoadKey().toLowerCase(Locale.ROOT);
|
||||
for (String allowed : placement.caveBiomes()) {
|
||||
if (matchesBiomeKey(actual, allowed)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static boolean matchesBiomeKey(String actual, String allowed) {
|
||||
if (actual == null || actual.isBlank() || allowed == null || allowed.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String normalizedActual = actual.trim().toLowerCase(Locale.ROOT);
|
||||
String normalizedAllowed = allowed.trim().toLowerCase(Locale.ROOT);
|
||||
return normalizedActual.equals(normalizedAllowed)
|
||||
|| normalizedActual.endsWith(":" + normalizedAllowed)
|
||||
|| normalizedAllowed.endsWith(":" + normalizedActual);
|
||||
}
|
||||
|
||||
public record Anchor(int x, int y, int z) {
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
package art.arcane.iris.engine.framework;
|
||||
|
||||
import art.arcane.iris.builtin.structure.StructurePlacement;
|
||||
import art.arcane.iris.builtin.structure.StructurePlacementSettings;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.iris.engine.IrisComplex;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* The structure placements that apply at a chunk: its biome's, its cave biome's cave-anchored ones, its region's and
|
||||
* the dimension's. Each world keeps which of those levels declare placements at all, so chunks skip the biome and
|
||||
* region lookups a pack never needs.
|
||||
*/
|
||||
public final class StructurePlacementScope {
|
||||
private StructurePlacementScope() {
|
||||
}
|
||||
|
||||
/** The placements {@code owner} declares in its {@code "structures"} settings; empty for none. */
|
||||
public static List<StructurePlacement> placementsOf(IrisRegistrant owner) {
|
||||
if (owner == null) {
|
||||
return List.of();
|
||||
}
|
||||
return owner.getModuleSettings().find(StructurePlacementSettings.class)
|
||||
.map(StructurePlacementSettings::placements)
|
||||
.orElse(List.of());
|
||||
}
|
||||
|
||||
public static KList<StructurePlacement> placementsAt(Engine engine, int chunkX, int chunkZ) {
|
||||
Engine activeEngine = Objects.requireNonNull(engine, "Structure placement scope requires an engine");
|
||||
IrisComplex complex = activeEngine.getComplex();
|
||||
int blockX = (chunkX << 4) + 8;
|
||||
int blockZ = (chunkZ << 4) + 8;
|
||||
KList<StructurePlacement> placements = new KList<>();
|
||||
Set<StructurePlacement> seen = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
ScopeIndex index = scopeIndex(activeEngine);
|
||||
if (complex != null) {
|
||||
if (index.biome()) {
|
||||
IrisBiome biome = complex.getTrueBiomeStream().get(blockX, blockZ);
|
||||
addUnique(placements, seen, placementsOf(biome));
|
||||
}
|
||||
if (index.caveBiome()) {
|
||||
IrisBiome caveBiome = complex.getCaveBiomeStream().get(blockX, blockZ);
|
||||
addCaveUnique(placements, seen, placementsOf(caveBiome));
|
||||
}
|
||||
if (index.region()) {
|
||||
IrisRegion region = complex.getRegionStream().get(blockX, blockZ);
|
||||
addUnique(placements, seen, placementsOf(region));
|
||||
}
|
||||
}
|
||||
if (index.dimension()) {
|
||||
addUnique(placements, seen, placementsOf(activeEngine.getDimension()));
|
||||
}
|
||||
return placements;
|
||||
}
|
||||
|
||||
private static ScopeIndex scopeIndex(Engine engine) {
|
||||
return engine.getGeneration().state(ScopeIndex.class, StructurePlacementScope::buildScopeIndex);
|
||||
}
|
||||
|
||||
private static ScopeIndex buildScopeIndex(Engine engine) {
|
||||
boolean biome = false;
|
||||
boolean caveBiome = false;
|
||||
KList<IrisBiome> allBiomes = engine.getAllBiomes();
|
||||
if (allBiomes == null) {
|
||||
biome = true;
|
||||
caveBiome = true;
|
||||
} else {
|
||||
for (IrisBiome candidate : allBiomes) {
|
||||
List<StructurePlacement> structures = placementsOf(candidate);
|
||||
if (structures.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
biome = true;
|
||||
caveBiome |= structures.stream().anyMatch(placement -> placement.resolvedAnchor().isCave());
|
||||
}
|
||||
}
|
||||
boolean region = false;
|
||||
if (engine.getDimension() != null) {
|
||||
KList<IrisRegion> allRegions = engine.getDimension().getAllRegions(engine);
|
||||
region = allRegions == null
|
||||
|| allRegions.stream().anyMatch(candidate -> !placementsOf(candidate).isEmpty());
|
||||
}
|
||||
boolean dimension = !placementsOf(engine.getDimension()).isEmpty();
|
||||
return new ScopeIndex(biome, caveBiome, region, dimension);
|
||||
}
|
||||
|
||||
private static void addUnique(KList<StructurePlacement> destination, Set<StructurePlacement> seen,
|
||||
List<StructurePlacement> source) {
|
||||
for (StructurePlacement placement : source) {
|
||||
if (placement != null && seen.add(placement)) {
|
||||
destination.add(placement);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void addCaveUnique(KList<StructurePlacement> destination, Set<StructurePlacement> seen,
|
||||
List<StructurePlacement> source) {
|
||||
for (StructurePlacement placement : source) {
|
||||
if (placement != null && placement.resolvedAnchor().isCave() && seen.add(placement)) {
|
||||
destination.add(placement);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private record ScopeIndex(boolean biome, boolean caveBiome, boolean region, boolean dimension) {
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
public final class CompiledStructureGraph {
|
||||
private final IrisStructure structure;
|
||||
private final Map<String, IrisJigsawPool> pools;
|
||||
private final Map<String, IrisJigsawPiece> pieces;
|
||||
private final Map<String, IrisObject> objects;
|
||||
private final Set<String> reachablePools;
|
||||
private final Set<String> reachablePieces;
|
||||
|
||||
private CompiledStructureGraph(Builder builder) {
|
||||
structure = builder.structure;
|
||||
pools = Collections.unmodifiableMap(new LinkedHashMap<>(builder.pools));
|
||||
pieces = Collections.unmodifiableMap(new LinkedHashMap<>(builder.pieces));
|
||||
objects = Collections.unmodifiableMap(new LinkedHashMap<>(builder.objects));
|
||||
reachablePools = Collections.unmodifiableSet(new LinkedHashSet<>(builder.reachablePools));
|
||||
reachablePieces = Collections.unmodifiableSet(new LinkedHashSet<>(builder.reachablePieces));
|
||||
}
|
||||
|
||||
static Builder builder(IrisStructure structure) {
|
||||
return new Builder(structure);
|
||||
}
|
||||
|
||||
public IrisStructure getStructure() {
|
||||
return structure;
|
||||
}
|
||||
|
||||
public String getStructureKey() {
|
||||
String key = structure.getLoadKey();
|
||||
return key == null || key.isBlank() ? "<unloaded>" : key;
|
||||
}
|
||||
|
||||
public Map<String, IrisJigsawPool> getPools() {
|
||||
return pools;
|
||||
}
|
||||
|
||||
public Map<String, IrisJigsawPiece> getPieces() {
|
||||
return pieces;
|
||||
}
|
||||
|
||||
public Map<String, IrisObject> getObjects() {
|
||||
return objects;
|
||||
}
|
||||
|
||||
public Set<String> getReachablePools() {
|
||||
return reachablePools;
|
||||
}
|
||||
|
||||
public Set<String> getReachablePieces() {
|
||||
return reachablePieces;
|
||||
}
|
||||
|
||||
static final class Builder {
|
||||
private final IrisStructure structure;
|
||||
private final Map<String, IrisJigsawPool> pools = new LinkedHashMap<>();
|
||||
private final Map<String, IrisJigsawPiece> pieces = new LinkedHashMap<>();
|
||||
private final Map<String, IrisObject> objects = new LinkedHashMap<>();
|
||||
private final Set<String> reachablePools = new LinkedHashSet<>();
|
||||
private final Set<String> reachablePieces = new LinkedHashSet<>();
|
||||
|
||||
private Builder(IrisStructure structure) {
|
||||
this.structure = Objects.requireNonNull(structure);
|
||||
}
|
||||
|
||||
Map<String, IrisJigsawPool> pools() {
|
||||
return pools;
|
||||
}
|
||||
|
||||
Map<String, IrisJigsawPiece> pieces() {
|
||||
return pieces;
|
||||
}
|
||||
|
||||
Map<String, IrisObject> objects() {
|
||||
return objects;
|
||||
}
|
||||
|
||||
Set<String> reachablePools() {
|
||||
return reachablePools;
|
||||
}
|
||||
|
||||
Set<String> reachablePieces() {
|
||||
return reachablePieces;
|
||||
}
|
||||
|
||||
CompiledStructureGraph build() {
|
||||
return new CompiledStructureGraph(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,386 +0,0 @@
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
public final class IrisObjectFrameReader {
|
||||
private static final String HEADER = "Iris V2 IOB;";
|
||||
private static final int MAX_FILE_BYTES = 64 * 1024 * 1024;
|
||||
private static final int MAX_TILE_COUNT = 65_536;
|
||||
private static final int MAX_CANDIDATE_OFFSETS = 1_024;
|
||||
private static final long MAX_TILE_PARSE_STATES = 262_144L;
|
||||
private static final int MAX_LEGACY_SIGN_COLOR_INDEX = 15;
|
||||
|
||||
private IrisObjectFrameReader() {
|
||||
}
|
||||
|
||||
public static IrisObject readBounds(InputStream stream, String resourceName) throws IOException {
|
||||
String activeResourceName = resourceName == null || resourceName.isBlank()
|
||||
? "<unknown>" : resourceName;
|
||||
try {
|
||||
byte[] content = readLimitedContent(Objects.requireNonNull(stream), activeResourceName);
|
||||
return readBounds(content, activeResourceName);
|
||||
} catch (IOException e) {
|
||||
if (e.getMessage() != null && e.getMessage().startsWith("Malformed Iris object resource ")) {
|
||||
throw e;
|
||||
}
|
||||
throw malformed(activeResourceName, e.getMessage() == null
|
||||
? e.getClass().getSimpleName() : e.getMessage());
|
||||
} catch (RuntimeException e) {
|
||||
throw malformed(activeResourceName, e.getMessage() == null
|
||||
? e.getClass().getSimpleName() : e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static IrisObject readBounds(byte[] content, String resourceName) throws IOException {
|
||||
ByteArrayInputStream bytes = new ByteArrayInputStream(content);
|
||||
DataInputStream input = new DataInputStream(bytes);
|
||||
int width = input.readInt();
|
||||
int height = input.readInt();
|
||||
int depth = input.readInt();
|
||||
long volume = requireDimensions(resourceName, width, height, depth);
|
||||
if (!HEADER.equals(input.readUTF())) {
|
||||
throw malformed(resourceName, "invalid header");
|
||||
}
|
||||
|
||||
int paletteSize = input.readShort();
|
||||
if (paletteSize < 0) {
|
||||
throw malformed(resourceName, "palette exceeds the signed IOB limit");
|
||||
}
|
||||
for (int index = 0; index < paletteSize; index++) {
|
||||
if (input.readUTF().isBlank()) {
|
||||
throw malformed(resourceName, "palette entry " + index + " is blank");
|
||||
}
|
||||
}
|
||||
|
||||
int blockCount = input.readInt();
|
||||
if (blockCount < 0 || blockCount > volume || blockCount > 0 && paletteSize == 0) {
|
||||
throw malformed(resourceName, "invalid block count " + blockCount);
|
||||
}
|
||||
for (int index = 0; index < blockCount; index++) {
|
||||
int x = input.readShort();
|
||||
int y = input.readShort();
|
||||
int z = input.readShort();
|
||||
int paletteIndex = input.readShort();
|
||||
requirePosition(resourceName, "block", index, x, y, z, width, height, depth);
|
||||
if (paletteIndex < 0 || paletteIndex >= paletteSize) {
|
||||
throw malformed(resourceName, "block " + index
|
||||
+ " references invalid palette index " + paletteIndex);
|
||||
}
|
||||
}
|
||||
|
||||
int tileCount = input.readInt();
|
||||
if (tileCount < 0 || tileCount > volume) {
|
||||
throw malformed(resourceName, "invalid tile count " + tileCount);
|
||||
}
|
||||
if (tileCount > MAX_TILE_COUNT) {
|
||||
throw malformed(resourceName, "tile count " + tileCount
|
||||
+ " exceeds limit " + MAX_TILE_COUNT);
|
||||
}
|
||||
int tileStart = content.length - bytes.available();
|
||||
requireCompleteTileFraming(content, tileStart, tileCount, width, height, depth, resourceName);
|
||||
return new IrisObject(width, height, depth);
|
||||
}
|
||||
|
||||
private static void requireCompleteTileFraming(
|
||||
byte[] content,
|
||||
int tileStart,
|
||||
int tileCount,
|
||||
int width,
|
||||
int height,
|
||||
int depth,
|
||||
String resourceName
|
||||
) throws IOException {
|
||||
Set<Integer> offsets = Set.of(tileStart);
|
||||
long parseStates = 0L;
|
||||
for (int tileIndex = 0; tileIndex < tileCount; tileIndex++) {
|
||||
Set<Integer> nextOffsets = new LinkedHashSet<>();
|
||||
TileFailureTracker failures = new TileFailureTracker();
|
||||
for (int offset : offsets) {
|
||||
parseStates++;
|
||||
requireParseStateBudget(resourceName, tileIndex, parseStates);
|
||||
TilePrefix prefix = readTilePrefix(
|
||||
content, offset, width, height, depth, tileIndex, failures);
|
||||
if (prefix == null) {
|
||||
continue;
|
||||
}
|
||||
int modernEnd = readModernTileEnd(
|
||||
content, prefix.payloadOffset(), tileIndex, failures);
|
||||
if (modernEnd >= 0) {
|
||||
addCandidateOffset(resourceName, tileIndex, nextOffsets, modernEnd);
|
||||
}
|
||||
for (int legacyEnd : readLegacyTileEnds(
|
||||
content, prefix.payloadOffset(), tileIndex, failures)) {
|
||||
addCandidateOffset(resourceName, tileIndex, nextOffsets, legacyEnd);
|
||||
}
|
||||
}
|
||||
if (nextOffsets.isEmpty()) {
|
||||
throw malformed(resourceName, failures.detailOr(
|
||||
"tile " + tileIndex + " is truncated or malformed"));
|
||||
}
|
||||
offsets = nextOffsets;
|
||||
}
|
||||
if (!offsets.contains(content.length)) {
|
||||
throw malformed(resourceName, "tile records leave trailing or incomplete data");
|
||||
}
|
||||
}
|
||||
|
||||
private static TilePrefix readTilePrefix(
|
||||
byte[] content,
|
||||
int offset,
|
||||
int width,
|
||||
int height,
|
||||
int depth,
|
||||
int tileIndex,
|
||||
TileFailureTracker failures
|
||||
) {
|
||||
try {
|
||||
ByteArrayInputStream bytes = slice(content, offset);
|
||||
DataInputStream input = new DataInputStream(bytes);
|
||||
int x = input.readShort();
|
||||
int y = input.readShort();
|
||||
int z = input.readShort();
|
||||
if (!withinSignedObjectAxis(x, width) || !withinSignedObjectAxis(y, height)
|
||||
|| !withinSignedObjectAxis(z, depth)) {
|
||||
failures.record("tile " + tileIndex + " position " + x + "," + y + "," + z
|
||||
+ " is outside object bounds", 20);
|
||||
return null;
|
||||
}
|
||||
return new TilePrefix(content.length - bytes.available());
|
||||
} catch (IOException | RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static int readModernTileEnd(
|
||||
byte[] content,
|
||||
int offset,
|
||||
int tileIndex,
|
||||
TileFailureTracker failures
|
||||
) {
|
||||
try {
|
||||
ByteArrayInputStream bytes = slice(content, offset);
|
||||
DataInputStream input = new DataInputStream(bytes);
|
||||
String material = input.readUTF();
|
||||
if (material.isBlank()) {
|
||||
failures.record("tile " + tileIndex + " modern material is blank", 40);
|
||||
return -1;
|
||||
}
|
||||
JsonElement properties = JsonParser.parseString(input.readUTF());
|
||||
if (!properties.isJsonObject()) {
|
||||
failures.record("tile " + tileIndex
|
||||
+ " modern properties are not a JSON object", 30);
|
||||
return -1;
|
||||
}
|
||||
return content.length - bytes.available();
|
||||
} catch (IOException | RuntimeException e) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private static Set<Integer> readLegacyTileEnds(
|
||||
byte[] content,
|
||||
int offset,
|
||||
int tileIndex,
|
||||
TileFailureTracker failures
|
||||
) {
|
||||
try {
|
||||
ByteArrayInputStream bytes = slice(content, offset);
|
||||
DataInputStream input = new DataInputStream(bytes);
|
||||
int id = input.readShort();
|
||||
return switch (id) {
|
||||
case 0 -> singletonEnd(content, readLegacySign(input, bytes, tileIndex, failures));
|
||||
case 1 -> readLegacySpawnerEnds(content, content.length - bytes.available());
|
||||
case 2 -> readLegacyBannerEnds(content, input, bytes);
|
||||
case 3 -> singletonEnd(content, readLegacyLootable(input, bytes));
|
||||
default -> Set.of();
|
||||
};
|
||||
} catch (IOException | RuntimeException e) {
|
||||
return Set.of();
|
||||
}
|
||||
}
|
||||
|
||||
private static int readLegacySign(
|
||||
DataInputStream input,
|
||||
ByteArrayInputStream bytes,
|
||||
int tileIndex,
|
||||
TileFailureTracker failures
|
||||
) throws IOException {
|
||||
input.readUTF();
|
||||
input.readUTF();
|
||||
input.readUTF();
|
||||
input.readUTF();
|
||||
int colorIndex = input.readByte();
|
||||
if (colorIndex < 0 || colorIndex > MAX_LEGACY_SIGN_COLOR_INDEX) {
|
||||
failures.record("tile " + tileIndex + " legacy sign color index " + colorIndex
|
||||
+ " is outside 0.." + MAX_LEGACY_SIGN_COLOR_INDEX, 50);
|
||||
throw new IOException("Invalid legacy sign color index");
|
||||
}
|
||||
return bytes.available();
|
||||
}
|
||||
|
||||
private static Set<Integer> readLegacySpawnerEnds(byte[] content, int payloadOffset) {
|
||||
Set<Integer> ends = new LinkedHashSet<>();
|
||||
try {
|
||||
ByteArrayInputStream keyedBytes = slice(content, payloadOffset);
|
||||
new DataInputStream(keyedBytes).readUTF();
|
||||
ends.add(content.length - keyedBytes.available());
|
||||
} catch (IOException | RuntimeException ignored) {
|
||||
}
|
||||
if (payloadOffset <= content.length - Short.BYTES) {
|
||||
ends.add(payloadOffset + Short.BYTES);
|
||||
}
|
||||
return Set.copyOf(ends);
|
||||
}
|
||||
|
||||
private static Set<Integer> readLegacyBannerEnds(
|
||||
byte[] content,
|
||||
DataInputStream input,
|
||||
ByteArrayInputStream bytes
|
||||
) throws IOException {
|
||||
input.readUnsignedByte();
|
||||
int patternCount = input.readUnsignedByte();
|
||||
int patternsOffset = content.length - bytes.available();
|
||||
Set<Integer> ends = new LinkedHashSet<>();
|
||||
try {
|
||||
ByteArrayInputStream keyedBytes = slice(content, patternsOffset);
|
||||
DataInputStream keyedInput = new DataInputStream(keyedBytes);
|
||||
for (int index = 0; index < patternCount; index++) {
|
||||
keyedInput.readUnsignedByte();
|
||||
keyedInput.readUTF();
|
||||
}
|
||||
ends.add(content.length - keyedBytes.available());
|
||||
} catch (IOException | RuntimeException ignored) {
|
||||
}
|
||||
long legacyEnd = (long) patternsOffset + (long) patternCount * 2L;
|
||||
if (legacyEnd <= content.length) {
|
||||
ends.add((int) legacyEnd);
|
||||
}
|
||||
return Set.copyOf(ends);
|
||||
}
|
||||
|
||||
private static int readLegacyLootable(DataInputStream input, ByteArrayInputStream bytes) throws IOException {
|
||||
input.readUTF();
|
||||
input.readUTF();
|
||||
input.readLong();
|
||||
return bytes.available();
|
||||
}
|
||||
|
||||
private static Set<Integer> singletonEnd(byte[] content, int remaining) {
|
||||
return Set.of(content.length - remaining);
|
||||
}
|
||||
|
||||
private static byte[] readLimitedContent(InputStream stream, String resourceName) throws IOException {
|
||||
return readLimitedContent(stream, resourceName, MAX_FILE_BYTES);
|
||||
}
|
||||
|
||||
static byte[] readLimitedContent(
|
||||
InputStream stream,
|
||||
String resourceName,
|
||||
int maximumBytes
|
||||
) throws IOException {
|
||||
byte[] content = stream.readNBytes(maximumBytes + 1);
|
||||
if (content.length > maximumBytes) {
|
||||
throw malformed(resourceName, "file exceeds " + maximumBytes + "-byte limit");
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
private static void addCandidateOffset(
|
||||
String resourceName,
|
||||
int tileIndex,
|
||||
Set<Integer> offsets,
|
||||
int offset
|
||||
) throws IOException {
|
||||
offsets.add(offset);
|
||||
if (offsets.size() > MAX_CANDIDATE_OFFSETS) {
|
||||
throw malformed(resourceName, "tile " + tileIndex + " exceeds candidate-offset limit "
|
||||
+ MAX_CANDIDATE_OFFSETS);
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireParseStateBudget(
|
||||
String resourceName,
|
||||
int tileIndex,
|
||||
long parseStates
|
||||
) throws IOException {
|
||||
if (parseStates > MAX_TILE_PARSE_STATES) {
|
||||
throw malformed(resourceName, "tile " + tileIndex + " exceeds parse-state limit "
|
||||
+ MAX_TILE_PARSE_STATES);
|
||||
}
|
||||
}
|
||||
|
||||
private static ByteArrayInputStream slice(byte[] content, int offset) {
|
||||
if (offset < 0 || offset > content.length) {
|
||||
throw new IllegalArgumentException("Invalid IOB frame offset " + offset);
|
||||
}
|
||||
return new ByteArrayInputStream(content, offset, content.length - offset);
|
||||
}
|
||||
|
||||
private static long requireDimensions(String resourceName, int width, int height, int depth) throws IOException {
|
||||
if (width < 1 || height < 1 || depth < 1) {
|
||||
throw malformed(resourceName, "invalid dimensions " + width + "x" + height + "x" + depth);
|
||||
}
|
||||
try {
|
||||
return Math.multiplyExact(Math.multiplyExact((long) width, height), depth);
|
||||
} catch (ArithmeticException e) {
|
||||
throw malformed(resourceName, "dimensions overflow the IOB volume limit");
|
||||
}
|
||||
}
|
||||
|
||||
private static void requirePosition(
|
||||
String resourceName,
|
||||
String type,
|
||||
int index,
|
||||
int x,
|
||||
int y,
|
||||
int z,
|
||||
int width,
|
||||
int height,
|
||||
int depth
|
||||
) throws IOException {
|
||||
if (!withinSignedObjectAxis(x, width) || !withinSignedObjectAxis(y, height)
|
||||
|| !withinSignedObjectAxis(z, depth)) {
|
||||
throw malformed(resourceName, type + " " + index + " position "
|
||||
+ x + "," + y + "," + z + " is outside object bounds");
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean withinSignedObjectAxis(int coordinate, int size) {
|
||||
int center = size / 2;
|
||||
return coordinate >= -center && coordinate < size - center;
|
||||
}
|
||||
|
||||
private static IOException malformed(String resourceName, String detail) {
|
||||
return new IOException("Malformed Iris object resource " + resourceName + ": " + detail);
|
||||
}
|
||||
|
||||
private record TilePrefix(int payloadOffset) {
|
||||
}
|
||||
|
||||
private static final class TileFailureTracker {
|
||||
private String detail;
|
||||
private int priority = Integer.MIN_VALUE;
|
||||
|
||||
private void record(String candidateDetail, int candidatePriority) {
|
||||
if (candidatePriority <= priority) {
|
||||
return;
|
||||
}
|
||||
detail = candidateDetail;
|
||||
priority = candidatePriority;
|
||||
}
|
||||
|
||||
private String detailOr(String fallback) {
|
||||
return detail == null ? fallback : detail;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceRules;
|
||||
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.IrisStructure;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class JigsawPoolSelection {
|
||||
private JigsawPoolSelection() {
|
||||
}
|
||||
|
||||
public static String directFallbackKey(IrisJigsawPool pool) {
|
||||
Objects.requireNonNull(pool);
|
||||
return normalize(pool.getFallback());
|
||||
}
|
||||
|
||||
public static List<String> candidatePoolKeys(
|
||||
String primaryKey,
|
||||
IrisJigsawPool primaryPool,
|
||||
boolean includePrimary
|
||||
) {
|
||||
Objects.requireNonNull(primaryPool);
|
||||
String normalizedPrimary = normalize(primaryKey);
|
||||
String directFallback = directFallbackKey(primaryPool);
|
||||
if (!includePrimary) {
|
||||
return directFallback.isEmpty() ? List.of() : List.of(directFallback);
|
||||
}
|
||||
if (normalizedPrimary.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
return directFallback.isEmpty()
|
||||
? List.of(normalizedPrimary)
|
||||
: List.of(normalizedPrimary, directFallback);
|
||||
}
|
||||
|
||||
public static String selectTheme(IrisStructure structure, RNG rng) {
|
||||
IrisStructure activeStructure = Objects.requireNonNull(structure);
|
||||
RNG activeRng = Objects.requireNonNull(rng);
|
||||
if (activeStructure.getThemeSets() == null || activeStructure.getThemeSets().isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
List<IrisJigsawThemeSet> themes = new ArrayList<>(activeStructure.getThemeSets().size());
|
||||
long totalWeight = 0L;
|
||||
for (IrisJigsawThemeSet theme : activeStructure.getThemeSets()) {
|
||||
if (theme == null || normalize(theme.getKey()).isEmpty() || theme.getWeight() <= 0) {
|
||||
throw new IllegalArgumentException("Jigsaw theme sets require non-blank keys and positive weights");
|
||||
}
|
||||
themes.add(theme);
|
||||
totalWeight = Math.addExact(totalWeight, theme.getWeight());
|
||||
}
|
||||
if (themes.size() == 1) {
|
||||
return normalize(themes.getFirst().getKey());
|
||||
}
|
||||
long target = activeRng.nextLong(totalWeight);
|
||||
for (IrisJigsawThemeSet theme : themes) {
|
||||
target -= theme.getWeight();
|
||||
if (target < 0L) {
|
||||
return normalize(theme.getKey());
|
||||
}
|
||||
}
|
||||
return normalize(themes.getLast().getKey());
|
||||
}
|
||||
|
||||
public static boolean passesChance(IrisJigsawPieceEntry entry, RNG rng) {
|
||||
IrisJigsawPieceEntry activeEntry = Objects.requireNonNull(entry);
|
||||
RNG activeRng = Objects.requireNonNull(rng);
|
||||
double chance = activeEntry.getChance();
|
||||
if (!Double.isFinite(chance) || chance < 0D || chance > 1D) {
|
||||
throw new IllegalArgumentException("Jigsaw pool membership chance must be finite and within 0 and 1");
|
||||
}
|
||||
if (!activeEntry.requiresChanceRoll()) {
|
||||
return chance >= 1D;
|
||||
}
|
||||
return activeEntry.passesChance(activeRng.nextDouble());
|
||||
}
|
||||
|
||||
public static boolean pieceEligible(
|
||||
IrisJigsawPiece piece,
|
||||
String selectedTheme,
|
||||
int depth,
|
||||
int existingPlacements
|
||||
) {
|
||||
IrisJigsawPiece activePiece = Objects.requireNonNull(piece);
|
||||
IrisJigsawPieceRules rules = activePiece.resolvedRules();
|
||||
return activePiece.supportsTheme(normalize(selectedTheme))
|
||||
&& rules.allowsDepth(depth)
|
||||
&& rules.allowsPlacement(existingPlacements);
|
||||
}
|
||||
|
||||
public static boolean needsMinimumPlacement(IrisJigsawPiece piece, int existingPlacements) {
|
||||
return Objects.requireNonNull(piece).resolvedRules().requiresMorePlacements(existingPlacements);
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
}
|
||||
-392
@@ -1,392 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.builtin.anchor.PlaceTrait;
|
||||
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
|
||||
import art.arcane.iris.core.pack.PackValidationIo;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
import com.volmit.validation.Problem;
|
||||
import com.volmit.validation.Subject;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Checks the structure placements of a pack's dimensions, regions and biomes that replace a vanilla structure with
|
||||
* an Iris one ({@code nativeSuppression: REPLACE_SOURCE}): only a dimension may, it must name Iris structures, each
|
||||
* with a namespaced {@code vanillaSource}, that {@link StructureGraphValidation} found always produce output, and
|
||||
* whose sampled pieces fit the placement's height band inside the dimension. Reads the pack's JSON as written, so a
|
||||
* value of the wrong type is reported rather than read as a default. Every problem is an error about the file of the
|
||||
* dimension, region or biome. It runs with the structure graph check, whose samples it needs.
|
||||
*/
|
||||
public final class NativeReplacementValidation {
|
||||
private static final List<String> STRUCTURE_HOST_FOLDERS = List.of("dimensions", "regions", "biomes");
|
||||
private static final String DIMENSIONS_FOLDER = "dimensions";
|
||||
private static final String JSON_EXTENSION = ".json";
|
||||
private static final Pattern RESOURCE_KEY_PATTERN = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+");
|
||||
|
||||
private NativeReplacementValidation() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the pack in {@code packFolder}.
|
||||
*
|
||||
* @param replacementOutputStructures the structures that always produce output, which alone may replace a vanilla one
|
||||
* @param sampledVerticalEnvelopes each viable structure's sampled envelopes
|
||||
*/
|
||||
public static List<Problem> validate(
|
||||
File packFolder,
|
||||
Set<String> replacementOutputStructures,
|
||||
Map<String, List<StructureGraphValidation.SampledVerticalEnvelope>> sampledVerticalEnvelopes
|
||||
) {
|
||||
List<Problem> problems = new ArrayList<>();
|
||||
if (packFolder == null || !packFolder.isDirectory()) {
|
||||
return problems;
|
||||
}
|
||||
Set<String> viableStructures = replacementOutputStructures == null
|
||||
? Set.of() : replacementOutputStructures;
|
||||
Map<String, List<StructureGraphValidation.SampledVerticalEnvelope>> verticalEnvelopes =
|
||||
sampledVerticalEnvelopes == null ? Map.of() : sampledVerticalEnvelopes;
|
||||
Map<String, JSONObject> structures = readStructures(packFolder);
|
||||
for (String folderName : STRUCTURE_HOST_FOLDERS) {
|
||||
File resourceFolder = new File(packFolder, folderName);
|
||||
if (!resourceFolder.isDirectory()) {
|
||||
continue;
|
||||
}
|
||||
List<File> resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder);
|
||||
resourceFiles.sort(Comparator.comparing(File::getPath));
|
||||
for (File resourceFile : resourceFiles) {
|
||||
JSONObject resource = PackValidationIo.readJson(resourceFile);
|
||||
if (resource == null) {
|
||||
continue;
|
||||
}
|
||||
String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile);
|
||||
Subject file = Subject.file(folderName + "/" + resourceKey + JSON_EXTENSION);
|
||||
for (String error : validateResource(folderName, resourceKey, resource, structures, viableStructures, verticalEnvelopes)) {
|
||||
problems.add(Problem.error(file, error));
|
||||
}
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
private static Map<String, JSONObject> readStructures(File packFolder) {
|
||||
File structuresFolder = new File(packFolder, StructureResources.STRUCTURES.folder());
|
||||
Map<String, JSONObject> structures = new HashMap<>();
|
||||
for (File structureFile : PackValidationIo.listJsonRecursive(structuresFolder)) {
|
||||
JSONObject structure = PackValidationIo.readJson(structureFile);
|
||||
if (structure != null) {
|
||||
structures.put(PackValidationIo.deriveKey(structuresFolder, structureFile), structure);
|
||||
}
|
||||
}
|
||||
return structures;
|
||||
}
|
||||
|
||||
private static List<String> validateResource(
|
||||
String folderName,
|
||||
String resourceKey,
|
||||
JSONObject resource,
|
||||
Map<String, JSONObject> structures,
|
||||
Set<String> viableStructures,
|
||||
Map<String, List<StructureGraphValidation.SampledVerticalEnvelope>> verticalEnvelopes
|
||||
) {
|
||||
List<String> blockingErrors = new ArrayList<>();
|
||||
JSONArray placements = resource.optJSONArray("structures");
|
||||
if (placements == null) {
|
||||
return blockingErrors;
|
||||
}
|
||||
String resourceType = structureHostType(folderName);
|
||||
for (int placementIndex = 0; placementIndex < placements.length(); placementIndex++) {
|
||||
JSONObject placement = placements.optJSONObject(placementIndex);
|
||||
if (placement == null || !placement.has("nativeSuppression")) {
|
||||
continue;
|
||||
}
|
||||
Object rawSuppression = placement.opt("nativeSuppression");
|
||||
if (!(rawSuppression instanceof String suppression)) {
|
||||
blockingErrors.add(resourceType + " '" + resourceKey + "' structures["
|
||||
+ placementIndex + "].nativeSuppression must be NONE or REPLACE_SOURCE.");
|
||||
continue;
|
||||
}
|
||||
if ("NONE".equals(suppression)) {
|
||||
continue;
|
||||
}
|
||||
if (!"REPLACE_SOURCE".equals(suppression)) {
|
||||
blockingErrors.add(resourceType + " '" + resourceKey + "' structures["
|
||||
+ placementIndex + "].nativeSuppression has unsupported value '"
|
||||
+ suppression + "'. Use NONE or REPLACE_SOURCE.");
|
||||
continue;
|
||||
}
|
||||
if (!DIMENSIONS_FOLDER.equals(folderName)) {
|
||||
blockingErrors.add(resourceType + " '" + resourceKey + "' structures["
|
||||
+ placementIndex + "] requests REPLACE_SOURCE, but native replacement is only"
|
||||
+ " valid on dimension-level placements.");
|
||||
continue;
|
||||
}
|
||||
JSONArray references = placement.optJSONArray("structures");
|
||||
JSONArray nativeStructures = placement.optJSONArray("nativeStructures");
|
||||
if (nativeStructures != null && nativeStructures.length() > 0) {
|
||||
continue;
|
||||
}
|
||||
if (references == null || references.length() == 0) {
|
||||
blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex
|
||||
+ "] requests REPLACE_SOURCE without any structure backend.");
|
||||
continue;
|
||||
}
|
||||
for (int referenceIndex = 0; referenceIndex < references.length(); referenceIndex++) {
|
||||
Object rawReference = references.opt(referenceIndex);
|
||||
if (!(rawReference instanceof String structureKey) || structureKey.isBlank()) {
|
||||
blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex
|
||||
+ "].structures[" + referenceIndex
|
||||
+ "] must name an Iris structure for REPLACE_SOURCE.");
|
||||
continue;
|
||||
}
|
||||
JSONObject structure = structures.get(structureKey);
|
||||
if (structure == null) {
|
||||
blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex
|
||||
+ "] cannot REPLACE_SOURCE with missing or invalid structure '"
|
||||
+ structureKey + "'.");
|
||||
continue;
|
||||
}
|
||||
String vanillaSource = structure.optString("vanillaSource", "").trim();
|
||||
if (!RESOURCE_KEY_PATTERN.matcher(vanillaSource).matches()) {
|
||||
blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex
|
||||
+ "] requests REPLACE_SOURCE for structure '" + structureKey
|
||||
+ "', but its vanillaSource is not a valid namespaced registry key.");
|
||||
}
|
||||
if (!viableStructures.contains(structureKey)) {
|
||||
blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex
|
||||
+ "] requests REPLACE_SOURCE for structure '" + structureKey
|
||||
+ "', but that structure is not runtime-viable. Native generation will not"
|
||||
+ " be used as a fallback.");
|
||||
continue;
|
||||
}
|
||||
validateReplacementVerticalEnvelope(
|
||||
resourceKey,
|
||||
resource,
|
||||
placementIndex,
|
||||
placement,
|
||||
structureKey,
|
||||
structure,
|
||||
verticalEnvelopes.get(structureKey),
|
||||
blockingErrors);
|
||||
}
|
||||
}
|
||||
return blockingErrors;
|
||||
}
|
||||
|
||||
private static String structureHostType(String folderName) {
|
||||
return switch (folderName) {
|
||||
case "dimensions" -> "Dimension";
|
||||
case "regions" -> "Region";
|
||||
case "biomes" -> "Biome";
|
||||
default -> "Resource";
|
||||
};
|
||||
}
|
||||
|
||||
private static void validateReplacementVerticalEnvelope(
|
||||
String dimensionKey,
|
||||
JSONObject dimension,
|
||||
int placementIndex,
|
||||
JSONObject placement,
|
||||
String structureKey,
|
||||
JSONObject structure,
|
||||
List<StructureGraphValidation.SampledVerticalEnvelope> sampledVerticalEnvelopes,
|
||||
List<String> blockingErrors
|
||||
) {
|
||||
String context = "Dimension '" + dimensionKey + "' structures[" + placementIndex
|
||||
+ "] REPLACE_SOURCE structure '" + structureKey + "'";
|
||||
if (sampledVerticalEnvelopes == null || sampledVerticalEnvelopes.isEmpty()) {
|
||||
blockingErrors.add(context + " has no sampled vertical envelope. Native generation will not"
|
||||
+ " be used as a fallback.");
|
||||
return;
|
||||
}
|
||||
|
||||
DimensionVerticalBounds worldBounds = resolveDimensionVerticalBounds(dimension, context, blockingErrors);
|
||||
PlacementVerticalBounds placementBounds = resolvePlacementVerticalBounds(placement, context, blockingErrors);
|
||||
ObjectPlaceMode placeMode = resolvePlaceMode(structure, context, blockingErrors);
|
||||
if (worldBounds == null || placementBounds == null || placeMode == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (StructureGraphValidation.SampledVerticalEnvelope sampled : sampledVerticalEnvelopes) {
|
||||
boolean exactY = placementBounds.underground()
|
||||
|| sampled.pieceCount() > 1
|
||||
|| placeMode.placeMode().has(PlaceTrait.FREE_HEIGHT);
|
||||
if (!exactY) {
|
||||
continue;
|
||||
}
|
||||
|
||||
long minimumYOffset = sampled.minimumYOffset();
|
||||
long maximumYOffset = sampled.maximumYOffset();
|
||||
boolean surfaceAligned = !placementBounds.underground()
|
||||
&& sampled.pieceCount() > 1
|
||||
&& !placeMode.placeMode().has(PlaceTrait.FREE_HEIGHT);
|
||||
if (surfaceAligned) {
|
||||
maximumYOffset -= minimumYOffset;
|
||||
minimumYOffset = 0L;
|
||||
}
|
||||
|
||||
boolean fitsConfiguredRange;
|
||||
if (placementBounds.underground()) {
|
||||
long minimumAnchor = Math.max(
|
||||
Math.max(placementBounds.minimumY(), worldBounds.minimumY()),
|
||||
worldBounds.minimumY() - minimumYOffset);
|
||||
long maximumAnchor = Math.min(
|
||||
Math.min(placementBounds.maximumY(), worldBounds.maximumY()),
|
||||
worldBounds.maximumY() - maximumYOffset);
|
||||
fitsConfiguredRange = minimumAnchor <= maximumAnchor;
|
||||
} else {
|
||||
long minimumTerrainY = Math.max(placementBounds.minimumY(), worldBounds.minimumY());
|
||||
long maximumTerrainY = Math.min(placementBounds.maximumY(), worldBounds.maximumY());
|
||||
fitsConfiguredRange = minimumTerrainY <= maximumTerrainY
|
||||
&& minimumTerrainY + minimumYOffset >= worldBounds.minimumY()
|
||||
&& maximumTerrainY + maximumYOffset <= worldBounds.maximumY();
|
||||
}
|
||||
if (fitsConfiguredRange) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String alignment = surfaceAligned ? "surface-aligned " : "";
|
||||
blockingErrors.add(context + " sampled seed " + sampled.seed() + " has an " + alignment
|
||||
+ "exact-Y piece envelope " + minimumYOffset + ".." + maximumYOffset
|
||||
+ " relative to its anchor, which cannot fit placement band "
|
||||
+ placementBounds.minimumY() + ".." + placementBounds.maximumY()
|
||||
+ " inside writable world " + worldBounds.minimumY() + ".." + worldBounds.maximumY()
|
||||
+ ". Native generation will not be used as a fallback.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private static DimensionVerticalBounds resolveDimensionVerticalBounds(
|
||||
JSONObject dimension,
|
||||
String context,
|
||||
List<String> blockingErrors
|
||||
) {
|
||||
long dimensionMinimum = -64L;
|
||||
long dimensionMaximum = 320L;
|
||||
if (dimension.has("dimensionHeight")) {
|
||||
JSONObject dimensionHeight = dimension.optJSONObject("dimensionHeight");
|
||||
if (dimensionHeight == null) {
|
||||
blockingErrors.add(context + " cannot validate its vertical envelope because dimensionHeight"
|
||||
+ " must be an object.");
|
||||
return null;
|
||||
}
|
||||
Long configuredMinimum = integralJsonNumber(dimensionHeight, "min", 16L);
|
||||
Long configuredMaximum = integralJsonNumber(dimensionHeight, "max", 32L);
|
||||
if (configuredMinimum == null || configuredMaximum == null) {
|
||||
blockingErrors.add(context + " cannot validate its vertical envelope because dimensionHeight"
|
||||
+ " min and max must be finite integer values.");
|
||||
return null;
|
||||
}
|
||||
dimensionMinimum = configuredMinimum;
|
||||
dimensionMaximum = configuredMaximum;
|
||||
}
|
||||
|
||||
long writableMinimum = dimensionMinimum + 1L;
|
||||
long writableMaximum = dimensionMaximum - 1L;
|
||||
if (writableMinimum > writableMaximum) {
|
||||
blockingErrors.add(context + " cannot validate its vertical envelope because dimensionHeight "
|
||||
+ dimensionMinimum + ".." + dimensionMaximum + " has no writable structure range.");
|
||||
return null;
|
||||
}
|
||||
return new DimensionVerticalBounds(writableMinimum, writableMaximum);
|
||||
}
|
||||
|
||||
private static PlacementVerticalBounds resolvePlacementVerticalBounds(
|
||||
JSONObject placement,
|
||||
String context,
|
||||
List<String> blockingErrors
|
||||
) {
|
||||
boolean underground = false;
|
||||
if (placement.has("underground")) {
|
||||
Object rawUnderground = placement.opt("underground");
|
||||
if (!(rawUnderground instanceof Boolean configuredUnderground)) {
|
||||
blockingErrors.add(context + " cannot validate its vertical envelope because underground"
|
||||
+ " must be true or false.");
|
||||
return null;
|
||||
}
|
||||
underground = configuredUnderground;
|
||||
}
|
||||
Long configuredMinimum = integralJsonNumber(placement, "minHeight", -2032L);
|
||||
Long configuredMaximum = integralJsonNumber(placement, "maxHeight", 2032L);
|
||||
if (configuredMinimum == null || configuredMaximum == null) {
|
||||
blockingErrors.add(context + " cannot validate its vertical envelope because minHeight and"
|
||||
+ " maxHeight must be finite integer values.");
|
||||
return null;
|
||||
}
|
||||
long minimumY = underground
|
||||
? Math.min(configuredMinimum, configuredMaximum) : configuredMinimum;
|
||||
long maximumY = underground
|
||||
? Math.max(configuredMinimum, configuredMaximum) : configuredMaximum;
|
||||
return new PlacementVerticalBounds(minimumY, maximumY, underground);
|
||||
}
|
||||
|
||||
private static ObjectPlaceMode resolvePlaceMode(
|
||||
JSONObject structure,
|
||||
String context,
|
||||
List<String> blockingErrors
|
||||
) {
|
||||
if (!structure.has("placeMode")) {
|
||||
return ObjectPlaceMode.STRUCTURE_PIECE;
|
||||
}
|
||||
Object rawPlaceMode = structure.opt("placeMode");
|
||||
if (!(rawPlaceMode instanceof String placeModeName)) {
|
||||
blockingErrors.add(context + " cannot validate its vertical envelope because placeMode must name"
|
||||
+ " an Iris object place mode.");
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return ObjectPlaceMode.valueOf(placeModeName);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
blockingErrors.add(context + " cannot validate its vertical envelope because placeMode '"
|
||||
+ placeModeName + "' is not supported.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Long integralJsonNumber(JSONObject owner, String field, long defaultValue) {
|
||||
if (!owner.has(field)) {
|
||||
return defaultValue;
|
||||
}
|
||||
Object rawValue = owner.opt(field);
|
||||
if (!(rawValue instanceof Number number)) {
|
||||
return null;
|
||||
}
|
||||
double value = number.doubleValue();
|
||||
if (!Double.isFinite(value) || value != Math.rint(value)
|
||||
|| value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
|
||||
return null;
|
||||
}
|
||||
return (long) value;
|
||||
}
|
||||
|
||||
private record DimensionVerticalBounds(long minimumY, long maximumY) {
|
||||
}
|
||||
|
||||
private record PlacementVerticalBounds(long minimumY, long maximumY, boolean underground) {
|
||||
}
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.StructurePlacementGrid;
|
||||
import art.arcane.iris.engine.framework.StructurePlacementScope;
|
||||
import art.arcane.iris.builtin.structure.StructureAnchorMode;
|
||||
import art.arcane.iris.builtin.structure.StructurePlacement;
|
||||
import art.arcane.iris.builtin.structure.NativeStructureSource;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Where the pack's {@code nativeStructures} placements start platform structures: for one chunk, every placement in
|
||||
* scope whose grid starts there picks a weighted source and a base height. When several placements start the same
|
||||
* structure in one chunk, the placement with the lowest {@link StructurePlacementGrid#placementIdentity} (unsigned)
|
||||
* wins. Seeded from the mantle seed with the selection domain the planner always used, so worlds keep their starts.
|
||||
*/
|
||||
public final class NativeStartPlanner {
|
||||
private static final long NATIVE_SELECTION_DOMAIN = 0x4E41544956454A53L;
|
||||
|
||||
private NativeStartPlanner() {
|
||||
}
|
||||
|
||||
/** One start a {@code nativeStructures} placement makes: the placement, its chosen source and world base Y. */
|
||||
public record Plan(StructurePlacement placement, NativeStructureSource source, int chunkX, int chunkZ, int baseY) {
|
||||
}
|
||||
|
||||
public static List<Plan> plansAt(Engine engine, int chunkX, int chunkZ) {
|
||||
Map<String, Plan> plansByStructure = new LinkedHashMap<>();
|
||||
for (StructurePlacement placement : StructurePlacementScope.placementsAt(engine, chunkX, chunkZ)) {
|
||||
Plan plan = planAt(engine, placement, chunkX, chunkZ);
|
||||
if (plan == null) {
|
||||
continue;
|
||||
}
|
||||
String structureKey = normalize(plan.source().structure());
|
||||
Plan current = plansByStructure.get(structureKey);
|
||||
if (current == null || comparePlacementPriority(plan.placement(), current.placement()) < 0) {
|
||||
plansByStructure.put(structureKey, plan);
|
||||
}
|
||||
}
|
||||
return List.copyOf(plansByStructure.values());
|
||||
}
|
||||
|
||||
public static Plan planAt(Engine engine, StructurePlacement placement, int chunkX, int chunkZ) {
|
||||
validateBackend(placement);
|
||||
if (!placement.hasNativeStructures()) {
|
||||
return null;
|
||||
}
|
||||
Engine activeEngine = Objects.requireNonNull(engine, "Native structure planner requires an engine");
|
||||
if (activeEngine.getSeedManager() == null) {
|
||||
throw new IllegalStateException("Native structure planner requires a bound seed manager");
|
||||
}
|
||||
long mantleSeed = activeEngine.getSeedManager().getMantle();
|
||||
if (!StructurePlacementGrid.startsInChunk(placement, chunkX, chunkZ, mantleSeed)) {
|
||||
return null;
|
||||
}
|
||||
RNG placementRng = StructurePlacementGrid.placementRng(
|
||||
placement, chunkX, chunkZ, mantleSeed).nextParallelRNG(NATIVE_SELECTION_DOMAIN);
|
||||
NativeStructureSource source = selectSource(placement.nativeStructures(), placementRng);
|
||||
Integer baseY = resolveBaseY(activeEngine, placement, chunkX, chunkZ, placementRng);
|
||||
if (baseY == null) {
|
||||
return null;
|
||||
}
|
||||
return new Plan(placement, source, chunkX, chunkZ, baseY);
|
||||
}
|
||||
|
||||
public static void validateBackend(StructurePlacement placement) {
|
||||
if (placement == null) {
|
||||
throw new IllegalStateException("Structure placement must not be null");
|
||||
}
|
||||
boolean iris = placement.hasIrisStructures();
|
||||
boolean nativeStructure = placement.hasNativeStructures();
|
||||
if (iris == nativeStructure) {
|
||||
throw new IllegalStateException("Structure placement must declare exactly one backend: "
|
||||
+ "structures or nativeStructures");
|
||||
}
|
||||
if (nativeStructure && placement.anchor() != StructureAnchorMode.LEGACY) {
|
||||
throw new IllegalStateException("Native structure placements do not support the Iris anchor field");
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isSubmerged(Engine engine, int blockX, int blockZ) {
|
||||
return engine.getHeight(blockX, blockZ, true) < engine.getDimension().getFluidHeight();
|
||||
}
|
||||
|
||||
static NativeStructureSource selectSource(List<NativeStructureSource> sources, RNG rng) {
|
||||
Objects.requireNonNull(sources, "Native structure sources must not be null");
|
||||
Objects.requireNonNull(rng, "Native structure selection requires an RNG");
|
||||
long totalWeight = 0L;
|
||||
for (NativeStructureSource source : sources) {
|
||||
if (source == null || source.structure() == null || source.structure().isBlank()) {
|
||||
throw new IllegalStateException("Native structure placement contains a blank source");
|
||||
}
|
||||
if (source.weight() < 1) {
|
||||
throw new IllegalStateException("Native structure source '" + source.structure()
|
||||
+ "' has invalid weight " + source.weight());
|
||||
}
|
||||
totalWeight = Math.addExact(totalWeight, source.weight());
|
||||
}
|
||||
if (totalWeight > Integer.MAX_VALUE) {
|
||||
throw new IllegalStateException("Native structure source weights exceed " + Integer.MAX_VALUE);
|
||||
}
|
||||
int roll = rng.nextInt((int) totalWeight);
|
||||
for (NativeStructureSource source : sources) {
|
||||
roll -= source.weight();
|
||||
if (roll < 0) {
|
||||
return source;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("Native structure source selection produced no result");
|
||||
}
|
||||
|
||||
private static Integer resolveBaseY(Engine engine, StructurePlacement placement,
|
||||
int chunkX, int chunkZ, RNG rng) {
|
||||
int worldMin = engine.getMinHeight() + 1;
|
||||
int worldMax = engine.getMinHeight() + engine.getHeight() - 1;
|
||||
if (worldMin > worldMax) {
|
||||
throw new IllegalStateException("Native structure placement has invalid world height bounds");
|
||||
}
|
||||
int blockX = (chunkX << 4) + 8;
|
||||
int blockZ = (chunkZ << 4) + 8;
|
||||
if (!placement.underwater() && isSubmerged(engine, blockX, blockZ)) {
|
||||
return null;
|
||||
}
|
||||
if (!placement.underground()) {
|
||||
int surfaceY = engine.getHeight(blockX, blockZ, true) + engine.getMinHeight();
|
||||
if (surfaceY < placement.minHeight() || surfaceY > placement.maxHeight()) {
|
||||
return null;
|
||||
}
|
||||
return surfaceY;
|
||||
}
|
||||
int bandMin = Math.max(worldMin, Math.min(placement.minHeight(), placement.maxHeight()));
|
||||
int bandMax = Math.min(worldMax, Math.max(placement.minHeight(), placement.maxHeight()));
|
||||
if (bandMin > bandMax) {
|
||||
return null;
|
||||
}
|
||||
return bandMin == bandMax ? bandMin : bandMin + rng.nextInt((bandMax - bandMin) + 1);
|
||||
}
|
||||
|
||||
private static int comparePlacementPriority(StructurePlacement left, StructurePlacement right) {
|
||||
long leftIdentity = StructurePlacementGrid.placementIdentity(left);
|
||||
long rightIdentity = StructurePlacementGrid.placementIdentity(right);
|
||||
return Long.compareUnsigned(leftIdentity, rightIdentity);
|
||||
}
|
||||
|
||||
private static String normalize(String structureKey) {
|
||||
return structureKey == null ? "" : structureKey.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
-139
@@ -1,139 +0,0 @@
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcell;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.value.IrisPosition;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class PlanarJigsawWorkcellResolver {
|
||||
public static final int DEFAULT_SIZE = 16;
|
||||
public static final int MAX_WIDTH = 128;
|
||||
public static final int MAX_HEIGHT = 192;
|
||||
public static final int MAX_DEPTH = 128;
|
||||
public static final long MAX_VOLUME = 2_097_152L;
|
||||
|
||||
private PlanarJigsawWorkcellResolver() {
|
||||
}
|
||||
|
||||
public static Map<IrisJigsawWorkcellArchetype, ResolvedWorkcell> resolve(IrisStructure structure) {
|
||||
IrisStructure source = Objects.requireNonNull(structure, "Planar jigsaw structure");
|
||||
EnumMap<IrisJigsawWorkcellArchetype, ResolvedWorkcell> resolved =
|
||||
new EnumMap<>(IrisJigsawWorkcellArchetype.class);
|
||||
if (source.getPlanarWorkcells() == null || source.getPlanarWorkcells().isEmpty()) {
|
||||
IrisPosition fallback = source.getCellSize() == null
|
||||
? new IrisPosition(DEFAULT_SIZE, DEFAULT_SIZE, DEFAULT_SIZE)
|
||||
: source.getCellSize();
|
||||
for (IrisJigsawWorkcellArchetype archetype : IrisJigsawWorkcellArchetype.values()) {
|
||||
ResolvedWorkcell workcell = new ResolvedWorkcell(
|
||||
archetype,
|
||||
"",
|
||||
fallback.getX(),
|
||||
fallback.getY(),
|
||||
fallback.getZ(),
|
||||
true);
|
||||
validate(workcell);
|
||||
resolved.put(archetype, workcell);
|
||||
}
|
||||
return Collections.unmodifiableMap(resolved);
|
||||
}
|
||||
|
||||
for (IrisJigsawWorkcell configured : source.getPlanarWorkcells()) {
|
||||
if (configured == null || configured.getArchetype() == null) {
|
||||
throw new IllegalArgumentException("Planar jigsaw workcells require an archetype");
|
||||
}
|
||||
ResolvedWorkcell workcell = new ResolvedWorkcell(
|
||||
configured.getArchetype(),
|
||||
normalizeDisplayName(configured.getDisplayName()),
|
||||
configured.getWidth(),
|
||||
configured.getHeight(),
|
||||
configured.getDepth(),
|
||||
configured.isEnabled());
|
||||
validate(workcell);
|
||||
if (resolved.putIfAbsent(workcell.archetype(), workcell) != null) {
|
||||
throw new IllegalArgumentException(
|
||||
"Planar jigsaw workcell " + workcell.archetype() + " is configured more than once");
|
||||
}
|
||||
}
|
||||
if (resolved.size() != IrisJigsawWorkcellArchetype.values().length) {
|
||||
for (IrisJigsawWorkcellArchetype archetype : IrisJigsawWorkcellArchetype.values()) {
|
||||
if (!resolved.containsKey(archetype)) {
|
||||
throw new IllegalArgumentException("Planar jigsaw workcell " + archetype + " is missing");
|
||||
}
|
||||
}
|
||||
}
|
||||
return Collections.unmodifiableMap(resolved);
|
||||
}
|
||||
|
||||
public static ResolvedWorkcell workcell(
|
||||
Map<IrisJigsawWorkcellArchetype, ResolvedWorkcell> workcells,
|
||||
IrisJigsawPiece piece
|
||||
) {
|
||||
Map<IrisJigsawWorkcellArchetype, ResolvedWorkcell> resolved = Objects.requireNonNull(
|
||||
workcells,
|
||||
"Planar jigsaw workcells");
|
||||
IrisJigsawWorkcellArchetype archetype = IrisJigsawWorkcellArchetype.fromPiece(piece);
|
||||
ResolvedWorkcell workcell = resolved.get(archetype);
|
||||
if (workcell == null) {
|
||||
throw new IllegalArgumentException("Planar jigsaw workcell " + archetype + " is not configured");
|
||||
}
|
||||
return workcell;
|
||||
}
|
||||
|
||||
public static IrisPosition canonicalDimensions(IrisJigsawPiece piece, IrisObject object) {
|
||||
IrisJigsawPiece sourcePiece = Objects.requireNonNull(piece, "Planar jigsaw piece");
|
||||
IrisObject sourceObject = Objects.requireNonNull(object, "Planar jigsaw object");
|
||||
IrisJigsawWorkcellArchetype archetype = IrisJigsawWorkcellArchetype.fromPiece(sourcePiece);
|
||||
int quarterTurns = archetype.sourceToCanonicalQuarterTurns(sourcePiece);
|
||||
return Math.floorMod(quarterTurns, 2) == 0
|
||||
? new IrisPosition(sourceObject.getW(), sourceObject.getH(), sourceObject.getD())
|
||||
: new IrisPosition(sourceObject.getD(), sourceObject.getH(), sourceObject.getW());
|
||||
}
|
||||
|
||||
public record ResolvedWorkcell(
|
||||
IrisJigsawWorkcellArchetype archetype,
|
||||
String displayName,
|
||||
int width,
|
||||
int height,
|
||||
int depth,
|
||||
boolean enabled
|
||||
) {
|
||||
public ResolvedWorkcell {
|
||||
Objects.requireNonNull(archetype, "Planar jigsaw workcell archetype");
|
||||
displayName = normalizeDisplayName(displayName);
|
||||
}
|
||||
|
||||
public IrisPosition dimensions() {
|
||||
return new IrisPosition(width, height, depth);
|
||||
}
|
||||
|
||||
public boolean contains(IrisPosition dimensions) {
|
||||
IrisPosition size = Objects.requireNonNull(dimensions, "Planar jigsaw object dimensions");
|
||||
return size.getX() <= width && size.getY() <= height && size.getZ() <= depth;
|
||||
}
|
||||
}
|
||||
|
||||
private static String normalizeDisplayName(String displayName) {
|
||||
return displayName == null ? "" : displayName.trim();
|
||||
}
|
||||
|
||||
private static void validate(ResolvedWorkcell workcell) {
|
||||
if (workcell.width() < 3 || workcell.width() > MAX_WIDTH
|
||||
|| workcell.height() < 1 || workcell.height() > MAX_HEIGHT
|
||||
|| workcell.depth() < 3 || workcell.depth() > MAX_DEPTH) {
|
||||
throw new IllegalArgumentException("Planar jigsaw workcell " + workcell.archetype()
|
||||
+ " dimensions must keep width/depth within 3..128 and height within 1..192");
|
||||
}
|
||||
long volume = (long) workcell.width() * workcell.height() * workcell.depth();
|
||||
if (volume > MAX_VOLUME) {
|
||||
throw new IllegalArgumentException("Planar jigsaw workcell " + workcell.archetype()
|
||||
+ " volume cannot exceed " + MAX_VOLUME + " blocks");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.engine.framework.PlacedStructurePiece;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public record StructureAssemblyResult(
|
||||
StructureAssemblyStatus status,
|
||||
List<PlacedStructurePiece> pieces,
|
||||
String selectedTheme,
|
||||
String detail
|
||||
) {
|
||||
public StructureAssemblyResult {
|
||||
status = Objects.requireNonNull(status, "Structure assembly status");
|
||||
pieces = List.copyOf(Objects.requireNonNull(pieces, "Structure assembly pieces"));
|
||||
selectedTheme = normalize(selectedTheme);
|
||||
detail = normalize(detail);
|
||||
if (status == StructureAssemblyStatus.COMPLETE && pieces.isEmpty()) {
|
||||
throw new IllegalArgumentException("A complete structure assembly must contain at least one piece");
|
||||
}
|
||||
if (status == StructureAssemblyStatus.INTENTIONAL_EMPTY && !pieces.isEmpty()) {
|
||||
throw new IllegalArgumentException("An intentionally empty structure assembly cannot contain pieces");
|
||||
}
|
||||
if (status.isFailure() && detail.isEmpty()) {
|
||||
throw new IllegalArgumentException("A failed structure assembly requires failure detail");
|
||||
}
|
||||
}
|
||||
|
||||
public static StructureAssemblyResult complete(
|
||||
List<PlacedStructurePiece> pieces,
|
||||
String selectedTheme
|
||||
) {
|
||||
return new StructureAssemblyResult(
|
||||
StructureAssemblyStatus.COMPLETE,
|
||||
pieces,
|
||||
selectedTheme,
|
||||
"");
|
||||
}
|
||||
|
||||
public static StructureAssemblyResult intentionalEmpty(
|
||||
String selectedTheme,
|
||||
String detail
|
||||
) {
|
||||
return new StructureAssemblyResult(
|
||||
StructureAssemblyStatus.INTENTIONAL_EMPTY,
|
||||
List.of(),
|
||||
selectedTheme,
|
||||
detail);
|
||||
}
|
||||
|
||||
public static StructureAssemblyResult failed(
|
||||
StructureAssemblyStatus status,
|
||||
List<PlacedStructurePiece> pieces,
|
||||
String selectedTheme,
|
||||
String detail
|
||||
) {
|
||||
if (Objects.requireNonNull(status, "Structure assembly failure status").isComplete()) {
|
||||
throw new IllegalArgumentException("A failed structure assembly requires a failure status");
|
||||
}
|
||||
return new StructureAssemblyResult(status, pieces, selectedTheme, detail);
|
||||
}
|
||||
|
||||
public boolean hasOutput() {
|
||||
return status == StructureAssemblyStatus.COMPLETE && !pieces.isEmpty();
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.IrisPackResources;
|
||||
import art.arcane.iris.engine.framework.StructureAssembler;
|
||||
import art.arcane.iris.engine.object.value.IrisPosition;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
|
||||
import com.volmit.ModuleLog;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
/**
|
||||
* Compiled structure graphs, kept per resource snapshot of the pack: every reload of the pack's resources starts a new
|
||||
* snapshot ({@link IrisData#getPackResources()}), so nothing stale is ever read and nothing is invalidated by hand.
|
||||
*/
|
||||
public final class StructureGraphCatalog {
|
||||
private static final Cache<IrisPackResources, ConcurrentMap<String, StructureGraphCompilation>> CACHE =
|
||||
Caffeine.newBuilder().weakKeys().build();
|
||||
private static final Cache<IrisPackResources, ConcurrentMap<String, Boolean>> RUNTIME_OUTPUT =
|
||||
Caffeine.newBuilder().weakKeys().build();
|
||||
private static final List<Long> RUNTIME_SAMPLE_SEEDS = List.of(
|
||||
0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L);
|
||||
|
||||
private StructureGraphCatalog() {
|
||||
}
|
||||
|
||||
public static StructureGraphCompilation compile(IrisData data, IrisStructure structure, ModuleLog log) {
|
||||
IrisData activeData = Objects.requireNonNull(data);
|
||||
IrisStructure activeStructure = Objects.requireNonNull(structure);
|
||||
String structureKey = activeStructure.getLoadKey();
|
||||
if (structureKey == null || structureKey.isBlank()) {
|
||||
return compileAndReport(activeData, activeStructure, log);
|
||||
}
|
||||
ConcurrentMap<String, StructureGraphCompilation> catalog = CACHE.get(
|
||||
activeData.getPackResources(), ignored -> new ConcurrentHashMap<>());
|
||||
return catalog.computeIfAbsent(structureKey, ignored -> compileAndReport(activeData, activeStructure, log));
|
||||
}
|
||||
|
||||
public static boolean guaranteesRuntimeOutput(IrisData data, IrisStructure structure, ModuleLog log) {
|
||||
IrisData activeData = Objects.requireNonNull(data);
|
||||
IrisStructure activeStructure = Objects.requireNonNull(structure);
|
||||
if (!compile(activeData, activeStructure, log).guaranteesAssemblyOutput()) {
|
||||
return false;
|
||||
}
|
||||
String structureKey = activeStructure.getLoadKey();
|
||||
if (structureKey == null || structureKey.isBlank()) {
|
||||
return sampleRuntimeAssembly(activeData, activeStructure, log);
|
||||
}
|
||||
ConcurrentMap<String, Boolean> catalog = RUNTIME_OUTPUT.get(
|
||||
activeData.getPackResources(), ignored -> new ConcurrentHashMap<>());
|
||||
return catalog.computeIfAbsent(
|
||||
structureKey, ignored -> sampleRuntimeAssembly(activeData, activeStructure, log));
|
||||
}
|
||||
|
||||
private static StructureGraphCompilation compileAndReport(IrisData data, IrisStructure structure, ModuleLog log) {
|
||||
StructureGraphCompilation compilation = StructureGraphCompiler.compile(
|
||||
structure, StructureGraphResolver.forData(data));
|
||||
String structureKey = structure.getLoadKey() == null || structure.getLoadKey().isBlank()
|
||||
? "<unkeyed>" : structure.getLoadKey();
|
||||
for (StructureGraphDiagnostic diagnostic : compilation.getDiagnostics()) {
|
||||
String message = "[StructureGraph:" + structureKey + "] " + diagnostic.message();
|
||||
if (diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR) {
|
||||
log.error(message, null);
|
||||
} else {
|
||||
log.warn(message);
|
||||
}
|
||||
}
|
||||
if (!compilation.isAssemblyViable()) {
|
||||
log.error("[StructureGraph:" + structureKey
|
||||
+ "] Graph rejected because deterministic assembly did not complete.", null);
|
||||
}
|
||||
return compilation;
|
||||
}
|
||||
|
||||
private static boolean sampleRuntimeAssembly(IrisData data, IrisStructure structure, ModuleLog log) {
|
||||
for (long seed : RUNTIME_SAMPLE_SEEDS) {
|
||||
try {
|
||||
StructureAssembler assembler = StructureAssembler.forData(
|
||||
data, structure, new IrisPosition(0, 64, 0), log);
|
||||
StructureAssemblyResult result = assembler.assemble(new RNG(seed));
|
||||
if (!result.hasOutput()) {
|
||||
return false;
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
log.error("Failed to sample the runtime assembly of a structure", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
-242
@@ -1,242 +0,0 @@
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class StructureGraphCompilation {
|
||||
private final CompiledStructureGraph graph;
|
||||
private final List<StructureGraphDiagnostic> diagnostics;
|
||||
private final List<StructureGraphAssemblySample> assemblySamples;
|
||||
|
||||
StructureGraphCompilation(Builder builder) {
|
||||
graph = Objects.requireNonNull(builder.graph);
|
||||
diagnostics = Collections.unmodifiableList(new ArrayList<>(builder.diagnostics));
|
||||
assemblySamples = Collections.unmodifiableList(new ArrayList<>(builder.assemblySamples));
|
||||
}
|
||||
|
||||
static Builder builder(CompiledStructureGraph graph) {
|
||||
return new Builder(graph);
|
||||
}
|
||||
|
||||
public CompiledStructureGraph getGraph() {
|
||||
return graph;
|
||||
}
|
||||
|
||||
public List<StructureGraphDiagnostic> getDiagnostics() {
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
public List<StructureGraphAssemblySample> getAssemblySamples() {
|
||||
return assemblySamples;
|
||||
}
|
||||
|
||||
public boolean hasErrors() {
|
||||
for (StructureGraphDiagnostic diagnostic : diagnostics) {
|
||||
if (diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isAssemblyViable() {
|
||||
if (hasErrors() || assemblySamples.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (StructureGraphAssemblySample sample : assemblySamples) {
|
||||
if (!sample.outcome().isComplete()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean guaranteesAssemblyOutput() {
|
||||
if (!isAssemblyViable()) {
|
||||
return false;
|
||||
}
|
||||
String startPoolKey = graph.getStructure().getStartPool();
|
||||
if (startPoolKey == null || startPoolKey.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
IrisJigsawPool startPool = graph.getPools().get(startPoolKey.trim());
|
||||
if (startPool == null || startPool.getPieces() == null || startPool.getPieces().isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (String theme : themes()) {
|
||||
if (!startPoolGuaranteesOutput(startPool, theme)
|
||||
|| !reachableBranchesCanTerminate(theme)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean startPoolGuaranteesOutput(IrisJigsawPool startPool, String theme) {
|
||||
boolean certainPhysicalEntry = false;
|
||||
for (IrisJigsawPieceEntry entry : startPool.getPieces()) {
|
||||
if (entry == null || entry.getWeight() <= 0 || !Double.isFinite(entry.getChance())
|
||||
|| entry.getChance() <= 0D || entry.getChance() > 1D) {
|
||||
continue;
|
||||
}
|
||||
if (entry.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
IrisJigsawPiece piece = graph.getPieces().get(normalize(entry.getPiece()));
|
||||
if (piece == null || !JigsawPoolSelection.pieceEligible(piece, theme, 0, 0)) {
|
||||
continue;
|
||||
}
|
||||
IrisObject object = graph.getObjects().get(normalize(piece.getObject()));
|
||||
if (object == null || !fitsStartRadius(object)) {
|
||||
return false;
|
||||
}
|
||||
if (entry.getChance() == 1D) {
|
||||
certainPhysicalEntry = true;
|
||||
}
|
||||
}
|
||||
return certainPhysicalEntry;
|
||||
}
|
||||
|
||||
private boolean reachableBranchesCanTerminate(String theme) {
|
||||
for (String pieceKey : graph.getReachablePieces()) {
|
||||
IrisJigsawPiece piece = graph.getPieces().get(pieceKey);
|
||||
if (piece == null || piece.getConnectors() == null) {
|
||||
return false;
|
||||
}
|
||||
if (!piece.supportsTheme(theme) || piece.resolvedRules().isTerminal()) {
|
||||
continue;
|
||||
}
|
||||
for (IrisJigsawConnector connector : piece.getConnectors()) {
|
||||
if (connector == null) {
|
||||
return false;
|
||||
}
|
||||
IrisJigsawPool pool = graph.getPools().get(normalize(connector.getPool()));
|
||||
if (pool == null) {
|
||||
return false;
|
||||
}
|
||||
if (pool.requiresFallback(graph.getStructure().isRequireCaps())) {
|
||||
if (!hasRequiredTerminal(pool, theme)) {
|
||||
return false;
|
||||
}
|
||||
} else if (graph.getStructure().resolvedBranchFailurePolicy()
|
||||
!= IrisJigsawBranchFailurePolicy.TERMINATE_BRANCH
|
||||
&& !canTerminateWithoutPlacement(pool)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean hasRequiredTerminal(IrisJigsawPool pool, String theme) {
|
||||
String fallbackKey = JigsawPoolSelection.directFallbackKey(pool);
|
||||
if (fallbackKey.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
IrisJigsawPool fallback = graph.getPools().get(fallbackKey);
|
||||
if (fallback == null || fallback.getPieces() == null) {
|
||||
return false;
|
||||
}
|
||||
for (IrisJigsawPieceEntry entry : fallback.getPieces()) {
|
||||
if (entry == null || entry.isEmpty() || entry.getWeight() <= 0 || entry.getChance() != 1D) {
|
||||
continue;
|
||||
}
|
||||
IrisJigsawPiece piece = graph.getPieces().get(normalize(entry.getPiece()));
|
||||
if (piece != null && piece.supportsTheme(theme) && piece.resolvedRules().isTerminal()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean canTerminateWithoutPlacement(IrisJigsawPool pool) {
|
||||
if (hasEmptyChoice(pool)) {
|
||||
return true;
|
||||
}
|
||||
if (pool == null) {
|
||||
return false;
|
||||
}
|
||||
String fallbackKey = JigsawPoolSelection.directFallbackKey(pool);
|
||||
return !fallbackKey.isEmpty() && hasEmptyChoice(graph.getPools().get(fallbackKey));
|
||||
}
|
||||
|
||||
private boolean hasEmptyChoice(IrisJigsawPool pool) {
|
||||
if (pool == null || pool.getPieces() == null) {
|
||||
return false;
|
||||
}
|
||||
if (pool.getPieces().isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
for (IrisJigsawPieceEntry entry : pool.getPieces()) {
|
||||
if (entry != null && entry.getWeight() > 0 && entry.getChance() == 1D && entry.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean fitsStartRadius(IrisObject object) {
|
||||
long radius = (long) graph.getStructure().getMaxSizeChunks() * 16L;
|
||||
return axisFitsRadius(object.getW(), radius) && axisFitsRadius(object.getD(), radius);
|
||||
}
|
||||
|
||||
private List<String> themes() {
|
||||
if (graph.getStructure().getThemeSets() == null || graph.getStructure().getThemeSets().isEmpty()) {
|
||||
return List.of("");
|
||||
}
|
||||
List<String> themes = new ArrayList<>(graph.getStructure().getThemeSets().size());
|
||||
for (IrisJigsawThemeSet theme : graph.getStructure().getThemeSets()) {
|
||||
if (theme != null && theme.getKey() != null && !theme.getKey().isBlank()) {
|
||||
themes.add(theme.getKey().trim());
|
||||
}
|
||||
}
|
||||
return List.copyOf(themes);
|
||||
}
|
||||
|
||||
private boolean axisFitsRadius(int size, long radius) {
|
||||
if (size < 1 || radius < 1L) {
|
||||
return false;
|
||||
}
|
||||
long minimum = -(size / 2L);
|
||||
long maximum = minimum + size - 1L;
|
||||
return minimum >= -radius && maximum <= radius;
|
||||
}
|
||||
|
||||
private String normalize(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
|
||||
static final class Builder {
|
||||
private final CompiledStructureGraph graph;
|
||||
private final List<StructureGraphDiagnostic> diagnostics = new ArrayList<>();
|
||||
private final List<StructureGraphAssemblySample> assemblySamples = new ArrayList<>();
|
||||
|
||||
private Builder(CompiledStructureGraph graph) {
|
||||
this.graph = Objects.requireNonNull(graph);
|
||||
}
|
||||
|
||||
Builder diagnostics(List<StructureGraphDiagnostic> values) {
|
||||
diagnostics.addAll(values);
|
||||
return this;
|
||||
}
|
||||
|
||||
Builder assemblySamples(List<StructureGraphAssemblySample> values) {
|
||||
assemblySamples.addAll(values);
|
||||
return this;
|
||||
}
|
||||
|
||||
StructureGraphCompilation build() {
|
||||
return new StructureGraphCompilation(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
-1264
File diff suppressed because it is too large.
Load diff
@@ -1,74 +0,0 @@
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public interface StructureGraphResolver {
|
||||
IrisJigsawPool loadPool(String key);
|
||||
|
||||
IrisJigsawPiece loadPiece(String key);
|
||||
|
||||
IrisObject loadObject(String key);
|
||||
|
||||
static StructureGraphResolver forData(IrisData data) {
|
||||
return new IrisDataStructureGraphResolver(Objects.requireNonNull(data));
|
||||
}
|
||||
|
||||
static StructureGraphResolver forCompiledGraph(CompiledStructureGraph graph) {
|
||||
return new CompiledStructureGraphResolver(Objects.requireNonNull(graph));
|
||||
}
|
||||
}
|
||||
|
||||
final class IrisDataStructureGraphResolver implements StructureGraphResolver {
|
||||
private final IrisData data;
|
||||
|
||||
IrisDataStructureGraphResolver(IrisData data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisJigsawPool loadPool(String key) {
|
||||
return StructureResources.pool(data, key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisJigsawPiece loadPiece(String key) {
|
||||
return StructureResources.piece(data, key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisObject loadObject(String key) {
|
||||
return data.load(IrisObject.class, key, false);
|
||||
}
|
||||
}
|
||||
|
||||
final class CompiledStructureGraphResolver implements StructureGraphResolver {
|
||||
private final CompiledStructureGraph graph;
|
||||
|
||||
CompiledStructureGraphResolver(CompiledStructureGraph graph) {
|
||||
this.graph = graph;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisJigsawPool loadPool(String key) {
|
||||
return graph.getPools().get(normalize(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisJigsawPiece loadPiece(String key) {
|
||||
return graph.getPieces().get(normalize(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisObject loadObject(String key) {
|
||||
return graph.getObjects().get(normalize(key));
|
||||
}
|
||||
|
||||
private static String normalize(String key) {
|
||||
return key == null ? "" : key.trim();
|
||||
}
|
||||
}
|
||||
-324
@@ -1,324 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.framework.PlacedStructurePiece;
|
||||
import art.arcane.iris.engine.framework.StructureAssembler;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
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 art.arcane.iris.engine.object.value.IrisPosition;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.validation.Problem;
|
||||
import com.volmit.validation.Severity;
|
||||
import com.volmit.validation.Subject;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Checks that the structures of a pack assemble: each one's jigsaw graph is compiled, the compiler's diagnostics
|
||||
* become problems, and a viable graph is assembled from every seed of {@link #GEOMETRY_SAMPLE_SEEDS} with collisions
|
||||
* and radius checked. What the samples show tells {@link NativeReplacementValidation} which structures always give
|
||||
* output and how far their pieces reach above and below the anchor.
|
||||
* <p>
|
||||
* Structures, pools and pieces are the pack's {@link StructureResources}; objects are read only as far as their
|
||||
* bounds, straight from their files. A structure file that fails to load is skipped here: Iris's own structure graph
|
||||
* check reports malformed JSON. Every problem concerns the structure's file.
|
||||
*/
|
||||
public final class StructureGraphValidation {
|
||||
private static final List<Long> GEOMETRY_SAMPLE_SEEDS = List.of(
|
||||
0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L);
|
||||
private static final int GEOMETRY_SAMPLE_ORIGIN_Y = 64;
|
||||
private static final String LEGACY_INDEX_KEY = "structure-index";
|
||||
private static final String OBJECTS_FOLDER = "objects";
|
||||
private static final String OBJECT_EXTENSION = ".iob";
|
||||
private static final String JSON_EXTENSION = ".json";
|
||||
|
||||
private StructureGraphValidation() {
|
||||
}
|
||||
|
||||
/** Checks every structure of the pack {@code data} holds. */
|
||||
public static Validation validate(IrisData data) {
|
||||
return validate(data, null);
|
||||
}
|
||||
|
||||
/** Checks the structures of the pack {@code data} holds whose keys are in {@code activeStructureKeys}, or all when it is null. */
|
||||
public static Validation validate(IrisData data, Set<String> activeStructureKeys) {
|
||||
List<Problem> problems = new ArrayList<>();
|
||||
Set<String> replacementOutputStructures = new LinkedHashSet<>();
|
||||
Map<String, List<SampledVerticalEnvelope>> sampledVerticalEnvelopes = new LinkedHashMap<>();
|
||||
PackStructureResolver resolver = new PackStructureResolver(data);
|
||||
for (ResourceId id : data.getPackResources().ids(StructureResources.STRUCTURES)) {
|
||||
String structureKey = id.path();
|
||||
if (structureKey.equals(LEGACY_INDEX_KEY) || (activeStructureKeys != null && !activeStructureKeys.contains(structureKey))) {
|
||||
continue;
|
||||
}
|
||||
IrisStructure structure = StructureResources.structure(data, structureKey);
|
||||
if (structure == null) {
|
||||
continue;
|
||||
}
|
||||
validateStructure(structure, resolver, problems, replacementOutputStructures, sampledVerticalEnvelopes);
|
||||
}
|
||||
return new Validation(problems, replacementOutputStructures, sampledVerticalEnvelopes);
|
||||
}
|
||||
|
||||
private static void validateStructure(
|
||||
IrisStructure structure,
|
||||
StructureGraphResolver resolver,
|
||||
List<Problem> problems,
|
||||
Set<String> replacementOutputStructures,
|
||||
Map<String, List<SampledVerticalEnvelope>> sampledVerticalEnvelopes
|
||||
) {
|
||||
String structureKey = structure.getLoadKey();
|
||||
Subject file = Subject.file(StructureResources.STRUCTURES.folder() + "/" + structureKey + JSON_EXTENSION);
|
||||
StructureGraphCompilation compilation;
|
||||
try {
|
||||
compilation = StructureGraphCompiler.compile(structure, resolver);
|
||||
} catch (MalformedObjectResourceException e) {
|
||||
problems.add(Problem.error(file, e.getMessage()));
|
||||
return;
|
||||
}
|
||||
for (StructureGraphDiagnostic diagnostic : compilation.getDiagnostics()) {
|
||||
problems.add(diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR
|
||||
? Problem.error(file, diagnostic.message())
|
||||
: Problem.warning(file, diagnostic.message()));
|
||||
}
|
||||
if (!compilation.isAssemblyViable()) {
|
||||
problems.add(Problem.error(file, "Structure '" + structureKey
|
||||
+ "' does not produce a complete deterministic assembly and will not generate"
|
||||
+ failedSampleSummary(compilation) + "."));
|
||||
return;
|
||||
}
|
||||
RuntimeGeometryValidation geometry = validateRuntimeGeometry(compilation);
|
||||
if (!geometry.failures().isEmpty()) {
|
||||
problems.add(Problem.error(file, "Structure '" + structureKey
|
||||
+ "' fails sampled collision- and radius-aware assembly: "
|
||||
+ String.join("; ", geometry.failures()) + "."));
|
||||
return;
|
||||
}
|
||||
sampledVerticalEnvelopes.put(structureKey, geometry.sampledVerticalEnvelopes());
|
||||
if (compilation.guaranteesAssemblyOutput() && geometry.outputForEverySample()) {
|
||||
replacementOutputStructures.add(structureKey);
|
||||
}
|
||||
}
|
||||
|
||||
private static RuntimeGeometryValidation validateRuntimeGeometry(
|
||||
StructureGraphCompilation compilation
|
||||
) {
|
||||
List<String> failures = new ArrayList<>();
|
||||
List<SampledVerticalEnvelope> sampledVerticalEnvelopes = new ArrayList<>();
|
||||
boolean outputForEverySample = true;
|
||||
for (long seed : GEOMETRY_SAMPLE_SEEDS) {
|
||||
try {
|
||||
StructureAssembler assembler = StructureAssembler.forCompilation(
|
||||
compilation, new IrisPosition(0, GEOMETRY_SAMPLE_ORIGIN_Y, 0));
|
||||
StructureAssemblyResult result = assembler.assemble(new RNG(seed));
|
||||
if (result.status().isFailure()) {
|
||||
failures.add("seed " + seed + " returned " + result.status() + ": " + result.detail());
|
||||
} else if (!result.hasOutput()) {
|
||||
outputForEverySample = false;
|
||||
} else {
|
||||
sampledVerticalEnvelopes.add(sampleVerticalEnvelope(seed, result.pieces()));
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
failures.add("seed " + seed + " threw " + e.getClass().getSimpleName()
|
||||
+ ": " + failureMessage(e));
|
||||
}
|
||||
}
|
||||
return new RuntimeGeometryValidation(
|
||||
List.copyOf(failures), outputForEverySample, List.copyOf(sampledVerticalEnvelopes));
|
||||
}
|
||||
|
||||
private static SampledVerticalEnvelope sampleVerticalEnvelope(
|
||||
long seed,
|
||||
List<PlacedStructurePiece> pieces
|
||||
) {
|
||||
int minimumY = Integer.MAX_VALUE;
|
||||
int maximumY = Integer.MIN_VALUE;
|
||||
for (PlacedStructurePiece piece : pieces) {
|
||||
minimumY = Math.min(minimumY, piece.getMinY());
|
||||
maximumY = Math.max(maximumY, piece.getMaxY());
|
||||
}
|
||||
return new SampledVerticalEnvelope(
|
||||
seed,
|
||||
pieces.size(),
|
||||
Math.subtractExact(minimumY, GEOMETRY_SAMPLE_ORIGIN_Y),
|
||||
Math.subtractExact(maximumY, GEOMETRY_SAMPLE_ORIGIN_Y));
|
||||
}
|
||||
|
||||
private static Map<String, List<SampledVerticalEnvelope>> immutableEnvelopes(
|
||||
Map<String, List<SampledVerticalEnvelope>> sampledVerticalEnvelopes
|
||||
) {
|
||||
Map<String, List<SampledVerticalEnvelope>> immutable = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, List<SampledVerticalEnvelope>> entry : sampledVerticalEnvelopes.entrySet()) {
|
||||
immutable.put(entry.getKey(), List.copyOf(entry.getValue()));
|
||||
}
|
||||
return Map.copyOf(immutable);
|
||||
}
|
||||
|
||||
private static String failureMessage(RuntimeException exception) {
|
||||
return exception.getMessage() == null || exception.getMessage().isBlank()
|
||||
? "no failure detail" : exception.getMessage();
|
||||
}
|
||||
|
||||
private static String failedSampleSummary(StructureGraphCompilation compilation) {
|
||||
List<String> failures = new ArrayList<>();
|
||||
for (StructureGraphAssemblySample sample : compilation.getAssemblySamples()) {
|
||||
if (sample.outcome().isComplete()) {
|
||||
continue;
|
||||
}
|
||||
failures.add("seed " + sample.seed() + " placed " + sample.outcome().pieceKeys().size()
|
||||
+ " piece(s), status=" + sample.outcome().status()
|
||||
+ ": " + sample.outcome().detail());
|
||||
if (failures.size() == 3) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return failures.isEmpty() ? "" : " (" + String.join("; ", failures) + ")";
|
||||
}
|
||||
|
||||
/**
|
||||
* What the check found: its problems, the structures that gave output for every sample of a graph that
|
||||
* guarantees output (the only ones that may replace a vanilla structure), and each viable structure's sampled
|
||||
* vertical envelopes.
|
||||
*/
|
||||
public record Validation(
|
||||
List<Problem> problems,
|
||||
Set<String> replacementOutputStructures,
|
||||
Map<String, List<SampledVerticalEnvelope>> sampledVerticalEnvelopes
|
||||
) {
|
||||
public Validation {
|
||||
problems = List.copyOf(problems);
|
||||
replacementOutputStructures = Set.copyOf(replacementOutputStructures);
|
||||
sampledVerticalEnvelopes = immutableEnvelopes(sampledVerticalEnvelopes);
|
||||
}
|
||||
|
||||
/** The messages of the problems that stop the pack from loading. */
|
||||
public List<String> errors() {
|
||||
return messages(Severity.ERROR);
|
||||
}
|
||||
|
||||
/** The messages of the problems that are only shown. */
|
||||
public List<String> warnings() {
|
||||
return messages(Severity.WARNING);
|
||||
}
|
||||
|
||||
private List<String> messages(Severity severity) {
|
||||
return problems.stream().filter(problem -> problem.severity() == severity).map(Problem::message).distinct().toList();
|
||||
}
|
||||
}
|
||||
|
||||
/** Where one sampled assembly's pieces reach, relative to its anchor. */
|
||||
public record SampledVerticalEnvelope(long seed, int pieceCount, int minimumYOffset, int maximumYOffset) {
|
||||
public SampledVerticalEnvelope {
|
||||
if (pieceCount <= 0) {
|
||||
throw new IllegalArgumentException("Sampled vertical envelope must contain at least one piece");
|
||||
}
|
||||
if (maximumYOffset < minimumYOffset) {
|
||||
throw new IllegalArgumentException("Sampled vertical envelope maximum Y cannot be below minimum Y");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private record RuntimeGeometryValidation(
|
||||
List<String> failures,
|
||||
boolean outputForEverySample,
|
||||
List<SampledVerticalEnvelope> sampledVerticalEnvelopes
|
||||
) {
|
||||
}
|
||||
|
||||
/** Pools and pieces from the pack's structure resources; objects as far as their bounds, read from their files once each. */
|
||||
private static final class PackStructureResolver implements StructureGraphResolver {
|
||||
private final IrisData data;
|
||||
private final Path objectsRoot;
|
||||
private final Map<String, IrisObject> objects = new HashMap<>();
|
||||
private final Set<String> missingObjects = new LinkedHashSet<>();
|
||||
|
||||
private PackStructureResolver(IrisData data) {
|
||||
this.data = data;
|
||||
this.objectsRoot = data.getDataFolder().toPath().toAbsolutePath().normalize().resolve(OBJECTS_FOLDER);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisJigsawPool loadPool(String key) {
|
||||
return StructureResources.pool(data, key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisJigsawPiece loadPiece(String key) {
|
||||
return StructureResources.piece(data, key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisObject loadObject(String key) {
|
||||
if (objects.containsKey(key)) {
|
||||
return objects.get(key);
|
||||
}
|
||||
if (missingObjects.contains(key)) {
|
||||
return null;
|
||||
}
|
||||
Path file = resolveObject(key);
|
||||
IrisObject object = file == null ? null : readObjectBounds(file);
|
||||
if (object == null) {
|
||||
missingObjects.add(key);
|
||||
return null;
|
||||
}
|
||||
objects.put(key, object);
|
||||
return object;
|
||||
}
|
||||
|
||||
private Path resolveObject(String key) {
|
||||
if (key == null || key.isBlank() || key.indexOf('\\') >= 0 || key.indexOf(':') >= 0) {
|
||||
return null;
|
||||
}
|
||||
Path file = objectsRoot.resolve(key + OBJECT_EXTENSION).normalize();
|
||||
if (!file.startsWith(objectsRoot) || !Files.isRegularFile(file)) {
|
||||
return null;
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
private IrisObject readObjectBounds(Path file) {
|
||||
try (BufferedInputStream input = new BufferedInputStream(Files.newInputStream(file))) {
|
||||
return IrisObjectFrameReader.readBounds(input, file.toString());
|
||||
} catch (IOException e) {
|
||||
throw new MalformedObjectResourceException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class MalformedObjectResourceException extends RuntimeException {
|
||||
private MalformedObjectResourceException(String message, IOException cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.IrisStructureLocator;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.service.LocateResult;
|
||||
import com.volmit.service.StructureLocator;
|
||||
import com.volmit.world.BlockPosition;
|
||||
import com.volmit.world.PackWorld;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* How {@code iris:structure} lets Iris find its structures: the structures of the pack's {@code structures} folder,
|
||||
* the ones the world's placements assemble from jigsaw pools, and their nearest start, searched with
|
||||
* {@link IrisStructureLocator}. The keys it places also name the platform structures its native placements start and
|
||||
* the ones its structures stand in for; it locates those too. The platform's own locate of a natively started
|
||||
* structure goes through {@link StructureVanillaStructures#locateStart} instead.
|
||||
* <p>
|
||||
* Iris's locator names structures by key: a pack structure by its pack key, a platform structure by its
|
||||
* {@code namespace:path}. A key with a namespace is that id; any other is the pack's.
|
||||
*/
|
||||
public final class StructureLocating implements StructureLocator {
|
||||
private static final char NAMESPACE_SEPARATOR = ':';
|
||||
|
||||
@Override
|
||||
public Set<ResourceId> structures(PackResources pack) {
|
||||
return idsOf(pack, StructureResources.structureKeysOf(pack));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<ResourceId> locatable(PackWorld world) {
|
||||
return idsOf(world.resources(), IrisStructureLocator.locatableEditableKeys(engine(world)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<ResourceId> placed(PackWorld world) {
|
||||
return idsOf(world.resources(), IrisStructureLocator.placedKeysAndAliases(engine(world)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocateResult locate(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRadiusChunks) {
|
||||
Engine engine = engine(world);
|
||||
String key = keyOf(world.resources(), IrisStructureLocator.placedKeysAndAliases(engine), structure);
|
||||
IrisStructureLocator.LocateResult result = IrisStructureLocator.locate(engine, key, fromX, fromZ, maxRadiusChunks);
|
||||
return switch (result.status()) {
|
||||
case FOUND -> LocateResult.found(new BlockPosition(result.originX(), result.baseY() - engine.getMinHeight(), result.originZ()));
|
||||
case NOT_FOUND -> LocateResult.NOT_FOUND;
|
||||
case SEARCH_LIMIT_REACHED -> LocateResult.SEARCH_LIMIT_REACHED;
|
||||
};
|
||||
}
|
||||
|
||||
private static Engine engine(PackWorld world) {
|
||||
return world.extension(Engine.class).orElseThrow();
|
||||
}
|
||||
|
||||
private static Set<ResourceId> idsOf(PackResources pack, Collection<String> keys) {
|
||||
Set<ResourceId> ids = new LinkedHashSet<>();
|
||||
for (String key : keys) {
|
||||
ids.add(idOf(pack, key));
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
private static ResourceId idOf(PackResources pack, String key) {
|
||||
return key.indexOf(NAMESPACE_SEPARATOR) >= 0 ? ResourceId.parse(key.toLowerCase(Locale.ROOT)) : pack.idOf(key);
|
||||
}
|
||||
|
||||
/** The locator's key of {@code structure}: the placed key with that id, else the id as written. */
|
||||
private static String keyOf(PackResources pack, Collection<String> placedKeys, ResourceId structure) {
|
||||
for (String key : placedKeys) {
|
||||
if (idOf(pack, key).equals(structure)) {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
return structure.toString();
|
||||
}
|
||||
}
|
||||
-201
@@ -1,201 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.core.structure.authoring.StructureResourceBundle;
|
||||
import art.arcane.iris.engine.framework.StructureAssembler;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.value.IrisPosition;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class StructureResourceBundleGraphCompiler {
|
||||
private static final Gson GSON = new GsonBuilder().create();
|
||||
private static final List<Long> ASSEMBLY_SEEDS = List.of(
|
||||
0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L);
|
||||
|
||||
private StructureResourceBundleGraphCompiler() {
|
||||
}
|
||||
|
||||
public static List<StructureGraphCompilation> compile(StructureResourceBundle bundle) {
|
||||
BundleGraph graph = parse(Objects.requireNonNull(bundle));
|
||||
List<StructureGraphCompilation> compilations = new ArrayList<>(graph.structures().size());
|
||||
for (IrisStructure structure : graph.structures().values()) {
|
||||
compilations.add(StructureGraphCompiler.compile(structure, graph.resolver()));
|
||||
}
|
||||
return List.copyOf(compilations);
|
||||
}
|
||||
|
||||
public static void requireViable(StructureResourceBundle bundle) {
|
||||
BundleGraph graph = parse(Objects.requireNonNull(bundle));
|
||||
if (graph.structures().isEmpty()) {
|
||||
throw new StructureGraphValidationException("Structure bundle does not contain a root structure resource");
|
||||
}
|
||||
for (IrisStructure structure : graph.structures().values()) {
|
||||
StructureGraphCompilation compilation = StructureGraphCompiler.compile(structure, graph.resolver());
|
||||
if (!compilation.isAssemblyViable()) {
|
||||
throw new StructureGraphValidationException(
|
||||
"Structure bundle graph is not viable: " + viabilityFailure(compilation));
|
||||
}
|
||||
requireGeometryViable(compilation);
|
||||
}
|
||||
}
|
||||
|
||||
private static String viabilityFailure(StructureGraphCompilation compilation) {
|
||||
for (StructureGraphDiagnostic diagnostic : compilation.getDiagnostics()) {
|
||||
if (diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR) {
|
||||
return diagnostic.message();
|
||||
}
|
||||
}
|
||||
for (StructureGraphAssemblySample sample : compilation.getAssemblySamples()) {
|
||||
StructureGraphAssemblySample.Outcome outcome = sample.outcome();
|
||||
if (!outcome.isComplete()) {
|
||||
return "sampled assembly at seed " + sample.seed() + " returned "
|
||||
+ outcome.status() + ": " + outcome.detail();
|
||||
}
|
||||
}
|
||||
return "deterministic assembly did not complete";
|
||||
}
|
||||
|
||||
private static BundleGraph parse(StructureResourceBundle activeBundle) {
|
||||
Map<String, IrisStructure> structures = new LinkedHashMap<>();
|
||||
Map<String, IrisJigsawPool> pools = new LinkedHashMap<>();
|
||||
Map<String, IrisJigsawPiece> pieces = new LinkedHashMap<>();
|
||||
Map<String, IrisObject> objects = new LinkedHashMap<>();
|
||||
for (StructureResourceBundle.Resource resource : activeBundle.resources().values()) {
|
||||
String path = resource.relativePath();
|
||||
if (matches(path, "structures/", ".json")) {
|
||||
IrisStructure structure = readJson(resource, IrisStructure.class);
|
||||
String key = key(path, "structures/", ".json");
|
||||
structure.setLoadKey(key);
|
||||
structures.put(key, structure);
|
||||
} else if (matches(path, "jigsaw-pools/", ".json")) {
|
||||
pools.put(key(path, "jigsaw-pools/", ".json"), readJson(resource, IrisJigsawPool.class));
|
||||
} else if (matches(path, "jigsaw-pieces/", ".json")) {
|
||||
pieces.put(key(path, "jigsaw-pieces/", ".json"), readJson(resource, IrisJigsawPiece.class));
|
||||
} else if (matches(path, "objects/", ".iob")) {
|
||||
objects.put(key(path, "objects/", ".iob"), readObjectBounds(resource));
|
||||
}
|
||||
}
|
||||
return new BundleGraph(structures, new BundleResolver(pools, pieces, objects));
|
||||
}
|
||||
|
||||
private static void requireGeometryViable(StructureGraphCompilation compilation) {
|
||||
String structureKey = compilation.getGraph().getStructureKey();
|
||||
for (long seed : ASSEMBLY_SEEDS) {
|
||||
try {
|
||||
StructureAssembler assembler = StructureAssembler.forCompilation(
|
||||
compilation, new IrisPosition(0, 64, 0));
|
||||
StructureAssemblyResult result = assembler.assemble(new RNG(seed));
|
||||
if (result.status().isFailure()) {
|
||||
throw new StructureGraphValidationException("Structure bundle graph '" + structureKey
|
||||
+ "' fails sampled runtime geometry assembly at seed " + seed + ": "
|
||||
+ result.status() + ": " + result.detail());
|
||||
}
|
||||
} catch (StructureGraphValidationException e) {
|
||||
throw e;
|
||||
} catch (RuntimeException e) {
|
||||
throw new IllegalStateException("Structure bundle graph '" + structureKey
|
||||
+ "' encountered an unexpected sampled runtime geometry failure at seed " + seed + ": "
|
||||
+ e.getClass().getSimpleName() + ": " + failureMessage(e), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String failureMessage(RuntimeException exception) {
|
||||
return exception.getMessage() == null || exception.getMessage().isBlank()
|
||||
? "no failure detail" : exception.getMessage();
|
||||
}
|
||||
|
||||
private static boolean matches(String path, String prefix, String suffix) {
|
||||
return path.startsWith(prefix) && path.endsWith(suffix) && path.length() > prefix.length() + suffix.length();
|
||||
}
|
||||
|
||||
private static String key(String path, String prefix, String suffix) {
|
||||
return path.substring(prefix.length(), path.length() - suffix.length());
|
||||
}
|
||||
|
||||
private static <T> T readJson(StructureResourceBundle.Resource resource, Class<T> type) {
|
||||
T value;
|
||||
try {
|
||||
value = GSON.fromJson(new String(resource.content(), StandardCharsets.UTF_8), type);
|
||||
} catch (RuntimeException e) {
|
||||
throw new StructureGraphValidationException("Malformed structure resource " + resource.relativePath(), e);
|
||||
}
|
||||
if (value == null) {
|
||||
throw new StructureGraphValidationException("Empty structure resource " + resource.relativePath());
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static IrisObject readObjectBounds(StructureResourceBundle.Resource resource) {
|
||||
try (ByteArrayInputStream input = new ByteArrayInputStream(resource.content())) {
|
||||
return IrisObjectFrameReader.readBounds(input, resource.relativePath());
|
||||
} catch (IOException e) {
|
||||
throw new StructureGraphValidationException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private record BundleResolver(
|
||||
Map<String, IrisJigsawPool> pools,
|
||||
Map<String, IrisJigsawPiece> pieces,
|
||||
Map<String, IrisObject> objects
|
||||
) implements StructureGraphResolver {
|
||||
private BundleResolver {
|
||||
pools = Map.copyOf(pools);
|
||||
pieces = Map.copyOf(pieces);
|
||||
objects = Map.copyOf(objects);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisJigsawPool loadPool(String key) {
|
||||
return pools.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisJigsawPiece loadPiece(String key) {
|
||||
return pieces.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrisObject loadObject(String key) {
|
||||
return objects.get(key);
|
||||
}
|
||||
}
|
||||
|
||||
private record BundleGraph(Map<String, IrisStructure> structures, BundleResolver resolver) {
|
||||
private BundleGraph {
|
||||
structures = Map.copyOf(structures);
|
||||
Objects.requireNonNull(resolver);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.IrisPackResources;
|
||||
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 Iris's module {@code iris:structure-model}, which keep the folders and files Iris packs have always used,
|
||||
* and lookups by pack key for code that still names structures, pools and pieces by key. Every lookup goes through
|
||||
* the pack's {@link com.volmit.resource.PackResources}, so it sees the pack's current snapshot: a hotload, or
|
||||
* {@link IrisData#invalidateStructureResources()} after a tool rewrote the files, reads them again.
|
||||
* <p>
|
||||
* 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 StructureResources {
|
||||
/** Jigsaw structures, in {@code structures/}. */
|
||||
public static final ResourceKind<IrisStructure> STRUCTURES = ResourceKind.of("iris:structure-model/structure", "structures", IrisStructure.class);
|
||||
/** Jigsaw pools a structure starts from and connectors lead to, in {@code jigsaw-pools/}. */
|
||||
public static final ResourceKind<IrisJigsawPool> POOLS = ResourceKind.of("iris:structure-model/pool", "jigsaw-pools", IrisJigsawPool.class);
|
||||
/** Jigsaw pieces pools hold, each an object with connectors, in {@code jigsaw-pieces/}. */
|
||||
public static final ResourceKind<IrisJigsawPiece> PIECES = ResourceKind.of("iris:structure-model/piece", "jigsaw-pieces", IrisJigsawPiece.class);
|
||||
|
||||
private StructureResources() {
|
||||
}
|
||||
|
||||
/** Every resource kind of the structure model. */
|
||||
public static List<ResourceKind<?>> kinds() {
|
||||
return List.of(STRUCTURES, POOLS, PIECES);
|
||||
}
|
||||
|
||||
public static IrisStructure structure(IrisData data, String key) {
|
||||
return find(data, STRUCTURES, key);
|
||||
}
|
||||
|
||||
public static IrisJigsawPool pool(IrisData data, String key) {
|
||||
return find(data, POOLS, key);
|
||||
}
|
||||
|
||||
public static IrisJigsawPiece piece(IrisData data, String key) {
|
||||
return find(data, PIECES, key);
|
||||
}
|
||||
|
||||
/** The key of every structure of the pack, in key order. */
|
||||
public static List<String> structureKeys(IrisData data) {
|
||||
return structureKeysOf(data.getPackResources());
|
||||
}
|
||||
|
||||
/** The key of every structure of the pack snapshot {@code pack}, in key order. */
|
||||
public static List<String> structureKeysOf(PackResources pack) {
|
||||
return keys(pack, STRUCTURES);
|
||||
}
|
||||
|
||||
/** The key of every jigsaw piece of the pack, in key order. */
|
||||
public static List<String> pieceKeys(IrisData data) {
|
||||
return keys(data, PIECES);
|
||||
}
|
||||
|
||||
private static <T> T find(IrisData data, ResourceKind<T> kind, String key) {
|
||||
if (key == null || key.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
IrisPackResources resources = data.getPackResources();
|
||||
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<String> keys(IrisData data, ResourceKind<?> kind) {
|
||||
return keys(data.getPackResources(), kind);
|
||||
}
|
||||
|
||||
private static List<String> keys(PackResources pack, ResourceKind<?> kind) {
|
||||
return pack.ids(kind).stream().map(ResourceId::path).toList();
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.IrisValidationContext;
|
||||
import art.arcane.iris.core.pack.PackValidationIo;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
import com.volmit.validation.ValidationContext;
|
||||
import com.volmit.validation.Validator;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Module {@code iris:structure}'s check of a pack: every structure a dimension, region or biome places must assemble
|
||||
* ({@link StructureGraphValidation}), and a dimension that replaces a vanilla structure with an Iris one may only use
|
||||
* structures that always assemble and fit ({@link NativeReplacementValidation}). Graph diagnostics keep their
|
||||
* severity; everything else is an error, as when Iris's own pack validator ran these checks.
|
||||
*/
|
||||
public final class StructureValidator implements Validator {
|
||||
private static final List<String> STRUCTURE_HOST_FOLDERS = List.of("dimensions", "regions", "biomes");
|
||||
private static final String STRUCTURES_FIELD = "structures";
|
||||
|
||||
@Override
|
||||
public void validate(ValidationContext pack) {
|
||||
IrisData data = IrisValidationContext.of(pack).data();
|
||||
StructureGraphValidation.Validation graphs = StructureGraphValidation.validate(data, placedStructureKeys(data.getDataFolder()));
|
||||
graphs.problems().forEach(pack::report);
|
||||
NativeReplacementValidation.validate(data.getDataFolder(), graphs.replacementOutputStructures(), graphs.sampledVerticalEnvelopes())
|
||||
.forEach(pack::report);
|
||||
}
|
||||
|
||||
/**
|
||||
* The keys of the structures the dimension, region and biome files of the pack in {@code packFolder} place, read
|
||||
* from their JSON as written, like the other checks of these files.
|
||||
*/
|
||||
public static Set<String> placedStructureKeys(File packFolder) {
|
||||
Set<String> structureKeys = new LinkedHashSet<>();
|
||||
if (packFolder == null || !packFolder.isDirectory()) {
|
||||
return structureKeys;
|
||||
}
|
||||
for (String folderName : STRUCTURE_HOST_FOLDERS) {
|
||||
File resourceFolder = new File(packFolder, folderName);
|
||||
if (!resourceFolder.isDirectory()) {
|
||||
continue;
|
||||
}
|
||||
for (File resourceFile : PackValidationIo.listJsonRecursive(resourceFolder)) {
|
||||
addPlacedKeys(structureKeys, PackValidationIo.readJson(resourceFile));
|
||||
}
|
||||
}
|
||||
return Set.copyOf(structureKeys);
|
||||
}
|
||||
|
||||
private static void addPlacedKeys(Set<String> structureKeys, JSONObject resource) {
|
||||
JSONArray placements = resource == null ? null : resource.optJSONArray(STRUCTURES_FIELD);
|
||||
if (placements == null) {
|
||||
return;
|
||||
}
|
||||
for (int placementIndex = 0; placementIndex < placements.length(); placementIndex++) {
|
||||
JSONObject placement = placements.optJSONObject(placementIndex);
|
||||
JSONArray references = placement == null ? null : placement.optJSONArray(STRUCTURES_FIELD);
|
||||
if (references == null) {
|
||||
continue;
|
||||
}
|
||||
for (int referenceIndex = 0; referenceIndex < references.length(); referenceIndex++) {
|
||||
if (references.opt(referenceIndex) instanceof String structureKey && !structureKey.isBlank()) {
|
||||
structureKeys.add(structureKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-163
@@ -1,163 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.IrisStructureLocator;
|
||||
import art.arcane.iris.engine.framework.StructurePlacementGrid;
|
||||
import art.arcane.iris.engine.framework.structure.fit.StartLayouts;
|
||||
import art.arcane.iris.engine.framework.structure.fit.StructureFitting;
|
||||
import art.arcane.iris.builtin.structure.StructurePlacement;
|
||||
import art.arcane.iris.builtin.structure.NativeStructureSuppression;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.service.LocateResult;
|
||||
import com.volmit.service.VanillaStructures;
|
||||
import com.volmit.vanilla.PlatformStart;
|
||||
import com.volmit.vanilla.StartMemo;
|
||||
import com.volmit.vanilla.StartReach;
|
||||
import com.volmit.vanilla.StructureFit;
|
||||
import com.volmit.vanilla.VanillaStructureContext;
|
||||
import com.volmit.vanilla.VanillaStructureRule;
|
||||
import com.volmit.vanilla.VanillaStructureSetup;
|
||||
import com.volmit.vanilla.VanillaStructureStart;
|
||||
import com.volmit.vanilla.VanillaStructureStartContext;
|
||||
import com.volmit.world.BlockPosition;
|
||||
import com.volmit.world.PackWorld;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* What {@code iris:structure} says about the platform's own structures. The dimension's {@code importedStructures}
|
||||
* settings ({@link ImportedStructures}) disable, move, fit and set them up; the pack's structure placements replace
|
||||
* them ({@code vanillaSource} with native suppression), place them alongside ({@link IrisStructureLocator#isPlaced}),
|
||||
* start them where their {@code nativeStructures} grids say ({@link NativeStartPlanner}) and fit those starts the way
|
||||
* the placement says, which their memo carries to every chunk they reach ({@link StructureFitting}). It names the
|
||||
* structures its native placements start and finds their starts for the platform's own locate.
|
||||
*/
|
||||
public final class StructureVanillaStructures implements VanillaStructures {
|
||||
/**
|
||||
* {@link VanillaStructureRule#REPLACE} for a structure an Iris structure replaces or the dimension disables while a
|
||||
* placement places it, {@link VanillaStructureRule#BLOCK} for one the dimension disables, and
|
||||
* {@link VanillaStructureRule#ALSO_PLACE} for one a placement places alongside the platform.
|
||||
*/
|
||||
@Override
|
||||
public VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context) {
|
||||
Engine engine = context.settings().extension(Engine.class).orElseThrow();
|
||||
String key = structure.toString();
|
||||
boolean replaced = IrisStructureLocator.suppressesVanilla(engine, key);
|
||||
boolean blocked = replaced || ImportedStructures.of(context.settings()).disables(key);
|
||||
boolean placed = replaced || IrisStructureLocator.isPlaced(engine, key);
|
||||
VanillaStructureRule rule = blocked ? VanillaStructureRule.BLOCK : VanillaStructureRule.GENERATE;
|
||||
return placed ? rule.and(VanillaStructureRule.ALSO_PLACE) : rule;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<VanillaStructureStart> starts(int chunkX, int chunkZ, VanillaStructureStartContext context) {
|
||||
Engine engine = engine(context.world());
|
||||
return NativeStartPlanner.plansAt(engine, chunkX, chunkZ).stream()
|
||||
.map(plan -> start(plan, engine.getMinHeight()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int shift(PlatformStart start, VanillaStructureContext context) {
|
||||
return StartLayouts.shift(start, ImportedStructures.of(context.settings())
|
||||
.adjustment(start.structure().toString(), start.underground()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public StartReach reach(ResourceId structure, boolean underground, Optional<StartMemo> memo,
|
||||
VanillaStructureContext context) {
|
||||
NativeStructureFit fit = memo.map(NativeStructureFit::of)
|
||||
.orElseGet(() -> ImportedStructures.of(context.settings()).adjustment(structure.toString(), underground));
|
||||
return StartLayouts.reach(fit.resolvedTerrain());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforePieces(StructureFit fit) {
|
||||
StructureFitting.beforePieces(fit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPieces(StructureFit fit, StructureFit.Start placed) {
|
||||
StructureFitting.afterPieces(fit, placed);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VanillaStructureSetup setup(VanillaStructureContext context) {
|
||||
return ImportedStructures.of(context.settings()).setup();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<ResourceId> startedStructures(PackWorld world) {
|
||||
return structureIds(IrisStructureLocator.nativeKeys(engine(world)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<ResourceId> locatableStarts(PackWorld world) {
|
||||
return structureIds(IrisStructureLocator.locatableNativeKeys(engine(world)));
|
||||
}
|
||||
|
||||
/** Searches the rings of the placements that start {@code structure} natively, as the platform's own locate does. */
|
||||
@Override
|
||||
public LocateResult locateStart(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRings,
|
||||
ChunkFilter accepts) {
|
||||
Engine engine = engine(world);
|
||||
IrisStructureLocator.LocateResult result = IrisStructureLocator.locateInPlacementRings(
|
||||
engine, structure.toString(), fromX, fromZ, maxRings, accepts::accepts);
|
||||
return switch (result.status()) {
|
||||
case FOUND -> LocateResult.found(new BlockPosition(result.originX(), result.baseY() - engine.getMinHeight(), result.originZ()));
|
||||
case NOT_FOUND -> LocateResult.NOT_FOUND;
|
||||
case SEARCH_LIMIT_REACHED -> LocateResult.SEARCH_LIMIT_REACHED;
|
||||
};
|
||||
}
|
||||
|
||||
private static Engine engine(PackWorld world) {
|
||||
return world.extension(Engine.class).orElseThrow();
|
||||
}
|
||||
|
||||
private static Set<ResourceId> structureIds(Set<String> keys) {
|
||||
Set<ResourceId> ids = new LinkedHashSet<>();
|
||||
for (String key : keys) {
|
||||
ids.add(ResourceId.parse(key.toLowerCase(Locale.ROOT)));
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/** {@code plan} as the start the platform generates: heights above the bottom, the placement's identity and fit. */
|
||||
static VanillaStructureStart start(NativeStartPlanner.Plan plan, int minHeight) {
|
||||
StructurePlacement placement = plan.placement();
|
||||
NativeStructureFit fit = new NativeStructureFit(0, null, false, placement.stilt().orElse(null), placement.resolvedTerrain());
|
||||
VanillaStructureStart start = VanillaStructureStart.at(ResourceId.parse(plan.source().structure()),
|
||||
plan.chunkX(), plan.chunkZ(), plan.baseY() - minHeight)
|
||||
.withIdentity(StructurePlacementGrid.placementIdentity(placement))
|
||||
.withMemo(fit.memo());
|
||||
if (placement.underground()) {
|
||||
start = start.underground();
|
||||
}
|
||||
if (placement.nativeSuppression() == NativeStructureSuppression.REPLACE_SOURCE) {
|
||||
start = start.replacingPlatformStart();
|
||||
}
|
||||
return plan.source().jigsaw().map(start::withJigsaw).orElse(start);
|
||||
}
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.framework.structure.fit;
|
||||
|
||||
import art.arcane.iris.engine.mantle.components.StructureCarvingFootprint;
|
||||
import com.volmit.vanilla.StartKey;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.WeakHashMap;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Per-column occupancy of whole starts for organic carving, kept because a structure spans many chunks and every one of
|
||||
* them carves against the same shrinkwrapped footprint. Keyed weakly on the platform's own key of the start, so retired
|
||||
* starts (world unload, generation done) are collectable; values hold only primitives, so no value pins its key. The
|
||||
* cached cells stay inside a budget, the oldest starts giving way first.
|
||||
*/
|
||||
final class CarveFootprints {
|
||||
private static final int MAX_CACHED_CARVE_CELLS = 2_000_000;
|
||||
private static final int MAX_CARVE_COLUMNS = 2_000_000;
|
||||
private static final Map<Object, Map<Integer, CachedCarveFootprint>> CARVE_FOOTPRINTS = new WeakHashMap<>(16);
|
||||
private static final ConcurrentHashMap<CarveFootprintKey, CompletableFuture<StructureCarvingFootprint>> BUILDS =
|
||||
new ConcurrentHashMap<>();
|
||||
private static int cachedCarveCells;
|
||||
|
||||
private CarveFootprints() {
|
||||
}
|
||||
|
||||
static StructureCarvingFootprint of(FitStart start, int horizontalPadding) {
|
||||
CarveFootprintKey key = new CarveFootprintKey(start.key(), horizontalPadding);
|
||||
StructureCarvingFootprint cached = cached(key);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
CompletableFuture<StructureCarvingFootprint> build = new CompletableFuture<>();
|
||||
CompletableFuture<StructureCarvingFootprint> active = BUILDS.putIfAbsent(key, build);
|
||||
if (active != null) {
|
||||
return await(active);
|
||||
}
|
||||
// Close the check-then-claim window: a racer whose cache check missed before the previous builder cached can
|
||||
// claim the build slot after that builder retired it, and would rebuild a second instance without this re-check.
|
||||
StructureCarvingFootprint published = cached(key);
|
||||
if (published != null) {
|
||||
build.complete(published);
|
||||
BUILDS.remove(key, build);
|
||||
return published;
|
||||
}
|
||||
try {
|
||||
StructureCarvingFootprint footprint = StructureCarvingFootprint.fromColumns(sink -> {
|
||||
for (FitPiece piece : start.pieces()) {
|
||||
piece.columns(sink::column);
|
||||
}
|
||||
return true;
|
||||
}, horizontalPadding, MAX_CARVE_COLUMNS);
|
||||
if (footprint == null) {
|
||||
throw new IllegalStateException("Native structure carve footprint is empty or exceeds "
|
||||
+ MAX_CARVE_COLUMNS + " columns");
|
||||
}
|
||||
cache(key, footprint);
|
||||
build.complete(footprint);
|
||||
return footprint;
|
||||
} catch (RuntimeException | Error error) {
|
||||
build.completeExceptionally(error);
|
||||
throw error;
|
||||
} finally {
|
||||
BUILDS.remove(key, build);
|
||||
}
|
||||
}
|
||||
|
||||
static int cachedCells() {
|
||||
synchronized (CARVE_FOOTPRINTS) {
|
||||
cachedCarveCells = liveCells();
|
||||
return cachedCarveCells;
|
||||
}
|
||||
}
|
||||
|
||||
static int maximumCachedCells() {
|
||||
return MAX_CACHED_CARVE_CELLS;
|
||||
}
|
||||
|
||||
private static int liveCells() {
|
||||
int total = 0;
|
||||
for (Map<Integer, CachedCarveFootprint> perStart : CARVE_FOOTPRINTS.values()) {
|
||||
for (CachedCarveFootprint cached : perStart.values()) {
|
||||
total += cached.cells();
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
private static StructureCarvingFootprint cached(CarveFootprintKey key) {
|
||||
synchronized (CARVE_FOOTPRINTS) {
|
||||
Map<Integer, CachedCarveFootprint> perStart = CARVE_FOOTPRINTS.get(key.start());
|
||||
CachedCarveFootprint cached = perStart == null ? null : perStart.get(key.padding());
|
||||
return cached == null ? null : cached.footprint();
|
||||
}
|
||||
}
|
||||
|
||||
/** The loser of a build race surfaces the builder's own exception, not a CompletionException wrapper. */
|
||||
private static StructureCarvingFootprint await(CompletableFuture<StructureCarvingFootprint> future) {
|
||||
try {
|
||||
return future.join();
|
||||
} catch (CompletionException error) {
|
||||
Throwable cause = error.getCause();
|
||||
if (cause instanceof RuntimeException runtime) {
|
||||
throw runtime;
|
||||
}
|
||||
if (cause instanceof Error fatal) {
|
||||
throw fatal;
|
||||
}
|
||||
if (cause == null) {
|
||||
throw error;
|
||||
}
|
||||
throw new IllegalStateException("Native structure carve footprint build failed", cause);
|
||||
}
|
||||
}
|
||||
|
||||
private static void cache(CarveFootprintKey key, StructureCarvingFootprint footprint) {
|
||||
int cells = Math.multiplyExact(footprint.width(), footprint.depth());
|
||||
synchronized (CARVE_FOOTPRINTS) {
|
||||
// Weak keys expunge silently as the GC drops retired starts; re-derive the live total so the cell budget
|
||||
// tracks reality instead of drifting.
|
||||
cachedCarveCells = liveCells();
|
||||
Map<Integer, CachedCarveFootprint> perStart =
|
||||
CARVE_FOOTPRINTS.computeIfAbsent(key.start(), ignored -> new LinkedHashMap<>(4));
|
||||
CachedCarveFootprint previous = perStart.remove(key.padding());
|
||||
if (previous != null) {
|
||||
cachedCarveCells -= previous.cells();
|
||||
}
|
||||
Iterator<Map.Entry<Object, Map<Integer, CachedCarveFootprint>>> eviction =
|
||||
CARVE_FOOTPRINTS.entrySet().iterator();
|
||||
while (cachedCarveCells + cells > MAX_CACHED_CARVE_CELLS && eviction.hasNext()) {
|
||||
Map.Entry<Object, Map<Integer, CachedCarveFootprint>> victim = eviction.next();
|
||||
if (victim.getKey() == key.start()) {
|
||||
continue;
|
||||
}
|
||||
for (CachedCarveFootprint evicted : victim.getValue().values()) {
|
||||
cachedCarveCells -= evicted.cells();
|
||||
}
|
||||
eviction.remove();
|
||||
}
|
||||
perStart.put(key.padding(), new CachedCarveFootprint(footprint, cells));
|
||||
cachedCarveCells += cells;
|
||||
}
|
||||
}
|
||||
|
||||
/** A start's key is equal only to itself, so the key pins the exact start a chunk carves against. */
|
||||
private record CarveFootprintKey(StartKey start, int padding) {
|
||||
}
|
||||
|
||||
private record CachedCarveFootprint(StructureCarvingFootprint footprint, int cells) {
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.framework.structure.fit;
|
||||
|
||||
import art.arcane.iris.builtin.structure.StructureStilts;
|
||||
import art.arcane.iris.engine.framework.structure.ImportedStructures;
|
||||
import art.arcane.iris.engine.framework.structure.NativeStructureFit;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.block.PaletteSpec;
|
||||
import com.volmit.vanilla.StructureFit;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.IntBinaryOperator;
|
||||
|
||||
/**
|
||||
* How {@code iris:structure} fits the platform's starts into one chunk. Before any piece is placed it fits the
|
||||
* surface around SOURCE beard and VACUUM starts, integrates the terrain of every start and bridges short gaps between
|
||||
* rigid pieces; after each start's pieces it builds that start's stilts, and after the last one it repairs the gaps
|
||||
* left under VACUUM foundations. A start the module placed itself is fitted the way its memo records; one of the
|
||||
* platform's own starts the way the dimension's {@code importedStructures} adjust it today.
|
||||
*/
|
||||
public final class StructureFitting {
|
||||
private StructureFitting() {
|
||||
}
|
||||
|
||||
public static void beforePieces(StructureFit fit) {
|
||||
chunkOf(fit).prepare();
|
||||
}
|
||||
|
||||
public static void afterPieces(StructureFit fit, StructureFit.Start placed) {
|
||||
ChunkFit chunk = chunkOf(fit);
|
||||
chunk.buildStilts(placed);
|
||||
if (placed == fit.starts().getLast()) {
|
||||
chunk.repairFoundations();
|
||||
}
|
||||
}
|
||||
|
||||
private static ChunkFit chunkOf(StructureFit fit) {
|
||||
return fit.state(ChunkFit.class, () -> new ChunkFit(fit));
|
||||
}
|
||||
|
||||
/** One chunk's fit: its starts with their resolved fits, and the foundations VACUUM raised the terrain to. */
|
||||
private static final class ChunkFit {
|
||||
private final StructureFit fit;
|
||||
private final FitBlocks blocks;
|
||||
private final Box area;
|
||||
private final List<FitStart> starts;
|
||||
private final IntBinaryOperator surfaceHeight;
|
||||
private SurfaceFitting.VacuumFoundationPlan vacuumFoundations = SurfaceFitting.VacuumFoundationPlan.EMPTY;
|
||||
|
||||
private ChunkFit(StructureFit fit) {
|
||||
this.fit = fit;
|
||||
this.blocks = new FitBlocks(fit.blocks(), fit.bottomY());
|
||||
this.area = Box.of(fit.area(), fit.bottomY());
|
||||
this.starts = resolvedStarts(fit);
|
||||
this.surfaceHeight = (x, z) -> fit.surfaceY(x, z) + fit.bottomY();
|
||||
}
|
||||
|
||||
private static List<FitStart> resolvedStarts(StructureFit fit) {
|
||||
List<FitStart> starts = new ArrayList<>(fit.starts().size());
|
||||
for (StructureFit.Start start : fit.starts()) {
|
||||
starts.add(new FitStart(start, fitOf(fit, start), fit.bottomY()));
|
||||
}
|
||||
return List.copyOf(starts);
|
||||
}
|
||||
|
||||
private static NativeStructureFit fitOf(StructureFit fit, StructureFit.Start start) {
|
||||
return start.memo()
|
||||
.map(NativeStructureFit::of)
|
||||
.orElseGet(() -> ImportedStructures.of(fit.world().settings())
|
||||
.adjustment(start.structure().toString(), start.step().isUnderground()));
|
||||
}
|
||||
|
||||
private void prepare() {
|
||||
vacuumFoundations = SurfaceFitting.prepareSurfaceStructures(blocks, area, starts, surfaceHeight,
|
||||
SurfaceFitting.MAX_SURFACE_TEMPLATE_CELLS, fit.log());
|
||||
TerrainIntegration.prepareTerrain(blocks, area, starts, fit.seed(), this::naturalBlock, this::paletteBlock);
|
||||
RigidSupport.bridgeRigidPieceSupport(blocks, area, starts);
|
||||
}
|
||||
|
||||
private void buildStilts(StructureFit.Start placed) {
|
||||
FitStart start = fitStartOf(placed);
|
||||
StructureStilts stilts = start.fit().stilts();
|
||||
if (stilts == null) {
|
||||
return;
|
||||
}
|
||||
FoundationStilts.placeStilts(blocks, area, start, stilts, fit.seed(), this::paletteBlock, surfaceHeight,
|
||||
!start.step().isUnderground());
|
||||
}
|
||||
|
||||
private void repairFoundations() {
|
||||
SurfaceFitting.repairVacuumFoundations(blocks, area, vacuumFoundations);
|
||||
}
|
||||
|
||||
private FitStart fitStartOf(StructureFit.Start placed) {
|
||||
for (FitStart start : starts) {
|
||||
if (start.start() == placed) {
|
||||
return start;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Start " + placed.structure() + " is not one of the chunk's starts");
|
||||
}
|
||||
|
||||
private BlockState naturalBlock(int worldY) {
|
||||
return fit.naturalBlock(worldY - fit.bottomY());
|
||||
}
|
||||
|
||||
private BlockState paletteBlock(PaletteSpec palette, long seed, int x, int y, int z) {
|
||||
return fit.world().resources().blocks().palette(palette, seed).at(x, y, z);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,633 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.framework.structure.fit;
|
||||
|
||||
import art.arcane.iris.builtin.structure.StructureCarveShape;
|
||||
import art.arcane.iris.builtin.structure.StructureTerrain;
|
||||
import art.arcane.iris.builtin.structure.StructureTerrainMode;
|
||||
import art.arcane.iris.engine.mantle.components.StructureCarveEnvelope;
|
||||
import art.arcane.iris.engine.mantle.components.StructureCarvingFootprint;
|
||||
import art.arcane.iris.util.project.noise.CNG;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.block.PaletteSpec;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.vanilla.TerrainAdaptation;
|
||||
import com.volmit.world.BlockPosition;
|
||||
|
||||
import java.util.BitSet;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.IntFunction;
|
||||
|
||||
/**
|
||||
* The terrain fitting that runs before a start's pieces are placed, for every mode but VACUUM: SOURCE replays the
|
||||
* platform's BURY and ENCAPSULATE adaptations by filling the envelope around rigid pieces with the nearby natural
|
||||
* material, ENCASE fills the padded piece boxes, BORE clears them, FORCE_CARVE clears a box or a rounded, optionally
|
||||
* eroded shape around the pieces' silhouette. Legacy templates then clear their authored air over the terrain.
|
||||
*/
|
||||
final class TerrainIntegration {
|
||||
private static final long CARVE_CEILING_ROLL_SIGNATURE = 0x2A17L;
|
||||
private static final long CARVE_FLOOR_ROLL_SIGNATURE = 0x5B3DL;
|
||||
private static final long CARVE_LOBE_SIGNATURE = 0x7C41L;
|
||||
private static final long CARVE_IDENTITY_X = 341873128712L;
|
||||
private static final long CARVE_IDENTITY_Z = 132897987541L;
|
||||
private static final int SOURCE_BURY_HORIZONTAL_RADIUS = 6;
|
||||
private static final int SOURCE_BURY_VERTICAL_RADIUS = 12;
|
||||
private static final int SOURCE_ENCAPSULATE_RADIUS = 12;
|
||||
private static final int SOURCE_JUNCTION_RADIUS = 12;
|
||||
private static final int SOURCE_MATERIAL_SAMPLE_RADIUS = 8;
|
||||
private static final Set<String> VANILLA_SOURCE_TERRAIN_BLOCKS = Set.of(
|
||||
"minecraft:stone", "minecraft:granite", "minecraft:diorite", "minecraft:andesite",
|
||||
"minecraft:tuff", "minecraft:deepslate", "minecraft:netherrack", "minecraft:basalt",
|
||||
"minecraft:blackstone", "minecraft:dirt", "minecraft:coarse_dirt", "minecraft:rooted_dirt",
|
||||
"minecraft:grass_block", "minecraft:podzol", "minecraft:mycelium", "minecraft:mud",
|
||||
"minecraft:moss_block", "minecraft:sand", "minecraft:red_sand", "minecraft:terracotta",
|
||||
"minecraft:crimson_nylium", "minecraft:warped_nylium", "minecraft:snow_block",
|
||||
"minecraft:ice", "minecraft:packed_ice", "minecraft:blue_ice", "minecraft:soul_sand",
|
||||
"minecraft:soul_soil", "minecraft:end_stone", "minecraft:gravel", "minecraft:clay",
|
||||
"minecraft:calcite", "minecraft:dripstone_block", "minecraft:sandstone",
|
||||
"minecraft:red_sandstone", "minecraft:sculk");
|
||||
private static final List<ResourceId> SOURCE_TERRAIN_TAGS = List.of(
|
||||
ResourceId.parse("minecraft:base_stone_overworld"), ResourceId.parse("minecraft:base_stone_nether"),
|
||||
ResourceId.parse("minecraft:substrate_overworld"), ResourceId.parse("minecraft:dirt"),
|
||||
ResourceId.parse("minecraft:sand"), ResourceId.parse("minecraft:terracotta"),
|
||||
ResourceId.parse("minecraft:mud"), ResourceId.parse("minecraft:moss_blocks"),
|
||||
ResourceId.parse("minecraft:grass_blocks"), ResourceId.parse("minecraft:nylium"),
|
||||
ResourceId.parse("minecraft:snow"), ResourceId.parse("minecraft:ice"),
|
||||
ResourceId.parse("minecraft:coral_blocks"), ResourceId.parse("minecraft:soul_fire_base_blocks"));
|
||||
|
||||
private TerrainIntegration() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Integrates the terrain of every start, then clears the legacy template air of those that replay their own
|
||||
* adaptation or are encased. The natural material SOURCE fills with is read once for all starts, before any fill.
|
||||
*/
|
||||
static void prepareTerrain(FitBlocks blocks, Box area, List<FitStart> starts, long seed,
|
||||
IntFunction<BlockState> naturalBlock, FitPalettes palettes) {
|
||||
if (starts.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
SourceTerrainSnapshot sourceTerrain = captureSourceTerrain(blocks, area, starts);
|
||||
for (FitStart start : starts) {
|
||||
integrateTerrain(blocks, area, start, seed, naturalBlock, palettes, sourceTerrain);
|
||||
}
|
||||
for (FitStart start : starts) {
|
||||
if (clearsLegacyTemplateAir(start)) {
|
||||
clearLegacyTemplateAir(blocks, area, start);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void integrateTerrain(FitBlocks blocks, Box area, FitStart start, long seed,
|
||||
IntFunction<BlockState> naturalBlock, FitPalettes palettes,
|
||||
SourceTerrainSnapshot sourceTerrain) {
|
||||
StructureTerrain terrain = start.terrain();
|
||||
StructureTerrainMode mode = terrain.resolvedMode();
|
||||
switch (mode) {
|
||||
case SOURCE -> integrateSourceTerrain(blocks, area, start, naturalBlock, sourceTerrain);
|
||||
case PRESERVE, VACUUM -> {
|
||||
}
|
||||
case ENCASE -> encasePieces(blocks, area, start, terrain, seed, naturalBlock, palettes);
|
||||
case BORE, FORCE_CARVE -> carve(blocks, area, start, terrain, seed);
|
||||
}
|
||||
}
|
||||
|
||||
private static void carve(FitBlocks blocks, Box area, FitStart start, StructureTerrain terrain, long seed) {
|
||||
StructureCarveShape shape = terrain.resolvedMode() == StructureTerrainMode.BORE
|
||||
? StructureCarveShape.BOX : terrain.resolvedShape();
|
||||
if (shape == StructureCarveShape.BOX) {
|
||||
carvePieceBoxes(blocks, area, start, terrain);
|
||||
return;
|
||||
}
|
||||
carveOrganicColumns(blocks, area, organicCarve(
|
||||
CarveFootprints.of(start, Math.max(0, terrain.horizontalPadding())),
|
||||
terrain, shape, carveNoiseIdentity(seed, start)));
|
||||
}
|
||||
|
||||
static SourceTerrainSnapshot captureSourceTerrain(FitBlocks blocks, Box area, List<FitStart> starts) {
|
||||
BitSet requiredLayers = new BitSet(area.ySpan());
|
||||
boolean requiresSnapshot = false;
|
||||
for (FitStart start : starts) {
|
||||
if (requiresSourceTerrainFill(start)) {
|
||||
requiresSnapshot = true;
|
||||
markSourceTerrainLayers(area, start, requiredLayers);
|
||||
}
|
||||
}
|
||||
return requiresSnapshot ? SourceTerrainSnapshot.capture(blocks, area, requiredLayers) : null;
|
||||
}
|
||||
|
||||
private static void markSourceTerrainLayers(Box area, FitStart start, BitSet requiredLayers) {
|
||||
TerrainAdaptation adaptation = start.adaptation();
|
||||
for (FitPiece piece : start.pieces()) {
|
||||
if (!piece.isRigidOrFixed()) {
|
||||
continue;
|
||||
}
|
||||
Box bounds = piece.box();
|
||||
long horizontalDistanceSquared = minimumHorizontalDistanceSquared(area, bounds);
|
||||
if (adaptation == TerrainAdaptation.BURY) {
|
||||
long remainingDistanceSquared = (long) SOURCE_BURY_VERTICAL_RADIUS * SOURCE_BURY_VERTICAL_RADIUS
|
||||
- 1L - horizontalDistanceSquared * 4L;
|
||||
if (remainingDistanceSquared < 0L) {
|
||||
continue;
|
||||
}
|
||||
int verticalRadius = (int) Math.floor(Math.sqrt(remainingDistanceSquared));
|
||||
long groundY = piece.groundY();
|
||||
markLayers(area, requiredLayers, groundY - verticalRadius, groundY + verticalRadius);
|
||||
} else {
|
||||
long remainingDistanceSquared = (long) SOURCE_ENCAPSULATE_RADIUS * SOURCE_ENCAPSULATE_RADIUS
|
||||
- 1L - horizontalDistanceSquared;
|
||||
if (remainingDistanceSquared < 0L) {
|
||||
continue;
|
||||
}
|
||||
int verticalRadius = (int) Math.floor(Math.sqrt(remainingDistanceSquared));
|
||||
markLayers(area, requiredLayers, (long) bounds.minY() - verticalRadius,
|
||||
(long) bounds.maxY() + verticalRadius);
|
||||
}
|
||||
}
|
||||
markSourceJunctionLayers(area, start, requiredLayers);
|
||||
}
|
||||
|
||||
private static void markSourceJunctionLayers(Box area, FitStart start, BitSet requiredLayers) {
|
||||
for (BlockPosition anchor : sourceJunctionAnchors(start)) {
|
||||
long deltaX = intervalDistance(area.minX(), area.maxX(), anchor.x(), anchor.x());
|
||||
long deltaZ = intervalDistance(area.minZ(), area.maxZ(), anchor.z(), anchor.z());
|
||||
long horizontalDistanceSquared = deltaX * deltaX + deltaZ * deltaZ;
|
||||
long remainingDistanceSquared = (long) SOURCE_JUNCTION_RADIUS * SOURCE_JUNCTION_RADIUS
|
||||
- 1L - horizontalDistanceSquared;
|
||||
if (remainingDistanceSquared < 1L) {
|
||||
continue;
|
||||
}
|
||||
int verticalRadius = (int) Math.floor(Math.sqrt(remainingDistanceSquared));
|
||||
markLayers(area, requiredLayers, (long) anchor.y() - verticalRadius, (long) anchor.y() - 1L);
|
||||
}
|
||||
}
|
||||
|
||||
private static long minimumHorizontalDistanceSquared(Box area, Box bounds) {
|
||||
long deltaX = intervalDistance(area.minX(), area.maxX(), bounds.minX(), bounds.maxX());
|
||||
long deltaZ = intervalDistance(area.minZ(), area.maxZ(), bounds.minZ(), bounds.maxZ());
|
||||
return deltaX * deltaX + deltaZ * deltaZ;
|
||||
}
|
||||
|
||||
private static long intervalDistance(int firstMin, int firstMax, int secondMin, int secondMax) {
|
||||
if (firstMax < secondMin) {
|
||||
return (long) secondMin - firstMax;
|
||||
}
|
||||
if (firstMin > secondMax) {
|
||||
return (long) firstMin - secondMax;
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
|
||||
private static void markLayers(Box area, BitSet requiredLayers, long minimumY, long maximumY) {
|
||||
long clippedMinimumY = Math.max(area.minY(), minimumY);
|
||||
long clippedMaximumY = Math.min(area.maxY(), maximumY);
|
||||
if (clippedMinimumY > clippedMaximumY) {
|
||||
return;
|
||||
}
|
||||
int fromIndex = Math.toIntExact(clippedMinimumY - area.minY());
|
||||
int toIndex = Math.toIntExact(clippedMaximumY - area.minY() + 1L);
|
||||
requiredLayers.set(fromIndex, toIndex);
|
||||
}
|
||||
|
||||
/** Whether SOURCE fills terrain for the start: it buries or encapsulates its rigid pieces. */
|
||||
private static boolean requiresSourceTerrainFill(FitStart start) {
|
||||
return start.terrain().resolvedMode() == StructureTerrainMode.SOURCE
|
||||
&& (start.adaptation() == TerrainAdaptation.BURY || start.adaptation() == TerrainAdaptation.ENCAPSULATE);
|
||||
}
|
||||
|
||||
static boolean clearsLegacyTemplateAir(FitStart start) {
|
||||
StructureTerrainMode mode = start.terrain().resolvedMode();
|
||||
return mode == StructureTerrainMode.ENCASE
|
||||
|| mode == StructureTerrainMode.SOURCE && start.adaptation() != TerrainAdaptation.NONE;
|
||||
}
|
||||
|
||||
private static void integrateSourceTerrain(FitBlocks blocks, Box area, FitStart start,
|
||||
IntFunction<BlockState> naturalBlock, SourceTerrainSnapshot sourceTerrain) {
|
||||
if (start.adaptation() == TerrainAdaptation.BURY) {
|
||||
fillBuriedTerrain(blocks, area, start, naturalBlock, requireSourceTerrain(blocks, area, start, sourceTerrain));
|
||||
} else if (start.adaptation() == TerrainAdaptation.ENCAPSULATE) {
|
||||
fillEncapsulatedTerrain(blocks, area, start, naturalBlock,
|
||||
requireSourceTerrain(blocks, area, start, sourceTerrain));
|
||||
}
|
||||
}
|
||||
|
||||
private static SourceTerrainSnapshot requireSourceTerrain(FitBlocks blocks, Box area, FitStart start,
|
||||
SourceTerrainSnapshot sourceTerrain) {
|
||||
if (sourceTerrain != null) {
|
||||
return sourceTerrain;
|
||||
}
|
||||
BitSet requiredLayers = new BitSet(area.ySpan());
|
||||
markSourceTerrainLayers(area, start, requiredLayers);
|
||||
return SourceTerrainSnapshot.capture(blocks, area, requiredLayers);
|
||||
}
|
||||
|
||||
private static void fillBuriedTerrain(FitBlocks blocks, Box area, FitStart start, IntFunction<BlockState> naturalBlock,
|
||||
SourceTerrainSnapshot sourceTerrain) {
|
||||
for (FitPiece piece : start.pieces()) {
|
||||
if (!piece.isRigidOrFixed()) {
|
||||
continue;
|
||||
}
|
||||
Box bounds = piece.box();
|
||||
int groundY = piece.groundY();
|
||||
int minX = Math.max(area.minX(), bounds.minX() - SOURCE_BURY_HORIZONTAL_RADIUS);
|
||||
int maxX = Math.min(area.maxX(), bounds.maxX() + SOURCE_BURY_HORIZONTAL_RADIUS);
|
||||
int minY = Math.max(area.minY(), groundY - SOURCE_BURY_VERTICAL_RADIUS);
|
||||
int maxY = Math.min(area.maxY(), groundY + SOURCE_BURY_VERTICAL_RADIUS);
|
||||
int minZ = Math.max(area.minZ(), bounds.minZ() - SOURCE_BURY_HORIZONTAL_RADIUS);
|
||||
int maxZ = Math.min(area.maxZ(), bounds.maxZ() + SOURCE_BURY_HORIZONTAL_RADIUS);
|
||||
for (int x = minX; x <= maxX; x++) {
|
||||
int outX = outset(x, bounds.minX(), bounds.maxX());
|
||||
for (int z = minZ; z <= maxZ; z++) {
|
||||
int outZ = outset(z, bounds.minZ(), bounds.maxZ());
|
||||
for (int y = minY; y <= maxY; y++) {
|
||||
if (insideBurialEnvelope(outX, Math.abs(y - groundY), outZ)) {
|
||||
fillEncaseable(blocks, x, y, z, naturalBlock, sourceTerrain);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fillSourceJunctionTerrain(blocks, area, start, naturalBlock, sourceTerrain);
|
||||
}
|
||||
|
||||
private static void fillEncapsulatedTerrain(FitBlocks blocks, Box area, FitStart start,
|
||||
IntFunction<BlockState> naturalBlock, SourceTerrainSnapshot sourceTerrain) {
|
||||
for (FitPiece piece : start.pieces()) {
|
||||
if (!piece.isRigidOrFixed()) {
|
||||
continue;
|
||||
}
|
||||
Box bounds = piece.box();
|
||||
int minX = Math.max(area.minX(), bounds.minX() - SOURCE_ENCAPSULATE_RADIUS);
|
||||
int maxX = Math.min(area.maxX(), bounds.maxX() + SOURCE_ENCAPSULATE_RADIUS);
|
||||
int minY = Math.max(area.minY(), bounds.minY() - SOURCE_ENCAPSULATE_RADIUS);
|
||||
int maxY = Math.min(area.maxY(), bounds.maxY() + SOURCE_ENCAPSULATE_RADIUS);
|
||||
int minZ = Math.max(area.minZ(), bounds.minZ() - SOURCE_ENCAPSULATE_RADIUS);
|
||||
int maxZ = Math.min(area.maxZ(), bounds.maxZ() + SOURCE_ENCAPSULATE_RADIUS);
|
||||
for (int x = minX; x <= maxX; x++) {
|
||||
int outX = outset(x, bounds.minX(), bounds.maxX());
|
||||
for (int z = minZ; z <= maxZ; z++) {
|
||||
int outZ = outset(z, bounds.minZ(), bounds.maxZ());
|
||||
for (int y = minY; y <= maxY; y++) {
|
||||
if (insideEncapsulationEnvelope(outX, outset(y, bounds.minY(), bounds.maxY()), outZ)) {
|
||||
fillEncaseable(blocks, x, y, z, naturalBlock, sourceTerrain);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fillSourceJunctionTerrain(blocks, area, start, naturalBlock, sourceTerrain);
|
||||
}
|
||||
|
||||
static boolean insideBurialEnvelope(int outX, int verticalDistance, int outZ) {
|
||||
long horizontalSquared = (long) outX * outX + (long) outZ * outZ;
|
||||
long verticalSquared = (long) verticalDistance * verticalDistance;
|
||||
return horizontalSquared * 4L + verticalSquared < (long) SOURCE_BURY_VERTICAL_RADIUS * SOURCE_BURY_VERTICAL_RADIUS;
|
||||
}
|
||||
|
||||
static boolean insideEncapsulationEnvelope(int outX, int outY, int outZ) {
|
||||
return (long) outX * outX + (long) outY * outY + (long) outZ * outZ
|
||||
< (long) SOURCE_ENCAPSULATE_RADIUS * SOURCE_ENCAPSULATE_RADIUS;
|
||||
}
|
||||
|
||||
static boolean insideSourceJunctionEnvelope(int deltaX, int deltaY, int deltaZ) {
|
||||
if (deltaY >= 0) {
|
||||
return false;
|
||||
}
|
||||
return (long) deltaX * deltaX + (long) deltaY * deltaY + (long) deltaZ * deltaZ
|
||||
< (long) SOURCE_JUNCTION_RADIUS * SOURCE_JUNCTION_RADIUS;
|
||||
}
|
||||
|
||||
private static void fillSourceJunctionTerrain(FitBlocks blocks, Box area, FitStart start,
|
||||
IntFunction<BlockState> naturalBlock, SourceTerrainSnapshot sourceTerrain) {
|
||||
for (BlockPosition anchor : sourceJunctionAnchors(start)) {
|
||||
int minX = Math.max(area.minX(), anchor.x() - SOURCE_JUNCTION_RADIUS + 1);
|
||||
int maxX = Math.min(area.maxX(), anchor.x() + SOURCE_JUNCTION_RADIUS - 1);
|
||||
int minY = Math.max(area.minY(), anchor.y() - SOURCE_JUNCTION_RADIUS + 1);
|
||||
int maxY = Math.min(area.maxY(), anchor.y() - 1);
|
||||
int minZ = Math.max(area.minZ(), anchor.z() - SOURCE_JUNCTION_RADIUS + 1);
|
||||
int maxZ = Math.min(area.maxZ(), anchor.z() + SOURCE_JUNCTION_RADIUS - 1);
|
||||
for (int x = minX; x <= maxX; x++) {
|
||||
int deltaX = x - anchor.x();
|
||||
for (int z = minZ; z <= maxZ; z++) {
|
||||
int deltaZ = z - anchor.z();
|
||||
for (int y = minY; y <= maxY; y++) {
|
||||
if (insideSourceJunctionEnvelope(deltaX, y - anchor.y(), deltaZ)) {
|
||||
fillEncaseable(blocks, x, y, z, naturalBlock, sourceTerrain);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The jigsaw junctions of every piece, each place once. The order is a set's, as no fill depends on it. */
|
||||
private static Set<BlockPosition> sourceJunctionAnchors(FitStart start) {
|
||||
Set<BlockPosition> anchors = new HashSet<>();
|
||||
for (FitPiece piece : start.pieces()) {
|
||||
anchors.addAll(piece.junctions());
|
||||
}
|
||||
return anchors;
|
||||
}
|
||||
|
||||
private static int outset(int value, int minimum, int maximum) {
|
||||
if (value < minimum) {
|
||||
return minimum - value;
|
||||
}
|
||||
return Math.max(0, value - maximum);
|
||||
}
|
||||
|
||||
private static void fillEncaseable(FitBlocks blocks, int x, int y, int z, IntFunction<BlockState> naturalBlock,
|
||||
SourceTerrainSnapshot sourceTerrain) {
|
||||
if (blocks.isEncaseable(blocks.get(x, y, z))) {
|
||||
blocks.set(x, y, z, sourceEncaseBlock(x, y, z, naturalBlock, sourceTerrain));
|
||||
}
|
||||
}
|
||||
|
||||
/** The nearest natural terrain block of the snapshot along the axes, within 8 blocks; else the dimension's own. */
|
||||
static BlockState sourceEncaseBlock(int x, int y, int z, IntFunction<BlockState> naturalBlock,
|
||||
SourceTerrainSnapshot sourceTerrain) {
|
||||
for (int distance = 1; distance <= SOURCE_MATERIAL_SAMPLE_RADIUS; distance++) {
|
||||
BlockState sampled = sourceTerrain.stateAt(x - distance, y, z);
|
||||
if (sampled != null) {
|
||||
return sampled;
|
||||
}
|
||||
sampled = sourceTerrain.stateAt(x + distance, y, z);
|
||||
if (sampled != null) {
|
||||
return sampled;
|
||||
}
|
||||
sampled = sourceTerrain.stateAt(x, y, z - distance);
|
||||
if (sampled != null) {
|
||||
return sampled;
|
||||
}
|
||||
sampled = sourceTerrain.stateAt(x, y, z + distance);
|
||||
if (sampled != null) {
|
||||
return sampled;
|
||||
}
|
||||
}
|
||||
return naturalBlock.apply(y);
|
||||
}
|
||||
|
||||
private static BlockState sourceTerrainBlock(FitBlocks blocks, BlockState state) {
|
||||
if (!blocks.isSolid(state) || blocks.isTree(state)) {
|
||||
return null;
|
||||
}
|
||||
if (VANILLA_SOURCE_TERRAIN_BLOCKS.contains(state.material().toString())) {
|
||||
return state;
|
||||
}
|
||||
for (ResourceId tag : SOURCE_TERRAIN_TAGS) {
|
||||
if (blocks.inTag(state, tag)) {
|
||||
return state;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static OrganicCarve organicCarve(StructureCarvingFootprint footprint, StructureTerrain terrain,
|
||||
StructureCarveShape shape, long identity) {
|
||||
double strength = terrain.resolvedErosionStrength();
|
||||
double lobeStrength = terrain.resolvedLobeStrength();
|
||||
RNG noiseRng = new RNG(identity);
|
||||
CNG blob = null;
|
||||
CNG ceilingRoll = null;
|
||||
CNG floorRoll = null;
|
||||
CNG lobe = null;
|
||||
if (shape == StructureCarveShape.ERODED && strength > 0D) {
|
||||
blob = CNG.signature(noiseRng);
|
||||
ceilingRoll = CNG.signature(noiseRng.nextParallelRNG(CARVE_CEILING_ROLL_SIGNATURE));
|
||||
floorRoll = CNG.signature(noiseRng.nextParallelRNG(CARVE_FLOOR_ROLL_SIGNATURE));
|
||||
}
|
||||
if (shape == StructureCarveShape.ERODED && lobeStrength > 0D) {
|
||||
// A plain single octave channel: the fractured signature noise has no usable low frequency band.
|
||||
lobe = new CNG(noiseRng.nextParallelRNG(CARVE_LOBE_SIGNATURE), 1D, 1);
|
||||
}
|
||||
return new OrganicCarve(footprint, shape,
|
||||
Math.max(0, terrain.horizontalPadding()),
|
||||
Math.max(0, terrain.ceilingPadding()),
|
||||
Math.max(0, terrain.floorPadding()),
|
||||
strength, terrain.resolvedErosionFrequency(), blob, ceilingRoll, floorRoll,
|
||||
lobe, terrain.resolvedLobeFrequency(), lobeStrength);
|
||||
}
|
||||
|
||||
static void carveOrganicColumns(FitBlocks blocks, Box area, OrganicCarve carve) {
|
||||
StructureCarvingFootprint footprint = carve.footprint();
|
||||
int minX = Math.max(area.minX(), footprint.minX());
|
||||
int maxX = Math.min(area.maxX(), footprint.maxX());
|
||||
int minZ = Math.max(area.minZ(), footprint.minZ());
|
||||
int maxZ = Math.min(area.maxZ(), footprint.maxZ());
|
||||
if (minX > maxX || minZ > maxZ) {
|
||||
return;
|
||||
}
|
||||
boolean eroded = carve.blob() != null;
|
||||
for (int z = minZ; z <= maxZ; z++) {
|
||||
for (int x = minX; x <= maxX; x++) {
|
||||
int index = footprint.indexAt(x, z);
|
||||
long horizontalDistanceSquared = footprint.distanceSquaredAt(index);
|
||||
double sideReach = StructureCarveEnvelope.lobedSideReach(carve.lobe(),
|
||||
carve.lobeFrequency(), carve.lobeStrength(), x, z, carve.horizontalPadding());
|
||||
double sideReachSquared = sideReach * sideReach;
|
||||
if (horizontalDistanceSquared > sideReachSquared) {
|
||||
continue;
|
||||
}
|
||||
double normalizedHorizontal = sideReachSquared == 0D ? 0D : horizontalDistanceSquared / sideReachSquared;
|
||||
int sourceMinY = footprint.sourceMinYAt(index);
|
||||
int sourceMaxY = footprint.sourceMaxYAt(index);
|
||||
double upReach = eroded
|
||||
? StructureCarveEnvelope.lobedUpReach(carve.lobe(), carve.lobeFrequency(),
|
||||
carve.lobeStrength(), x, z,
|
||||
StructureCarveEnvelope.erodedUpReach(carve.ceilingRoll(),
|
||||
carve.frequency(), carve.strength(), x, z, carve.ceilingPadding()))
|
||||
: Math.max(1D, carve.ceilingPadding());
|
||||
double floorReach = eroded
|
||||
? StructureCarveEnvelope.erodedDownReach(carve.floorRoll(), carve.frequency(),
|
||||
carve.strength(), x, z, carve.floorPadding())
|
||||
: carve.floorPadding();
|
||||
int columnMinY = Math.max(area.minY(), sourceMinY - (int) Math.floor(floorReach));
|
||||
int columnMaxY = Math.min(area.maxY(),
|
||||
sourceMaxY + (eroded ? (int) Math.ceil(upReach) : carve.ceilingPadding()));
|
||||
double downReach = Math.max(1D, floorReach);
|
||||
for (int y = columnMinY; y <= columnMaxY; y++) {
|
||||
double normalizedVertical = StructureCarveEnvelope.normalizedVerticalDistance(
|
||||
y, sourceMinY, sourceMaxY, upReach, downReach);
|
||||
double distanceSquared = normalizedHorizontal + normalizedVertical * normalizedVertical;
|
||||
if (distanceSquared > 1D) {
|
||||
continue;
|
||||
}
|
||||
if (distanceSquared > 0D && eroded) {
|
||||
double noise = carve.blob().fitDouble(0D, 1D,
|
||||
x * carve.frequency(), y * carve.frequency(), z * carve.frequency());
|
||||
if (!StructureCarveEnvelope.shouldCarveOverboreCell(
|
||||
carve.shape(), distanceSquared, noise, carve.strength())) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
blocks.set(x, y, z, FitBlocks.AIR);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static long carveNoiseIdentity(long seed, FitStart start) {
|
||||
return seed
|
||||
^ ((long) start.chunkX() * CARVE_IDENTITY_X)
|
||||
^ ((long) start.chunkZ() * CARVE_IDENTITY_Z)
|
||||
^ start.structureId().hashCode();
|
||||
}
|
||||
|
||||
private static void encasePieces(FitBlocks blocks, Box area, FitStart start, StructureTerrain terrain, long seed,
|
||||
IntFunction<BlockState> naturalBlock, FitPalettes palettes) {
|
||||
Optional<PaletteSpec> palette = terrain.encasePalette();
|
||||
long paletteSeed = seed ^ start.structureId().hashCode();
|
||||
for (FitPiece piece : start.pieces()) {
|
||||
Box shell = paddedPieceArea(area, piece.box(), terrain);
|
||||
if (shell == null) {
|
||||
continue;
|
||||
}
|
||||
for (int x = shell.minX(); x <= shell.maxX(); x++) {
|
||||
for (int z = shell.minZ(); z <= shell.maxZ(); z++) {
|
||||
for (int y = shell.minY(); y <= shell.maxY(); y++) {
|
||||
if (!blocks.isEncaseable(blocks.get(x, y, z))) {
|
||||
continue;
|
||||
}
|
||||
BlockState fill = palette.isEmpty()
|
||||
? naturalBlock.apply(y)
|
||||
: Objects.requireNonNull(palettes.at(palette.get(), paletteSeed, x, y, z),
|
||||
"Encase palette returned no block for " + start.structureId() + " at "
|
||||
+ x + "," + y + "," + z);
|
||||
blocks.set(x, y, z, fill);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void carvePieceBoxes(FitBlocks blocks, Box area, FitStart start, StructureTerrain terrain) {
|
||||
for (FitPiece piece : start.pieces()) {
|
||||
Box carve = paddedPieceArea(area, piece.box(), terrain);
|
||||
if (carve == null) {
|
||||
continue;
|
||||
}
|
||||
for (int x = carve.minX(); x <= carve.maxX(); x++) {
|
||||
for (int z = carve.minZ(); z <= carve.maxZ(); z++) {
|
||||
for (int y = carve.minY(); y <= carve.maxY(); y++) {
|
||||
blocks.set(x, y, z, FitBlocks.AIR);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Box paddedPieceArea(Box area, Box bounds, StructureTerrain terrain) {
|
||||
int horizontalPadding = Math.max(0, terrain.horizontalPadding());
|
||||
int minX = Math.max(area.minX(), bounds.minX() - horizontalPadding);
|
||||
int minY = Math.max(area.minY(), bounds.minY() - Math.max(0, terrain.floorPadding()));
|
||||
int minZ = Math.max(area.minZ(), bounds.minZ() - horizontalPadding);
|
||||
int maxX = Math.min(area.maxX(), bounds.maxX() + horizontalPadding);
|
||||
int maxY = Math.min(area.maxY(), bounds.maxY() + Math.max(0, terrain.ceilingPadding()));
|
||||
int maxZ = Math.min(area.maxZ(), bounds.maxZ() + horizontalPadding);
|
||||
if (minX > maxX || minY > maxY || minZ > maxZ) {
|
||||
return null;
|
||||
}
|
||||
return new Box(minX, minY, minZ, maxX, maxY, maxZ);
|
||||
}
|
||||
|
||||
/** Clears the air of rigid legacy templates over the terrain, from their ground level up, sparing trees. */
|
||||
static void clearLegacyTemplateAir(FitBlocks blocks, Box area, FitStart start) {
|
||||
for (FitPiece piece : start.pieces()) {
|
||||
if (!piece.isRigid() || !piece.box().intersects(area)) {
|
||||
continue;
|
||||
}
|
||||
int groundY = piece.groundY();
|
||||
for (BlockPosition air : piece.legacyAir(area)) {
|
||||
BlockState existing = blocks.get(air.x(), air.y(), air.z());
|
||||
if (shouldClearLegacyAir(air.y(), groundY, blocks.isAir(existing)) && !blocks.isTree(existing)) {
|
||||
blocks.set(air.x(), air.y(), air.z(), FitBlocks.AIR);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static boolean shouldClearLegacyAir(int airY, int groundY, boolean existingAir) {
|
||||
return airY >= groundY && !existingAir;
|
||||
}
|
||||
|
||||
/** The natural terrain blocks of some layers of the area, read before any fill, so fills never feed on fills. */
|
||||
static final class SourceTerrainSnapshot {
|
||||
private final Box area;
|
||||
private final int width;
|
||||
private final BlockState[][] statesByLayer;
|
||||
private final int sampledCells;
|
||||
|
||||
private SourceTerrainSnapshot(Box area, int width, BlockState[][] statesByLayer, int sampledCells) {
|
||||
this.area = area;
|
||||
this.width = width;
|
||||
this.statesByLayer = statesByLayer;
|
||||
this.sampledCells = sampledCells;
|
||||
}
|
||||
|
||||
static SourceTerrainSnapshot capture(FitBlocks blocks, Box area, BitSet requiredLayers) {
|
||||
Objects.requireNonNull(requiredLayers, "Source terrain snapshot requires sampled layers");
|
||||
int width = area.xSpan();
|
||||
int horizontalCells = Math.multiplyExact(width, area.zSpan());
|
||||
int height = area.ySpan();
|
||||
BlockState[][] statesByLayer = new BlockState[height][];
|
||||
int sampledCells = 0;
|
||||
for (int layer = requiredLayers.nextSetBit(0); layer >= 0; layer = requiredLayers.nextSetBit(layer + 1)) {
|
||||
if (layer >= height) {
|
||||
throw new IllegalArgumentException("Source terrain snapshot layer exceeds writable bounds: " + layer);
|
||||
}
|
||||
BlockState[] states = new BlockState[horizontalCells];
|
||||
statesByLayer[layer] = states;
|
||||
sampledCells = Math.addExact(sampledCells, horizontalCells);
|
||||
int y = Math.addExact(area.minY(), layer);
|
||||
for (int z = area.minZ(); z <= area.maxZ(); z++) {
|
||||
for (int x = area.minX(); x <= area.maxX(); x++) {
|
||||
states[area.columnIndex(x, z)] = sourceTerrainBlock(blocks, blocks.get(x, y, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
return new SourceTerrainSnapshot(area, width, statesByLayer, sampledCells);
|
||||
}
|
||||
|
||||
BlockState stateAt(int x, int y, int z) {
|
||||
if (!area.contains(x, y, z)) {
|
||||
return null;
|
||||
}
|
||||
BlockState[] states = statesByLayer[y - area.minY()];
|
||||
if (states == null) {
|
||||
return null;
|
||||
}
|
||||
return states[(z - area.minZ()) * width + x - area.minX()];
|
||||
}
|
||||
|
||||
int sampledCells() {
|
||||
return sampledCells;
|
||||
}
|
||||
}
|
||||
|
||||
record OrganicCarve(StructureCarvingFootprint footprint, StructureCarveShape shape,
|
||||
int horizontalPadding, int ceilingPadding, int floorPadding,
|
||||
double strength, double frequency, CNG blob, CNG ceilingRoll, CNG floorRoll,
|
||||
CNG lobe, double lobeFrequency, double lobeStrength) {
|
||||
}
|
||||
}
|
||||
@@ -1,424 +0,0 @@
|
||||
package art.arcane.iris.engine.image;
|
||||
|
||||
import art.arcane.iris.engine.object.image.IrisImage;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMap;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapOutOfBounds;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapSampling;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapType;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public final class CompiledIrisImageMap {
|
||||
private final State state;
|
||||
|
||||
CompiledIrisImageMap(State state) {
|
||||
this.state = Objects.requireNonNull(state, "Compiled image-map state");
|
||||
}
|
||||
|
||||
public static CompiledIrisImageMap compile(IrisImageMap definition, IrisImage image) {
|
||||
return IrisImageMapCompiler.compile(definition, image);
|
||||
}
|
||||
|
||||
public IrisImageMap getDefinition() {
|
||||
return state.definition();
|
||||
}
|
||||
|
||||
public IrisImageMapSourceMetadata getSourceMetadata() {
|
||||
return state.sourceMetadata();
|
||||
}
|
||||
|
||||
public IrisImageMapType getType() {
|
||||
return state.type();
|
||||
}
|
||||
|
||||
public int getSourceWidth() {
|
||||
return state.sourceMetadata().width();
|
||||
}
|
||||
|
||||
public int getSourceHeight() {
|
||||
return state.sourceMetadata().height();
|
||||
}
|
||||
|
||||
public String getContentHash() {
|
||||
return state.contentHash();
|
||||
}
|
||||
|
||||
public String contentHash() {
|
||||
return state.contentHash();
|
||||
}
|
||||
|
||||
public CompiledIrisImageMap withoutDecodedValues() {
|
||||
return state.scalarValues() == null && state.targetIndices() == null
|
||||
? this
|
||||
: new CompiledIrisImageMap(state.withoutDecodedValues());
|
||||
}
|
||||
|
||||
public int getClippedPixelCount() {
|
||||
return state.clippedPixelCount();
|
||||
}
|
||||
|
||||
public int getUnknownColorPixelCount() {
|
||||
return state.unknownColorPixelCount();
|
||||
}
|
||||
|
||||
public boolean containsWorld(double worldX, double worldZ) {
|
||||
if (!Double.isFinite(worldX) || !Double.isFinite(worldZ)) {
|
||||
return false;
|
||||
}
|
||||
double sourceX = state.sourceTransform().sourceX(worldX, worldZ);
|
||||
double sourceZ = state.sourceTransform().sourceZ(worldX, worldZ);
|
||||
return validSourceCoordinate(sourceX, sourceZ)
|
||||
&& sourceX >= 0D
|
||||
&& sourceZ >= 0D
|
||||
&& sourceX < state.sourceMetadata().width()
|
||||
&& sourceZ < state.sourceMetadata().height();
|
||||
}
|
||||
|
||||
public boolean containsWorldForSampling(double worldX, double worldZ) {
|
||||
if (!Double.isFinite(worldX) || !Double.isFinite(worldZ)) {
|
||||
return false;
|
||||
}
|
||||
double sourceX = state.sourceTransform().sourceX(worldX, worldZ);
|
||||
double sourceZ = state.sourceTransform().sourceZ(worldX, worldZ);
|
||||
if (!validSourceCoordinate(sourceX, sourceZ)) {
|
||||
return false;
|
||||
}
|
||||
long baseX = floorToLong(sourceX);
|
||||
long baseZ = floorToLong(sourceZ);
|
||||
return switch (state.sampling()) {
|
||||
case NEAREST -> sourceIndexInBounds(baseX, baseZ);
|
||||
case BILINEAR -> bilinearKernelInBounds(sourceX, sourceZ, baseX, baseZ);
|
||||
case BICUBIC -> bicubicKernelInBounds(sourceX, sourceZ, baseX, baseZ);
|
||||
};
|
||||
}
|
||||
|
||||
public double sampleNormalized(double worldX, double worldZ) {
|
||||
requireScalarType();
|
||||
requireWorldCoordinate(worldX, worldZ);
|
||||
double sourceX = state.sourceTransform().sourceX(worldX, worldZ);
|
||||
double sourceZ = state.sourceTransform().sourceZ(worldX, worldZ);
|
||||
requireSourceCoordinate(sourceX, sourceZ);
|
||||
double sampled = switch (state.sampling()) {
|
||||
case NEAREST -> scalarAt(floorToLong(sourceX), floorToLong(sourceZ));
|
||||
case BILINEAR -> bilinear(sourceX, sourceZ);
|
||||
case BICUBIC -> bicubic(sourceX, sourceZ);
|
||||
};
|
||||
return clamp01(sampled);
|
||||
}
|
||||
|
||||
public double sampleHeight(double worldX, double worldZ) {
|
||||
if (!isHeightType()) {
|
||||
throw new IrisImageMapValidationException("Image map type " + state.type() + " does not produce terrain heights");
|
||||
}
|
||||
double normalized = sampleNormalized(worldX, worldZ);
|
||||
double height = state.minimumHeight()
|
||||
+ (normalized * (state.maximumHeight() - state.minimumHeight()))
|
||||
+ state.verticalOffset();
|
||||
if (!state.clampHeight()) {
|
||||
return height;
|
||||
}
|
||||
return Math.max(state.minimumHeight(), Math.min(state.maximumHeight(), height));
|
||||
}
|
||||
|
||||
public String sampleTarget(double worldX, double worldZ) {
|
||||
if (state.type() != IrisImageMapType.COLOR_MAP) {
|
||||
throw new IrisImageMapValidationException("Image map type " + state.type() + " does not produce legend targets");
|
||||
}
|
||||
if (state.targetIndices() == null) {
|
||||
throw new IrisImageMapValidationException("Compiled image-map view does not retain decoded target data");
|
||||
}
|
||||
requireWorldCoordinate(worldX, worldZ);
|
||||
double transformedX = state.sourceTransform().sourceX(worldX, worldZ);
|
||||
double transformedZ = state.sourceTransform().sourceZ(worldX, worldZ);
|
||||
requireSourceCoordinate(transformedX, transformedZ);
|
||||
long sourceX = floorToLong(transformedX);
|
||||
long sourceZ = floorToLong(transformedZ);
|
||||
int resolvedX = resolveIndex(sourceX, state.sourceMetadata().width());
|
||||
int resolvedZ = resolveIndex(sourceZ, state.sourceMetadata().height());
|
||||
if (resolvedX < 0 || resolvedZ < 0) {
|
||||
return state.fallbackTarget();
|
||||
}
|
||||
int targetIndex = state.targetIndices().get((resolvedZ * state.sourceMetadata().width()) + resolvedX);
|
||||
return targetIndex < 0 ? null : state.targets()[targetIndex];
|
||||
}
|
||||
|
||||
private void requireWorldCoordinate(double worldX, double worldZ) {
|
||||
if (!Double.isFinite(worldX) || !Double.isFinite(worldZ)) {
|
||||
throw new IrisImageMapValidationException("World coordinates must be finite, got " + worldX + "," + worldZ);
|
||||
}
|
||||
}
|
||||
|
||||
private void requireSourceCoordinate(double sourceX, double sourceZ) {
|
||||
if (!validSourceCoordinate(sourceX, sourceZ)) {
|
||||
throw new IrisImageMapValidationException(
|
||||
"World coordinates transform outside the supported source-coordinate range: "
|
||||
+ sourceX + "," + sourceZ
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean bilinearKernelInBounds(double sourceX, double sourceZ, long baseX, long baseZ) {
|
||||
long maximumX = sourceX == baseX ? baseX : baseX + 1L;
|
||||
long maximumZ = sourceZ == baseZ ? baseZ : baseZ + 1L;
|
||||
return baseX >= 0L
|
||||
&& baseZ >= 0L
|
||||
&& maximumX < state.sourceMetadata().width()
|
||||
&& maximumZ < state.sourceMetadata().height();
|
||||
}
|
||||
|
||||
private boolean bicubicKernelInBounds(double sourceX, double sourceZ, long baseX, long baseZ) {
|
||||
if (sourceX == baseX && sourceZ == baseZ) {
|
||||
return sourceIndexInBounds(baseX, baseZ);
|
||||
}
|
||||
return baseX >= 1L
|
||||
&& baseZ >= 1L
|
||||
&& baseX + 2L < state.sourceMetadata().width()
|
||||
&& baseZ + 2L < state.sourceMetadata().height();
|
||||
}
|
||||
|
||||
private boolean sourceIndexInBounds(long sourceX, long sourceZ) {
|
||||
return sourceX >= 0L
|
||||
&& sourceZ >= 0L
|
||||
&& sourceX < state.sourceMetadata().width()
|
||||
&& sourceZ < state.sourceMetadata().height();
|
||||
}
|
||||
|
||||
private double bilinear(double sourceX, double sourceZ) {
|
||||
long x0 = floorToLong(sourceX);
|
||||
long z0 = floorToLong(sourceZ);
|
||||
double fractionX = sourceX - x0;
|
||||
double fractionZ = sourceZ - z0;
|
||||
if (fractionX == 0D && fractionZ == 0D) {
|
||||
return scalarAt(x0, z0);
|
||||
}
|
||||
if (fractionZ == 0D) {
|
||||
return lerp(scalarAt(x0, z0), scalarAt(x0 + 1L, z0), fractionX);
|
||||
}
|
||||
if (fractionX == 0D) {
|
||||
return lerp(scalarAt(x0, z0), scalarAt(x0, z0 + 1L), fractionZ);
|
||||
}
|
||||
double top = lerp(scalarAt(x0, z0), scalarAt(x0 + 1L, z0), fractionX);
|
||||
double bottom = lerp(scalarAt(x0, z0 + 1L), scalarAt(x0 + 1L, z0 + 1L), fractionX);
|
||||
return lerp(top, bottom, fractionZ);
|
||||
}
|
||||
|
||||
private double bicubic(double sourceX, double sourceZ) {
|
||||
long baseX = floorToLong(sourceX);
|
||||
long baseZ = floorToLong(sourceZ);
|
||||
double fractionX = sourceX - baseX;
|
||||
double fractionZ = sourceZ - baseZ;
|
||||
if (fractionX == 0D && fractionZ == 0D) {
|
||||
return scalarAt(baseX, baseZ);
|
||||
}
|
||||
double row0 = cubicRow(baseX, baseZ - 1L, fractionX);
|
||||
double row1 = cubicRow(baseX, baseZ, fractionX);
|
||||
double row2 = cubicRow(baseX, baseZ + 1L, fractionX);
|
||||
double row3 = cubicRow(baseX, baseZ + 2L, fractionX);
|
||||
return cubic(row0, row1, row2, row3, fractionZ);
|
||||
}
|
||||
|
||||
private double cubicRow(long baseX, long sourceZ, double fractionX) {
|
||||
return cubic(
|
||||
scalarAt(baseX - 1L, sourceZ),
|
||||
scalarAt(baseX, sourceZ),
|
||||
scalarAt(baseX + 1L, sourceZ),
|
||||
scalarAt(baseX + 2L, sourceZ),
|
||||
fractionX
|
||||
);
|
||||
}
|
||||
|
||||
private double scalarAt(long sourceX, long sourceZ) {
|
||||
int resolvedX = resolveIndex(sourceX, state.sourceMetadata().width());
|
||||
int resolvedZ = resolveIndex(sourceZ, state.sourceMetadata().height());
|
||||
if (resolvedX < 0 || resolvedZ < 0) {
|
||||
return state.fallbackValue();
|
||||
}
|
||||
return state.scalarValues().get((resolvedZ * state.sourceMetadata().width()) + resolvedX);
|
||||
}
|
||||
|
||||
private int resolveIndex(long coordinate, int length) {
|
||||
if (coordinate >= 0L && coordinate < length) {
|
||||
return (int) coordinate;
|
||||
}
|
||||
IrisImageMapOutOfBounds outOfBounds = state.outOfBounds();
|
||||
return switch (outOfBounds) {
|
||||
case FALLBACK -> -1;
|
||||
case CLAMP -> coordinate < 0L ? 0 : length - 1;
|
||||
case REPEAT -> (int) Math.floorMod(coordinate, (long) length);
|
||||
case MIRROR -> mirrorIndex(coordinate, length);
|
||||
case ERROR -> throw new IrisImageMapValidationException(
|
||||
"Source coordinate " + coordinate + " is outside 0.." + (length - 1)
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
private int mirrorIndex(long coordinate, int length) {
|
||||
if (length == 1) {
|
||||
return 0;
|
||||
}
|
||||
long period = (long) length * 2L;
|
||||
long mirrored = Math.floorMod(coordinate, period);
|
||||
if (mirrored >= length) {
|
||||
mirrored = period - 1L - mirrored;
|
||||
}
|
||||
return (int) mirrored;
|
||||
}
|
||||
|
||||
private boolean isHeightType() {
|
||||
return state.type() == IrisImageMapType.GRAYSCALE_HEIGHT
|
||||
|| state.type() == IrisImageMapType.RGB_HEIGHT;
|
||||
}
|
||||
|
||||
private void requireScalarType() {
|
||||
if (state.scalarValues() == null) {
|
||||
if (isHeightType()
|
||||
|| state.type() == IrisImageMapType.BINARY_MASK
|
||||
|| state.type() == IrisImageMapType.GRAYSCALE_MASK
|
||||
|| state.type() == IrisImageMapType.ALPHA_MASK) {
|
||||
throw new IrisImageMapValidationException("Compiled image-map view does not retain decoded scalar data");
|
||||
}
|
||||
throw new IrisImageMapValidationException("Image map type " + state.type() + " does not produce normalized scalar data");
|
||||
}
|
||||
}
|
||||
|
||||
private static long floorToLong(double value) {
|
||||
return (long) Math.floor(value);
|
||||
}
|
||||
|
||||
private static boolean validSourceCoordinate(double sourceX, double sourceZ) {
|
||||
double safeMinimum = -9_000_000_000_000_000_000D;
|
||||
double safeMaximum = 9_000_000_000_000_000_000D;
|
||||
return Double.isFinite(sourceX)
|
||||
&& Double.isFinite(sourceZ)
|
||||
&& sourceX >= safeMinimum
|
||||
&& sourceX <= safeMaximum
|
||||
&& sourceZ >= safeMinimum
|
||||
&& sourceZ <= safeMaximum;
|
||||
}
|
||||
|
||||
private static double lerp(double a, double b, double factor) {
|
||||
return a + ((b - a) * factor);
|
||||
}
|
||||
|
||||
private static double cubic(double p0, double p1, double p2, double p3, double factor) {
|
||||
double squared = factor * factor;
|
||||
double cubed = squared * factor;
|
||||
return 0.5D * ((2D * p1)
|
||||
+ ((-p0 + p2) * factor)
|
||||
+ (((2D * p0) - (5D * p1) + (4D * p2) - p3) * squared)
|
||||
+ ((-p0 + (3D * p1) - (3D * p2) + p3) * cubed));
|
||||
}
|
||||
|
||||
private static double clamp01(double value) {
|
||||
return Math.max(0D, Math.min(1D, value));
|
||||
}
|
||||
|
||||
static record State(
|
||||
IrisImageMap definition,
|
||||
IrisImageMapSourceMetadata sourceMetadata,
|
||||
IrisImageMapType type,
|
||||
FloatTiles scalarValues,
|
||||
IntTiles targetIndices,
|
||||
String[] targets,
|
||||
SourceTransform sourceTransform,
|
||||
IrisImageMapSampling sampling,
|
||||
IrisImageMapOutOfBounds outOfBounds,
|
||||
double fallbackValue,
|
||||
String fallbackTarget,
|
||||
double minimumHeight,
|
||||
double maximumHeight,
|
||||
double verticalOffset,
|
||||
boolean clampHeight,
|
||||
int clippedPixelCount,
|
||||
int unknownColorPixelCount,
|
||||
String contentHash
|
||||
) {
|
||||
State withoutDecodedValues() {
|
||||
return new State(
|
||||
definition,
|
||||
sourceMetadata,
|
||||
type,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
sourceTransform,
|
||||
sampling,
|
||||
outOfBounds,
|
||||
fallbackValue,
|
||||
fallbackTarget,
|
||||
minimumHeight,
|
||||
maximumHeight,
|
||||
verticalOffset,
|
||||
clampHeight,
|
||||
clippedPixelCount,
|
||||
unknownColorPixelCount,
|
||||
contentHash
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
static record SourceTransform(
|
||||
double sourceXFromWorldX,
|
||||
double sourceXFromWorldZ,
|
||||
double sourceXOffset,
|
||||
double sourceZFromWorldX,
|
||||
double sourceZFromWorldZ,
|
||||
double sourceZOffset
|
||||
) {
|
||||
double sourceX(double worldX, double worldZ) {
|
||||
return (sourceXFromWorldX * worldX) + (sourceXFromWorldZ * worldZ) + sourceXOffset;
|
||||
}
|
||||
|
||||
double sourceZ(double worldX, double worldZ) {
|
||||
return (sourceZFromWorldX * worldX) + (sourceZFromWorldZ * worldZ) + sourceZOffset;
|
||||
}
|
||||
}
|
||||
|
||||
static final class FloatTiles {
|
||||
private static final int TILE_SHIFT = 20;
|
||||
private static final int TILE_SIZE = 1 << TILE_SHIFT;
|
||||
private static final int TILE_MASK = TILE_SIZE - 1;
|
||||
private final float[][] tiles;
|
||||
|
||||
FloatTiles(int size) {
|
||||
int tileCount = (size + TILE_SIZE - 1) >>> TILE_SHIFT;
|
||||
tiles = new float[tileCount][];
|
||||
for (int tile = 0; tile < tileCount; tile++) {
|
||||
int remaining = size - (tile << TILE_SHIFT);
|
||||
tiles[tile] = new float[Math.min(TILE_SIZE, remaining)];
|
||||
}
|
||||
}
|
||||
|
||||
float get(int index) {
|
||||
return tiles[index >>> TILE_SHIFT][index & TILE_MASK];
|
||||
}
|
||||
|
||||
void set(int index, float value) {
|
||||
tiles[index >>> TILE_SHIFT][index & TILE_MASK] = value;
|
||||
}
|
||||
}
|
||||
|
||||
static final class IntTiles {
|
||||
private static final int TILE_SHIFT = 20;
|
||||
private static final int TILE_SIZE = 1 << TILE_SHIFT;
|
||||
private static final int TILE_MASK = TILE_SIZE - 1;
|
||||
private final int[][] tiles;
|
||||
|
||||
IntTiles(int size) {
|
||||
int tileCount = (size + TILE_SIZE - 1) >>> TILE_SHIFT;
|
||||
tiles = new int[tileCount][];
|
||||
for (int tile = 0; tile < tileCount; tile++) {
|
||||
int remaining = size - (tile << TILE_SHIFT);
|
||||
tiles[tile] = new int[Math.min(TILE_SIZE, remaining)];
|
||||
}
|
||||
}
|
||||
|
||||
int get(int index) {
|
||||
return tiles[index >>> TILE_SHIFT][index & TILE_MASK];
|
||||
}
|
||||
|
||||
void set(int index, int value) {
|
||||
tiles[index >>> TILE_SHIFT][index & TILE_MASK] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,825 +0,0 @@
|
||||
package art.arcane.iris.engine.image;
|
||||
|
||||
import art.arcane.iris.engine.object.image.IrisImage;
|
||||
import art.arcane.iris.engine.object.image.IrisImageColorMode;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMap;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapAlpha;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapOrigin;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapOutOfBounds;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapSampling;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapType;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapUnknownColor;
|
||||
import art.arcane.volmlib.util.collection.KMap;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class IrisImageMapCompiler {
|
||||
public static final int MINIMUM_DIMENSION = 1;
|
||||
public static final int MAXIMUM_DIMENSION = 16_384;
|
||||
public static final long MAXIMUM_PIXELS = 16_777_216L;
|
||||
|
||||
private static final Pattern COLOR_PATTERN = Pattern.compile("#[0-9a-fA-F]{6}");
|
||||
|
||||
private IrisImageMapCompiler() {
|
||||
}
|
||||
|
||||
public static CompiledIrisImageMap compile(IrisImageMap definition, IrisImage image) {
|
||||
if (definition == null) {
|
||||
throw new IrisImageMapValidationException("Image-map definition is required");
|
||||
}
|
||||
if (image == null) {
|
||||
throw new IrisImageMapValidationException("Decoded image source is required");
|
||||
}
|
||||
|
||||
List<String> diagnostics = validate(definition, image);
|
||||
if (!diagnostics.isEmpty()) {
|
||||
throw new IrisImageMapValidationException(diagnostics);
|
||||
}
|
||||
|
||||
try {
|
||||
SourceDigest sourceDigest = hashSource(image);
|
||||
IrisImageMapSourceMetadata metadata = new IrisImageMapSourceMetadata(
|
||||
image.getFormat(),
|
||||
image.getColorMode(),
|
||||
image.getWidth(),
|
||||
image.getHeight(),
|
||||
image.getColorComponentCount(),
|
||||
image.getChannelCount(),
|
||||
image.getBitDepth(),
|
||||
image.hasAlpha(),
|
||||
sourceDigest.minimumAlpha(),
|
||||
sourceDigest.maximumAlpha(),
|
||||
sourceDigest.hash()
|
||||
);
|
||||
IrisImageMap snapshot = snapshot(definition);
|
||||
CompiledIrisImageMap.FloatTiles scalarValues = null;
|
||||
CompiledIrisImageMap.IntTiles targetIndices = null;
|
||||
String[] targets = null;
|
||||
int clippedPixelCount = 0;
|
||||
int unknownColorPixelCount = 0;
|
||||
|
||||
if (definition.getType() == IrisImageMapType.COLOR_MAP) {
|
||||
CompiledTargets compiledTargets = compileTargets(definition, image);
|
||||
targetIndices = compiledTargets.indices();
|
||||
targets = compiledTargets.targets();
|
||||
unknownColorPixelCount = compiledTargets.unknownColorPixelCount();
|
||||
} else {
|
||||
scalarValues = compileScalars(definition, image);
|
||||
if (definition.getSmoothingRadius() > 0) {
|
||||
smooth(scalarValues, image.getWidth(), image.getHeight(), definition.getSmoothingRadius());
|
||||
}
|
||||
clippedPixelCount = countClippedPixels(
|
||||
definition, scalarValues, Math.multiplyExact(image.getWidth(), image.getHeight())
|
||||
);
|
||||
}
|
||||
|
||||
String contentHash = hashContent(snapshot, metadata);
|
||||
String fallbackTarget = definition.getFallbackTarget() == null || definition.getFallbackTarget().isBlank()
|
||||
? null
|
||||
: definition.getFallbackTarget();
|
||||
CompiledIrisImageMap.SourceTransform sourceTransform = compileSourceTransform(definition);
|
||||
CompiledIrisImageMap.State state = new CompiledIrisImageMap.State(
|
||||
snapshot,
|
||||
metadata,
|
||||
definition.getType(),
|
||||
scalarValues,
|
||||
targetIndices,
|
||||
targets,
|
||||
sourceTransform,
|
||||
definition.getSampling(),
|
||||
definition.getOutOfBounds(),
|
||||
definition.getFallbackValue(),
|
||||
fallbackTarget,
|
||||
definition.getMinimumHeight(),
|
||||
definition.getMaximumHeight(),
|
||||
definition.getVerticalOffset(),
|
||||
definition.isClamp(),
|
||||
clippedPixelCount,
|
||||
unknownColorPixelCount,
|
||||
contentHash
|
||||
);
|
||||
return new CompiledIrisImageMap(state);
|
||||
} catch (IrisImageMapValidationException exception) {
|
||||
throw exception;
|
||||
} catch (RuntimeException exception) {
|
||||
throw new IrisImageMapValidationException(
|
||||
"Failed to compile image map '" + definition.getSource() + "': " + exception.getMessage(),
|
||||
exception
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> validate(IrisImageMap definition, IrisImage image) {
|
||||
List<String> diagnostics = new ArrayList<>();
|
||||
if (definition.getSource() == null || definition.getSource().isBlank()) {
|
||||
diagnostics.add("Image-map source must not be blank");
|
||||
}
|
||||
validateSource(image, diagnostics);
|
||||
validateCoordinates(definition, diagnostics);
|
||||
validateScalarSettings(definition, diagnostics);
|
||||
validateType(definition, image, diagnostics);
|
||||
validateLegend(definition, diagnostics);
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
private static void validateSource(IrisImage image, List<String> diagnostics) {
|
||||
if (!"png".equals(image.getFormat())) {
|
||||
diagnostics.add("Image format must be PNG, got " + image.getFormat());
|
||||
}
|
||||
int width = image.getWidth();
|
||||
int height = image.getHeight();
|
||||
if (width < MINIMUM_DIMENSION || width > MAXIMUM_DIMENSION) {
|
||||
diagnostics.add("Image width must be " + MINIMUM_DIMENSION + ".." + MAXIMUM_DIMENSION + ", got " + width);
|
||||
}
|
||||
if (height < MINIMUM_DIMENSION || height > MAXIMUM_DIMENSION) {
|
||||
diagnostics.add("Image height must be " + MINIMUM_DIMENSION + ".." + MAXIMUM_DIMENSION + ", got " + height);
|
||||
}
|
||||
long pixels = (long) width * height;
|
||||
if (pixels > MAXIMUM_PIXELS) {
|
||||
diagnostics.add("Image contains " + pixels + " pixels; maximum is " + MAXIMUM_PIXELS);
|
||||
}
|
||||
if (image.getColorMode() == IrisImageColorMode.INDEXED) {
|
||||
diagnostics.add("Indexed PNG images are unsupported; convert the source to grayscale, RGB, or RGBA");
|
||||
} else if (image.getColorMode() == IrisImageColorMode.UNSUPPORTED) {
|
||||
diagnostics.add("Unsupported PNG color mode with " + image.getColorComponentCount()
|
||||
+ " color components and " + image.getChannelCount() + " channels");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateCoordinates(IrisImageMap definition, List<String> diagnostics) {
|
||||
if (!finiteAtLeast(definition.getBlocksPerPixel(), IrisImageMap.MINIMUM_SCALE)) {
|
||||
diagnostics.add("blocksPerPixel must be finite and at least " + IrisImageMap.MINIMUM_SCALE);
|
||||
}
|
||||
IrisImageMapOrigin origin = definition.getOrigin();
|
||||
if (origin == null || !Double.isFinite(origin.getX()) || !Double.isFinite(origin.getZ())) {
|
||||
diagnostics.add("origin X and Z must be finite");
|
||||
}
|
||||
IrisImageMapOrigin sourceOrigin = definition.getSourceOrigin();
|
||||
if (sourceOrigin == null || !Double.isFinite(sourceOrigin.getX()) || !Double.isFinite(sourceOrigin.getZ())) {
|
||||
diagnostics.add("sourceOrigin X and Z must be finite");
|
||||
}
|
||||
if (definition.getRotation() == null) {
|
||||
diagnostics.add("rotation is required");
|
||||
}
|
||||
if (definition.getSampling() == null) {
|
||||
diagnostics.add("sampling is required");
|
||||
}
|
||||
if (definition.getOutOfBounds() == null) {
|
||||
diagnostics.add("outOfBounds is required");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateScalarSettings(IrisImageMap definition, List<String> diagnostics) {
|
||||
if (!range(definition.getFallbackValue(), 0D, 1D)) {
|
||||
diagnostics.add("fallbackValue must be finite and within 0..1");
|
||||
}
|
||||
if (!Double.isFinite(definition.getMinimumHeight()) || !Double.isFinite(definition.getMaximumHeight())) {
|
||||
diagnostics.add("minimumHeight and maximumHeight must be finite");
|
||||
} else if (definition.getMaximumHeight() < definition.getMinimumHeight()) {
|
||||
diagnostics.add("maximumHeight must be greater than or equal to minimumHeight");
|
||||
}
|
||||
if (!Double.isFinite(definition.getVerticalOffset())) {
|
||||
diagnostics.add("verticalOffset must be finite");
|
||||
}
|
||||
if (!finiteAtLeast(definition.getCurveExponent(), IrisImageMap.MINIMUM_SCALE)) {
|
||||
diagnostics.add("curveExponent must be finite and at least " + IrisImageMap.MINIMUM_SCALE);
|
||||
}
|
||||
if (definition.getSmoothingRadius() < 0 || definition.getSmoothingRadius() > 32) {
|
||||
diagnostics.add("smoothingRadius must be within 0..32");
|
||||
}
|
||||
if (!range(definition.getThreshold(), 0D, 1D)) {
|
||||
diagnostics.add("threshold must be finite and within 0..1");
|
||||
}
|
||||
if (!range(definition.getFalloff(), 0D, 1D)) {
|
||||
diagnostics.add("falloff must be finite and within 0..1");
|
||||
}
|
||||
if (!range(definition.getColorTolerance(), 0D, IrisImageMap.MAXIMUM_COLOR_TOLERANCE)) {
|
||||
diagnostics.add("colorTolerance must be finite and within 0.."
|
||||
+ IrisImageMap.MAXIMUM_COLOR_TOLERANCE);
|
||||
}
|
||||
if (definition.getAlpha() == null) {
|
||||
diagnostics.add("alpha policy is required");
|
||||
}
|
||||
if (definition.getUnknownColor() == null) {
|
||||
diagnostics.add("unknownColor policy is required");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateType(IrisImageMap definition, IrisImage image, List<String> diagnostics) {
|
||||
IrisImageMapType type = definition.getType();
|
||||
if (type == null) {
|
||||
diagnostics.add("Image-map type is required");
|
||||
return;
|
||||
}
|
||||
|
||||
IrisImageColorMode colorMode = image.getColorMode();
|
||||
int bitDepth = image.getBitDepth();
|
||||
switch (type) {
|
||||
case GRAYSCALE_HEIGHT, BINARY_MASK, GRAYSCALE_MASK -> {
|
||||
if (colorMode != IrisImageColorMode.GRAYSCALE) {
|
||||
diagnostics.add(type + " requires a grayscale PNG, got " + colorMode);
|
||||
}
|
||||
if (bitDepth != 8 && bitDepth != 16) {
|
||||
diagnostics.add(type + " requires 8-bit or 16-bit grayscale samples, got " + bitDepth + "-bit");
|
||||
}
|
||||
}
|
||||
case RGB_HEIGHT, COLOR_MAP -> {
|
||||
if (colorMode != IrisImageColorMode.RGB && colorMode != IrisImageColorMode.RGBA) {
|
||||
diagnostics.add(type + " requires an RGB or RGBA PNG, got " + colorMode);
|
||||
}
|
||||
if (bitDepth != 8) {
|
||||
diagnostics.add(type + " requires canonical 8-bit RGB channels, got " + bitDepth + "-bit");
|
||||
}
|
||||
}
|
||||
case ALPHA_MASK -> {
|
||||
if (colorMode != IrisImageColorMode.RGBA || !image.hasAlpha()) {
|
||||
diagnostics.add("ALPHA_MASK requires an 8-bit RGBA PNG");
|
||||
}
|
||||
if (bitDepth != 8) {
|
||||
diagnostics.add("ALPHA_MASK requires an 8-bit alpha channel, got " + bitDepth + "-bit color channels");
|
||||
}
|
||||
if (definition.getAlpha() != null && definition.getAlpha() != IrisImageMapAlpha.IGNORE) {
|
||||
diagnostics.add("ALPHA_MASK requires alpha=IGNORE because alpha is the map data");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((type == IrisImageMapType.COLOR_MAP || type == IrisImageMapType.BINARY_MASK)
|
||||
&& definition.getSampling() != null
|
||||
&& definition.getSampling() != IrisImageMapSampling.NEAREST) {
|
||||
diagnostics.add(type + " requires NEAREST sampling");
|
||||
}
|
||||
if (type == IrisImageMapType.COLOR_MAP && definition.getSmoothingRadius() != 0) {
|
||||
diagnostics.add("COLOR_MAP does not support numeric smoothing");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateLegend(IrisImageMap definition, List<String> diagnostics) {
|
||||
KMap<String, String> colors = definition.getColors();
|
||||
if (definition.getType() != IrisImageMapType.COLOR_MAP) {
|
||||
if (colors != null && !colors.isEmpty()) {
|
||||
diagnostics.add("colors may only be set for COLOR_MAP definitions");
|
||||
}
|
||||
if (definition.getColorTolerance() != 0D) {
|
||||
diagnostics.add("colorTolerance may only be set for COLOR_MAP definitions");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (colors == null || colors.isEmpty()) {
|
||||
diagnostics.add("COLOR_MAP requires at least one #RRGGBB legend entry");
|
||||
return;
|
||||
}
|
||||
|
||||
Map<Integer, String> decoded = new HashMap<>();
|
||||
for (Map.Entry<String, String> entry : colors.entrySet()) {
|
||||
String encoded = entry.getKey();
|
||||
String target = entry.getValue();
|
||||
if (encoded == null || !COLOR_PATTERN.matcher(encoded).matches()) {
|
||||
diagnostics.add("Color legend key must use exact #RRGGBB syntax, got " + encoded);
|
||||
continue;
|
||||
}
|
||||
if (target == null || target.isBlank()) {
|
||||
diagnostics.add("Color legend target for " + encoded + " must not be blank");
|
||||
}
|
||||
int rgb = Integer.parseInt(encoded.substring(1), 16);
|
||||
String previous = decoded.putIfAbsent(rgb, encoded);
|
||||
if (previous != null) {
|
||||
diagnostics.add("Color legend duplicates raw color " + previous + " as " + encoded);
|
||||
}
|
||||
}
|
||||
|
||||
boolean fallbackRequired = definition.getOutOfBounds() == IrisImageMapOutOfBounds.FALLBACK
|
||||
|| definition.getUnknownColor() == IrisImageMapUnknownColor.FALLBACK
|
||||
|| definition.getAlpha() == IrisImageMapAlpha.TRANSPARENT_IS_FALLBACK
|
||||
|| definition.getAlpha() == IrisImageMapAlpha.MASK;
|
||||
if (fallbackRequired && (definition.getFallbackTarget() == null || definition.getFallbackTarget().isBlank())) {
|
||||
diagnostics.add("fallbackTarget is required by the configured color-map fallback policy");
|
||||
}
|
||||
}
|
||||
|
||||
private static CompiledIrisImageMap.FloatTiles compileScalars(IrisImageMap definition, IrisImage image) {
|
||||
int width = image.getWidth();
|
||||
int height = image.getHeight();
|
||||
CompiledIrisImageMap.FloatTiles values = new CompiledIrisImageMap.FloatTiles(
|
||||
Math.multiplyExact(width, height)
|
||||
);
|
||||
for (int sourceZ = 0; sourceZ < height; sourceZ++) {
|
||||
for (int sourceX = 0; sourceX < width; sourceX++) {
|
||||
double alpha = image.getAlphaNormalized(sourceX, sourceZ);
|
||||
validateAlphaPixel(definition, sourceX, sourceZ, alpha);
|
||||
double value;
|
||||
if (definition.getAlpha() == IrisImageMapAlpha.TRANSPARENT_IS_FALLBACK && alpha == 0D) {
|
||||
value = definition.getFallbackValue();
|
||||
} else {
|
||||
value = rawScalar(definition.getType(), image, sourceX, sourceZ);
|
||||
if (definition.isInverted()) {
|
||||
value = 1D - value;
|
||||
}
|
||||
value = Math.pow(clamp01(value), definition.getCurveExponent());
|
||||
if (definition.getType() == IrisImageMapType.BINARY_MASK) {
|
||||
value = threshold(value, definition.getThreshold(), definition.getFalloff());
|
||||
}
|
||||
if (definition.getAlpha() == IrisImageMapAlpha.MASK) {
|
||||
value *= alpha;
|
||||
}
|
||||
}
|
||||
values.set((sourceZ * width) + sourceX, (float) clamp01(value));
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private static double rawScalar(IrisImageMapType type, IrisImage image, int sourceX, int sourceZ) {
|
||||
return switch (type) {
|
||||
case GRAYSCALE_HEIGHT, BINARY_MASK, GRAYSCALE_MASK -> image.getBandNormalized(sourceX, sourceZ, 0);
|
||||
case RGB_HEIGHT -> {
|
||||
int red = image.getBandSample(sourceX, sourceZ, 0);
|
||||
int green = image.getBandSample(sourceX, sourceZ, 1);
|
||||
int blue = image.getBandSample(sourceX, sourceZ, 2);
|
||||
int encoded = (red << 16) | (green << 8) | blue;
|
||||
yield encoded / 16_777_215D;
|
||||
}
|
||||
case ALPHA_MASK -> image.getAlphaNormalized(sourceX, sourceZ);
|
||||
case COLOR_MAP -> throw new IrisImageMapValidationException("COLOR_MAP does not produce scalar pixels");
|
||||
};
|
||||
}
|
||||
|
||||
private static CompiledTargets compileTargets(IrisImageMap definition, IrisImage image) {
|
||||
Legend legend = compileLegend(definition);
|
||||
int width = image.getWidth();
|
||||
int height = image.getHeight();
|
||||
CompiledIrisImageMap.IntTiles indices = new CompiledIrisImageMap.IntTiles(
|
||||
Math.multiplyExact(width, height)
|
||||
);
|
||||
int unknownColorPixelCount = 0;
|
||||
for (int sourceZ = 0; sourceZ < height; sourceZ++) {
|
||||
for (int sourceX = 0; sourceX < width; sourceX++) {
|
||||
double alpha = image.getAlphaNormalized(sourceX, sourceZ);
|
||||
validateAlphaPixel(definition, sourceX, sourceZ, alpha);
|
||||
int targetIndex;
|
||||
if (definition.getAlpha() == IrisImageMapAlpha.TRANSPARENT_IS_FALLBACK && alpha == 0D) {
|
||||
targetIndex = legend.fallbackIndex();
|
||||
} else if (definition.getAlpha() == IrisImageMapAlpha.MASK && alpha < 1D) {
|
||||
if (alpha == 0D) {
|
||||
targetIndex = legend.fallbackIndex();
|
||||
} else {
|
||||
throw new IrisImageMapValidationException(
|
||||
"COLOR_MAP alpha=MASK requires binary alpha; pixel " + sourceX + "," + sourceZ
|
||||
+ " has alpha " + alpha
|
||||
);
|
||||
}
|
||||
} else {
|
||||
int rgb = image.getRawRgb8(sourceX, sourceZ);
|
||||
TargetMatch match = matchTarget(definition, legend, rgb, sourceX, sourceZ);
|
||||
targetIndex = match.targetIndex();
|
||||
if (match.unknown()) {
|
||||
unknownColorPixelCount++;
|
||||
}
|
||||
}
|
||||
indices.set((sourceZ * width) + sourceX, targetIndex);
|
||||
}
|
||||
}
|
||||
return new CompiledTargets(indices, legend.targets(), unknownColorPixelCount);
|
||||
}
|
||||
|
||||
private static Legend compileLegend(IrisImageMap definition) {
|
||||
List<MutableLegendEntry> entries = new ArrayList<>();
|
||||
for (Map.Entry<String, String> entry : definition.getColors().entrySet()) {
|
||||
int rgb = Integer.parseInt(entry.getKey().substring(1), 16);
|
||||
entries.add(new MutableLegendEntry(rgb, entry.getKey().toUpperCase(), entry.getValue()));
|
||||
}
|
||||
entries.sort(Comparator.comparingInt(MutableLegendEntry::rgb).thenComparing(MutableLegendEntry::target));
|
||||
|
||||
LinkedHashMap<String, Integer> targetIndexes = new LinkedHashMap<>();
|
||||
Map<Integer, LegendEntry> exact = new HashMap<>();
|
||||
List<LegendEntry> compiled = new ArrayList<>();
|
||||
for (MutableLegendEntry entry : entries) {
|
||||
int targetIndex = targetIndexes.computeIfAbsent(entry.target(), ignored -> targetIndexes.size());
|
||||
LegendEntry compiledEntry = new LegendEntry(entry.rgb(), entry.encoded(), entry.target(), targetIndex);
|
||||
exact.put(entry.rgb(), compiledEntry);
|
||||
compiled.add(compiledEntry);
|
||||
}
|
||||
|
||||
int fallbackIndex = -1;
|
||||
if (definition.getFallbackTarget() != null && !definition.getFallbackTarget().isBlank()) {
|
||||
fallbackIndex = targetIndexes.computeIfAbsent(
|
||||
definition.getFallbackTarget(),
|
||||
ignored -> targetIndexes.size()
|
||||
);
|
||||
}
|
||||
String[] targets = new String[targetIndexes.size()];
|
||||
for (Map.Entry<String, Integer> entry : targetIndexes.entrySet()) {
|
||||
targets[entry.getValue()] = entry.getKey();
|
||||
}
|
||||
return new Legend(List.copyOf(compiled), Map.copyOf(exact), targets, fallbackIndex);
|
||||
}
|
||||
|
||||
private static TargetMatch matchTarget(
|
||||
IrisImageMap definition,
|
||||
Legend legend,
|
||||
int rgb,
|
||||
int sourceX,
|
||||
int sourceZ
|
||||
) {
|
||||
LegendEntry exact = legend.exact().get(rgb);
|
||||
if (exact != null) {
|
||||
return new TargetMatch(exact.targetIndex(), false);
|
||||
}
|
||||
|
||||
double toleranceSquared = definition.getColorTolerance() * definition.getColorTolerance();
|
||||
LegendEntry matched = null;
|
||||
List<String> ambiguous = new ArrayList<>();
|
||||
if (toleranceSquared > 0D) {
|
||||
for (LegendEntry candidate : legend.entries()) {
|
||||
if (colorDistanceSquared(rgb, candidate.rgb()) <= toleranceSquared) {
|
||||
if (matched == null) {
|
||||
matched = candidate;
|
||||
}
|
||||
ambiguous.add(candidate.encoded());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ambiguous.size() > 1) {
|
||||
throw new IrisImageMapValidationException(
|
||||
"Color " + encodeColor(rgb) + " at " + sourceX + "," + sourceZ
|
||||
+ " ambiguously matches " + String.join(", ", ambiguous)
|
||||
);
|
||||
}
|
||||
if (matched != null) {
|
||||
return new TargetMatch(matched.targetIndex(), false);
|
||||
}
|
||||
|
||||
int targetIndex = switch (definition.getUnknownColor()) {
|
||||
case ERROR -> throw new IrisImageMapValidationException(
|
||||
"Color " + encodeColor(rgb) + " at " + sourceX + "," + sourceZ + " is absent from the legend"
|
||||
);
|
||||
case FALLBACK -> legend.fallbackIndex();
|
||||
case IGNORE -> -1;
|
||||
};
|
||||
return new TargetMatch(targetIndex, true);
|
||||
}
|
||||
|
||||
private static int countClippedPixels(
|
||||
IrisImageMap definition,
|
||||
CompiledIrisImageMap.FloatTiles values,
|
||||
int size
|
||||
) {
|
||||
if (!definition.isClamp()
|
||||
|| (definition.getType() != IrisImageMapType.GRAYSCALE_HEIGHT
|
||||
&& definition.getType() != IrisImageMapType.RGB_HEIGHT)) {
|
||||
return 0;
|
||||
}
|
||||
double minimum = definition.getMinimumHeight();
|
||||
double maximum = definition.getMaximumHeight();
|
||||
double range = maximum - minimum;
|
||||
double offset = definition.getVerticalOffset();
|
||||
int clipped = 0;
|
||||
for (int index = 0; index < size; index++) {
|
||||
double height = minimum + (values.get(index) * range) + offset;
|
||||
if (height < minimum || height > maximum) {
|
||||
clipped++;
|
||||
}
|
||||
}
|
||||
return clipped;
|
||||
}
|
||||
|
||||
private static void validateAlphaPixel(IrisImageMap definition, int sourceX, int sourceZ, double alpha) {
|
||||
if (definition.getAlpha() == IrisImageMapAlpha.ERROR && alpha < 1D) {
|
||||
throw new IrisImageMapValidationException(
|
||||
"Transparent pixel at " + sourceX + "," + sourceZ + " violates alpha=ERROR"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static double threshold(double value, double threshold, double falloff) {
|
||||
if (falloff == 0D) {
|
||||
return value >= threshold ? 1D : 0D;
|
||||
}
|
||||
return clamp01((value - threshold) / falloff);
|
||||
}
|
||||
|
||||
private static void smooth(CompiledIrisImageMap.FloatTiles values, int width, int height, int radius) {
|
||||
float[] line = new float[Math.max(width, height)];
|
||||
int diameter = (radius * 2) + 1;
|
||||
for (int sourceZ = 0; sourceZ < height; sourceZ++) {
|
||||
int rowOffset = sourceZ * width;
|
||||
for (int sourceX = 0; sourceX < width; sourceX++) {
|
||||
line[sourceX] = values.get(rowOffset + sourceX);
|
||||
}
|
||||
double sum = 0D;
|
||||
for (int offset = -radius; offset <= radius; offset++) {
|
||||
int sourceX = Math.max(0, Math.min(width - 1, offset));
|
||||
sum += line[sourceX];
|
||||
}
|
||||
for (int sourceX = 0; sourceX < width; sourceX++) {
|
||||
values.set(rowOffset + sourceX, (float) (sum / diameter));
|
||||
int leavingX = Math.max(0, Math.min(width - 1, sourceX - radius));
|
||||
int enteringX = Math.max(0, Math.min(width - 1, sourceX + radius + 1));
|
||||
sum += line[enteringX] - line[leavingX];
|
||||
}
|
||||
}
|
||||
|
||||
for (int sourceX = 0; sourceX < width; sourceX++) {
|
||||
for (int sourceZ = 0; sourceZ < height; sourceZ++) {
|
||||
line[sourceZ] = values.get((sourceZ * width) + sourceX);
|
||||
}
|
||||
double sum = 0D;
|
||||
for (int offset = -radius; offset <= radius; offset++) {
|
||||
int sourceZ = Math.max(0, Math.min(height - 1, offset));
|
||||
sum += line[sourceZ];
|
||||
}
|
||||
for (int sourceZ = 0; sourceZ < height; sourceZ++) {
|
||||
values.set((sourceZ * width) + sourceX, (float) (sum / diameter));
|
||||
int leavingZ = Math.max(0, Math.min(height - 1, sourceZ - radius));
|
||||
int enteringZ = Math.max(0, Math.min(height - 1, sourceZ + radius + 1));
|
||||
sum += line[enteringZ] - line[leavingZ];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static SourceDigest hashSource(IrisImage image) {
|
||||
HashAccumulator hash = new HashAccumulator();
|
||||
hash.addString(image.getFormat());
|
||||
hash.addString(image.getColorMode().name());
|
||||
hash.addInt(image.getWidth());
|
||||
hash.addInt(image.getHeight());
|
||||
hash.addInt(image.getColorComponentCount());
|
||||
hash.addInt(image.getChannelCount());
|
||||
hash.addInt(image.getBitDepth());
|
||||
hash.addBoolean(image.hasAlpha());
|
||||
double minimumAlpha = 1D;
|
||||
double maximumAlpha = image.hasAlpha() ? 0D : 1D;
|
||||
for (int sourceZ = 0; sourceZ < image.getHeight(); sourceZ++) {
|
||||
for (int sourceX = 0; sourceX < image.getWidth(); sourceX++) {
|
||||
double alpha = image.getAlphaNormalized(sourceX, sourceZ);
|
||||
minimumAlpha = Math.min(minimumAlpha, alpha);
|
||||
maximumAlpha = Math.max(maximumAlpha, alpha);
|
||||
for (int band = 0; band < image.getChannelCount(); band++) {
|
||||
hash.addInt(image.getBandSample(sourceX, sourceZ, band));
|
||||
}
|
||||
}
|
||||
}
|
||||
return new SourceDigest(hash.finish(), minimumAlpha, maximumAlpha);
|
||||
}
|
||||
|
||||
private static String hashContent(IrisImageMap definition, IrisImageMapSourceMetadata metadata) {
|
||||
HashAccumulator hash = new HashAccumulator();
|
||||
hash.addString(metadata.decodedContentHash());
|
||||
hash.addString(definition.getSource());
|
||||
hash.addString(definition.getType().name());
|
||||
hash.addDouble(definition.getBlocksPerPixel());
|
||||
hash.addDouble(definition.getOrigin().getX());
|
||||
hash.addDouble(definition.getOrigin().getZ());
|
||||
hash.addDouble(definition.getSourceOrigin().getX());
|
||||
hash.addDouble(definition.getSourceOrigin().getZ());
|
||||
hash.addString(definition.getRotation().name());
|
||||
hash.addBoolean(definition.isMirrorX());
|
||||
hash.addBoolean(definition.isMirrorZ());
|
||||
hash.addString(definition.getSampling().name());
|
||||
hash.addString(definition.getOutOfBounds().name());
|
||||
hash.addDouble(definition.getFallbackValue());
|
||||
hash.addString(definition.getFallbackTarget());
|
||||
hash.addString(definition.getAlpha().name());
|
||||
hash.addDouble(definition.getMinimumHeight());
|
||||
hash.addDouble(definition.getMaximumHeight());
|
||||
hash.addDouble(definition.getVerticalOffset());
|
||||
hash.addBoolean(definition.isClamp());
|
||||
hash.addBoolean(definition.isInverted());
|
||||
hash.addDouble(definition.getCurveExponent());
|
||||
hash.addInt(definition.getSmoothingRadius());
|
||||
hash.addDouble(definition.getThreshold());
|
||||
hash.addDouble(definition.getFalloff());
|
||||
hash.addDouble(definition.getColorTolerance());
|
||||
hash.addString(definition.getUnknownColor().name());
|
||||
|
||||
KMap<String, String> configuredColors = definition.getColors();
|
||||
List<Map.Entry<String, String>> colors = configuredColors == null
|
||||
? new ArrayList<>()
|
||||
: new ArrayList<>(configuredColors.entrySet());
|
||||
colors.sort(Map.Entry.comparingByKey(String.CASE_INSENSITIVE_ORDER));
|
||||
hash.addInt(colors.size());
|
||||
for (Map.Entry<String, String> entry : colors) {
|
||||
hash.addString(entry.getKey().toUpperCase());
|
||||
hash.addString(entry.getValue());
|
||||
}
|
||||
return hash.finish();
|
||||
}
|
||||
|
||||
private static CompiledIrisImageMap.SourceTransform compileSourceTransform(IrisImageMap definition) {
|
||||
double sourceXFromWorldX;
|
||||
double sourceXFromWorldZ;
|
||||
double sourceZFromWorldX;
|
||||
double sourceZFromWorldZ;
|
||||
switch (definition.getRotation()) {
|
||||
case DEG_0 -> {
|
||||
sourceXFromWorldX = 1D;
|
||||
sourceXFromWorldZ = 0D;
|
||||
sourceZFromWorldX = 0D;
|
||||
sourceZFromWorldZ = 1D;
|
||||
}
|
||||
case DEG_90 -> {
|
||||
sourceXFromWorldX = 0D;
|
||||
sourceXFromWorldZ = 1D;
|
||||
sourceZFromWorldX = -1D;
|
||||
sourceZFromWorldZ = 0D;
|
||||
}
|
||||
case DEG_180 -> {
|
||||
sourceXFromWorldX = -1D;
|
||||
sourceXFromWorldZ = 0D;
|
||||
sourceZFromWorldX = 0D;
|
||||
sourceZFromWorldZ = -1D;
|
||||
}
|
||||
case DEG_270 -> {
|
||||
sourceXFromWorldX = 0D;
|
||||
sourceXFromWorldZ = -1D;
|
||||
sourceZFromWorldX = 1D;
|
||||
sourceZFromWorldZ = 0D;
|
||||
}
|
||||
default -> throw new IrisImageMapValidationException(
|
||||
"Unsupported image-map rotation " + definition.getRotation()
|
||||
);
|
||||
}
|
||||
if (definition.isMirrorX()) {
|
||||
sourceXFromWorldX = -sourceXFromWorldX;
|
||||
sourceXFromWorldZ = -sourceXFromWorldZ;
|
||||
}
|
||||
if (definition.isMirrorZ()) {
|
||||
sourceZFromWorldX = -sourceZFromWorldX;
|
||||
sourceZFromWorldZ = -sourceZFromWorldZ;
|
||||
}
|
||||
double inverseScale = 1D / definition.getBlocksPerPixel();
|
||||
sourceXFromWorldX *= inverseScale;
|
||||
sourceXFromWorldZ *= inverseScale;
|
||||
sourceZFromWorldX *= inverseScale;
|
||||
sourceZFromWorldZ *= inverseScale;
|
||||
double sourceXOffset = definition.getSourceOrigin().getX()
|
||||
- (sourceXFromWorldX * definition.getOrigin().getX())
|
||||
- (sourceXFromWorldZ * definition.getOrigin().getZ());
|
||||
double sourceZOffset = definition.getSourceOrigin().getZ()
|
||||
- (sourceZFromWorldX * definition.getOrigin().getX())
|
||||
- (sourceZFromWorldZ * definition.getOrigin().getZ());
|
||||
if (!Double.isFinite(sourceXFromWorldX)
|
||||
|| !Double.isFinite(sourceXFromWorldZ)
|
||||
|| !Double.isFinite(sourceXOffset)
|
||||
|| !Double.isFinite(sourceZFromWorldX)
|
||||
|| !Double.isFinite(sourceZFromWorldZ)
|
||||
|| !Double.isFinite(sourceZOffset)) {
|
||||
throw new IrisImageMapValidationException("Image-map coordinate transform must remain finite");
|
||||
}
|
||||
return new CompiledIrisImageMap.SourceTransform(
|
||||
sourceXFromWorldX,
|
||||
sourceXFromWorldZ,
|
||||
sourceXOffset,
|
||||
sourceZFromWorldX,
|
||||
sourceZFromWorldZ,
|
||||
sourceZOffset
|
||||
);
|
||||
}
|
||||
|
||||
private static IrisImageMap snapshot(IrisImageMap definition) {
|
||||
KMap<String, String> configuredColors = definition.getColors();
|
||||
KMap<String, String> colors = configuredColors == null ? new KMap<>() : new KMap<>(configuredColors);
|
||||
return new IrisImageMap()
|
||||
.setSource(definition.getSource())
|
||||
.setType(definition.getType())
|
||||
.setBlocksPerPixel(definition.getBlocksPerPixel())
|
||||
.setOrigin(new IrisImageMapOrigin(definition.getOrigin().getX(), definition.getOrigin().getZ()))
|
||||
.setSourceOrigin(new IrisImageMapOrigin(
|
||||
definition.getSourceOrigin().getX(),
|
||||
definition.getSourceOrigin().getZ()
|
||||
))
|
||||
.setRotation(definition.getRotation())
|
||||
.setMirrorX(definition.isMirrorX())
|
||||
.setMirrorZ(definition.isMirrorZ())
|
||||
.setSampling(definition.getSampling())
|
||||
.setOutOfBounds(definition.getOutOfBounds())
|
||||
.setFallbackValue(definition.getFallbackValue())
|
||||
.setFallbackTarget(definition.getFallbackTarget())
|
||||
.setAlpha(definition.getAlpha())
|
||||
.setMinimumHeight(definition.getMinimumHeight())
|
||||
.setMaximumHeight(definition.getMaximumHeight())
|
||||
.setVerticalOffset(definition.getVerticalOffset())
|
||||
.setClamp(definition.isClamp())
|
||||
.setInverted(definition.isInverted())
|
||||
.setCurveExponent(definition.getCurveExponent())
|
||||
.setSmoothingRadius(definition.getSmoothingRadius())
|
||||
.setThreshold(definition.getThreshold())
|
||||
.setFalloff(definition.getFalloff())
|
||||
.setColorTolerance(definition.getColorTolerance())
|
||||
.setUnknownColor(definition.getUnknownColor())
|
||||
.setColors(colors);
|
||||
}
|
||||
|
||||
private static double colorDistanceSquared(int first, int second) {
|
||||
int red = ((first >>> 16) & 0xFF) - ((second >>> 16) & 0xFF);
|
||||
int green = ((first >>> 8) & 0xFF) - ((second >>> 8) & 0xFF);
|
||||
int blue = (first & 0xFF) - (second & 0xFF);
|
||||
return (red * red) + (green * green) + (blue * blue);
|
||||
}
|
||||
|
||||
private static String encodeColor(int rgb) {
|
||||
return String.format(Locale.ROOT, "#%06X", rgb & 0xFFFFFF);
|
||||
}
|
||||
|
||||
private static boolean finiteAtLeast(double value, double minimum) {
|
||||
return Double.isFinite(value) && value >= minimum;
|
||||
}
|
||||
|
||||
private static boolean range(double value, double minimum, double maximum) {
|
||||
return Double.isFinite(value) && value >= minimum && value <= maximum;
|
||||
}
|
||||
|
||||
private static double clamp01(double value) {
|
||||
return Math.max(0D, Math.min(1D, value));
|
||||
}
|
||||
|
||||
private record MutableLegendEntry(int rgb, String encoded, String target) {
|
||||
}
|
||||
|
||||
private record LegendEntry(int rgb, String encoded, String target, int targetIndex) {
|
||||
}
|
||||
|
||||
private record Legend(
|
||||
List<LegendEntry> entries,
|
||||
Map<Integer, LegendEntry> exact,
|
||||
String[] targets,
|
||||
int fallbackIndex
|
||||
) {
|
||||
}
|
||||
|
||||
private record CompiledTargets(
|
||||
CompiledIrisImageMap.IntTiles indices,
|
||||
String[] targets,
|
||||
int unknownColorPixelCount
|
||||
) {
|
||||
}
|
||||
|
||||
private record TargetMatch(int targetIndex, boolean unknown) {
|
||||
}
|
||||
|
||||
private record SourceDigest(String hash, double minimumAlpha, double maximumAlpha) {
|
||||
}
|
||||
|
||||
private static final class HashAccumulator {
|
||||
private final MessageDigest digest;
|
||||
|
||||
private HashAccumulator() {
|
||||
try {
|
||||
digest = MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException exception) {
|
||||
throw new IllegalStateException("SHA-256 is unavailable", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private void addBoolean(boolean value) {
|
||||
digest.update((byte) (value ? 1 : 0));
|
||||
}
|
||||
|
||||
private void addInt(int value) {
|
||||
digest.update((byte) (value >>> 24));
|
||||
digest.update((byte) (value >>> 16));
|
||||
digest.update((byte) (value >>> 8));
|
||||
digest.update((byte) value);
|
||||
}
|
||||
|
||||
private void addLong(long value) {
|
||||
digest.update((byte) (value >>> 56));
|
||||
digest.update((byte) (value >>> 48));
|
||||
digest.update((byte) (value >>> 40));
|
||||
digest.update((byte) (value >>> 32));
|
||||
digest.update((byte) (value >>> 24));
|
||||
digest.update((byte) (value >>> 16));
|
||||
digest.update((byte) (value >>> 8));
|
||||
digest.update((byte) value);
|
||||
}
|
||||
|
||||
private void addDouble(double value) {
|
||||
addLong(Double.doubleToLongBits(value));
|
||||
}
|
||||
|
||||
private void addString(String value) {
|
||||
if (value == null) {
|
||||
addInt(-1);
|
||||
return;
|
||||
}
|
||||
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
|
||||
addInt(bytes.length);
|
||||
digest.update(bytes);
|
||||
}
|
||||
|
||||
private String finish() {
|
||||
return HexFormat.of().formatHex(digest.digest());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
package art.arcane.iris.engine.image;
|
||||
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapMask;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapMaskOperation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class IrisImageMapMaskSampler {
|
||||
private static final IrisImageMapMaskSampler EMPTY = new IrisImageMapMaskSampler(List.of());
|
||||
|
||||
private final List<Layer> layers;
|
||||
|
||||
public IrisImageMapMaskSampler(List<Layer> layers) {
|
||||
this.layers = List.copyOf(Objects.requireNonNull(layers, "Image-map mask layers"));
|
||||
}
|
||||
|
||||
public static IrisImageMapMaskSampler empty() {
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
public static Layer layer(CompiledIrisImageMap compiled, IrisImageMapMask definition) {
|
||||
Objects.requireNonNull(definition, "Image-map mask definition");
|
||||
if (definition.getOperation() == null) {
|
||||
throw new IrisImageMapValidationException("Image-map mask operation is required");
|
||||
}
|
||||
if (!unitRange(definition.getThreshold()) || !unitRange(definition.getFalloff())) {
|
||||
throw new IrisImageMapValidationException("Image-map mask threshold and falloff must be within 0..1");
|
||||
}
|
||||
return new Layer(
|
||||
Objects.requireNonNull(compiled, "Compiled image-map mask"),
|
||||
definition.getOperation(),
|
||||
definition.isInverted(),
|
||||
definition.getThreshold(),
|
||||
definition.getFalloff()
|
||||
);
|
||||
}
|
||||
|
||||
public static IrisImageMapMaskSampler of(
|
||||
List<CompiledIrisImageMap> compiled,
|
||||
List<IrisImageMapMask> definitions
|
||||
) {
|
||||
if (compiled.size() != definitions.size()) {
|
||||
throw new IllegalArgumentException("Compiled image-map masks and definitions must have equal sizes");
|
||||
}
|
||||
List<Layer> layers = new ArrayList<>(compiled.size());
|
||||
for (int index = 0; index < compiled.size(); index++) {
|
||||
layers.add(layer(compiled.get(index), definitions.get(index)));
|
||||
}
|
||||
return layers.isEmpty() ? empty() : new IrisImageMapMaskSampler(layers);
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return layers.isEmpty();
|
||||
}
|
||||
|
||||
public double sample(double worldX, double worldZ) {
|
||||
double weight = 1D;
|
||||
for (Layer layer : layers) {
|
||||
double value = layer.sample(worldX, worldZ);
|
||||
weight = switch (layer.operation()) {
|
||||
case MULTIPLY -> weight * value;
|
||||
case MINIMUM -> Math.min(weight, value);
|
||||
case MAXIMUM -> Math.max(weight, value);
|
||||
case ADD -> weight + value;
|
||||
case SUBTRACT -> weight - value;
|
||||
};
|
||||
weight = clamp01(weight);
|
||||
}
|
||||
return weight;
|
||||
}
|
||||
|
||||
private static boolean unitRange(double value) {
|
||||
return Double.isFinite(value) && value >= 0D && value <= 1D;
|
||||
}
|
||||
|
||||
private static double clamp01(double value) {
|
||||
return Math.max(0D, Math.min(1D, value));
|
||||
}
|
||||
|
||||
public record Layer(
|
||||
CompiledIrisImageMap compiled,
|
||||
IrisImageMapMaskOperation operation,
|
||||
boolean inverted,
|
||||
double threshold,
|
||||
double falloff
|
||||
) {
|
||||
public Layer {
|
||||
Objects.requireNonNull(compiled, "Compiled image-map mask");
|
||||
Objects.requireNonNull(operation, "Image-map mask operation");
|
||||
if (!unitRange(threshold) || !unitRange(falloff)) {
|
||||
throw new IrisImageMapValidationException(
|
||||
"Image-map mask threshold and falloff must be within 0..1"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private double sample(double worldX, double worldZ) {
|
||||
double value = compiled.sampleNormalized(worldX, worldZ);
|
||||
if (inverted) {
|
||||
value = 1D - value;
|
||||
}
|
||||
if (threshold == 0D && falloff == 0D) {
|
||||
return value;
|
||||
}
|
||||
if (falloff == 0D) {
|
||||
return value >= threshold ? 1D : 0D;
|
||||
}
|
||||
return clamp01((value - threshold) / falloff);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,386 +0,0 @@
|
||||
package art.arcane.iris.engine.image;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.object.image.IrisImage;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMap;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapApplication;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapBinding;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapMask;
|
||||
import art.arcane.iris.engine.object.image.IrisImageMapType;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.iris.engine.object.world.biome.InferredType;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.iris.util.common.data.B;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
public final class IrisImageMapRuntime {
|
||||
private final int minimumWorldHeight;
|
||||
private final Map<String, RuntimeBinding> bindings;
|
||||
private final Map<IrisImageMapApplication, RuntimeBinding> applications;
|
||||
private final Set<IrisRegion> mappedRegions;
|
||||
private final Set<IrisBiome> mappedBiomes;
|
||||
|
||||
private IrisImageMapRuntime(
|
||||
int minimumWorldHeight,
|
||||
Map<String, RuntimeBinding> bindings,
|
||||
Map<IrisImageMapApplication, RuntimeBinding> applications,
|
||||
Set<IrisRegion> mappedRegions,
|
||||
Set<IrisBiome> mappedBiomes
|
||||
) {
|
||||
this.minimumWorldHeight = minimumWorldHeight;
|
||||
this.bindings = Map.copyOf(bindings);
|
||||
this.applications = Map.copyOf(applications);
|
||||
this.mappedRegions = Set.copyOf(mappedRegions);
|
||||
this.mappedBiomes = Set.copyOf(mappedBiomes);
|
||||
}
|
||||
|
||||
public static IrisImageMapRuntime compile(Engine engine) {
|
||||
Objects.requireNonNull(engine, "Image-map runtime requires an engine");
|
||||
return compile(engine.getData(), engine.getDimension(), engine.getMinHeight());
|
||||
}
|
||||
|
||||
public static IrisImageMapRuntime compile(IrisData data, IrisDimension dimension, int minimumWorldHeight) {
|
||||
Objects.requireNonNull(data, "Image-map runtime requires Iris data");
|
||||
Objects.requireNonNull(dimension, "Image-map runtime requires a dimension");
|
||||
Map<String, RuntimeBinding> bindings = new LinkedHashMap<>();
|
||||
Map<IrisImageMapApplication, RuntimeBinding> applications = new EnumMap<>(IrisImageMapApplication.class);
|
||||
Set<IrisRegion> mappedRegions = new LinkedHashSet<>();
|
||||
Set<IrisBiome> mappedBiomes = new LinkedHashSet<>();
|
||||
|
||||
for (IrisImageMapBinding binding : dimension.getImageMaps()) {
|
||||
RuntimeBinding runtimeBinding = compileBinding(binding, data, dimension, mappedRegions, mappedBiomes);
|
||||
RuntimeBinding duplicate = bindings.putIfAbsent(runtimeBinding.key, runtimeBinding);
|
||||
if (duplicate != null) {
|
||||
throw validation("Duplicate dimension image-map key '" + runtimeBinding.key + "'");
|
||||
}
|
||||
IrisImageMapApplication application = runtimeBinding.application;
|
||||
if (application != IrisImageMapApplication.MASK && application != IrisImageMapApplication.CUSTOM) {
|
||||
RuntimeBinding applicationDuplicate = applications.putIfAbsent(application, runtimeBinding);
|
||||
if (applicationDuplicate != null) {
|
||||
throw validation("Dimension declares more than one " + application + " image-map binding");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (RuntimeBinding binding : bindings.values()) {
|
||||
binding.masks = resolveMasks(binding, bindings);
|
||||
}
|
||||
|
||||
return new IrisImageMapRuntime(
|
||||
minimumWorldHeight, bindings, applications, mappedRegions, mappedBiomes
|
||||
);
|
||||
}
|
||||
|
||||
public boolean has(IrisImageMapApplication application) {
|
||||
return applications.containsKey(application);
|
||||
}
|
||||
|
||||
public Set<IrisRegion> getMappedRegions() {
|
||||
return mappedRegions;
|
||||
}
|
||||
|
||||
public Set<IrisBiome> getMappedBiomes() {
|
||||
return mappedBiomes;
|
||||
}
|
||||
|
||||
public double sampleTerrainHeight(double worldX, double worldZ, double proceduralLocalHeight) {
|
||||
RuntimeBinding binding = applications.get(IrisImageMapApplication.TERRAIN_HEIGHT);
|
||||
if (binding == null) {
|
||||
return proceduralLocalHeight;
|
||||
}
|
||||
double mappedLocalHeight = binding.compiled.sampleHeight(worldX, worldZ) - minimumWorldHeight;
|
||||
double weight = binding.maskWeight(worldX, worldZ);
|
||||
return blendTerrainHeight(mappedLocalHeight, proceduralLocalHeight, weight);
|
||||
}
|
||||
|
||||
public IrisRegion sampleRegion(double worldX, double worldZ) {
|
||||
RuntimeBinding binding = applications.get(IrisImageMapApplication.REGION);
|
||||
if (binding == null || !selectCategorical(binding.maskWeight(worldX, worldZ))) {
|
||||
return null;
|
||||
}
|
||||
String target = binding.compiled.sampleTarget(worldX, worldZ);
|
||||
return target == null ? null : binding.regions.get(target);
|
||||
}
|
||||
|
||||
public IrisBiome sampleBiome(double worldX, double worldZ) {
|
||||
RuntimeBinding binding = applications.get(IrisImageMapApplication.BIOME);
|
||||
if (binding == null || !selectCategorical(binding.maskWeight(worldX, worldZ))) {
|
||||
return null;
|
||||
}
|
||||
String target = binding.compiled.sampleTarget(worldX, worldZ);
|
||||
return target == null ? null : binding.biomes.get(target);
|
||||
}
|
||||
|
||||
public PlatformBlockState sampleSurfaceBlock(double worldX, double worldZ) {
|
||||
RuntimeBinding binding = applications.get(IrisImageMapApplication.SURFACE_BLOCK);
|
||||
if (binding == null || !selectCategorical(binding.maskWeight(worldX, worldZ))) {
|
||||
return null;
|
||||
}
|
||||
String target = binding.compiled.sampleTarget(worldX, worldZ);
|
||||
return target == null ? null : binding.blocks.get(target);
|
||||
}
|
||||
|
||||
public CompiledIrisImageMap getCompiled(String key) {
|
||||
RuntimeBinding binding = bindings.get(key);
|
||||
return binding == null ? null : binding.compiled;
|
||||
}
|
||||
|
||||
public static double blendTerrainHeight(double mappedLocalHeight, double proceduralLocalHeight, double weight) {
|
||||
return proceduralLocalHeight + ((mappedLocalHeight - proceduralLocalHeight) * weight);
|
||||
}
|
||||
|
||||
public static boolean selectCategorical(double weight) {
|
||||
return weight >= 0.5D;
|
||||
}
|
||||
|
||||
private static RuntimeBinding compileBinding(
|
||||
IrisImageMapBinding binding,
|
||||
IrisData data,
|
||||
IrisDimension dimension,
|
||||
Set<IrisRegion> mappedRegions,
|
||||
Set<IrisBiome> mappedBiomes
|
||||
) {
|
||||
if (binding == null) {
|
||||
throw validation("Dimension imageMaps contains a null binding");
|
||||
}
|
||||
String key = requireText(binding.getKey(), "Dimension image-map key");
|
||||
String mapKey = requireText(binding.getMap(), "Dimension image-map resource for '" + key + "'");
|
||||
IrisImageMapApplication application = binding.getApplication();
|
||||
if (application == null) {
|
||||
throw validation("Dimension image-map '" + key + "' requires an application");
|
||||
}
|
||||
IrisImageMap definition = data.getImageMapLoader().load(mapKey);
|
||||
if (definition == null) {
|
||||
throw validation("Dimension image-map '" + key + "' references missing image-map resource '" + mapKey + "'");
|
||||
}
|
||||
String source = requireText(definition.getSource(), "Image-map resource '" + mapKey + "' source");
|
||||
IrisImage image = data.getImageLoader().load(source);
|
||||
if (image == null) {
|
||||
throw validation("Image-map resource '" + mapKey + "' references missing or invalid PNG '" + source + "'");
|
||||
}
|
||||
CompiledIrisImageMap compiled;
|
||||
try {
|
||||
validateApplication(key, application, definition.getType(), binding.getMasks());
|
||||
compiled = CompiledIrisImageMap.compile(definition, image);
|
||||
} finally {
|
||||
data.getImageLoader().unload(source);
|
||||
}
|
||||
Map<String, IrisRegion> regions = new LinkedHashMap<>();
|
||||
Map<String, IrisBiome> biomes = new LinkedHashMap<>();
|
||||
Map<String, PlatformBlockState> blocks = new LinkedHashMap<>();
|
||||
Set<String> targets = legendTargets(definition);
|
||||
|
||||
if (application == IrisImageMapApplication.REGION) {
|
||||
for (String target : targets) {
|
||||
IrisRegion region = data.getRegionLoader().load(localResourceKey(target));
|
||||
if (region == null) {
|
||||
throw validation("Image-map '" + key + "' references missing region target '" + target + "'");
|
||||
}
|
||||
regions.put(target, region);
|
||||
mappedRegions.add(region);
|
||||
}
|
||||
} else if (application == IrisImageMapApplication.BIOME) {
|
||||
for (String target : targets) {
|
||||
String localTarget = localResourceKey(target);
|
||||
IrisBiome biome = data.getBiomeLoader().load(localTarget);
|
||||
if (biome == null) {
|
||||
throw validation("Image-map '" + key + "' references missing biome target '" + target + "'");
|
||||
}
|
||||
IrisBiome typedBiome = biome.withInferredType(resolveBiomeType(localTarget, dimension, data));
|
||||
biomes.put(target, typedBiome);
|
||||
mappedBiomes.add(typedBiome);
|
||||
}
|
||||
} else if (application == IrisImageMapApplication.SURFACE_BLOCK) {
|
||||
for (String target : targets) {
|
||||
PlatformBlockState block = B.getStateOrNull(target, false);
|
||||
if (block == null) {
|
||||
throw validation("Image-map '" + key + "' references unknown surface block target '" + target + "'");
|
||||
}
|
||||
blocks.put(target, block);
|
||||
}
|
||||
}
|
||||
|
||||
return new RuntimeBinding(
|
||||
key,
|
||||
application,
|
||||
compiled,
|
||||
Map.copyOf(regions),
|
||||
Map.copyOf(biomes),
|
||||
Map.copyOf(blocks),
|
||||
binding.getMasks() == null ? List.of() : List.copyOf(binding.getMasks())
|
||||
);
|
||||
}
|
||||
|
||||
private static void validateApplication(
|
||||
String key,
|
||||
IrisImageMapApplication application,
|
||||
IrisImageMapType type,
|
||||
List<IrisImageMapMask> masks
|
||||
) {
|
||||
if (type == null) {
|
||||
throw validation("Image-map '" + key + "' requires a type");
|
||||
}
|
||||
boolean valid = switch (application) {
|
||||
case TERRAIN_HEIGHT -> type == IrisImageMapType.GRAYSCALE_HEIGHT
|
||||
|| type == IrisImageMapType.RGB_HEIGHT;
|
||||
case BIOME, REGION, SURFACE_BLOCK -> type == IrisImageMapType.COLOR_MAP;
|
||||
case MASK -> isMaskType(type);
|
||||
case CUSTOM -> true;
|
||||
};
|
||||
if (!valid) {
|
||||
throw validation("Image-map '" + key + "' type " + type + " is incompatible with " + application);
|
||||
}
|
||||
if (application == IrisImageMapApplication.MASK && masks != null && !masks.isEmpty()) {
|
||||
throw validation("MASK image-map '" + key + "' cannot reference additional masks");
|
||||
}
|
||||
}
|
||||
|
||||
private static IrisImageMapMaskSampler resolveMasks(
|
||||
RuntimeBinding binding,
|
||||
Map<String, RuntimeBinding> bindings
|
||||
) {
|
||||
if (binding.maskDefinitions.isEmpty()) {
|
||||
return IrisImageMapMaskSampler.empty();
|
||||
}
|
||||
List<IrisImageMapMaskSampler.Layer> masks = new ArrayList<>(binding.maskDefinitions.size());
|
||||
for (IrisImageMapMask mask : binding.maskDefinitions) {
|
||||
if (mask == null) {
|
||||
throw validation("Image-map '" + binding.key + "' contains a null mask reference");
|
||||
}
|
||||
String maskKey = requireText(mask.getMap(), "Mask reference on image-map '" + binding.key + "'");
|
||||
RuntimeBinding maskBinding = bindings.get(maskKey);
|
||||
if (maskBinding == null) {
|
||||
throw validation("Image-map '" + binding.key + "' references missing MASK binding '" + maskKey + "'");
|
||||
}
|
||||
if (maskBinding.application != IrisImageMapApplication.MASK) {
|
||||
throw validation("Image-map '" + binding.key + "' references '" + maskKey + "', which is not a MASK binding");
|
||||
}
|
||||
if (mask.getOperation() == null) {
|
||||
throw validation("Mask '" + maskKey + "' on image-map '" + binding.key + "' requires an operation");
|
||||
}
|
||||
if (!range(mask.getThreshold()) || !range(mask.getFalloff())) {
|
||||
throw validation("Mask '" + maskKey + "' threshold and falloff must be finite values within 0..1");
|
||||
}
|
||||
masks.add(IrisImageMapMaskSampler.layer(maskBinding.compiled, mask));
|
||||
}
|
||||
return new IrisImageMapMaskSampler(masks);
|
||||
}
|
||||
|
||||
private static Set<String> legendTargets(IrisImageMap definition) {
|
||||
Set<String> targets = new LinkedHashSet<>();
|
||||
if (definition.getColors() != null) {
|
||||
for (String target : definition.getColors().values()) {
|
||||
if (target != null && !target.isBlank()) {
|
||||
targets.add(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
String fallback = definition.getFallbackTarget();
|
||||
if (fallback != null && !fallback.isBlank()) {
|
||||
targets.add(fallback);
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
private static InferredType resolveBiomeType(String biomeKey, IrisDimension dimension, IrisData data) {
|
||||
Set<InferredType> types = new LinkedHashSet<>();
|
||||
for (IrisRegion region : dimension.getAllRegions(() -> data)) {
|
||||
if (region == null) {
|
||||
continue;
|
||||
}
|
||||
if (region.getLandBiomes().contains(biomeKey)) {
|
||||
types.add(InferredType.LAND);
|
||||
}
|
||||
if (region.getSeaBiomes().contains(biomeKey)) {
|
||||
types.add(InferredType.SEA);
|
||||
}
|
||||
if (region.getShoreBiomes().contains(biomeKey)) {
|
||||
types.add(InferredType.SHORE);
|
||||
}
|
||||
}
|
||||
if (types.size() != 1) {
|
||||
throw validation("Image-mapped biome '" + biomeKey
|
||||
+ "' must occur in exactly one landBiomes, seaBiomes, or shoreBiomes role across the dimension; found "
|
||||
+ types);
|
||||
}
|
||||
return types.iterator().next();
|
||||
}
|
||||
|
||||
private static String localResourceKey(String target) {
|
||||
String normalized = requireText(target, "Image-map Iris resource target");
|
||||
int separator = normalized.indexOf(':');
|
||||
if (separator < 0) {
|
||||
return normalized;
|
||||
}
|
||||
if (!normalized.startsWith("iris:") || separator == normalized.length() - 1) {
|
||||
throw validation("Iris biome and region targets must be bare pack keys or use the iris: namespace, got '"
|
||||
+ target + "'");
|
||||
}
|
||||
return normalized.substring(separator + 1);
|
||||
}
|
||||
|
||||
private static String requireText(String value, String name) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw validation(name + " must not be blank");
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
private static boolean range(double value) {
|
||||
return Double.isFinite(value) && value >= 0D && value <= 1D;
|
||||
}
|
||||
|
||||
private static boolean isMaskType(IrisImageMapType type) {
|
||||
return type == IrisImageMapType.BINARY_MASK
|
||||
|| type == IrisImageMapType.GRAYSCALE_MASK
|
||||
|| type == IrisImageMapType.ALPHA_MASK;
|
||||
}
|
||||
|
||||
private static IrisImageMapValidationException validation(String message) {
|
||||
return new IrisImageMapValidationException(message);
|
||||
}
|
||||
|
||||
private static final class RuntimeBinding {
|
||||
private final String key;
|
||||
private final IrisImageMapApplication application;
|
||||
private final CompiledIrisImageMap compiled;
|
||||
private final Map<String, IrisRegion> regions;
|
||||
private final Map<String, IrisBiome> biomes;
|
||||
private final Map<String, PlatformBlockState> blocks;
|
||||
private final List<IrisImageMapMask> maskDefinitions;
|
||||
private IrisImageMapMaskSampler masks = IrisImageMapMaskSampler.empty();
|
||||
|
||||
private RuntimeBinding(
|
||||
String key,
|
||||
IrisImageMapApplication application,
|
||||
CompiledIrisImageMap compiled,
|
||||
Map<String, IrisRegion> regions,
|
||||
Map<String, IrisBiome> biomes,
|
||||
Map<String, PlatformBlockState> blocks,
|
||||
List<IrisImageMapMask> maskDefinitions
|
||||
) {
|
||||
this.key = key;
|
||||
this.application = application;
|
||||
this.compiled = compiled;
|
||||
this.regions = regions;
|
||||
this.biomes = biomes;
|
||||
this.blocks = blocks;
|
||||
this.maskDefinitions = maskDefinitions;
|
||||
}
|
||||
|
||||
private double maskWeight(double worldX, double worldZ) {
|
||||
return masks.sample(worldX, worldZ);
|
||||
}
|
||||
}
|
||||
}
|
||||
-286
@@ -1,286 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.mantle.components;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.volmlib.util.cache.CacheKey;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.placement.IObjectPlacer;
|
||||
import art.arcane.iris.engine.object.prefab.TileData;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.iris.util.common.data.B;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public final class CaveObjectPlacementTransaction implements IObjectPlacer {
|
||||
private static final int CACHE_MISS = Integer.MIN_VALUE;
|
||||
|
||||
private final IObjectPlacer delegate;
|
||||
private final Engine engine;
|
||||
private final int anchorY;
|
||||
private final int minDepthBelowSurface;
|
||||
private final int worldHeight;
|
||||
private final KList<BufferedMutation> mutations;
|
||||
private final Map<PositionKey, PlatformBlockState> bufferedBlocks;
|
||||
private final Long2IntOpenHashMap surfaceHeights;
|
||||
private final Long2IntOpenHashMap caveCeilings;
|
||||
private int blockWrites;
|
||||
|
||||
public CaveObjectPlacementTransaction(IObjectPlacer delegate, int anchorY, int minDepthBelowSurface) {
|
||||
this.delegate = delegate;
|
||||
this.engine = delegate.getEngine();
|
||||
this.anchorY = anchorY;
|
||||
this.minDepthBelowSurface = Math.max(0, minDepthBelowSurface);
|
||||
this.worldHeight = engine == null ? 0 : engine.getHeight();
|
||||
this.mutations = new KList<>();
|
||||
this.bufferedBlocks = new HashMap<>();
|
||||
this.surfaceHeights = new Long2IntOpenHashMap();
|
||||
this.caveCeilings = new Long2IntOpenHashMap();
|
||||
this.surfaceHeights.defaultReturnValue(CACHE_MISS);
|
||||
this.caveCeilings.defaultReturnValue(CACHE_MISS);
|
||||
}
|
||||
|
||||
public CommitResult commit() {
|
||||
if (blockWrites == 0) {
|
||||
discard();
|
||||
return CommitResult.EMPTY;
|
||||
}
|
||||
|
||||
for (BufferedMutation mutation : mutations) {
|
||||
if (!isWithinBounds(mutation.x(), mutation.y(), mutation.z())) {
|
||||
discard();
|
||||
return CommitResult.REJECTED_BOUNDS;
|
||||
}
|
||||
}
|
||||
|
||||
for (BufferedMutation mutation : mutations) {
|
||||
mutation.apply(delegate);
|
||||
}
|
||||
discard();
|
||||
return CommitResult.COMMITTED;
|
||||
}
|
||||
|
||||
public void discard() {
|
||||
mutations.clear();
|
||||
bufferedBlocks.clear();
|
||||
blockWrites = 0;
|
||||
}
|
||||
|
||||
public int getCaveCeiling(int x, int z) {
|
||||
long key = CacheKey.key(x, z);
|
||||
int cached = caveCeilings.get(key);
|
||||
if (cached != CACHE_MISS) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
int ceiling = findCaveCeiling(x, z);
|
||||
caveCeilings.put(key, ceiling);
|
||||
return ceiling;
|
||||
}
|
||||
|
||||
static int maxBuriedY(int worldHeight, int surfaceY, int minDepthBelowSurface) {
|
||||
return Math.min(worldHeight - 1, surfaceY - Math.max(0, minDepthBelowSurface));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHighest(int x, int z, IrisData data) {
|
||||
return delegate.getHighest(x, z, data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) {
|
||||
return delegate.getHighest(x, z, data, ignoreFluid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(int x, int y, int z, PlatformBlockState state) {
|
||||
if (state == null) {
|
||||
return;
|
||||
}
|
||||
mutations.add(new BlockMutation(x, y, z, state));
|
||||
bufferedBlocks.put(new PositionKey(x, y, z), state);
|
||||
blockWrites++;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformBlockState get(int x, int y, int z) {
|
||||
PlatformBlockState buffered = bufferedBlocks.get(new PositionKey(x, y, z));
|
||||
return buffered == null ? delegate.get(x, y, z) : buffered;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPreventingDecay() {
|
||||
return delegate.isPreventingDecay();
|
||||
}
|
||||
|
||||
@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 isSolid(int x, int y, int z) {
|
||||
PlatformBlockState buffered = bufferedBlocks.get(new PositionKey(x, y, z));
|
||||
return buffered == null ? delegate.isSolid(x, y, z) : B.isSolid(buffered);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUnderwater(int x, int z) {
|
||||
return delegate.isUnderwater(x, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getFluidHeight() {
|
||||
return delegate.getFluidHeight();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDebugSmartBore() {
|
||||
return delegate.isDebugSmartBore();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTile(int x, int y, int z, TileData tile) {
|
||||
if (tile != null) {
|
||||
mutations.add(new TileMutation(x, y, z, tile));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void setData(int x, int y, int z, T data) {
|
||||
if (data == null) {
|
||||
return;
|
||||
}
|
||||
mutations.add(new DataMutation(x, y, z, data));
|
||||
if (data instanceof PlatformBlockState state) {
|
||||
bufferedBlocks.put(new PositionKey(x, y, z), state);
|
||||
blockWrites++;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @Nullable T getData(int x, int y, int z, Class<T> type) {
|
||||
for (int i = mutations.size() - 1; i >= 0; i--) {
|
||||
BufferedMutation mutation = mutations.get(i);
|
||||
if (mutation.x() != x || mutation.y() != y || mutation.z() != z) {
|
||||
continue;
|
||||
}
|
||||
Object value = mutation.value();
|
||||
if (type.isInstance(value)) {
|
||||
return type.cast(value);
|
||||
}
|
||||
}
|
||||
return delegate.getData(x, y, z, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Engine getEngine() {
|
||||
return engine;
|
||||
}
|
||||
|
||||
private boolean isWithinBounds(int x, int y, int z) {
|
||||
if (engine == null || y < 0 || y >= worldHeight) {
|
||||
return false;
|
||||
}
|
||||
int surfaceY = getSurfaceHeight(x, z);
|
||||
if (y > maxBuriedY(worldHeight, surfaceY, minDepthBelowSurface)) {
|
||||
return false;
|
||||
}
|
||||
return y < getCaveCeiling(x, z);
|
||||
}
|
||||
|
||||
private int getSurfaceHeight(int x, int z) {
|
||||
long key = CacheKey.key(x, z);
|
||||
int cached = surfaceHeights.get(key);
|
||||
if (cached != CACHE_MISS) {
|
||||
return cached;
|
||||
}
|
||||
int surfaceY = engine.getHeight(x, z, true);
|
||||
surfaceHeights.put(key, surfaceY);
|
||||
return surfaceY;
|
||||
}
|
||||
|
||||
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, getSurfaceHeight(x, z)));
|
||||
for (int y = anchorY + 1; y <= scanLimit; y++) {
|
||||
if (!delegate.isCarved(x, y, z)) {
|
||||
return y;
|
||||
}
|
||||
}
|
||||
return Math.min(worldHeight, scanLimit + 1);
|
||||
}
|
||||
|
||||
public enum CommitResult {
|
||||
COMMITTED,
|
||||
EMPTY,
|
||||
REJECTED_BOUNDS
|
||||
}
|
||||
|
||||
private interface BufferedMutation {
|
||||
int x();
|
||||
|
||||
int y();
|
||||
|
||||
int z();
|
||||
|
||||
Object value();
|
||||
|
||||
void apply(IObjectPlacer placer);
|
||||
}
|
||||
|
||||
private record BlockMutation(int x, int y, int z, PlatformBlockState value) implements BufferedMutation {
|
||||
@Override
|
||||
public void apply(IObjectPlacer placer) {
|
||||
placer.set(x, y, z, value);
|
||||
}
|
||||
}
|
||||
|
||||
private record TileMutation(int x, int y, int z, TileData value) implements BufferedMutation {
|
||||
@Override
|
||||
public void apply(IObjectPlacer placer) {
|
||||
placer.setTile(x, y, z, value);
|
||||
}
|
||||
}
|
||||
|
||||
private record DataMutation(int x, int y, int z, Object value) implements BufferedMutation {
|
||||
@Override
|
||||
public void apply(IObjectPlacer placer) {
|
||||
placer.setData(x, y, z, value);
|
||||
}
|
||||
}
|
||||
|
||||
private record PositionKey(int x, int y, int z) {
|
||||
}
|
||||
}
|
||||
-211
@@ -1,211 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.mantle.components;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.placement.IObjectPlacer;
|
||||
import art.arcane.iris.engine.object.prefab.TileData;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.iris.util.common.data.B;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public final class FloatingObjectPlacementTransaction implements IObjectPlacer {
|
||||
private final IslandAnchorPlacer delegate;
|
||||
private final KList<BufferedMutation> mutations;
|
||||
private final Map<PositionKey, PlatformBlockState> bufferedBlocks;
|
||||
private int blockWrites;
|
||||
|
||||
public FloatingObjectPlacementTransaction(IslandAnchorPlacer delegate) {
|
||||
this.delegate = delegate;
|
||||
this.mutations = new KList<>();
|
||||
this.bufferedBlocks = new HashMap<>();
|
||||
}
|
||||
|
||||
public CommitResult commit() {
|
||||
if (blockWrites == 0) {
|
||||
discard();
|
||||
return CommitResult.EMPTY;
|
||||
}
|
||||
for (BufferedMutation mutation : mutations) {
|
||||
if (!delegate.canWriteObjectBlock(mutation.x(), mutation.y(), mutation.z())) {
|
||||
discard();
|
||||
return CommitResult.REJECTED_SUPPORT;
|
||||
}
|
||||
}
|
||||
for (BufferedMutation mutation : mutations) {
|
||||
mutation.apply(delegate);
|
||||
}
|
||||
discard();
|
||||
return CommitResult.COMMITTED;
|
||||
}
|
||||
|
||||
public void discard() {
|
||||
mutations.clear();
|
||||
bufferedBlocks.clear();
|
||||
blockWrites = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHighest(int x, int z, IrisData data) {
|
||||
return delegate.getHighest(x, z, data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) {
|
||||
return delegate.getHighest(x, z, data, ignoreFluid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(int x, int y, int z, PlatformBlockState state) {
|
||||
if (state == null) {
|
||||
return;
|
||||
}
|
||||
mutations.add(new BlockMutation(x, y, z, state));
|
||||
bufferedBlocks.put(new PositionKey(x, y, z), state);
|
||||
blockWrites++;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformBlockState get(int x, int y, int z) {
|
||||
PlatformBlockState state = bufferedBlocks.get(new PositionKey(x, y, z));
|
||||
return state == null ? delegate.get(x, y, z) : state;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPreventingDecay() {
|
||||
return delegate.isPreventingDecay();
|
||||
}
|
||||
|
||||
@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 isSolid(int x, int y, int z) {
|
||||
PlatformBlockState state = bufferedBlocks.get(new PositionKey(x, y, z));
|
||||
return state == null ? delegate.isSolid(x, y, z) : B.isSolid(state);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUnderwater(int x, int z) {
|
||||
return delegate.isUnderwater(x, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getFluidHeight() {
|
||||
return delegate.getFluidHeight();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDebugSmartBore() {
|
||||
return delegate.isDebugSmartBore();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTile(int x, int y, int z, TileData tile) {
|
||||
if (tile != null) {
|
||||
mutations.add(new TileMutation(x, y, z, tile));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void setData(int x, int y, int z, T data) {
|
||||
if (data == null) {
|
||||
return;
|
||||
}
|
||||
mutations.add(new DataMutation(x, y, z, data));
|
||||
if (data instanceof PlatformBlockState state) {
|
||||
bufferedBlocks.put(new PositionKey(x, y, z), state);
|
||||
blockWrites++;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @Nullable T getData(int x, int y, int z, Class<T> type) {
|
||||
for (int i = mutations.size() - 1; i >= 0; i--) {
|
||||
BufferedMutation mutation = mutations.get(i);
|
||||
if (mutation.x() != x || mutation.y() != y || mutation.z() != z) {
|
||||
continue;
|
||||
}
|
||||
Object value = mutation.value();
|
||||
if (type.isInstance(value)) {
|
||||
return type.cast(value);
|
||||
}
|
||||
}
|
||||
return delegate.getData(x, y, z, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Engine getEngine() {
|
||||
return delegate.getEngine();
|
||||
}
|
||||
|
||||
public enum CommitResult {
|
||||
COMMITTED,
|
||||
EMPTY,
|
||||
REJECTED_SUPPORT
|
||||
}
|
||||
|
||||
private interface BufferedMutation {
|
||||
int x();
|
||||
|
||||
int y();
|
||||
|
||||
int z();
|
||||
|
||||
Object value();
|
||||
|
||||
void apply(IObjectPlacer placer);
|
||||
}
|
||||
|
||||
private record BlockMutation(int x, int y, int z, PlatformBlockState value) implements BufferedMutation {
|
||||
@Override
|
||||
public void apply(IObjectPlacer placer) {
|
||||
placer.set(x, y, z, value);
|
||||
}
|
||||
}
|
||||
|
||||
private record TileMutation(int x, int y, int z, TileData value) implements BufferedMutation {
|
||||
@Override
|
||||
public void apply(IObjectPlacer placer) {
|
||||
placer.setTile(x, y, z, value);
|
||||
}
|
||||
}
|
||||
|
||||
private record DataMutation(int x, int y, int z, Object value) implements BufferedMutation {
|
||||
@Override
|
||||
public void apply(IObjectPlacer placer) {
|
||||
placer.setData(x, y, z, value);
|
||||
}
|
||||
}
|
||||
|
||||
private record PositionKey(int x, int y, int z) {
|
||||
}
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.mantle.components;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.placement.IObjectPlacer;
|
||||
import art.arcane.iris.engine.object.prefab.TileData;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import com.volmit.ModuleLog;
|
||||
|
||||
public final class GoldenDebugObjectPlacer implements IObjectPlacer {
|
||||
private static final int[] GOLDEN_DEBUG_TARGET = parseGoldenDebugTarget(resolveGoldenDebugSpec());
|
||||
private static final boolean GOLDEN_DEBUG = GOLDEN_DEBUG_TARGET != null;
|
||||
|
||||
private final IObjectPlacer delegate;
|
||||
private final String tag;
|
||||
private final ModuleLog log;
|
||||
|
||||
public GoldenDebugObjectPlacer(IObjectPlacer delegate, String tag, ModuleLog log) {
|
||||
this.delegate = delegate;
|
||||
this.tag = tag;
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
private static String resolveGoldenDebugSpec() {
|
||||
String property = System.getProperty("iris.goldendebug");
|
||||
if (property != null && !property.isBlank()) {
|
||||
return property;
|
||||
}
|
||||
try {
|
||||
java.io.File marker = new java.io.File("plugins/Iris/goldendebug.txt");
|
||||
if (marker.isFile()) {
|
||||
return java.nio.file.Files.readString(marker.toPath()).trim();
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static int[] parseGoldenDebugTarget(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 e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isGoldenDebugChunk(int x, int z) {
|
||||
return GOLDEN_DEBUG
|
||||
&& Math.abs(GOLDEN_DEBUG_TARGET[0] - x) <= GOLDEN_DEBUG_TARGET[2]
|
||||
&& Math.abs(GOLDEN_DEBUG_TARGET[1] - z) <= GOLDEN_DEBUG_TARGET[2];
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHighest(int x, int z, IrisData data) {
|
||||
int result = delegate.getHighest(x, z, data);
|
||||
log.debug("Goldendebug query: tag=" + tag + " getHighest(" + x + "," + z + ")=" + result);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) {
|
||||
int result = delegate.getHighest(x, z, data, ignoreFluid);
|
||||
log.debug("Goldendebug query: tag=" + tag + " getHighest(" + x + "," + z + ",ignoreFluid=" + ignoreFluid + ")=" + result);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(int x, int y, int z, PlatformBlockState d) {
|
||||
delegate.set(x, y, z, d);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformBlockState get(int x, int y, int z) {
|
||||
return delegate.get(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPreventingDecay() {
|
||||
return delegate.isPreventingDecay();
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSurfaceSolid(int x, int y, int z) {
|
||||
return delegate.isSurfaceSolid(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSolid(int x, int y, int z) {
|
||||
boolean result = delegate.isSolid(x, y, z);
|
||||
log.debug("Goldendebug query: tag=" + tag + " isSolid(" + x + "," + y + "," + z + ")=" + result);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUnderwater(int x, int z) {
|
||||
return delegate.isUnderwater(x, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getFluidHeight() {
|
||||
return delegate.getFluidHeight();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDebugSmartBore() {
|
||||
return delegate.isDebugSmartBore();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void setData(int xx, int yy, int zz, T data) {
|
||||
delegate.setData(xx, yy, zz, data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T getData(int xx, int yy, int zz, Class<T> t) {
|
||||
return delegate.getData(xx, yy, zz, t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTile(int xx, int yy, int zz, TileData tile) {
|
||||
delegate.setTile(xx, yy, zz, tile);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Engine getEngine() {
|
||||
return delegate.getEngine();
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.mantle.components;
|
||||
|
||||
import art.arcane.iris.builtin.floating.IslandAnchor;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.mantle.MantleWriter;
|
||||
import art.arcane.iris.engine.object.placement.IObjectPlacer;
|
||||
import art.arcane.iris.engine.object.prefab.TileData;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Iris's placer for an object placed against a floating island: heights and the island's solid blocks come from the
|
||||
* {@link IslandAnchor} the floating module samples, and a block is written only where the anchor lets the object write.
|
||||
* Everything else is the mantle's.
|
||||
*/
|
||||
public final class IslandAnchorPlacer implements IObjectPlacer {
|
||||
private final MantleWriter wrapped;
|
||||
private final IslandAnchor anchor;
|
||||
|
||||
public IslandAnchorPlacer(MantleWriter wrapped, IslandAnchor anchor) {
|
||||
this.wrapped = wrapped;
|
||||
this.anchor = anchor;
|
||||
}
|
||||
|
||||
public boolean canWriteObjectBlock(int x, int y, int z) {
|
||||
return anchor.writes(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHighest(int x, int z, IrisData data) {
|
||||
return anchor.faceY(x, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) {
|
||||
return getHighest(x, z, data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUnderwater(int x, int z) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSolid(int x, int y, int z) {
|
||||
return anchor.hasIsland(x, z) ? anchor.islandSolid(x, y, z) : wrapped.isSolid(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCarved(int x, int y, int z) {
|
||||
return wrapped.isCarved(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSurfaceSolid(int x, int y, int z) {
|
||||
return wrapped.isSurfaceSolid(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(int x, int y, int z, PlatformBlockState state) {
|
||||
if (anchor.writes(x, y, z)) {
|
||||
wrapped.set(x, y, z, state);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformBlockState get(int x, int y, int z) {
|
||||
return wrapped.get(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPreventingDecay() {
|
||||
return wrapped.isPreventingDecay();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getFluidHeight() {
|
||||
return wrapped.getFluidHeight();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDebugSmartBore() {
|
||||
return wrapped.isDebugSmartBore();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTile(int x, int y, int z, TileData tile) {
|
||||
if (anchor.writes(x, y, z)) {
|
||||
wrapped.setTile(x, y, z, tile);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void setData(int x, int y, int z, T data) {
|
||||
if (anchor.writes(x, y, z)) {
|
||||
wrapped.setData(x, y, z, data);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @Nullable T getData(int x, int y, int z, Class<T> type) {
|
||||
return wrapped.getData(x, y, z, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Engine getEngine() {
|
||||
return wrapped == null ? null : wrapped.getEngine();
|
||||
}
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.mantle.components;
|
||||
|
||||
import art.arcane.iris.builtin.structure.StructureCarveShape;
|
||||
import art.arcane.iris.util.project.noise.CNG;
|
||||
|
||||
/**
|
||||
* Carve envelope math shared by the Iris-assembled structure path and the native (vanilla template)
|
||||
* structure path so both shrinkwrap a structure footprint the same way. The lobe channel and the
|
||||
* eroded floor are only sampled by the native path; the Iris-assembled path still carves a uniform
|
||||
* side reach and a uniform floor cut.
|
||||
*/
|
||||
public final class StructureCarveEnvelope {
|
||||
private static final double CEILING_LOBE_RATIO = 0.5D;
|
||||
private static final double CEILING_ROLL_FREQUENCY_RATIO = 3D / 7D;
|
||||
private static final double FLOOR_ROLL_AMPLITUDE = 0.35D;
|
||||
private static final double FLOOR_ROLL_FREQUENCY_RATIO = 5D / 11D;
|
||||
// Maps a lobe frequency onto the smooth 2D channel so the auto-derived 0.015 lands near a
|
||||
// 40 block wavelength: wide enough that walls bulge and recede instead of tracking the footprint.
|
||||
private static final double LOBE_FREQUENCY_SCALE = 256D;
|
||||
|
||||
private StructureCarveEnvelope() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-column horizontal carve reach. The lobe channel only ever removes padding, so the boundary
|
||||
* stays inside the footprint bounds the carve was sized against and never falls below
|
||||
* {@code horizontalPadding * (1 - lobeStrength)}.
|
||||
*/
|
||||
public static double lobedSideReach(CNG lobe, double lobeFrequency, double lobeStrength,
|
||||
int x, int z, int horizontalPadding) {
|
||||
if (horizontalPadding <= 0) {
|
||||
return 0D;
|
||||
}
|
||||
return horizontalPadding * lobeFactor(lobe, lobeFrequency, lobeStrength, x, z);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ceiling counterpart of {@link #lobedSideReach}, deliberately half as strong so the roof swells
|
||||
* with the same lobes without collapsing onto the pieces.
|
||||
*/
|
||||
public static double lobedUpReach(CNG lobe, double lobeFrequency, double lobeStrength,
|
||||
int x, int z, double upReach) {
|
||||
if (upReach <= 0D) {
|
||||
return upReach;
|
||||
}
|
||||
return Math.max(1D, upReach
|
||||
* lobeFactor(lobe, lobeFrequency, lobeStrength * CEILING_LOBE_RATIO, x, z));
|
||||
}
|
||||
|
||||
private static double lobeFactor(CNG lobe, double lobeFrequency, double lobeStrength,
|
||||
int x, int z) {
|
||||
double clampedStrength = Math.max(0D, Math.min(1D, lobeStrength));
|
||||
if (lobe == null || clampedStrength <= 0D) {
|
||||
return 1D;
|
||||
}
|
||||
double scaledFrequency = lobeFrequency * LOBE_FREQUENCY_SCALE;
|
||||
double sample = Math.max(0D, Math.min(1D, lobe.fitDouble(
|
||||
0D, 1D, x * scaledFrequency, z * scaledFrequency)));
|
||||
return 1D - clampedStrength * (1D - sample);
|
||||
}
|
||||
|
||||
public static double erodedUpReach(CNG roll, double frequency, double strength, int x, int z, int head) {
|
||||
if (head <= 0) {
|
||||
return 0D;
|
||||
}
|
||||
double clampedStrength = Math.max(0D, Math.min(1D, strength));
|
||||
if (clampedStrength <= 0D) {
|
||||
return Math.max(1D, head);
|
||||
}
|
||||
double rollFrequency = frequency * CEILING_ROLL_FREQUENCY_RATIO;
|
||||
double sample = roll.fitDouble(0D, 1D, x * rollFrequency, z * rollFrequency) * 0.7D
|
||||
+ roll.fitDouble(0D, 1D, x * rollFrequency * 3D, z * rollFrequency * 3D) * 0.3D;
|
||||
double contrast = Math.max(0D, Math.min(1D, (sample - 0.5D) * 2.6D + 0.5D));
|
||||
double roundedReach = Math.max(1D, head);
|
||||
double erodedReach = Math.max(1D, head * (0.4D + 1.4D * contrast));
|
||||
return roundedReach + clampedStrength * (erodedReach - roundedReach);
|
||||
}
|
||||
|
||||
/**
|
||||
* Floor counterpart of {@link #erodedUpReach}. The amplitude is deliberately small and the result
|
||||
* never exceeds the configured floor padding, so a padding of zero leaves every column standing on
|
||||
* its own supporting block instead of undermining the structure.
|
||||
*/
|
||||
public static double erodedDownReach(CNG roll, double frequency, double strength, int x, int z, int floorCut) {
|
||||
if (floorCut <= 0) {
|
||||
return 0D;
|
||||
}
|
||||
double clampedStrength = Math.max(0D, Math.min(1D, strength));
|
||||
if (clampedStrength <= 0D) {
|
||||
return floorCut;
|
||||
}
|
||||
double rollFrequency = frequency * FLOOR_ROLL_FREQUENCY_RATIO;
|
||||
double sample = roll.fitDouble(0D, 1D, x * rollFrequency, z * rollFrequency);
|
||||
return floorCut * (1D - clampedStrength * FLOOR_ROLL_AMPLITUDE * (1D - sample));
|
||||
}
|
||||
|
||||
public static double normalizedVerticalDistance(int y, int sourceMinY, int sourceMaxY,
|
||||
double upReach, double downReach) {
|
||||
if (y > sourceMaxY) {
|
||||
return (y - sourceMaxY) / upReach;
|
||||
}
|
||||
if (y < sourceMinY) {
|
||||
return (sourceMinY - y) / downReach;
|
||||
}
|
||||
return 0D;
|
||||
}
|
||||
|
||||
public static double overboreBoundaryLimit(double noise, double strength) {
|
||||
double clampedNoise = Math.max(0.0, Math.min(1.0, noise));
|
||||
double clampedStrength = Math.max(0.0, Math.min(1.0, strength));
|
||||
return 1D - clampedStrength * (1D - clampedNoise);
|
||||
}
|
||||
|
||||
public static boolean shouldCarveOverboreCell(StructureCarveShape shape, double distanceSquared,
|
||||
double noise, double strength) {
|
||||
if (distanceSquared <= 0.0) {
|
||||
return true;
|
||||
}
|
||||
StructureCarveShape resolvedShape = shape == null ? StructureCarveShape.ERODED : shape;
|
||||
return switch (resolvedShape) {
|
||||
case BOX -> true;
|
||||
case ROUNDED -> distanceSquared <= 1D;
|
||||
case ERODED -> {
|
||||
double limit = overboreBoundaryLimit(noise, strength);
|
||||
yield distanceSquared <= 1D && distanceSquared <= limit * limit;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
-456
@@ -1,456 +0,0 @@
|
||||
package art.arcane.iris.engine.mantle.components;
|
||||
|
||||
import art.arcane.iris.engine.framework.PlacedStructurePiece;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObjectRotation;
|
||||
import art.arcane.iris.util.common.data.B;
|
||||
import art.arcane.volmlib.util.math.IrisBlockVector;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import it.unimi.dsi.fastutil.longs.Long2LongMap;
|
||||
import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public final class StructureCarvingFootprint {
|
||||
static final int DEFAULT_MAX_CELLS = 1_048_576;
|
||||
|
||||
private final int minX;
|
||||
private final int maxX;
|
||||
private final int minZ;
|
||||
private final int maxZ;
|
||||
private final int width;
|
||||
private final int depth;
|
||||
private final long[] distanceSquared;
|
||||
private final int[] nearestSourceIds;
|
||||
private final int[] sourceMinY;
|
||||
private final int[] sourceMaxY;
|
||||
|
||||
private StructureCarvingFootprint(FootprintData data) {
|
||||
minX = data.minX();
|
||||
maxX = data.maxX();
|
||||
minZ = data.minZ();
|
||||
maxZ = data.maxZ();
|
||||
width = data.width();
|
||||
depth = data.depth();
|
||||
distanceSquared = data.distanceSquared();
|
||||
nearestSourceIds = data.nearestSourceIds();
|
||||
sourceMinY = data.sourceMinY();
|
||||
sourceMaxY = data.sourceMaxY();
|
||||
}
|
||||
|
||||
static StructureCarvingFootprint from(KList<PlacedStructurePiece> pieces, int padding) {
|
||||
return from(pieces, padding, DEFAULT_MAX_CELLS);
|
||||
}
|
||||
|
||||
static StructureCarvingFootprint from(KList<PlacedStructurePiece> pieces, int padding, int maxCells) {
|
||||
return fromColumns(sink -> emitPieceColumns(pieces, sink), padding, maxCells);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a footprint from any per-column occupancy source. The source reports one contribution per
|
||||
* occupied column; overlapping contributions merge into a single column whose vertical extents span
|
||||
* every contribution.
|
||||
*/
|
||||
public static StructureCarvingFootprint fromColumns(ColumnSource source, int padding, int maxCells) {
|
||||
if (padding < 0) {
|
||||
throw new IllegalArgumentException("padding must be non-negative");
|
||||
}
|
||||
if (maxCells < 1) {
|
||||
throw new IllegalArgumentException("maxCells must be positive");
|
||||
}
|
||||
if (source == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
SourceCollection sources = collectSources(source);
|
||||
if (sources == null || sources.columns().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Bounds bounds = paddedBounds(sources.bounds(), padding, maxCells);
|
||||
if (bounds == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int[] nearestSourceIds = new int[bounds.cellCount()];
|
||||
Arrays.fill(nearestSourceIds, -1);
|
||||
int sourceCount = sources.columns().size();
|
||||
int[] sourceX = new int[sourceCount];
|
||||
int[] sourceZ = new int[sourceCount];
|
||||
int[] sourceMinY = new int[sourceCount];
|
||||
int[] sourceMaxY = new int[sourceCount];
|
||||
int sourceId = 0;
|
||||
for (Long2LongMap.Entry entry : sources.columns().long2LongEntrySet()) {
|
||||
int localX = unpackX(entry.getLongKey()) - bounds.minX();
|
||||
int localZ = unpackZ(entry.getLongKey()) - bounds.minZ();
|
||||
long heights = entry.getLongValue();
|
||||
sourceX[sourceId] = localX;
|
||||
sourceZ[sourceId] = localZ;
|
||||
sourceMinY[sourceId] = unpackMinY(heights);
|
||||
sourceMaxY[sourceId] = unpackMaxY(heights);
|
||||
nearestSourceIds[localZ * bounds.width() + localX] = sourceId;
|
||||
sourceId++;
|
||||
}
|
||||
|
||||
transformRows(nearestSourceIds, sourceX, sourceZ, bounds.width(), bounds.depth());
|
||||
long[] distanceSquared = transformColumns(
|
||||
nearestSourceIds, sourceX, sourceZ, bounds.width(), bounds.depth());
|
||||
FootprintData data = new FootprintData(
|
||||
bounds.minX(), bounds.maxX(), bounds.minZ(), bounds.maxZ(),
|
||||
bounds.width(), bounds.depth(), distanceSquared, nearestSourceIds,
|
||||
sourceMinY, sourceMaxY);
|
||||
return new StructureCarvingFootprint(data);
|
||||
}
|
||||
|
||||
public int minX() {
|
||||
return minX;
|
||||
}
|
||||
|
||||
public int maxX() {
|
||||
return maxX;
|
||||
}
|
||||
|
||||
public int minZ() {
|
||||
return minZ;
|
||||
}
|
||||
|
||||
public int maxZ() {
|
||||
return maxZ;
|
||||
}
|
||||
|
||||
public int width() {
|
||||
return width;
|
||||
}
|
||||
|
||||
public int depth() {
|
||||
return depth;
|
||||
}
|
||||
|
||||
public boolean contains(int worldX, int worldZ) {
|
||||
return worldX >= minX && worldX <= maxX && worldZ >= minZ && worldZ <= maxZ;
|
||||
}
|
||||
|
||||
public int indexAt(int worldX, int worldZ) {
|
||||
if (!contains(worldX, worldZ)) {
|
||||
return -1;
|
||||
}
|
||||
return (worldZ - minZ) * width + worldX - minX;
|
||||
}
|
||||
|
||||
public long distanceSquaredAt(int worldX, int worldZ) {
|
||||
return distanceSquaredAt(requireIndex(worldX, worldZ));
|
||||
}
|
||||
|
||||
public long distanceSquaredAt(int index) {
|
||||
return distanceSquared[index];
|
||||
}
|
||||
|
||||
public int sourceMinYAt(int worldX, int worldZ) {
|
||||
return sourceMinYAt(requireIndex(worldX, worldZ));
|
||||
}
|
||||
|
||||
public int sourceMinYAt(int index) {
|
||||
return sourceMinY[nearestSourceIds[index]];
|
||||
}
|
||||
|
||||
public int sourceMaxYAt(int worldX, int worldZ) {
|
||||
return sourceMaxYAt(requireIndex(worldX, worldZ));
|
||||
}
|
||||
|
||||
public int sourceMaxYAt(int index) {
|
||||
return sourceMaxY[nearestSourceIds[index]];
|
||||
}
|
||||
|
||||
Column sample(int worldX, int worldZ) {
|
||||
int index = indexAt(worldX, worldZ);
|
||||
if (index < 0) {
|
||||
return null;
|
||||
}
|
||||
return new Column(distanceSquaredAt(index), sourceMinYAt(index), sourceMaxYAt(index));
|
||||
}
|
||||
|
||||
private static SourceCollection collectSources(ColumnSource source) {
|
||||
Long2LongOpenHashMap columns = new Long2LongOpenHashMap();
|
||||
MutableBounds bounds = new MutableBounds();
|
||||
boolean usable = source.emit((worldX, worldZ, minY, maxY) -> {
|
||||
mergeColumn(columns, worldX, worldZ, minY, maxY);
|
||||
bounds.include(worldX, worldZ);
|
||||
});
|
||||
if (!usable) {
|
||||
return null;
|
||||
}
|
||||
return columns.isEmpty() ? null : new SourceCollection(columns, bounds.freeze());
|
||||
}
|
||||
|
||||
private static boolean emitPieceColumns(KList<PlacedStructurePiece> pieces, ColumnSink sink) {
|
||||
if (pieces == null) {
|
||||
return true;
|
||||
}
|
||||
for (PlacedStructurePiece piece : pieces) {
|
||||
if (piece == null) {
|
||||
continue;
|
||||
}
|
||||
IrisObject object = piece.getObject();
|
||||
IrisObjectRotation rotation = piece.getRotation();
|
||||
if (object == null || rotation == null || object.getBlocks() == null) {
|
||||
continue;
|
||||
}
|
||||
for (IrisBlockVector local : object.getBlocks().keys()) {
|
||||
if (local == null || B.isAir(object.getBlocks().get(local))) {
|
||||
continue;
|
||||
}
|
||||
IrisBlockVector rotated = rotation.rotate(local.clone());
|
||||
long worldX = (long) piece.getX() + rotated.getBlockX();
|
||||
long worldY = (long) piece.getY() + rotated.getBlockY();
|
||||
long worldZ = (long) piece.getZ() + rotated.getBlockZ();
|
||||
if (!fitsInteger(worldX) || !fitsInteger(worldY) || !fitsInteger(worldZ)) {
|
||||
return false;
|
||||
}
|
||||
sink.column((int) worldX, (int) worldZ, (int) worldY, (int) worldY);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Bounds paddedBounds(MutableBoundsSnapshot sourceBounds, int padding, int maxCells) {
|
||||
long paddedMinX = (long) sourceBounds.minX() - padding;
|
||||
long paddedMaxX = (long) sourceBounds.maxX() + padding;
|
||||
long paddedMinZ = (long) sourceBounds.minZ() - padding;
|
||||
long paddedMaxZ = (long) sourceBounds.maxZ() + padding;
|
||||
if (!fitsInteger(paddedMinX) || !fitsInteger(paddedMaxX)
|
||||
|| !fitsInteger(paddedMinZ) || !fitsInteger(paddedMaxZ)) {
|
||||
return null;
|
||||
}
|
||||
long width = paddedMaxX - paddedMinX + 1L;
|
||||
long depth = paddedMaxZ - paddedMinZ + 1L;
|
||||
if (width < 1L || depth < 1L || width > Integer.MAX_VALUE || depth > Integer.MAX_VALUE
|
||||
|| width > maxCells / depth) {
|
||||
return null;
|
||||
}
|
||||
int cellCount = (int) (width * depth);
|
||||
return new Bounds(
|
||||
(int) paddedMinX, (int) paddedMaxX, (int) paddedMinZ, (int) paddedMaxZ,
|
||||
(int) width, (int) depth, cellCount);
|
||||
}
|
||||
|
||||
private static void mergeColumn(Long2LongOpenHashMap columns, int x, int z, int minY, int maxY) {
|
||||
long key = pack(x, z);
|
||||
if (!columns.containsKey(key)) {
|
||||
columns.put(key, packHeights(minY, maxY));
|
||||
return;
|
||||
}
|
||||
long existing = columns.get(key);
|
||||
columns.put(key, packHeights(
|
||||
Math.min(minY, unpackMinY(existing)), Math.max(maxY, unpackMaxY(existing))));
|
||||
}
|
||||
|
||||
private static void transformRows(int[] nearestSourceIds, int[] sourceX, int[] sourceZ,
|
||||
int width, int depth) {
|
||||
for (int z = 0; z < depth; z++) {
|
||||
int rowStart = z * width;
|
||||
int previousSource = -1;
|
||||
for (int x = 0; x < width; x++) {
|
||||
int index = rowStart + x;
|
||||
int sourceId = nearestSourceIds[index];
|
||||
if (isExplicitSource(sourceId, x, z, sourceX, sourceZ)) {
|
||||
previousSource = sourceId;
|
||||
} else {
|
||||
nearestSourceIds[index] = previousSource;
|
||||
}
|
||||
}
|
||||
int nextSource = -1;
|
||||
for (int x = width - 1; x >= 0; x--) {
|
||||
int index = rowStart + x;
|
||||
int currentSource = nearestSourceIds[index];
|
||||
if (isExplicitSource(currentSource, x, z, sourceX, sourceZ)) {
|
||||
nextSource = currentSource;
|
||||
}
|
||||
if (isBetterHorizontalSource(nextSource, currentSource, x, sourceX)) {
|
||||
nearestSourceIds[index] = nextSource;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static long[] transformColumns(int[] nearestSourceIds, int[] sourceX, int[] sourceZ,
|
||||
int width, int depth) {
|
||||
long[] distanceSquared = new long[nearestSourceIds.length];
|
||||
int[] siteRows = new int[depth];
|
||||
int[] siteSourceIds = new int[depth];
|
||||
int[] starts = new int[depth];
|
||||
long[] siteCosts = new long[depth];
|
||||
for (int x = 0; x < width; x++) {
|
||||
int siteCount = buildEnvelope(
|
||||
nearestSourceIds, sourceX, width, depth, x,
|
||||
siteRows, siteSourceIds, starts, siteCosts);
|
||||
int siteIndex = 0;
|
||||
for (int z = 0; z < depth; z++) {
|
||||
while (siteIndex + 1 < siteCount && starts[siteIndex + 1] <= z) {
|
||||
siteIndex++;
|
||||
}
|
||||
int sourceId = siteSourceIds[siteIndex];
|
||||
int index = z * width + x;
|
||||
long deltaX = (long) x - sourceX[sourceId];
|
||||
long deltaZ = (long) z - sourceZ[sourceId];
|
||||
nearestSourceIds[index] = sourceId;
|
||||
distanceSquared[index] = deltaX * deltaX + deltaZ * deltaZ;
|
||||
}
|
||||
}
|
||||
return distanceSquared;
|
||||
}
|
||||
|
||||
private static int buildEnvelope(int[] nearestSourceIds, int[] sourceX, int width, int depth,
|
||||
int x, int[] siteRows, int[] siteSourceIds,
|
||||
int[] starts, long[] siteCosts) {
|
||||
int siteCount = 0;
|
||||
for (int z = 0; z < depth; z++) {
|
||||
int sourceId = nearestSourceIds[z * width + x];
|
||||
if (sourceId < 0) {
|
||||
continue;
|
||||
}
|
||||
long deltaX = (long) x - sourceX[sourceId];
|
||||
long cost = deltaX * deltaX;
|
||||
int start = Integer.MIN_VALUE;
|
||||
while (siteCount > 0) {
|
||||
start = firstStrictlyBetterAt(
|
||||
siteRows[siteCount - 1], siteCosts[siteCount - 1], z, cost);
|
||||
if (start > starts[siteCount - 1]) {
|
||||
break;
|
||||
}
|
||||
siteCount--;
|
||||
}
|
||||
if (siteCount == 0) {
|
||||
start = Integer.MIN_VALUE;
|
||||
}
|
||||
siteRows[siteCount] = z;
|
||||
siteSourceIds[siteCount] = sourceId;
|
||||
siteCosts[siteCount] = cost;
|
||||
starts[siteCount] = start;
|
||||
siteCount++;
|
||||
}
|
||||
return siteCount;
|
||||
}
|
||||
|
||||
private static int firstStrictlyBetterAt(int existingRow, long existingCost,
|
||||
int candidateRow, long candidateCost) {
|
||||
long numerator = candidateCost + (long) candidateRow * candidateRow
|
||||
- existingCost - (long) existingRow * existingRow;
|
||||
long denominator = 2L * (candidateRow - existingRow);
|
||||
long start = Math.floorDiv(numerator, denominator) + 1L;
|
||||
if (start < Integer.MIN_VALUE) {
|
||||
return Integer.MIN_VALUE;
|
||||
}
|
||||
if (start > Integer.MAX_VALUE) {
|
||||
return Integer.MAX_VALUE;
|
||||
}
|
||||
return (int) start;
|
||||
}
|
||||
|
||||
private static boolean isExplicitSource(int sourceId, int x, int z,
|
||||
int[] sourceX, int[] sourceZ) {
|
||||
return sourceId >= 0 && sourceX[sourceId] == x && sourceZ[sourceId] == z;
|
||||
}
|
||||
|
||||
private static boolean isBetterHorizontalSource(int candidateId, int currentId,
|
||||
int x, int[] sourceX) {
|
||||
if (candidateId < 0) {
|
||||
return false;
|
||||
}
|
||||
if (currentId < 0) {
|
||||
return true;
|
||||
}
|
||||
long candidateDelta = (long) x - sourceX[candidateId];
|
||||
long currentDelta = (long) x - sourceX[currentId];
|
||||
long candidateDistance = candidateDelta * candidateDelta;
|
||||
long currentDistance = currentDelta * currentDelta;
|
||||
return candidateDistance < currentDistance
|
||||
|| candidateDistance == currentDistance && sourceX[candidateId] < sourceX[currentId];
|
||||
}
|
||||
|
||||
private int requireIndex(int worldX, int worldZ) {
|
||||
int index = indexAt(worldX, worldZ);
|
||||
if (index < 0) {
|
||||
throw new IndexOutOfBoundsException(
|
||||
"coordinate outside carving footprint: " + worldX + "," + worldZ);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
private static boolean fitsInteger(long value) {
|
||||
return value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE;
|
||||
}
|
||||
|
||||
private static long pack(int x, int z) {
|
||||
return (long) x << 32 | z & 0xffffffffL;
|
||||
}
|
||||
|
||||
private static int unpackX(long packed) {
|
||||
return (int) (packed >> 32);
|
||||
}
|
||||
|
||||
private static int unpackZ(long packed) {
|
||||
return (int) packed;
|
||||
}
|
||||
|
||||
private static long packHeights(int minY, int maxY) {
|
||||
return (long) minY << 32 | maxY & 0xffffffffL;
|
||||
}
|
||||
|
||||
private static int unpackMinY(long packed) {
|
||||
return (int) (packed >> 32);
|
||||
}
|
||||
|
||||
private static int unpackMaxY(long packed) {
|
||||
return (int) packed;
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ColumnSink {
|
||||
void column(int worldX, int worldZ, int minY, int maxY);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ColumnSource {
|
||||
/**
|
||||
* Reports every occupied column to the sink. Returning false abandons the footprint, which is how
|
||||
* a source rejects occupancy it cannot address (for example coordinates outside the integer range).
|
||||
*/
|
||||
boolean emit(ColumnSink sink);
|
||||
}
|
||||
|
||||
record Column(long distanceSquared, int sourceMinY, int sourceMaxY) {
|
||||
}
|
||||
|
||||
private record Bounds(int minX, int maxX, int minZ, int maxZ,
|
||||
int width, int depth, int cellCount) {
|
||||
}
|
||||
|
||||
private record FootprintData(int minX, int maxX, int minZ, int maxZ,
|
||||
int width, int depth, long[] distanceSquared,
|
||||
int[] nearestSourceIds, int[] sourceMinY, int[] sourceMaxY) {
|
||||
}
|
||||
|
||||
private record SourceCollection(Long2LongOpenHashMap columns, MutableBoundsSnapshot bounds) {
|
||||
}
|
||||
|
||||
private record MutableBoundsSnapshot(int minX, int maxX, int minZ, int maxZ) {
|
||||
}
|
||||
|
||||
private static final class MutableBounds {
|
||||
private int minX = Integer.MAX_VALUE;
|
||||
private int maxX = Integer.MIN_VALUE;
|
||||
private int minZ = Integer.MAX_VALUE;
|
||||
private int maxZ = Integer.MIN_VALUE;
|
||||
|
||||
private void include(int x, int z) {
|
||||
minX = Math.min(minX, x);
|
||||
maxX = Math.max(maxX, x);
|
||||
minZ = Math.min(minZ, z);
|
||||
maxZ = Math.max(maxZ, z);
|
||||
}
|
||||
|
||||
private MutableBoundsSnapshot freeze() {
|
||||
return new MutableBoundsSnapshot(minX, maxX, minZ, maxZ);
|
||||
}
|
||||
}
|
||||
}
|
||||
-79
@@ -1,79 +0,0 @@
|
||||
package art.arcane.iris.engine.mantle.components;
|
||||
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
|
||||
|
||||
import java.util.function.IntConsumer;
|
||||
import java.util.function.IntPredicate;
|
||||
|
||||
final class StructureFoundationPlanner {
|
||||
static final int NO_GROUND = Integer.MIN_VALUE;
|
||||
|
||||
private StructureFoundationPlanner() {
|
||||
}
|
||||
|
||||
static void recordBaseCell(Long2IntOpenHashMap columns, int x, int y, int z,
|
||||
PlatformBlockState state, boolean supportNonOccluding) {
|
||||
if (columns == null || state == null
|
||||
|| !(supportNonOccluding ? state.isSolid() : state.isOccluding())) {
|
||||
return;
|
||||
}
|
||||
long columnKey = pack(x, z);
|
||||
if (!columns.containsKey(columnKey) || y < columns.get(columnKey)) {
|
||||
columns.put(columnKey, y);
|
||||
}
|
||||
}
|
||||
|
||||
static int findGroundY(int foundationY, int maxDepth, int minimumY, IntPredicate solidAtY) {
|
||||
if (foundationY <= minimumY) {
|
||||
return NO_GROUND;
|
||||
}
|
||||
long requestedFloor = (long) foundationY - Math.max(1, maxDepth);
|
||||
int scanFloor = (int) Math.max(minimumY, requestedFloor);
|
||||
for (int y = foundationY - 1; y >= scanFloor; y--) {
|
||||
if (solidAtY.test(y)) {
|
||||
return y;
|
||||
}
|
||||
}
|
||||
return NO_GROUND;
|
||||
}
|
||||
|
||||
static boolean isGroundSolid(PlatformBlockState overlay, boolean carved, int mantleY, int terrainHeight) {
|
||||
if (mantleY <= 0) {
|
||||
return true;
|
||||
}
|
||||
if (overlay != null) {
|
||||
return overlay.isSolid();
|
||||
}
|
||||
return !carved && mantleY <= terrainHeight;
|
||||
}
|
||||
|
||||
static boolean isSurfaceSupportBoundary(PlatformBlockState overlay, boolean carved,
|
||||
int mantleY, int terrainHeight) {
|
||||
return carved || isGroundSolid(overlay, false, mantleY, terrainHeight);
|
||||
}
|
||||
|
||||
static int fillSupportColumn(int foundationY, int groundY, IntConsumer supportAtY) {
|
||||
if (groundY == NO_GROUND || groundY >= foundationY - 1) {
|
||||
return 0;
|
||||
}
|
||||
int written = 0;
|
||||
for (int y = foundationY - 1; y > groundY; y--) {
|
||||
supportAtY.accept(y);
|
||||
written++;
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
static long pack(int x, int z) {
|
||||
return ((long) x << 32) | (z & 0xffffffffL);
|
||||
}
|
||||
|
||||
static int unpackX(long packed) {
|
||||
return (int) (packed >> 32);
|
||||
}
|
||||
|
||||
static int unpackZ(long packed) {
|
||||
return (int) packed;
|
||||
}
|
||||
}
|
||||
@@ -1,685 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.mantle.components;
|
||||
|
||||
import art.arcane.iris.builtin.anchor.PlaceTrait;
|
||||
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
|
||||
import art.arcane.iris.core.IrisSettings;
|
||||
import art.arcane.volmlib.util.cache.CacheKey;
|
||||
import art.arcane.iris.engine.framework.IrisStructureLocator;
|
||||
import art.arcane.iris.engine.framework.PlacedStructurePiece;
|
||||
import art.arcane.iris.engine.framework.StructurePlacementScope;
|
||||
import art.arcane.iris.builtin.structure.StructurePlacementMarker;
|
||||
import art.arcane.iris.engine.framework.TreeBlockMaterial;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.mantle.MantleWriter;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
import art.arcane.iris.builtin.structure.StructureCarveShape;
|
||||
import art.arcane.iris.builtin.structure.StructurePlacement;
|
||||
import art.arcane.iris.builtin.structure.StructureStilts;
|
||||
import com.volmit.ModuleLog;
|
||||
import com.volmit.block.PaletteSampler;
|
||||
import com.volmit.block.PaletteSpec;
|
||||
import art.arcane.iris.builtin.structure.StructureTerrain;
|
||||
import art.arcane.iris.builtin.structure.StructureTerrainMode;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.iris.util.common.data.B;
|
||||
import art.arcane.volmlib.util.math.IrisBlockVector;
|
||||
import art.arcane.iris.util.project.matter.TileWrapper;
|
||||
import art.arcane.iris.util.project.noise.CNG;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.iris.util.project.context.ChunkContext;
|
||||
import art.arcane.volmlib.util.documentation.ChunkCoordinates;
|
||||
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
|
||||
import art.arcane.volmlib.util.matter.Matter;
|
||||
import art.arcane.volmlib.util.matter.MatterCavern;
|
||||
import art.arcane.volmlib.util.matter.MatterStructurePOI;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import it.unimi.dsi.fastutil.longs.Long2IntMap;
|
||||
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Places the Iris structures of the dimension, its regions and biomes into the mantle for
|
||||
* {@link StructureModule}: their pieces, foundations, bores and carves, clearing object trees they
|
||||
* intersect. One per engine runtime. Its reach is the largest structure any placement can produce.
|
||||
*/
|
||||
public class StructurePlacing {
|
||||
private static final MatterCavern CARVE_CAVERN = new MatterCavern(true, "", (byte) 3);
|
||||
|
||||
private final Engine engine;
|
||||
private final ModuleLog log;
|
||||
|
||||
public StructurePlacing(Engine engine, ModuleLog log) {
|
||||
this.engine = engine;
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
/** Places what originates in the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */
|
||||
@ChunkCoordinates
|
||||
public void place(MantleWriter writer, int x, int z, ChunkContext context) {
|
||||
for (StructurePlacement placement : StructurePlacementScope.placementsAt(
|
||||
engine, x, z)) {
|
||||
if (!placement.hasIrisStructures()) {
|
||||
continue;
|
||||
}
|
||||
placeFromPlacement(writer, placement, x, z);
|
||||
}
|
||||
}
|
||||
|
||||
@ChunkCoordinates
|
||||
private void placeFromPlacement(MantleWriter writer, StructurePlacement placement, int cx, int cz) {
|
||||
IrisStructureLocator.ResolvedPlacement resolved = IrisStructureLocator.resolvePlacement(
|
||||
engine, placement, cx, cz);
|
||||
if (resolved == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
boolean trace = IrisSettings.get().getGeneral().isDebug();
|
||||
if (trace) {
|
||||
log.debug("[StructTrace] ORIGIN chunk=" + cx + "," + cz + " structures=" + placement.structures()
|
||||
+ " anchor=" + placement.resolvedAnchor() + " band=" + placement.minHeight() + ".." + placement.maxHeight());
|
||||
}
|
||||
|
||||
String key = resolved.structureKey();
|
||||
IrisStructure structure = resolved.structure();
|
||||
KList<PlacedStructurePiece> pieces = resolvedPiecesOrNull(resolved, cx, cz);
|
||||
if (pieces == null) {
|
||||
return;
|
||||
}
|
||||
RNG rng = resolved.rng();
|
||||
int baseY = resolved.baseY();
|
||||
if (trace) {
|
||||
log.debug("[StructTrace] ASSEMBLED chunk=" + cx + "," + cz + " key=" + key + " baseY=" + baseY + " pieces=" + pieces.size());
|
||||
}
|
||||
|
||||
if (!placement.isAnchoredUnderground()) {
|
||||
clearIntersectingObjectTrees(writer, resolved);
|
||||
}
|
||||
|
||||
StructureTerrain terrain = placement.resolvedTerrain();
|
||||
StructureTerrainMode terrainMode = terrain.resolvedMode();
|
||||
if (terrainMode == StructureTerrainMode.FORCE_CARVE) {
|
||||
forceCarveStructure(writer, pieces, terrain);
|
||||
} else if (terrainMode == StructureTerrainMode.BORE) {
|
||||
boreStructure(writer, pieces, terrain);
|
||||
} else if (terrainMode != StructureTerrainMode.PRESERVE
|
||||
&& terrainMode != StructureTerrainMode.SOURCE) {
|
||||
throw new IllegalStateException("Iris assembly terrain mode " + terrainMode
|
||||
+ " is not implemented for structure '" + key + "'");
|
||||
}
|
||||
|
||||
ObjectPlaceMode mode = structure.getPlaceMode();
|
||||
int failedPieces = 0;
|
||||
StructureStilts stilt = placement.stilt().orElse(null);
|
||||
Long2IntOpenHashMap foundationColumns = stilt == null
|
||||
? null : new Long2IntOpenHashMap();
|
||||
boolean supportNonOccluding = stilt != null && stilt.supportNonOccluding();
|
||||
if (placement.isAnchoredUnderground()) {
|
||||
ObjectPlaceMode undergroundMode = mode.placeMode().has(PlaceTrait.CAVE_ANCHORED)
|
||||
? mode : ObjectPlaceMode.STRUCTURE_PIECE;
|
||||
for (PlacedStructurePiece p : pieces) {
|
||||
if (placeObject(writer, structure, p, undergroundMode, p.getY(), rng,
|
||||
foundationColumns, supportNonOccluding) == -1) {
|
||||
failedPieces++;
|
||||
}
|
||||
}
|
||||
} else if (mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) {
|
||||
for (PlacedStructurePiece p : pieces) {
|
||||
if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, p.getY(), rng,
|
||||
foundationColumns, supportNonOccluding) == -1) {
|
||||
failedPieces++;
|
||||
}
|
||||
}
|
||||
} else if (pieces.size() == 1) {
|
||||
if (placeObject(writer, structure, pieces.getFirst(), mode, -1, rng,
|
||||
foundationColumns, supportNonOccluding) == -1) {
|
||||
failedPieces++;
|
||||
}
|
||||
} else {
|
||||
for (PlacedStructurePiece p : pieces) {
|
||||
if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, p.getY(), rng,
|
||||
foundationColumns, supportNonOccluding) == -1) {
|
||||
failedPieces++;
|
||||
}
|
||||
}
|
||||
}
|
||||
requireAppliedPieces(resolved, cx, cz, failedPieces);
|
||||
if (failedPieces == 0 && stilt != null) {
|
||||
placeFoundation(writer, foundationColumns, stilt, rng, !placement.isAnchoredUnderground());
|
||||
}
|
||||
}
|
||||
|
||||
private void placeFoundation(MantleWriter writer, Long2IntOpenHashMap columns,
|
||||
StructureStilts settings, RNG rng,
|
||||
boolean surfaceStructure) {
|
||||
PaletteSpec palette = settings.palette().orElseThrow(
|
||||
() -> new NullPointerException("Structure stilt palette must not be null"));
|
||||
PaletteSampler picker = engine.getData().getPackResources().blocks().palette(palette, rng.getSeed());
|
||||
int mantleOffset = engine.getMinHeight();
|
||||
int maxDepth = Math.max(1, settings.maxDepth());
|
||||
for (Long2IntMap.Entry column : columns.long2IntEntrySet()) {
|
||||
int worldX = StructureFoundationPlanner.unpackX(column.getLongKey());
|
||||
int worldZ = StructureFoundationPlanner.unpackZ(column.getLongKey());
|
||||
int foundationY = column.getIntValue();
|
||||
PlatformBlockState foundationState = writer.getDataIfPresent(
|
||||
worldX, foundationY, worldZ, PlatformBlockState.class);
|
||||
if (foundationState == null || !foundationState.isSolid()) {
|
||||
continue;
|
||||
}
|
||||
int terrainHeight = engine.getMantle().trueHeight(worldX, worldZ);
|
||||
int groundY = StructureFoundationPlanner.findGroundY(
|
||||
foundationY, maxDepth, 0,
|
||||
y -> {
|
||||
PlatformBlockState overlay = writer.getDataIfPresent(
|
||||
worldX, y, worldZ, PlatformBlockState.class);
|
||||
boolean carved = writer.getDataIfPresent(
|
||||
worldX, y, worldZ, MatterCavern.class) != null;
|
||||
return surfaceStructure
|
||||
? StructureFoundationPlanner.isSurfaceSupportBoundary(
|
||||
overlay, carved, y, terrainHeight)
|
||||
: StructureFoundationPlanner.isGroundSolid(
|
||||
overlay, carved, y, terrainHeight);
|
||||
});
|
||||
if (groundY == StructureFoundationPlanner.NO_GROUND) {
|
||||
continue;
|
||||
}
|
||||
StructureFoundationPlanner.fillSupportColumn(foundationY, groundY, y -> {
|
||||
writeFoundationSupport(writer, picker, worldX, y, worldZ, mantleOffset);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes the stilt palette's block at the column's mantle height, clearing any carve there. */
|
||||
static void writeFoundationSupport(MantleWriter writer, PaletteSampler picker, int worldX, int mantleY, int worldZ,
|
||||
int mantleOffset) {
|
||||
int worldY = mantleY + mantleOffset;
|
||||
PlatformBlockState support = B.getState(picker.at(worldX, worldY, worldZ).key());
|
||||
if (support == null) {
|
||||
throw new IllegalStateException("Structure stilt palette resolved no block at "
|
||||
+ worldX + "," + worldY + "," + worldZ);
|
||||
}
|
||||
writer.clearData(worldX, mantleY, worldZ, MatterCavern.class);
|
||||
writer.set(worldX, mantleY, worldZ, support);
|
||||
}
|
||||
|
||||
static KList<PlacedStructurePiece> resolvedPiecesOrNull(
|
||||
IrisStructureLocator.ResolvedPlacement resolved,
|
||||
int chunkX,
|
||||
int chunkZ
|
||||
) {
|
||||
if (resolved == null) {
|
||||
return null;
|
||||
}
|
||||
KList<PlacedStructurePiece> pieces = resolved.pieces();
|
||||
if (!IrisStructureLocator.requirePlacementOutput(
|
||||
resolved.placement(), resolved.structureKey(), chunkX, chunkZ,
|
||||
pieces != null && !pieces.isEmpty(), "placement application received no assembled pieces")) {
|
||||
return null;
|
||||
}
|
||||
return pieces;
|
||||
}
|
||||
|
||||
static void requireAppliedPieces(IrisStructureLocator.ResolvedPlacement resolved,
|
||||
int chunkX, int chunkZ, int failedPieces) {
|
||||
IrisStructureLocator.requirePlacementOutput(
|
||||
resolved.placement(), resolved.structureKey(), chunkX, chunkZ, failedPieces == 0,
|
||||
"object placement rejected " + failedPieces + " of " + resolved.pieces().size()
|
||||
+ " assembled piece(s)");
|
||||
}
|
||||
|
||||
private void boreStructure(MantleWriter writer, KList<PlacedStructurePiece> pieces,
|
||||
StructureTerrain terrain) {
|
||||
int[] bounds = computePieceBounds(pieces);
|
||||
if (bounds == null) {
|
||||
return;
|
||||
}
|
||||
int pad = Math.max(0, terrain.horizontalPadding());
|
||||
int minX = bounds[0] - pad;
|
||||
int minY = bounds[1] - Math.max(0, terrain.floorPadding());
|
||||
int minZ = bounds[2] - pad;
|
||||
int maxX = bounds[3] + pad;
|
||||
int maxY = bounds[4] + Math.max(0, terrain.ceilingPadding());
|
||||
int maxZ = bounds[5] + pad;
|
||||
int worldMin = engine.getMinHeight() + 1;
|
||||
int worldMax = engine.getMinHeight() + engine.getHeight() - 1;
|
||||
minY = Math.max(minY, worldMin);
|
||||
maxY = Math.min(maxY, worldMax);
|
||||
if (maxX < minX || maxY < minY || maxZ < minZ) {
|
||||
return;
|
||||
}
|
||||
int mantleOffset = engine.getMinHeight();
|
||||
for (int bx = minX; bx <= maxX; bx++) {
|
||||
for (int by = minY; by <= maxY; by++) {
|
||||
for (int bz = minZ; bz <= maxZ; bz++) {
|
||||
writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void forceCarveStructure(MantleWriter writer, KList<PlacedStructurePiece> pieces,
|
||||
StructureTerrain terrain) {
|
||||
int[] bounds = computePieceBounds(pieces);
|
||||
if (bounds == null) {
|
||||
return;
|
||||
}
|
||||
StructureCarveShape shape = terrain.resolvedShape();
|
||||
int margin = Math.max(0, terrain.horizontalPadding());
|
||||
int head = Math.max(0, terrain.ceilingPadding());
|
||||
int floorCut = Math.max(0, terrain.floorPadding());
|
||||
double strength = terrain.resolvedErosionStrength();
|
||||
int mantleOffset = engine.getMinHeight();
|
||||
int worldMin = engine.getMinHeight() + 1;
|
||||
int worldMax = engine.getMinHeight() + engine.getHeight() - 1;
|
||||
int upExtension = shape.maximumCeilingExtension(head, strength);
|
||||
|
||||
if (shape == StructureCarveShape.BOX) {
|
||||
carveOverboreBox(writer, bounds, margin, head, floorCut, mantleOffset, worldMin, worldMax);
|
||||
return;
|
||||
}
|
||||
|
||||
long work = overboreCandidateVolume(bounds, margin, upExtension, floorCut);
|
||||
StructureCarvingFootprint footprint = StructureCarvingFootprint.from(
|
||||
pieces, margin, Integer.MAX_VALUE);
|
||||
if (footprint == null) {
|
||||
throw new IllegalStateException("Structure force-carve footprint is empty or exceeds addressable memory");
|
||||
}
|
||||
|
||||
double frequency = terrain.resolvedErosionFrequency();
|
||||
boolean eroded = shape == StructureCarveShape.ERODED && strength > 0D;
|
||||
CNG blob = null;
|
||||
CNG roll = null;
|
||||
if (eroded) {
|
||||
RNG noiseRng = new RNG(engine.getSeedManager().getMantle() + CacheKey.key(bounds[0], bounds[2]));
|
||||
blob = CNG.signature(noiseRng);
|
||||
roll = CNG.signature(noiseRng.nextParallelRNG(0x2A17));
|
||||
}
|
||||
|
||||
if (IrisSettings.get().getGeneral().isDebug()) {
|
||||
log.info("Overbore carving structure cavern: shape=" + shape + " pieces=" + pieces.size()
|
||||
+ " footprint=" + footprint.width() + "x" + footprint.depth()
|
||||
+ " margin=" + margin + " head=" + head + " floorCut=" + floorCut + " work=" + work);
|
||||
}
|
||||
|
||||
double sideReachSquared = (double) margin * margin;
|
||||
double downReach = Math.max(1D, floorCut);
|
||||
for (int bz = footprint.minZ(); bz <= footprint.maxZ(); bz++) {
|
||||
int footprintIndex = footprint.indexAt(footprint.minX(), bz);
|
||||
for (int bx = footprint.minX(); bx <= footprint.maxX(); bx++, footprintIndex++) {
|
||||
long horizontalDistanceSquared = footprint.distanceSquaredAt(footprintIndex);
|
||||
if (horizontalDistanceSquared < 0L || horizontalDistanceSquared > sideReachSquared) {
|
||||
continue;
|
||||
}
|
||||
double normalizedHorizontalDistanceSquared = sideReachSquared == 0D
|
||||
? 0D : horizontalDistanceSquared / sideReachSquared;
|
||||
int sourceMinY = footprint.sourceMinYAt(footprintIndex);
|
||||
int sourceMaxY = footprint.sourceMaxYAt(footprintIndex);
|
||||
double upReach = eroded
|
||||
? StructureCarveEnvelope.erodedUpReach(roll, frequency, strength, bx, bz, head)
|
||||
: Math.max(1D, head);
|
||||
int columnUpExtension = eroded
|
||||
? (int) Math.ceil(upReach) : head;
|
||||
int minY = Math.max(worldMin, sourceMinY - floorCut);
|
||||
int maxY = Math.min(worldMax, sourceMaxY + columnUpExtension);
|
||||
for (int by = minY; by <= maxY; by++) {
|
||||
double normalizedY = StructureCarveEnvelope.normalizedVerticalDistance(
|
||||
by, sourceMinY, sourceMaxY, upReach, downReach);
|
||||
double distanceSquared = normalizedHorizontalDistanceSquared
|
||||
+ normalizedY * normalizedY;
|
||||
if (distanceSquared <= 0D) {
|
||||
writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN);
|
||||
continue;
|
||||
}
|
||||
if (distanceSquared > 1D) {
|
||||
continue;
|
||||
}
|
||||
if (!eroded) {
|
||||
writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN);
|
||||
continue;
|
||||
}
|
||||
double noise = blob.fitDouble(
|
||||
0D, 1D, bx * frequency, by * frequency, bz * frequency);
|
||||
if (StructureCarveEnvelope.shouldCarveOverboreCell(
|
||||
shape, distanceSquared, noise, strength)) {
|
||||
writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void carveOverboreBox(MantleWriter writer, int[] bounds, int margin, int head, int floorCut,
|
||||
int mantleOffset, int worldMin, int worldMax) {
|
||||
int minX = bounds[0] - margin;
|
||||
int minY = Math.max(worldMin, bounds[1] - floorCut);
|
||||
int minZ = bounds[2] - margin;
|
||||
int maxX = bounds[3] + margin;
|
||||
int maxY = Math.min(worldMax, bounds[4] + head);
|
||||
int maxZ = bounds[5] + margin;
|
||||
for (int bx = minX; bx <= maxX; bx++) {
|
||||
for (int by = minY; by <= maxY; by++) {
|
||||
for (int bz = minZ; bz <= maxZ; bz++) {
|
||||
writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static long overboreCandidateVolume(int[] bounds, int margin, int upExtension,
|
||||
int floorCut) {
|
||||
return inclusiveVolume(
|
||||
bounds[0] - margin, bounds[1] - floorCut, bounds[2] - margin,
|
||||
bounds[3] + margin, bounds[4] + upExtension, bounds[5] + margin);
|
||||
}
|
||||
|
||||
private static long inclusiveVolume(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
|
||||
long width = (long) maxX - minX + 1L;
|
||||
long height = (long) maxY - minY + 1L;
|
||||
long depth = (long) maxZ - minZ + 1L;
|
||||
if (width <= 0L || height <= 0L || depth <= 0L
|
||||
|| width > Long.MAX_VALUE / height
|
||||
|| width * height > Long.MAX_VALUE / depth) {
|
||||
return Long.MAX_VALUE;
|
||||
}
|
||||
return width * height * depth;
|
||||
}
|
||||
|
||||
private void clearIntersectingObjectTrees(MantleWriter writer, IrisStructureLocator.ResolvedPlacement resolved) {
|
||||
int mantleOffset = engine.getMinHeight();
|
||||
int worldHeight = engine.getHeight();
|
||||
Map<String, ObjectMarkerBounds> intersectingObjects = new HashMap<>();
|
||||
for (PlacedStructurePiece piece : resolved.pieces()) {
|
||||
for (IrisBlockVector local : piece.getObject().getBlocks().keys()) {
|
||||
PlatformBlockState structureState = piece.getObject().getBlocks().get(local);
|
||||
if (!isOccupiedStructureState(structureState)) {
|
||||
continue;
|
||||
}
|
||||
IrisBlockVector rotated = piece.getRotation().rotate(local.clone());
|
||||
int y = piece.getY() - mantleOffset + rotated.getBlockY();
|
||||
if (y >= 0 && y < worldHeight) {
|
||||
collectIntersectingObjectTreeMarker(
|
||||
writer, piece.getX() + rotated.getBlockX(), y,
|
||||
piece.getZ() + rotated.getBlockZ(), intersectingObjects);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, ObjectMarkerBounds> entry : intersectingObjects.entrySet()) {
|
||||
clearMarkerOwnedObject(writer, entry.getKey(), entry.getValue(), worldHeight);
|
||||
}
|
||||
}
|
||||
|
||||
static boolean isOccupiedStructureState(PlatformBlockState state) {
|
||||
return !B.isAir(state);
|
||||
}
|
||||
|
||||
private void collectIntersectingObjectTreeMarker(MantleWriter writer, int x, int y, int z,
|
||||
Map<String, ObjectMarkerBounds> intersectingObjects) {
|
||||
PlatformBlockState state = writer.getDataIfPresent(x, y, z, PlatformBlockState.class);
|
||||
if (state == null || !state.isTreeBlock()) {
|
||||
return;
|
||||
}
|
||||
String marker = writer.getDataIfPresent(x, y, z, String.class);
|
||||
if (isOrdinaryObjectMarker(marker)) {
|
||||
intersectingObjects.computeIfAbsent(marker, ignored -> new ObjectMarkerBounds())
|
||||
.include(x, y, z);
|
||||
}
|
||||
}
|
||||
|
||||
private void clearMarkerOwnedObject(MantleWriter writer, String marker,
|
||||
ObjectMarkerBounds intersections, int worldHeight) {
|
||||
StructurePlacementMarker.Decoded decoded = StructurePlacementMarker.decode(marker);
|
||||
if (decoded == null) {
|
||||
return;
|
||||
}
|
||||
IrisObject object = engine.getData().load(IrisObject.class, decoded.objectKey(), false);
|
||||
if (object == null) {
|
||||
return;
|
||||
}
|
||||
int horizontalSpan = Math.max(1, Math.max(object.getW(), object.getD()));
|
||||
int verticalSpan = Math.max(1, object.getH());
|
||||
ObjectMarkerBounds search = intersections.expand(horizontalSpan - 1, verticalSpan - 1, worldHeight);
|
||||
KList<ObjectBlockPosition> positions = new KList<>();
|
||||
int minChunkX = Math.floorDiv(search.minX, 16);
|
||||
int maxChunkX = Math.floorDiv(search.maxX, 16);
|
||||
int minChunkZ = Math.floorDiv(search.minZ, 16);
|
||||
int maxChunkZ = Math.floorDiv(search.maxZ, 16);
|
||||
for (int chunkX = minChunkX; chunkX <= maxChunkX; chunkX++) {
|
||||
for (int chunkZ = minChunkZ; chunkZ <= maxChunkZ; chunkZ++) {
|
||||
MantleChunk<Matter> chunk = writer.acquireChunk(chunkX, chunkZ);
|
||||
if (chunk == null) {
|
||||
continue;
|
||||
}
|
||||
int blockX = chunkX << 4;
|
||||
int blockZ = chunkZ << 4;
|
||||
chunk.iterate(String.class, (localX, y, localZ, value) -> {
|
||||
int x = blockX + localX;
|
||||
int z = blockZ + localZ;
|
||||
if (marker.equals(value) && search.contains(x, y, z)) {
|
||||
positions.add(new ObjectBlockPosition(x, y, z));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
for (ObjectBlockPosition position : positions) {
|
||||
writer.clearBlock(position.x(), position.y(), position.z());
|
||||
writer.clearData(position.x(), position.y(), position.z(), String.class);
|
||||
writer.clearData(position.x(), position.y(), position.z(), TreeBlockMaterial.class);
|
||||
writer.clearData(position.x(), position.y(), position.z(), TileWrapper.class);
|
||||
writer.clearData(position.x(), position.y(), position.z(), MatterStructurePOI.class);
|
||||
}
|
||||
}
|
||||
|
||||
static boolean isOrdinaryObjectMarker(String marker) {
|
||||
StructurePlacementMarker.Decoded decoded = StructurePlacementMarker.decode(marker);
|
||||
return decoded != null && !decoded.structureAware();
|
||||
}
|
||||
|
||||
static ObjectMarkerBounds markerSearchBounds(int minX, int minY, int minZ,
|
||||
int maxX, int maxY, int maxZ,
|
||||
int horizontalSpan, int verticalSpan,
|
||||
int worldHeight) {
|
||||
ObjectMarkerBounds bounds = new ObjectMarkerBounds();
|
||||
bounds.minX = minX;
|
||||
bounds.minY = minY;
|
||||
bounds.minZ = minZ;
|
||||
bounds.maxX = maxX;
|
||||
bounds.maxY = maxY;
|
||||
bounds.maxZ = maxZ;
|
||||
return bounds.expand(
|
||||
Math.max(0, horizontalSpan - 1), Math.max(0, verticalSpan - 1), worldHeight);
|
||||
}
|
||||
|
||||
private int[] computePieceBounds(KList<PlacedStructurePiece> pieces) {
|
||||
if (pieces == null || pieces.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
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 (PlacedStructurePiece p : pieces) {
|
||||
minX = Math.min(minX, p.getMinX());
|
||||
minY = Math.min(minY, p.getMinY());
|
||||
minZ = Math.min(minZ, p.getMinZ());
|
||||
maxX = Math.max(maxX, p.getMaxX());
|
||||
maxY = Math.max(maxY, p.getMaxY());
|
||||
maxZ = Math.max(maxZ, p.getMaxZ());
|
||||
}
|
||||
return new int[]{minX, minY, minZ, maxX, maxY, maxZ};
|
||||
}
|
||||
|
||||
private int placeObject(MantleWriter writer, IrisStructure structure, PlacedStructurePiece p,
|
||||
ObjectPlaceMode mode, int y, RNG rng, Long2IntOpenHashMap foundationColumns,
|
||||
boolean supportNonOccluding) {
|
||||
IrisObject object = p.getObject();
|
||||
String objectKey = object.getLoadKey();
|
||||
IrisObjectPlacement config = structure.createLootPlacement(objectKey);
|
||||
config.setMode(mode);
|
||||
config.setRotation(p.getRotation());
|
||||
if (!structure.getEdit().isEmpty()) {
|
||||
config.setEdit(structure.getEdit());
|
||||
}
|
||||
if (!mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) {
|
||||
config.setForcePlace(true);
|
||||
}
|
||||
int placeY = (y == -1) ? -1 : y - engine.getMinHeight();
|
||||
String marker = structurePlacementMarker(structure, p, objectKey);
|
||||
return object.place(p.getX(), placeY, p.getZ(), writer, config, rng, (position, state) -> {
|
||||
StructureFoundationPlanner.recordBaseCell(
|
||||
foundationColumns, position.getX(), position.getY(), position.getZ(), state,
|
||||
supportNonOccluding);
|
||||
if (marker != null && shouldWriteStructureMarker(state)) {
|
||||
writer.setData(position.getX(), position.getY(), position.getZ(), marker);
|
||||
}
|
||||
}, null, engine.getData());
|
||||
}
|
||||
|
||||
static boolean shouldWriteStructureMarker(PlatformBlockState state) {
|
||||
return state != null && state.isStorageChest();
|
||||
}
|
||||
|
||||
static int structurePlacementId(String structureKey, String objectKey, int x, int y, int z) {
|
||||
int hash = 17;
|
||||
hash = 31 * hash + structureKey.hashCode();
|
||||
hash = 31 * hash + objectKey.hashCode();
|
||||
hash = 31 * hash + x;
|
||||
hash = 31 * hash + y;
|
||||
hash = 31 * hash + z;
|
||||
return hash & Integer.MAX_VALUE;
|
||||
}
|
||||
|
||||
private static String structurePlacementMarker(IrisStructure structure, PlacedStructurePiece piece, String objectKey) {
|
||||
String structureKey = structure.getLoadKey();
|
||||
if (structureKey == null || structureKey.isBlank() || objectKey == null || objectKey.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
int placementId = structurePlacementId(structureKey, objectKey, piece.getX(), piece.getY(), piece.getZ());
|
||||
return StructurePlacementMarker.encodeStructure(objectKey, placementId, structureKey);
|
||||
}
|
||||
|
||||
/** How far, in blocks along X and Z, placements may write beyond their chunk. */
|
||||
public int reach() {
|
||||
IrisDimension dimension = engine.getDimension();
|
||||
int maxBlocks = 0;
|
||||
|
||||
for (IrisRegion region : dimension.getAllRegions(engine)) {
|
||||
maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(region)));
|
||||
}
|
||||
for (IrisBiome biome : dimension.getReachableBiomes(engine)) {
|
||||
maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(biome)));
|
||||
}
|
||||
maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(dimension)));
|
||||
|
||||
return maxBlocks;
|
||||
}
|
||||
|
||||
private int maxBlocksFrom(List<StructurePlacement> placements) {
|
||||
int max = 0;
|
||||
for (StructurePlacement placement : placements) {
|
||||
if (!placement.hasIrisStructures()) {
|
||||
continue;
|
||||
}
|
||||
StructureTerrain terrain = placement.resolvedTerrain();
|
||||
int carvePadding = terrain.resolvedMode() == StructureTerrainMode.FORCE_CARVE
|
||||
|| terrain.resolvedMode() == StructureTerrainMode.BORE
|
||||
? Math.max(0, terrain.horizontalPadding()) : 0;
|
||||
for (String key : placement.structures()) {
|
||||
IrisStructure structure = StructureResources.structure(engine.getData(), key);
|
||||
if (structure != null) {
|
||||
max = Math.max(max, Math.max(1, structure.getMaxSizeChunks()) * 16 + carvePadding);
|
||||
}
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
static final class ObjectMarkerBounds {
|
||||
private int minX = Integer.MAX_VALUE;
|
||||
private int minY = Integer.MAX_VALUE;
|
||||
private int minZ = Integer.MAX_VALUE;
|
||||
private int maxX = Integer.MIN_VALUE;
|
||||
private int maxY = Integer.MIN_VALUE;
|
||||
private int maxZ = Integer.MIN_VALUE;
|
||||
|
||||
void include(int x, int y, int z) {
|
||||
minX = Math.min(minX, x);
|
||||
minY = Math.min(minY, y);
|
||||
minZ = Math.min(minZ, z);
|
||||
maxX = Math.max(maxX, x);
|
||||
maxY = Math.max(maxY, y);
|
||||
maxZ = Math.max(maxZ, z);
|
||||
}
|
||||
|
||||
ObjectMarkerBounds expand(int horizontal, int vertical, int worldHeight) {
|
||||
ObjectMarkerBounds expanded = new ObjectMarkerBounds();
|
||||
expanded.minX = minX - horizontal;
|
||||
expanded.minY = Math.max(0, minY - vertical);
|
||||
expanded.minZ = minZ - horizontal;
|
||||
expanded.maxX = maxX + horizontal;
|
||||
expanded.maxY = Math.min(worldHeight - 1, maxY + vertical);
|
||||
expanded.maxZ = maxZ + horizontal;
|
||||
return expanded;
|
||||
}
|
||||
|
||||
boolean contains(int x, int y, int z) {
|
||||
return x >= minX && x <= maxX
|
||||
&& y >= minY && y <= maxY
|
||||
&& z >= minZ && z <= maxZ;
|
||||
}
|
||||
|
||||
int minX() {
|
||||
return minX;
|
||||
}
|
||||
|
||||
int minY() {
|
||||
return minY;
|
||||
}
|
||||
|
||||
int minZ() {
|
||||
return minZ;
|
||||
}
|
||||
|
||||
int maxX() {
|
||||
return maxX;
|
||||
}
|
||||
|
||||
int maxY() {
|
||||
return maxY;
|
||||
}
|
||||
|
||||
int maxZ() {
|
||||
return maxZ;
|
||||
}
|
||||
}
|
||||
|
||||
private record ObjectBlockPosition(int x, int y, int z) {
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package art.arcane.iris.engine.object.annotations;
|
||||
|
||||
import art.arcane.iris.engine.framework.ListFunction;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
|
||||
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 RegistryListFunction {
|
||||
Class<? extends ListFunction<KList<String>>> value();
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package art.arcane.iris.engine.object.annotations.functions;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.MantleStageFlags;
|
||||
import art.arcane.iris.engine.framework.ListFunction;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.mantle.flag.MantleFlag;
|
||||
|
||||
/**
|
||||
* What studio offers for a dimension's {@code disabledComponents}: the flags of Iris's own mantle stages, such as
|
||||
* {@code CARVED} for caves, then the ids of the pack's mantle stages.
|
||||
*/
|
||||
public class ComponentFlagFunction implements ListFunction<KList<String>> {
|
||||
@Override
|
||||
public String key() {
|
||||
return "component-flag";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String fancyName() {
|
||||
return "Component Flag";
|
||||
}
|
||||
|
||||
@Override
|
||||
public KList<String> apply(IrisData data) {
|
||||
KList<String> names = MantleStageFlags.builtIn().stream().map(MantleFlag::toString).collect(KList.collector());
|
||||
names.addAll(MantleStageFlags.packStageIds(data.getModules().pack().mantle().stages()));
|
||||
return names;
|
||||
}
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package art.arcane.iris.engine.object.annotations.functions;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.framework.ListFunction;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
|
||||
public class LootTableKeyFunction implements ListFunction<KList<String>> {
|
||||
@Override
|
||||
public String key() {
|
||||
return "loot-table-key";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String fancyName() {
|
||||
return "LootTable Key";
|
||||
}
|
||||
|
||||
@Override
|
||||
public KList<String> apply(IrisData data) {
|
||||
return new KList<>(IrisPlatforms.get().registries().lootTableKeys());
|
||||
}
|
||||
}
|
||||
@@ -1,381 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.compatibility;
|
||||
|
||||
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
|
||||
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import com.google.gson.Gson;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.io.IO;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import lombok.Data;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
@Data
|
||||
public class IrisCompat {
|
||||
private KList<IrisCompatabilityBlockFilter> blockFilters;
|
||||
private KList<IrisCompatabilityItemFilter> itemFilters;
|
||||
|
||||
public IrisCompat() {
|
||||
blockFilters = getDefaultBlockCompatabilityFilters();
|
||||
itemFilters = getDefaultItemCompatabilityFilters();
|
||||
}
|
||||
|
||||
public static IrisCompat configured(File f) {
|
||||
IrisCompat def = new IrisCompat();
|
||||
String defa = new JSONObject(new Gson().toJson(def)).toString(4);
|
||||
J.attemptAsync(() -> IO.writeAll(new File(f.getParentFile(), "compat.default.json"), defa));
|
||||
|
||||
|
||||
if (!f.exists()) {
|
||||
J.a(() -> {
|
||||
try {
|
||||
IO.writeAll(f, defa);
|
||||
} catch (IOException e) {
|
||||
IrisLogging.error("Failed to writeNodeData to compat file");
|
||||
IrisLogging.reportError(e);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// If the file doesn't exist, no additional mappings are present outside default
|
||||
// so we shouldn't try getting them
|
||||
try {
|
||||
IrisCompat rea = new Gson().fromJson(IO.readAll(f), IrisCompat.class);
|
||||
|
||||
for (IrisCompatabilityBlockFilter i : rea.getBlockFilters()) {
|
||||
def.getBlockFilters().add(i);
|
||||
}
|
||||
|
||||
for (IrisCompatabilityItemFilter i : rea.getItemFilters()) {
|
||||
def.getItemFilters().add(i);
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
}
|
||||
}
|
||||
|
||||
return def;
|
||||
}
|
||||
|
||||
private static KList<IrisCompatabilityItemFilter> getDefaultItemCompatabilityFilters() {
|
||||
KList<IrisCompatabilityItemFilter> filters = new KList<>();
|
||||
|
||||
// Below 1.16
|
||||
filters.add(new IrisCompatabilityItemFilter("NETHERITE_HELMET", "DIAMOND_HELMET"));
|
||||
filters.add(new IrisCompatabilityItemFilter("NETHERITE_CHESTPLATE", "DIAMOND_CHESTPLATE"));
|
||||
filters.add(new IrisCompatabilityItemFilter("NETHERITE_BOOTS", "DIAMOND_BOOTS"));
|
||||
filters.add(new IrisCompatabilityItemFilter("NETHERITE_LEGGINGS", "DIAMOND_LEGGINGS"));
|
||||
filters.add(new IrisCompatabilityItemFilter("MUSIC_DISC_PIGSTEP", "MUSIC_DISC_FAR"));
|
||||
filters.add(new IrisCompatabilityItemFilter("NETHERITE_SWORD", "DIAMOND_SWORD"));
|
||||
filters.add(new IrisCompatabilityItemFilter("NETHERITE_AXE", "DIAMOND_AXE"));
|
||||
filters.add(new IrisCompatabilityItemFilter("NETHERITE_PICKAXE", "DIAMOND_PICKAXE"));
|
||||
filters.add(new IrisCompatabilityItemFilter("NETHERITE_HOE", "DIAMOND_HOE"));
|
||||
filters.add(new IrisCompatabilityItemFilter("NETHERITE_SHOVEL", "DIAMOND_SHOVEL"));
|
||||
filters.add(new IrisCompatabilityItemFilter("NETHERITE_INGOT", "DIAMOND"));
|
||||
filters.add(new IrisCompatabilityItemFilter("PIGLIN_BANNER_PATTERN", "PORKCHOP"));
|
||||
filters.add(new IrisCompatabilityItemFilter("NETHERITE_SCRAP", "GOLD_INGOT"));
|
||||
filters.add(new IrisCompatabilityItemFilter("WARPED_FUNGUS_ON_A_STICK", "CARROT_ON_A_STICK"));
|
||||
|
||||
// Below 1.15
|
||||
filters.add(new IrisCompatabilityItemFilter("HONEY_BOTTLE", "GLASS_BOTTLE"));
|
||||
filters.add(new IrisCompatabilityItemFilter("HONEYCOMB", "GLASS"));
|
||||
|
||||
// Below 1.14
|
||||
filters.add(new IrisCompatabilityItemFilter("SWEET_BERRIES", "APPLE"));
|
||||
filters.add(new IrisCompatabilityItemFilter("SUSPICIOUS_STEW", "MUSHROOM_STEW"));
|
||||
filters.add(new IrisCompatabilityItemFilter("BLACK_DYE", "INK_SAC"));
|
||||
filters.add(new IrisCompatabilityItemFilter("WHITE_DYE", "BONE_MEAL"));
|
||||
filters.add(new IrisCompatabilityItemFilter("BROWN_DYE", "COCOA_BEANS"));
|
||||
filters.add(new IrisCompatabilityItemFilter("BLUE_DYE", "LAPIS_LAZULI"));
|
||||
filters.add(new IrisCompatabilityItemFilter("CROSSBOW", "BOW"));
|
||||
filters.add(new IrisCompatabilityItemFilter("FLOWER_BANNER_PATTERN", "CORNFLOWER"));
|
||||
filters.add(new IrisCompatabilityItemFilter("SKULL_BANNER_PATTERN", "BONE"));
|
||||
filters.add(new IrisCompatabilityItemFilter("GLOBE_BANNER_PATTERN", "WHEAT_SEEDS"));
|
||||
filters.add(new IrisCompatabilityItemFilter("MOJANG_BANNER_PATTERN", "DIRT"));
|
||||
filters.add(new IrisCompatabilityItemFilter("CREEPER_BANNER_PATTERN", "CREEPER_HEAD"));
|
||||
|
||||
return filters;
|
||||
}
|
||||
|
||||
private static KList<IrisCompatabilityBlockFilter> getDefaultBlockCompatabilityFilters() {
|
||||
KList<IrisCompatabilityBlockFilter> filters = new KList<>();
|
||||
|
||||
filters.add(new IrisCompatabilityBlockFilter("CHAIN", "IRON_CHAIN"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("GRASS", "SHORT_GRASS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SHORT_GRASS", "GRASS"));
|
||||
|
||||
// Below 1.16
|
||||
filters.add(new IrisCompatabilityBlockFilter("WEEPING_VINES", "NETHER_FENCE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("WEEPING_VINES_PLANT", "NETHER_FENCE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("WARPED_WART_BLOCK", "NETHER_WART_BLOCK"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("TWISTING_VINES", "BAMBOO"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("TWISTING_VINES_PLANT", "BAMBOO"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("TARGET", "COBBLESTONE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SOUL_SOIL", "SOULSAND"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SOUL_TORCH", "TORCH"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SOUL_LANTERN", "LANTERN"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SOUL_FIRE", "FIRE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SOUL_CAMPFIRE", "CAMPFIRE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SHROOMLIGHT", "GLOWSTONE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("RESPAWN_ANCHOR", "OBSIDIAN"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("NETHER_SPROUTS", "RED_MUSHROOM"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("NETHER_GOLD_ORE", "GOLD_ORE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("LODESTONE", "STONE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("STRIPPED_WARPED_HYPHAE", "BROWN_MUSHROOM_BLOCK"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("STRIPPED_CRIMSON_HYPHAE", "RED_MUSHROOM_BLOCK"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("WARPED_HYPHAE", "MUSHROOM_STEM"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_HYPHAE", "RED_MUSHROOM_BLOCK"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("GILDED_BLACKSTONE", "COBBLESTONE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CRYING_OBSIDIAN", "OBSIDIAN"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("STRIPPED_WARPED_STEM", "MUSHROOM_STEM"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("STRIPPED_CRIMSON_STEM", "MUSHROOM_STEM"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("WARPED_STEM", "MUSHROOM_STEM"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_STEM", "MUSHROOM_STEM"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_ROOTS", "RED_MUSHROOM"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("WARPED_ROOTS", "BROWN_MUSHROOM"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_PLANKS", "OAK_PLANKS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("WARPED_PLANKS", "OAK_PLANKS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("WARPED_NYLIUM", "MYCELIUM"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_NYLIUM", "MYCELIUM"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("WARPED_FUNGUS", "BROWN_MUSHROOM"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_FUNGUS", "RED_MUSHROOM"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CRACKED_NETHER_BRICKS", "NETHER_BRICKS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CHISELED_NETHER_BRICKS", "NETHER_BRICKS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("NETHER_FENCE", "LEGACY_NETHER_FENCE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("IRON_CHAIN", "IRON_BARS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("NETHERITE_BLOCK", "QUARTZ_BLOCK"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("BLACKSTONE", "COBBLESTONE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("BASALT", "STONE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("ANCIENT_DEBRIS", "NETHERRACK"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("NETHERRACK", "LEGACY_NETHERRACK"));
|
||||
|
||||
// Below 1.15
|
||||
filters.add(new IrisCompatabilityBlockFilter("HONEY_BLOCK", "OAK_LEAVES"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("BEEHIVE", "OAK_LEAVES"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("BEE_NEST", "OAK_LEAVES"));
|
||||
|
||||
// Below 1.14
|
||||
filters.add(new IrisCompatabilityBlockFilter("GRANITE_WALL", "COBBLESTONE_WALL"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("BLUE_ICE", "PACKED_ICE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("DIORITE_WALL", "COBBLESTONE_WALL"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("ANDESITE_WALL", "COBBLESTONE_WALL"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SWEET_BERRY_BUSH", "GRASS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("STONECUTTER", "CRAFTING_TABLE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SANDSTONE_STAIRS", "LEGACY_SANDSTONE_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SMOOTH_SANDSTONE_STAIRS", "LEGACY_SANDSTONE_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("MOSSY_COBBLESTONE_STAIRS", "COBBLESTONE_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("MOSSY_STONE_BRICK_STAIRS", "STONE_BRICK_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("POLISHED_GRANITE_STAIRS", "COBBLESTONE_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("GRANITE_STAIRS", "COBBLESTONE_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("POLISHED_DIORITE_STAIRS", "COBBLESTONE_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("DIORITE_STAIRS", "COBBLESTONE_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("POLISHED_ANDESITE_STAIRS", "COBBLESTONE_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("ANDESITE_STAIRS", "COBBLESTONE_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("STONE_STAIRS", "COBBLESTONE_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("END_STONE_BRICK_STAIRS", "LEGACY_SANDSTONE_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("NETHER_BRICK_STAIRS", "LEGACY_NETHER_BRICK_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("RED_NETHER_BRICK_STAIRS", "NETHER_BRICK_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SMOOTH_QUARTZ_STAIRS", "LEGACY_QUARTZ_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("QUARTZ_STAIRS", "LEGACY_QUARTZ_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("RED_SANDSTONE_STAIRS", "LEGACY_RED_SANDSTONE_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SMOOTH_RED_SANDSTONE_STAIRS", "LEGACY_RED_SANDSTONE_STAIRS"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("STONE_SLAB", "SMOOTH_STONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SMOKER", "FURNACE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SMITHING_TABLE", "CRAFTING_TABLE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("END_STONE_BRICK_SLAB", "SANDSTONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("RED_NETHER_BRICK_SLAB", "NETHER_BRICK_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SMOOTH_QUARTZ_SLAB", "QUARTZ_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CUT_SANDSTONE_SLAB", "SANDSTONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CUT_RED_SANDSTONE_SLAB", "RED_SANDSTONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SMOOTH_RED_SANDSTONE_SLAB", "RED_SANDSTONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SMOOTH_SANDSTONE_SLAB", "SANDSTONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("MOSSY_COBBLESTONE_SLAB", "COBBLESTONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("MOSSY_STONE_BRICK_SLAB", "STONE_BRICK_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("STONE_SLAB", "SMOOTH_STONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("ANDESITE_SLAB", "COBBLESTONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("ANDESITE_SLAB", "COBBLESTONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("DIORITE_SLAB", "COBBLESTONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("GRANITE_SLAB", "COBBLESTONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("POLISHED_ANDESITE_SLAB", "SMOOTH_STONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("POLISHED_DIORITE_SLAB", "SMOOTH_STONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("POLISHED_GRANITE_SLAB", "SMOOTH_STONE_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("WARPED_WALL_SIGN", "LEGACY_WALL_SIGN"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("WARPED_SIGN", "LEGACY_SIGN_POST"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SPRUCE_WALL_SIGN", "LEGACY_WALL_SIGN"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SPRUCE_SIGN", "LEGACY_SIGN_POST"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("OAK_WALL_SIGN", "LEGACY_WALL_SIGN"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("OAK_SIGN", "LEGACY_SIGN_POST"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("JUNGLE_WALL_SIGN", "LEGACY_WALL_SIGN"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("JUNGLE_SIGN", "LEGACY_SIGN_POST"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("DARK_OAK_WALL_SIGN", "LEGACY_WALL_SIGN"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("DARK_OAK_SIGN", "LEGACY_SIGN_POST"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_WALL_SIGN", "LEGACY_WALL_SIGN"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_SIGN", "LEGACY_SIGN_POST"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("BIRCH_WALL_SIGN", "LEGACY_WALL_SIGN"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("BIRCH_SIGN", "LEGACY_SIGN_POST"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("ACACIA_WALL_SIGN", "LEGACY_WALL_SIGN"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("ACACIA_SIGN", "LEGACY_SIGN_POST"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("SCAFFOLDING", "BIRCH_FENCE"));
|
||||
//filters.add(new IrisCompatabilityBlockFilter("LOOM", "LOOM"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("LECTERN", "BOOKSHELF"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("LANTERN", "REDSTONE_LAMP"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("JIGSAW", "AIR"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("GRINDSTONE", "COBBLESTONE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("FLETCHING_TABLE", "CRAFTING_TABLE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("COMPOSTER", "CHEST"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CARTOGRAPHY_TABLE", "CRAFTING_TABLE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("CAMPFIRE", "DARK_OAK_SLAB"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("BLAST_FURNACE", "FURNACE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("BELL", "REDSTONE_LAMP"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=south]", "minecraft:hay_bale[axis=z]", true));
|
||||
filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=north]", "minecraft:hay_bale[axis=z]", true));
|
||||
filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=east]", "minecraft:hay_bale[axis=x]", true));
|
||||
filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=west]", "minecraft:hay_bale[axis=x]", true));
|
||||
filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=up]", "minecraft:hay_bale[axis=y]", true));
|
||||
filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=down]", "minecraft:hay_bale[axis=y]", true));
|
||||
filters.add(new IrisCompatabilityBlockFilter("BAMBOO", "BIRCH_FENCE"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("BAMBOO_SAPLING", "BIRCH_SAPLING"));
|
||||
filters.add(new IrisCompatabilityBlockFilter("POTTED_BAMBOO", "POTTED_BIRCH_SAPLING"));
|
||||
|
||||
return filters;
|
||||
}
|
||||
|
||||
public BlockData getBlock(String n) {
|
||||
String buf = n;
|
||||
int err = 16;
|
||||
|
||||
BlockData tx = BukkitBlockResolution.getOrNull(buf, false);
|
||||
|
||||
if (tx != null) {
|
||||
return tx;
|
||||
}
|
||||
|
||||
searching:
|
||||
while (true) {
|
||||
if (err-- <= 0) {
|
||||
IrisLogging.warnOnce("compat-block:" + n, "Can't find block data for " + n + "; using STONE.");
|
||||
return BukkitBlockResolution.getNoCompat("STONE");
|
||||
}
|
||||
String m = buf;
|
||||
if (m.contains("[")) {
|
||||
m = m.split("\\Q[\\E")[0];
|
||||
}
|
||||
if (m.contains(":")) {
|
||||
m = m.split("\\Q:\\E", 2)[1];
|
||||
}
|
||||
|
||||
for (IrisCompatabilityBlockFilter i : blockFilters) {
|
||||
if (i.getWhen().equalsIgnoreCase(i.isExact() ? buf : m)) {
|
||||
BlockData b = i.getReplace();
|
||||
|
||||
if (b != null) {
|
||||
return b;
|
||||
}
|
||||
|
||||
buf = i.getSupplement();
|
||||
continue searching;
|
||||
}
|
||||
}
|
||||
|
||||
IrisLogging.warnOnce("compat-block:" + n, "Can't find block data for " + n + "; using STONE.");
|
||||
return BukkitBlockResolution.getNoCompat("STONE");
|
||||
}
|
||||
}
|
||||
|
||||
public Material getItem(String n) {
|
||||
String buf = n;
|
||||
int err = 16;
|
||||
Material txf = BukkitBlockResolution.getMaterialOrNull(buf);
|
||||
|
||||
if (txf != null) {
|
||||
return txf;
|
||||
}
|
||||
|
||||
int nomore = 64;
|
||||
|
||||
searching:
|
||||
while (true) {
|
||||
if (nomore < 0) {
|
||||
return BukkitBlockResolution.getMaterial("STONE");
|
||||
}
|
||||
|
||||
nomore--;
|
||||
if (err-- <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
for (IrisCompatabilityItemFilter i : itemFilters) {
|
||||
if (i.getWhen().equalsIgnoreCase(buf)) {
|
||||
Material b = i.getReplace();
|
||||
|
||||
if (b != null) {
|
||||
return b;
|
||||
}
|
||||
|
||||
buf = i.getSupplement();
|
||||
continue searching;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
buf = n;
|
||||
BlockData tx = BukkitBlockResolution.getOrNull(buf, false);
|
||||
|
||||
if (tx != null) {
|
||||
return tx.getMaterial();
|
||||
}
|
||||
nomore = 64;
|
||||
|
||||
searching:
|
||||
while (true) {
|
||||
if (nomore < 0) {
|
||||
return BukkitBlockResolution.getMaterial("STONE");
|
||||
}
|
||||
|
||||
nomore--;
|
||||
|
||||
if (err-- <= 0) {
|
||||
return BukkitBlockResolution.getMaterial("STONE");
|
||||
}
|
||||
|
||||
for (IrisCompatabilityBlockFilter i : blockFilters) {
|
||||
if (i.getWhen().equalsIgnoreCase(buf)) {
|
||||
BlockData b = i.getReplace();
|
||||
|
||||
if (b != null) {
|
||||
return b.getMaterial();
|
||||
}
|
||||
|
||||
buf = i.getSupplement();
|
||||
continue searching;
|
||||
}
|
||||
}
|
||||
|
||||
return BukkitBlockResolution.getMaterial("STONE");
|
||||
}
|
||||
}
|
||||
}
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.compatibility;
|
||||
|
||||
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
|
||||
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.engine.object.annotations.Required;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("Find and replace object materials for compatability")
|
||||
@Data
|
||||
public class IrisCompatabilityBlockFilter {
|
||||
private final transient AtomicCache<BlockData> findData = new AtomicCache<>(true);
|
||||
private final transient AtomicCache<BlockData> replaceData = new AtomicCache<>(true);
|
||||
@Required
|
||||
@Desc("When iris sees this block, and it's not reconized")
|
||||
private String when = "";
|
||||
@Required
|
||||
@Desc("Replace it with this block. Dont worry if this block is also not reconized, iris repeat this compat check.")
|
||||
private String supplement = "";
|
||||
@Desc("If exact is true, it compares block data for example minecraft:some_log[axis=x]")
|
||||
private boolean exact = false;
|
||||
|
||||
public IrisCompatabilityBlockFilter(String when, String supplement) {
|
||||
this(when, supplement, false);
|
||||
}
|
||||
|
||||
public BlockData getFind() {
|
||||
return findData.aquire(() -> BukkitBlockResolution.get(when));
|
||||
}
|
||||
|
||||
public BlockData getReplace() {
|
||||
return replaceData.aquire(() ->
|
||||
{
|
||||
BlockData b = BukkitBlockResolution.getOrNull(supplement, false);
|
||||
|
||||
if (b == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
IrisLogging.warn("Compat: Using '%s' in place of '%s' since this server doesnt support '%s'", supplement, when, when);
|
||||
|
||||
return b;
|
||||
});
|
||||
}
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.compatibility;
|
||||
|
||||
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
|
||||
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.engine.object.annotations.Required;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.bukkit.Material;
|
||||
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@Desc("Find and replace object items for compatability")
|
||||
@Data
|
||||
public class IrisCompatabilityItemFilter {
|
||||
private final transient AtomicCache<Material> findData = new AtomicCache<>(true);
|
||||
private final transient AtomicCache<Material> replaceData = new AtomicCache<>(true);
|
||||
@Required
|
||||
@Desc("When iris sees this block, and it's not reconized")
|
||||
private String when = "";
|
||||
@Required
|
||||
@Desc("Replace it with this block. Dont worry if this block is also not reconized, iris repeat this compat check.")
|
||||
private String supplement = "";
|
||||
|
||||
public IrisCompatabilityItemFilter(String when, String supplement) {
|
||||
this.when = when;
|
||||
this.supplement = supplement;
|
||||
}
|
||||
|
||||
public Material getFind() {
|
||||
return findData.aquire(() -> BukkitBlockResolution.getMaterial(when));
|
||||
}
|
||||
|
||||
public Material getReplace() {
|
||||
return replaceData.aquire(() ->
|
||||
{
|
||||
Material b = BukkitBlockResolution.getMaterialOrNull(supplement);
|
||||
|
||||
if (b == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
IrisLogging.debug("Compat: Using " + supplement + " in place of " + when + " since this server doesnt support '" + supplement + "'");
|
||||
|
||||
return b;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.image;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
|
||||
import java.awt.image.ColorModel;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.awt.image.IndexColorModel;
|
||||
import java.awt.image.Raster;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class IrisImage extends IrisRegistrant {
|
||||
private final BufferedImage image;
|
||||
private final Raster raster;
|
||||
private final ColorModel colorModel;
|
||||
private final String format;
|
||||
|
||||
public IrisImage() {
|
||||
this(new BufferedImage(4, 4, BufferedImage.TYPE_INT_RGB), "png");
|
||||
}
|
||||
|
||||
public IrisImage(BufferedImage image) {
|
||||
this(image, "png");
|
||||
}
|
||||
|
||||
public IrisImage(BufferedImage image, String format) {
|
||||
this.image = Objects.requireNonNull(image, "IrisImage requires a decoded image (the source file was unreadable or not an image)");
|
||||
this.raster = image.getRaster();
|
||||
this.colorModel = image.getColorModel();
|
||||
this.format = Objects.requireNonNull(format, "Image format").toLowerCase();
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return image.getWidth();
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return image.getHeight();
|
||||
}
|
||||
|
||||
public String getFormat() {
|
||||
return format;
|
||||
}
|
||||
|
||||
public IrisImageColorMode getColorMode() {
|
||||
if (colorModel instanceof IndexColorModel) {
|
||||
return IrisImageColorMode.INDEXED;
|
||||
}
|
||||
int colorComponents = colorModel.getNumColorComponents();
|
||||
if (colorComponents == 1) {
|
||||
return colorModel.hasAlpha() ? IrisImageColorMode.UNSUPPORTED : IrisImageColorMode.GRAYSCALE;
|
||||
}
|
||||
if (colorComponents == 3) {
|
||||
return colorModel.hasAlpha() ? IrisImageColorMode.RGBA : IrisImageColorMode.RGB;
|
||||
}
|
||||
return IrisImageColorMode.UNSUPPORTED;
|
||||
}
|
||||
|
||||
public int getColorComponentCount() {
|
||||
return colorModel.getNumColorComponents();
|
||||
}
|
||||
|
||||
public int getChannelCount() {
|
||||
return raster.getNumBands();
|
||||
}
|
||||
|
||||
public int getBitDepth() {
|
||||
int[] sampleSizes = raster.getSampleModel().getSampleSize();
|
||||
int maximum = 0;
|
||||
int colorBands = Math.min(getColorComponentCount(), sampleSizes.length);
|
||||
for (int index = 0; index < colorBands; index++) {
|
||||
maximum = Math.max(maximum, sampleSizes[index]);
|
||||
}
|
||||
return maximum;
|
||||
}
|
||||
|
||||
public boolean hasAlpha() {
|
||||
return colorModel.hasAlpha();
|
||||
}
|
||||
|
||||
public double getBandNormalized(int x, int z, int band) {
|
||||
requireCoordinate(x, z);
|
||||
if (band < 0 || band >= raster.getNumBands()) {
|
||||
throw new IllegalArgumentException("Image band " + band + " is outside 0.." + (raster.getNumBands() - 1));
|
||||
}
|
||||
int bits = raster.getSampleModel().getSampleSize(band);
|
||||
long maximum = (1L << bits) - 1L;
|
||||
return raster.getSample(x, z, band) / (double) maximum;
|
||||
}
|
||||
|
||||
public int getBandSample(int x, int z, int band) {
|
||||
requireCoordinate(x, z);
|
||||
if (band < 0 || band >= raster.getNumBands()) {
|
||||
throw new IllegalArgumentException("Image band " + band + " is outside 0.." + (raster.getNumBands() - 1));
|
||||
}
|
||||
return raster.getSample(x, z, band);
|
||||
}
|
||||
|
||||
public double getAlphaNormalized(int x, int z) {
|
||||
requireCoordinate(x, z);
|
||||
if (!hasAlpha()) {
|
||||
return 1D;
|
||||
}
|
||||
int alphaBand = raster.getNumBands() - 1;
|
||||
return getBandNormalized(x, z, alphaBand);
|
||||
}
|
||||
|
||||
public int getRawRgb8(int x, int z) {
|
||||
requireCoordinate(x, z);
|
||||
IrisImageColorMode mode = getColorMode();
|
||||
if (mode != IrisImageColorMode.RGB && mode != IrisImageColorMode.RGBA) {
|
||||
throw new IllegalStateException("Raw RGB sampling requires an RGB or RGBA image, not " + mode);
|
||||
}
|
||||
int red = scaleTo8Bit(x, z, 0);
|
||||
int green = scaleTo8Bit(x, z, 1);
|
||||
int blue = scaleTo8Bit(x, z, 2);
|
||||
return red << 16 | green << 8 | blue;
|
||||
}
|
||||
|
||||
public int getPreviewArgb(int x, int z) {
|
||||
requireCoordinate(x, z);
|
||||
return image.getRGB(x, z);
|
||||
}
|
||||
|
||||
private int scaleTo8Bit(int x, int z, int band) {
|
||||
int bits = raster.getSampleModel().getSampleSize(band);
|
||||
int sample = raster.getSample(x, z, band);
|
||||
if (bits == 8) {
|
||||
return sample;
|
||||
}
|
||||
long maximum = (1L << bits) - 1L;
|
||||
return (int) Math.round(sample * 255D / maximum);
|
||||
}
|
||||
|
||||
private void requireCoordinate(int x, int z) {
|
||||
if (x < 0 || z < 0 || x >= getWidth() || z >= getHeight()) {
|
||||
throw new IndexOutOfBoundsException("Image coordinate " + x + "," + z + " is outside " + getWidth() + "x" + getHeight());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFolderName() {
|
||||
return "images";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeName() {
|
||||
return "Image";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
package art.arcane.iris.engine.object.image;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
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.volmlib.util.collection.KMap;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@Desc("A reusable typed image-map definition")
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
public class IrisImageMap extends IrisRegistrant {
|
||||
public static final double MINIMUM_SCALE = 0.000001D;
|
||||
public static final double MAXIMUM_COLOR_TOLERANCE = 441.672956D;
|
||||
|
||||
@RegistryListResource(IrisImage.class)
|
||||
@Desc("PNG source under images/, without the file extension")
|
||||
private String source = "";
|
||||
|
||||
@Desc("How source pixels are decoded")
|
||||
private IrisImageMapType type = IrisImageMapType.GRAYSCALE_HEIGHT;
|
||||
|
||||
@MinNumber(MINIMUM_SCALE)
|
||||
@Desc("Minecraft blocks represented by one source pixel")
|
||||
private double blocksPerPixel = 1D;
|
||||
|
||||
@Desc("Minecraft X/Z coordinate that maps to sourceOrigin")
|
||||
private IrisImageMapOrigin origin = new IrisImageMapOrigin();
|
||||
|
||||
@Desc("Source pixel X/Y coordinate placed at origin")
|
||||
private IrisImageMapOrigin sourceOrigin = new IrisImageMapOrigin();
|
||||
|
||||
@Desc("Clockwise quarter-turn rotation around sourceOrigin")
|
||||
private IrisImageMapRotation rotation = IrisImageMapRotation.DEG_0;
|
||||
|
||||
@Desc("Mirror image X around sourceOrigin before rotation")
|
||||
private boolean mirrorX = false;
|
||||
|
||||
@Desc("Mirror image Y around sourceOrigin before rotation")
|
||||
private boolean mirrorZ = false;
|
||||
|
||||
@Desc("Numeric sampling filter; exact color and binary maps require NEAREST")
|
||||
private IrisImageMapSampling sampling = IrisImageMapSampling.NEAREST;
|
||||
|
||||
@Desc("Behavior outside the source rectangle")
|
||||
private IrisImageMapOutOfBounds outOfBounds = IrisImageMapOutOfBounds.FALLBACK;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(1)
|
||||
@Desc("Normalized scalar used by FALLBACK coordinates")
|
||||
private double fallbackValue = 0D;
|
||||
|
||||
@Desc("Legend target used by FALLBACK or unknown color-map pixels")
|
||||
private String fallbackTarget = "";
|
||||
|
||||
@Desc("How alpha affects decoded data")
|
||||
private IrisImageMapAlpha alpha = IrisImageMapAlpha.IGNORE;
|
||||
|
||||
@Desc("Minimum absolute world Y for height maps")
|
||||
private double minimumHeight = -64D;
|
||||
|
||||
@Desc("Maximum absolute world Y for height maps")
|
||||
private double maximumHeight = 320D;
|
||||
|
||||
@Desc("Vertical block offset applied after height decoding")
|
||||
private double verticalOffset = 0D;
|
||||
|
||||
@Desc("Clamp decoded height to minimumHeight and maximumHeight after offset")
|
||||
private boolean clamp = true;
|
||||
|
||||
@Desc("Invert decoded scalar values before curve evaluation")
|
||||
private boolean inverted = false;
|
||||
|
||||
@MinNumber(MINIMUM_SCALE)
|
||||
@Desc("Power curve applied after optional inversion; 1 is linear")
|
||||
private double curveExponent = 1D;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(32)
|
||||
@Desc("Load-time box smoothing radius in source pixels")
|
||||
private int smoothingRadius = 0;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(1)
|
||||
@Desc("Binary mask threshold")
|
||||
private double threshold = 0.5D;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(1)
|
||||
@Desc("Mask transition width above threshold")
|
||||
private double falloff = 0D;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(MAXIMUM_COLOR_TOLERANCE)
|
||||
@Desc("Euclidean raw sRGB distance accepted by tolerant color matching; zero is exact")
|
||||
private double colorTolerance = 0D;
|
||||
|
||||
@Desc("How colors absent from the legend are handled")
|
||||
private IrisImageMapUnknownColor unknownColor = IrisImageMapUnknownColor.ERROR;
|
||||
|
||||
@Desc("Exact #RRGGBB colors mapped to Iris resource or Minecraft block keys")
|
||||
private KMap<String, String> colors = new KMap<>();
|
||||
|
||||
@Override
|
||||
public String getFolderName() {
|
||||
return "image-maps";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeName() {
|
||||
return "Image Map";
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package art.arcane.iris.engine.object.image;
|
||||
|
||||
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.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@Desc("Binds a reusable image map to one dimension generation role")
|
||||
@Data
|
||||
public class IrisImageMapBinding {
|
||||
@Desc("Unique name used by Studio previews and custom map lookups")
|
||||
private String key = "";
|
||||
|
||||
@RegistryListResource(IrisImageMap.class)
|
||||
@Desc("Image-map resource key under image-maps/")
|
||||
private String map = "";
|
||||
|
||||
@Desc("Generation input controlled by this binding")
|
||||
private IrisImageMapApplication application = IrisImageMapApplication.CUSTOM;
|
||||
|
||||
@ArrayType(type = IrisImageMapMask.class)
|
||||
@Desc("Named mask maps composed in declaration order")
|
||||
private KList<IrisImageMapMask> masks = new KList<>();
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package art.arcane.iris.engine.object.material;
|
||||
|
||||
import art.arcane.iris.platform.bukkit.BukkitBlockState;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
|
||||
public final class BlockDataMergeSupport {
|
||||
private static volatile StateMerger PLATFORM_MERGER = null;
|
||||
|
||||
private BlockDataMergeSupport() {
|
||||
}
|
||||
|
||||
public interface StateMerger {
|
||||
PlatformBlockState merge(PlatformBlockState base, PlatformBlockState update);
|
||||
}
|
||||
|
||||
public static synchronized StateMerger bindPlatformMerger(StateMerger merger) {
|
||||
StateMerger previous = PLATFORM_MERGER;
|
||||
PLATFORM_MERGER = Objects.requireNonNull(merger, "merger");
|
||||
return previous;
|
||||
}
|
||||
|
||||
public static synchronized void restorePlatformMerger(StateMerger merger) {
|
||||
PLATFORM_MERGER = merger;
|
||||
}
|
||||
|
||||
public static PlatformBlockState merge(PlatformBlockState base, PlatformBlockState update) {
|
||||
StateMerger merger = PLATFORM_MERGER;
|
||||
if (merger != null) {
|
||||
return merger.merge(base, update);
|
||||
}
|
||||
BlockData merged = merge((BlockData) base.nativeHandle(), (BlockData) update.nativeHandle(), BukkitBlockResolution::get);
|
||||
return merged == null ? null : BukkitBlockState.of(merged);
|
||||
}
|
||||
|
||||
static BlockData merge(BlockData base, BlockData update, Function<String, BlockData> resolver) {
|
||||
try {
|
||||
return base.merge(update);
|
||||
} catch (IllegalArgumentException e) {
|
||||
BlockData normalizedBase = resolve(base, resolver);
|
||||
BlockData normalizedUpdate = resolve(update, resolver);
|
||||
|
||||
if (normalizedBase != null && normalizedUpdate != null) {
|
||||
try {
|
||||
return normalizedBase.merge(normalizedUpdate);
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
return normalizedUpdate;
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedUpdate != null) {
|
||||
return normalizedUpdate;
|
||||
}
|
||||
|
||||
return update;
|
||||
}
|
||||
}
|
||||
|
||||
private static BlockData resolve(BlockData data, Function<String, BlockData> resolver) {
|
||||
if (data == null || resolver == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String serialized = data.getAsString(false);
|
||||
if (serialized == null || serialized.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return resolver.apply(serialized);
|
||||
}
|
||||
}
|
||||
@@ -1,237 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.material;
|
||||
|
||||
|
||||
import art.arcane.iris.engine.object.prefab.TileData;
|
||||
import art.arcane.iris.core.link.Identifier;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
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.RegistryListBlockType;
|
||||
import art.arcane.iris.engine.object.annotations.RegistryMapBlockState;
|
||||
import art.arcane.iris.engine.object.annotations.Required;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.collection.KMap;
|
||||
import art.arcane.iris.util.common.data.B;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("Represents Block Data")
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
public class IrisBlockData extends IrisRegistrant {
|
||||
private final transient AtomicCache<PlatformBlockState> blockdata = new AtomicCache<>();
|
||||
private final transient AtomicCache<String> realProperties = new AtomicCache<>();
|
||||
@RegistryListBlockType
|
||||
@Required
|
||||
@Desc("The block to use")
|
||||
private String block = "air";
|
||||
@Desc("Debug this block by printing it to the console when it's used. Must have debug turned on in settings.")
|
||||
private boolean debug = false;
|
||||
@MinNumber(1)
|
||||
@MaxNumber(1000)
|
||||
@Desc("The weight is used when this block data is inside of a list of blockdata. A weight of two is just as if you placed two of the same block data values in the same list making it more common when randomly picked.")
|
||||
private int weight = 1;
|
||||
@Desc("If the block cannot be created on this version, Iris will attempt to use this backup block data instead.")
|
||||
private IrisBlockData backup = null;
|
||||
@RegistryMapBlockState("block")
|
||||
@Desc("Optional properties for this block data such as 'waterlogged': true")
|
||||
private KMap<String, Object> data = new KMap<>();
|
||||
@Desc("Optional tile data for this block data")
|
||||
private KMap<String, Object> tileData = new KMap<>();
|
||||
|
||||
public IrisBlockData(String b) {
|
||||
this.block = b;
|
||||
}
|
||||
|
||||
public static IrisBlockData from(String j) {
|
||||
IrisBlockData b = new IrisBlockData();
|
||||
String v = j.toLowerCase().trim();
|
||||
|
||||
if (v.contains("[")) {
|
||||
KList<String> props = new KList<>();
|
||||
String rp = v.split("\\Q[\\E")[1].replaceAll("\\Q]\\E", "");
|
||||
b.setBlock(v.split("\\Q[\\E")[0]);
|
||||
|
||||
if (rp.contains(",")) {
|
||||
props.add(rp.split("\\Q,\\E"));
|
||||
} else {
|
||||
props.add(rp);
|
||||
}
|
||||
|
||||
for (String i : props) {
|
||||
Object kg = filter(i.split("\\Q=\\E")[1]);
|
||||
b.data.put(i.split("\\Q=\\E")[0], kg);
|
||||
}
|
||||
} else {
|
||||
b.setBlock(v);
|
||||
}
|
||||
|
||||
return b;
|
||||
}
|
||||
|
||||
private static Object filter(String string) {
|
||||
if (string.equals("true")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (string.equals("false")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return Integer.parseInt(string);
|
||||
} catch (Throwable ignored) {
|
||||
// Checks
|
||||
}
|
||||
|
||||
try {
|
||||
return Double.valueOf(string).intValue();
|
||||
} catch (Throwable ignored) {
|
||||
// Checks
|
||||
}
|
||||
|
||||
return string;
|
||||
}
|
||||
|
||||
public String computeProperties(KMap<String, Object> data) {
|
||||
if (data.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
KList<String> r = new KList<>();
|
||||
|
||||
for (Map.Entry<String, Object> entry : data.entrySet()) {
|
||||
r.add(entry.getKey() + "=" + filter(entry.getValue().toString()));
|
||||
}
|
||||
|
||||
return "[" + r.toString(",") + "]";
|
||||
}
|
||||
|
||||
public String computeProperties() {
|
||||
return computeProperties(getData());
|
||||
}
|
||||
|
||||
public PlatformBlockState getBlockData(IrisData data) {
|
||||
return blockdata.aquire(() ->
|
||||
{
|
||||
IrisBlockData customData = data.getBlockLoader().load(getBlock(), false);
|
||||
|
||||
if (customData != null) {
|
||||
PlatformBlockState customState = customData.getBlockData(data);
|
||||
|
||||
if (customState != null) {
|
||||
String st = customState.key();
|
||||
|
||||
if (st.contains("[")) {
|
||||
st = st.split("\\Q[\\E")[0];
|
||||
}
|
||||
|
||||
KMap<String, Object> cdata = customData.getData().copy();
|
||||
|
||||
for (String i : getData().keySet()) {
|
||||
cdata.put(i, getData().get(i));
|
||||
}
|
||||
|
||||
String sx = keyify(st) + computeProperties(cdata);
|
||||
|
||||
if (debug) {
|
||||
IrisLogging.debug("Block Data used " + sx + " (CUSTOM)");
|
||||
}
|
||||
|
||||
PlatformBlockState bx = B.getState(sx);
|
||||
|
||||
if (bx != null) {
|
||||
return bx;
|
||||
}
|
||||
|
||||
return customState;
|
||||
}
|
||||
}
|
||||
|
||||
String ss = keyify(getBlock()) + computeProperties();
|
||||
PlatformBlockState resolved = B.getState(ss);
|
||||
|
||||
if (debug) {
|
||||
IrisLogging.debug("Block Data used " + ss);
|
||||
}
|
||||
|
||||
if (resolved != null) {
|
||||
return resolved;
|
||||
}
|
||||
|
||||
if (backup != null) {
|
||||
return backup.getBlockData(data);
|
||||
}
|
||||
|
||||
return B.getState("AIR");
|
||||
});
|
||||
}
|
||||
|
||||
public TileData tryGetTile(IrisData data) {
|
||||
//TODO Do like a registry thing with the tile data registry. Also update the parsing of data to include **block** entities.
|
||||
PlatformBlockState state = getBlockData(data);
|
||||
String stateKey = state.key();
|
||||
int bracket = stateKey.indexOf('[');
|
||||
String blockKey = bracket >= 0 ? stateKey.substring(0, bracket) : stateKey;
|
||||
if (blockKey.equals("minecraft:spawner") && this.data.containsKey("entitySpawn")) {
|
||||
String id = (String) this.data.get("entitySpawn");
|
||||
if (tileData == null) tileData = new KMap<>();
|
||||
KMap<String, Object> spawnData = (KMap<String, Object>) tileData.computeIfAbsent("SpawnData", k -> new KMap<>());
|
||||
KMap<String, Object> entity = (KMap<String, Object>) spawnData.computeIfAbsent("entity", k -> new KMap<>());
|
||||
entity.putIfAbsent("id", Identifier.fromString(id).toString());
|
||||
}
|
||||
|
||||
if (tileData == null || tileData.isEmpty() || !state.hasTileEntity())
|
||||
return null;
|
||||
return TileData.of(state, this.tileData);
|
||||
}
|
||||
|
||||
private String keyify(String dat) {
|
||||
if (dat.contains(":")) {
|
||||
return dat;
|
||||
}
|
||||
|
||||
return "minecraft:" + dat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFolderName() {
|
||||
return "blocks";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeName() {
|
||||
return "Block";
|
||||
}
|
||||
}
|
||||
@@ -1,203 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.material;
|
||||
|
||||
import art.arcane.iris.engine.object.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.engine.object.noise.NoiseStyle;
|
||||
import art.arcane.iris.engine.object.prefab.TileData;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.volmlib.util.cache.LazyBoundedCache;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.annotations.ArrayType;
|
||||
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 art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.iris.util.project.noise.CNG;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
@Snippet("palette")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("A palette of materials")
|
||||
@Data
|
||||
public class IrisMaterialPalette {
|
||||
private static final int LAYER_GENERATOR_CACHE_SIZE = 32;
|
||||
private static final int LAYER_GENERATOR_SALT = -23_498_896;
|
||||
|
||||
private final transient AtomicCache<KList<PlatformBlockState>> blockData = new AtomicCache<>();
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private final transient LazyBoundedCache<LayerGeneratorKey, CNG> layerGenerators =
|
||||
new LazyBoundedCache<>(LAYER_GENERATOR_CACHE_SIZE);
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private final transient AtomicReference<CachedLayerGenerator> recentLayerGenerator = new AtomicReference<>();
|
||||
private final transient AtomicCache<CNG> heightGenerator = new AtomicCache<>();
|
||||
@Desc("The style of noise")
|
||||
private IrisGeneratorStyle style = NoiseStyle.STATIC.style();
|
||||
@MinNumber(0.0001)
|
||||
@Desc("The terrain zoom mostly for zooming in on a wispy palette")
|
||||
private double zoom = 5;
|
||||
@Required
|
||||
@ArrayType(min = 1, type = IrisBlockData.class)
|
||||
@Desc("The palette of blocks to be used in this layer")
|
||||
private KList<IrisBlockData> palette = new KList<IrisBlockData>().qadd(new IrisBlockData("STONE"));
|
||||
|
||||
public PlatformBlockState get(RNG rng, double x, double y, double z, IrisData rdata) {
|
||||
KList<PlatformBlockState> localBlockData = getBlockData(rdata);
|
||||
int blockDataSize = localBlockData.size();
|
||||
if (blockDataSize == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (blockDataSize == 1) {
|
||||
return localBlockData.get(0);
|
||||
}
|
||||
|
||||
double scaledX = x / zoom;
|
||||
double scaledY = y / zoom;
|
||||
double scaledZ = z / zoom;
|
||||
return getLayerGenerator(rng, rdata).fit(localBlockData, scaledX, scaledY, scaledZ);
|
||||
}
|
||||
|
||||
public Optional<TileData> getTile(RNG rng, double x, double y, double z, IrisData rdata) {
|
||||
if (getBlockData(rdata).isEmpty())
|
||||
return Optional.empty();
|
||||
|
||||
TileData tile = getBlockData(rdata).size() == 1 ? palette.get(0).tryGetTile(rdata) : palette.getRandom(rng).tryGetTile(rdata);
|
||||
return tile != null ? Optional.of(tile) : Optional.empty();
|
||||
}
|
||||
|
||||
public CNG getLayerGenerator(RNG rng, IrisData rdata) {
|
||||
Engine engine = rdata == null ? null : rdata.getEngine();
|
||||
int generatorSignature = LAYER_GENERATOR_SALT + getBlockData(rdata).size();
|
||||
long generatorSeed = rng.getSeed() + generatorSignature;
|
||||
CachedLayerGenerator recent = recentLayerGenerator.get();
|
||||
if (recent != null && recent.key.matches(rdata, engine, generatorSeed)) {
|
||||
return recent.generator;
|
||||
}
|
||||
|
||||
LayerGeneratorKey key = new LayerGeneratorKey(rdata, engine, generatorSeed);
|
||||
CNG generator = layerGenerators.computeIfAbsent(key,
|
||||
ignored -> style.create(new RNG(generatorSeed), rdata, engine));
|
||||
if (generator != null) {
|
||||
recentLayerGenerator.set(new CachedLayerGenerator(key, generator));
|
||||
}
|
||||
return generator;
|
||||
}
|
||||
|
||||
public IrisMaterialPalette qclear() {
|
||||
palette.clear();
|
||||
return this;
|
||||
}
|
||||
|
||||
public KList<IrisBlockData> add(String b) {
|
||||
palette.add(new IrisBlockData(b));
|
||||
|
||||
return palette;
|
||||
}
|
||||
|
||||
public IrisMaterialPalette qadd(String b) {
|
||||
palette.add(new IrisBlockData(b));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public KList<PlatformBlockState> getBlockData(IrisData rdata) {
|
||||
return blockData.aquire(() ->
|
||||
{
|
||||
KList<PlatformBlockState> blockData = new KList<>();
|
||||
for (IrisBlockData ix : palette) {
|
||||
PlatformBlockState bx = ix.getBlockData(rdata);
|
||||
if (bx != null) {
|
||||
for (int i = 0; i < ix.getWeight(); i++) {
|
||||
blockData.add(bx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return blockData;
|
||||
});
|
||||
}
|
||||
|
||||
public IrisMaterialPalette zero() {
|
||||
palette.clear();
|
||||
return this;
|
||||
}
|
||||
|
||||
private static final class LayerGeneratorKey {
|
||||
private final IrisData data;
|
||||
private final Engine engine;
|
||||
private final long seed;
|
||||
|
||||
private LayerGeneratorKey(IrisData data, Engine engine, long seed) {
|
||||
this.data = data;
|
||||
this.engine = engine;
|
||||
this.seed = seed;
|
||||
}
|
||||
|
||||
private boolean matches(IrisData data, Engine engine, long seed) {
|
||||
return this.data == data && this.engine == engine && this.seed == seed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object object) {
|
||||
if (this == object) {
|
||||
return true;
|
||||
}
|
||||
if (!(object instanceof LayerGeneratorKey other)) {
|
||||
return false;
|
||||
}
|
||||
return data == other.data && engine == other.engine && seed == other.seed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = System.identityHashCode(data);
|
||||
result = 31 * result + System.identityHashCode(engine);
|
||||
result = 31 * result + Long.hashCode(seed);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class CachedLayerGenerator {
|
||||
private final LayerGeneratorKey key;
|
||||
private final CNG generator;
|
||||
|
||||
private CachedLayerGenerator(LayerGeneratorKey key, CNG generator) {
|
||||
this.key = key;
|
||||
this.generator = generator;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.mod;
|
||||
|
||||
import art.arcane.iris.builtin.blocks.ObjectReplace;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
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.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)
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Desc("Represents a pack modification schema")
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
public class IrisMod extends IrisRegistrant {
|
||||
@MinNumber(2)
|
||||
@Required
|
||||
@Desc("The human-readable name of this pack modification")
|
||||
private String name = "A Pack Modification";
|
||||
|
||||
@Desc("The optional dimension load key this modification targets. An empty value does not restrict the target.")
|
||||
private String forDimension = "";
|
||||
|
||||
@MinNumber(-1)
|
||||
@MaxNumber(512)
|
||||
@Desc("Override the fluid height. Otherwise set it to -1")
|
||||
private int overrideFluidHeight = -1;
|
||||
|
||||
@Desc("A list of biomes to remove")
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@ArrayType(type = String.class, min = 1)
|
||||
private KList<String> removeBiomes = new KList<>();
|
||||
|
||||
@Desc("A list of objects to remove")
|
||||
@RegistryListResource(IrisObject.class)
|
||||
@ArrayType(type = String.class, min = 1)
|
||||
private KList<String> removeObjects = new KList<>();
|
||||
|
||||
@Desc("A list of regions to remove")
|
||||
@RegistryListResource(IrisRegion.class)
|
||||
@ArrayType(type = String.class, min = 1)
|
||||
private KList<String> removeRegions = new KList<>();
|
||||
|
||||
@Desc("A list of regions to inject")
|
||||
@RegistryListResource(IrisRegion.class)
|
||||
@ArrayType(type = String.class, min = 1)
|
||||
private KList<String> injectRegions = new KList<>();
|
||||
|
||||
@ArrayType(min = 1, type = IrisModBiomeInjector.class)
|
||||
@Desc("Inject biomes into existing regions")
|
||||
private KList<IrisModBiomeInjector> biomeInjectors = new KList<>();
|
||||
|
||||
@ArrayType(min = 1, type = IrisModBiomeReplacer.class)
|
||||
@Desc("Replace biomes with other biomes")
|
||||
private KList<IrisModBiomeReplacer> biomeReplacers = new KList<>();
|
||||
|
||||
@ArrayType(min = 1, type = IrisModObjectReplacer.class)
|
||||
@Desc("Replace objects with other objects")
|
||||
private KList<IrisModObjectReplacer> objectReplacers = new KList<>();
|
||||
|
||||
@ArrayType(min = 1, type = IrisModObjectPlacementBiomeInjector.class)
|
||||
@Desc("Inject placers into existing biomes")
|
||||
private KList<IrisModObjectPlacementBiomeInjector> biomeObjectPlacementInjectors = new KList<>();
|
||||
|
||||
@ArrayType(min = 1, type = IrisModObjectPlacementRegionInjector.class)
|
||||
@Desc("Inject placers into existing regions")
|
||||
private KList<IrisModObjectPlacementRegionInjector> regionObjectPlacementInjectors = new KList<>();
|
||||
|
||||
@ArrayType(min = 1, type = IrisModRegionReplacer.class)
|
||||
@Desc("Replace regions with other regions")
|
||||
private KList<IrisModRegionReplacer> regionReplacers = new KList<>();
|
||||
|
||||
@ArrayType(min = 1, type = ObjectReplace.class)
|
||||
@Desc("Replace blocks with other blocks")
|
||||
private KList<ObjectReplace> blockReplacers = new KList<>();
|
||||
|
||||
@ArrayType(min = 1, type = IrisModNoiseStyleReplacer.class)
|
||||
@Desc("Replace noise styles with other styles")
|
||||
private KList<IrisModNoiseStyleReplacer> styleReplacers = new KList<>();
|
||||
|
||||
@Override
|
||||
public String getFolderName() {
|
||||
return "mods";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeName() {
|
||||
return "Mod";
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.mod;
|
||||
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
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.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Snippet("biome-injector")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("A biome injector")
|
||||
@Data
|
||||
public class IrisModBiomeInjector {
|
||||
@Required
|
||||
@Desc("The region to find")
|
||||
@RegistryListResource(IrisRegion.class)
|
||||
private String region = "";
|
||||
|
||||
@Required
|
||||
@Desc("A biome to inject into the region")
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@ArrayType(type = String.class, min = 1)
|
||||
private KList<String> inject = new KList<>();
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.mod;
|
||||
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
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.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Snippet("biome-replacer")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("A biome replacer")
|
||||
@Data
|
||||
public class IrisModBiomeReplacer {
|
||||
@Required
|
||||
@Desc("A list of biomes to find")
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@ArrayType(type = String.class, min = 1)
|
||||
private KList<String> find = new KList<>();
|
||||
|
||||
@Required
|
||||
@Desc("A biome to replace it with")
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
private String replace = "";
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.mod;
|
||||
|
||||
import art.arcane.iris.engine.object.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.engine.object.noise.NoiseStyle;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.engine.object.annotations.Required;
|
||||
import art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Snippet("noise-style-replacer")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("A noise style replacer")
|
||||
@Data
|
||||
public class IrisModNoiseStyleReplacer {
|
||||
@Required
|
||||
@Desc("A noise style to find")
|
||||
private NoiseStyle find = NoiseStyle.IRIS;
|
||||
|
||||
@Required
|
||||
@Desc("If replaceTypeOnly is set to true, Iris will keep the existing generator style and only replace the type itself. Otherwise it will use the replace tag for every style using the find type.")
|
||||
private boolean replaceTypeOnly = false;
|
||||
|
||||
@Required
|
||||
@Desc("A noise style to replace it with")
|
||||
private IrisGeneratorStyle replace = new IrisGeneratorStyle();
|
||||
}
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.mod;
|
||||
|
||||
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
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.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Snippet("object-placement-biome-injector")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("An object placement injector")
|
||||
@Data
|
||||
public class IrisModObjectPlacementBiomeInjector {
|
||||
@Required
|
||||
@Desc("The biome to find")
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
private String biome = "";
|
||||
|
||||
@Required
|
||||
@Desc("Object placements to inject into the biome")
|
||||
@ArrayType(type = IrisObjectPlacement.class, min = 1)
|
||||
private KList<IrisObjectPlacement> place = new KList<>();
|
||||
}
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.mod;
|
||||
|
||||
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
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.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Snippet("object-placement-region-injector")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("An object placement injector")
|
||||
@Data
|
||||
public class IrisModObjectPlacementRegionInjector {
|
||||
@Required
|
||||
@Desc("The region to find")
|
||||
@RegistryListResource(IrisRegion.class)
|
||||
private String biome = "";
|
||||
|
||||
@Required
|
||||
@Desc("Object placements to inject into the region")
|
||||
@ArrayType(type = IrisObjectPlacement.class, min = 1)
|
||||
private KList<IrisObjectPlacement> place = new KList<>();
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.mod;
|
||||
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
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.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Snippet("object-replacer")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("An object replacer")
|
||||
@Data
|
||||
public class IrisModObjectReplacer {
|
||||
@Required
|
||||
@Desc("A list of objects to find")
|
||||
@RegistryListResource(IrisObject.class)
|
||||
@ArrayType(type = String.class, min = 1)
|
||||
private KList<String> find = new KList<>();
|
||||
|
||||
@Required
|
||||
@Desc("An object to replace it with")
|
||||
@RegistryListResource(IrisObject.class)
|
||||
private String replace = "";
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.mod;
|
||||
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
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.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Snippet("region-replacer")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("A region replacer")
|
||||
@Data
|
||||
public class IrisModRegionReplacer {
|
||||
@Required
|
||||
@Desc("A list of regions to find")
|
||||
@RegistryListResource(IrisRegion.class)
|
||||
@ArrayType(type = String.class, min = 1)
|
||||
private KList<String> find = new KList<>();
|
||||
|
||||
@Required
|
||||
@Desc("A region to replace it with")
|
||||
@RegistryListResource(IrisRegion.class)
|
||||
private String replace = "";
|
||||
}
|
||||
@@ -1,278 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.noise;
|
||||
|
||||
import art.arcane.iris.engine.object.image.IrisImageMap;
|
||||
import art.arcane.iris.engine.object.noise.expression.IrisExpression;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.volmlib.util.cache.LazyBoundedCache;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
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.Snippet;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.iris.util.project.noise.CNG;
|
||||
import art.arcane.iris.util.project.noise.ExpressionNoise;
|
||||
import art.arcane.iris.util.project.noise.ImageNoise;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Snippet("style")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("A gen style")
|
||||
@Data
|
||||
public class IrisGeneratorStyle {
|
||||
private static final int GENERATOR_CACHE_SIZE = 8;
|
||||
private static final ConcurrentHashMap<String, String> ACTIVE_CACHE_KEYS = new ConcurrentHashMap<>();
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private final transient LazyBoundedCache<GeneratorCacheKey, CNG> generatorCache =
|
||||
new LazyBoundedCache<>(GENERATOR_CACHE_SIZE);
|
||||
@Desc("The base noise style. Used when neither expression nor imageMap is set; a failed expression also falls back to this style.")
|
||||
private NoiseStyle style = NoiseStyle.FLAT;
|
||||
|
||||
@Desc("If set above 0, this style will be cellularized")
|
||||
private double cellularFrequency = 0;
|
||||
|
||||
@Desc("Cell zooms")
|
||||
private double cellularZoom = 1;
|
||||
@MinNumber(0.00001)
|
||||
@Desc("The zoom of this style")
|
||||
private double zoom = 1;
|
||||
@Desc("Instead of using the style property, use a custom expression to represent this style.")
|
||||
@RegistryListResource(IrisExpression.class)
|
||||
private String expression = null;
|
||||
@Desc("Use an Image map instead of a generated value")
|
||||
@RegistryListResource(IrisImageMap.class)
|
||||
private String imageMap = null;
|
||||
@MinNumber(0.00001)
|
||||
@Desc("The Output multiplier. Only used if parent is fracture.")
|
||||
private double multiplier = 1;
|
||||
@Desc("Apply a generator to the coordinate field fed into this parent generator. I.e. Distort your generator with another generator.")
|
||||
private IrisGeneratorStyle fracture = null;
|
||||
@MinNumber(0.01562)
|
||||
@MaxNumber(64)
|
||||
@Desc("The exponent")
|
||||
private double exponent = 1;
|
||||
@MinNumber(0)
|
||||
@MaxNumber(8192)
|
||||
@Desc("If the cache size is set above 0, this generator will be cached")
|
||||
private int cacheSize = 0;
|
||||
|
||||
public IrisGeneratorStyle(NoiseStyle s) {
|
||||
this.style = s;
|
||||
}
|
||||
|
||||
public IrisGeneratorStyle zoomed(double z) {
|
||||
this.zoom = z;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CNG createNoCache(RNG rng, IrisData data) {
|
||||
return createNoCache(rng, data, false, 0, false, resolveEngine(data));
|
||||
}
|
||||
|
||||
public CNG createForPrebake(RNG rng, IrisData data, int fallbackCacheSize) {
|
||||
return createNoCache(rng, data, false, Math.max(0, fallbackCacheSize), true, resolveEngine(data));
|
||||
}
|
||||
|
||||
|
||||
private int imageMapHash() {
|
||||
if (imageMap == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return imageMap.hashCode();
|
||||
}
|
||||
|
||||
private int hash() {
|
||||
return Objects.hash(expression, imageMapHash(), multiplier, fracture != null ? fracture.hash() : 0, exponent, cacheSize, zoom, cellularZoom, cellularFrequency, style);
|
||||
}
|
||||
|
||||
public int prebakeSignature() {
|
||||
return hash();
|
||||
}
|
||||
|
||||
private String cachePrefix(RNG rng, int effectiveCacheSize, long engineStamp) {
|
||||
return "style-" + Integer.toUnsignedString(hash())
|
||||
+ "-seed-" + Long.toUnsignedString(rng.getSeed())
|
||||
+ "-eng-" + Long.toUnsignedString(engineStamp)
|
||||
+ "-sz-" + effectiveCacheSize
|
||||
+ "-src-";
|
||||
}
|
||||
|
||||
private String cacheKey(RNG rng, long sourceStamp, int effectiveCacheSize, long engineStamp) {
|
||||
return cachePrefix(rng, effectiveCacheSize, engineStamp) + Long.toUnsignedString(sourceStamp);
|
||||
}
|
||||
|
||||
private void clearStaleCacheEntries(IrisData data, String prefix, String key) {
|
||||
File cacheFolder = new File(data.getDataFolder(), ".cache");
|
||||
String cacheFolderKey = cacheFolder.getAbsolutePath() + File.separator + prefix;
|
||||
String previousKey = ACTIVE_CACHE_KEYS.put(cacheFolderKey, key);
|
||||
if (key.equals(previousKey)) {
|
||||
return;
|
||||
}
|
||||
File[] files = cacheFolder.listFiles((dir, name) -> name.endsWith(".cnm") && name.startsWith(prefix));
|
||||
if (files == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String keepFile = key + ".cnm";
|
||||
for (File file : files) {
|
||||
if (keepFile.equals(file.getName())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!file.delete()) {
|
||||
IrisLogging.debug("Unable to delete stale noise cache " + file.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public CNG createNoCache(RNG rng, IrisData data, boolean actuallyCached) {
|
||||
return createNoCache(rng, data, actuallyCached, 0, false, resolveEngine(data));
|
||||
}
|
||||
|
||||
private CNG createNoCache(RNG rng, IrisData data, boolean actuallyCached, int fallbackCacheSize,
|
||||
boolean quietCacheLog, Engine engine) {
|
||||
CNG cng = null;
|
||||
long sourceStamp = 0L;
|
||||
if (getExpression() != null) {
|
||||
IrisExpression e = data.getExpressionLoader().load(getExpression());
|
||||
if (e != null) {
|
||||
cng = new CNG(rng, new ExpressionNoise(rng, e), 1D, 1).bake();
|
||||
sourceStamp = Integer.toUnsignedLong(Objects.hash(getExpression(),
|
||||
e.getLoadFile() == null ? 0L : e.getLoadFile().lastModified()));
|
||||
}
|
||||
} else if (getImageMap() != null) {
|
||||
ImageNoise imageNoise = new ImageNoise(data, getImageMap());
|
||||
cng = new CNG(rng, imageNoise, 1D, 1).bake();
|
||||
sourceStamp = Integer.toUnsignedLong(imageNoise.getContentHash().hashCode());
|
||||
}
|
||||
|
||||
if (cng == null) {
|
||||
cng = (style != null ? style : NoiseStyle.FLAT).create(rng).bake();
|
||||
}
|
||||
|
||||
cng = cng.scale(1D / zoom).pow(exponent).bake();
|
||||
|
||||
if (fracture != null) {
|
||||
cng.fractureWith(fracture.createNoCache(rng.nextParallelRNG(2934), data, false,
|
||||
fallbackCacheSize, quietCacheLog, engine), fracture.getMultiplier());
|
||||
}
|
||||
|
||||
if (cellularFrequency > 0) {
|
||||
cng = cng.cellularize(rng.nextParallelRNG(884466), cellularFrequency).scale(1D / cellularZoom).bake();
|
||||
}
|
||||
|
||||
int effectiveCacheSize = cacheSize > 0 ? cacheSize : Math.max(0, fallbackCacheSize);
|
||||
if (effectiveCacheSize > 0) {
|
||||
long engineStamp = engineStamp(engine);
|
||||
String key = cacheKey(rng, sourceStamp, effectiveCacheSize, engineStamp);
|
||||
clearStaleCacheEntries(data, cachePrefix(rng, effectiveCacheSize, engineStamp), key);
|
||||
cng = cng.cached(effectiveCacheSize, key, data.getDataFolder(), quietCacheLog);
|
||||
}
|
||||
|
||||
return cng;
|
||||
}
|
||||
|
||||
public double warp(RNG rng, IrisData data, double value, double... coords) {
|
||||
return create(rng, data).noise(coords) + value;
|
||||
}
|
||||
|
||||
public CNG create(RNG rng, IrisData data) {
|
||||
return create(rng, data, resolveEngine(data));
|
||||
}
|
||||
|
||||
public CNG create(RNG rng, IrisData data, Engine engine) {
|
||||
GeneratorCacheKey key = new GeneratorCacheKey(data, engine, rng.getSeed());
|
||||
return generatorCache.computeIfAbsent(key,
|
||||
ignored -> createNoCache(rng, data, true, 0, false, engine));
|
||||
}
|
||||
|
||||
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
|
||||
public boolean isFlat() {
|
||||
return style == null || style.equals(NoiseStyle.FLAT);
|
||||
}
|
||||
|
||||
public double getMaxFractureDistance() {
|
||||
return multiplier;
|
||||
}
|
||||
|
||||
private long engineStamp(Engine engine) {
|
||||
if (engine == null) {
|
||||
return 0L;
|
||||
}
|
||||
return Integer.toUnsignedLong(Objects.hash(
|
||||
engine.getSeedManager().getSeed(),
|
||||
engine.getMinHeight(),
|
||||
engine.getMaxHeight(),
|
||||
engine.getDimension().getLoadKey(),
|
||||
engine.getDimension().getFluidHeight()
|
||||
));
|
||||
}
|
||||
|
||||
private Engine resolveEngine(IrisData data) {
|
||||
return data == null ? null : data.getEngine();
|
||||
}
|
||||
|
||||
private static final class GeneratorCacheKey {
|
||||
private final IrisData data;
|
||||
private final Engine engine;
|
||||
private final long seed;
|
||||
|
||||
private GeneratorCacheKey(IrisData data, Engine engine, long seed) {
|
||||
this.data = data;
|
||||
this.engine = engine;
|
||||
this.seed = seed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) {
|
||||
return true;
|
||||
}
|
||||
if (!(other instanceof GeneratorCacheKey key)) {
|
||||
return false;
|
||||
}
|
||||
return data == key.data && engine == key.engine && seed == key.seed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = System.identityHashCode(data);
|
||||
result = 31 * result + System.identityHashCode(engine);
|
||||
return 31 * result + Long.hashCode(seed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.noise;
|
||||
|
||||
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.Required;
|
||||
import art.arcane.volmlib.util.function.NoiseProvider;
|
||||
import art.arcane.iris.util.project.interpolation.InterpolationMethod;
|
||||
import art.arcane.iris.util.project.interpolation.IrisInterpolation;
|
||||
import art.arcane.iris.util.project.interpolation.NoiseBounds;
|
||||
import art.arcane.iris.util.project.interpolation.NoiseBoundsProvider;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("Configures rotation for iris")
|
||||
@Data
|
||||
public class IrisInterpolator {
|
||||
public static final IrisInterpolator DEFAULT = new IrisInterpolator();
|
||||
|
||||
@Required
|
||||
@Desc("The interpolation method when two biomes use different heights but this same generator")
|
||||
private InterpolationMethod function = InterpolationMethod.BILINEAR_STARCAST_6;
|
||||
|
||||
@Required
|
||||
@MinNumber(1)
|
||||
@MaxNumber(8192)
|
||||
@Desc("The range checked horizontally. Smaller ranges yeild more detail but are not as smooth.")
|
||||
private double horizontalScale = 7;
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
// Bit-identical to Objects.hash(horizontalScale, function) without the Object[] or Double boxing.
|
||||
int result = 31 + Double.hashCode(horizontalScale);
|
||||
return (31 * result) + (function == null ? 0 : function.hashCode());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o instanceof IrisInterpolator i) {
|
||||
return i.getFunction().equals(function) && i.getHorizontalScale() == horizontalScale;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public double interpolate(double x, double z, NoiseProvider provider) {
|
||||
return interpolate((int) Math.round(x), (int) Math.round(z), provider);
|
||||
}
|
||||
|
||||
public double interpolate(int x, int z, NoiseProvider provider) {
|
||||
return IrisInterpolation.getNoise(getFunction(), x, z, getHorizontalScale(), provider);
|
||||
}
|
||||
|
||||
public NoiseBounds interpolateBounds(double x, double z, NoiseBoundsProvider provider) {
|
||||
return interpolateBounds((int) Math.round(x), (int) Math.round(z), provider);
|
||||
}
|
||||
|
||||
public NoiseBounds interpolateBounds(int x, int z, NoiseBoundsProvider provider) {
|
||||
return IrisInterpolation.getNoiseBounds(getFunction(), x, z, getHorizontalScale(), provider);
|
||||
}
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.noise;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.volmlib.util.cache.LazyBoundedCache;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
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.Required;
|
||||
import art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.iris.util.project.interpolation.IrisInterpolation;
|
||||
import art.arcane.iris.util.project.noise.CNG;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
@Snippet("generator")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("A noise generator")
|
||||
@Data
|
||||
public class IrisNoiseGenerator {
|
||||
private static final int GENERATOR_CACHE_SIZE = 32;
|
||||
private static final long GENERATOR_SEED_SALT = 33_955_677L;
|
||||
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private final transient LazyBoundedCache<GeneratorKey, CNG> generators =
|
||||
new LazyBoundedCache<>(GENERATOR_CACHE_SIZE);
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private final transient AtomicReference<CachedGenerator> recentGenerator = new AtomicReference<>();
|
||||
@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 IrisGeneratorStyle style = NoiseStyle.IRIS.style();
|
||||
@MinNumber(1)
|
||||
@Desc("Multiple octaves for multple generators of changing zooms added together")
|
||||
private int octaves = 1;
|
||||
@ArrayType(min = 1, type = IrisNoiseGenerator.class)
|
||||
@Desc("Apply a child noise generator to fracture the input coordinates of this generator")
|
||||
private KList<IrisNoiseGenerator> fracture = new KList<>();
|
||||
|
||||
public IrisNoiseGenerator(boolean enabled) {
|
||||
this();
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
protected CNG getGenerator(long superSeed, IrisData data) {
|
||||
Engine engine = data == null ? null : data.getEngine();
|
||||
long generatorSeed = superSeed + GENERATOR_SEED_SALT - seed;
|
||||
CachedGenerator recent = recentGenerator.get();
|
||||
if (recent != null && recent.key.matches(data, engine, generatorSeed)) {
|
||||
return recent.generator;
|
||||
}
|
||||
|
||||
GeneratorKey key = new GeneratorKey(data, engine, generatorSeed);
|
||||
CNG generator = generators.computeIfAbsent(key,
|
||||
ignored -> style.createNoCache(new RNG(generatorSeed), data).oct(octaves));
|
||||
if (generator != null) {
|
||||
recentGenerator.set(new CachedGenerator(key, generator));
|
||||
}
|
||||
return generator;
|
||||
}
|
||||
|
||||
public double getMax() {
|
||||
return getOffsetY() + opacity;
|
||||
}
|
||||
|
||||
public double getNoise(long superSeed, double xv, double zv, IrisData data) {
|
||||
if (!enabled) {
|
||||
return offsetY;
|
||||
}
|
||||
|
||||
double x = xv;
|
||||
double z = zv;
|
||||
int g = 33;
|
||||
|
||||
for (IrisNoiseGenerator i : fracture) {
|
||||
if (i.isEnabled()) {
|
||||
double fractureOffset = i.getOpacity() / 2D;
|
||||
x += i.getNoise(superSeed + seed + g, xv, zv, data) - fractureOffset;
|
||||
z += i.getNoise(superSeed + seed + g, zv, xv, data) - fractureOffset;
|
||||
}
|
||||
g += 819;
|
||||
}
|
||||
|
||||
CNG cng = getGenerator(superSeed, data);
|
||||
double sampleX = (x / zoom) + offsetX;
|
||||
double sampleZ = (z / zoom) + offsetZ;
|
||||
double n = cng.noiseFast2D(sampleX, sampleZ) * opacity;
|
||||
n = negative ? (-n + opacity) : n;
|
||||
n = (exponent != 1 ? n < 0 ? -Math.pow(-n, exponent) : Math.pow(n, exponent) : n) + offsetY;
|
||||
n = parametric ? IrisInterpolation.parametric(n, 1) : n;
|
||||
n = bezier ? IrisInterpolation.bezier(n) : n;
|
||||
n = sinCentered ? IrisInterpolation.sinCenter(n) : n;
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
public KList<IrisNoiseGenerator> getAllComposites() {
|
||||
KList<IrisNoiseGenerator> g = new KList<>();
|
||||
|
||||
g.add(this);
|
||||
|
||||
for (IrisNoiseGenerator i : getFracture()) {
|
||||
g.addAll(i.getAllComposites());
|
||||
}
|
||||
|
||||
return g;
|
||||
}
|
||||
|
||||
private static final class GeneratorKey {
|
||||
private final IrisData data;
|
||||
private final Engine engine;
|
||||
private final long seed;
|
||||
|
||||
private GeneratorKey(IrisData data, Engine engine, long seed) {
|
||||
this.data = data;
|
||||
this.engine = engine;
|
||||
this.seed = seed;
|
||||
}
|
||||
|
||||
private boolean matches(IrisData data, Engine engine, long seed) {
|
||||
return this.data == data && this.engine == engine && this.seed == seed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object object) {
|
||||
if (this == object) {
|
||||
return true;
|
||||
}
|
||||
if (!(object instanceof GeneratorKey other)) {
|
||||
return false;
|
||||
}
|
||||
return data == other.data && engine == other.engine && seed == other.seed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = System.identityHashCode(data);
|
||||
result = 31 * result + System.identityHashCode(engine);
|
||||
result = 31 * result + Long.hashCode(seed);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class CachedGenerator {
|
||||
private final GeneratorKey key;
|
||||
private final CNG generator;
|
||||
|
||||
private CachedGenerator(GeneratorKey key, CNG generator) {
|
||||
this.key = key;
|
||||
this.generator = generator;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.noise;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
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.Required;
|
||||
import art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Snippet("shaped-style")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("This represents a generator with a min and max height")
|
||||
@Data
|
||||
public class IrisShapedGeneratorStyle {
|
||||
@Required
|
||||
@Desc("The generator id")
|
||||
private IrisGeneratorStyle generator = new IrisGeneratorStyle(NoiseStyle.IRIS);
|
||||
|
||||
@Required
|
||||
@MinNumber(-2032)
|
||||
@MaxNumber(2032)
|
||||
@Desc("The min block value")
|
||||
private int min = 0;
|
||||
|
||||
@Required
|
||||
@MinNumber(-2032)
|
||||
@MaxNumber(2032)
|
||||
@Desc("The max block value")
|
||||
private int max = 0;
|
||||
|
||||
public IrisShapedGeneratorStyle(NoiseStyle style, int min, int max) {
|
||||
this(style);
|
||||
this.min = min;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
public IrisShapedGeneratorStyle(NoiseStyle style) {
|
||||
this.generator = new IrisGeneratorStyle(style);
|
||||
}
|
||||
|
||||
public double get(RNG rng, IrisData data, double... dim) {
|
||||
return generator.create(rng, data).fitDouble(min, max, dim);
|
||||
}
|
||||
|
||||
public double get(RNG rng, IrisData data, double x, double z) {
|
||||
return generator.create(rng, data).fitDouble(min, max, x, z);
|
||||
}
|
||||
|
||||
public double get(RNG rng, IrisData data, double x, double y, double z) {
|
||||
return generator.create(rng, data).fitDouble(min, max, x, y, z);
|
||||
}
|
||||
|
||||
public boolean isFlat() {
|
||||
return min == max || getGenerator().isFlat();
|
||||
}
|
||||
|
||||
public int getMid() {
|
||||
return (getMax() + getMin()) / 2;
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.noise;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.volmlib.util.math.M;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.iris.util.project.stream.ProceduralStream;
|
||||
import art.arcane.iris.util.project.stream.interpolation.Interpolated;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Snippet("style-range")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("Represents a range styled with a custom generator")
|
||||
@Data
|
||||
public class IrisStyledRange {
|
||||
@Desc("The minimum value")
|
||||
private double min = 16;
|
||||
|
||||
@Desc("The maximum value")
|
||||
private double max = 32;
|
||||
|
||||
@Desc("The style to pick the range")
|
||||
private IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.STATIC);
|
||||
|
||||
public double get(RNG rng, double x, double z, IrisData data) {
|
||||
if (min == max) {
|
||||
return min;
|
||||
}
|
||||
|
||||
if (style.isFlat()) {
|
||||
return M.lerp(min, max, 0.5);
|
||||
}
|
||||
|
||||
return style.create(rng, data).fitDouble(min, max, x, z);
|
||||
}
|
||||
|
||||
public ProceduralStream<Double> stream(RNG rng, IrisData data) {
|
||||
return ProceduralStream.of((x, z) -> get(rng, x, z, data), Interpolated.DOUBLE);
|
||||
}
|
||||
|
||||
public boolean isFlat() {
|
||||
return getMax() == getMin() || style.isFlat();
|
||||
}
|
||||
|
||||
public int getMid() {
|
||||
return (int) ((getMax() + getMin()) / 2);
|
||||
}
|
||||
}
|
||||
@@ -1,566 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.noise;
|
||||
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.iris.util.project.noise.CNG;
|
||||
import art.arcane.iris.util.project.noise.CNGFactory;
|
||||
import art.arcane.iris.util.project.noise.NoiseType;
|
||||
import art.arcane.iris.util.project.stream.ProceduralStream;
|
||||
@Desc("Styles of noise")
|
||||
public enum NoiseStyle {
|
||||
@Desc("White Noise is like static. Useful for block scattering but not terrain.")
|
||||
STATIC(rng -> new CNG(rng, NoiseType.WHITE, 1D, 1)),
|
||||
|
||||
@Desc("White Noise is like static. Useful for block scattering but not terrain.")
|
||||
STATIC_BILINEAR(rng -> new CNG(rng, NoiseType.WHITE_BILINEAR, 1D, 1)),
|
||||
|
||||
@Desc("White Noise is like static. Useful for block scattering but not terrain.")
|
||||
STATIC_BICUBIC(rng -> new CNG(rng, NoiseType.WHITE_BICUBIC, 1D, 1)),
|
||||
|
||||
@Desc("White Noise is like static. Useful for block scattering but not terrain.")
|
||||
STATIC_HERMITE(rng -> new CNG(rng, NoiseType.WHITE_HERMITE, 1D, 1)),
|
||||
|
||||
@Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.")
|
||||
IRIS(rng -> CNG.signature(rng).scale(1)),
|
||||
|
||||
@Desc("Clover Noise")
|
||||
CLOVER(rng -> new CNG(rng, NoiseType.CLOVER, 1D, 1).scale(0.06).bake()),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_STARCAST_3(rng -> new CNG(rng, NoiseType.CLOVER_STARCAST_3, 1D, 1)),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_STARCAST_6(rng -> new CNG(rng, NoiseType.CLOVER_STARCAST_6, 1D, 1)),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_STARCAST_9(rng -> new CNG(rng, NoiseType.CLOVER_STARCAST_9, 1D, 1)),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_STARCAST_12(rng -> new CNG(rng, NoiseType.CLOVER_STARCAST_12, 1D, 1)),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_BILINEAR_STARCAST_3(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR_STARCAST_3, 1D, 1)),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_BILINEAR_STARCAST_6(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR_STARCAST_6, 1D, 1)),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_BILINEAR_STARCAST_9(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR_STARCAST_9, 1D, 1)),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_BILINEAR_STARCAST_12(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR_STARCAST_12, 1D, 1)),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_HERMITE_STARCAST_3(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE_STARCAST_3, 1D, 1)),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_HERMITE_STARCAST_6(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE_STARCAST_6, 1D, 1)),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_HERMITE_STARCAST_9(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE_STARCAST_9, 1D, 1)),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_HERMITE_STARCAST_12(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE_STARCAST_12, 1D, 1)),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_BILINEAR(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR, 1D, 1)),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_BICUBIC(rng -> new CNG(rng, NoiseType.CLOVER_BICUBIC, 1D, 1)),
|
||||
|
||||
@Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CLOVER_HERMITE(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE, 1D, 1)),
|
||||
|
||||
@Desc("Vascular noise gets higher as the position nears a cell border.")
|
||||
VASCULAR(rng -> new CNG(rng, NoiseType.VASCULAR, 1D, 1)),
|
||||
|
||||
@Desc("It always returns 0.5")
|
||||
FLAT(rng -> new CNG(rng, NoiseType.FLAT, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR(rng -> new CNG(rng, NoiseType.CELLULAR, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_STARCAST_3(rng -> new CNG(rng, NoiseType.CELLULAR_STARCAST_3, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_STARCAST_6(rng -> new CNG(rng, NoiseType.CELLULAR_STARCAST_6, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_STARCAST_9(rng -> new CNG(rng, NoiseType.CELLULAR_STARCAST_9, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_STARCAST_12(rng -> new CNG(rng, NoiseType.CELLULAR_STARCAST_12, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_BILINEAR_STARCAST_3(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR_STARCAST_3, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_BILINEAR_STARCAST_6(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR_STARCAST_6, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_BILINEAR_STARCAST_9(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR_STARCAST_9, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_BILINEAR_STARCAST_12(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR_STARCAST_12, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_HERMITE_STARCAST_3(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE_STARCAST_3, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_HERMITE_STARCAST_6(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE_STARCAST_6, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_HERMITE_STARCAST_9(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE_STARCAST_9, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_HERMITE_STARCAST_12(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE_STARCAST_12, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_BILINEAR(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_BICUBIC(rng -> new CNG(rng, NoiseType.CELLULAR_BICUBIC, 1D, 1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.")
|
||||
CELLULAR_HERMITE(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE, 1D, 1)),
|
||||
|
||||
@Desc("Hexagonal cells with stable per-cell values.")
|
||||
HEXAGON(rng -> new CNG(rng, NoiseType.HEXAGON, 1D, 1).scale(1)),
|
||||
|
||||
@Desc("Hex James substitution pattern with 3 large and 3 small recursive hex children plus gaps.")
|
||||
HEX_JAMES(rng -> new CNG(rng, NoiseType.HEX_JAMES, 1D, 1).scale(1)),
|
||||
|
||||
@Desc("Interlocked solid hex cells with per-cell values from a smooth simplex heatmap.")
|
||||
HEX_SIMPLEX(rng -> new CNG(rng, NoiseType.HEX_SIMPLEX, 1D, 1).scale(1)),
|
||||
|
||||
@Desc("Randomized finite-depth Sierpinski-style hex recursion with per-level random 3-large/3-small James substitution.")
|
||||
HEX_RANDOM_SIZE(rng -> new CNG(rng, NoiseType.HEX_RANDOM_SIZE, 1D, 1).scale(1)),
|
||||
|
||||
@Desc("Sierpinski triangle mask blended with simplex heat.")
|
||||
SIERPINSKI_TRIANGLE(rng -> new CNG(rng, NoiseType.SIERPINSKI_TRIANGLE, 1D, 1).scale(1)),
|
||||
|
||||
@Desc("Classic German Engineering")
|
||||
NOWHERE(rng -> CNG.signaturePerlin(rng).scale(0.776).bake()),
|
||||
|
||||
@Desc("Classic German Engineering")
|
||||
NOWHERE_CELLULAR(rng -> CNG.signaturePerlin(rng, NoiseType.CELLULAR).scale(1).bake()),
|
||||
|
||||
@Desc("Classic German Engineering")
|
||||
NOWHERE_CLOVER(rng -> CNG.signaturePerlin(rng, NoiseType.CLOVER).scale(1).bake()),
|
||||
|
||||
@Desc("Classic German Engineering")
|
||||
NOWHERE_HEXAGON(rng -> CNG.signaturePerlin(rng, NoiseType.HEXAGON).scale(1).bake()),
|
||||
|
||||
@Desc("Classic German Engineering")
|
||||
NOWHERE_HEX_JAMES(rng -> CNG.signaturePerlin(rng, NoiseType.HEX_JAMES).scale(1).bake()),
|
||||
|
||||
@Desc("Classic German Engineering")
|
||||
NOWHERE_HEX_SIMPLEX(rng -> CNG.signaturePerlin(rng, NoiseType.HEX_SIMPLEX).scale(1).bake()),
|
||||
|
||||
@Desc("Classic German Engineering")
|
||||
NOWHERE_HEX_RANDOM_SIZE(rng -> CNG.signaturePerlin(rng, NoiseType.HEX_RANDOM_SIZE).scale(1).bake()),
|
||||
|
||||
@Desc("Classic German Engineering")
|
||||
NOWHERE_SIERPINSKI_TRIANGLE(rng -> CNG.signaturePerlin(rng, NoiseType.SIERPINSKI_TRIANGLE).scale(1).bake()),
|
||||
|
||||
@Desc("Classic German Engineering")
|
||||
NOWHERE_SIMPLEX(rng -> CNG.signaturePerlin(rng, NoiseType.SIMPLEX).scale(1).bake()),
|
||||
|
||||
@Desc("Classic German Engineering")
|
||||
NOWHERE_GLOB(rng -> CNG.signaturePerlin(rng, NoiseType.GLOB).scale(1).bake()),
|
||||
|
||||
@Desc("Classic German Engineering")
|
||||
NOWHERE_VASCULAR(rng -> CNG.signaturePerlin(rng, NoiseType.VASCULAR).scale(1).bake()),
|
||||
|
||||
@Desc("Classic German Engineering")
|
||||
NOWHERE_CUBIC(rng -> CNG.signaturePerlin(rng, NoiseType.CUBIC).scale(1).bake()),
|
||||
|
||||
@Desc("Classic German Engineering")
|
||||
NOWHERE_SUPERFRACTAL(rng -> CNG.signaturePerlin(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX).scale(1).bake()),
|
||||
|
||||
@Desc("Classic German Engineering")
|
||||
NOWHERE_FRACTAL(rng -> CNG.signaturePerlin(rng, NoiseType.FRACTAL_BILLOW_PERLIN).scale(1).bake()),
|
||||
|
||||
@Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.")
|
||||
IRIS_DOUBLE(rng -> CNG.signatureDouble(rng).scale(1)),
|
||||
|
||||
@Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.")
|
||||
IRIS_THICK(rng -> CNG.signatureThick(rng).scale(1)),
|
||||
|
||||
@Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.")
|
||||
IRIS_HALF(rng -> CNG.signatureHalf(rng).scale(1)),
|
||||
|
||||
@Desc("Basic, Smooth & Fast Simplex noise.")
|
||||
SIMPLEX(rng -> new CNG(rng, 1D, 1).scale(1)),
|
||||
|
||||
@Desc("Very Detailed smoke using simplex fractured with fractal billow simplex at high octaves.")
|
||||
FRACTAL_SMOKE(rng -> new CNG(rng, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(1), NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 8).scale(0.2), 1000).scale(0.34)),
|
||||
|
||||
@Desc("Thinner Veins.")
|
||||
VASCULAR_THIN(rng -> new CNG(rng.nextParallelRNG(1), NoiseType.VASCULAR, 1D, 1).scale(1).pow(0.65)),
|
||||
|
||||
@Desc("Cells of simplex noise")
|
||||
SIMPLEX_CELLS(rng -> new CNG(rng.nextParallelRNG(1), NoiseType.SIMPLEX, 1D, 1).scale(1).fractureWith(new CNG(rng.nextParallelRNG(8), NoiseType.CELLULAR, 1D, 1).scale(1), 200)),
|
||||
|
||||
@Desc("Veins of simplex noise")
|
||||
SIMPLEX_VASCULAR(rng -> new CNG(rng.nextParallelRNG(1), NoiseType.SIMPLEX, 1D, 1).scale(1).fractureWith(new CNG(rng.nextParallelRNG(8), NoiseType.VASCULAR, 1D, 1).scale(1), 200)),
|
||||
|
||||
@Desc("Very Detailed fluid using simplex fractured with fractal billow simplex at high octaves.")
|
||||
FRACTAL_WATER(rng -> new CNG(rng, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(1), NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 9).scale(0.03), 9900).scale(1.14)),
|
||||
|
||||
@Desc("Perlin. Like simplex but more natural")
|
||||
PERLIN(rng -> new CNG(rng, NoiseType.PERLIN, 1D, 1).scale(1.15)),
|
||||
|
||||
@Desc("Perlin. Like simplex but more natural")
|
||||
PERLIN_IRIS(rng -> CNG.signature(rng, NoiseType.PERLIN).scale(1.47)),
|
||||
|
||||
@Desc("Perlin. Like simplex but more natural")
|
||||
PERLIN_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.PERLIN).scale(1.47)),
|
||||
|
||||
@Desc("Perlin. Like simplex but more natural")
|
||||
PERLIN_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.PERLIN).scale(1.47)),
|
||||
|
||||
@Desc("Perlin. Like simplex but more natural")
|
||||
PERLIN_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.PERLIN).scale(1.47)),
|
||||
|
||||
@Desc("Billow Fractal Perlin Noise.")
|
||||
FRACTAL_BILLOW_PERLIN(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_PERLIN, 1D, 1).scale(1.47)),
|
||||
|
||||
@Desc("Billow Fractal Perlin Noise. 2 Octaves")
|
||||
BIOCTAVE_FRACTAL_BILLOW_PERLIN(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_PERLIN, 1D, 2).scale(1.17)),
|
||||
|
||||
@Desc("Billow Fractal Simplex Noise. Single octave.")
|
||||
FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 1)),
|
||||
|
||||
@Desc("FBM Fractal Simplex Noise. Single octave.")
|
||||
FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 1)),
|
||||
|
||||
@Desc("Billow Fractal Iris Noise. Single octave.")
|
||||
FRACTAL_BILLOW_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)),
|
||||
|
||||
@Desc("FBM Fractal Iris Noise. Single octave.")
|
||||
FRACTAL_FBM_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_FBM_SIMPLEX)),
|
||||
|
||||
@Desc("Billow Fractal Iris Noise. Single octave.")
|
||||
FRACTAL_BILLOW_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)),
|
||||
|
||||
@Desc("FBM Fractal Iris Noise. Single octave.")
|
||||
FRACTAL_FBM_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_FBM_SIMPLEX)),
|
||||
|
||||
@Desc("Billow Fractal Iris Noise. Single octave.")
|
||||
FRACTAL_BILLOW_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)),
|
||||
|
||||
@Desc("FBM Fractal Iris Noise. Single octave.")
|
||||
FRACTAL_FBM_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_FBM_SIMPLEX)),
|
||||
|
||||
@Desc("Fractal hexagonal cell noise.")
|
||||
FRACTAL_HEXAGON(rng -> new CNG(rng, NoiseType.HEXAGON, 1D, 4).scale(1)),
|
||||
|
||||
@Desc("Fractal Hex James substitution pattern with recursive 3-large/3-small child hexes and gaps.")
|
||||
FRACTAL_HEX_JAMES(rng -> new CNG(rng, NoiseType.HEX_JAMES, 1D, 4).scale(1)),
|
||||
|
||||
@Desc("Interlocked solid hex cells with per-cell fractal simplex heatmap values.")
|
||||
FRACTAL_HEX_SIMPLEX(rng -> new CNG(rng, NoiseType.HEX_SIMPLEX, 1D, 4).scale(1)),
|
||||
|
||||
@Desc("Fractal hexagonal gradient noise with randomized local hex sizes and blended random/simplex heatmaps.")
|
||||
FRACTAL_HEX_RANDOM_SIZE(rng -> new CNG(rng, NoiseType.HEX_RANDOM_SIZE, 1D, 4).scale(1)),
|
||||
|
||||
@Desc("Fractal Sierpinski triangle mask blended with simplex heat.")
|
||||
FRACTAL_SIERPINSKI_TRIANGLE(rng -> new CNG(rng, NoiseType.SIERPINSKI_TRIANGLE, 1D, 4).scale(1)),
|
||||
|
||||
@Desc("Rigid Multi Fractal Simplex Noise. Single octave.")
|
||||
FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 1)),
|
||||
|
||||
@Desc("Billow Fractal Simplex Noise. 2 octaves.")
|
||||
BIOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 2)),
|
||||
|
||||
@Desc("FBM Fractal Simplex Noise. 2 octaves.")
|
||||
BIOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 2)),
|
||||
|
||||
@Desc("Rigid Multi Fractal Simplex Noise. 2 octaves.")
|
||||
BIOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 2)),
|
||||
|
||||
@Desc("Rigid Multi Fractal Simplex Noise. 3 octaves.")
|
||||
TRIOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 3)),
|
||||
|
||||
@Desc("Billow Fractal Simplex Noise. 3 octaves.")
|
||||
TRIOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 3)),
|
||||
|
||||
@Desc("FBM Fractal Simplex Noise. 3 octaves.")
|
||||
TRIOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 3)),
|
||||
|
||||
@Desc("Rigid Multi Fractal Simplex Noise. 4 octaves.")
|
||||
QUADOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 4)),
|
||||
|
||||
@Desc("Billow Fractal Simplex Noise. 4 octaves.")
|
||||
QUADOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 4)),
|
||||
|
||||
@Desc("FBM Fractal Simplex Noise. 4 octaves.")
|
||||
QUADOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 4)),
|
||||
|
||||
@Desc("Rigid Multi Fractal Simplex Noise. 5 octaves.")
|
||||
QUINTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 5)),
|
||||
|
||||
@Desc("Billow Fractal Simplex Noise. 5 octaves.")
|
||||
QUINTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 5)),
|
||||
|
||||
@Desc("FBM Fractal Simplex Noise. 5 octaves.")
|
||||
QUINTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 5)),
|
||||
|
||||
@Desc("Rigid Multi Fractal Simplex Noise. 6 octaves.")
|
||||
SEXOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 6)),
|
||||
|
||||
@Desc("Billow Fractal Simplex Noise. 6 octaves.")
|
||||
SEXOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 6)),
|
||||
|
||||
@Desc("FBM Fractal Simplex Noise. 6 octaves.")
|
||||
SEXOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 6)),
|
||||
|
||||
@Desc("Rigid Multi Fractal Simplex Noise. 7 octaves.")
|
||||
SEPTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 7)),
|
||||
|
||||
@Desc("Billow Fractal Simplex Noise. 7 octaves.")
|
||||
SEPTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 7)),
|
||||
|
||||
@Desc("FBM Fractal Simplex Noise. 7 octaves.")
|
||||
SEPTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 7)),
|
||||
|
||||
@Desc("Rigid Multi Fractal Simplex Noise. 8 octaves.")
|
||||
OCTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 8)),
|
||||
|
||||
@Desc("Billow Fractal Simplex Noise. 8 octaves.")
|
||||
OCTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 8)),
|
||||
|
||||
@Desc("FBM Fractal Simplex Noise. 8 octaves.")
|
||||
OCTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 8)),
|
||||
|
||||
@Desc("Rigid Multi Fractal Simplex Noise. 9 octaves.")
|
||||
NONOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 9)),
|
||||
|
||||
@Desc("Billow Fractal Simplex Noise. 9 octaves.")
|
||||
NONOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 9)),
|
||||
|
||||
@Desc("FBM Fractal Simplex Noise. 9 octaves.")
|
||||
NONOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 9)),
|
||||
|
||||
@Desc("Rigid Multi Fractal Simplex Noise. 10 octaves.")
|
||||
VIGOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 10)),
|
||||
|
||||
@Desc("Billow Fractal Simplex Noise. 10 octaves.")
|
||||
VIGOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 10)),
|
||||
|
||||
@Desc("FBM Fractal Simplex Noise. 10 octaves.")
|
||||
VIGOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 10)),
|
||||
|
||||
@Desc("Basic, Smooth & Fast Simplex noise. Uses 2 octaves")
|
||||
BIOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 2).scale(1D / 2D)),
|
||||
|
||||
@Desc("Basic, Smooth & Fast Simplex noise. Uses 3 octaves")
|
||||
TRIOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 3).scale(1D / 3D)),
|
||||
|
||||
@Desc("Basic, Smooth & Fast Simplex noise. Uses 4 octaves")
|
||||
QUADOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 4).scale(1D / 4D)),
|
||||
|
||||
@Desc("Basic, Smooth & Fast Simplex noise. Uses 5 octaves")
|
||||
QUINTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 5).scale(1D / 5D)),
|
||||
|
||||
@Desc("Basic, Smooth & Fast Simplex noise. Uses 6 octaves")
|
||||
SEXOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 6).scale(1D / 6D)),
|
||||
|
||||
@Desc("Basic, Smooth & Fast Simplex noise. Uses 7 octaves")
|
||||
SEPTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 7).scale(1D / 12D)),
|
||||
|
||||
@Desc("Basic, Smooth & Fast Simplex noise. Uses 8 octaves")
|
||||
OCTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 8).scale(1D / 25D)),
|
||||
|
||||
@Desc("Basic, Smooth & Fast Simplex noise. Uses 9 octaves")
|
||||
NONOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 9).scale(1D / 50D)),
|
||||
|
||||
@Desc("Basic, Smooth & Fast Simplex noise. Uses 10 octaves")
|
||||
VIGOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 10).scale(1D / 100D)),
|
||||
|
||||
@Desc("Glob noise is like cellular, but with globs...")
|
||||
GLOB(rng -> new CNG(rng, NoiseType.GLOB, 1D, 1)),
|
||||
|
||||
@Desc("Glob noise is like cellular, but with globs...")
|
||||
GLOB_IRIS(rng -> CNG.signature(rng, NoiseType.GLOB)),
|
||||
|
||||
@Desc("Glob noise is like cellular, but with globs...")
|
||||
GLOB_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.GLOB)),
|
||||
|
||||
@Desc("Glob noise is like cellular, but with globs...")
|
||||
GLOB_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.GLOB)),
|
||||
|
||||
@Desc("Glob noise is like cellular, but with globs...")
|
||||
GLOB_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.GLOB)),
|
||||
|
||||
@Desc("Cubic Noise")
|
||||
CUBIC(rng -> new CNG(rng, NoiseType.CUBIC, 1D, 1).scale(256)),
|
||||
|
||||
@Desc("Fractal Cubic Noise")
|
||||
FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 1).scale(2)),
|
||||
|
||||
@Desc("Fractal Cubic Noise With Iris Swirls")
|
||||
FRACTAL_CUBIC_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_CUBIC).scale(2)),
|
||||
|
||||
@Desc("Fractal Cubic Noise With Iris Swirls")
|
||||
FRACTAL_CUBIC_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_CUBIC).scale(2)),
|
||||
|
||||
@Desc("Fractal Cubic Noise With Iris Swirls")
|
||||
FRACTAL_CUBIC_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_CUBIC).scale(2)),
|
||||
|
||||
@Desc("Fractal Cubic Noise With Iris Swirls")
|
||||
FRACTAL_CUBIC_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.FRACTAL_CUBIC).scale(2)),
|
||||
|
||||
@Desc("Fractal Cubic Noise, 2 Octaves")
|
||||
BIOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 2).scale(2)),
|
||||
|
||||
@Desc("Fractal Cubic Noise, 3 Octaves")
|
||||
TRIOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 3).scale(1.5)),
|
||||
|
||||
@Desc("Fractal Cubic Noise, 4 Octaves")
|
||||
QUADOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 4).scale(1)),
|
||||
|
||||
@Desc("Cubic Noise")
|
||||
CUBIC_IRIS(rng -> CNG.signature(rng, NoiseType.CUBIC).scale(256)),
|
||||
|
||||
@Desc("Cubic Noise")
|
||||
CUBIC_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.CUBIC).scale(256)),
|
||||
|
||||
@Desc("Cubic Noise")
|
||||
CUBIC_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.CUBIC).scale(256)),
|
||||
|
||||
@Desc("Cubic Noise")
|
||||
CUBIC_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.CUBIC).scale(256)),
|
||||
|
||||
@Desc("Hexagonal cell noise distorted using Iris styled wispy noise.")
|
||||
HEXAGON_IRIS(rng -> CNG.signature(rng, NoiseType.HEXAGON).scale(1)),
|
||||
|
||||
@Desc("Hexagonal cell noise distorted using Iris styled wispy noise.")
|
||||
HEXAGON_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.HEXAGON).scale(1)),
|
||||
|
||||
@Desc("Hexagonal cell noise distorted using Iris styled wispy noise.")
|
||||
HEXAGON_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.HEXAGON).scale(1)),
|
||||
|
||||
@Desc("Hexagonal cell noise distorted using Iris styled wispy noise.")
|
||||
HEXAGON_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.HEXAGON).scale(1)),
|
||||
|
||||
@Desc("Hex James substitution pattern distorted using Iris styled wispy noise.")
|
||||
HEX_JAMES_IRIS(rng -> CNG.signature(rng, NoiseType.HEX_JAMES).scale(1)),
|
||||
|
||||
@Desc("Hex James substitution pattern distorted using Iris styled wispy noise.")
|
||||
HEX_JAMES_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.HEX_JAMES).scale(1)),
|
||||
|
||||
@Desc("Hex James substitution pattern distorted using Iris styled wispy noise.")
|
||||
HEX_JAMES_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.HEX_JAMES).scale(1)),
|
||||
|
||||
@Desc("Hex James substitution pattern distorted using Iris styled wispy noise.")
|
||||
HEX_JAMES_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.HEX_JAMES).scale(1)),
|
||||
|
||||
@Desc("Interlocked solid hex-cell simplex heatmap distorted using Iris styled wispy noise.")
|
||||
HEX_SIMPLEX_IRIS(rng -> CNG.signature(rng, NoiseType.HEX_SIMPLEX).scale(1)),
|
||||
|
||||
@Desc("Interlocked solid hex-cell simplex heatmap distorted using Iris styled wispy noise.")
|
||||
HEX_SIMPLEX_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.HEX_SIMPLEX).scale(1)),
|
||||
|
||||
@Desc("Interlocked solid hex-cell simplex heatmap distorted using Iris styled wispy noise.")
|
||||
HEX_SIMPLEX_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.HEX_SIMPLEX).scale(1)),
|
||||
|
||||
@Desc("Interlocked solid hex-cell simplex heatmap distorted using Iris styled wispy noise.")
|
||||
HEX_SIMPLEX_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.HEX_SIMPLEX).scale(1)),
|
||||
|
||||
@Desc("Hexagonal random-size gradient noise and distorted using Iris styled wispy noise.")
|
||||
HEX_RANDOM_SIZE_IRIS(rng -> CNG.signature(rng, NoiseType.HEX_RANDOM_SIZE).scale(1)),
|
||||
|
||||
@Desc("Hexagonal random-size gradient noise and distorted using Iris styled wispy noise.")
|
||||
HEX_RANDOM_SIZE_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.HEX_RANDOM_SIZE).scale(1)),
|
||||
|
||||
@Desc("Hexagonal random-size gradient noise and distorted using Iris styled wispy noise.")
|
||||
HEX_RANDOM_SIZE_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.HEX_RANDOM_SIZE).scale(1)),
|
||||
|
||||
@Desc("Hexagonal random-size gradient noise and distorted using Iris styled wispy noise.")
|
||||
HEX_RANDOM_SIZE_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.HEX_RANDOM_SIZE).scale(1)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders. Cells are distorted using Iris styled wispy noise.")
|
||||
CELLULAR_IRIS(rng -> CNG.signature(rng, NoiseType.CELLULAR)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders. Cells are distorted using Iris styled wispy noise.")
|
||||
CELLULAR_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.CELLULAR)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders. Cells are distorted using Iris styled wispy noise.")
|
||||
CELLULAR_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.CELLULAR)),
|
||||
|
||||
@Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders. Cells are distorted using Iris styled wispy noise.")
|
||||
CELLULAR_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.CELLULAR)),
|
||||
|
||||
@Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell")
|
||||
CELLULAR_HEIGHT(rng -> new CNG(rng, NoiseType.CELLULAR_HEIGHT, 1D, 1)),
|
||||
|
||||
@Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell, using the iris style.")
|
||||
CELLULAR_HEIGHT_IRIS(rng -> CNG.signature(rng, NoiseType.CELLULAR_HEIGHT)),
|
||||
|
||||
@Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell, using the iris style.")
|
||||
CELLULAR_HEIGHT_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.CELLULAR_HEIGHT)),
|
||||
|
||||
@Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell, using the iris style.")
|
||||
CELLULAR_HEIGHT_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.CELLULAR_HEIGHT)),
|
||||
|
||||
@Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell, using the iris style.")
|
||||
CELLULAR_HEIGHT_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.CELLULAR_HEIGHT)),
|
||||
|
||||
@Desc("Vascular noise gets higher as the position nears a cell border. Cells are distorted using Iris styled wispy noise.")
|
||||
VASCULAR_IRIS(rng -> CNG.signature(rng, NoiseType.VASCULAR)),
|
||||
|
||||
@Desc("Vascular noise gets higher as the position nears a cell border. Cells are distorted using Iris styled wispy noise.")
|
||||
VASCULAR_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.VASCULAR)),
|
||||
|
||||
@Desc("Vascular noise gets higher as the position nears a cell border. Cells are distorted using Iris styled wispy noise.")
|
||||
VASCULAR_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.VASCULAR)),
|
||||
|
||||
@Desc("Vascular noise gets higher as the position nears a cell border. Cells are distorted using Iris styled wispy noise.")
|
||||
VASCULAR_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.VASCULAR)),
|
||||
;
|
||||
|
||||
private final CNGFactory f;
|
||||
|
||||
NoiseStyle(CNGFactory f) {
|
||||
this.f = f;
|
||||
}
|
||||
|
||||
public ProceduralStream<Double> stream(RNG seed) {
|
||||
return create(seed).stream();
|
||||
}
|
||||
|
||||
public ProceduralStream<Double> stream(long seed) {
|
||||
return create(new RNG(seed)).stream();
|
||||
}
|
||||
|
||||
public CNG create(RNG seed) {
|
||||
CNG cng = f.create(seed).bake();
|
||||
cng.setLeakStyle(this);
|
||||
return cng;
|
||||
}
|
||||
|
||||
public IrisGeneratorStyle style() {
|
||||
return new IrisGeneratorStyle(this);
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.noise.expression;
|
||||
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import com.dfsek.paralithic.Expression;
|
||||
import com.dfsek.paralithic.eval.parser.Parser;
|
||||
import com.dfsek.paralithic.eval.parser.Scope;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.iris.engine.object.noise.expression.IrisExpressionFunction.FunctionContext;
|
||||
import art.arcane.iris.engine.object.annotations.ArrayType;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.engine.object.annotations.Required;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.iris.util.project.stream.ProceduralStream;
|
||||
import art.arcane.iris.util.project.stream.interpolation.Interpolated;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("Represents an Iris Expression")
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
public class IrisExpression extends IrisRegistrant {
|
||||
@ArrayType(type = IrisExpressionLoad.class, min = 1)
|
||||
@Desc("Variables to use in this expression")
|
||||
private KList<IrisExpressionLoad> variables = new KList<>();
|
||||
|
||||
@ArrayType(type = IrisExpressionFunction.class, min = 1)
|
||||
@Desc("Functions to use in this expression")
|
||||
private KList<IrisExpressionFunction> functions = new KList<>();
|
||||
|
||||
@Required
|
||||
@Desc("The expression. Inherited variables are x, y and z. Avoid using those variable names.")
|
||||
private String expression;
|
||||
|
||||
private transient AtomicCache<Expression> expressionCache = new AtomicCache<>();
|
||||
private transient AtomicCache<ProceduralStream<Double>> streamCache = new AtomicCache<>();
|
||||
|
||||
private Expression expression() {
|
||||
return expressionCache.aquire(() -> {
|
||||
Scope scope = new Scope(); // Create variable scope. This scope can hold both constants and invocation variables.
|
||||
Parser parser = new Parser();
|
||||
|
||||
try {
|
||||
for (IrisExpressionLoad i : variables) {
|
||||
scope.addInvocationVariable(i.getName());
|
||||
}
|
||||
|
||||
scope.addInvocationVariable("x");
|
||||
scope.addInvocationVariable("y");
|
||||
scope.addInvocationVariable("z");
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError("Script variable load failed in " + getLoadFile().getPath() + ".", e);
|
||||
}
|
||||
|
||||
for (IrisExpressionFunction f : functions) {
|
||||
if (!f.isValid()) continue;
|
||||
f.setData(getLoader());
|
||||
parser.registerFunction(f.getName(), f);
|
||||
}
|
||||
|
||||
try {
|
||||
return parser.parse(getExpression(), scope);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError("Script load failed in " + getLoadFile().getPath() + ".", e);
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
public ProceduralStream<Double> stream(RNG rng) {
|
||||
return streamCache.aquire(() -> ProceduralStream.of((x, z) -> evaluate(rng, x, z),
|
||||
(x, y, z) -> evaluate(rng, x, y, z), Interpolated.DOUBLE));
|
||||
}
|
||||
|
||||
public double evaluate(RNG rng, double x, double z) {
|
||||
double[] g = new double[3 + getVariables().size()];
|
||||
int m = 0;
|
||||
for (IrisExpressionLoad i : getVariables()) {
|
||||
g[m++] = i.getValue(rng, getLoader(), x, z);
|
||||
}
|
||||
|
||||
g[m++] = x;
|
||||
g[m++] = z;
|
||||
g[m] = -1;
|
||||
|
||||
return expression().evaluate(new FunctionContext(rng), g);
|
||||
}
|
||||
|
||||
public double evaluate(RNG rng, double x, double y, double z) {
|
||||
double[] g = new double[3 + getVariables().size()];
|
||||
int m = 0;
|
||||
for (IrisExpressionLoad i : getVariables()) {
|
||||
g[m++] = i.getValue(rng, getLoader(), x, y, z);
|
||||
}
|
||||
|
||||
g[m++] = x;
|
||||
g[m++] = y;
|
||||
g[m] = z;
|
||||
|
||||
return expression().evaluate(new FunctionContext(rng), g);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFolderName() {
|
||||
return "expressions";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeName() {
|
||||
return "Expression";
|
||||
}
|
||||
}
|
||||
-110
@@ -1,110 +0,0 @@
|
||||
package art.arcane.iris.engine.object.noise.expression;
|
||||
|
||||
import art.arcane.iris.engine.object.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.engine.object.runtime.IrisEngineStreamType;
|
||||
import com.dfsek.paralithic.functions.dynamic.Context;
|
||||
import com.dfsek.paralithic.functions.dynamic.DynamicFunction;
|
||||
import com.dfsek.paralithic.node.Statefulness;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
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 art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.volmlib.util.collection.KMap;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.NonNull;
|
||||
import lombok.Setter;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@Snippet("expression-function")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("Represents a function to use in your expression. Do not set the name to x, y, or z, also don't duplicate names.")
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
public class IrisExpressionFunction implements DynamicFunction {
|
||||
@Required
|
||||
@Desc("The function to assign this value to. Do not set the name to x, y, or z")
|
||||
private String name;
|
||||
|
||||
@Desc("If defined, this variable will use a generator style as it's value")
|
||||
private IrisGeneratorStyle styleValue = null;
|
||||
|
||||
@Desc("If defined, iris will use an internal stream from the engine as it's value")
|
||||
private IrisEngineStreamType engineStreamValue = null;
|
||||
|
||||
@MinNumber(2)
|
||||
@Desc("Number of arguments for the function")
|
||||
private int args = 2;
|
||||
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private transient final KMap<FunctionContext, Provider> cache = new KMap<>();
|
||||
private transient IrisData data;
|
||||
|
||||
public boolean isValid() {
|
||||
return styleValue != null || engineStreamValue != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getArgNumber() {
|
||||
if (engineStreamValue != null) return 2;
|
||||
return Math.max(args, 2);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public Statefulness statefulness() {
|
||||
return Statefulness.STATEFUL;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double eval(double... doubles) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double eval(@Nullable Context raw, double... args) {
|
||||
return cache.computeIfAbsent((FunctionContext) raw, context -> {
|
||||
assert context != null;
|
||||
if (engineStreamValue != null) {
|
||||
var stream = engineStreamValue.get(data.getEngine());
|
||||
return d -> stream.get(d[0], d[1]);
|
||||
}
|
||||
|
||||
if (styleValue != null) {
|
||||
return styleValue.createNoCache(context.rng, data)::noise;
|
||||
}
|
||||
|
||||
return d -> Double.NaN;
|
||||
}).eval(args);
|
||||
}
|
||||
|
||||
public record FunctionContext(@NonNull RNG rng) implements Context {
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
FunctionContext that = (FunctionContext) o;
|
||||
return rng.getSeed() == that.rng.getSeed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Long.hashCode(rng.getSeed());
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface Provider {
|
||||
double eval(double... args);
|
||||
}
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.noise.expression;
|
||||
|
||||
import art.arcane.iris.engine.object.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.engine.object.runtime.IrisEngineStreamType;
|
||||
import art.arcane.iris.engine.object.runtime.IrisEngineValueType;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.volmlib.util.cache.LazyBoundedCache;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.engine.object.annotations.Required;
|
||||
import art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.iris.util.project.noise.CNG;
|
||||
import art.arcane.iris.util.project.stream.ProceduralStream;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
@Snippet("expression-load")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("Represents a variable to use in your expression. Do not set the name to x, y, or z, also don't duplicate names.")
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
public class IrisExpressionLoad {
|
||||
private static final int STYLE_CACHE_SIZE = 8;
|
||||
@Required
|
||||
@Desc("The variable to assign this value to. Do not set the name to x, y, or z")
|
||||
private String name = "";
|
||||
|
||||
@Desc("If the style value is not defined, this value will be used")
|
||||
private double staticValue = -1;
|
||||
|
||||
@Desc("If defined, this variable will use a generator style as it's value")
|
||||
private IrisGeneratorStyle styleValue = null;
|
||||
|
||||
@Desc("If defined, iris will use an internal stream from the engine as it's value")
|
||||
private IrisEngineStreamType engineStreamValue = null;
|
||||
|
||||
@Desc("If defined, iris will use an internal value from the engine as it's value")
|
||||
private IrisEngineValueType engineValue = null;
|
||||
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private transient final Map<Engine, EngineCache> engineCaches =
|
||||
Collections.synchronizedMap(new IdentityHashMap<>());
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private transient final LazyBoundedCache<StandaloneStyleKey, CNG> standaloneStyleCache =
|
||||
new LazyBoundedCache<>(STYLE_CACHE_SIZE);
|
||||
|
||||
public double getValue(RNG rng, IrisData data, double x, double z) {
|
||||
if (engineValue != null) {
|
||||
Engine engine = requireEngine(data);
|
||||
return cacheFor(engine).value.aquire(() -> engineValue.get(engine));
|
||||
}
|
||||
|
||||
if (engineStreamValue != null) {
|
||||
Engine engine = requireEngine(data);
|
||||
return cacheFor(engine).stream.aquire(() -> engineStreamValue.get(engine)).get(x, z);
|
||||
}
|
||||
|
||||
if (styleValue != null) {
|
||||
return style(data, rng).noise(x, z);
|
||||
}
|
||||
|
||||
return staticValue;
|
||||
}
|
||||
|
||||
public double getValue(RNG rng, IrisData data, double x, double y, double z) {
|
||||
if (engineValue != null) {
|
||||
Engine engine = requireEngine(data);
|
||||
return cacheFor(engine).value.aquire(() -> engineValue.get(engine));
|
||||
}
|
||||
|
||||
if (engineStreamValue != null) {
|
||||
Engine engine = requireEngine(data);
|
||||
return cacheFor(engine).stream.aquire(() -> engineStreamValue.get(engine)).get(x, z);
|
||||
}
|
||||
|
||||
if (styleValue != null) {
|
||||
return style(data, rng).noise(x, y, z);
|
||||
}
|
||||
|
||||
return staticValue;
|
||||
}
|
||||
|
||||
private Engine requireEngine(IrisData data) {
|
||||
Engine engine = data.getEngine();
|
||||
if (engine == null) {
|
||||
throw new IllegalStateException("Expression variable '" + name + "' requires an active Iris engine.");
|
||||
}
|
||||
return engine;
|
||||
}
|
||||
|
||||
private EngineCache cacheFor(Engine engine) {
|
||||
synchronized (engineCaches) {
|
||||
Iterator<Map.Entry<Engine, EngineCache>> iterator = engineCaches.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
if (iterator.next().getKey().isClosed()) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
EngineCache cache = engineCaches.get(engine);
|
||||
if (cache != null) {
|
||||
return cache;
|
||||
}
|
||||
EngineCache created = new EngineCache();
|
||||
engineCaches.put(engine, created);
|
||||
return created;
|
||||
}
|
||||
}
|
||||
|
||||
private CNG style(IrisData data, RNG rng) {
|
||||
Engine engine = data.getEngine();
|
||||
long seed = rng.getSeed();
|
||||
if (engine != null) {
|
||||
return cacheFor(engine).styles.computeIfAbsent(seed,
|
||||
ignored -> styleValue.createNoCache(new RNG(seed), data));
|
||||
}
|
||||
StandaloneStyleKey key = new StandaloneStyleKey(data, seed);
|
||||
return standaloneStyleCache.computeIfAbsent(key,
|
||||
ignored -> styleValue.createNoCache(new RNG(seed), data));
|
||||
}
|
||||
|
||||
private static final class EngineCache {
|
||||
private final AtomicCache<ProceduralStream<Double>> stream = new AtomicCache<>();
|
||||
private final AtomicCache<Double> value = new AtomicCache<>();
|
||||
private final LazyBoundedCache<Long, CNG> styles = new LazyBoundedCache<>(STYLE_CACHE_SIZE);
|
||||
}
|
||||
|
||||
private static final class StandaloneStyleKey {
|
||||
private final IrisData data;
|
||||
private final long seed;
|
||||
|
||||
private StandaloneStyleKey(IrisData data, long seed) {
|
||||
this.data = data;
|
||||
this.seed = seed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) {
|
||||
return true;
|
||||
}
|
||||
if (!(other instanceof StandaloneStyleKey key)) {
|
||||
return false;
|
||||
}
|
||||
return data == key.data && seed == key.seed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return 31 * System.identityHashCode(data) + Long.hashCode(seed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.placement;
|
||||
|
||||
import art.arcane.iris.engine.object.prefab.TileData;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class DecayControlPlacer implements IObjectPlacer {
|
||||
private final IObjectPlacer delegate;
|
||||
|
||||
public DecayControlPlacer(IObjectPlacer delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHighest(int x, int z, IrisData data) {
|
||||
return delegate.getHighest(x, z, data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) {
|
||||
return delegate.getHighest(x, z, data, ignoreFluid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(int x, int y, int z, PlatformBlockState d) {
|
||||
delegate.set(x, y, z, d);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformBlockState get(int x, int y, int z) {
|
||||
return delegate.get(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPreventingDecay() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@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 isSolid(int x, int y, int z) {
|
||||
return delegate.isSolid(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUnderwater(int x, int z) {
|
||||
return delegate.isUnderwater(x, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getFluidHeight() {
|
||||
return delegate.getFluidHeight();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDebugSmartBore() {
|
||||
return delegate.isDebugSmartBore();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTile(int xx, int yy, int zz, TileData tile) {
|
||||
delegate.setTile(xx, yy, zz, tile);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void setData(int xx, int yy, int zz, T data) {
|
||||
delegate.setData(xx, yy, zz, data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @Nullable T getData(int xx, int yy, int zz, Class<T> t) {
|
||||
return delegate.getData(xx, yy, zz, t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Engine getEngine() {
|
||||
return delegate.getEngine();
|
||||
}
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.placement;
|
||||
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class FloatingObjectFootprint {
|
||||
private final int lowestSolidKeyY;
|
||||
private final int highestSolidKeyY;
|
||||
private final int centerX;
|
||||
private final int centerY;
|
||||
private final int centerZ;
|
||||
private final int tallestKx;
|
||||
private final int tallestKz;
|
||||
private final int tallestKxBottom;
|
||||
private final int tallestKzBottom;
|
||||
private final long[] footprintXZ;
|
||||
|
||||
private FloatingObjectFootprint(int lowestSolidKeyY, int highestSolidKeyY, int centerX, int centerY, int centerZ, int tallestKx, int tallestKz, int tallestKxBottom, int tallestKzBottom, long[] footprintXZ) {
|
||||
this.lowestSolidKeyY = lowestSolidKeyY;
|
||||
this.highestSolidKeyY = highestSolidKeyY;
|
||||
this.centerX = centerX;
|
||||
this.centerY = centerY;
|
||||
this.centerZ = centerZ;
|
||||
this.tallestKx = tallestKx;
|
||||
this.tallestKz = tallestKz;
|
||||
this.tallestKxBottom = tallestKxBottom;
|
||||
this.tallestKzBottom = tallestKzBottom;
|
||||
this.footprintXZ = footprintXZ;
|
||||
}
|
||||
|
||||
/**
|
||||
* Memoized per object instance, never in a global map: loadKey + declared dimensions is
|
||||
* not unique across packs or across hotloads (a block edit keeps the header W/H/D), so a
|
||||
* shared key space served stale or foreign footprints. A reload builds a new IrisObject,
|
||||
* which drops the memo for free.
|
||||
*/
|
||||
public static FloatingObjectFootprint compute(IrisObject obj) {
|
||||
return obj.floatingFootprint.aquire(() -> doCompute(obj));
|
||||
}
|
||||
|
||||
private static FloatingObjectFootprint doCompute(IrisObject obj) {
|
||||
int cx = obj.getCenter().getBlockX();
|
||||
int cy = obj.getCenter().getBlockY();
|
||||
int cz = obj.getCenter().getBlockZ();
|
||||
Map<Long, int[]> columnStats = new HashMap<>();
|
||||
|
||||
int[] globalHighestY = {Integer.MIN_VALUE};
|
||||
int[] globalHighestKx = {0};
|
||||
int[] globalHighestKz = {0};
|
||||
|
||||
obj.getBlocks().forEach((key, bd) -> {
|
||||
if (!bd.isSolid()) {
|
||||
return;
|
||||
}
|
||||
int kx = key.getBlockX();
|
||||
int ky = key.getBlockY();
|
||||
int kz = key.getBlockZ();
|
||||
long packed = ((long) kx << 32) | (kz & 0xFFFFFFFFL);
|
||||
int[] stats = columnStats.get(packed);
|
||||
if (stats == null) {
|
||||
stats = new int[]{ky, 1};
|
||||
columnStats.put(packed, stats);
|
||||
} else {
|
||||
if (ky < stats[0]) {
|
||||
stats[0] = ky;
|
||||
}
|
||||
stats[1]++;
|
||||
}
|
||||
if (ky > globalHighestY[0]) {
|
||||
globalHighestY[0] = ky;
|
||||
globalHighestKx[0] = kx;
|
||||
globalHighestKz[0] = kz;
|
||||
}
|
||||
});
|
||||
|
||||
long[] footprintArray = new long[columnStats.size()];
|
||||
int idx = 0;
|
||||
for (Long packed : columnStats.keySet()) {
|
||||
footprintArray[idx++] = packed;
|
||||
}
|
||||
|
||||
long tallestPacked = resolveTallestColumn(columnStats);
|
||||
int lowestSolidKeyY = columnStats.isEmpty() ? cy : columnStats.get(tallestPacked)[0];
|
||||
int highestSolidKeyY = columnStats.isEmpty() ? cy : globalHighestY[0];
|
||||
int tallestKx = columnStats.isEmpty() ? 0 : (int) (tallestPacked >> 32);
|
||||
int tallestKz = columnStats.isEmpty() ? 0 : (int) (tallestPacked & 0xFFFFFFFFL);
|
||||
int tallestKxBottom = columnStats.isEmpty() ? 0 : globalHighestKx[0];
|
||||
int tallestKzBottom = columnStats.isEmpty() ? 0 : globalHighestKz[0];
|
||||
return new FloatingObjectFootprint(lowestSolidKeyY, highestSolidKeyY, cx, cy, cz, tallestKx, tallestKz, tallestKxBottom, tallestKzBottom, footprintArray);
|
||||
}
|
||||
|
||||
private static long resolveTallestColumn(Map<Long, int[]> columnStats) {
|
||||
long bestPacked = 0L;
|
||||
int tallestCount = 0;
|
||||
int tallestLow = Integer.MAX_VALUE;
|
||||
for (Map.Entry<Long, int[]> e : columnStats.entrySet()) {
|
||||
int[] stats = e.getValue();
|
||||
int count = stats[1];
|
||||
int low = stats[0];
|
||||
if (count > tallestCount || (count == tallestCount && low < tallestLow)) {
|
||||
tallestCount = count;
|
||||
tallestLow = low;
|
||||
bestPacked = e.getKey();
|
||||
}
|
||||
}
|
||||
return bestPacked;
|
||||
}
|
||||
|
||||
public int lowestSolidRelCenterY() {
|
||||
return lowestSolidKeyY - centerY;
|
||||
}
|
||||
|
||||
public int getLowestSolidKeyY() {
|
||||
return lowestSolidKeyY;
|
||||
}
|
||||
|
||||
public int getCenterX() {
|
||||
return centerX;
|
||||
}
|
||||
|
||||
public int getCenterY() {
|
||||
return centerY;
|
||||
}
|
||||
|
||||
public int getCenterZ() {
|
||||
return centerZ;
|
||||
}
|
||||
|
||||
public int getTallestKx() {
|
||||
return tallestKx;
|
||||
}
|
||||
|
||||
public int getTallestKz() {
|
||||
return tallestKz;
|
||||
}
|
||||
|
||||
public int getHighestSolidKeyY() {
|
||||
return highestSolidKeyY;
|
||||
}
|
||||
|
||||
public int getTallestKxBottom() {
|
||||
return tallestKxBottom;
|
||||
}
|
||||
|
||||
public int getTallestKzBottom() {
|
||||
return tallestKzBottom;
|
||||
}
|
||||
|
||||
public long[] footprintXZ() {
|
||||
return footprintXZ;
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.placement;
|
||||
|
||||
import art.arcane.iris.engine.object.prefab.TileData;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public interface IObjectPlacer {
|
||||
int getHighest(int x, int z, IrisData data);
|
||||
|
||||
int getHighest(int x, int z, IrisData data, boolean ignoreFluid);
|
||||
|
||||
void set(int x, int y, int z, PlatformBlockState d);
|
||||
|
||||
PlatformBlockState get(int x, int y, int z);
|
||||
|
||||
boolean isPreventingDecay();
|
||||
|
||||
boolean isCarved(int x, int y, int z);
|
||||
|
||||
/**
|
||||
* Whether the block at this position is real, solid ground. Only live-world placers can answer this;
|
||||
* at mantle time terrain has not been written yet, so the height stream is the authority.
|
||||
*/
|
||||
default boolean isSurfaceSolid(int x, int y, int z) {
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean isSolid(int x, int y, int z);
|
||||
|
||||
boolean isUnderwater(int x, int z);
|
||||
|
||||
int getFluidHeight();
|
||||
|
||||
boolean isDebugSmartBore();
|
||||
|
||||
void setTile(int xx, int yy, int zz, TileData tile);
|
||||
|
||||
<T> void setData(int xx, int yy, int zz, T data);
|
||||
|
||||
<T> @Nullable T getData(int xx, int yy, int zz, Class<T> t);
|
||||
|
||||
Engine getEngine();
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.placement;
|
||||
|
||||
import art.arcane.iris.engine.object.terrain.carving.CaveResult;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import org.bukkit.generator.ChunkGenerator.ChunkData;
|
||||
|
||||
public interface IPostBlockAccess {
|
||||
PlatformBlockState getPostBlock(int x, int y, int z, int currentPostX, int currentPostZ, ChunkData currentData);
|
||||
|
||||
void setPostBlock(int x, int y, int z, PlatformBlockState d, int currentPostX, int currentPostZ, ChunkData currentData);
|
||||
|
||||
int highestTerrainOrFluidBlock(int x, int z);
|
||||
|
||||
int highestTerrainBlock(int x, int z);
|
||||
|
||||
void updateHeight(int x, int z, int h);
|
||||
|
||||
KList<CaveResult> caveFloors(int x, int z);
|
||||
}
|
||||
@@ -1,325 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.placement;
|
||||
|
||||
import art.arcane.iris.builtin.carve.CarvingMode;
|
||||
import art.arcane.iris.builtin.objects.TreeOverride;
|
||||
import art.arcane.iris.builtin.carve.CaveAnchorMode;
|
||||
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
|
||||
import art.arcane.iris.builtin.blocks.ObjectReplace;
|
||||
import art.arcane.iris.builtin.stilt.StiltSettings;
|
||||
import art.arcane.iris.builtin.prepare.SlopeClip;
|
||||
import art.arcane.iris.builtin.vacuum.VacuumSettings;
|
||||
import art.arcane.iris.builtin.validate.ObjectLimit;
|
||||
import art.arcane.iris.core.modules.ModuleSettings;
|
||||
import art.arcane.iris.builtin.loot.ObjectLoot;
|
||||
import art.arcane.iris.builtin.loot.ObjectVanillaLoot;
|
||||
import art.arcane.iris.builtin.spawn.PlacementMarker;
|
||||
import art.arcane.iris.engine.object.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.engine.object.noise.IrisNoiseGenerator;
|
||||
import art.arcane.iris.engine.object.noise.IrisStyledRange;
|
||||
import art.arcane.iris.engine.object.noise.NoiseStyle;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObjectRotation;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObjectScale;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObjectTranslate;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.volmlib.util.cache.LazyBoundedCache;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
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.Required;
|
||||
import art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.iris.util.common.data.DataProvider;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.iris.util.project.noise.CNG;
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
|
||||
@Snippet("object-placer")
|
||||
@EqualsAndHashCode()
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("Represents an iris object placer. It places objects.")
|
||||
@Data
|
||||
public class IrisObjectPlacement {
|
||||
private static final int SURFACE_WARP_CACHE_SIZE = 8;
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private final transient LazyBoundedCache<SurfaceWarpCacheKey, CNG> surfaceWarpCache =
|
||||
new LazyBoundedCache<>(SURFACE_WARP_CACHE_SIZE);
|
||||
@RegistryListResource(IrisObject.class)
|
||||
@Required
|
||||
@ArrayType(min = 1, type = String.class)
|
||||
@Desc("List of objects to place")
|
||||
private KList<String> place = new KList<>();
|
||||
@Desc("Rotate this objects placement")
|
||||
private IrisObjectRotation rotation = new IrisObjectRotation();
|
||||
@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;
|
||||
@MinNumber(1)
|
||||
@Desc("If the chance check passes, place this many in a single chunk")
|
||||
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 IrisStyledRange 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;
|
||||
@ArrayType(min = 1, type = PlacementMarker.class)
|
||||
@Desc("Add markers to blocks in this object")
|
||||
private KList<PlacementMarker> markers = new KList<>();
|
||||
@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 = 2;
|
||||
@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 = 2;
|
||||
@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 IrisNoiseGenerator 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 IrisGeneratorStyle warp = new IrisGeneratorStyle(NoiseStyle.FLAT);
|
||||
@Desc("The placement mode")
|
||||
private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT;
|
||||
@ArrayType(min = 1, type = ObjectReplace.class)
|
||||
@Desc("Find and replace blocks")
|
||||
private KList<ObjectReplace> edit = new KList<>();
|
||||
@Desc("Translate this object's placement")
|
||||
private IrisObjectTranslate translate = new IrisObjectTranslate();
|
||||
@Desc("Scale Objects")
|
||||
private IrisObjectScale scale = new IrisObjectScale();
|
||||
@ArrayType(min = 1, type = ObjectLoot.class)
|
||||
@Desc("The loot tables to apply to these objects")
|
||||
private KList<ObjectLoot> loot = new KList<>();
|
||||
@ArrayType(min = 1, type = ObjectVanillaLoot.class)
|
||||
@Desc("The vanilla loot tables to apply to these objects")
|
||||
private KList<ObjectVanillaLoot> vanillaLoot = new KList<>();
|
||||
@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...")
|
||||
@ArrayType(min = 1, type = TreeOverride.class)
|
||||
private KList<TreeOverride> trees = new KList<>();
|
||||
@RegistryListResource(IrisObject.class)
|
||||
@ArrayType(type = String.class)
|
||||
@Desc("List of objects to this object is allowed to collied with")
|
||||
private KList<String> allowedCollisions = new KList<>();
|
||||
@RegistryListResource(IrisObject.class)
|
||||
@ArrayType(type = String.class)
|
||||
@Desc("List of objects to this object is forbidden to collied with")
|
||||
private KList<String> forbiddenCollisions = new KList<>();
|
||||
@Desc("Ignore any placement restrictions for this object")
|
||||
@SerializedName(value = "forcePlace", alternate = {"force"})
|
||||
private boolean forcePlace = false;
|
||||
/** The pack modules' settings this placement declares, decoded with it. */
|
||||
private transient ModuleSettings moduleSettings = ModuleSettings.NONE;
|
||||
|
||||
/** A placement that stamps each object exactly at the position it is given, as a structure piece. */
|
||||
public static IrisObjectPlacement stampingStructurePieces() {
|
||||
return new IrisObjectPlacement().setMode(ObjectPlaceMode.STRUCTURE_PIECE);
|
||||
}
|
||||
|
||||
public IrisObjectPlacement toPlacement(String... place) {
|
||||
IrisObjectPlacement p = new IrisObjectPlacement();
|
||||
p.setPlace(new KList<>(place));
|
||||
p.setMode(mode);
|
||||
p.setEdit(edit);
|
||||
p.setTranslate(translate);
|
||||
p.setScale(scale);
|
||||
p.setWarp(warp);
|
||||
p.setBore(bore);
|
||||
p.setMeld(meld);
|
||||
p.setWaterloggable(waterloggable);
|
||||
p.setOnwater(onwater);
|
||||
p.setFromBottom(fromBottom);
|
||||
p.setBottom(bottom);
|
||||
p.setSmartBore(smartBore);
|
||||
p.setCarvingSupport(carvingSupport);
|
||||
p.setSurfaceSupportBuffer(surfaceSupportBuffer);
|
||||
p.setSurfaceSupportDepth(surfaceSupportDepth);
|
||||
p.setRequireSurfaceSupport(requireSurfaceSupport);
|
||||
p.setCaveAnchorMode(caveAnchorMode);
|
||||
p.setUnderwater(underwater);
|
||||
p.setHeightmap(heightmap);
|
||||
p.setBoreExtendMaxY(boreExtendMaxY);
|
||||
p.setBoreExtendMinY(boreExtendMinY);
|
||||
p.setStiltSettings(stiltSettings);
|
||||
p.setVacuumSettings(vacuumSettings);
|
||||
p.setDensity(density);
|
||||
p.setDensityStyle(densityStyle);
|
||||
p.setChance(chance);
|
||||
p.setSnow(snow);
|
||||
p.setClamp(clamp);
|
||||
p.setRotation(rotation);
|
||||
p.setSlopeCondition(slopeCondition);
|
||||
p.setRotateTowardsSlope(rotateTowardsSlope);
|
||||
p.setDolphinTarget(isDolphinTarget);
|
||||
p.setMarkers(markers);
|
||||
p.setLoot(loot);
|
||||
p.setVanillaLoot(vanillaLoot);
|
||||
p.setOverrideGlobalLoot(overrideGlobalLoot);
|
||||
p.setTrees(trees);
|
||||
p.setAllowedCollisions(allowedCollisions);
|
||||
p.setForbiddenCollisions(forbiddenCollisions);
|
||||
p.setForcePlace(forcePlace);
|
||||
p.setModuleSettings(moduleSettings);
|
||||
return p;
|
||||
}
|
||||
|
||||
public CNG getSurfaceWarp(RNG rng, IrisData data) {
|
||||
return getSurfaceWarp(rng, data, data.getEngine());
|
||||
}
|
||||
|
||||
public CNG getSurfaceWarp(RNG rng, IrisData data, @Nullable Engine engine) {
|
||||
long seed = engine == null ? rng.getSeed() : engine.getSeedManager().getComponent() + 1024L;
|
||||
SurfaceWarpCacheKey key = new SurfaceWarpCacheKey(data, engine, seed);
|
||||
return surfaceWarpCache.computeIfAbsent(key,
|
||||
ignored -> getWarp().create(new RNG(seed), data, engine));
|
||||
}
|
||||
|
||||
public double warp(RNG rng, double x, double y, double z, IrisData data) {
|
||||
return getSurfaceWarp(rng, data).fitDouble(-(getWarp().getMultiplier() / 2D), (getWarp().getMultiplier() / 2D), x, y, z);
|
||||
}
|
||||
|
||||
public IrisObject getObject(DataProvider g, RNG random) {
|
||||
if (place.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return g.getData().getObjectLoader().load(place.get(random.nextInt(place.size())));
|
||||
}
|
||||
|
||||
/** Whether a tree placement grows the species the platform calls {@code species} for a sapling area of {@code width} by {@code depth}. */
|
||||
public boolean matches(int width, int depth, String species) {
|
||||
for (TreeOverride tree : getTrees()) {
|
||||
if (tree.matches(width, depth, species)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public int getDensity() {
|
||||
if (densityStyle == null) {
|
||||
return density;
|
||||
}
|
||||
return densityStyle.getMid();
|
||||
}
|
||||
|
||||
public int getDensity(RNG rng, double x, double z, IrisData data) {
|
||||
if (densityStyle == null) {
|
||||
return density;
|
||||
}
|
||||
|
||||
return (int) Math.round(densityStyle.get(rng, x, z, data));
|
||||
}
|
||||
|
||||
private static final class SurfaceWarpCacheKey {
|
||||
private final IrisData data;
|
||||
private final Engine engine;
|
||||
private final long seed;
|
||||
|
||||
private SurfaceWarpCacheKey(IrisData data, Engine engine, long seed) {
|
||||
this.data = data;
|
||||
this.engine = engine;
|
||||
this.seed = seed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) {
|
||||
return true;
|
||||
}
|
||||
if (!(other instanceof SurfaceWarpCacheKey key)) {
|
||||
return false;
|
||||
}
|
||||
return data == key.data && engine == key.engine && seed == key.seed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = System.identityHashCode(data);
|
||||
result = 31 * result + System.identityHashCode(engine);
|
||||
return 31 * result + Long.hashCode(seed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.placement;
|
||||
|
||||
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.TreeGrowthSettings;
|
||||
import art.arcane.iris.builtin.objects.UpperObjectsForceSettings;
|
||||
import art.arcane.iris.builtin.objects.UpperObjectsSettings;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.WeakHashMap;
|
||||
|
||||
/**
|
||||
* The object placements a region or biome declares, as Iris places them: the module settings of
|
||||
* {@code iris:objects}, made into Iris's own placements once and kept for as long as the settings live.
|
||||
*/
|
||||
public final class ObjectPlacements {
|
||||
private static final Map<ObjectSettings, Placements> PLACEMENTS = Collections.synchronizedMap(new WeakHashMap<>());
|
||||
|
||||
private ObjectPlacements() {
|
||||
}
|
||||
|
||||
/** Every placement {@code owner} declares. */
|
||||
public static KList<IrisObjectPlacement> all(IrisRegistrant owner) {
|
||||
return placementsOf(owner).all;
|
||||
}
|
||||
|
||||
/** The placements of {@code owner} that place on the surface. */
|
||||
public static KList<IrisObjectPlacement> surface(IrisRegistrant owner) {
|
||||
return placementsOf(owner).surface;
|
||||
}
|
||||
|
||||
/** The placements of {@code owner} that place in carvings. */
|
||||
public static KList<IrisObjectPlacement> carving(IrisRegistrant owner) {
|
||||
return placementsOf(owner).carving;
|
||||
}
|
||||
|
||||
/** Whether {@code dimension} places its objects in the terrain stacked above it too. */
|
||||
public static boolean upperObjects(IrisRegistrant dimension) {
|
||||
return dimension.getModuleSettings().find(UpperObjectsSettings.class).map(UpperObjectsSettings::enabled).orElse(false);
|
||||
}
|
||||
|
||||
/** Whether the objects placed in the terrain stacked above ignore placement restrictions. */
|
||||
public static boolean upperObjectsForced(IrisRegistrant dimension) {
|
||||
return dimension.getModuleSettings().find(UpperObjectsForceSettings.class).map(UpperObjectsForceSettings::force).orElse(false);
|
||||
}
|
||||
|
||||
/** Whether {@code dimension} refuses surface objects over carved openings. */
|
||||
public static boolean requiresSurfaceSupport(IrisRegistrant dimension) {
|
||||
return dimension.getModuleSettings().find(RequireSurfaceSupportSettings.class).map(RequireSurfaceSupportSettings::require)
|
||||
.orElse(NO_SURFACE_SUPPORT_REQUIREMENT.require());
|
||||
}
|
||||
|
||||
/** The least surface-support buffer {@code dimension} gives its surface objects. */
|
||||
public static int surfaceSupportBuffer(IrisRegistrant dimension) {
|
||||
return dimension.getModuleSettings().find(SurfaceSupportBufferSettings.class).map(SurfaceSupportBufferSettings::buffer)
|
||||
.orElse(NO_SURFACE_SUPPORT_BUFFER.buffer());
|
||||
}
|
||||
|
||||
/** The tree growth settings of {@code dimension}. */
|
||||
public static TreeGrowthSettings treeGrowth(IrisRegistrant dimension) {
|
||||
return dimension.getModuleSettings().find(TreeGrowthSettings.class).orElse(NO_TREE_GROWTH);
|
||||
}
|
||||
|
||||
/** Iris's placement for the settings {@code placement}, read from the JSON it was written as. */
|
||||
public static IrisObjectPlacement host(ObjectPlacement placement, IrisData data) {
|
||||
Object kept = placement.hostForm();
|
||||
if (kept instanceof IrisObjectPlacement hostPlacement) {
|
||||
return hostPlacement;
|
||||
}
|
||||
IrisObjectPlacement made = data.getGson().fromJson(placement.json(), IrisObjectPlacement.class);
|
||||
placement.hostForm(made);
|
||||
return made;
|
||||
}
|
||||
|
||||
private static final RequireSurfaceSupportSettings NO_SURFACE_SUPPORT_REQUIREMENT = new RequireSurfaceSupportSettings();
|
||||
private static final SurfaceSupportBufferSettings NO_SURFACE_SUPPORT_BUFFER = new SurfaceSupportBufferSettings();
|
||||
private static final TreeGrowthSettings NO_TREE_GROWTH = new TreeGrowthSettings();
|
||||
private static final ObjectSettings NO_OBJECTS = new ObjectSettings();
|
||||
|
||||
private static Placements placementsOf(IrisRegistrant owner) {
|
||||
ObjectSettings settings = owner.getModuleSettings().find(ObjectSettings.class).orElse(NO_OBJECTS);
|
||||
Placements found = PLACEMENTS.get(settings);
|
||||
if (found != null) {
|
||||
return found;
|
||||
}
|
||||
return PLACEMENTS.computeIfAbsent(settings, declared -> new Placements(declared, owner.getLoader()));
|
||||
}
|
||||
|
||||
private record Placements(KList<IrisObjectPlacement> all, KList<IrisObjectPlacement> surface, KList<IrisObjectPlacement> carving) {
|
||||
Placements(ObjectSettings settings, IrisData data) {
|
||||
this(new KList<>(), new KList<>(), new KList<>());
|
||||
for (ObjectPlacement declared : settings.objects()) {
|
||||
IrisObjectPlacement placement = host(declared, data);
|
||||
all.add(placement);
|
||||
if (placement.getCarvingSupport().supportsSurface()) {
|
||||
surface.add(placement);
|
||||
}
|
||||
if (placement.getCarvingSupport().supportsCarving()) {
|
||||
carving.add(placement);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,409 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.prefab;
|
||||
|
||||
import art.arcane.iris.builtin.objects.PlaceableObject;
|
||||
import art.arcane.iris.engine.object.placement.FloatingObjectFootprint;
|
||||
import art.arcane.iris.engine.object.placement.IObjectPlacer;
|
||||
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
|
||||
import art.arcane.iris.engine.object.terrain.carving.CarveResult;
|
||||
import art.arcane.iris.engine.object.value.IrisPosition;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.ModuleObjectPlacement;
|
||||
import art.arcane.iris.core.modules.ObjectGeometry;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.iris.platform.bukkit.BukkitBlockState;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.iris.util.common.data.B;
|
||||
import art.arcane.volmlib.util.data.VectorMap;
|
||||
import art.arcane.iris.util.common.math.AxisAlignedBB;
|
||||
import art.arcane.volmlib.util.math.IrisBlockVector;
|
||||
import art.arcane.volmlib.util.math.IrisVector;
|
||||
import art.arcane.volmlib.util.math.Vector3i;
|
||||
import art.arcane.iris.util.common.plugin.VolmitSender;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.math.BlockPosition;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import com.volmit.object.GeneratedObject;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
/**
|
||||
* A voxel volume loaded from a .iob file. Instances are loader cached and shared across generation threads, so all
|
||||
* volume access goes through the read/write lock pair below.
|
||||
* <p>
|
||||
* The heavy behaviour lives in package-private collaborators that read this state directly:
|
||||
* {@link IrisObjectIO} (binary persistence), {@link IrisObjectShaping} (boring, shrinkwrap, block classification),
|
||||
* {@link IrisObjectTransforms} (rotation, scaling, interpolated upscaling) and {@link ModuleObjectPlacement}
|
||||
* (world placement).
|
||||
*/
|
||||
@Accessors(chain = true)
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
public class IrisObject extends IrisRegistrant implements PlaceableObject {
|
||||
protected static final IrisVector HALF = new IrisVector(0.5, 0.5, 0.5);
|
||||
public static final class States {
|
||||
public static final PlatformBlockState AIR = B.getState("CAVE_AIR");
|
||||
public static final PlatformBlockState STONE = B.getState("STONE");
|
||||
public static final PlatformBlockState VAIR = B.getState("VOID_AIR");
|
||||
public static final PlatformBlockState VAIR_DEBUG = B.getState("COBWEB");
|
||||
public static final PlatformBlockState[] SNOW_LAYERS = new PlatformBlockState[]{B.getState("minecraft:snow[layers=1]"), B.getState("minecraft:snow[layers=2]"), B.getState("minecraft:snow[layers=3]"), B.getState("minecraft:snow[layers=4]"), B.getState("minecraft:snow[layers=5]"), B.getState("minecraft:snow[layers=6]"), B.getState("minecraft:snow[layers=7]"), B.getState("minecraft:snow[layers=8]")};
|
||||
}
|
||||
public transient final Lock readLock;
|
||||
protected transient final Lock writeLock;
|
||||
@Getter
|
||||
@Setter
|
||||
protected transient volatile boolean smartBored = false;
|
||||
@Setter
|
||||
protected transient AtomicCache<AxisAlignedBB> aabb = new AtomicCache<>();
|
||||
transient final AtomicCache<KList<IrisBlockVector>> surfaceSupportOffsets = new AtomicCache<>();
|
||||
public transient final AtomicCache<FloatingObjectFootprint> floatingFootprint = new AtomicCache<>();
|
||||
private transient final AtomicCache<GeneratedObject> geometry = new AtomicCache<>();
|
||||
@Getter
|
||||
public VectorMap<PlatformBlockState> blocks;
|
||||
@Getter
|
||||
public VectorMap<TileData> states;
|
||||
@Getter
|
||||
@Setter
|
||||
public int w;
|
||||
@Getter
|
||||
@Setter
|
||||
public int d;
|
||||
@Getter
|
||||
@Setter
|
||||
public int h;
|
||||
@Getter
|
||||
@Setter
|
||||
transient Vector3i center;
|
||||
@Getter
|
||||
transient Vector3i shrinkOffset;
|
||||
|
||||
public IrisObject(int w, int h, int d) {
|
||||
blocks = new VectorMap<>();
|
||||
states = new VectorMap<>();
|
||||
this.w = w;
|
||||
this.h = h;
|
||||
this.d = d;
|
||||
center = new Vector3i(w / 2, h / 2, d / 2);
|
||||
shrinkOffset = new Vector3i(0, 0, 0);
|
||||
var lock = new ReentrantReadWriteLock();
|
||||
readLock = lock.readLock();
|
||||
writeLock = lock.writeLock();
|
||||
}
|
||||
|
||||
public IrisObject() {
|
||||
this(0, 0, 0);
|
||||
}
|
||||
|
||||
public static AxisAlignedBB getAABBFor(IrisBlockVector size) {
|
||||
IrisBlockVector center = new IrisBlockVector(size.getX() / 2, size.getY() / 2, size.getZ() / 2);
|
||||
IrisVector min = new IrisBlockVector(0, 0, 0).subtract(center);
|
||||
IrisVector max = new IrisBlockVector(size.getX() - 1, size.getY() - 1, size.getZ() - 1).subtract(center);
|
||||
return new AxisAlignedBB(new IrisPosition(min.getBlockX(), min.getBlockY(), min.getBlockZ()),
|
||||
new IrisPosition(max.getBlockX(), max.getBlockY(), max.getBlockZ()));
|
||||
}
|
||||
|
||||
public static IrisBlockVector sampleSize(File file) throws IOException {
|
||||
return IrisObjectIO.sampleSize(file);
|
||||
}
|
||||
|
||||
public AxisAlignedBB getAABB() {
|
||||
return aabb.aquire(() -> getAABBFor(new IrisBlockVector(w, h, d)));
|
||||
}
|
||||
|
||||
public synchronized IrisObject copy() {
|
||||
IrisObject o = new IrisObject(w, h, d);
|
||||
o.setLoadKey(getLoadKey());
|
||||
o.setLoader(getLoader());
|
||||
o.setLoadFile(getLoadFile());
|
||||
o.setCenter(getCenter().clone());
|
||||
|
||||
blocks.forEach((i, v) -> o.blocks.put(i.clone(), v));
|
||||
states.forEach((i, v) -> o.states.put(i.clone(), v.clone()));
|
||||
|
||||
return o;
|
||||
}
|
||||
|
||||
public void readLegacy(InputStream in) throws IOException {
|
||||
IrisObjectIO.readLegacy(this, in);
|
||||
}
|
||||
|
||||
public void read(InputStream in) throws Throwable {
|
||||
IrisObjectIO.read(this, in);
|
||||
}
|
||||
|
||||
public void read(File file) throws IOException {
|
||||
IrisObjectIO.read(this, file);
|
||||
}
|
||||
|
||||
public void write(OutputStream o) throws IOException {
|
||||
IrisObjectIO.write(this, o);
|
||||
}
|
||||
|
||||
public void write(OutputStream o, VolmitSender sender) throws IOException {
|
||||
IrisObjectIO.write(this, o, sender);
|
||||
}
|
||||
|
||||
public void write(File file) throws IOException {
|
||||
IrisObjectIO.write(this, file);
|
||||
}
|
||||
|
||||
public void write(File file, VolmitSender sender) throws IOException {
|
||||
IrisObjectIO.write(this, file, sender);
|
||||
}
|
||||
|
||||
public void shrinkwrap() {
|
||||
// Instances are loader cached and shared across generation threads; mutating the
|
||||
// volume without the write lock let a concurrent placement mix pre-shrink anchors
|
||||
// with post-shrink blocks. Rotation paths call the package-private statics while
|
||||
// already holding this (reentrant) lock.
|
||||
writeLock.lock();
|
||||
try {
|
||||
IrisObjectShaping.shrinkwrap(this);
|
||||
} finally {
|
||||
writeLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void clean() {
|
||||
writeLock.lock();
|
||||
try {
|
||||
IrisObjectShaping.clean(this);
|
||||
} finally {
|
||||
writeLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public IrisBlockVector getSigned(int x, int y, int z) {
|
||||
if (x >= w || y >= h || z >= d) {
|
||||
throw new RuntimeException(x + " " + y + " " + z + " exceeds limit of " + w + " " + h + " " + d);
|
||||
}
|
||||
|
||||
return new IrisBlockVector(x - center.getX(), y - center.getY(), z - center.getZ());
|
||||
}
|
||||
|
||||
public void setUnsigned(int x, int y, int z, PlatformBlockState block) {
|
||||
IrisBlockVector v = getSigned(x, y, z);
|
||||
|
||||
if (block == null) {
|
||||
blocks.remove(v);
|
||||
states.remove(v);
|
||||
} else {
|
||||
blocks.put(v, block);
|
||||
}
|
||||
|
||||
forgetDerivedShapes();
|
||||
}
|
||||
|
||||
public void setUnsignedTile(int x, int y, int z, TileData tile) {
|
||||
IrisBlockVector v = getSigned(x, y, z);
|
||||
|
||||
if (tile == null) {
|
||||
states.remove(v);
|
||||
} else {
|
||||
states.put(v, tile);
|
||||
}
|
||||
|
||||
forgetDerivedShapes();
|
||||
}
|
||||
|
||||
public void setUnsigned(int x, int y, int z, Block block, boolean legacy) {
|
||||
IrisBlockVector v = getSigned(x, y, z);
|
||||
|
||||
if (block == null) {
|
||||
blocks.remove(v);
|
||||
states.remove(v);
|
||||
} else {
|
||||
BlockData data = block.getBlockData();
|
||||
blocks.put(v, BukkitBlockState.of(data));
|
||||
TileData state = TileData.getTileState(block, legacy);
|
||||
if (state != null) {
|
||||
IrisLogging.debug("Saved State " + v);
|
||||
states.put(v, state);
|
||||
}
|
||||
}
|
||||
|
||||
forgetDerivedShapes();
|
||||
}
|
||||
|
||||
public int place(int x, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, IrisData rdata) {
|
||||
return place(x, -1, z, placer, config, rng, rdata);
|
||||
}
|
||||
|
||||
public int place(int x, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, CarveResult c, IrisData rdata) {
|
||||
return place(x, -1, z, placer, config, rng, null, c, rdata);
|
||||
}
|
||||
|
||||
public int place(int x, int yv, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, IrisData rdata) {
|
||||
return place(x, yv, z, placer, config, rng, null, null, rdata);
|
||||
}
|
||||
|
||||
public int place(Location loc, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, IrisData rdata) {
|
||||
return place(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), placer, config, rng, rdata);
|
||||
}
|
||||
|
||||
/** The height the object was placed at, or -1 when the placement rejected it. */
|
||||
public int place(int x, int yv, int z, IObjectPlacer oplacer, IrisObjectPlacement config, RNG rng, BiConsumer<BlockPosition, PlatformBlockState> listener, CarveResult c, IrisData rdata) {
|
||||
return ModuleObjectPlacement.place(this, x, yv, z, oplacer, config, rng, listener, c, rdata).heightOrRejected();
|
||||
}
|
||||
|
||||
/** This object as IrisApi geometry, read once until its blocks change. */
|
||||
public GeneratedObject getGeometry() {
|
||||
return geometry.aquireOrThrow(() -> ObjectGeometry.of(this));
|
||||
}
|
||||
|
||||
/** Drops what is computed from the blocks, after they change. */
|
||||
void forgetDerivedShapes() {
|
||||
surfaceSupportOffsets.reset();
|
||||
floatingFootprint.reset();
|
||||
geometry.reset();
|
||||
}
|
||||
|
||||
public KList<IrisBlockVector> getSurfaceSupportOffsets() {
|
||||
return surfaceSupportOffsets.aquire(() -> {
|
||||
readLock.lock();
|
||||
try {
|
||||
int lowestY = Integer.MAX_VALUE;
|
||||
KList<IrisBlockVector> offsets = new KList<>();
|
||||
for (Map.Entry<IrisBlockVector, PlatformBlockState> entry : blocks) {
|
||||
PlatformBlockState state = entry.getValue();
|
||||
if (state == null || !state.isSolid() || state.isFoliage()) {
|
||||
continue;
|
||||
}
|
||||
IrisBlockVector position = entry.getKey();
|
||||
int blockY = position.getBlockY();
|
||||
if (blockY < lowestY) {
|
||||
lowestY = blockY;
|
||||
offsets.clear();
|
||||
}
|
||||
if (blockY == lowestY) {
|
||||
offsets.add(position.clone());
|
||||
}
|
||||
}
|
||||
return offsets;
|
||||
} finally {
|
||||
readLock.unlock();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public IrisObject rotateCopy(IrisObjectRotation rt) {
|
||||
return IrisObjectTransforms.rotateCopy(this, rt);
|
||||
}
|
||||
|
||||
public IrisObject scaled(double scale, IrisObjectPlacementScaleInterpolator interpolation) {
|
||||
return IrisObjectTransforms.scaled(this, scale, interpolation);
|
||||
}
|
||||
|
||||
public void place(Location at) {
|
||||
readLock.lock();
|
||||
try {
|
||||
for (var entry : blocks) {
|
||||
var i = entry.getKey();
|
||||
Block b = at.clone().add(0, getCenter().getY(), 0).add(i.getX(), i.getY(), i.getZ()).getBlock();
|
||||
b.setBlockData((BlockData) Objects.requireNonNull(entry.getValue()).nativeHandle(), false);
|
||||
|
||||
if (states.containsKey(i)) {
|
||||
IrisLogging.info(Objects.requireNonNull(states.get(i)).toString());
|
||||
Objects.requireNonNull(states.get(i)).toBukkitTry(b);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
readLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void placeCenterY(Location at) {
|
||||
readLock.lock();
|
||||
try {
|
||||
for (var entry : blocks) {
|
||||
var i = entry.getKey();
|
||||
Block b = at.clone().add(getCenter().getX(), getCenter().getY(), getCenter().getZ()).add(i.getX(), i.getY(), i.getZ()).getBlock();
|
||||
b.setBlockData((BlockData) Objects.requireNonNull(entry.getValue()).nativeHandle(), false);
|
||||
|
||||
if (states.containsKey(i)) {
|
||||
Objects.requireNonNull(states.get(i)).toBukkitTry(b);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
readLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void unplaceCenterY(Location at) {
|
||||
readLock.lock();
|
||||
try {
|
||||
for (IrisBlockVector i : blocks.keys()) {
|
||||
at.clone().add(getCenter().getX(), getCenter().getY(), getCenter().getZ()).add(i.getX(), i.getY(), i.getZ()).getBlock().setBlockData((BlockData) States.AIR.nativeHandle(), false);
|
||||
}
|
||||
} finally {
|
||||
readLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return getLoadKey();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int width() {
|
||||
return w;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int height() {
|
||||
return h;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int depth() {
|
||||
return d;
|
||||
}
|
||||
|
||||
public int volume() {
|
||||
return blocks.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFolderName() {
|
||||
return "objects";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeName() {
|
||||
return "Object";
|
||||
}
|
||||
}
|
||||
@@ -1,394 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.prefab;
|
||||
|
||||
import art.arcane.iris.core.localization.IrisLanguage;
|
||||
import art.arcane.iris.core.localization.RuntimeUiMessages;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.iris.util.common.data.B;
|
||||
import art.arcane.volmlib.util.math.IrisBlockVector;
|
||||
import art.arcane.volmlib.util.math.Vector3i;
|
||||
import art.arcane.iris.util.common.plugin.VolmitSender;
|
||||
import art.arcane.iris.util.common.scheduling.jobs.Job;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
/**
|
||||
* Binary (.iob) persistence for {@link IrisObject}. The field layout written here is pinned by the on-disk
|
||||
* format - do not reorder reads or writes.
|
||||
*/
|
||||
public final class IrisObjectIO {
|
||||
private static final String V2_HEADER = "Iris V2 IOB;";
|
||||
private static final int MAX_PALETTE_ENTRIES = 32_767;
|
||||
|
||||
private IrisObjectIO() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads only the V2 palette block-state keys out of an {@code .iob} header. Read-only pack-tooling hook: no
|
||||
* IrisObject is built and no block state is resolved, so it runs without a bound platform.
|
||||
* <p>
|
||||
* Returns an empty list for a legacy (V1) object, an unreadable file, or a truncated header - a scan must never
|
||||
* fail pack validation.
|
||||
*/
|
||||
public static List<String> readPaletteKeys(File file) {
|
||||
if (file == null || !file.isFile()) {
|
||||
return List.of();
|
||||
}
|
||||
try (DataInputStream din = new DataInputStream(new BufferedInputStream(new FileInputStream(file)))) {
|
||||
din.readInt();
|
||||
din.readInt();
|
||||
din.readInt();
|
||||
if (!V2_HEADER.equals(din.readUTF())) {
|
||||
return List.of();
|
||||
}
|
||||
int count = din.readShort();
|
||||
if (count <= 0 || count > MAX_PALETTE_ENTRIES) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> palette = new ArrayList<>(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
palette.add(din.readUTF());
|
||||
}
|
||||
return palette;
|
||||
} catch (Throwable e) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
static IrisBlockVector sampleSize(File file) throws IOException {
|
||||
try (DataInputStream din = new DataInputStream(new FileInputStream(file))) {
|
||||
return new IrisBlockVector(din.readInt(), din.readInt(), din.readInt());
|
||||
}
|
||||
}
|
||||
|
||||
static void readLegacy(IrisObject self, InputStream in) throws IOException {
|
||||
self.forgetDerivedShapes();
|
||||
DataInputStream din = new DataInputStream(in);
|
||||
self.w = din.readInt();
|
||||
self.h = din.readInt();
|
||||
self.d = din.readInt();
|
||||
self.center = new Vector3i(self.w / 2, self.h / 2, self.d / 2);
|
||||
int s = din.readInt();
|
||||
|
||||
for (int i = 0; i < s; i++) {
|
||||
IrisBlockVector pos = new IrisBlockVector(din.readShort(), din.readShort(), din.readShort());
|
||||
PlatformBlockState data = B.getState(din.readUTF());
|
||||
if (isStructureMarker(data)) {
|
||||
continue;
|
||||
}
|
||||
self.blocks.put(pos, data);
|
||||
}
|
||||
|
||||
if (din.available() == 0)
|
||||
return;
|
||||
|
||||
try {
|
||||
int size = din.readInt();
|
||||
|
||||
for (int i = 0; i < size; i++) {
|
||||
self.states.put(new IrisBlockVector(din.readShort(), din.readShort(), din.readShort()), TileData.read(din));
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
}
|
||||
}
|
||||
|
||||
static void read(IrisObject self, InputStream in) throws Throwable {
|
||||
self.forgetDerivedShapes();
|
||||
DataInputStream din = new DataInputStream(in);
|
||||
self.w = din.readInt();
|
||||
self.h = din.readInt();
|
||||
self.d = din.readInt();
|
||||
if (!din.readUTF().equals("Iris V2 IOB;")) {
|
||||
throw new HeaderException();
|
||||
}
|
||||
self.center = new Vector3i(self.w / 2, self.h / 2, self.d / 2);
|
||||
int s = din.readShort();
|
||||
int i;
|
||||
KList<String> palette = new KList<>();
|
||||
|
||||
for (i = 0; i < s; i++) {
|
||||
palette.add(din.readUTF());
|
||||
}
|
||||
|
||||
// Resolve the palette once: B.getState per BLOCK was a registry lookup times the
|
||||
// block count (tens of thousands) instead of times the palette size (hundreds).
|
||||
PlatformBlockState[] resolved = new PlatformBlockState[palette.size()];
|
||||
for (i = 0; i < resolved.length; i++) {
|
||||
resolved[i] = B.getState(palette.get(i));
|
||||
}
|
||||
|
||||
s = din.readInt();
|
||||
|
||||
for (i = 0; i < s; i++) {
|
||||
IrisBlockVector pos = new IrisBlockVector(din.readShort(), din.readShort(), din.readShort());
|
||||
PlatformBlockState data = resolved[din.readShort()];
|
||||
if (isStructureMarker(data)) {
|
||||
continue;
|
||||
}
|
||||
self.blocks.put(pos, data);
|
||||
}
|
||||
|
||||
s = din.readInt();
|
||||
|
||||
for (i = 0; i < s; i++) {
|
||||
self.states.put(new IrisBlockVector(din.readShort(), din.readShort(), din.readShort()), TileData.read(din));
|
||||
}
|
||||
}
|
||||
|
||||
static void read(IrisObject self, File file) throws IOException {
|
||||
try (var fin = new BufferedInputStream(new FileInputStream(file))) {
|
||||
read(self, fin);
|
||||
} catch (Throwable e) {
|
||||
if (!(e instanceof HeaderException))
|
||||
IrisLogging.reportError(e);
|
||||
// The V2 parse populates blocks/states incrementally; a mid-file failure must not
|
||||
// leave those entries to be merged with the legacy parse of the same file.
|
||||
self.blocks.clear();
|
||||
self.states.clear();
|
||||
try (var fin = new BufferedInputStream(new FileInputStream(file))) {
|
||||
readLegacy(self, fin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isStructureMarker(PlatformBlockState data) {
|
||||
if (data == null) {
|
||||
return false;
|
||||
}
|
||||
String material = IrisObjectShaping.materialKey(data);
|
||||
return material.equals("minecraft:jigsaw") || material.equals("minecraft:structure_block") || material.equals("minecraft:structure_void");
|
||||
}
|
||||
|
||||
/**
|
||||
* The .iob V2 format stores the palette count, palette indices, and block coordinates as
|
||||
* shorts. Values beyond the short range used to wrap silently and corrupt the object; every
|
||||
* write path now rejects them with a descriptive error before any byte is written.
|
||||
*/
|
||||
static void validateWritable(IrisObject self) throws IOException {
|
||||
KList<String> palette = new KList<>();
|
||||
for (PlatformBlockState i : self.blocks.values()) {
|
||||
palette.addIfMissing(i.key());
|
||||
}
|
||||
if (palette.size() > MAX_PALETTE_ENTRIES) {
|
||||
throw new IOException("Object '" + self.getLoadKey() + "' has " + palette.size()
|
||||
+ " distinct block states; the .iob format supports at most " + MAX_PALETTE_ENTRIES + ".");
|
||||
}
|
||||
for (var entry : self.blocks) {
|
||||
requireShortCoordinates(self, "block", entry.getKey());
|
||||
}
|
||||
for (var entry : self.states) {
|
||||
requireShortCoordinates(self, "tile", entry.getKey());
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireShortCoordinates(IrisObject self, String kind, IrisBlockVector position) throws IOException {
|
||||
requireShort(self, kind, "x", position.getBlockX(), position);
|
||||
requireShort(self, kind, "y", position.getBlockY(), position);
|
||||
requireShort(self, kind, "z", position.getBlockZ(), position);
|
||||
}
|
||||
|
||||
private static void requireShort(IrisObject self, String kind, String axis, int value, IrisBlockVector position) throws IOException {
|
||||
if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
|
||||
throw new IOException("Object '" + self.getLoadKey() + "' " + kind + " at (" + position.getBlockX()
|
||||
+ "," + position.getBlockY() + "," + position.getBlockZ()
|
||||
+ ") exceeds the .iob coordinate range of ±32767 on the " + axis + " axis (" + value + ").");
|
||||
}
|
||||
}
|
||||
|
||||
static void write(IrisObject self, OutputStream o) throws IOException {
|
||||
validateWritable(self);
|
||||
writeValidated(self, o);
|
||||
}
|
||||
|
||||
private static void writeValidated(IrisObject self, OutputStream o) throws IOException {
|
||||
DataOutputStream dos = new DataOutputStream(o);
|
||||
dos.writeInt(self.w);
|
||||
dos.writeInt(self.h);
|
||||
dos.writeInt(self.d);
|
||||
dos.writeUTF("Iris V2 IOB;");
|
||||
KList<String> palette = new KList<>();
|
||||
|
||||
for (PlatformBlockState i : self.blocks.values()) {
|
||||
palette.addIfMissing(i.key());
|
||||
}
|
||||
|
||||
dos.writeShort(palette.size());
|
||||
|
||||
for (String i : palette) {
|
||||
dos.writeUTF(i);
|
||||
}
|
||||
|
||||
dos.writeInt(self.blocks.size());
|
||||
|
||||
for (var entry : self.blocks) {
|
||||
var i = entry.getKey();
|
||||
dos.writeShort(i.getBlockX());
|
||||
dos.writeShort(i.getBlockY());
|
||||
dos.writeShort(i.getBlockZ());
|
||||
dos.writeShort(palette.indexOf(entry.getValue().key()));
|
||||
}
|
||||
|
||||
dos.writeInt(self.states.size());
|
||||
for (var entry : self.states) {
|
||||
var i = entry.getKey();
|
||||
dos.writeShort(i.getBlockX());
|
||||
dos.writeShort(i.getBlockY());
|
||||
dos.writeShort(i.getBlockZ());
|
||||
entry.getValue().toBinary(dos);
|
||||
}
|
||||
}
|
||||
|
||||
static void write(IrisObject self, OutputStream o, VolmitSender sender) throws IOException {
|
||||
validateWritable(self);
|
||||
writeValidated(self, o, sender);
|
||||
}
|
||||
|
||||
private static void writeValidated(IrisObject self, OutputStream o, VolmitSender sender) throws IOException {
|
||||
AtomicReference<IOException> ref = new AtomicReference<>();
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
new Job() {
|
||||
private volatile int total = self.blocks.size() * 3 + self.states.size();
|
||||
private volatile int c = 0;
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return IrisLanguage.text(RuntimeUiMessages.JOB_SAVING_OBJECT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
try {
|
||||
DataOutputStream dos = new DataOutputStream(o);
|
||||
dos.writeInt(self.w);
|
||||
dos.writeInt(self.h);
|
||||
dos.writeInt(self.d);
|
||||
dos.writeUTF("Iris V2 IOB;");
|
||||
|
||||
KList<String> palette = new KList<>();
|
||||
|
||||
for (PlatformBlockState i : self.blocks.values()) {
|
||||
palette.addIfMissing(i.key());
|
||||
++c;
|
||||
}
|
||||
total -= self.blocks.size() - palette.size();
|
||||
|
||||
dos.writeShort(palette.size());
|
||||
|
||||
for (String i : palette) {
|
||||
dos.writeUTF(i);
|
||||
++c;
|
||||
}
|
||||
|
||||
dos.writeInt(self.blocks.size());
|
||||
|
||||
for (var entry : self.blocks) {
|
||||
var i = entry.getKey();
|
||||
dos.writeShort(i.getBlockX());
|
||||
dos.writeShort(i.getBlockY());
|
||||
dos.writeShort(i.getBlockZ());
|
||||
dos.writeShort(palette.indexOf(entry.getValue().key()));
|
||||
++c;
|
||||
}
|
||||
|
||||
dos.writeInt(self.states.size());
|
||||
for (var entry : self.states) {
|
||||
var i = entry.getKey();
|
||||
dos.writeShort(i.getBlockX());
|
||||
dos.writeShort(i.getBlockY());
|
||||
dos.writeShort(i.getBlockZ());
|
||||
entry.getValue().toBinary(dos);
|
||||
++c;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
ref.set(e);
|
||||
} finally {
|
||||
latch.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void completeWork() {}
|
||||
|
||||
@Override
|
||||
public int getTotalWork() {
|
||||
return total;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getWorkCompleted() {
|
||||
return c;
|
||||
}
|
||||
}.execute(sender, true, () -> {});
|
||||
|
||||
try {
|
||||
latch.await();
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted while writing object", interrupted);
|
||||
}
|
||||
if (ref.get() != null)
|
||||
throw ref.get();
|
||||
}
|
||||
|
||||
static void write(IrisObject self, File file) throws IOException {
|
||||
if (file == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate before opening the stream: FileOutputStream truncates, and a rejected
|
||||
// object must leave the existing .iob untouched.
|
||||
validateWritable(self);
|
||||
try (FileOutputStream out = new FileOutputStream(file)) {
|
||||
writeValidated(self, out);
|
||||
}
|
||||
}
|
||||
|
||||
static void write(IrisObject self, File file, VolmitSender sender) throws IOException {
|
||||
if (file == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
validateWritable(self);
|
||||
try (FileOutputStream out = new FileOutputStream(file)) {
|
||||
writeValidated(self, out, sender);
|
||||
}
|
||||
}
|
||||
|
||||
private static class HeaderException extends IOException {
|
||||
public HeaderException() {
|
||||
super("Invalid Header");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,518 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.prefab;
|
||||
|
||||
import art.arcane.iris.builtin.prepare.AxisRotationClamp;
|
||||
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.Snippet;
|
||||
import art.arcane.iris.platform.bukkit.BukkitBlockState;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.volmlib.util.math.IrisBlockVector;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.collection.KMap;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.bukkit.Axis;
|
||||
import org.bukkit.block.BlockFace;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
import org.bukkit.block.data.Directional;
|
||||
import org.bukkit.block.data.MultipleFacing;
|
||||
import org.bukkit.block.data.Orientable;
|
||||
import org.bukkit.block.data.Rotatable;
|
||||
import org.bukkit.block.data.type.RedstoneWire;
|
||||
import org.bukkit.block.data.type.Wall;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
@Snippet("object-rotator")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("Configures rotation for iris")
|
||||
@Data
|
||||
public class IrisObjectRotation {
|
||||
private static volatile StateRotator PLATFORM_ROTATOR = null;
|
||||
|
||||
public interface StateRotator {
|
||||
PlatformBlockState rotate(IrisObjectRotation rotation, PlatformBlockState state, int spinx, int spiny, int spinz);
|
||||
}
|
||||
|
||||
public static synchronized StateRotator bindPlatformRotator(StateRotator rotator) {
|
||||
StateRotator previous = PLATFORM_ROTATOR;
|
||||
PLATFORM_ROTATOR = Objects.requireNonNull(rotator, "rotator");
|
||||
return previous;
|
||||
}
|
||||
|
||||
public static synchronized void restorePlatformRotator(StateRotator rotator) {
|
||||
PLATFORM_ROTATOR = rotator;
|
||||
}
|
||||
|
||||
private static final class Faces {
|
||||
private static final List<BlockFace> WALL_FACES = List.of(BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST);
|
||||
}
|
||||
|
||||
@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, 90);
|
||||
|
||||
@Desc("The z axis rotation")
|
||||
private AxisRotationClamp zAxis = new AxisRotationClamp();
|
||||
|
||||
public static IrisObjectRotation xFlip180() {
|
||||
IrisObjectRotation rt = new IrisObjectRotation();
|
||||
rt.setEnabled(true);
|
||||
rt.setXAxis(AxisRotationClamp.locked(true, 180, 0));
|
||||
rt.setYAxis(new AxisRotationClamp());
|
||||
rt.setZAxis(new AxisRotationClamp());
|
||||
return rt;
|
||||
}
|
||||
|
||||
public static IrisObjectRotation xFlip180RandomY() {
|
||||
IrisObjectRotation rt = xFlip180();
|
||||
rt.setYAxis(AxisRotationClamp.of(true, false, 0, 0, 90));
|
||||
return rt;
|
||||
}
|
||||
|
||||
public static IrisObjectRotation xFlip180WithY(double y) {
|
||||
IrisObjectRotation rt = xFlip180();
|
||||
rt.setYAxis(AxisRotationClamp.locked(true, y, 90));
|
||||
return rt;
|
||||
}
|
||||
|
||||
public static IrisObjectRotation of(double x, double y, double z) {
|
||||
IrisObjectRotation rt = new IrisObjectRotation();
|
||||
rt.setEnabled(x != 0 || y != 0 || z != 0);
|
||||
rt.setXAxis(AxisRotationClamp.locked(x != 0, x, 90));
|
||||
rt.setYAxis(AxisRotationClamp.locked(y != 0, y, 90));
|
||||
rt.setZAxis(AxisRotationClamp.locked(z != 0, z, 90));
|
||||
|
||||
return rt;
|
||||
}
|
||||
|
||||
public double getYRotation(int spin) {
|
||||
return getRotation(spin, yAxis);
|
||||
}
|
||||
|
||||
public double getXRotation(int spin) {
|
||||
return getRotation(spin, xAxis);
|
||||
}
|
||||
|
||||
public double getZRotation(int spin) {
|
||||
return getRotation(spin, zAxis);
|
||||
}
|
||||
|
||||
public IrisObject rotateCopy(IrisObject e) {
|
||||
if (e == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return e.rotateCopy(this);
|
||||
}
|
||||
|
||||
public IrisBlockVector rotate(IrisBlockVector direction) {
|
||||
return rotate(direction, 0, 0, 0);
|
||||
}
|
||||
|
||||
public IrisDirection rotate(IrisDirection direction) {
|
||||
IrisBlockVector v = rotate(new IrisBlockVector(direction.x(), direction.y(), direction.z()));
|
||||
double m = Double.MAX_VALUE;
|
||||
IrisDirection s = null;
|
||||
|
||||
for (IrisDirection i : IrisDirection.values()) {
|
||||
double g = new IrisBlockVector(i.x(), i.y(), i.z()).distance(v);
|
||||
|
||||
if (g < m) {
|
||||
m = g;
|
||||
s = i;
|
||||
}
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
public double getRotation(int spin, AxisRotationClamp clamp) {
|
||||
if (!enabled) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!clamp.enabled()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return clamp.getRadians(spin);
|
||||
}
|
||||
|
||||
public BlockFace getFace(IrisBlockVector v) {
|
||||
int x = (int) Math.round(v.getX());
|
||||
int y = (int) Math.round(v.getY());
|
||||
int z = (int) Math.round(v.getZ());
|
||||
|
||||
if (x == 0 && z == -1) {
|
||||
return BlockFace.NORTH;
|
||||
}
|
||||
|
||||
if (x == 0 && z == 1) {
|
||||
return BlockFace.SOUTH;
|
||||
}
|
||||
|
||||
if (x == 1 && z == 0) {
|
||||
return BlockFace.EAST;
|
||||
}
|
||||
|
||||
if (x == -1 && z == 0) {
|
||||
return BlockFace.WEST;
|
||||
}
|
||||
|
||||
if (y > 0) {
|
||||
return BlockFace.UP;
|
||||
}
|
||||
|
||||
if (y < 0) {
|
||||
return BlockFace.DOWN;
|
||||
}
|
||||
|
||||
return BlockFace.SOUTH;
|
||||
}
|
||||
|
||||
public BlockFace getHexFace(IrisBlockVector v) {
|
||||
int x = v.getBlockX();
|
||||
int y = v.getBlockY();
|
||||
int z = v.getBlockZ();
|
||||
|
||||
if (x == 0 && z == -1) return BlockFace.NORTH;
|
||||
if (x == 1 && z == -2) return BlockFace.NORTH_NORTH_EAST;
|
||||
if (x == 1 && z == -1) return BlockFace.NORTH_EAST;
|
||||
if (x == 2 && z == -1) return BlockFace.EAST_NORTH_EAST;
|
||||
if (x == 1 && z == 0) return BlockFace.EAST;
|
||||
if (x == 2 && z == 1) return BlockFace.EAST_SOUTH_EAST;
|
||||
if (x == 1 && z == 1) return BlockFace.SOUTH_EAST;
|
||||
if (x == 1 && z == 2) return BlockFace.SOUTH_SOUTH_EAST;
|
||||
if (x == 0 && z == 1) return BlockFace.SOUTH;
|
||||
if (x == -1 && z == 2) return BlockFace.SOUTH_SOUTH_WEST;
|
||||
if (x == -1 && z == 1) return BlockFace.SOUTH_WEST;
|
||||
if (x == -2 && z == 1) return BlockFace.WEST_SOUTH_WEST;
|
||||
if (x == -1 && z == 0) return BlockFace.WEST;
|
||||
if (x == -2 && z == -1) return BlockFace.WEST_NORTH_WEST;
|
||||
if (x == -1 && z == -1) return BlockFace.NORTH_WEST;
|
||||
if (x == -1 && z == -2) return BlockFace.NORTH_NORTH_WEST;
|
||||
|
||||
if (y > 0) {
|
||||
return BlockFace.UP;
|
||||
}
|
||||
|
||||
if (y < 0) {
|
||||
return BlockFace.DOWN;
|
||||
}
|
||||
|
||||
return BlockFace.SOUTH;
|
||||
}
|
||||
|
||||
public BlockFace faceForAxis(Axis axis) {
|
||||
return switch (axis) {
|
||||
case X -> BlockFace.EAST;
|
||||
case Y -> BlockFace.UP;
|
||||
case Z -> BlockFace.NORTH;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
public Axis axisFor(BlockFace f) {
|
||||
return switch (f) {
|
||||
case NORTH, SOUTH -> Axis.Z;
|
||||
case EAST, WEST -> Axis.X;
|
||||
default -> Axis.Y;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
public Axis axisFor2D(BlockFace f) {
|
||||
return switch (f) {
|
||||
case EAST, WEST, UP, DOWN -> Axis.X;
|
||||
default -> Axis.Z;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
public PlatformBlockState rotate(PlatformBlockState state, int spinx, int spiny, int spinz) {
|
||||
if (state == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
StateRotator rotator = PLATFORM_ROTATOR;
|
||||
if (rotator != null) {
|
||||
return rotator.rotate(this, state, spinx, spiny, spinz);
|
||||
}
|
||||
|
||||
BlockData original = (BlockData) state.nativeHandle();
|
||||
if (!canRotate() || !canRotateBlockData(original)) {
|
||||
return state;
|
||||
}
|
||||
|
||||
BlockData raw = original.clone();
|
||||
BlockData rotated = rotate(raw, spinx, spiny, spinz);
|
||||
return rotated == null ? null : BukkitBlockState.of(rotated);
|
||||
}
|
||||
|
||||
private static boolean canRotateBlockData(BlockData data) {
|
||||
return data instanceof Directional
|
||||
|| data instanceof Rotatable
|
||||
|| data instanceof Orientable
|
||||
|| data instanceof MultipleFacing
|
||||
|| data instanceof Wall
|
||||
|| data instanceof RedstoneWire;
|
||||
}
|
||||
|
||||
public BlockData rotate(BlockData dd, int spinxx, int spinyy, int spinzz) {
|
||||
BlockData d = dd;
|
||||
try {
|
||||
int spinx = (int) (90D * (Math.ceil(Math.abs((spinxx % 360D) / 90D))));
|
||||
int spiny = (int) (90D * (Math.ceil(Math.abs((spinyy % 360D) / 90D))));
|
||||
int spinz = (int) (90D * (Math.ceil(Math.abs((spinzz % 360D) / 90D))));
|
||||
|
||||
if (!canRotate()) {
|
||||
return d;
|
||||
}
|
||||
|
||||
if (d instanceof Directional g) {
|
||||
BlockFace f = g.getFacing();
|
||||
IrisBlockVector bv = new IrisBlockVector(f.getModX(), f.getModY(), f.getModZ());
|
||||
bv = rotate(bv.clone(), spinx, spiny, spinz);
|
||||
BlockFace t = getFace(bv);
|
||||
|
||||
if (g.getFaces().contains(t)) {
|
||||
g.setFacing(t);
|
||||
} else if (!g.getMaterial().isSolid()) {
|
||||
d = null;
|
||||
}
|
||||
} else if (d instanceof Rotatable g) {
|
||||
BlockFace f = g.getRotation();
|
||||
|
||||
IrisBlockVector bv = new IrisBlockVector(f.getModX(), 0, f.getModZ());
|
||||
bv = rotate(bv.clone(), spinx, spiny, spinz);
|
||||
BlockFace face = getHexFace(bv);
|
||||
|
||||
g.setRotation(face);
|
||||
|
||||
} else if (d instanceof Orientable g) {
|
||||
BlockFace f = getFace(g.getAxis());
|
||||
IrisBlockVector bv = new IrisBlockVector(f.getModX(), f.getModY(), f.getModZ());
|
||||
bv = rotate(bv.clone(), spinx, spiny, spinz);
|
||||
Axis a = getAxis(bv);
|
||||
|
||||
if (!a.equals(g.getAxis()) && g.getAxes().contains(a)) {
|
||||
g.setAxis(a);
|
||||
}
|
||||
} else if (d instanceof MultipleFacing g) {
|
||||
List<BlockFace> faces = new KList<>();
|
||||
|
||||
for (BlockFace i : g.getFaces()) {
|
||||
IrisBlockVector bv = new IrisBlockVector(i.getModX(), i.getModY(), i.getModZ());
|
||||
bv = rotate(bv.clone(), spinx, spiny, spinz);
|
||||
BlockFace r = getFace(bv);
|
||||
|
||||
if (g.getAllowedFaces().contains(r)) {
|
||||
faces.add(r);
|
||||
}
|
||||
}
|
||||
|
||||
for (BlockFace i : g.getFaces()) {
|
||||
g.setFace(i, false);
|
||||
}
|
||||
|
||||
for (BlockFace i : faces) {
|
||||
g.setFace(i, true);
|
||||
}
|
||||
} else if (d instanceof Wall wall) {
|
||||
KMap<BlockFace, Wall.Height> faces = new KMap<>();
|
||||
|
||||
for (BlockFace i : Faces.WALL_FACES) {
|
||||
Wall.Height h = wall.getHeight(i);
|
||||
IrisBlockVector bv = new IrisBlockVector(i.getModX(), i.getModY(), i.getModZ());
|
||||
bv = rotate(bv.clone(), spinx, spiny, spinz);
|
||||
BlockFace r = getFace(bv);
|
||||
if (Faces.WALL_FACES.contains(r)) {
|
||||
faces.put(r, h);
|
||||
}
|
||||
}
|
||||
|
||||
for (BlockFace i : Faces.WALL_FACES) {
|
||||
wall.setHeight(i, faces.getOrDefault(i, Wall.Height.NONE));
|
||||
}
|
||||
} else if (d instanceof RedstoneWire wire) {
|
||||
Map<BlockFace, RedstoneWire.Connection> faces = new HashMap<>();
|
||||
|
||||
Set<BlockFace> allowed = wire.getAllowedFaces();
|
||||
for (BlockFace i : allowed) {
|
||||
RedstoneWire.Connection connection = wire.getFace(i);
|
||||
IrisBlockVector bv = new IrisBlockVector(i.getModX(), i.getModY(), i.getModZ());
|
||||
bv = rotate(bv.clone(), spinx, spiny, spinz);
|
||||
BlockFace r = getFace(bv);
|
||||
if (allowed.contains(r))
|
||||
faces.put(r, connection);
|
||||
}
|
||||
|
||||
for (BlockFace i : allowed) {
|
||||
wire.setFace(i, faces.getOrDefault(i, RedstoneWire.Connection.NONE));
|
||||
}
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
|
||||
}
|
||||
|
||||
return d;
|
||||
}
|
||||
|
||||
public Axis getAxis(IrisBlockVector v) {
|
||||
if (Math.abs(v.getBlockX()) > Math.max(Math.abs(v.getBlockY()), Math.abs(v.getBlockZ()))) {
|
||||
return Axis.X;
|
||||
}
|
||||
|
||||
if (Math.abs(v.getBlockY()) > Math.max(Math.abs(v.getBlockX()), Math.abs(v.getBlockZ()))) {
|
||||
return Axis.Y;
|
||||
}
|
||||
|
||||
if (Math.abs(v.getBlockZ()) > Math.max(Math.abs(v.getBlockX()), Math.abs(v.getBlockY()))) {
|
||||
return Axis.Z;
|
||||
}
|
||||
|
||||
return Axis.Y;
|
||||
}
|
||||
|
||||
private BlockFace getFace(Axis axis) {
|
||||
return switch (axis) {
|
||||
case X -> BlockFace.EAST;
|
||||
case Y -> BlockFace.UP;
|
||||
case Z -> BlockFace.SOUTH;
|
||||
};
|
||||
}
|
||||
|
||||
public IrisPosition rotate(IrisPosition b) {
|
||||
return rotate(b, 0, 0, 0);
|
||||
}
|
||||
|
||||
public IrisPosition rotate(IrisPosition b, int spinx, int spiny, int spinz) {
|
||||
IrisBlockVector v = rotate(new IrisBlockVector(b.getX(), b.getY(), b.getZ()), spinx, spiny, spinz);
|
||||
return new IrisPosition(v.getBlockX(), v.getBlockY(), v.getBlockZ());
|
||||
}
|
||||
|
||||
public IrisBlockVector rotate(IrisBlockVector b, int spinx, int spiny, int spinz) {
|
||||
if (!canRotate()) {
|
||||
return b;
|
||||
}
|
||||
|
||||
IrisBlockVector v = b.clone();
|
||||
|
||||
if (canRotateX()) {
|
||||
if (getXAxis().isLocked()) {
|
||||
if (Math.abs(getXAxis().max()) % 360D == 180D) {
|
||||
v.setZ(-v.getZ());
|
||||
v.setY(-v.getY());
|
||||
} else if (getXAxis().max() % 360D == 90D || getXAxis().max() % 360D == -270D) {
|
||||
double z = v.getZ();
|
||||
v.setZ(v.getY());
|
||||
v.setY(-z);
|
||||
} else if (getXAxis().max() == -90D || getXAxis().max() % 360D == 270D) {
|
||||
double z = v.getZ();
|
||||
v.setZ(-v.getY());
|
||||
v.setY(z);
|
||||
} else {
|
||||
v.rotateAroundX(getXRotation(spinx));
|
||||
}
|
||||
} else {
|
||||
v.rotateAroundX(getXRotation(spinx));
|
||||
}
|
||||
}
|
||||
|
||||
if (canRotateZ()) {
|
||||
if (getZAxis().isLocked()) {
|
||||
if (Math.abs(getZAxis().max()) % 360D == 180D) {
|
||||
v.setY(-v.getY());
|
||||
v.setX(-v.getX());
|
||||
} else if (getZAxis().max() % 360D == 90D || getZAxis().max() % 360D == -270D) {
|
||||
double y = v.getY();
|
||||
v.setY(v.getX());
|
||||
v.setX(-y);
|
||||
} else if (getZAxis().max() == -90D || getZAxis().max() % 360D == 270D) {
|
||||
double y = v.getY();
|
||||
v.setY(-v.getX());
|
||||
v.setX(y);
|
||||
} else {
|
||||
v.rotateAroundZ(getZRotation(spinz));
|
||||
}
|
||||
} else {
|
||||
v.rotateAroundZ(getZRotation(spinz));
|
||||
}
|
||||
}
|
||||
|
||||
if (canRotateY()) {
|
||||
if (getYAxis().isLocked()) {
|
||||
if (Math.abs(getYAxis().max()) % 360D == 180D) {
|
||||
v.setX(-v.getX());
|
||||
v.setZ(-v.getZ());
|
||||
} else if (getYAxis().max() % 360D == 90D || getYAxis().max() % 360D == -270D) {
|
||||
double x = v.getX();
|
||||
v.setX(v.getZ());
|
||||
v.setZ(-x);
|
||||
} else if (getYAxis().max() == -90D || getYAxis().max() % 360D == 270D) {
|
||||
double x = v.getX();
|
||||
v.setX(-v.getZ());
|
||||
v.setZ(x);
|
||||
} else {
|
||||
v.rotateAroundY(getYRotation(spiny));
|
||||
}
|
||||
} else {
|
||||
v.rotateAroundY(getYRotation(spiny));
|
||||
}
|
||||
}
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
public boolean canRotateX() {
|
||||
return enabled && xAxis.enabled();
|
||||
}
|
||||
|
||||
public boolean canRotateY() {
|
||||
return enabled && yAxis.enabled();
|
||||
}
|
||||
|
||||
public boolean canRotateZ() {
|
||||
return enabled && zAxis.enabled();
|
||||
}
|
||||
|
||||
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
|
||||
public boolean canRotate() {
|
||||
return canRotateX() || canRotateY() || canRotateZ();
|
||||
}
|
||||
}
|
||||
@@ -1,380 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.prefab;
|
||||
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
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.Snippet;
|
||||
import art.arcane.volmlib.util.math.Vector3i;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.lang.ref.ReferenceQueue;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Snippet("object-scale")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("Scale objects")
|
||||
@Data
|
||||
public class IrisObjectScale {
|
||||
private static final long CACHE_MIN_ESTIMATED_BYTES = 16L * 1024L * 1024L;
|
||||
private static final long CACHE_MAX_ESTIMATED_BYTES = 64L * 1024L * 1024L;
|
||||
private static final long CACHE_ENTRY_ESTIMATED_BYTES = 512L;
|
||||
private static final long CACHE_VARIANT_ESTIMATED_BYTES = 256L;
|
||||
private static final long CACHE_ESTIMATED_BYTES_PER_VOXEL = 128L;
|
||||
private static final int CACHE_LOAD_LOCK_COUNT = 256;
|
||||
|
||||
@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 = 1;
|
||||
|
||||
@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 = 1;
|
||||
|
||||
@MinNumber(0.01)
|
||||
@MaxNumber(50)
|
||||
@Desc("The maximum scale. Used when size is 1 to pick a random scale per placement.")
|
||||
private double maximumScale = 1;
|
||||
|
||||
@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 IrisObjectPlacementScaleInterpolator interpolation = IrisObjectPlacementScaleInterpolator.NONE;
|
||||
|
||||
public boolean shouldScale() {
|
||||
if (size != 1) {
|
||||
return true;
|
||||
}
|
||||
if (variations <= 0) {
|
||||
return false;
|
||||
}
|
||||
return minimumScale != 1 || maximumScale != 1;
|
||||
}
|
||||
|
||||
public int getMaxSizeFor(int indim) {
|
||||
return (int) Math.ceil(getMaxScale() * indim);
|
||||
}
|
||||
|
||||
public double getMaxScale() {
|
||||
if (size != 1) {
|
||||
return size;
|
||||
}
|
||||
return Math.max(minimumScale, maximumScale);
|
||||
}
|
||||
|
||||
/** The scaled variant of {@code origin} this scale picks, built once per world and kept in the world's cache. */
|
||||
public IrisObject get(RNG rng, IrisObject origin, Engine engine) {
|
||||
if (origin == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ScaleRequest request = snapshotRequest();
|
||||
if (!request.shouldScale()) {
|
||||
return origin;
|
||||
}
|
||||
|
||||
int variantIndex = request.selectVariant(rng);
|
||||
ScaleCache cache = cacheOf(engine);
|
||||
CacheKey key = cache.key(origin, request, variantIndex);
|
||||
IrisObject cached = cache.lookup(key);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
synchronized (cache.loadLock(key)) {
|
||||
IrisObject afterWait = cache.lookup(key);
|
||||
if (afterWait != null) {
|
||||
return afterWait;
|
||||
}
|
||||
|
||||
IrisObject variant = origin.scaled(request.scaleAt(variantIndex), request.interpolation());
|
||||
long estimatedBytes = estimateVariant(variant);
|
||||
return cache.putIfAbsent(key, variant, estimatedBytes);
|
||||
}
|
||||
}
|
||||
|
||||
static ScaleCache cacheOf(Engine engine) {
|
||||
return engine.getGeneration().state(ScaleCache.class, world -> new ScaleCache(resolveCacheMaximumEstimatedBytes()));
|
||||
}
|
||||
|
||||
public boolean canScaleBeyond() {
|
||||
return shouldScale() && getMaxScale() > 1;
|
||||
}
|
||||
|
||||
private ScaleRequest snapshotRequest() {
|
||||
IrisObjectPlacementScaleInterpolator configuredInterpolation = interpolation == null
|
||||
? IrisObjectPlacementScaleInterpolator.NONE
|
||||
: interpolation;
|
||||
return new ScaleRequest(size, minimumScale, maximumScale, variations, configuredInterpolation);
|
||||
}
|
||||
|
||||
private static long estimateVariant(IrisObject variant) {
|
||||
long width = Math.max(1L, variant.getW());
|
||||
long height = Math.max(1L, variant.getH());
|
||||
long depth = Math.max(1L, variant.getD());
|
||||
long volume = saturatedMultiply(saturatedMultiply(width, height), depth);
|
||||
long populatedVoxels = saturatedAdd(variant.getBlocks().size(), variant.getStates().size());
|
||||
long voxelBytes = saturatedMultiply(Math.max(volume, populatedVoxels), CACHE_ESTIMATED_BYTES_PER_VOXEL);
|
||||
return saturatedAdd(CACHE_ENTRY_ESTIMATED_BYTES,
|
||||
saturatedAdd(CACHE_VARIANT_ESTIMATED_BYTES, voxelBytes));
|
||||
}
|
||||
|
||||
private static long saturatedAdd(long first, long second) {
|
||||
if (first >= Long.MAX_VALUE - second) {
|
||||
return Long.MAX_VALUE;
|
||||
}
|
||||
return first + second;
|
||||
}
|
||||
|
||||
private static long saturatedMultiply(long first, long second) {
|
||||
if (first == 0L || second == 0L) {
|
||||
return 0L;
|
||||
}
|
||||
if (first > Long.MAX_VALUE / second) {
|
||||
return Long.MAX_VALUE;
|
||||
}
|
||||
return first * second;
|
||||
}
|
||||
|
||||
private static long resolveCacheMaximumEstimatedBytes() {
|
||||
long heapShare = Runtime.getRuntime().maxMemory() / 32L;
|
||||
return Math.max(CACHE_MIN_ESTIMATED_BYTES, Math.min(CACHE_MAX_ESTIMATED_BYTES, heapShare));
|
||||
}
|
||||
|
||||
record ScaleRequest(double size, double minimumScale, double maximumScale, int variations,
|
||||
IrisObjectPlacementScaleInterpolator interpolation) {
|
||||
boolean shouldScale() {
|
||||
if (size != 1D) {
|
||||
return true;
|
||||
}
|
||||
return variations > 0 && (minimumScale != 1D || maximumScale != 1D);
|
||||
}
|
||||
|
||||
int variantCount() {
|
||||
if (size != 1D || minimumScale == maximumScale) {
|
||||
return 1;
|
||||
}
|
||||
return Math.max(1, Math.min(variations, 32));
|
||||
}
|
||||
|
||||
int selectVariant(RNG rng) {
|
||||
int count = variantCount();
|
||||
return count == 1 ? 0 : rng.nextInt(count);
|
||||
}
|
||||
|
||||
double scaleAt(int index) {
|
||||
if (size != 1D) {
|
||||
return size;
|
||||
}
|
||||
if (minimumScale == maximumScale) {
|
||||
return minimumScale;
|
||||
}
|
||||
return minimumScale + (((maximumScale - minimumScale) / variantCount()) * index);
|
||||
}
|
||||
}
|
||||
|
||||
static final class CacheKey extends WeakReference<IrisObject> {
|
||||
private final ScaleRequest request;
|
||||
private final int variantIndex;
|
||||
private final int originRevision;
|
||||
private final int loadHashCode;
|
||||
private final int hashCode;
|
||||
|
||||
CacheKey(IrisObject origin, ScaleRequest request, int variantIndex) {
|
||||
this(origin, request, variantIndex, null);
|
||||
}
|
||||
|
||||
CacheKey(IrisObject origin, ScaleRequest request, int variantIndex,
|
||||
ReferenceQueue<IrisObject> collectedOrigins) {
|
||||
super(origin, collectedOrigins);
|
||||
this.request = request;
|
||||
this.variantIndex = variantIndex;
|
||||
this.originRevision = originRevision(origin);
|
||||
int result = System.identityHashCode(origin);
|
||||
result = (31 * result) + originRevision;
|
||||
result = (31 * result) + request.hashCode();
|
||||
this.loadHashCode = result;
|
||||
this.hashCode = (31 * result) + variantIndex;
|
||||
}
|
||||
|
||||
boolean hasOrigin(IrisObject candidate) {
|
||||
return get() == candidate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object object) {
|
||||
if (this == object) {
|
||||
return true;
|
||||
}
|
||||
if (!(object instanceof CacheKey other)) {
|
||||
return false;
|
||||
}
|
||||
IrisObject origin = get();
|
||||
return origin != null
|
||||
&& origin == other.get()
|
||||
&& originRevision == other.originRevision
|
||||
&& request.equals(other.request)
|
||||
&& variantIndex == other.variantIndex;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return hashCode;
|
||||
}
|
||||
|
||||
int loadHashCode() {
|
||||
return loadHashCode;
|
||||
}
|
||||
|
||||
private static int originRevision(IrisObject origin) {
|
||||
origin.readLock.lock();
|
||||
try {
|
||||
int result = origin.getW();
|
||||
result = (31 * result) + origin.getH();
|
||||
result = (31 * result) + origin.getD();
|
||||
result = (31 * result) + System.identityHashCode(origin.getBlocks());
|
||||
result = (31 * result) + System.identityHashCode(origin.getStates());
|
||||
result = (31 * result) + Long.hashCode(origin.getBlocks().modificationRevision());
|
||||
result = (31 * result) + Long.hashCode(origin.getStates().modificationRevision());
|
||||
Vector3i center = origin.getCenter();
|
||||
if (center != null) {
|
||||
result = (31 * result) + center.getX();
|
||||
result = (31 * result) + center.getY();
|
||||
result = (31 * result) + center.getZ();
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
origin.readLock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static final class ScaleCache {
|
||||
private final long maximumEstimatedBytes;
|
||||
private final LinkedHashMap<CacheKey, CacheValue> entries;
|
||||
private final Object[] loadLocks;
|
||||
private final ReferenceQueue<IrisObject> collectedOrigins;
|
||||
private long estimatedBytes;
|
||||
|
||||
ScaleCache(long maximumEstimatedBytes) {
|
||||
if (maximumEstimatedBytes <= 0L) {
|
||||
throw new IllegalArgumentException("maximumEstimatedBytes must be positive");
|
||||
}
|
||||
this.maximumEstimatedBytes = maximumEstimatedBytes;
|
||||
this.entries = new LinkedHashMap<>(256, 0.75F, true);
|
||||
this.loadLocks = new Object[CACHE_LOAD_LOCK_COUNT];
|
||||
this.collectedOrigins = new ReferenceQueue<>();
|
||||
for (int index = 0; index < loadLocks.length; index++) {
|
||||
loadLocks[index] = new Object();
|
||||
}
|
||||
}
|
||||
|
||||
CacheKey key(IrisObject origin, ScaleRequest request, int variantIndex) {
|
||||
return new CacheKey(origin, request, variantIndex, collectedOrigins);
|
||||
}
|
||||
|
||||
Object loadLock(CacheKey key) {
|
||||
return loadLocks[key.loadHashCode() & (loadLocks.length - 1)];
|
||||
}
|
||||
|
||||
synchronized IrisObject lookup(CacheKey key) {
|
||||
drainCollectedOrigins();
|
||||
CacheValue value = entries.get(key);
|
||||
return value == null ? null : value.variant();
|
||||
}
|
||||
|
||||
synchronized IrisObject putIfAbsent(CacheKey key, IrisObject variant, long entryEstimatedBytes) {
|
||||
drainCollectedOrigins();
|
||||
CacheValue present = entries.get(key);
|
||||
if (present != null) {
|
||||
return present.variant();
|
||||
}
|
||||
if (entryEstimatedBytes > maximumEstimatedBytes) {
|
||||
return variant;
|
||||
}
|
||||
|
||||
entries.put(key, new CacheValue(variant, entryEstimatedBytes));
|
||||
estimatedBytes += entryEstimatedBytes;
|
||||
evictToBudget();
|
||||
return variant;
|
||||
}
|
||||
|
||||
synchronized int size() {
|
||||
drainCollectedOrigins();
|
||||
return entries.size();
|
||||
}
|
||||
|
||||
synchronized long estimatedBytes() {
|
||||
drainCollectedOrigins();
|
||||
return estimatedBytes;
|
||||
}
|
||||
|
||||
long maximumEstimatedBytes() {
|
||||
return maximumEstimatedBytes;
|
||||
}
|
||||
|
||||
synchronized boolean containsOrigin(IrisObject origin) {
|
||||
drainCollectedOrigins();
|
||||
for (CacheKey key : entries.keySet()) {
|
||||
if (key.hasOrigin(origin)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void evictToBudget() {
|
||||
Iterator<Map.Entry<CacheKey, CacheValue>> iterator = entries.entrySet().iterator();
|
||||
while (estimatedBytes > maximumEstimatedBytes && iterator.hasNext()) {
|
||||
Map.Entry<CacheKey, CacheValue> entry = iterator.next();
|
||||
estimatedBytes -= entry.getValue().estimatedBytes();
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
|
||||
private void drainCollectedOrigins() {
|
||||
CacheKey collected;
|
||||
while ((collected = (CacheKey) collectedOrigins.poll()) != null) {
|
||||
CacheValue removed = entries.remove(collected);
|
||||
if (removed != null) {
|
||||
estimatedBytes -= removed.estimatedBytes();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
record CacheValue(IrisObject variant, long estimatedBytes) {
|
||||
}
|
||||
}
|
||||
@@ -1,316 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.prefab;
|
||||
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.volmlib.util.data.VectorMap;
|
||||
import art.arcane.volmlib.util.math.IrisBlockVector;
|
||||
import art.arcane.volmlib.util.math.IrisVector;
|
||||
import art.arcane.volmlib.util.math.Vector3i;
|
||||
import art.arcane.iris.util.common.parallel.BurstExecutor;
|
||||
import art.arcane.iris.util.common.parallel.MultiBurst;
|
||||
import art.arcane.volmlib.util.format.Form;
|
||||
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* Volume shaping for {@link IrisObject}: smart boring, shrinkwrapping, compaction and the shared block
|
||||
* classification helpers used by placement.
|
||||
*/
|
||||
public final class IrisObjectShaping {
|
||||
private IrisObjectShaping() {
|
||||
}
|
||||
|
||||
public static void ensureSmartBored(IrisObject self) {
|
||||
if (self.smartBored) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Whole computation under the object's write lock: two racing callers would otherwise
|
||||
// both compute, with the loser reading self.blocks while the winner merges into it.
|
||||
self.writeLock.lock();
|
||||
try {
|
||||
if (self.smartBored) {
|
||||
return;
|
||||
}
|
||||
ensureSmartBoredLocked(self);
|
||||
} finally {
|
||||
self.writeLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private static void ensureSmartBoredLocked(IrisObject self) {
|
||||
PrecisionStopwatch p = PrecisionStopwatch.start();
|
||||
PlatformBlockState vair = IrisObject.States.VAIR;
|
||||
AtomicInteger applied = new AtomicInteger();
|
||||
IrisBlockVector max = new IrisBlockVector(Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE);
|
||||
IrisBlockVector min = new IrisBlockVector(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE);
|
||||
VectorMap<PlatformBlockState> source;
|
||||
self.readLock.lock();
|
||||
try {
|
||||
if (self.blocks.isEmpty()) {
|
||||
IrisLogging.warn("Cannot Smart Bore " + self.getLoadKey() + " because it has 0 blocks in it.");
|
||||
self.smartBored = true;
|
||||
return;
|
||||
}
|
||||
|
||||
source = self.blocks;
|
||||
|
||||
for (IrisBlockVector i : self.blocks.keys()) {
|
||||
max.setX(Math.max(i.getX(), max.getX()));
|
||||
min.setX(Math.min(i.getX(), min.getX()));
|
||||
max.setY(Math.max(i.getY(), max.getY()));
|
||||
min.setY(Math.min(i.getY(), min.getY()));
|
||||
max.setZ(Math.max(i.getZ(), max.getZ()));
|
||||
min.setZ(Math.min(i.getZ(), min.getZ()));
|
||||
}
|
||||
} finally {
|
||||
self.readLock.unlock();
|
||||
}
|
||||
|
||||
VectorMap<PlatformBlockState> bore = new VectorMap<>();
|
||||
// Inline on purpose: the three axis passes read AND write the shared bore map, so the
|
||||
// bored volume must come from a fixed X->Y->Z order on the calling (lock-owning)
|
||||
// thread, not from pool scheduling. This matches what burst-worker callers (studio,
|
||||
// generation threads) already produced, so output is unchanged where it was stable.
|
||||
BurstExecutor burst = MultiBurst.burst.burst();
|
||||
burst.setMulticore(false);
|
||||
|
||||
// Smash X
|
||||
for (int rayY = min.getBlockY(); rayY <= max.getBlockY(); rayY++) {
|
||||
int finalRayY = rayY;
|
||||
burst.queue(() -> {
|
||||
for (int rayZ = min.getBlockZ(); rayZ <= max.getBlockZ(); rayZ++) {
|
||||
int start = Integer.MAX_VALUE;
|
||||
int end = Integer.MIN_VALUE;
|
||||
|
||||
for (int ray = min.getBlockX(); ray <= max.getBlockX(); ray++) {
|
||||
if (boreContains(source, bore, new IrisBlockVector(ray, finalRayY, rayZ))) {
|
||||
start = Math.min(ray, start);
|
||||
end = Math.max(ray, end);
|
||||
}
|
||||
}
|
||||
|
||||
if (start != Integer.MAX_VALUE && end != Integer.MIN_VALUE) {
|
||||
for (int i = start; i <= end; i++) {
|
||||
boreCell(source, bore, new IrisBlockVector(i, finalRayY, rayZ), vair, applied);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Smash Y
|
||||
for (int rayX = min.getBlockX(); rayX <= max.getBlockX(); rayX++) {
|
||||
int finalRayX = rayX;
|
||||
burst.queue(() -> {
|
||||
for (int rayZ = min.getBlockZ(); rayZ <= max.getBlockZ(); rayZ++) {
|
||||
int start = Integer.MAX_VALUE;
|
||||
int end = Integer.MIN_VALUE;
|
||||
|
||||
for (int ray = min.getBlockY(); ray <= max.getBlockY(); ray++) {
|
||||
if (boreContains(source, bore, new IrisBlockVector(finalRayX, ray, rayZ))) {
|
||||
start = Math.min(ray, start);
|
||||
end = Math.max(ray, end);
|
||||
}
|
||||
}
|
||||
|
||||
if (start != Integer.MAX_VALUE && end != Integer.MIN_VALUE) {
|
||||
for (int i = start; i <= end; i++) {
|
||||
boreCell(source, bore, new IrisBlockVector(finalRayX, i, rayZ), vair, applied);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Smash Z
|
||||
for (int rayX = min.getBlockX(); rayX <= max.getBlockX(); rayX++) {
|
||||
int finalRayX = rayX;
|
||||
burst.queue(() -> {
|
||||
for (int rayY = min.getBlockY(); rayY <= max.getBlockY(); rayY++) {
|
||||
int start = Integer.MAX_VALUE;
|
||||
int end = Integer.MIN_VALUE;
|
||||
|
||||
for (int ray = min.getBlockZ(); ray <= max.getBlockZ(); ray++) {
|
||||
if (boreContains(source, bore, new IrisBlockVector(finalRayX, rayY, ray))) {
|
||||
start = Math.min(ray, start);
|
||||
end = Math.max(ray, end);
|
||||
}
|
||||
}
|
||||
|
||||
if (start != Integer.MAX_VALUE && end != Integer.MIN_VALUE) {
|
||||
for (int i = start; i <= end; i++) {
|
||||
boreCell(source, bore, new IrisBlockVector(finalRayX, rayY, i), vair, applied);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
burst.complete();
|
||||
|
||||
self.writeLock.lock();
|
||||
try {
|
||||
if (!self.smartBored) {
|
||||
bore.forEach((v, s) -> self.blocks.computeIfAbsent(v, (vv) -> s));
|
||||
self.forgetDerivedShapes();
|
||||
self.smartBored = true;
|
||||
}
|
||||
} finally {
|
||||
self.writeLock.unlock();
|
||||
}
|
||||
|
||||
IrisLogging.debug("Smart Bore: " + self.getLoadKey() + " in " + Form.duration(p.getMilliseconds(), 2) + " (" + Form.f(applied.get()) + ")");
|
||||
}
|
||||
|
||||
private static boolean boreContains(VectorMap<PlatformBlockState> source, VectorMap<PlatformBlockState> bore, IrisBlockVector v) {
|
||||
return source.containsKey(v) || bore.containsKey(v);
|
||||
}
|
||||
|
||||
private static void boreCell(VectorMap<PlatformBlockState> source, VectorMap<PlatformBlockState> bore, IrisBlockVector v, PlatformBlockState vair, AtomicInteger applied) {
|
||||
PlatformBlockState existing = source.get(v);
|
||||
|
||||
if (existing == null) {
|
||||
if (vair.equals(bore.get(v))) {
|
||||
return;
|
||||
}
|
||||
|
||||
bore.computeIfAbsent(v, (vv) -> vair);
|
||||
} else if (vair.equals(existing)) {
|
||||
return;
|
||||
}
|
||||
|
||||
applied.getAndIncrement();
|
||||
}
|
||||
|
||||
public static void shrinkwrap(IrisObject self) {
|
||||
if (self.blocks.isEmpty()) return;
|
||||
IrisBlockVector min = new IrisBlockVector(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE);
|
||||
IrisBlockVector max = new IrisBlockVector(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE);
|
||||
|
||||
for (IrisBlockVector i : self.blocks.keys()) {
|
||||
min.setX(Math.min(min.getX(), i.getX()));
|
||||
min.setY(Math.min(min.getY(), i.getY()));
|
||||
min.setZ(Math.min(min.getZ(), i.getZ()));
|
||||
max.setX(Math.max(max.getX(), i.getX()));
|
||||
max.setY(Math.max(max.getY(), i.getY()));
|
||||
max.setZ(Math.max(max.getZ(), i.getZ()));
|
||||
}
|
||||
|
||||
// Compute into locals and assign every field in one block at the end, so a reader can
|
||||
// never observe post-shrink dimensions paired with pre-shrink volume (or vice versa).
|
||||
int w = max.getBlockX() - min.getBlockX() + 1;
|
||||
int h = max.getBlockY() - min.getBlockY() + 1;
|
||||
int d = max.getBlockZ() - min.getBlockZ() + 1;
|
||||
Vector3i center = new Vector3i(w / 2, h / 2, d / 2);
|
||||
|
||||
Vector3i offset = new Vector3i(
|
||||
-center.getBlockX() - min.getBlockX(),
|
||||
-center.getBlockY() - min.getBlockY(),
|
||||
-center.getBlockZ() - min.getBlockZ()
|
||||
);
|
||||
if (offset.getBlockX() == 0 && offset.getBlockY() == 0 && offset.getBlockZ() == 0) {
|
||||
self.w = w;
|
||||
self.h = h;
|
||||
self.d = d;
|
||||
self.center = center;
|
||||
return;
|
||||
}
|
||||
|
||||
VectorMap<PlatformBlockState> b = new VectorMap<>();
|
||||
VectorMap<TileData> s = new VectorMap<>();
|
||||
IrisBlockVector shift = new IrisBlockVector(offset.getX(), offset.getY(), offset.getZ());
|
||||
|
||||
self.blocks.forEach((vector, data) -> {
|
||||
vector.add(shift);
|
||||
b.put(vector, data);
|
||||
});
|
||||
|
||||
self.states.forEach((vector, data) -> {
|
||||
vector.add(shift);
|
||||
s.put(vector, data);
|
||||
});
|
||||
|
||||
self.w = w;
|
||||
self.h = h;
|
||||
self.d = d;
|
||||
self.center = center;
|
||||
self.shrinkOffset = offset;
|
||||
self.blocks = b;
|
||||
self.states = s;
|
||||
self.forgetDerivedShapes();
|
||||
}
|
||||
|
||||
public static void clean(IrisObject self) {
|
||||
VectorMap<PlatformBlockState> d = new VectorMap<>();
|
||||
d.putAll(self.blocks);
|
||||
|
||||
VectorMap<TileData> dx = new VectorMap<>();
|
||||
dx.putAll(self.states);
|
||||
|
||||
self.blocks = d;
|
||||
self.states = dx;
|
||||
self.forgetDerivedShapes();
|
||||
}
|
||||
|
||||
public static boolean shouldStilt(PlatformBlockState state) {
|
||||
if (!state.isOccluding()) {
|
||||
return false;
|
||||
}
|
||||
String material = materialKey(state);
|
||||
if (material.endsWith("_stairs") || material.endsWith("_slab")) {
|
||||
return false;
|
||||
}
|
||||
return !material.equals("minecraft:dirt_path");
|
||||
}
|
||||
|
||||
public static String materialKey(PlatformBlockState state) {
|
||||
String memoized = state.materialKey();
|
||||
if (memoized != null) {
|
||||
return memoized;
|
||||
}
|
||||
String key = state.key();
|
||||
int bracket = key.indexOf('[');
|
||||
return bracket < 0 ? key : key.substring(0, bracket);
|
||||
}
|
||||
|
||||
public static List<IrisBlockVector> blocksBetweenTwoPoints(IrisVector loc1, IrisVector loc2) {
|
||||
List<IrisBlockVector> locations = new ArrayList<>();
|
||||
int topBlockX = Math.max(loc1.getBlockX(), loc2.getBlockX());
|
||||
int bottomBlockX = Math.min(loc1.getBlockX(), loc2.getBlockX());
|
||||
int topBlockY = Math.max(loc1.getBlockY(), loc2.getBlockY());
|
||||
int bottomBlockY = Math.min(loc1.getBlockY(), loc2.getBlockY());
|
||||
int topBlockZ = Math.max(loc1.getBlockZ(), loc2.getBlockZ());
|
||||
int bottomBlockZ = Math.min(loc1.getBlockZ(), loc2.getBlockZ());
|
||||
|
||||
for (int x = bottomBlockX; x <= topBlockX; x++) {
|
||||
for (int z = bottomBlockZ; z <= topBlockZ; z++) {
|
||||
for (int y = bottomBlockY; y <= topBlockY; y++) {
|
||||
locations.add(new IrisBlockVector(x, y, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
return locations;
|
||||
}
|
||||
}
|
||||
@@ -1,370 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.prefab;
|
||||
|
||||
import art.arcane.iris.engine.object.value.IrisPosition;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.iris.util.common.data.B;
|
||||
import art.arcane.volmlib.util.data.VectorMap;
|
||||
import art.arcane.volmlib.util.math.IrisBlockVector;
|
||||
import art.arcane.volmlib.util.math.IrisVector;
|
||||
import art.arcane.iris.util.project.interpolation.Interpolation3D;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Geometric transforms for {@link IrisObject}: rotation, scaling and the interpolated upscalers.
|
||||
*/
|
||||
final class IrisObjectTransforms {
|
||||
private IrisObjectTransforms() {
|
||||
}
|
||||
|
||||
static IrisObject rotateCopy(IrisObject self, IrisObjectRotation rt) {
|
||||
IrisObject copy = self.copy();
|
||||
rotate(copy, rt, 0, 0, 0);
|
||||
return copy;
|
||||
}
|
||||
|
||||
static void rotate(IrisObject self, IrisObjectRotation r, int spinx, int spiny, int spinz) {
|
||||
self.writeLock.lock();
|
||||
try {
|
||||
VectorMap<PlatformBlockState> d = new VectorMap<>();
|
||||
|
||||
for (var entry : self.blocks) {
|
||||
d.put(r.rotate(entry.getKey(), spinx, spiny, spinz), r.rotate(entry.getValue(), spinx, spiny, spinz));
|
||||
}
|
||||
|
||||
VectorMap<TileData> dx = new VectorMap<>();
|
||||
|
||||
for (var entry : self.states) {
|
||||
dx.put(r.rotate(entry.getKey(), spinx, spiny, spinz), entry.getValue());
|
||||
}
|
||||
|
||||
self.blocks = d;
|
||||
self.states = dx;
|
||||
IrisObjectShaping.shrinkwrap(self);
|
||||
self.surfaceSupportOffsets.reset();
|
||||
self.floatingFootprint.reset();
|
||||
} finally {
|
||||
self.writeLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
static IrisObject scaled(IrisObject self, double scale, IrisObjectPlacementScaleInterpolator interpolation) {
|
||||
if (interpolation == null) {
|
||||
interpolation = IrisObjectPlacementScaleInterpolator.NONE;
|
||||
}
|
||||
IrisVector sm1 = new IrisVector(scale - 1, scale - 1, scale - 1);
|
||||
scale = Math.max(0.001, Math.min(50, scale));
|
||||
if (scale < 1) {
|
||||
scale = scale - 0.0001;
|
||||
}
|
||||
|
||||
IrisPosition l1 = self.getAABB().max();
|
||||
IrisPosition l2 = self.getAABB().min();
|
||||
VectorMap<PlatformBlockState> placeBlock = new VectorMap<>();
|
||||
|
||||
IrisVector center = new IrisVector(self.getCenter().getX(), self.getCenter().getY(), self.getCenter().getZ());
|
||||
if (self.getH() == 2) {
|
||||
center = center.setY(center.getBlockY() + 0.5);
|
||||
}
|
||||
if (self.getW() == 2) {
|
||||
center = center.setX(center.getBlockX() + 0.5);
|
||||
}
|
||||
if (self.getD() == 2) {
|
||||
center = center.setZ(center.getBlockZ() + 0.5);
|
||||
}
|
||||
|
||||
IrisObject oo = new IrisObject((int) Math.ceil((self.w * scale) + (scale * 2)), (int) Math.ceil((self.h * scale) + (scale * 2)), (int) Math.ceil((self.d * scale) + (scale * 2)));
|
||||
oo.setLoadKey(self.getLoadKey());
|
||||
oo.setLoader(self.getLoader());
|
||||
oo.setLoadFile(self.getLoadFile());
|
||||
|
||||
self.readLock.lock();
|
||||
try {
|
||||
for (var entry : self.blocks) {
|
||||
PlatformBlockState bd = entry.getValue();
|
||||
placeBlock.put(entry.getKey().clone().add(IrisObject.HALF).subtract(center)
|
||||
.multiply(scale).add(sm1).toBlockVector(), bd);
|
||||
}
|
||||
} finally {
|
||||
self.readLock.unlock();
|
||||
}
|
||||
|
||||
for (var entry : placeBlock) {
|
||||
IrisBlockVector v = entry.getKey();
|
||||
if (scale > 1) {
|
||||
for (IrisBlockVector vec : IrisObjectShaping.blocksBetweenTwoPoints(v.clone().add(center), v.clone().add(center).add(sm1))) {
|
||||
oo.blocks.put(vec, entry.getValue());
|
||||
}
|
||||
} else {
|
||||
oo.setUnsigned(v.getBlockX(), v.getBlockY(), v.getBlockZ(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
if (scale > 1) {
|
||||
switch (interpolation) {
|
||||
case TRILINEAR -> trilinear(oo, (int) Math.round(scale));
|
||||
case TRICUBIC -> tricubic(oo, (int) Math.round(scale));
|
||||
case TRIHERMITE -> trihermite(oo, (int) Math.round(scale));
|
||||
}
|
||||
}
|
||||
|
||||
return oo;
|
||||
}
|
||||
|
||||
static void trilinear(IrisObject self, int rad) {
|
||||
self.writeLock.lock();
|
||||
try {
|
||||
VectorMap<PlatformBlockState> v = self.blocks;
|
||||
VectorMap<PlatformBlockState> b = new VectorMap<>();
|
||||
IrisPosition min = self.getAABB().min();
|
||||
IrisPosition max = self.getAABB().max();
|
||||
NearestBlockIndex nearestBlocks = NearestBlockIndex.create(v);
|
||||
|
||||
for (int x = min.getX(); x <= max.getX(); x++) {
|
||||
for (int y = min.getY(); y <= max.getY(); y++) {
|
||||
for (int z = min.getZ(); z <= max.getZ(); z++) {
|
||||
if (Interpolation3D.getTrilinear(x, y, z, rad, (xx, yy, zz) -> {
|
||||
PlatformBlockState data = v.get(new IrisBlockVector((int) xx, (int) yy, (int) zz));
|
||||
|
||||
if (B.isAir(data)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}) >= 0.5) {
|
||||
b.put(new IrisBlockVector(x, y, z), nearestBlockData(v, nearestBlocks, x, y, z));
|
||||
} else {
|
||||
b.put(new IrisBlockVector(x, y, z), IrisObject.States.AIR);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.blocks = b;
|
||||
self.surfaceSupportOffsets.reset();
|
||||
self.floatingFootprint.reset();
|
||||
} finally {
|
||||
self.writeLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
static void tricubic(IrisObject self, int rad) {
|
||||
self.writeLock.lock();
|
||||
try {
|
||||
VectorMap<PlatformBlockState> v = self.blocks;
|
||||
VectorMap<PlatformBlockState> b = new VectorMap<>();
|
||||
IrisPosition min = self.getAABB().min();
|
||||
IrisPosition max = self.getAABB().max();
|
||||
NearestBlockIndex nearestBlocks = NearestBlockIndex.create(v);
|
||||
|
||||
for (int x = min.getX(); x <= max.getX(); x++) {
|
||||
for (int y = min.getY(); y <= max.getY(); y++) {
|
||||
for (int z = min.getZ(); z <= max.getZ(); z++) {
|
||||
if (Interpolation3D.getTricubic(x, y, z, rad, (xx, yy, zz) -> {
|
||||
PlatformBlockState data = v.get(new IrisBlockVector((int) xx, (int) yy, (int) zz));
|
||||
|
||||
if (B.isAir(data)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}) >= 0.5) {
|
||||
b.put(new IrisBlockVector(x, y, z), nearestBlockData(v, nearestBlocks, x, y, z));
|
||||
} else {
|
||||
b.put(new IrisBlockVector(x, y, z), IrisObject.States.AIR);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.blocks = b;
|
||||
self.surfaceSupportOffsets.reset();
|
||||
self.floatingFootprint.reset();
|
||||
} finally {
|
||||
self.writeLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
static void trihermite(IrisObject self, int rad) {
|
||||
trihermite(self, rad, 0D, 0D);
|
||||
}
|
||||
|
||||
static void trihermite(IrisObject self, int rad, double tension, double bias) {
|
||||
self.writeLock.lock();
|
||||
try {
|
||||
VectorMap<PlatformBlockState> v = self.blocks;
|
||||
VectorMap<PlatformBlockState> b = new VectorMap<>();
|
||||
IrisPosition min = self.getAABB().min();
|
||||
IrisPosition max = self.getAABB().max();
|
||||
NearestBlockIndex nearestBlocks = NearestBlockIndex.create(v);
|
||||
|
||||
for (int x = min.getX(); x <= max.getX(); x++) {
|
||||
for (int y = min.getY(); y <= max.getY(); y++) {
|
||||
for (int z = min.getZ(); z <= max.getZ(); z++) {
|
||||
if (Interpolation3D.getTrihermite(x, y, z, rad, (xx, yy, zz) -> {
|
||||
PlatformBlockState data = v.get(new IrisBlockVector((int) xx, (int) yy, (int) zz));
|
||||
|
||||
if (B.isAir(data)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}, tension, bias) >= 0.5) {
|
||||
b.put(new IrisBlockVector(x, y, z), nearestBlockData(v, nearestBlocks, x, y, z));
|
||||
} else {
|
||||
b.put(new IrisBlockVector(x, y, z), IrisObject.States.AIR);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.blocks = b;
|
||||
self.surfaceSupportOffsets.reset();
|
||||
self.floatingFootprint.reset();
|
||||
} finally {
|
||||
self.writeLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private static PlatformBlockState nearestBlockData(VectorMap<PlatformBlockState> blocks,
|
||||
NearestBlockIndex nearestBlocks,
|
||||
int x, int y, int z) {
|
||||
IrisBlockVector vv = new IrisBlockVector(x, y, z);
|
||||
PlatformBlockState direct = blocks.get(vv);
|
||||
if (!B.isAir(direct)) {
|
||||
return direct;
|
||||
}
|
||||
return nearestBlocks.nearest(x, y, z, direct);
|
||||
}
|
||||
|
||||
static final class NearestBlockIndex {
|
||||
private static final Comparator<NearestBlock> X_ORDER = Comparator
|
||||
.comparingInt(NearestBlock::x)
|
||||
.thenComparingInt(NearestBlock::rank);
|
||||
private static final Comparator<NearestBlock> Y_ORDER = Comparator
|
||||
.comparingInt(NearestBlock::y)
|
||||
.thenComparingInt(NearestBlock::rank);
|
||||
private static final Comparator<NearestBlock> Z_ORDER = Comparator
|
||||
.comparingInt(NearestBlock::z)
|
||||
.thenComparingInt(NearestBlock::rank);
|
||||
|
||||
private final NearestNode root;
|
||||
private PlatformBlockState bestState;
|
||||
private double bestDistance;
|
||||
private int bestRank;
|
||||
|
||||
private NearestBlockIndex(NearestNode root) {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
static NearestBlockIndex create(VectorMap<PlatformBlockState> blocks) {
|
||||
List<NearestBlock> points = new ArrayList<>(blocks.size());
|
||||
VectorMap<PlatformBlockState>.Cursor cursor = blocks.cursor();
|
||||
int rank = 0;
|
||||
while (cursor.next()) {
|
||||
PlatformBlockState state = cursor.value();
|
||||
if (!B.isAir(state)) {
|
||||
IrisBlockVector position = cursor.key();
|
||||
points.add(new NearestBlock(position.getBlockX(), position.getBlockY(), position.getBlockZ(),
|
||||
rank, state));
|
||||
}
|
||||
rank++;
|
||||
}
|
||||
|
||||
NearestBlock[] pointArray = points.toArray(new NearestBlock[0]);
|
||||
return new NearestBlockIndex(build(pointArray, 0, pointArray.length, 0));
|
||||
}
|
||||
|
||||
PlatformBlockState nearest(int x, int y, int z, PlatformBlockState fallback) {
|
||||
if (root == null) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
bestState = fallback;
|
||||
bestDistance = Double.MAX_VALUE;
|
||||
bestRank = Integer.MAX_VALUE;
|
||||
search(root, x, y, z);
|
||||
return bestState;
|
||||
}
|
||||
|
||||
private static NearestNode build(NearestBlock[] points, int from, int to, int depth) {
|
||||
if (from >= to) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int axis = depth % 3;
|
||||
Arrays.sort(points, from, to, comparator(axis));
|
||||
int middle = (from + to) >>> 1;
|
||||
return new NearestNode(
|
||||
points[middle],
|
||||
axis,
|
||||
build(points, from, middle, depth + 1),
|
||||
build(points, middle + 1, to, depth + 1)
|
||||
);
|
||||
}
|
||||
|
||||
private static Comparator<NearestBlock> comparator(int axis) {
|
||||
return switch (axis) {
|
||||
case 0 -> X_ORDER;
|
||||
case 1 -> Y_ORDER;
|
||||
default -> Z_ORDER;
|
||||
};
|
||||
}
|
||||
|
||||
private void search(NearestNode node, int x, int y, int z) {
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
NearestBlock point = node.point();
|
||||
double xDistance = point.x() - x;
|
||||
double yDistance = point.y() - y;
|
||||
double zDistance = point.z() - z;
|
||||
double distance = (xDistance * xDistance) + (yDistance * yDistance) + (zDistance * zDistance);
|
||||
if (distance < bestDistance || (distance == bestDistance && point.rank() < bestRank)) {
|
||||
bestState = point.state();
|
||||
bestDistance = distance;
|
||||
bestRank = point.rank();
|
||||
}
|
||||
|
||||
double axisDistance = switch (node.axis()) {
|
||||
case 0 -> x - point.x();
|
||||
case 1 -> y - point.y();
|
||||
default -> z - point.z();
|
||||
};
|
||||
NearestNode near = axisDistance <= 0D ? node.lower() : node.upper();
|
||||
NearestNode far = axisDistance <= 0D ? node.upper() : node.lower();
|
||||
search(near, x, y, z);
|
||||
if ((axisDistance * axisDistance) <= bestDistance) {
|
||||
search(far, x, y, z);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private record NearestNode(NearestBlock point, int axis, NearestNode lower, NearestNode upper) {
|
||||
}
|
||||
|
||||
private record NearestBlock(int x, int y, int z, int rank, PlatformBlockState state) {
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.prefab;
|
||||
|
||||
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.Required;
|
||||
import art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.volmlib.util.math.IrisBlockVector;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Snippet("object-translator")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("Translate objects")
|
||||
@Data
|
||||
public class IrisObjectTranslate {
|
||||
@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 boolean canTranslate() {
|
||||
return x != 0 || y != 0 || z != 0;
|
||||
}
|
||||
|
||||
public IrisBlockVector translate(IrisBlockVector i) {
|
||||
if (canTranslate()) {
|
||||
return (IrisBlockVector) i.clone().add(new IrisBlockVector(x, y, z));
|
||||
}
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
public IrisBlockVector translate(IrisBlockVector clone, IrisObjectRotation rotation, int sx, int sy, int sz) {
|
||||
if (canTranslate()) {
|
||||
return (IrisBlockVector) clone.clone().add(rotation.rotate(new IrisBlockVector(x, y, z), sx, sy, sz));
|
||||
}
|
||||
|
||||
return clone;
|
||||
}
|
||||
}
|
||||
@@ -1,476 +0,0 @@
|
||||
package art.arcane.iris.engine.object.prefab;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.DyeColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.Registry;
|
||||
import org.bukkit.Tag;
|
||||
import org.bukkit.block.Banner;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.BlockState;
|
||||
import org.bukkit.block.CreatureSpawner;
|
||||
import org.bukkit.block.Sign;
|
||||
import art.arcane.iris.core.nms.container.Pair;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.collection.KMap;
|
||||
import art.arcane.iris.util.common.reflect.KeyedType;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NonNull;
|
||||
import lombok.ToString;
|
||||
import org.apache.commons.io.function.IOFunction;
|
||||
import org.bukkit.block.banner.Pattern;
|
||||
import org.bukkit.block.banner.PatternType;
|
||||
import org.bukkit.block.sign.Side;
|
||||
import org.bukkit.block.sign.SignSide;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
import org.bukkit.entity.EntityType;
|
||||
import org.bukkit.loot.LootTable;
|
||||
import org.bukkit.loot.Lootable;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
/**
|
||||
* Bukkit-only pre-key tile format. Unreachable from the modded loaders: every entry point is
|
||||
* either Bukkit-typed ({@link #fromBukkit(BlockState)}, reached only from
|
||||
* {@link TileData#getTileState(Block, boolean)} and the Bukkit structure importer) or follows the
|
||||
* bound platform-reader path in {@link TileData#read(DataInputStream)}, which returns before this
|
||||
* class is ever referenced. The nested handler types
|
||||
* therefore keep their raw Bukkit fields.
|
||||
*/
|
||||
@ToString
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
public class LegacyTileData extends TileData {
|
||||
private final int id;
|
||||
private final Handler handler;
|
||||
|
||||
public LegacyTileData(DataInputStream in) throws IOException {
|
||||
id = in.readShort();
|
||||
Pair<Builder, IOFunction<DataInputStream, Handler>> factory = Handlers.LEGACY.get(id);
|
||||
if (factory == null)
|
||||
throw new IOException("Unknown tile type: " + id);
|
||||
handler = factory.getB().apply(in);
|
||||
}
|
||||
|
||||
private LegacyTileData(int id, Handler handler) {
|
||||
this.id = id;
|
||||
this.handler = handler;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static LegacyTileData fromBukkit(@NonNull BlockState tileState) {
|
||||
Material type = tileState.getType();
|
||||
for (Integer id : Handlers.LEGACY.keySet()) {
|
||||
Pair<Builder, IOFunction<DataInputStream, Handler>> factory = Handlers.LEGACY.get(id);
|
||||
Handler handler = factory.getA().apply(tileState, type);
|
||||
if (handler != null)
|
||||
return new LegacyTileData(id, handler);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static final class Handlers {
|
||||
private static final Map<Integer, Pair<Builder, IOFunction<DataInputStream, Handler>>> LEGACY = Map.of(
|
||||
0, new Pair<>(SignHandler::fromBukkit, SignHandler::new),
|
||||
1, new Pair<>(SpawnerHandler::fromBukkit, SpawnerHandler::new),
|
||||
2, new Pair<>(BannerHandler::fromBukkit, BannerHandler::new),
|
||||
3, new Pair<>(LootableHandler::fromBukkit, LootableHandler::new));
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull KMap<String, Object> getProperties() {
|
||||
return new KMap<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull String getMaterialKey() {
|
||||
return TileData.materialKey(handler.getMaterial());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Material resolveMaterial() {
|
||||
return handler.getMaterial();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isApplicable(BlockData data) {
|
||||
return handler.isApplicable(data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void toBukkit(Block block) {
|
||||
if (!J.runAt(block.getLocation(), () -> handler.toBukkit(block))) {
|
||||
J.s(() -> handler.toBukkit(block));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void toBinary(DataOutputStream out) throws IOException {
|
||||
out.writeShort(id);
|
||||
handler.toBinary(out);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TileData clone() {
|
||||
return this;
|
||||
}
|
||||
|
||||
private interface Handler {
|
||||
Material getMaterial();
|
||||
boolean isApplicable(BlockData data);
|
||||
void toBinary(DataOutputStream out) throws IOException;
|
||||
void toBukkit(Block block);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface Builder {
|
||||
@Nullable Handler apply(@NonNull BlockState blockState, @NonNull Material type);
|
||||
}
|
||||
|
||||
@ToString
|
||||
@EqualsAndHashCode
|
||||
@AllArgsConstructor
|
||||
private static class SignHandler implements Handler {
|
||||
private final String line1;
|
||||
private final String line2;
|
||||
private final String line3;
|
||||
private final String line4;
|
||||
private final DyeColor dyeColor;
|
||||
|
||||
private SignHandler(DataInputStream in) throws IOException {
|
||||
line1 = in.readUTF();
|
||||
line2 = in.readUTF();
|
||||
line3 = in.readUTF();
|
||||
line4 = in.readUTF();
|
||||
dyeColor = DyeColor.values()[in.readByte()];
|
||||
}
|
||||
|
||||
private static SignHandler fromBukkit(BlockState blockState, Material type) {
|
||||
if (!signsTag().isTagged(type) || !(blockState instanceof Sign sign))
|
||||
return null;
|
||||
SignSide front = sign.getSide(Side.FRONT);
|
||||
return new SignHandler(front.getLine(0), front.getLine(1), front.getLine(2), front.getLine(3), front.getColor());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Material getMaterial() {
|
||||
return Material.OAK_SIGN;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isApplicable(BlockData data) {
|
||||
return signsTag().isTagged(data.getMaterial());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void toBinary(DataOutputStream out) throws IOException {
|
||||
out.writeUTF(line1);
|
||||
out.writeUTF(line2);
|
||||
out.writeUTF(line3);
|
||||
out.writeUTF(line4);
|
||||
out.writeByte(dyeColor.ordinal());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void toBukkit(Block block) {
|
||||
Sign sign = (Sign) block.getState();
|
||||
SignSide front = sign.getSide(Side.FRONT);
|
||||
SignSide back = sign.getSide(Side.BACK);
|
||||
front.setLine(0, line1);
|
||||
front.setLine(1, line2);
|
||||
front.setLine(2, line3);
|
||||
front.setLine(3, line4);
|
||||
front.setColor(dyeColor);
|
||||
back.setLine(0, line1);
|
||||
back.setLine(1, line2);
|
||||
back.setLine(2, line3);
|
||||
back.setLine(3, line4);
|
||||
back.setColor(dyeColor);
|
||||
sign.update();
|
||||
}
|
||||
}
|
||||
@ToString
|
||||
@EqualsAndHashCode
|
||||
@AllArgsConstructor
|
||||
private static class SpawnerHandler implements Handler {
|
||||
private final EntityType type;
|
||||
|
||||
private SpawnerHandler(DataInputStream in) throws IOException {
|
||||
EntityType resolved = null;
|
||||
if (in.markSupported()) {
|
||||
in.mark(Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
try {
|
||||
String keyString = in.readUTF();
|
||||
NamespacedKey key = NamespacedKey.fromString(keyString);
|
||||
resolved = key == null ? null : Registry.ENTITY_TYPE.get(key);
|
||||
if (resolved == null && in.markSupported()) {
|
||||
in.reset();
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
if (in.markSupported()) {
|
||||
in.reset();
|
||||
}
|
||||
}
|
||||
|
||||
if (resolved == null) {
|
||||
short legacyOrdinal = in.readShort();
|
||||
EntityType[] legacyValues = EntityType.values();
|
||||
if (legacyOrdinal >= 0 && legacyOrdinal < legacyValues.length) {
|
||||
resolved = legacyValues[legacyOrdinal];
|
||||
}
|
||||
}
|
||||
|
||||
type = resolved == null ? EntityType.PIG : resolved;
|
||||
}
|
||||
|
||||
private static SpawnerHandler fromBukkit(BlockState blockState, Material material) {
|
||||
if (material != Material.SPAWNER || !(blockState instanceof CreatureSpawner spawner))
|
||||
return null;
|
||||
return new SpawnerHandler(spawner.getSpawnedType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Material getMaterial() {
|
||||
return Material.SPAWNER;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isApplicable(BlockData data) {
|
||||
return data.getMaterial() == Material.SPAWNER;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void toBinary(DataOutputStream out) throws IOException {
|
||||
NamespacedKey key = KeyedType.getKey(type);
|
||||
out.writeUTF(key == null ? type.name() : key.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void toBukkit(Block block) {
|
||||
CreatureSpawner spawner = (CreatureSpawner) block.getState();
|
||||
spawner.setSpawnedType(type);
|
||||
spawner.update();
|
||||
}
|
||||
}
|
||||
@ToString
|
||||
@EqualsAndHashCode
|
||||
@AllArgsConstructor
|
||||
private static class BannerHandler implements Handler {
|
||||
private final KList<Pattern> patterns;
|
||||
private final DyeColor baseColor;
|
||||
|
||||
private BannerHandler(DataInputStream in) throws IOException {
|
||||
DyeColor[] dyeColors = DyeColor.values();
|
||||
int baseColorIndex = in.readUnsignedByte();
|
||||
baseColor = baseColorIndex >= 0 && baseColorIndex < dyeColors.length ? dyeColors[baseColorIndex] : DyeColor.WHITE;
|
||||
patterns = new KList<>();
|
||||
int listSize = in.readUnsignedByte();
|
||||
|
||||
if (in.markSupported()) {
|
||||
in.mark(Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
boolean parsedKeyed = false;
|
||||
try {
|
||||
KList<Pattern> keyedPatterns = new KList<>();
|
||||
for (int i = 0; i < listSize; i++) {
|
||||
int colorIndex = in.readUnsignedByte();
|
||||
DyeColor color = colorIndex >= 0 && colorIndex < dyeColors.length ? dyeColors[colorIndex] : DyeColor.WHITE;
|
||||
NamespacedKey patternKey = NamespacedKey.fromString(in.readUTF());
|
||||
PatternType pattern = patternKey == null ? null : Registry.BANNER_PATTERN.get(patternKey);
|
||||
if (pattern == null) {
|
||||
throw new IOException("Unknown banner pattern key");
|
||||
}
|
||||
keyedPatterns.add(new Pattern(color, pattern));
|
||||
}
|
||||
patterns.addAll(keyedPatterns);
|
||||
parsedKeyed = true;
|
||||
} catch (Throwable ignored) {
|
||||
if (in.markSupported()) {
|
||||
in.reset();
|
||||
}
|
||||
}
|
||||
|
||||
if (parsedKeyed) {
|
||||
return;
|
||||
}
|
||||
|
||||
PatternType[] legacyPatternTypes = PatternType.values();
|
||||
PatternType fallbackPattern = Registry.BANNER_PATTERN.get(NamespacedKey.minecraft("base"));
|
||||
if (fallbackPattern == null && legacyPatternTypes.length > 0) {
|
||||
fallbackPattern = legacyPatternTypes[0];
|
||||
}
|
||||
|
||||
for (int i = 0; i < listSize; i++) {
|
||||
int colorIndex = in.readUnsignedByte();
|
||||
DyeColor color = colorIndex >= 0 && colorIndex < dyeColors.length ? dyeColors[colorIndex] : DyeColor.WHITE;
|
||||
int legacyPatternIndex = in.readUnsignedByte();
|
||||
PatternType pattern = legacyPatternIndex >= 0 && legacyPatternIndex < legacyPatternTypes.length ? legacyPatternTypes[legacyPatternIndex] : fallbackPattern;
|
||||
if (pattern != null) {
|
||||
patterns.add(new Pattern(color, pattern));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static BannerHandler fromBukkit(BlockState blockState, Material type) {
|
||||
if (!Tag.BANNERS.isTagged(type) || !(blockState instanceof Banner banner))
|
||||
return null;
|
||||
return new BannerHandler(new KList<>(banner.getPatterns()), banner.getBaseColor());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Material getMaterial() {
|
||||
return Material.WHITE_BANNER;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isApplicable(BlockData data) {
|
||||
return Tag.BANNERS.isTagged(data.getMaterial());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void toBinary(DataOutputStream out) throws IOException {
|
||||
out.writeByte(baseColor.ordinal());
|
||||
out.writeByte(patterns.size());
|
||||
for (Pattern i : patterns) {
|
||||
out.writeByte(i.getColor().ordinal());
|
||||
NamespacedKey key = KeyedType.getKey(i.getPattern());
|
||||
if (key == null) {
|
||||
key = NamespacedKey.minecraft("base");
|
||||
}
|
||||
out.writeUTF(key.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void toBukkit(Block block) {
|
||||
Banner banner = (Banner) block.getState();
|
||||
banner.setBaseColor(baseColor);
|
||||
banner.setPatterns(patterns);
|
||||
banner.update();
|
||||
}
|
||||
}
|
||||
|
||||
@ToString
|
||||
@EqualsAndHashCode
|
||||
@AllArgsConstructor
|
||||
private static class LootableHandler implements Handler {
|
||||
private final Material material;
|
||||
private final NamespacedKey lootTable;
|
||||
private final long seed;
|
||||
|
||||
private LootableHandler(DataInputStream in) throws IOException {
|
||||
String materialKey = in.readUTF();
|
||||
NamespacedKey resolvedMaterial = NamespacedKey.fromString(materialKey);
|
||||
Material resolved = resolvedMaterial == null ? null : Registry.MATERIAL.get(resolvedMaterial);
|
||||
if (resolved == null) {
|
||||
resolved = Material.matchMaterial(materialKey);
|
||||
}
|
||||
material = resolved == null ? Material.CHEST : resolved;
|
||||
String tableKey = in.readUTF();
|
||||
lootTable = tableKey.isEmpty() ? null : NamespacedKey.fromString(tableKey);
|
||||
seed = in.readLong();
|
||||
}
|
||||
|
||||
private static LootableHandler fromBukkit(BlockState blockState, Material type) {
|
||||
if (!(blockState instanceof Lootable lootable)) {
|
||||
return null;
|
||||
}
|
||||
LootTable table = lootable.getLootTable();
|
||||
if (table == null) {
|
||||
return null;
|
||||
}
|
||||
NamespacedKey key = table.getKey();
|
||||
if (key == null) {
|
||||
return null;
|
||||
}
|
||||
return new LootableHandler(type, key, lootable.getSeed());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Material getMaterial() {
|
||||
return material;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isApplicable(BlockData data) {
|
||||
return data.getMaterial() == material;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void toBinary(DataOutputStream out) throws IOException {
|
||||
NamespacedKey key = KeyedType.getKey(material);
|
||||
out.writeUTF(key == null ? material.name() : key.toString());
|
||||
out.writeUTF(lootTable == null ? "" : lootTable.toString());
|
||||
out.writeLong(seed);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void toBukkit(Block block) {
|
||||
if (lootTable == null || !(block.getState() instanceof Lootable lootable)) {
|
||||
return;
|
||||
}
|
||||
LootTable table = Bukkit.getLootTable(lootTable);
|
||||
if (table == null) {
|
||||
return;
|
||||
}
|
||||
lootable.setLootTable(table);
|
||||
lootable.setSeed(seed);
|
||||
((BlockState) lootable).update(true, false);
|
||||
}
|
||||
}
|
||||
|
||||
private static Tag<Material> signsTag() {
|
||||
return SignTags.get();
|
||||
}
|
||||
|
||||
private static final class SignTags {
|
||||
private static final AtomicCache<Tag<Material>> SIGNS = new AtomicCache<>();
|
||||
|
||||
private static Tag<Material> get() {
|
||||
return SIGNS.aquire(() -> {
|
||||
Tag<Material> signs = Bukkit.getTag("blocks", NamespacedKey.minecraft("all_signs"), Material.class);
|
||||
if (signs != null)
|
||||
return signs;
|
||||
return new Tag<>() {
|
||||
@Override
|
||||
public boolean isTagged(@NotNull Material item) {
|
||||
NamespacedKey key = KeyedType.getKey(item);
|
||||
if (key != null) {
|
||||
return key.getKey().endsWith("_sign");
|
||||
}
|
||||
return item.name().toLowerCase(Locale.ROOT).endsWith("_sign");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public Set<Material> getValues() {
|
||||
return StreamSupport.stream(Registry.MATERIAL.spliterator(), false)
|
||||
.filter(this::isTagged)
|
||||
.collect(Collectors.toUnmodifiableSet());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public NamespacedKey getKey() {
|
||||
return NamespacedKey.minecraft("all_signs");
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,278 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.prefab;
|
||||
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.Strictness;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.util.common.reflect.KeyedType;
|
||||
import art.arcane.volmlib.util.collection.KMap;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.NonNull;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.TileState;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@SuppressWarnings("ALL")
|
||||
@Getter
|
||||
@EqualsAndHashCode
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
public class TileData implements Cloneable {
|
||||
private static final Gson gson = new GsonBuilder().disableHtmlEscaping().setStrictness(Strictness.LENIENT).setObjectToNumberStrategy(com.google.gson.ToNumberPolicy.LONG_OR_DOUBLE).create();
|
||||
/**
|
||||
* Memoized {@link #resolveMaterial()}. Pasting one tile resolves its material at least twice
|
||||
* ({@link #isApplicable(BlockData)} then {@link #toBukkit(Block)}), and matchMaterial normalizes the string and
|
||||
* then hits the Bukkit registry - an object with thousands of tiles paid for that thousands of times.
|
||||
* <p>
|
||||
* Static and keyed by the stored key rather than an instance field for two reasons: distinct tiles overwhelmingly
|
||||
* repeat a handful of keys, so the cache is far more effective shared; and an instance field of a Bukkit type -
|
||||
* transient or not - fails the pack purity gate, because {@code Class#getDeclaredFields()} resolves every declared
|
||||
* field type eagerly, so one such field makes this class unloadable on Fabric/Forge/NeoForge. Static fields are
|
||||
* never part of that walk. Bounded by the number of distinct material keys a pack can name.
|
||||
*/
|
||||
private static final Map<String, Material> RESOLVED_MATERIALS = new ConcurrentHashMap<>();
|
||||
private static volatile TileReader PLATFORM_READER = null;
|
||||
private static volatile TileFactory PLATFORM_FACTORY = null;
|
||||
|
||||
public interface TileReader {
|
||||
TileData read(DataInputStream in) throws IOException;
|
||||
}
|
||||
|
||||
public interface TileFactory {
|
||||
TileData create(PlatformBlockState state, KMap<String, Object> properties);
|
||||
}
|
||||
|
||||
public static synchronized TileReader bindPlatformReader(TileReader reader) {
|
||||
TileReader previous = PLATFORM_READER;
|
||||
PLATFORM_READER = Objects.requireNonNull(reader, "reader");
|
||||
return previous;
|
||||
}
|
||||
|
||||
public static synchronized TileFactory bindPlatformFactory(TileFactory factory) {
|
||||
TileFactory previous = PLATFORM_FACTORY;
|
||||
PLATFORM_FACTORY = Objects.requireNonNull(factory, "factory");
|
||||
return previous;
|
||||
}
|
||||
|
||||
public static synchronized void restorePlatformReader(TileReader reader) {
|
||||
PLATFORM_READER = reader;
|
||||
}
|
||||
|
||||
public static synchronized void restorePlatformFactory(TileFactory factory) {
|
||||
PLATFORM_FACTORY = factory;
|
||||
}
|
||||
|
||||
/**
|
||||
* The block key this tile belongs to, stored as text so the field type never drags
|
||||
* org.bukkit.Material onto a Gson field walk or into generated equals/hashCode/toString.
|
||||
* <p>
|
||||
* Gson data-compat: Material serialized as its enum name, so the same JSON member name with a
|
||||
* String type parses every existing pack byte-for-byte. Persisted values are either a legacy
|
||||
* uppercase enum name ("CHEST") or a namespaced key ("minecraft:chest"); both are accepted at
|
||||
* the Bukkit resolution edge in {@link #resolveMaterial()}.
|
||||
*/
|
||||
@Getter(AccessLevel.NONE)
|
||||
@NonNull
|
||||
private String material;
|
||||
@NonNull
|
||||
private KMap<String, Object> properties;
|
||||
|
||||
/**
|
||||
* The platform-neutral block key. Safe on every platform - use this instead of resolving a
|
||||
* Material anywhere outside the Bukkit adapter.
|
||||
*/
|
||||
public String getMaterialKey() {
|
||||
return material;
|
||||
}
|
||||
|
||||
public static boolean setTileState(Block block, TileData data) {
|
||||
if (block.getState() instanceof TileState && data.isApplicable(block.getBlockData()))
|
||||
return data.toBukkitTry(block);
|
||||
return false;
|
||||
}
|
||||
|
||||
public static TileData getTileState(Block block, boolean useLegacy) {
|
||||
if (!BukkitPlatform.hasTile(block.getType()))
|
||||
return null;
|
||||
if (useLegacy) {
|
||||
LegacyTileData legacy = LegacyTileData.fromBukkit(block.getState());
|
||||
if (legacy != null)
|
||||
return legacy;
|
||||
}
|
||||
|
||||
return new TileData().fromBukkit(block);
|
||||
}
|
||||
|
||||
public static TileData of(PlatformBlockState state, KMap<String, Object> properties) {
|
||||
TileFactory factory = PLATFORM_FACTORY;
|
||||
if (factory != null) {
|
||||
return factory.create(state, properties);
|
||||
}
|
||||
Object handle = state.nativeHandle();
|
||||
if (!(handle instanceof BlockData blockData)) {
|
||||
return null;
|
||||
}
|
||||
return new TileData(materialKey(blockData.getMaterial()), properties);
|
||||
}
|
||||
|
||||
public static TileData read(DataInputStream in) throws IOException {
|
||||
TileReader reader = PLATFORM_READER;
|
||||
if (reader != null) {
|
||||
return reader.read(in);
|
||||
}
|
||||
if (!in.markSupported())
|
||||
throw new IOException("Mark not supported");
|
||||
in.mark(Integer.MAX_VALUE);
|
||||
try {
|
||||
// Resolving the material is the modern/legacy stream discriminator: an unresolvable
|
||||
// first UTF means these bytes are a LegacyTileData record, not a modern one.
|
||||
Material resolved = Material.matchMaterial(in.readUTF());
|
||||
if (resolved == null)
|
||||
throw new IOException("Not a modern tile record");
|
||||
return new TileData(materialKey(resolved), gson.fromJson(in.readUTF(), KMap.class));
|
||||
} catch (Throwable e) {
|
||||
in.reset();
|
||||
return new LegacyTileData(in);
|
||||
} finally {
|
||||
in.mark(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bukkit resolution edge: canonicalizes a Material to the namespaced key form that
|
||||
* {@link #toBinary(DataOutputStream)} has always written, falling back to the enum name.
|
||||
*/
|
||||
static String materialKey(Material material) {
|
||||
if (material == null) {
|
||||
return "";
|
||||
}
|
||||
NamespacedKey key = KeyedType.getKey(material);
|
||||
return key == null ? material.name() : key.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bukkit resolution edge. Accepts both persisted forms: the legacy uppercase enum name
|
||||
* ("CHEST") and the namespaced key ("minecraft:chest") - matchMaterial handles both.
|
||||
*/
|
||||
public Material resolveMaterial() {
|
||||
if (material == null || material.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Material cached = RESOLVED_MATERIALS.get(material);
|
||||
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
Material resolved = Material.matchMaterial(material);
|
||||
|
||||
if (resolved != null) {
|
||||
RESOLVED_MATERIALS.put(material, resolved);
|
||||
}
|
||||
|
||||
return resolved;
|
||||
}
|
||||
|
||||
public boolean isApplicable(BlockData data) {
|
||||
Material resolved = resolveMaterial();
|
||||
return resolved != null && data.getMaterial() == resolved;
|
||||
}
|
||||
|
||||
public void toBukkit(Block block) {
|
||||
Material resolved = resolveMaterial();
|
||||
if (resolved == null) throw new IllegalStateException("Material not set: " + material);
|
||||
if (block.getType() != resolved)
|
||||
throw new IllegalStateException("Material mismatch: " + block.getType() + " vs " + resolved);
|
||||
BukkitPlatform.deserializeTile(properties, block.getLocation());
|
||||
}
|
||||
|
||||
public TileData fromBukkit(Block block) {
|
||||
if (material != null && !material.isEmpty()) {
|
||||
Material resolved = resolveMaterial();
|
||||
if (block.getType() != resolved)
|
||||
throw new IllegalStateException("Material mismatch: " + block.getType() + " vs " + material);
|
||||
} else {
|
||||
material = materialKey(block.getType());
|
||||
}
|
||||
properties = BukkitPlatform.serializeTile(block.getLocation());
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean toBukkitTry(Block block) {
|
||||
try {
|
||||
//noinspection unchecked
|
||||
toBukkit(block);
|
||||
return true;
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean fromBukkitTry(Block block) {
|
||||
try {
|
||||
//noinspection unchecked
|
||||
fromBukkit(block);
|
||||
return true;
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public void toBinary(DataOutputStream out) throws IOException {
|
||||
// The field already holds the canonical key form that this stream has always carried.
|
||||
out.writeUTF(material == null ? "" : material);
|
||||
out.writeUTF(gson.toJson(properties));
|
||||
}
|
||||
|
||||
@Override
|
||||
public TileData clone() {
|
||||
TileData clone = new TileData();
|
||||
clone.material = material;
|
||||
clone.properties = properties.copy(); //TODO make a deep copy
|
||||
return clone;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.valueOf(material) + gson.toJson(properties);
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package art.arcane.iris.engine.object.prefab.matter;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.util.project.matter.IrisMatterContext;
|
||||
import art.arcane.iris.util.project.matter.IrisMatterSupport;
|
||||
import art.arcane.volmlib.util.matter.IrisMatter;
|
||||
import art.arcane.volmlib.util.matter.Matter;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
public class IrisMatterObject extends IrisRegistrant {
|
||||
private final Matter matter;
|
||||
|
||||
public IrisMatterObject() {
|
||||
this(1, 1, 1);
|
||||
}
|
||||
|
||||
public IrisMatterObject(int w, int h, int d) {
|
||||
this(createMatter(w, h, d));
|
||||
}
|
||||
|
||||
public IrisMatterObject(Matter matter) {
|
||||
IrisMatterSupport.ensureRegistered();
|
||||
this.matter = matter;
|
||||
}
|
||||
|
||||
public static IrisMatterObject from(IrisObject object) {
|
||||
return new IrisMatterObject(IrisMatterSupport.from(object));
|
||||
}
|
||||
|
||||
public static IrisMatterObject from(File j, IrisData data) throws IOException {
|
||||
IrisMatterSupport.ensureRegistered();
|
||||
try (IrisMatterContext.Scope scope = IrisMatterContext.open(data)) {
|
||||
return new IrisMatterObject(Matter.read(j));
|
||||
}
|
||||
}
|
||||
|
||||
private static Matter createMatter(int w, int h, int d) {
|
||||
IrisMatterSupport.ensureRegistered();
|
||||
return new IrisMatter(w, h, d);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFolderName() {
|
||||
return "matter";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeName() {
|
||||
return "Matter";
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.runtime;
|
||||
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.util.project.stream.ProceduralStream;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Desc("Represents a stream from the engine")
|
||||
public enum IrisEngineStreamType {
|
||||
@Desc("Represents the given slope at the x, z coordinates")
|
||||
SLOPE((f) -> f.getComplex().getSlopeStream()),
|
||||
|
||||
@Desc("Represents the base generator height at the given position. This includes only the biome generators / interpolation and noise features but does not include carving, caves.")
|
||||
HEIGHT((f) -> f.getComplex().getHeightStream()),
|
||||
|
||||
@Desc("Represents the base generator height at the given position. This includes only the biome generators / interpolation and noise features but does not include carving, caves. with Max(height, fluidHeight).")
|
||||
HEIGHT_OR_FLUID((f) -> f.getComplex().getHeightFluidStream()),
|
||||
|
||||
@Desc("Represents the overlay noise generators summed (dimension setting)")
|
||||
OVERLAY_NOISE((f) -> f.getComplex().getOverlayStream()),
|
||||
|
||||
@Desc("Represents the noise style of regions")
|
||||
REGION_STYLE((f) -> f.getComplex().getRegionStyleStream()),
|
||||
|
||||
@Desc("Represents the identity of regions. Each region has a unique number (very large numbers)")
|
||||
REGION_IDENTITY((f) -> f.getComplex().getRegionIdentityStream());
|
||||
|
||||
private final Function<Engine, ProceduralStream<Double>> getter;
|
||||
|
||||
IrisEngineStreamType(Function<Engine, ProceduralStream<Double>> getter) {
|
||||
this.getter = getter;
|
||||
}
|
||||
|
||||
public ProceduralStream<Double> get(Engine engine) {
|
||||
return getter.apply(engine);
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.runtime;
|
||||
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
@Desc("Represents a value from the engine")
|
||||
public enum IrisEngineValueType {
|
||||
@Desc("Represents actual height of the engine")
|
||||
ENGINE_HEIGHT((f) -> Double.valueOf(f.getHeight())),
|
||||
|
||||
@Desc("Represents virtual bottom of the engine in the compound. If this engine is on top of another engine, it's min height would be at the maxHeight of the previous engine + 1")
|
||||
ENGINE_MIN_HEIGHT((f) -> Double.valueOf(f.getMinHeight())),
|
||||
|
||||
@Desc("Represents virtual top of the engine in the compound. If this engine is below another engine, it's max height would be at the minHeight of the next engine - 1")
|
||||
ENGINE_MAX_HEIGHT((f) -> Double.valueOf(f.getWorld().maxHeight())),
|
||||
|
||||
@Desc("The fluid height defined in the dimension file")
|
||||
FLUID_HEIGHT((f) -> Double.valueOf(f.getComplex().getFluidHeight())),
|
||||
;
|
||||
|
||||
private final Function<Engine, Double> getter;
|
||||
|
||||
IrisEngineValueType(Function<Engine, Double> getter) {
|
||||
this.getter = getter;
|
||||
}
|
||||
|
||||
public Double get(Engine engine) {
|
||||
return getter.apply(engine);
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.runtime;
|
||||
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.engine.platform.BukkitChunkGenerator;
|
||||
import art.arcane.iris.engine.platform.studio.generators.BiomeBuffetGenerator;
|
||||
import art.arcane.iris.engine.platform.studio.generators.ObjectStudioGenerator;
|
||||
|
||||
@Desc("Represents a studio mode")
|
||||
public enum StudioMode {
|
||||
@Desc("Installs no studio generator; the dimension generates normally.")
|
||||
NORMAL,
|
||||
|
||||
@Desc("Debug layout: every biome in the dimension on a square grid, one chunk per biome cell, barrier floor past the last biome. Bukkit studio worlds only.")
|
||||
BIOME_BUFFET_1x1,
|
||||
|
||||
@Desc("Debug layout: every biome on a square grid with 3x3-chunk cells per biome, barrier floor past the last biome. Bukkit studio worlds only.")
|
||||
BIOME_BUFFET_3x3,
|
||||
|
||||
@Desc("Debug layout: every biome on a square grid with 5x5-chunk cells per biome, barrier floor past the last biome. Bukkit studio worlds only.")
|
||||
BIOME_BUFFET_5x5,
|
||||
|
||||
@Desc("Debug layout: every biome on a square grid with 9x9-chunk cells per biome, barrier floor past the last biome. Bukkit studio worlds only.")
|
||||
BIOME_BUFFET_9x9,
|
||||
|
||||
@Desc("Debug layout: every biome on a square grid with 18x18-chunk cells per biome, barrier floor past the last biome. Bukkit studio worlds only.")
|
||||
BIOME_BUFFET_18x18,
|
||||
|
||||
@Desc("Debug layout: every biome on a square grid with 36x36-chunk cells per biome, barrier floor past the last biome. Bukkit studio worlds only.")
|
||||
BIOME_BUFFET_36x36,
|
||||
|
||||
@Desc("Deprecated: generates exactly like NORMAL and will be removed in a future release.")
|
||||
REGION_BUFFET,
|
||||
|
||||
@Desc("Replaces terrain with the object studio: a flat polished-deepslate floor laying every pack object out on framed, end-rod-marked grid plinths. Bukkit studio worlds only.")
|
||||
OBJECT_BUFFET;
|
||||
|
||||
public void inject(BukkitChunkGenerator c) {
|
||||
switch (this) {
|
||||
case NORMAL, REGION_BUFFET -> c.setStudioGenerator(null);
|
||||
case BIOME_BUFFET_1x1 -> c.setStudioGenerator(new BiomeBuffetGenerator(c.getEngine(), 1));
|
||||
case BIOME_BUFFET_3x3 -> c.setStudioGenerator(new BiomeBuffetGenerator(c.getEngine(), 3));
|
||||
case BIOME_BUFFET_5x5 -> c.setStudioGenerator(new BiomeBuffetGenerator(c.getEngine(), 5));
|
||||
case BIOME_BUFFET_9x9 -> c.setStudioGenerator(new BiomeBuffetGenerator(c.getEngine(), 9));
|
||||
case BIOME_BUFFET_18x18 -> c.setStudioGenerator(new BiomeBuffetGenerator(c.getEngine(), 18));
|
||||
case BIOME_BUFFET_36x36 -> c.setStudioGenerator(new BiomeBuffetGenerator(c.getEngine(), 36));
|
||||
case OBJECT_BUFFET -> c.setStudioGenerator(new ObjectStudioGenerator(c.getEngine()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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.builtin.loot.ObjectLoot;
|
||||
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
|
||||
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.core.loader.IrisRegistrant;
|
||||
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 IrisRegistrant {
|
||||
@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<IrisJigsawWorkcell> 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<IrisJigsawThemeSet> 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<ObjectReplace> 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<String> 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;
|
||||
}
|
||||
|
||||
public IrisObjectPlacement createLootPlacement(String objectKey) {
|
||||
IrisObjectPlacement placement = new IrisObjectPlacement();
|
||||
placement.getPlace().add(objectKey);
|
||||
placement.setOverrideGlobalLoot(false);
|
||||
if (loot == null) {
|
||||
return placement;
|
||||
}
|
||||
for (String lootTable : loot) {
|
||||
if (lootTable != null && !lootTable.isBlank()) {
|
||||
placement.getLoot().add(new ObjectLoot(lootTable, 1));
|
||||
}
|
||||
}
|
||||
return placement;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFolderName() {
|
||||
return "structures";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeName() {
|
||||
return "Structure";
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.structure.jigsaw;
|
||||
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
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 IrisRegistrant {
|
||||
@Desc("Optional author-facing name shown by Jigsaw Studio. The resource key is shown when this is blank.")
|
||||
private String displayName = "";
|
||||
|
||||
@Required
|
||||
@RegistryListResource(IrisObject.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<IrisJigsawConnector> 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<String> 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";
|
||||
}
|
||||
}
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.structure.jigsaw;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
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 IrisRegistrant {
|
||||
@ArrayType(type = IrisJigsawPieceEntry.class, min = 1)
|
||||
@Desc("The weighted pieces in this pool.")
|
||||
private KList<IrisJigsawPieceEntry> 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";
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
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;
|
||||
}
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,258 +0,0 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.object.terrain;
|
||||
|
||||
import art.arcane.iris.engine.object.noise.IrisInterpolator;
|
||||
import art.arcane.iris.engine.object.noise.IrisNoiseGenerator;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
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.Required;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.iris.util.project.interpolation.IrisInterpolation;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.iris.util.project.noise.CellGenerator;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Desc("Represents a composite generator of noise gens")
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
public class IrisGenerator extends IrisRegistrant {
|
||||
private final transient AtomicCache<CellGenerator> cellGen = new AtomicCache<>();
|
||||
@MinNumber(0.001)
|
||||
@Desc("The zoom or frequency.")
|
||||
private double zoom = 1;
|
||||
@MinNumber(0)
|
||||
@Desc("The opacity, essentially a multiplier on the output.")
|
||||
private double opacity = 1;
|
||||
@Desc("Multiply the compsites instead of adding them")
|
||||
private boolean multiplicitive = false;
|
||||
@MinNumber(0.001)
|
||||
@Desc("The size of the cell fractures")
|
||||
private double cellFractureZoom = 1D;
|
||||
@MinNumber(0)
|
||||
@Desc("Cell Fracture Coordinate Shuffling")
|
||||
private double cellFractureShuffle = 12D;
|
||||
@Desc("The height of fracture cells. Set to 0 to disable")
|
||||
private double cellFractureHeight = 0D;
|
||||
@MinNumber(0)
|
||||
@MaxNumber(1)
|
||||
@Desc("How big are the cells (X,Z) relative to the veins that touch them. Between 0 and 1. 0.1 means thick veins, small cells.")
|
||||
private double cellPercentSize = 0.75D;
|
||||
@Desc("The offset to shift this noise x")
|
||||
private double offsetX = 0;
|
||||
@Desc("The offset to shift this noise z")
|
||||
private double offsetZ = 0;
|
||||
@Required
|
||||
@Desc("The seed for this generator")
|
||||
private long seed = 1;
|
||||
@Required
|
||||
@Desc("The interpolator to use when smoothing this generator into other regions & generators")
|
||||
private IrisInterpolator interpolator = new IrisInterpolator();
|
||||
@MinNumber(0)
|
||||
@MaxNumber(8192)
|
||||
@Desc("Cliff Height Max. Disable with 0 for min and max")
|
||||
private double cliffHeightMax = 0;
|
||||
@MinNumber(0)
|
||||
@MaxNumber(8192)
|
||||
@Desc("Cliff Height Min. Disable with 0 for min and max")
|
||||
private double cliffHeightMin = 0;
|
||||
@ArrayType(min = 1, type = IrisNoiseGenerator.class)
|
||||
@Desc("The list of noise gens this gen contains.")
|
||||
private KList<IrisNoiseGenerator> composite = new KList<>();
|
||||
@Desc("The noise gen for cliff height.")
|
||||
private IrisNoiseGenerator cliffHeightGenerator = new IrisNoiseGenerator();
|
||||
|
||||
public double getMax() {
|
||||
return opacity;
|
||||
}
|
||||
|
||||
public boolean hasCliffs() {
|
||||
return cliffHeightMax > 0;
|
||||
}
|
||||
|
||||
public CellGenerator getCellGenerator(long seed) {
|
||||
return cellGen.aquire(() -> new CellGenerator(new RNG(seed + 239466)));
|
||||
}
|
||||
|
||||
public <T> T fit(T[] v, long superSeed, double rx, double rz) {
|
||||
if (v.length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (v.length == 1) {
|
||||
return v[0];
|
||||
}
|
||||
|
||||
return v[fit(0, v.length - 1, superSeed, rx, rz)];
|
||||
}
|
||||
|
||||
public <T> T fit(List<T> v, long superSeed, double rx, double rz) {
|
||||
if (v.size() == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (v.size() == 1) {
|
||||
return v.get(0);
|
||||
}
|
||||
|
||||
return v.get(fit(0, v.size() - 1, superSeed, rx, rz));
|
||||
}
|
||||
|
||||
public int fit(int min, int max, long superSeed, double rx, double rz) {
|
||||
if (min == max) {
|
||||
return min;
|
||||
}
|
||||
|
||||
double noise = getHeight(rx, rz, superSeed);
|
||||
|
||||
return (int) Math.round(IrisInterpolation.lerp(min, max, noise));
|
||||
}
|
||||
|
||||
public int fit(double min, double max, long superSeed, double rx, double rz) {
|
||||
if (min == max) {
|
||||
return (int) Math.round(min);
|
||||
}
|
||||
|
||||
double noise = getHeight(rx, rz, superSeed);
|
||||
|
||||
return (int) Math.round(IrisInterpolation.lerp(min, max, noise));
|
||||
}
|
||||
|
||||
public double fitDouble(double min, double max, long superSeed, double rx, double rz) {
|
||||
if (min == max) {
|
||||
return min;
|
||||
}
|
||||
|
||||
double noise = getHeight(rx, rz, superSeed);
|
||||
|
||||
return IrisInterpolation.lerp(min, max, noise);
|
||||
}
|
||||
|
||||
public double getHeight(double rx, double rz, long superSeed) {
|
||||
return getHeight(rx, 0, rz, superSeed, true);
|
||||
}
|
||||
|
||||
|
||||
public double getHeight(double rx, double ry, double rz, long superSeed) {
|
||||
return getHeight(rx, ry, rz, superSeed, false);
|
||||
}
|
||||
|
||||
public double getHeight(double rx, double ry, double rz, long superSeed, boolean no3d) {
|
||||
if (composite.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ);
|
||||
double h = multiplicitive ? 1 : 0;
|
||||
double tp = 0;
|
||||
double sampleX = (rx + offsetX) / zoom;
|
||||
double sampleZ = (rz + offsetZ) / zoom;
|
||||
|
||||
if (composite.size() == 1) {
|
||||
if (multiplicitive) {
|
||||
h *= composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, getLoader());
|
||||
} else {
|
||||
tp += composite.get(0).getOpacity();
|
||||
h += composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, getLoader());
|
||||
}
|
||||
} else {
|
||||
for (IrisNoiseGenerator i : composite) {
|
||||
if (multiplicitive) {
|
||||
h *= i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, getLoader());
|
||||
} else {
|
||||
tp += i.getOpacity();
|
||||
h += i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, getLoader());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
double v = multiplicitive ? h * opacity : (h / tp) * opacity;
|
||||
|
||||
if (Double.isNaN(v)) {
|
||||
v = 0;
|
||||
}
|
||||
|
||||
v = hasCliffs() ? cliff(rx, rz, v, superSeed + 294596 + hc) : v;
|
||||
v = hasCellCracks() ? cell(rx, rz, v, superSeed + 48622 + hc) : v;
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
public double cell(double rx, double rz, double v, double superSeed) {
|
||||
getCellGenerator(getSeed() + 46222).setShuffle(getCellFractureShuffle());
|
||||
double fractureX = rx / getCellFractureZoom();
|
||||
double fractureZ = rz / getCellFractureZoom();
|
||||
return getCellGenerator(getSeed() + 46222).getDistance(fractureX, fractureZ) > getCellPercentSize() ? (v * getCellFractureHeight()) : v;
|
||||
}
|
||||
|
||||
private boolean hasCellCracks() {
|
||||
return getCellFractureHeight() != 0;
|
||||
}
|
||||
|
||||
public double getCliffHeight(double rx, double rz, double superSeed) {
|
||||
int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ);
|
||||
double sampleX = (rx + offsetX) / zoom;
|
||||
double sampleZ = (rz + offsetZ) / zoom;
|
||||
double h = cliffHeightGenerator.getNoise((long) (getSeed() + superSeed + hc), sampleX, sampleZ, getLoader());
|
||||
return IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, h);
|
||||
}
|
||||
|
||||
public double cliff(double rx, double rz, double v, double superSeed) {
|
||||
double cliffHeight = getCliffHeight(rx, rz, superSeed - 34857);
|
||||
return (Math.round((v * 255D) / cliffHeight) * cliffHeight) / 255D;
|
||||
}
|
||||
|
||||
public IrisGenerator rescale(double scale) {
|
||||
zoom /= scale;
|
||||
return this;
|
||||
}
|
||||
|
||||
public KList<IrisNoiseGenerator> getAllComposites() {
|
||||
KList<IrisNoiseGenerator> g = new KList<>();
|
||||
|
||||
for (IrisNoiseGenerator i : composite) {
|
||||
g.addAll(i.getAllComposites());
|
||||
}
|
||||
|
||||
return g;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFolderName() {
|
||||
return "generators";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeName() {
|
||||
return "Generator";
|
||||
}
|
||||
}
|
||||
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user