Merge branch 'dev/26.3-port'

This commit is contained in:
Zoe Gidiere committed 2026-11-09 18:08:03 -07:00
commit 1afba15b1d
440 files changed
+29411 -4874

No files matched your search

+2 -2
View File
@@ -18,10 +18,10 @@ jobs:
steps:
- uses: actions/checkout@v4.2.2
- name: Set up JDK 21
- name: Set up JDK 25
uses: actions/setup-java@v4.7.1
with:
java-version: '21'
java-version: '25'
distribution: 'temurin'
server-id: github # Value of the distributionManagement/repository/id field of the pom.xml
settings-path: ${{ github.workspace }} # location for the settings.xml file
+1 -5
View File
@@ -15,7 +15,7 @@ allprojects {
tasks.withType<JavaCompile>().configureEach {
options.isFork = true
options.isIncremental = true
options.release.set(21)
options.release.set(25)
}
tasks.withType<Test>().configureEach {
@@ -48,10 +48,6 @@ afterEvaluate {
forSubProjects(":common:addons") {
apply(plugin = "com.gradleup.shadow")
tasks.named("build") {
finalizedBy(tasks.named("shadowJar"))
}
dependencies {
"compileOnly"(project(":common:api"))
"testImplementation"(project(":common:api"))
+8 -3
View File
@@ -4,6 +4,12 @@ plugins {
}
repositories {
// TODO: remove once Tectonic 4.4.0 is published
mavenLocal {
content {
includeGroup("com.dfsek.tectonic")
}
}
mavenCentral()
gradlePluginPortal()
maven("https://maven.solo-studios.ca/releases") {
@@ -22,11 +28,10 @@ repositories {
dependencies {
//TODO Allow pulling from Versions.kt
implementation("com.gradleup.shadow", "shadow-gradle-plugin", "8.3.9")
implementation("com.gradleup.shadow", "shadow-gradle-plugin", "9.3.1")
implementation("io.papermc.paperweight.userdev", "io.papermc.paperweight.userdev.gradle.plugin", "2.0.0-beta.18")
implementation("org.ow2.asm", "asm", "9.9")
implementation("org.ow2.asm", "asm-tree", "9.9")
implementation("com.dfsek.tectonic", "common", "4.3.1")
implementation("com.dfsek.tectonic", "common", "4.4.0")
implementation("org.yaml", "snakeyaml", "2.5")
}
+11 -7
View File
@@ -41,22 +41,26 @@ fun Project.configureCompilation() {
}
}
// Gradle doesn't fingerprint filter arguments; the tokens are declared as inputs.
val metadataTokens = mapOf(
"DESCRIPTION" to properties["terra.description"],
"WIKI" to properties["terra.wiki"],
"SOURCE" to properties["terra.source"],
"ISSUES" to properties["terra.issues"],
"LICENSE" to properties["terra.license"]
)
tasks.withType<ProcessResources> {
include("**/*.*")
inputs.properties(metadataTokens.mapKeys { "token.${it.key}" }.mapValues { it.value.toString() })
filter<ReplaceTokens>(
"tokens" to mapOf(
"DESCRIPTION" to properties["terra.description"],
"WIKI" to properties["terra.wiki"],
"SOURCE" to properties["terra.source"],
"ISSUES" to properties["terra.issues"],
"LICENSE" to properties["terra.license"]
)
"tokens" to metadataTokens
)
}
afterEvaluate {
tasks.withType<ProcessResources> {
include("**/*.*")
inputs.property("token.VERSION", version.toString())
filter<ReplaceTokens>(
"tokens" to mapOf(
"VERSION" to version.toString()
@@ -57,9 +57,18 @@ fun Project.configureDependencies() {
maven("https://s01.oss.sonatype.org/content/repositories/snapshots/") {
name = "Sonatype Snapshots"
}
maven("https://repo.wyck.dev/snapshots") {
name = "Wyck Snapshots"
}
maven("https://repo.onarandombox.com/multiverse-releases") {
name = "onarandombox"
}
maven(url = "https://central.sonatype.com/repository/maven-snapshots/") {
content {
includeModule("net.minestom", "minestom")
includeModule("net.minestom", "testing")
}
}
}
dependencies {
+13 -4
View File
@@ -1,5 +1,4 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import io.papermc.paperweight.util.path
import java.io.File
import java.io.FileWriter
import java.net.URL
@@ -43,6 +42,16 @@ private fun Project.installAddonsInto(dest: Path) {
fun Project.configureDistribution() {
apply(plugin = "com.gradleup.shadow")
listOf("jar", "shadowJar").forEach { taskName ->
tasks.named<Jar>(taskName) {
manifest.attributes(mapOf(
"Implementation-Title" to "Terra",
"Implementation-Version" to project.version.toString(),
"Terra-Platform" to project.name
))
}
}
val downloadDefaultPacks = tasks.create("downloadDefaultPacks") {
group = "terra"
@@ -81,7 +90,7 @@ fun Project.configureDistribution() {
doLast {
// https://github.com/johnrengelman/shadow/issues/111
val dest = tasks.named<ShadowJar>("shadowJar").get().archiveFile.get().path
val dest = tasks.named<ShadowJar>("shadowJar").get().archiveFile.get().asFile.toPath()
installAddonsInto(dest)
}
}
@@ -91,7 +100,7 @@ fun Project.configureDistribution() {
dependsOn(compileAddons)
doLast {
val dest = tasks.named<Jar>("jar").get().archiveFile.get().path
val dest = tasks.named<Jar>("jar").get().archiveFile.get().asFile.toPath()
installAddonsInto(dest)
}
}
@@ -161,7 +170,7 @@ fun Project.configureDistribution() {
tasks.named<ShadowJar>("shadowJar") {
// Tell shadow to download the packs
dependsOn(downloadDefaultPacks)
configurations = listOf(project.configurations["shaded"])
configurations.set(listOf(project.configurations["shaded"]))
archiveClassifier.set("shaded")
version = project.version
relocate("org.apache.commons", "com.dfsek.terra.lib.commons")
+3 -8
View File
@@ -7,19 +7,14 @@ var isPrerelease = false
fun Project.getGitHash(): String {
val stdout = ByteArrayOutputStream()
exec {
return providers.exec {
commandLine = mutableListOf("git", "rev-parse", "--short", "HEAD")
standardOutput = stdout
}
return stdout.toString().trim()
}.standardOutput.asText.get().trim()
}
fun Project.gitClone(name: String) {
val stdout = ByteArrayOutputStream()
exec {
providers.exec {
commandLine = mutableListOf("git", "clone", name)
standardOutput = stdout
}
}
+21 -26
View File
@@ -7,19 +7,19 @@ object Versions {
}
object Libraries {
const val tectonic = "4.3.1"
const val tectonic = "4.4.0"
const val paralithic = "2.0.1"
const val strata = "1.3.2"
const val seismic = "2.5.7"
const val cloud = "2.0.0"
const val cloud = "2.1.0"
const val caffeine = "3.2.2"
const val slf4j = "2.0.17"
object Internal {
const val shadow = "8.3.9"
const val shadow = "9.3.1"
const val apacheText = "1.14.0"
const val apacheIO = "2.20.0"
const val guava = "33.5.0-jre"
@@ -32,8 +32,8 @@ object Versions {
}
object Fabric {
const val fabricAPI = "0.134.1+${Mod.minecraft}"
const val cloud = "2.0.0-beta.13"
const val fabricAPI = "0.165.2+${Mod.minecraft}"
const val cloud = "2.1.0"
}
//
// object Quilt {
@@ -42,15 +42,14 @@ object Versions {
// }
object Mod {
const val mixin = "0.16.4+mixin.0.8.7"
const val mixinExtras = "0.5.0"
const val mixin = "0.17.5+mixin.0.8.7"
const val mixinExtras = "0.5.5"
const val minecraft = "1.21.10"
const val yarn = "$minecraft+build.1"
const val fabricLoader = "0.18.2"
const val minecraft = "26.3"
const val fabricLoader = "0.20.1"
const val architecuryLoom = "1.11.451"
const val architecturyPlugin = "3.4.162"
const val architecturyLoom = "1.17.493"
const val architecturyPlugin = "3.5.170"
}
//
@@ -60,16 +59,12 @@ object Versions {
// }
object Bukkit {
const val minecraft = "1.21.10"
const val nms = "$minecraft-R0.1"
const val paperBuild = "$nms-20251012.013929-7"
const val minecraft = "26.3"
const val paperBuild = "$minecraft.build.244-stable"
const val paper = paperBuild
const val paperLib = "1.0.8"
const val reflectionRemapper = "0.1.3"
const val paperDevBundle = paperBuild
const val runPaper = "2.3.1"
const val paperWeight = "2.0.0-beta.19"
const val cloud = "2.0.0-beta.12"
const val runPaper = "3.0.2"
const val wyck = "4.0.0-0f573ad7"
const val cloud = "2.0.1"
const val multiverse = "5.3.0"
}
@@ -86,16 +81,16 @@ object Versions {
}
object Allay {
const val api = "0.20.0"
const val api = "0.28.0"
const val gson = "2.13.2"
const val mappings = "366baa6"
const val mappingsGenerator = "e957088"
const val mappings = "0c2ac22"
const val mappingsGenerator = "3742321"
const val mcmeta = "c976eb3"
const val mcmeta = "805b8ac"
}
object Minestom {
const val minestom = "2025.10.04-1.21.8"
const val minestom = "26_3-SNAPSHOT"
}
}
@@ -1,6 +1,5 @@
version = version("1.0.0")
version = version("2.0.0")
dependencies {
compileOnlyApi(project(":common:addons:manifest-addon-loader"))
compileOnlyApi(project(":common:addons:biome-query-api"))
}
@@ -7,6 +7,7 @@ import com.dfsek.terra.addons.biome.extrusion.api.ReplaceableBiome;
import com.dfsek.terra.addons.biome.extrusion.extrusions.ReplaceExtrusion;
import com.dfsek.terra.api.config.meta.Meta;
import com.dfsek.terra.api.util.collection.ProbabilityCollection;
import com.dfsek.terra.api.world.biome.tag.BiomeTag;
public class ReplaceExtrusionTemplate extends SamplerExtrusionTemplate {
@@ -14,10 +15,10 @@ public class ReplaceExtrusionTemplate extends SamplerExtrusionTemplate {
private @Meta ProbabilityCollection<@Meta ReplaceableBiome> biomes;
@Value("from")
private @Meta String fromTag;
private @Meta BiomeTag from;
@Override
public Extrusion get() {
return new ReplaceExtrusion(sampler, range, biomes, fromTag);
return new ReplaceExtrusion(sampler, range, biomes, from);
}
}
@@ -8,11 +8,10 @@ import java.util.stream.Collectors;
import com.dfsek.terra.addons.biome.extrusion.api.Extrusion;
import com.dfsek.terra.addons.biome.extrusion.api.ReplaceableBiome;
import com.dfsek.terra.addons.biome.query.api.BiomeQueries;
import com.dfsek.terra.api.util.collection.ProbabilityCollection;
import com.dfsek.terra.api.util.collection.TriStateIntCache;
import com.dfsek.terra.api.util.range.Range;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.api.world.biome.tag.BiomeTag;
/**
@@ -22,34 +21,19 @@ public class ReplaceExtrusion implements Extrusion {
private final Sampler sampler;
private final Range range;
private final ProbabilityCollection<ReplaceableBiome> biomes;
private final Predicate<Biome> hasTag;
private final TriStateIntCache cache;
// Concrete final type keeps has() monomorphic for inlining.
private final BiomeTag from;
public ReplaceExtrusion(Sampler sampler, Range range, ProbabilityCollection<ReplaceableBiome> biomes, String tag) {
public ReplaceExtrusion(Sampler sampler, Range range, ProbabilityCollection<ReplaceableBiome> biomes, BiomeTag from) {
this.sampler = sampler;
this.range = range;
this.biomes = biomes;
this.hasTag = BiomeQueries.has(tag);
this.cache = new TriStateIntCache(Biome.INT_ID_COUNTER.get());
this.from = from;
}
@Override
public Biome extrude(Biome original, int x, int y, int z, long seed) {
int id = original.getIntID();
long state = cache.get(id);
boolean passes;
if(state == TriStateIntCache.STATE_UNSET) {
// Only run the test if unset in cache
passes = hasTag.test(original);
cache.set(id, passes);
} else {
// Read the primitive long directly
passes = (state == TriStateIntCache.STATE_TRUE);
}
if(passes) {
if(from.has(original.getIntID())) {
if(range.isInRange(y)) {
return biomes.get(sampler, x, y, z, seed).get(original);
}
@@ -0,0 +1,215 @@
{
"id": "biome-provider-extrusion",
"docVersion": 1,
"description": "EXTRUSION biome provider and SET/REPLACE vertical extrusion variants.",
"types": {
"terra:BiomeProvider": {
"kind": "union",
"discriminator": "type",
"values": {
"EXTRUSION": {
"kind": "object",
"fields": {
"provider": {
"schema": {
"kind": "type",
"target": "terra:BiomeProvider"
},
"required": true
},
"resolution": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 4
},
"extrusions": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "Extrusion"
}
},
"required": true,
"summary": "Ordered extrusion steps."
}
}
}
}
},
"Extrusion": {
"kind": "union",
"discriminator": "type",
"values": {
"SET": {
"kind": "object",
"fields": {
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler"
},
"required": true
},
"range": {
"schema": {
"kind": "type",
"target": "terra:Range"
},
"required": true
},
"to": {
"schema": {
"kind": "type",
"target": "WeightedBiomes"
},
"required": true
}
},
"description": "Selects a replacement biome within the height range."
},
"REPLACE": {
"kind": "object",
"fields": {
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler"
},
"required": true
},
"range": {
"schema": {
"kind": "type",
"target": "terra:Range"
},
"required": true
},
"to": {
"schema": {
"kind": "type",
"target": "WeightedBiomes"
},
"required": true
},
"from": {
"schema": {
"kind": "type",
"target": "terra:Tag"
},
"required": true,
"summary": "Biome tag required before replacing."
}
},
"description": "Replaces biomes matching from within the height range."
}
}
},
"ReplaceableBiome": {
"kind": "oneOf",
"options": [
{
"kind": "ref",
"target": "terra:Biome"
},
{
"kind": "literal",
"value": "SELF",
"description": "Keep the input biome at this extrusion step."
}
],
"description": "Registered biome identifier or SELF. Unknown identifiers are rejected rather than becoming placeholders."
},
"WeightedBiomes": {
"kind": "oneOf",
"description": "Replaceable biome, biome-to-weight map, or list of maps. Singleton weights are ignored; all other weights are raw integers.",
"options": [
{
"kind": "type",
"target": "ReplaceableBiome"
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "ReplaceableBiome"
},
"values": {
"kind": "any",
"name": "Ignored singleton weight"
},
"maxEntries": 1
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "ReplaceableBiome"
},
"values": {
"kind": "integer"
},
"minEntries": 2
},
{
"kind": "list",
"element": {
"kind": "oneOf",
"options": [
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "ReplaceableBiome"
},
"values": {
"kind": "any",
"name": "Ignored singleton weight"
},
"maxEntries": 1
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "ReplaceableBiome"
},
"values": {
"kind": "integer"
},
"minEntries": 2
}
]
},
"maxItems": 1
},
{
"kind": "list",
"element": {
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "ReplaceableBiome"
},
"values": {
"kind": "integer"
}
},
"minItems": 2
}
]
}
}
}
@@ -10,5 +10,3 @@ website:
source: https://github.com/PolyhedralDev/Terra
docs: https://terra.polydev.org
license: MIT License
depends:
biome-query-api: "1.+"
@@ -0,0 +1,101 @@
package extrusion;
import com.dfsek.seismic.type.sampler.Sampler;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.Map;
import java.util.Set;
import com.dfsek.terra.addons.biome.extrusion.api.ReplaceableBiome;
import com.dfsek.terra.addons.biome.extrusion.extrusions.ReplaceExtrusion;
import com.dfsek.terra.api.properties.Context;
import com.dfsek.terra.api.util.collection.ProbabilityCollection;
import com.dfsek.terra.api.util.range.ConstantRange;
import com.dfsek.terra.api.util.range.Range;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.api.world.biome.PlatformBiome;
import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex;
import static org.junit.jupiter.api.Assertions.*;
class ReplaceExtrusionTest {
private static final Sampler SAMPLER = new Sampler() {
@Override
public double getSample(long seed, double x, double y) {
return 0;
}
@Override
public double getSample(long seed, double x, double y, double z) {
return 0;
}
};
private static final class StubBiome implements Biome {
private final String id;
private final Set<String> tags;
private final int intId;
StubBiome(BiomeTagIndex index, String id, Set<String> tags) {
this.id = id;
this.tags = tags;
this.intId = index.register(tags);
}
@Override
public PlatformBiome getPlatformBiome() {
return null;
}
@Override
public int getColor() {
return 0;
}
@Override
public Set<String> getTags() {
return tags;
}
@Override
public int getIntID() {
return intId;
}
@Override
public Context getContext() {
return null;
}
@Override
public String getID() {
return id;
}
}
private final BiomeTagIndex index = new BiomeTagIndex();
private final Map<String, Biome> biomes = Map.of(
"tagged", new StubBiome(index, "tagged", Set.of("X")),
"untagged", new StubBiome(index, "untagged", Set.of("Y")),
"replacement", new StubBiome(index, "replacement", Set.of()));
@ParameterizedTest(name = "{0}: {1} at y {2} -> {3}")
@CsvSource({
"X, tagged, 10, replacement",
"X, untagged, 10, untagged",
"X, tagged, 100, tagged",
"TYPO, tagged, 10, tagged",
"TYPO, untagged, 10, untagged",
"TYPO, replacement, 10, replacement",
})
void replacesTaggedBiomesInRange(String tag, String biome, int y, String expected) {
ProbabilityCollection<ReplaceableBiome> to = new ProbabilityCollection<ReplaceableBiome>()
.add(ReplaceableBiome.of(biomes.get("replacement")), 1);
Range range = new ConstantRange(0, 64);
ReplaceExtrusion extrusion = new ReplaceExtrusion(SAMPLER, range, to, index.tag(tag));
index.seal();
assertSame(biomes.get(expected), extrusion.extrude(biomes.get(biome), 0, y, 0, 0));
}
}
@@ -0,0 +1,118 @@
{
"id": "biome-provider-image",
"docVersion": 1,
"description": "Image biome provider with registered Biome outputs.",
"types": {
"terra:BiomeProvider": {
"kind": "union",
"discriminator": "type",
"values": {
"IMAGE": {
"kind": "object",
"fields": {
"resolution": {
"schema": {
"kind": "integer",
"nullable": true
},
"required": false,
"default": 1
},
"color-sampler": {
"schema": {
"kind": "type",
"target": "library-image:ColorSampler"
},
"required": true
},
"color-conversion": {
"schema": {
"kind": "type",
"target": "ColorConverter"
},
"required": true
}
}
}
}
},
"ColorConverter": {
"kind": "union",
"discriminator": "type",
"values": {
"EXACT": {
"kind": "object",
"fields": {
"match": {
"schema": {
"kind": "type",
"target": "ColorMapping"
},
"required": true
},
"else": {
"schema": {
"kind": "ref",
"target": "terra:Biome"
},
"required": true,
"summary": "Required fallback for colors with no exact mapping."
},
"ignore-alpha": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": true
}
},
"description": "Exact color matching with a fallback; alpha is ignored by default."
},
"CLOSEST": {
"kind": "object",
"fields": {
"match": {
"schema": {
"kind": "type",
"target": "ColorMapping"
},
"required": true
}
},
"description": "Closest color using summed absolute RGB differences; alpha is ignored. An empty map cannot produce a biome."
}
}
},
"ColorMapping": {
"kind": "union",
"discriminator": "type",
"values": {
"USE_BIOME_COLORS": {
"kind": "object",
"fields": {},
"description": "Build the mapping from registered Terra biome color values."
},
"MAP": {
"kind": "object",
"fields": {
"map": {
"schema": {
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "library-image:Color"
},
"values": {
"kind": "ref",
"target": "terra:Biome"
}
},
"required": true
}
}
}
}
}
}
}
@@ -1,4 +1,4 @@
version = version("2.0.0")
version = version("3.0.0")
dependencies {
compileOnlyApi(project(":common:addons:manifest-addon-loader"))
@@ -83,7 +83,7 @@ public class BiomePipelineAddon implements AddonInitializer {
.register(addon, ConfigPackPostLoadEvent.class)
.then(event -> {
Registry<Biome> biomeRegistry = event.getPack().getRegistry(Biome.class);
event.getPack().applyLoader(PipelineBiome.class, new PipelineBiomeLoader(biomeRegistry));
event.getPack().applyLoader(PipelineBiome.class, new PipelineBiomeLoader(biomeRegistry, event.getPack().getBiomeTagIndex()));
});
}
}
@@ -5,10 +5,11 @@ import java.util.Set;
import com.dfsek.terra.api.world.biome.Biome;
public final class DelegatedPipelineBiome implements PipelineBiome {
public final class DelegatedPipelineBiome extends PipelineBiome {
private final Biome biome;
public DelegatedPipelineBiome(Biome biome) {
super(biome.getIntID());
this.biome = biome;
}
@@ -4,30 +4,61 @@ import java.util.Set;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
public interface PipelineBiome extends StringIdentifiable {
static PipelineBiome placeholder(String id) {
return new PlaceholderPipelineBiome(id);
public abstract sealed class PipelineBiome implements StringIdentifiable
permits DelegatedPipelineBiome, PlaceholderPipelineBiome, SelfPipelineBiome {
private final int intId;
PipelineBiome(int intId) {
this.intId = intId;
}
static PipelineBiome from(Biome biome) {
/**
* Registers a new ID per call; call before {@code index} is sealed.
*/
@ApiStatus.Internal
public static PipelineBiome placeholder(String id, BiomeTagIndex index) {
return new PlaceholderPipelineBiome(id, index);
}
/**
* {@code biome} must come from the same pack as the index it is tested against.
*/
public static PipelineBiome from(Biome biome) {
return new DelegatedPipelineBiome(biome);
}
static PipelineBiome self() {
public static PipelineBiome self() {
return SelfPipelineBiome.INSTANCE;
}
Biome getBiome();
/**
* Dense per pack, not stable across loads.
*/
@Contract(pure = true)
public final int getIntID() {
return intId;
}
Set<String> getTags();
@NotNull
public abstract Biome getBiome();
default boolean isPlaceholder() {
@NotNull
public abstract Set<String> getTags();
@Contract(pure = true)
public boolean isPlaceholder() {
return false;
}
default boolean isSelf() {
@Contract(pure = true)
public boolean isSelf() {
return false;
}
@@ -4,17 +4,28 @@ import java.util.HashSet;
import java.util.Set;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex;
final class PlaceholderPipelineBiome implements PipelineBiome {
final class PlaceholderPipelineBiome extends PipelineBiome {
private final Set<String> tags;
private final String id;
public PlaceholderPipelineBiome(String id) {
public PlaceholderPipelineBiome(String id, BiomeTagIndex index) {
this(id, tagsOf(id), index);
}
private PlaceholderPipelineBiome(String id, Set<String> tags, BiomeTagIndex index) {
super(index.register(tags));
this.id = id;
tags = new HashSet<>();
this.tags = tags;
}
private static Set<String> tagsOf(String id) {
Set<String> tags = new HashSet<>();
tags.add(id);
tags.add("ALL");
return Set.copyOf(tags);
}
@Override
@@ -6,11 +6,11 @@ import java.util.Set;
import com.dfsek.terra.api.world.biome.Biome;
final class SelfPipelineBiome implements PipelineBiome {
final class SelfPipelineBiome extends PipelineBiome {
public static final SelfPipelineBiome INSTANCE = new SelfPipelineBiome();
private SelfPipelineBiome() {
super(0); // reserved in every pack's index, untagged
}
@Override
@@ -7,17 +7,23 @@ import com.dfsek.tectonic.api.loader.type.TypeLoader;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.AnnotatedType;
import java.util.concurrent.ConcurrentHashMap;
import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome;
import com.dfsek.terra.api.registry.Registry;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex;
public class PipelineBiomeLoader implements TypeLoader<PipelineBiome> {
private final Registry<Biome> biomeRegistry;
public PipelineBiomeLoader(Registry<Biome> biomeRegistry) {
private final BiomeTagIndex tagIndex;
private final ConcurrentHashMap<String, PipelineBiome> placeholders = new ConcurrentHashMap<>();
public PipelineBiomeLoader(Registry<Biome> biomeRegistry, BiomeTagIndex tagIndex) {
this.biomeRegistry = biomeRegistry;
this.tagIndex = tagIndex;
}
@Override
@@ -27,6 +33,6 @@ public class PipelineBiomeLoader implements TypeLoader<PipelineBiome> {
return biomeRegistry
.getByID((String) c)
.map(PipelineBiome::from)
.orElseGet(() -> PipelineBiome.placeholder((String) c));
.orElseGet(() -> placeholders.computeIfAbsent((String) c, id -> PipelineBiome.placeholder(id, tagIndex)));
}
}
@@ -17,15 +17,16 @@ import com.dfsek.terra.addons.biome.pipeline.config.stage.StageTemplate;
import com.dfsek.terra.addons.biome.pipeline.stage.mutators.BorderListStage;
import com.dfsek.terra.api.config.meta.Meta;
import com.dfsek.terra.api.util.collection.ProbabilityCollection;
import com.dfsek.terra.api.world.biome.tag.BiomeTag;
@SuppressWarnings("unused")
public class BorderListStageTemplate extends StageTemplate {
@Value("from")
private @Meta String from;
private @Meta BiomeTag from;
@Value("default-replace")
private @Meta String defaultReplace;
private @Meta BiomeTag defaultReplace;
@Value("default-to")
private @Meta ProbabilityCollection<@Meta PipelineBiome> defaultTo;
@@ -15,15 +15,16 @@ import com.dfsek.terra.addons.biome.pipeline.config.stage.StageTemplate;
import com.dfsek.terra.addons.biome.pipeline.stage.mutators.BorderStage;
import com.dfsek.terra.api.config.meta.Meta;
import com.dfsek.terra.api.util.collection.ProbabilityCollection;
import com.dfsek.terra.api.world.biome.tag.BiomeTag;
@SuppressWarnings("unused")
public class BorderStageTemplate extends StageTemplate {
@Value("from")
private @Meta String from;
private @Meta BiomeTag from;
@Value("replace")
private @Meta String replace;
private @Meta BiomeTag replace;
@Value("to")
private @Meta ProbabilityCollection<@Meta PipelineBiome> to;
@@ -17,12 +17,13 @@ import com.dfsek.terra.addons.biome.pipeline.config.stage.StageTemplate;
import com.dfsek.terra.addons.biome.pipeline.stage.mutators.ReplaceListStage;
import com.dfsek.terra.api.config.meta.Meta;
import com.dfsek.terra.api.util.collection.ProbabilityCollection;
import com.dfsek.terra.api.world.biome.tag.BiomeTag;
@SuppressWarnings("unused")
public class ReplaceListStageTemplate extends StageTemplate {
@Value("default-from")
private @Meta String defaultFrom;
private @Meta BiomeTag defaultFrom;
@Value("default-to")
private @Meta ProbabilityCollection<@Meta PipelineBiome> defaultTo;
@@ -15,12 +15,13 @@ import com.dfsek.terra.addons.biome.pipeline.config.stage.StageTemplate;
import com.dfsek.terra.addons.biome.pipeline.stage.mutators.ReplaceStage;
import com.dfsek.terra.api.config.meta.Meta;
import com.dfsek.terra.api.util.collection.ProbabilityCollection;
import com.dfsek.terra.api.world.biome.tag.BiomeTag;
@SuppressWarnings("unused")
public class ReplaceStageTemplate extends StageTemplate {
@Value("from")
private @Meta String from;
private @Meta BiomeTag from;
@Value("to")
private @Meta ProbabilityCollection<@Meta PipelineBiome> to;
@@ -21,24 +21,29 @@ import com.dfsek.terra.addons.biome.pipeline.api.Stage;
import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome;
import com.dfsek.terra.addons.biome.pipeline.pipeline.BiomeChunkImpl;
import com.dfsek.terra.api.util.collection.ProbabilityCollection;
import com.dfsek.terra.api.world.biome.tag.BiomeTag;
public class BorderListStage implements Stage {
private final String border;
private final BiomeTag border;
private final Sampler Sampler;
private final ProbabilityCollection<PipelineBiome> replaceDefault;
private final String defaultReplace;
private final BiomeTag defaultReplace;
private final Map<PipelineBiome, ProbabilityCollection<PipelineBiome>> replace;
// By PipelineBiome#getIntID(); relies on one ID per biome name.
private final ProbabilityCollection<PipelineBiome>[] replaceById;
private final Vector2Int[] borderPoints;
public BorderListStage(Map<PipelineBiome, ProbabilityCollection<PipelineBiome>> replace, String border, String defaultReplace,
public BorderListStage(Map<PipelineBiome, ProbabilityCollection<PipelineBiome>> replace, BiomeTag border,
BiomeTag defaultReplace,
Sampler Sampler, ProbabilityCollection<PipelineBiome> replaceDefault) {
this.border = border;
this.Sampler = Sampler;
this.replaceDefault = replaceDefault;
this.defaultReplace = defaultReplace;
this.replace = replace;
this.replaceById = ReplaceTable.byId(replace);
List<Vector2Int> points = new ArrayList<>();
for(int x = -1; x <= 1; x++) {
@@ -63,12 +68,14 @@ public class BorderListStage implements Stage {
@Override
public PipelineBiome apply(BiomeChunkImpl.ViewPoint viewPoint) {
PipelineBiome center = viewPoint.getBiome();
if(center.getTags().contains(defaultReplace)) {
int centerId = center.getIntID();
if(defaultReplace.has(centerId)) {
for(Vector2Int point : borderPoints) {
PipelineBiome current = viewPoint.getRelativeBiome(point.getX(), point.getZ());
if(current != null && current.getTags().contains(border)) {
if(replace.containsKey(center)) {
PipelineBiome replacement = replace.get(center).get(Sampler, viewPoint.worldX(), viewPoint.worldZ(),
if(current != null && border.has(current.getIntID())) {
ProbabilityCollection<PipelineBiome> collection = centerId < replaceById.length ? replaceById[centerId] : null;
if(collection != null) {
PipelineBiome replacement = collection.get(Sampler, viewPoint.worldX(), viewPoint.worldZ(),
viewPoint.worldSeed());
return replacement.isSelf() ? center : replacement;
}
@@ -20,16 +20,17 @@ import com.dfsek.terra.addons.biome.pipeline.api.Stage;
import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome;
import com.dfsek.terra.addons.biome.pipeline.pipeline.BiomeChunkImpl;
import com.dfsek.terra.api.util.collection.ProbabilityCollection;
import com.dfsek.terra.api.world.biome.tag.BiomeTag;
public class BorderStage implements Stage {
private final String border;
private final BiomeTag border;
private final Sampler Sampler;
private final ProbabilityCollection<PipelineBiome> replace;
private final String replaceTag;
private final BiomeTag replaceTag;
private final Vector2Int[] borderPoints;
public BorderStage(String border, String replaceTag, Sampler Sampler, ProbabilityCollection<PipelineBiome> replace) {
public BorderStage(BiomeTag border, BiomeTag replaceTag, Sampler Sampler, ProbabilityCollection<PipelineBiome> replace) {
this.border = border;
this.Sampler = Sampler;
this.replace = replace;
@@ -47,10 +48,10 @@ public class BorderStage implements Stage {
@Override
public PipelineBiome apply(BiomeChunkImpl.ViewPoint viewPoint) {
PipelineBiome center = viewPoint.getBiome();
if(center.getTags().contains(replaceTag)) {
if(replaceTag.has(center.getIntID())) {
for(Vector2Int point : borderPoints) {
PipelineBiome current = viewPoint.getRelativeBiome(point.getX(), point.getZ());
if(current != null && current.getTags().contains(border)) {
if(current != null && border.has(current.getIntID())) {
PipelineBiome replacement = replace.get(Sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed());
return replacement.isSelf() ? center : replacement;
}
@@ -18,17 +18,21 @@ import com.dfsek.terra.addons.biome.pipeline.api.Stage;
import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome;
import com.dfsek.terra.addons.biome.pipeline.pipeline.BiomeChunkImpl;
import com.dfsek.terra.api.util.collection.ProbabilityCollection;
import com.dfsek.terra.api.world.biome.tag.BiomeTag;
public class ReplaceListStage implements Stage {
private final Map<PipelineBiome, ProbabilityCollection<PipelineBiome>> replace;
// By PipelineBiome#getIntID(); relies on one ID per biome name.
private final ProbabilityCollection<PipelineBiome>[] replaceById;
private final Sampler sampler;
private final ProbabilityCollection<PipelineBiome> replaceDefault;
private final String defaultTag;
private final BiomeTag defaultTag;
public ReplaceListStage(Map<PipelineBiome, ProbabilityCollection<PipelineBiome>> replace, String defaultTag,
public ReplaceListStage(Map<PipelineBiome, ProbabilityCollection<PipelineBiome>> replace, BiomeTag defaultTag,
ProbabilityCollection<PipelineBiome> replaceDefault, Sampler sampler) {
this.replace = replace;
this.replaceById = ReplaceTable.byId(replace);
this.sampler = sampler;
this.defaultTag = defaultTag;
this.replaceDefault = replaceDefault;
@@ -37,11 +41,13 @@ public class ReplaceListStage implements Stage {
@Override
public PipelineBiome apply(BiomeChunkImpl.ViewPoint viewPoint) {
PipelineBiome center = viewPoint.getBiome();
if(replace.containsKey(center)) {
PipelineBiome biome = replace.get(center).get(sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed());
int id = center.getIntID();
ProbabilityCollection<PipelineBiome> collection = id < replaceById.length ? replaceById[id] : null;
if(collection != null) {
PipelineBiome biome = collection.get(sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed());
return biome.isSelf() ? viewPoint.getBiome() : biome;
}
if(viewPoint.getBiome().getTags().contains(defaultTag)) {
if(defaultTag.has(id)) {
PipelineBiome biome = replaceDefault.get(sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed());
return biome.isSelf() ? viewPoint.getBiome() : biome;
}
@@ -60,7 +66,7 @@ public class ReplaceListStage implements Stage {
Set<PipelineBiome> reject = new HashSet<>();
biomes.forEach(biome -> {
if(!biome.getTags().contains(defaultTag) && !replace.containsKey(biome)) {
if(!biome.getTags().contains(defaultTag.name()) && !replace.containsKey(biome)) {
biomeSet.add(biome);
} else {
reject.add(biome);
@@ -17,14 +17,15 @@ import com.dfsek.terra.addons.biome.pipeline.api.Stage;
import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome;
import com.dfsek.terra.addons.biome.pipeline.pipeline.BiomeChunkImpl;
import com.dfsek.terra.api.util.collection.ProbabilityCollection;
import com.dfsek.terra.api.world.biome.tag.BiomeTag;
public class ReplaceStage implements Stage {
private final String replaceableTag;
private final BiomeTag replaceableTag;
private final ProbabilityCollection<PipelineBiome> replace;
private final Sampler sampler;
public ReplaceStage(String replaceable, ProbabilityCollection<PipelineBiome> replace, Sampler sampler) {
public ReplaceStage(BiomeTag replaceable, ProbabilityCollection<PipelineBiome> replace, Sampler sampler) {
this.replaceableTag = replaceable;
this.replace = replace;
this.sampler = sampler;
@@ -32,7 +33,7 @@ public class ReplaceStage implements Stage {
@Override
public PipelineBiome apply(BiomeChunkImpl.ViewPoint viewPoint) {
if(viewPoint.getBiome().getTags().contains(replaceableTag)) {
if(replaceableTag.has(viewPoint.getBiome().getIntID())) {
PipelineBiome biome = replace.get(sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed());
return biome.isSelf() ? viewPoint.getBiome() : biome;
}
@@ -49,7 +50,7 @@ public class ReplaceStage implements Stage {
Set<PipelineBiome> biomeSet = new HashSet<>();
Set<PipelineBiome> reject = new HashSet<>();
biomes.forEach(biome -> {
if(!biome.getTags().contains(replaceableTag)) {
if(!biome.getTags().contains(replaceableTag.name())) {
biomeSet.add(biome);
} else {
reject.add(biome);
@@ -0,0 +1,27 @@
/*
* Copyright (c) 2020-2025 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addons.biome.pipeline.stage.mutators;
import java.util.Map;
import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome;
import com.dfsek.terra.api.util.collection.ProbabilityCollection;
final class ReplaceTable {
private ReplaceTable() { }
@SuppressWarnings("unchecked")
static ProbabilityCollection<PipelineBiome>[] byId(Map<PipelineBiome, ProbabilityCollection<PipelineBiome>> replace) {
int max = -1;
for(PipelineBiome key : replace.keySet()) max = Math.max(max, key.getIntID());
ProbabilityCollection<PipelineBiome>[] table = new ProbabilityCollection[max + 1];
replace.forEach((key, value) -> table[key.getIntID()] = value);
return table;
}
}
@@ -0,0 +1,420 @@
{
"id": "biome-provider-pipeline",
"docVersion": 1,
"description": "Pipeline biome provider, sampler source and six grid-processing stages. Pipeline stages are distinct from world generation stages.",
"types": {
"terra:BiomeProvider": {
"kind": "union",
"values": {
"PIPELINE": {
"kind": "object",
"fields": {
"resolution": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 1,
"summary": "Biome sample spacing in blocks. Higher values reduce work and detail; there is no template range validator."
},
"blend": {
"schema": {
"kind": "object",
"fields": {
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler",
"nullable": true
},
"required": false,
"summary": "Coordinate-warping sampler; defaults to an internal zero sampler."
},
"amplitude": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "float"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 0
}
},
"nullable": true
},
"required": false
},
"pipeline": {
"schema": {
"kind": "object",
"fields": {
"source": {
"schema": {
"kind": "type",
"target": "Source"
},
"required": true
},
"stages": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "Stage"
}
},
"required": true,
"summary": "Ordered stages; required even when the list is empty."
}
}
},
"required": true
}
}
}
}
},
"Source": {
"kind": "union",
"discriminator": "type",
"values": {
"SAMPLER": {
"kind": "object",
"fields": {
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler"
},
"required": true
},
"biomes": {
"schema": {
"kind": "type",
"target": "WeightedPipelineBiomes"
},
"required": true
}
}
}
}
},
"Stage": {
"kind": "union",
"discriminator": "type",
"values": {
"FRACTAL_EXPAND": {
"kind": "object",
"fields": {
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler"
},
"required": true,
"summary": "Sampler used to choose among replacements or neighboring biomes."
}
},
"description": "Expands the biome grid using fractal interpolation."
},
"SMOOTH": {
"kind": "object",
"fields": {
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler"
},
"required": true,
"summary": "Sampler used to choose among replacements or neighboring biomes."
}
},
"description": "Smooths the biome grid using neighboring biomes."
},
"REPLACE": {
"kind": "object",
"fields": {
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler"
},
"required": true,
"summary": "Sampler used to choose among replacements or neighboring biomes."
},
"from": {
"schema": {
"kind": "type",
"target": "terra:Tag"
},
"required": true,
"summary": "Tag identifying biomes to replace."
},
"to": {
"schema": {
"kind": "type",
"target": "WeightedPipelineBiomes"
},
"required": true,
"summary": "Replacement biomes; SELF preserves the current biome."
}
}
},
"REPLACE_LIST": {
"kind": "object",
"fields": {
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler"
},
"required": true,
"summary": "Sampler used to choose among replacements or neighboring biomes."
},
"default-from": {
"schema": {
"kind": "type",
"target": "terra:Tag"
},
"required": true,
"summary": "Tag to match when the current biome is not a key in to."
},
"default-to": {
"schema": {
"kind": "type",
"target": "WeightedPipelineBiomes"
},
"required": true,
"summary": "Replacement distribution for default-from."
},
"to": {
"schema": {
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "PipelineBiome"
},
"values": {
"kind": "type",
"target": "WeightedPipelineBiomes"
}
},
"required": true,
"summary": "Explicit per-biome replacements, checked before the default tag."
}
}
},
"BORDER": {
"kind": "object",
"fields": {
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler"
},
"required": true,
"summary": "Sampler used to choose among replacements or neighboring biomes."
},
"from": {
"schema": {
"kind": "type",
"target": "terra:Tag"
},
"required": true,
"summary": "Tag to look for among the eight neighboring cells."
},
"replace": {
"schema": {
"kind": "type",
"target": "terra:Tag"
},
"required": true,
"summary": "Tag that the center biome must have."
},
"to": {
"schema": {
"kind": "type",
"target": "WeightedPipelineBiomes"
},
"required": true,
"summary": "Replacement biomes when the center and a neighbor match."
}
}
},
"BORDER_LIST": {
"kind": "object",
"fields": {
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler"
},
"required": true,
"summary": "Sampler used to choose among replacements or neighboring biomes."
},
"from": {
"schema": {
"kind": "type",
"target": "terra:Tag"
},
"required": true,
"summary": "Tag to look for among the eight neighboring cells."
},
"default-replace": {
"schema": {
"kind": "type",
"target": "terra:Tag"
},
"required": true,
"summary": "Required tag for the center biome, including explicit map entries."
},
"default-to": {
"schema": {
"kind": "type",
"target": "WeightedPipelineBiomes"
},
"required": true,
"summary": "Replacement when the center has no entry in replace."
},
"replace": {
"schema": {
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "PipelineBiome"
},
"values": {
"kind": "type",
"target": "WeightedPipelineBiomes"
}
},
"required": true,
"summary": "Explicit center-biome replacements after tag and neighbor checks."
}
}
}
}
},
"PipelineBiome": {
"kind": "oneOf",
"description": "Pipeline biome loader input: a registered biome identifier, SELF, or an unregistered placeholder string. Placeholders must be removed before producing final biomes.",
"options": [
{
"kind": "ref",
"target": "terra:Biome"
},
{
"kind": "literal",
"value": "SELF",
"description": "Keep the current biome when used as a stage replacement."
},
{
"kind": "string",
"description": "An identifier not found in the biome registry becomes a placeholder with tags ALL and its own identifier."
}
],
"examples": [
"PLAINS",
"SELF",
"PLACEHOLDER"
]
},
"WeightedPipelineBiomes": {
"kind": "oneOf",
"description": "A pipeline biome, a pipeline-biome-to-integer-weight map, or a list of such maps. Singleton weights are ignored. Other weights are raw integers.",
"options": [
{
"kind": "type",
"target": "PipelineBiome"
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "PipelineBiome"
},
"values": {
"kind": "any",
"name": "Ignored singleton weight"
},
"maxEntries": 1
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "PipelineBiome"
},
"values": {
"kind": "integer"
},
"minEntries": 2
},
{
"kind": "list",
"element": {
"kind": "oneOf",
"options": [
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "PipelineBiome"
},
"values": {
"kind": "any",
"name": "Ignored singleton weight"
},
"maxEntries": 1
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "PipelineBiome"
},
"values": {
"kind": "integer"
},
"minEntries": 2
}
]
},
"maxItems": 1
},
{
"kind": "list",
"element": {
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "PipelineBiome"
},
"values": {
"kind": "integer"
}
},
"minItems": 2
}
]
}
}
}
@@ -0,0 +1,190 @@
package pipeline;
import com.dfsek.seismic.type.sampler.Sampler;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import com.dfsek.terra.addons.biome.pipeline.api.Source;
import com.dfsek.terra.addons.biome.pipeline.api.Stage;
import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome;
import com.dfsek.terra.addons.biome.pipeline.config.PipelineBiomeLoader;
import com.dfsek.terra.addons.biome.pipeline.pipeline.PipelineImpl;
import com.dfsek.terra.addons.biome.pipeline.stage.mutators.BorderListStage;
import com.dfsek.terra.addons.biome.pipeline.stage.mutators.ReplaceListStage;
import com.dfsek.terra.addons.biome.pipeline.stage.mutators.ReplaceStage;
import com.dfsek.terra.api.properties.Context;
import com.dfsek.terra.api.registry.Registry;
import com.dfsek.terra.api.util.cache.SeededVector2Key;
import com.dfsek.terra.api.util.collection.ProbabilityCollection;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.api.world.biome.PlatformBiome;
import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex;
import static org.junit.jupiter.api.Assertions.*;
class PipelineBiomeTagTest {
private static final Sampler SAMPLER = new Sampler() {
@Override
public double getSample(long seed, double x, double y) {
return 0;
}
@Override
public double getSample(long seed, double x, double y, double z) {
return 0;
}
};
private static final class StubBiome implements Biome {
private final String id;
private final Set<String> tags;
private final int intId;
StubBiome(BiomeTagIndex index, String id, Set<String> tags) {
this.id = id;
this.tags = tags;
this.intId = index.register(tags);
}
@Override
public PlatformBiome getPlatformBiome() {
return null;
}
@Override
public int getColor() {
return 0;
}
@Override
public Set<String> getTags() {
return tags;
}
@Override
public int getIntID() {
return intId;
}
@Override
public Context getContext() {
return null;
}
@Override
public String getID() {
return id;
}
}
@SuppressWarnings("unchecked")
private static Registry<Biome> emptyRegistry() {
return (Registry<Biome>) Proxy.newProxyInstance(Registry.class.getClassLoader(), new Class<?>[]{ Registry.class },
(proxy, method, args) -> {
if(method.getName().equals("getByID")) return Optional.empty();
throw new UnsupportedOperationException(method.getName());
});
}
private final BiomeTagIndex index = new BiomeTagIndex();
private final Map<String, PipelineBiome> biomes = new LinkedHashMap<>();
{
biome("border", "border");
biome("c", "R", "D");
biome("a", "R");
biome("b", "R");
biome("x");
biome("y");
biome("e");
biome("f", "R", "D");
}
private void biome(String id, String... tags) {
biomes.put(id, PipelineBiome.from(new StubBiome(index, id, Set.of(tags))));
}
private static ProbabilityCollection<PipelineBiome> only(PipelineBiome biome) {
return new ProbabilityCollection<PipelineBiome>().add(biome, 1);
}
private Map<PipelineBiome, ProbabilityCollection<PipelineBiome>> replaceTable() {
Map<PipelineBiome, ProbabilityCollection<PipelineBiome>> replace = new HashMap<>();
replace.put(biomes.get("a"), only(biomes.get("x")));
replace.put(biomes.get("b"), only(PipelineBiome.self()));
return replace;
}
private String run(Stage stage, String centre) {
index.seal();
PipelineBiome centreBiome = biomes.get(centre);
PipelineBiome border = biomes.get("border");
Source source = new Source() {
@Override
public PipelineBiome get(long seed, int x, int z) {
return x == 0 && z == 0 ? centreBiome : border;
}
@Override
public Iterable<PipelineBiome> getBiomes() {
return List.of(centreBiome, border);
}
};
return new PipelineImpl(source, List.of(stage), 1, 3).generateChunk(new SeededVector2Key(0, 0, 0)).get(0, 0).getID();
}
@ParameterizedTest(name = "{0} -> {1}")
@CsvSource({ "a, x", "b, b", "c, y", "e, e", "f, y" })
void borderListStage(String centre, String expected) {
assertEquals(expected, run(new BorderListStage(replaceTable(), index.tag("border"), index.tag("R"), SAMPLER,
only(biomes.get("y"))), centre));
}
@ParameterizedTest(name = "{0} -> {1}")
@CsvSource({ "a, x", "b, b", "c, y", "e, e", "f, y" })
void replaceListStage(String centre, String expected) {
assertEquals(expected, run(new ReplaceListStage(replaceTable(), index.tag("D"), only(biomes.get("y")), SAMPLER), centre));
}
@ParameterizedTest(name = "{0}: {1} -> {2}")
@CsvSource({ "D, c, y", "D, e, e", "TYPO, c, c", "TYPO, e, e" })
void replaceStage(String tag, String centre, String expected) {
assertEquals(expected, run(new ReplaceStage(index.tag(tag), only(biomes.get("y")), SAMPLER), centre));
}
@Test
void placeholderRegistration() {
PipelineBiomeLoader loader = new PipelineBiomeLoader(emptyRegistry(), index);
int before = index.size();
PipelineBiome first = load(loader, "OCEAN");
assertSame(first, load(loader, "OCEAN"));
assertEquals(before + 1, index.size());
assertDoesNotThrow(() -> load(loader, "ALL"));
index.seal();
assertTrue(index.tag("OCEAN").has(first.getIntID()));
assertTrue(index.tag("ALL").has(first.getIntID()));
assertFalse(index.tag("OTHER").has(first.getIntID()));
}
@Test
void selfHasNoTags() {
assertEquals(0, PipelineBiome.self().getIntID());
index.seal();
assertFalse(index.tag("ALL").has(PipelineBiome.self().getIntID()));
}
private static PipelineBiome load(PipelineBiomeLoader loader, String id) {
return loader.load((AnnotatedType) null, id, null, null);
}
}
@@ -0,0 +1,25 @@
{
"id": "biome-provider-single",
"docVersion": 1,
"description": "A biome provider that returns one registered biome everywhere.",
"types": {
"terra:BiomeProvider": {
"kind": "union",
"values": {
"SINGLE": {
"kind": "object",
"fields": {
"biome": {
"schema": {
"kind": "ref",
"target": "terra:Biome"
},
"required": true,
"summary": "Registered Terra biome to use everywhere."
}
}
}
}
}
}
}
-4
View File
@@ -1,4 +0,0 @@
# Biome Query API
This addon contains an API to allow other addons to quickly query
Biome data, by baking queries and using Contexts on biomes.
@@ -1,5 +0,0 @@
version = version("1.0.0")
dependencies {
compileOnlyApi(project(":common:addons:manifest-addon-loader"))
}
@@ -1,46 +0,0 @@
package com.dfsek.terra.addons.biome.query;
import java.util.Collection;
import com.dfsek.terra.addons.biome.query.impl.BiomeTagFlattener;
import com.dfsek.terra.addons.biome.query.impl.BiomeTagHolder;
import com.dfsek.terra.addons.manifest.api.AddonInitializer;
import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPostLoadEvent;
import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
import com.dfsek.terra.api.inject.annotations.Inject;
import com.dfsek.terra.api.properties.Context;
import com.dfsek.terra.api.properties.PropertyKey;
import com.dfsek.terra.api.world.biome.Biome;
public class BiomeQueryAPIAddon implements AddonInitializer {
public static PropertyKey<BiomeTagHolder> BIOME_TAG_KEY = Context.create(BiomeTagHolder.class);
@Inject
private Platform platform;
@Inject
private BaseAddon addon;
@Override
public void initialize() {
platform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(addon, ConfigPackPostLoadEvent.class)
.then(event -> {
Collection<Biome> biomes = event
.getPack()
.getRegistry(Biome.class)
.entries();
BiomeTagFlattener flattener = new BiomeTagFlattener(biomes
.stream()
.flatMap(biome -> biome.getTags().stream())
.toList());
biomes.forEach(biome -> biome.getContext().put(BIOME_TAG_KEY, new BiomeTagHolder(biome, flattener)));
})
.global();
}
}
@@ -1,17 +0,0 @@
package com.dfsek.terra.addons.biome.query.api;
import java.util.function.Predicate;
import com.dfsek.terra.addons.biome.query.impl.SingleTagQuery;
import com.dfsek.terra.api.world.biome.Biome;
public final class BiomeQueries {
private BiomeQueries() {
}
public static Predicate<Biome> has(String tag) {
return new SingleTagQuery(tag);
}
}
@@ -1,20 +0,0 @@
package com.dfsek.terra.addons.biome.query.impl;
import java.util.List;
public class BiomeTagFlattener {
private final List<String> tags;
public BiomeTagFlattener(List<String> tags) {
this.tags = tags;
}
public int index(String tag) {
return tags.indexOf(tag);
}
public int size() {
return tags.size();
}
}
@@ -1,26 +0,0 @@
package com.dfsek.terra.addons.biome.query.impl;
import com.dfsek.terra.api.properties.Properties;
import com.dfsek.terra.api.world.biome.Biome;
public class BiomeTagHolder implements Properties {
private final boolean[] tags;
private final BiomeTagFlattener flattener;
public BiomeTagHolder(Biome biome, BiomeTagFlattener flattener) {
this.tags = new boolean[flattener.size()];
this.flattener = flattener;
for(String tag : biome.getTags()) {
tags[flattener.index(tag)] = true;
}
}
boolean get(int index) {
return tags[index];
}
public BiomeTagFlattener getFlattener() {
return flattener;
}
}
@@ -1,31 +0,0 @@
package com.dfsek.terra.addons.biome.query.impl;
import java.util.function.Predicate;
import com.dfsek.terra.addons.biome.query.BiomeQueryAPIAddon;
import com.dfsek.terra.api.world.biome.Biome;
public class SingleTagQuery implements Predicate<Biome> {
private final String tag;
private int tagIndex = -1;
public SingleTagQuery(String tag) {
this.tag = tag;
}
@Override
public boolean test(Biome biome) {
if(tagIndex < 0) {
tagIndex = biome
.getContext()
.get(BiomeQueryAPIAddon.BIOME_TAG_KEY)
.getFlattener()
.index(tag);
}
return biome
.getContext()
.get(BiomeQueryAPIAddon.BIOME_TAG_KEY)
.get(tagIndex);
}
}
@@ -0,0 +1,388 @@
{
"id": "chunk-generator-noise-3d",
"docVersion": 1,
"description": "Registers NOISE_3D and contributes pack options and biome terrain, carving and palette fields whenever this addon loads. Existing core metadata documents blend.terrain.elevation (default 4).",
"types": {
"terra:PaletteReference": {
"kind": "oneOf",
"options": [
{
"kind": "ref",
"target": "terra:Palette"
}
]
},
"HeightPalettes": {
"kind": "list",
"element": {
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:PaletteReference"
},
"values": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
]
}
},
"description": "Palette references mapped to inclusive upper Y boundaries, in a sequence of maps. Duplicate heights replace earlier entries. At least one entry is needed, and the highest boundary must cover the builder's range through Y=255. Boundary values may be numeric expressions.",
"minItems": 1
},
"SlantLayer": {
"kind": "object",
"fields": {
"threshold": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "float"
},
{
"kind": "type",
"target": "terra:Expression"
}
]
},
"required": true,
"summary": "Slant threshold. Derivative uses the floor threshold; DotProduct uses the ceiling threshold. Multiple slant layers must use distinct thresholds."
},
"palette": {
"schema": {
"kind": "type",
"target": "HeightPalettes"
},
"required": true
}
}
},
"terra:Biome": {
"kind": "object",
"fields": {
"terrain": {
"schema": {
"kind": "object",
"fields": {
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler"
},
"required": true,
"summary": "Required terrain-density sampler."
},
"sampler-2d": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler",
"nullable": true
},
"required": false,
"summary": "Elevation sampler; defaults to an internal zero sampler."
},
"blend": {
"schema": {
"kind": "object",
"fields": {
"distance": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 3,
"summary": "Blend radius in sample steps."
},
"weight": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "float"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 1
},
"step": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 4,
"summary": "Distance between blend samples."
},
"weight-2d": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "float"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 1
}
},
"nullable": true
},
"required": false
}
}
},
"required": true
},
"carving": {
"schema": {
"kind": "object",
"fields": {
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler",
"nullable": true
},
"required": false,
"summary": "Carving sampler; defaults to an internal zero sampler."
},
"update-palette": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false,
"summary": "Update palette depth when carving removes blocks."
}
},
"nullable": true
},
"required": false
},
"palette": {
"schema": {
"kind": "type",
"target": "HeightPalettes"
},
"required": true,
"summary": "Height-indexed terrain palettes."
},
"slant": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "SlantLayer"
},
"nullable": true
},
"required": false,
"default": [],
"summary": "Optional palettes selected by terrain slant."
},
"slant-depth": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 2147483647,
"summary": "Maximum depth at which to apply a slant palette."
},
"ocean": {
"schema": {
"kind": "object",
"fields": {
"level": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 0,
"summary": "Sea level."
},
"palette": {
"schema": {
"kind": "type",
"target": "terra:PaletteReference",
"nullable": true
},
"required": false,
"summary": "Defaults to an internal palette returning platform air."
}
},
"nullable": true
},
"required": false
}
}
},
"Noise3DGenerator": {
"kind": "literal",
"value": "NOISE_3D",
"description": "Registered chunk generator provider identifier. generator in pack.yml is a scalar identifier, not an inline object."
},
"terra:ChunkGenerator": {
"kind": "string",
"description": "This addon registers the NOISE_3D chunk generator provider identifier.",
"examples": [
"NOISE_3D"
]
}
},
"files": {
"pack.yml": {
"kind": "object",
"fields": {
"carving": {
"schema": {
"kind": "object",
"fields": {
"resolution": {
"schema": {
"kind": "object",
"fields": {
"horizontal": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 4
},
"vertical": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 2
}
},
"nullable": true
},
"required": false
}
},
"nullable": true
},
"required": false
},
"slant": {
"schema": {
"kind": "object",
"fields": {
"calculation-method": {
"schema": {
"kind": "enum",
"values": [
"DotProduct",
"Derivative"
],
"nullable": true
},
"required": false,
"default": "Derivative",
"summary": "Slant calculation method; spelling is case-sensitive."
},
"disable-palettes": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false,
"summary": "Disable use of slant palettes; the biome slant fields are still loaded."
}
},
"nullable": true
},
"required": false
}
}
},
"BIOME": {
"kind": "object",
"fields": {},
"extends": [
"terra:Biome"
]
}
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-2025 Polyhedral Development
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,10 @@
version = version("1.0.0")
dependencies {
compileOnlyApi(project(":common:addons:manifest-addon-loader"))
testImplementation(project(":common:implementation:base"))
testImplementation(project(":common:addons:minecraft-attributes"))
testImplementation(project(":common:addons:manifest-addon-loader"))
testImplementation("com.dfsek", "paralithic", Versions.Libraries.paralithic)
}
@@ -0,0 +1,194 @@
package com.dfsek.terra.addons.attribute;
import org.slf4j.Logger;
import org.slf4j.helpers.MessageFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import com.dfsek.terra.addons.attribute.AttributeReader.Problem;
import com.dfsek.terra.addons.attribute.AttributeReader.Result;
import com.dfsek.terra.addons.attribute.AttributeReader.Scope;
import com.dfsek.terra.addons.manifest.api.AddonInitializer;
import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.event.events.config.ConfigurationLoadEvent;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPostLoadEvent;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
import com.dfsek.terra.api.inject.annotations.Inject;
import com.dfsek.terra.api.properties.Context;
import com.dfsek.terra.api.properties.PropertyKey;
import com.dfsek.terra.api.registry.Registry;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeMap;
import com.dfsek.terra.api.world.attribute.DecodeContext;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.api.world.attribute.PackAttributes;
import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule;
import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult;
import com.dfsek.terra.api.world.biome.Biome;
/**
* Biome configs load in parallel: the biome handler may only read shared immutable state and write to its own biome.
*/
public class AttributeAddon implements AddonInitializer {
private static final String ATTRIBUTE_WARNING = "Pack \"{}\", config \"{}\": attribute \"{}\" skipped: {}";
private static final String SCHEDULE_SKIPPED = "Pack \"{}\": schedule \"{}\" skipped: {}";
private static final String TRACK_DROPPED = "Pack \"{}\": schedule \"{}\" track \"{}\" dropped: {}";
private static final String PARENT_WARNING = "Pack \"{}\", config \"{}\": \"{}\" ignored: {}";
private static final String PACK_CONFIG = "pack.yml";
private static final String VANILLA = "vanilla";
private static final String VANILLA_GENERATION = "vanilla-generation";
@Inject
private Platform platform;
@Inject
private BaseAddon addon;
@Inject
private Logger logger;
@Override
public void initialize() {
AttributeHandle handle = platform.getAttributeHandle();
// Before any parallel load: Context.create is not thread safe.
PropertyKey<BiomeAttributeEntries> biomeKey = Context.create(BiomeAttributeEntries.class);
PropertyKey<PackAttributes> packKey = Context.create(PackAttributes.class);
platform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(addon, ConfigPackPreLoadEvent.class)
.then(event -> {
for(Class<?> type : ConfigDecodeContext.CAPTURED_TYPES) event.getPack().applyLoader(type, LazyConfigValue.LOADER);
})
.failThrough();
platform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(addon, ConfigurationLoadEvent.class)
.then(event -> {
if(!event.is(Biome.class)) return;
Map<String, LazyConfigValue> raw = event.load(new BiomeAttributesTemplate()).getAttributes();
AttributeReader reader = new AttributeReader(event.getPack().getRegistry(Attribute.REGISTRY_TYPE), handle);
Result result = reader.readConfig(raw, Scope.BIOME);
List<String> warnings = new ArrayList<>();
for(Problem problem : result.problems()) {
warnings.add(warn(ATTRIBUTE_WARNING, event.getPack(), event.getConfiguration().getID(), problem.key(),
problem.reason()));
}
event.getLoadedObject(Biome.class).getContext().put(biomeKey, new BiomeAttributeEntries(result.map(), warnings));
})
.failThrough();
platform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(addon, ConfigPackPostLoadEvent.class)
.then(event -> {
ConfigPack pack = event.getPack();
Registry<Attribute<?>> attributes = pack.getRegistry(Attribute.REGISTRY_TYPE);
PackAttributesTemplate template = event.loadTemplate(new PackAttributesTemplate());
List<String> warnings = new ArrayList<>();
Result result = new AttributeReader(attributes, handle).readConfig(template.getAttributes(), Scope.PACK);
for(Problem problem : result.problems()) {
warnings.add(warn(ATTRIBUTE_WARNING, pack, PACK_CONFIG, problem.key(), problem.reason()));
}
Map<String, RegistryKey> parents = new LinkedHashMap<>();
parent(parents, VANILLA, template.getVanilla(), pack, warnings);
parent(parents, VANILLA_GENERATION, template.getVanillaGeneration(), pack, warnings);
List<Either<RegistryKey, TagKey>> schedules = new ArrayList<>();
for(String schedule : template.getSchedules()) {
try {
schedules.add(ScheduleIds.reference(schedule));
} catch(IllegalArgumentException e) {
warnings.add(warn(SCHEDULE_SKIPPED, pack, schedule, e.getMessage()));
}
}
Map<RegistryKey, AttributeSchedule> definitions = new LinkedHashMap<>();
Set<RegistryKey> claimed = new HashSet<>();
RegistryAttributeLookup lookup = new RegistryAttributeLookup(attributes);
template.getScheduleDefinitions().forEach((idString, lazy) -> {
RegistryKey id;
try {
id = ScheduleIds.claim(idString, claimed);
} catch(IllegalArgumentException e) {
warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, e.getMessage()));
return;
}
DecodeContext context;
Object value;
try {
context = lazy == null ? handle.plainContext() : lazy.context(handle.plainContext());
value = lazy == null ? null : context.resolve(lazy.raw());
} catch(DecodeException e) {
warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, e.getMessage()));
return;
}
if(!(value instanceof Map<?, ?> map) || !map.keySet().stream().allMatch(String.class::isInstance)) {
warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, "a schedule must be a map"));
return;
}
@SuppressWarnings("unchecked")
Map<String, Object> raw = (Map<String, Object>) map;
ScheduleDecodeResult schedule = handle.decodeSchedule(id, raw, lookup, context);
for(ScheduleDecodeResult.Problem problem : schedule.droppedTracks()) {
warnings.add(warn(TRACK_DROPPED, pack, idString, problem.key(), problem.reason()));
}
schedule.skipped().ifPresent(problem -> warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, problem.reason())));
schedule.schedule().ifPresent(definition -> definitions.put(id, definition));
});
pack.getContext().put(packKey, new PackAttributesImpl(handle, platform.getAttributeParents(), attributes,
result.map(),
parents,
schedules,
definitions,
biomeEntries(pack, biomeKey),
warnings));
})
.failThrough();
}
private static AttributeMap[] biomeEntries(ConfigPack pack, PropertyKey<BiomeAttributeEntries> biomeKey) {
Registry<Biome> biomes = pack.getRegistry(Biome.class);
if(biomes == null) return new AttributeMap[0];
AttributeMap[] entries = new AttributeMap[pack.getBiomeTagIndex().size()];
biomes.forEach(biome -> {
if(biome.getContext().has(biomeKey)) entries[biome.getIntID()] = biome.getContext().get(biomeKey).entries();
});
return entries;
}
private void parent(Map<String, RegistryKey> parents, String key, Optional<String> value, ConfigPack pack, List<String> warnings) {
if(value.isEmpty()) return;
try {
parents.put(key, RegistryKey.parseNamespaced(value.get()));
} catch(IllegalArgumentException e) {
warnings.add(warn(PARENT_WARNING, pack, PACK_CONFIG, key, e.getMessage()));
}
}
private String warn(String format, ConfigPack pack, Object... args) {
Object[] all = new Object[args.length + 1];
all[0] = pack.getID();
System.arraycopy(args, 0, all, 1, args.length);
logger.warn(format, all);
return MessageFormatter.arrayFormat(format, all).getMessage();
}
}
@@ -0,0 +1,86 @@
package com.dfsek.terra.addons.attribute;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.api.registry.Registry;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeMap;
import com.dfsek.terra.api.world.attribute.AttributeScope;
import com.dfsek.terra.api.world.attribute.DecodeContext;
import com.dfsek.terra.api.world.attribute.DecodeException;
public final class AttributeReader {
private final RegistryAttributeLookup lookup;
private final AttributeHandle handle;
public AttributeReader(@Nullable Registry<Attribute<?>> registry, AttributeHandle handle) {
this.lookup = new RegistryAttributeLookup(registry);
this.handle = handle;
}
public enum Scope { BIOME, PACK }
public record Result(AttributeMap map, List<Problem> problems) { }
public record Problem(String key, String reason) { }
private record Value(Object raw, DecodeContext context) { }
public Result read(Map<String, Object> raw, Scope scope) {
DecodeContext plain = handle.plainContext();
Map<String, Value> values = new LinkedHashMap<>();
raw.forEach((key, value) -> values.put(key, new Value(value, plain)));
return readValues(values, scope);
}
Result readConfig(Map<String, LazyConfigValue> config, Scope scope) {
DecodeContext plain = handle.plainContext();
Map<String, Value> values = new LinkedHashMap<>();
config.forEach((key, value) -> values.put(key, value == null
? new Value(null, plain)
: new Value(value.raw(), value.context(plain))));
return readValues(values, scope);
}
private Result readValues(Map<String, Value> raw, Scope scope) {
AttributeMap.Builder builder = AttributeMap.builder();
List<Problem> problems = new ArrayList<>();
for(Map.Entry<String, Value> entry : raw.entrySet()) {
String keyString = entry.getKey();
Attribute<?> attribute;
try {
attribute = lookup.find(keyString);
} catch(DecodeException e) {
problems.add(new Problem(keyString, e.getMessage()));
continue;
}
if(scope == Scope.BIOME && attribute.scope() == AttributeScope.PACK_ONLY) {
problems.add(new Problem(keyString, "not allowed in a biome"));
continue;
}
// Explicit null un-sets an inherited value.
if(entry.getValue().raw() == null) continue;
try {
put(builder, attribute, entry.getValue().raw(), entry.getValue().context());
} catch(DecodeException | RuntimeException e) {
problems.add(new Problem(keyString, e.getMessage() == null ? "unexpected error" : e.getMessage()));
}
}
return new Result(builder.build(), problems);
}
private <T> void put(AttributeMap.Builder builder, Attribute<T> attribute, Object value, DecodeContext context)
throws DecodeException {
builder.put(attribute.key(), handle.decodeEntry(attribute, value, context));
}
}
@@ -0,0 +1,13 @@
package com.dfsek.terra.addons.attribute;
import java.util.List;
import com.dfsek.terra.api.properties.Properties;
import com.dfsek.terra.api.world.attribute.AttributeMap;
record BiomeAttributeEntries(AttributeMap entries, List<String> warnings) implements Properties {
BiomeAttributeEntries {
warnings = List.copyOf(warnings);
}
}
@@ -0,0 +1,23 @@
package com.dfsek.terra.addons.attribute;
import com.dfsek.tectonic.api.config.template.ConfigTemplate;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Merge;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import java.util.Collections;
import java.util.Map;
import com.dfsek.terra.api.config.meta.Meta;
public class BiomeAttributesTemplate implements ConfigTemplate {
@Value("attributes")
@Merge
@Default
private @Meta Map<@Meta String, LazyConfigValue> attributes = Map.of();
Map<String, LazyConfigValue> getAttributes() {
return Collections.unmodifiableMap(attributes);
}
}
@@ -0,0 +1,135 @@
package com.dfsek.terra.addons.attribute;
import com.dfsek.tectonic.api.depth.DepthTracker;
import com.dfsek.tectonic.api.exception.ConfigException;
import com.dfsek.tectonic.api.exception.LoadException;
import com.dfsek.tectonic.api.loader.ConfigLoader;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Type;
import java.util.AbstractList;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.dfsek.terra.api.config.meta.Meta;
import com.dfsek.terra.api.util.reflection.TypeKey;
import com.dfsek.terra.api.world.attribute.DecodeContext;
import com.dfsek.terra.api.world.attribute.DecodeException;
/**
* Tectonic picks preprocessors by declared type.
* <p>
* Not thread safe: include preprocessors mutate the {@link DepthTracker}.
*/
final class ConfigDecodeContext implements DecodeContext {
static final List<Class<?>> CAPTURED_TYPES = List.of(LazyConfigValue.class, MapShape.class, ListShape.class);
private static final AnnotatedType WHOLE_VALUE = new TypeKey<@Meta LazyConfigValue>() { }.getAnnotatedType();
private static final AnnotatedType MAP = new TypeKey<@Meta MapShape<String, LazyConfigValue>>() { }.getAnnotatedType();
private static final AnnotatedType LIST = new TypeKey<@Meta ListShape<LazyConfigValue>>() { }.getAnnotatedType();
private static final AnnotatedType STRING = new TypeKey<@Meta String>() { }.getAnnotatedType();
private static final AnnotatedType NUMBER = new TypeKey<@Meta Double>() { }.getAnnotatedType();
private final ConfigLoader loader;
private final DepthTracker tracker;
private final DecodeContext plain;
private final Set<Object> resolved = Collections.newSetFromMap(new IdentityHashMap<>());
ConfigDecodeContext(ConfigLoader loader, DepthTracker tracker, DecodeContext plain) {
this.loader = loader;
this.tracker = tracker;
this.plain = plain;
}
private static boolean numeric(Type type) {
return type instanceof Class<?> c && Number.class.isAssignableFrom(c);
}
private static DecodeException failure(RuntimeException e) {
String message = e instanceof ConfigException && e.getMessage() != null ? e.getMessage().strip() : "config preprocessing failed";
// Tectonic leaves some details only in the cause.
Throwable cause = e.getCause();
boolean readable = cause instanceof ConfigException
|| cause != null && !(cause instanceof RuntimeException || cause instanceof Error);
if(readable && cause.getMessage() != null && !message.contains(cause.getMessage().strip())) {
message += "\n\tCaused by: " + cause.getMessage().strip();
}
return new DecodeException(message, e);
}
@Override
public <V> V load(Type type, Object raw) throws DecodeException {
Object value = resolve(raw);
if(value instanceof String expression && numeric(type)) {
try {
value = loadType(NUMBER, expression, tracker);
} catch(RuntimeException e) {
throw failure(e);
}
}
return plain.load(type, value);
}
@Override
public Object resolve(Object raw) throws DecodeException {
try {
return resolve(raw, tracker);
} catch(RuntimeException e) {
throw failure(e);
}
}
private Object resolve(Object raw, DepthTracker at) {
if(raw == null || raw instanceof Number || raw instanceof Boolean || resolved.contains(raw)) return raw;
LazyConfigValue whole = capture(WHOLE_VALUE, raw, at);
Object value = whole.raw();
Object out;
if(value instanceof String) {
out = loadType(STRING, raw, at);
} else if(value instanceof Map<?, ?>) {
LazyConfigValue included = capture(MAP, value, whole.tracker());
Map<Object, Object> map = new LinkedHashMap<>();
for(Map.Entry<?, ?> entry : ((Map<?, ?>) included.raw()).entrySet()) {
map.put(entry.getKey(), resolve(entry.getValue(), included.tracker().entry(String.valueOf(entry.getKey()))));
}
out = Collections.unmodifiableMap(map);
} else if(value instanceof List<?>) {
LazyConfigValue included = capture(LIST, value, whole.tracker());
List<?> elements = (List<?>) included.raw();
List<Object> list = new ArrayList<>(elements.size());
for(int i = 0; i < elements.size(); i++) list.add(resolve(elements.get(i), included.tracker().index(i)));
out = Collections.unmodifiableList(list);
} else {
out = value;
}
if(out != null) resolved.add(out);
return out;
}
private LazyConfigValue capture(AnnotatedType type, Object raw, DepthTracker at) {
return (LazyConfigValue) loadType(type, raw, at);
}
private Object loadType(AnnotatedType type, Object raw, DepthTracker at) {
try {
return loader.loadType(type, raw, at);
} catch(ConfigException e) {
throw e;
} catch(RuntimeException e) {
throw new LoadException("config preprocessing failed", e, at);
}
}
private abstract static class MapShape<K, V> extends AbstractMap<K, V> { }
private abstract static class ListShape<E> extends AbstractList<E> { }
}
@@ -0,0 +1,19 @@
package com.dfsek.terra.addons.attribute;
import com.dfsek.tectonic.api.depth.DepthTracker;
import com.dfsek.tectonic.api.loader.ConfigLoader;
import com.dfsek.tectonic.api.loader.type.TypeLoader;
import com.dfsek.terra.api.world.attribute.DecodeContext;
/**
* Use only on the thread that loaded it: the {@link DepthTracker} is mutable.
*/
record LazyConfigValue(Object raw, ConfigLoader loader, DepthTracker tracker) {
static final TypeLoader<LazyConfigValue> LOADER = (type, o, loader, depthTracker) -> new LazyConfigValue(o, loader, depthTracker);
DecodeContext context(DecodeContext plain) {
return new ConfigDecodeContext(loader, tracker, plain);
}
}
@@ -0,0 +1,133 @@
package com.dfsek.terra.addons.attribute;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.api.registry.Registry;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeEntry;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeMap;
import com.dfsek.terra.api.world.attribute.AttributeParents;
import com.dfsek.terra.api.world.attribute.PackAttributes;
import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule;
import com.dfsek.terra.api.world.biome.Biome;
/**
* {@link #biomeEntryOrNull}, {@link #resolve} and {@link #resolvePack} must not allocate.
*/
public final class PackAttributesImpl implements PackAttributes {
private final AttributeHandle handle;
private final AttributeParents attributeParents;
private final AttributeMap entries;
private final AttributeEntry<?>[] packEntries;
private final AttributeEntry<?>[][] columns;
private final AttributeMap[] biomeEntries;
private final Map<String, RegistryKey> parents;
private final List<Either<RegistryKey, TagKey>> scheduleRefs;
private final Map<RegistryKey, AttributeSchedule> scheduleDefinitions;
private final List<String> warnings;
public PackAttributesImpl(AttributeHandle handle, AttributeParents attributeParents, @Nullable Registry<Attribute<?>> attributes,
AttributeMap entries, Map<String, RegistryKey> parents,
List<Either<RegistryKey, TagKey>> scheduleRefs, Map<RegistryKey, AttributeSchedule> scheduleDefinitions,
AttributeMap[] biomeEntries, List<String> warnings) {
this.handle = handle;
this.attributeParents = attributeParents;
this.entries = entries;
this.packEntries = new AttributeEntry<?>[handle.attributeCount()];
for(AttributeKey<?> key : entries.keys()) {
packEntries[attribute(attributes, key).index()] = entries.get(key).orElseThrow();
}
this.columns = new AttributeEntry<?>[handle.attributeCount()][];
for(int id = 0; id < biomeEntries.length; id++) {
AttributeMap declared = biomeEntries[id];
if(declared == null) continue;
for(AttributeKey<?> key : declared.keys()) {
int index = attribute(attributes, key).index();
if(columns[index] == null) columns[index] = new AttributeEntry<?>[biomeEntries.length];
columns[index][id] = declared.get(key).orElseThrow();
}
}
this.biomeEntries = biomeEntries;
this.parents = Collections.unmodifiableMap(new LinkedHashMap<>(parents));
this.scheduleRefs = List.copyOf(scheduleRefs);
this.scheduleDefinitions = Collections.unmodifiableMap(new LinkedHashMap<>(scheduleDefinitions));
this.warnings = List.copyOf(warnings);
}
private static Attribute<?> attribute(@Nullable Registry<Attribute<?>> attributes, AttributeKey<?> key) {
if(attributes == null) throw new IllegalArgumentException("entry " + key + " given for a pack without attributes");
return attributes.get(key.getRegistryKey())
.orElseThrow(() -> new IllegalArgumentException("entry " + key + " names no attribute of the pack"));
}
@Override
public AttributeMap entries() {
return entries;
}
@Override
public Map<String, RegistryKey> parents() {
return parents;
}
@Override
public List<Either<RegistryKey, TagKey>> scheduleRefs() {
return scheduleRefs;
}
@Override
public Map<RegistryKey, AttributeSchedule> scheduleDefinitions() {
return scheduleDefinitions;
}
@Override
@SuppressWarnings("unchecked")
public <T> @Nullable AttributeEntry<T> biomeEntryOrNull(Attribute<T> attribute, Biome biome) {
int index = attribute.index();
if(index >= columns.length) return null;
AttributeEntry<?>[] column = columns[index];
if(column == null) return null;
int id = biome.getIntID();
if(id < 0 || id >= column.length) return null;
return (AttributeEntry<T>) column[id];
}
@Override
public AttributeMap biomeEntries(Biome biome) {
int id = biome.getIntID();
if(id < 0 || id >= biomeEntries.length || biomeEntries[id] == null) return AttributeMap.empty();
return biomeEntries[id];
}
@SuppressWarnings("unchecked")
private <T> @Nullable AttributeEntry<T> packEntryOrNull(Attribute<T> attribute) {
int index = attribute.index();
return index < packEntries.length ? (AttributeEntry<T>) packEntries[index] : null;
}
@Override
public <T> @Nullable T resolve(Attribute<T> attribute, Biome biome) {
return handle.resolve(attribute, attributeParents.packOrNull(this, attribute), packEntryOrNull(attribute),
attributeParents.biomeOrNull(biome, attribute), biomeEntryOrNull(attribute, biome));
}
@Override
public <T> @Nullable T resolvePack(Attribute<T> attribute) {
return handle.resolve(attribute, attributeParents.packOrNull(this, attribute), packEntryOrNull(attribute), null);
}
public List<String> warnings() {
return warnings;
}
}
@@ -0,0 +1,60 @@
package com.dfsek.terra.addons.attribute;
import com.dfsek.tectonic.api.config.template.ConfigTemplate;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.dfsek.terra.api.config.meta.Meta;
public class PackAttributesTemplate implements ConfigTemplate {
@Value("attributes")
@Default
private @Meta Map<@Meta String, LazyConfigValue> attributes = Map.of();
@Value("schedules")
@Default
private @Meta List<@Meta String> schedules = List.of();
@Value("schedule-definitions")
@Default
private @Meta Map<@Meta String, LazyConfigValue> scheduleDefinitions = Map.of();
// May be a map (vanilla.mobs); only a string names a parent.
@Value("vanilla")
@Default
private @Meta LazyConfigValue vanilla = null;
@Value("vanilla-generation")
@Default
private @Meta LazyConfigValue vanillaGeneration = null;
Map<String, LazyConfigValue> getAttributes() {
return Collections.unmodifiableMap(attributes);
}
public List<String> getSchedules() {
return schedules;
}
Map<String, LazyConfigValue> getScheduleDefinitions() {
return Collections.unmodifiableMap(scheduleDefinitions);
}
public Optional<String> getVanilla() {
return string(vanilla);
}
public Optional<String> getVanillaGeneration() {
return string(vanillaGeneration);
}
private static Optional<String> string(LazyConfigValue value) {
return value != null && value.raw() instanceof String s ? Optional.of(s) : Optional.empty();
}
}
@@ -0,0 +1,60 @@
package com.dfsek.terra.addons.attribute;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
import com.dfsek.terra.api.registry.Registry;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeLookup;
import com.dfsek.terra.api.world.attribute.DecodeException;
/**
* Keys must be fully namespaced: inheritance merges config maps by raw key text.
*/
public final class RegistryAttributeLookup implements AttributeLookup {
private static final String NAMESPACE_REQUIRED = "attribute keys must include a namespace, e.g. \"minecraft:visual/fog_color\"";
private static final String UNKNOWN = "unknown attribute";
private static final Map<String, String> NAMESPACE_ADDONS = Map.of(
"minecraft", "minecraft-attributes",
"terra", "minecraft-attributes");
private final @Nullable Registry<Attribute<?>> registry;
public RegistryAttributeLookup(@Nullable Registry<Attribute<?>> registry) {
this.registry = registry;
}
@Override
public Attribute<?> find(String key) throws DecodeException {
AttributeKey<?> parsed;
try {
parsed = AttributeKey.parse(key);
} catch(IllegalArgumentException e) {
if(key.indexOf(':') < 0) throw new DecodeException(NAMESPACE_REQUIRED, e);
throw new DecodeException(invalidKey(e), e);
}
Attribute<?> attribute = registry == null ? null : registry.get(parsed.getRegistryKey()).orElse(null);
if(attribute == null) throw new DecodeException(unknownAttribute(parsed.getRegistryKey()));
return attribute;
}
private static String invalidKey(IllegalArgumentException e) {
Throwable cause = e.getCause() == null ? e : e.getCause();
String message = cause.getMessage();
return message == null ? "invalid attribute key" : "invalid attribute key: " + message;
}
private String unknownAttribute(RegistryKey key) {
String namespace = key.getNamespace();
String addon = NAMESPACE_ADDONS.get(namespace);
if(addon == null) return UNKNOWN;
if(registry != null && registry.keys().stream().anyMatch(registered -> registered.getNamespace().equals(namespace))) {
return UNKNOWN;
}
return UNKNOWN + ": no \"" + namespace + "\" attributes are registered; add the \"" + addon + "\" addon to the pack's addons";
}
}
@@ -0,0 +1,30 @@
package com.dfsek.terra.addons.attribute;
import java.util.Set;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
final class ScheduleIds {
private ScheduleIds() { }
static RegistryKey claim(String id, Set<RegistryKey> claimed) {
if(id.startsWith("#")) throw new IllegalArgumentException("schedule IDs must not be tags");
RegistryKey key;
try {
key = RegistryKey.parseNamespaced(id);
} catch(IllegalArgumentException e) {
if(id.indexOf(':') < 0) throw new IllegalArgumentException("schedule IDs must include a namespace, e.g. \"mypack:seasons\"", e);
throw e;
}
if(!claimed.add(key)) throw new IllegalArgumentException("duplicate schedule ID");
return key;
}
static Either<RegistryKey, TagKey> reference(String value) {
if(value.startsWith("#")) return Either.right(TagKey.parse(value));
return Either.left(RegistryKey.parseNamespaced(value));
}
}
@@ -0,0 +1,122 @@
{
"id": "config-attributes",
"docVersion": 1,
"description": "Environment attributes for biomes and packs. Contributes the attributes key to biome configurations, and attributes, schedules, schedule-definitions and vanilla-generation to pack.yml, and reads pack.yml's vanilla key when it is a string. The pack must list this addon under addons: in pack.yml, along with the addon that registers the attributes it uses (minecraft-attributes for the minecraft: and terra: ones); an unknown key's warning names that addon when none of its attributes are registered. Attribute keys must be fully namespaced (minecraft:visual/fog_color); a bad entry logs a warning and is skipped without affecting the rest of the pack.",
"types": {
"terra:AttributeEntry": {
"kind": "oneOf",
"options": [
{
"kind": "object",
"fields": {
"modifier": {
"schema": {
"kind": "string"
},
"required": true,
"summary": "Modifier name. The modifier form is exactly the two keys modifier and argument. Examples: override, add, subtract, multiply, minimum, maximum, overlay, alpha_blend or blend_to_gray. Which modifiers are valid depends on the attribute's value type."
},
"argument": {
"schema": {
"kind": "any"
},
"required": true,
"summary": "Modifier argument, in the attribute's value format or the modifier's own argument format. Range validation applies to plain values and override arguments; other modifier arguments are clamped when the value is resolved."
}
},
"description": "Modifier form. Any map containing a modifier key is read as this form, never as a plain value."
},
{
"kind": "any"
}
],
"description": "A plain value in the attribute's vanilla format (for example \"#c0d8ff\", 0.5, true, or a list or map for complex types), or a modifier object. Particle options and text components are kept as opaque raw values for platforms to decode, with meta resolved."
},
"terra:Biome": {
"kind": "object",
"fields": {
"attributes": {
"schema": {
"kind": "keyMap",
"keys": {
"kind": "string"
},
"values": {
"kind": "type",
"target": "terra:AttributeEntry"
},
"nullable": true
},
"required": false,
"default": {},
"summary": "Maps namespaced attribute IDs (for example minecraft:visual/fog_color) to a value or a {modifier, argument} object. Merged per key through extends, nearest config winning, and << meta includes work at every layer. A key without a namespace, an unknown key, a value that does not decode, or a non-biome attribute logs a warning and is skipped. Attributes not set here are inherited, not defaulted. An explicit null value for a known attribute that is allowed in biomes clears the inherited entry without a warning, so the attribute falls back to the lower layers (the platform's biome parent, the pack, the platform's pack parent, the default). Setting attributes: null on a child does not clear what it inherits, because inheritance merges per key and skips a null layer; clear entries one key at a time instead. Meta features work inside values at any depth: $file:key references, ${file:key} interpolation, << includes in maps and lists, and number expressions wherever a number is expected. A meta error inside a value logs a warning and skips that entry."
}
}
}
},
"files": {
"BIOME": {
"kind": "object",
"fields": {},
"extends": [
"terra:Biome"
]
},
"pack.yml": {
"kind": "object",
"fields": {
"attributes": {
"schema": {
"kind": "keyMap",
"keys": {
"kind": "string"
},
"values": {
"kind": "type",
"target": "terra:AttributeEntry"
},
"nullable": true
},
"required": false,
"default": {},
"summary": "Pack-level (dimension) attribute values, keyed by namespaced attribute ID. They layer over the platform's pack parent, which it may take from the IDs in vanilla: and vanilla-generation:, and biome values layer on top of them. Bad entries warn and are skipped. An explicit null value for a known attribute sets no entry, without a warning."
},
"schedules": {
"schema": {
"kind": "list",
"element": {
"kind": "string"
},
"nullable": true
},
"required": false,
"default": [],
"summary": "Schedule IDs or #tags to attach to the pack's dimension, each with a namespace (mypack:seasons, #mypack:in_overworld); an entry without one logs a warning and is skipped. Entries are resolved by the platform; they may also name schedules declared in schedule-definitions. A single string is accepted as a one-entry list. Platforms map schedules to Minecraft timelines."
},
"schedule-definitions": {
"schema": {
"kind": "keyMap",
"keys": {
"kind": "string"
},
"values": {
"kind": "any"
},
"nullable": true
},
"required": false,
"default": {},
"summary": "Maps schedule IDs to schedule objects in vanilla's format (clock, period_ticks, time_markers, tracks of keyframes). IDs must include a namespace (mypack:seasons), must not be tags, and must be unique; the first definition with an ID wins. Clock and time-marker IDs must include a namespace too; one without skips the whole definition. A shape error skips the whole definition; an unknown attribute, a modifier invalid for the attribute's type, or a bad keyframe value drops only that track. An unknown modifier name skips the whole definition."
},
"vanilla-generation": {
"schema": {
"kind": "string",
"nullable": true
},
"required": false,
"summary": "Parent ID for the platform's generation settings (for example minecraft:overworld). Like pack.yml's vanilla: key, which this addon reads only when it is a string ID (a map there is for other settings and is ignored here), it must include a namespace. An ID without one, or an invalid ID, in either key logs a warning and is ignored. The platform decides what each parent supplies and to which attributes; without platform support these layers are empty."
}
}
}
}
}
@@ -0,0 +1,14 @@
schema-version: 1
contributors:
- Terra contributors
id: config-attributes
version: @VERSION@
entrypoints:
- "com.dfsek.terra.addons.attribute.AttributeAddon"
website:
issues: https://github.com/PolyhedralDev/Terra/issues
source: https://github.com/PolyhedralDev/Terra
docs: https://terra.polydev.org
license: MIT License
depends:
config-biome: "1.+"
@@ -0,0 +1,193 @@
package attribute;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Stream;
import com.dfsek.terra.addons.attribute.AttributeReader;
import com.dfsek.terra.addons.attribute.AttributeReader.Problem;
import com.dfsek.terra.addons.attribute.AttributeReader.Result;
import com.dfsek.terra.addons.attribute.AttributeReader.Scope;
import com.dfsek.terra.addons.attribute.RegistryAttributeLookup;
import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTable;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes;
import com.dfsek.terra.api.registry.Registry;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeEntry;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.Operation;
import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult;
import com.dfsek.terra.registry.OpenRegistryImpl;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.*;
class AttributeReaderTest {
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
private static final Registry<Attribute<?>> REGISTRY = registry();
private static final AttributeReader READER = new AttributeReader(REGISTRY, HANDLE);
private static final String LIGHT = "terra:dimension/monster_spawn_light_level";
private static final String NAMESPACE_REQUIRED = "attribute keys must include a namespace, e.g. \"minecraft:visual/fog_color\"";
private static Registry<Attribute<?>> registry() {
OpenRegistryImpl<Attribute<?>> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
for(Attribute<?> attribute : MinecraftAttributeTable.create(HANDLE)) registry.register(attribute.getRegistryKey(), attribute);
return registry;
}
private static Map<String, Object> map(Object... kv) {
Map<String, Object> m = new LinkedHashMap<>();
for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]);
return m;
}
private static void assertExactProblem(Result result, String key, String reason) {
assertEquals(List.of(new Problem(key, reason)), result.problems());
}
static Stream<Arguments> accepted() {
return Stream.of(
Arguments.of(Scope.BIOME, "minecraft:visual/fog_color", "#c0d8ff", Operation.OVERRIDE),
Arguments.of(Scope.BIOME, "minecraft:visual/water_fog_end_distance", map("modifier", "multiply", "argument", 0.85),
Operation.MULTIPLY),
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "multiply", "argument", 5), Operation.MULTIPLY),
Arguments.of(Scope.BIOME, "minecraft:visual/ambient_particles", map("modifier", "append",
"argument", List.of(map("particle", map("type", "minecraft:crimson_spore"), "probability", 0.025))), Operation.APPEND),
Arguments.of(Scope.BIOME, "minecraft:gameplay/natural_mob_spawns", map("modifier", "overlay", "argument", map(
"spawn_costs", map("minecraft:enderman", map("energy_budget", 0.7, "charge", 0.15)),
"spawns_by_category", map("creature", List.of(
map("type", "minecraft:sheep", "count", 4, "weight", 12),
map("type", "minecraft:horse", "weight", 5,
"count", map("type", "minecraft:uniform", "max_inclusive", 6, "min_inclusive", 2)))))), Operation.OVERLAY),
Arguments.of(Scope.PACK, "minecraft:gameplay/fast_lava", true, Operation.OVERRIDE),
Arguments.of(Scope.PACK, LIGHT, map("type", "minecraft:uniform", "min_inclusive", 0, "max_inclusive", 7), Operation.OVERRIDE));
}
@ParameterizedTest(name = "{1}")
@MethodSource("accepted")
void accepts(Scope scope, String key, Object value, Operation operation) {
Result r = READER.read(Map.of(key, value), scope);
assertTrue(r.problems().isEmpty(), r.problems().toString());
assertEquals(operation, r.map().get(AttributeKey.parse(key)).orElseThrow().operation());
}
@Test
void intProviderModifierForm() {
Result r = READER.read(Map.of(LIGHT, Map.of("modifier", "override", "argument", 7)), Scope.PACK);
assertTrue(r.problems().isEmpty(), r.problems().toString());
AttributeEntry<?> e = r.map().get(MinecraftAttributes.DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL).orElseThrow();
assertEquals(Operation.OVERRIDE, e.operation());
assertEquals(new IntProviderValue(OptionalInt.of(7), Optional.empty()), e.argument());
}
static Stream<Arguments> problems() {
return Stream.of(
Arguments.of(Scope.BIOME, "minecraft:nope", 1, "unknown attribute"),
Arguments.of(Scope.BIOME, "minecraft:Visual/Sky_Color", "#123456", "unknown attribute"),
Arguments.of(Scope.BIOME, "visual/sky_color", "#123456", NAMESPACE_REQUIRED),
Arguments.of(Scope.BIOME, "minecraft:Bad Key!", 1, "invalid attribute key..."),
Arguments.of(Scope.BIOME, "minecraft:visual/sky_color", true, "expected..."),
Arguments.of(Scope.BIOME, "minecraft:audio/ambient_sounds", map("loop", "minecraft:Music.Game"),
"\"loop\" of ambient sounds: expected an identifier like \"minecraft:id\", got \"minecraft:Music.Game\""),
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", 2, "value 2.0 is outside [0, 1]"),
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "override", "argument", 2),
"value 2.0 is outside [0, 1]"),
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "and", "argument", true),
"modifier and is not valid for minecraft:visual/star_brightness"),
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "frobnicate", "argument", 1),
"unknown modifier \"frobnicate\""),
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "add", "argument", null),
"expected a number, got nothing"),
Arguments.of(Scope.PACK, LIGHT, map("modifier", "frobnicate", "argument", 7), "unknown modifier \"frobnicate\""),
Arguments.of(Scope.PACK, LIGHT, map("min_inclusive", 0, "max_inclusive", 7), "int provider object is missing \"type\""),
Arguments.of(Scope.PACK, "terra:dimension/height", 100, "value 100 is not a multiple of 16"),
Arguments.of(Scope.BIOME, "minecraft:gameplay/fast_lava", true, "not allowed in a biome"),
Arguments.of(Scope.BIOME, "minecraft:visual/ambient_particles", Arrays.asList((Object) null),
"element 0: expected an object for ambient particle, got nothing"),
Arguments.of(Scope.BIOME, "minecraft:visual/ambient_particles", List.of(map("particle", null, "probability", 0.1)),
"element 0: \"particle\" of ambient particle: expected a particle object with a \"type\" key, got nothing"));
}
@ParameterizedTest(name = "{1}: {3}")
@MethodSource("problems")
void badEntryIsolated(Scope scope, String key, Object value, String reason) {
Result r = READER.read(map(key, value, "minecraft:visual/fog_color", "#c0d8ff"), scope);
assertEquals(1, r.problems().size(), r.problems().toString());
assertEquals(key, r.problems().get(0).key());
if(reason.endsWith("...")) {
String prefix = reason.substring(0, reason.length() - 3);
assertTrue(r.problems().get(0).reason().startsWith(prefix), r.problems().get(0).reason());
} else {
assertEquals(reason, r.problems().get(0).reason());
}
assertTrue(r.map().get(MinecraftAttributes.VISUAL_FOG_COLOR).isPresent());
assertEquals(1, r.map().keys().size());
}
@Test
void nullUnsetsKnownKeys() {
for(Scope scope : Scope.values()) {
Result r = READER.read(map("minecraft:visual/fog_color", null, "minecraft:visual/sky_color", "#405060"), scope);
assertTrue(r.problems().isEmpty(), r.problems().toString());
assertTrue(r.map().get(MinecraftAttributes.VISUAL_FOG_COLOR).isEmpty());
assertEquals(1, r.map().keys().size());
}
Map<String, Object> raw = map("minecraft:nope", null, "minecraft:Bad Key!", null, "visual/sky_color", null,
"terra:world/sea_level", null, "minecraft:visual/fog_color", null);
Result r = READER.read(raw, Scope.BIOME);
assertEquals(List.of(
new Problem("minecraft:nope", "unknown attribute"),
new Problem("minecraft:Bad Key!", "invalid attribute key: ID must only contain alphanumeric characters, hyphens, underscores, periods, and slashes. \"Bad Key!\" is not a valid ID."),
new Problem("visual/sky_color", NAMESPACE_REQUIRED),
new Problem("terra:world/sea_level", "not allowed in a biome")),
r.problems());
assertTrue(r.map().isEmpty());
assertTrue(READER.read(map("terra:world/sea_level", null), Scope.PACK).problems().isEmpty());
}
@Test
void unknownKeyHint() {
AttributeReader empty = new AttributeReader(new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE), HANDLE);
for(String key : List.of("minecraft:visual/fog_color", "terra:biome/temperature")) {
String namespace = key.substring(0, key.indexOf(':'));
assertExactProblem(empty.read(Map.of(key, "#ffffff"), Scope.BIOME), key,
"unknown attribute: no \"" + namespace + "\" attributes are registered; add the \"minecraft-attributes\" addon "
+ "to the pack's addons");
}
Result none = new AttributeReader(null, HANDLE).read(Map.of("minecraft:visual/fog_color", "#ffffff"), Scope.PACK);
assertExactProblem(none, "minecraft:visual/fog_color", "unknown attribute: no \"minecraft\" attributes are registered; add the "
+ "\"minecraft-attributes\" addon to the pack's addons");
assertExactProblem(empty.read(Map.of("mypack:thing", 1), Scope.BIOME), "mypack:thing", "unknown attribute");
assertExactProblem(READER.read(Map.of("minecraft:visual/fog_colour", "#ffffff"), Scope.BIOME), "minecraft:visual/fog_colour",
"unknown attribute");
}
@Test
void scheduleTrackKeys() {
Map<String, Object> track = Map.of("keyframes", List.of(Map.of("ticks", 0, "value", 10.0)));
Map<String, Object> raw = map("clock", "minecraft:overworld", "tracks", map(
"visual/sun_angle", track,
"minecraft:visual/sun angle", track,
"minecraft:visual/moon_angle", track));
ScheduleDecodeResult r = HANDLE.decodeSchedule(RegistryKey.parse("terra:test"), raw, new RegistryAttributeLookup(REGISTRY),
HANDLE.plainContext());
assertEquals(List.of(
new ScheduleDecodeResult.Problem("visual/sun_angle", NAMESPACE_REQUIRED),
new ScheduleDecodeResult.Problem("minecraft:visual/sun angle", "invalid attribute key: ID must only contain alphanumeric characters, hyphens, underscores, periods, and slashes. \"visual/sun angle\" is not a valid ID.")),
r.droppedTracks());
assertEquals(1, r.schedule().orElseThrow().tracks().size());
}
}
@@ -0,0 +1,160 @@
package attribute;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Proxy;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import com.dfsek.terra.addons.attribute.PackAttributesImpl;
import com.dfsek.terra.api.registry.Registry;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeEntry;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeMap;
import com.dfsek.terra.api.world.attribute.AttributeParents;
import com.dfsek.terra.api.world.attribute.Operation;
import com.dfsek.terra.api.world.attribute.PackAttributes;
import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.registry.OpenRegistryImpl;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
class PackAttributesImplTest {
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
private static final Attribute<Integer> COUNT = HANDLE.attributeBuilder(AttributeKey.parse("test:count"), HANDLE.types().integer(),
10).build();
private static final Attribute<Integer> OTHER = HANDLE.attributeBuilder(AttributeKey.parse("test:other"), HANDLE.types().integer(),
0).build();
private static final Registry<Attribute<?>> REGISTRY = registry(COUNT, OTHER);
private static Registry<Attribute<?>> registry(Attribute<?>... attributes) {
OpenRegistryImpl<Attribute<?>> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
for(Attribute<?> attribute : attributes) registry.register(attribute.getRegistryKey(), attribute);
return registry;
}
private static Biome withId(int id) {
return (Biome) Proxy.newProxyInstance(Biome.class.getClassLoader(), new Class<?>[]{ Biome.class }, (proxy, method, args) ->
switch(method.getName()) {
case "getIntID" -> id;
default -> throw new UnsupportedOperationException(method.getName());
});
}
private static PackAttributesImpl pack(AttributeParents parents, AttributeMap entries, AttributeMap... biomeEntries) {
return new PackAttributesImpl(HANDLE, parents, REGISTRY, entries, Map.of(), List.of(), Map.of(), biomeEntries, List.of());
}
private static AttributeMap map(Attribute<Integer> attribute, AttributeEntry<Integer> entry) {
return AttributeMap.builder().put(attribute.key(), entry).build();
}
@Test
void resolveUsesParents() {
AttributeParents parents = new AttributeParents() {
@Override
@SuppressWarnings("unchecked")
public <T> @Nullable AttributeEntry<T> biomeOrNull(Biome biome, Attribute<T> attribute) {
return attribute == COUNT ? (AttributeEntry<T>) AttributeEntry.override(5) : null;
}
@Override
@SuppressWarnings("unchecked")
public <T> @Nullable AttributeEntry<T> packOrNull(PackAttributes pack, Attribute<T> attribute) {
return attribute == COUNT ? (AttributeEntry<T>) AttributeEntry.of(Operation.ADD, 1) : null;
}
};
PackAttributesImpl pack = pack(parents, map(COUNT, AttributeEntry.of(Operation.ADD, 2)), new AttributeMap[2]);
assertEquals(5, pack.resolve(COUNT, withId(1)));
assertEquals(COUNT.defaultValue() + 3, pack.resolvePack(COUNT));
PackAttributesImpl withBiome = pack(parents, map(COUNT, AttributeEntry.of(Operation.ADD, 2)), null,
map(COUNT, AttributeEntry.of(Operation.ADD, 100)));
assertEquals(105, withBiome.resolve(COUNT, withId(1)));
assertEquals(0, pack.resolve(OTHER, withId(1)));
assertEquals(0, pack.resolvePack(OTHER));
}
@Test
void parentsNone() {
PackAttributesImpl pack = pack(AttributeParents.NONE, map(COUNT, AttributeEntry.of(Operation.ADD, 2)), null,
map(COUNT, AttributeEntry.of(Operation.MULTIPLY, 3)));
assertEquals(36, pack.resolve(COUNT, withId(1)));
assertEquals(12, pack.resolve(COUNT, withId(0)));
assertEquals(12, pack.resolvePack(COUNT));
}
@Test
void twoPacksIndependentColumns() {
AttributeEntry<Integer> small1 = AttributeEntry.override(1);
AttributeEntry<Integer> large1 = AttributeEntry.override(2);
AttributeEntry<Integer> large2 = AttributeEntry.override(3);
PackAttributesImpl small = pack(AttributeParents.NONE, AttributeMap.empty(), null, map(COUNT, small1));
PackAttributesImpl large = pack(AttributeParents.NONE, AttributeMap.empty(), null, map(COUNT, large1), map(COUNT, large2));
assertSame(small1, small.biomeEntryOrNull(COUNT, withId(1)));
assertSame(large1, large.biomeEntryOrNull(COUNT, withId(1)));
assertSame(large2, large.biomeEntryOrNull(COUNT, withId(2)));
assertNull(small.biomeEntryOrNull(COUNT, withId(2)));
assertEquals(10, small.resolve(COUNT, withId(2)));
assertEquals(3, large.resolve(COUNT, withId(2)));
}
@Test
void storedBiomeEntry() {
AttributeEntry<Integer> stored = AttributeEntry.override(7);
PackAttributesImpl pack = pack(AttributeParents.NONE, AttributeMap.empty(), null, map(COUNT, stored), null);
assertSame(stored, pack.biomeEntryOrNull(COUNT, withId(1)));
assertNull(pack.biomeEntryOrNull(COUNT, withId(0)));
assertNull(pack.biomeEntryOrNull(COUNT, withId(-1)));
assertNull(pack.biomeEntryOrNull(COUNT, withId(3)));
assertNull(pack.biomeEntryOrNull(OTHER, withId(1)));
Attribute<Integer> later = HANDLE.attributeBuilder(AttributeKey.parse("test:later"), HANDLE.types().integer(), 4).build();
assertNull(pack.biomeEntryOrNull(later, withId(1)));
assertEquals(4, pack.resolve(later, withId(1)));
assertEquals(4, pack.resolvePack(later));
}
@Test
void biomeEntriesCold() {
AttributeMap declared = AttributeMap.builder()
.put(COUNT.key(), AttributeEntry.override(1))
.put(OTHER.key(), AttributeEntry.of(Operation.ADD, 2))
.build();
PackAttributesImpl pack = pack(AttributeParents.NONE, AttributeMap.empty(), null, declared);
assertSame(declared, pack.biomeEntries(withId(1)));
assertSame(AttributeMap.empty(), pack.biomeEntries(withId(0)));
assertSame(AttributeMap.empty(), pack.biomeEntries(withId(2)));
assertSame(AttributeMap.empty(), pack.biomeEntries(withId(-1)));
}
@Test
void configOrder() {
Map<String, RegistryKey> parents = new LinkedHashMap<>();
parents.put("vanilla-generation", RegistryKey.parse("test:generation"));
parents.put("vanilla", RegistryKey.parse("test:dimension"));
List<String> ids = List.of("terra:z", "terra:a", "terra:m", "terra:b", "terra:y", "terra:c", "terra:x", "terra:d");
Map<RegistryKey, AttributeSchedule> definitions = new LinkedHashMap<>();
for(String id : ids) {
definitions.put(RegistryKey.parse(id), new AttributeSchedule(RegistryKey.parse("test:clock"), OptionalInt.empty(),
Map.of(), Map.of()));
}
PackAttributesImpl pack = new PackAttributesImpl(HANDLE, AttributeParents.NONE, REGISTRY, AttributeMap.empty(), parents,
List.of(), definitions, new AttributeMap[0], List.of());
assertEquals(List.of("vanilla-generation", "vanilla"), List.copyOf(pack.parents().keySet()));
assertEquals(ids, pack.scheduleDefinitions().keySet().stream().map(RegistryKey::toString).toList());
}
}
@@ -0,0 +1,186 @@
package com.dfsek.terra.addons.attribute;
import com.dfsek.paralithic.eval.parser.Parser.ParseOptions;
import com.dfsek.tectonic.api.config.Configuration;
import com.dfsek.tectonic.api.depth.DepthTracker;
import com.dfsek.tectonic.api.loader.ConfigLoader;
import com.dfsek.tectonic.api.preprocessor.Result;
import com.dfsek.tectonic.api.preprocessor.ValuePreprocessor;
import com.dfsek.tectonic.impl.MapConfiguration;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Test;
import java.lang.reflect.AnnotatedType;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.api.config.meta.Meta;
import com.dfsek.terra.api.world.attribute.DecodeContext;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.config.preprocessor.MetaListLikePreprocessor;
import com.dfsek.terra.config.preprocessor.MetaMapPreprocessor;
import com.dfsek.terra.config.preprocessor.MetaNumberPreprocessor;
import com.dfsek.terra.config.preprocessor.MetaStringPreprocessor;
import com.dfsek.terra.config.preprocessor.MetaValuePreprocessor;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.*;
class ConfigDecodeContextTest {
private static final Map<String, Object> META = map(
"n", 3,
"s", "two",
"chain", "$meta.yml:s",
"obj", map("x", 1, "y", "$meta.yml:s"),
"list", List.of("a", "b"));
private static Map<String, Object> map(Object... kv) {
Map<String, Object> m = new LinkedHashMap<>();
for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]);
return m;
}
private static DecodeContext context() {
return context(Map.of("meta.yml", new MapConfiguration(META, "meta.yml")));
}
private static DecodeContext context(Map<String, Configuration> configs) {
ConfigLoader loader = new ConfigLoader();
loader.registerPreprocessor(Meta.class, new MetaStringPreprocessor(configs));
loader.registerPreprocessor(Meta.class, new MetaListLikePreprocessor(configs));
loader.registerPreprocessor(Meta.class, new MetaMapPreprocessor(configs));
loader.registerPreprocessor(Meta.class, new MetaValuePreprocessor(configs));
loader.registerPreprocessor(Meta.class, new MetaNumberPreprocessor(configs, new ParseOptions()));
return context(loader);
}
private static DecodeContext context(ConfigLoader loader) {
for(Class<?> type : ConfigDecodeContext.CAPTURED_TYPES) loader.registerLoader(type, LazyConfigValue.LOADER);
DepthTracker tracker = new DepthTracker(List.of(), new MapConfiguration(Map.of(), "biome.yml"));
return new LazyConfigValue(null, loader, tracker).context(new AttributeHandleImpl().plainContext());
}
@Test
void numberExpressions() throws DecodeException {
DecodeContext context = context();
assertEquals("2 * 6000", context.resolve("2 * 6000"));
assertEquals(12000, context.<Integer>load(Integer.class, "2 * 6000"));
assertEquals(1.5f, context.<Float>load(Float.class, "${meta.yml:n} / 2"));
assertEquals(3.0, context.<Double>load(Double.class, "$meta.yml:n"));
assertEquals(0.5f, context.<Float>load(Float.class, 0.5));
}
@Test
void plainConversion() {
DecodeContext context = context();
assertTrue(assertThrows(DecodeException.class, () -> context.load(Integer.class, "5 / 2")).getMessage()
.startsWith("expected an integer"));
assertEquals("expected a string, got 3",
assertThrows(DecodeException.class, () -> context.load(String.class, "$meta.yml:n")).getMessage());
assertEquals("expected a boolean (true or false), got \"two\"",
assertThrows(DecodeException.class, () -> context.load(Boolean.class, "$meta.yml:s")).getMessage());
}
@Test
void nestedResolve() throws DecodeException {
Map<String, Object> raw = map(
"null", null,
"ref", "$meta.yml:obj",
"list", List.of("<< meta.yml:list", "c", "${meta.yml:s}"),
"include", map("<<", List.of("meta.yml:obj"), "x", 2),
"string", "one-${meta.yml:s}",
"deep", map("a", List.of(map("b", "$meta.yml:n"))));
Map<?, ?> resolved = (Map<?, ?>) context().resolve(raw);
assertEquals(map(
"null", null,
"ref", map("x", 1, "y", "two"),
"list", List.of("a", "b", "c", "two"),
"include", map("x", 2, "y", "two"),
"string", "one-two",
"deep", map("a", List.of(map("b", 3)))), resolved);
assertEquals(List.copyOf(raw.keySet()), List.copyOf(resolved.keySet()));
}
@Test
void resolveTwice() throws DecodeException {
DecodeContext context = context();
Object once = context.resolve(map("a", "$meta.yml:chain"));
assertEquals(map("a", "$meta.yml:s"), once);
assertSame(once, context.resolve(once));
Object chained = ((Map<?, ?>) once).get("a");
assertSame(chained, context.resolve(chained));
assertEquals("$meta.yml:s", context.load(String.class, chained));
}
@Test
void preprocessingErrors() {
DecodeContext context = context();
String missing = assertThrows(DecodeException.class, () -> context.resolve(map("a", "${meta.yml:missing}"))).getMessage();
assertTrue(missing.contains("No such key missing"), missing);
assertTrue(missing.contains("Path: a"), missing);
String malformed = assertThrows(DecodeException.class, () -> context.resolve(List.of("${2 * 6000}"))).getMessage();
assertTrue(malformed.contains("meta reference \"2 * 6000\" must have the form file:key"), malformed);
assertTrue(malformed.contains("Path: [0]"), malformed);
assertReadable(malformed);
String escape = assertThrows(DecodeException.class, () -> context.resolve(map("a", "$meta.yml:bad\\q"))).getMessage();
assertTrue(escape.contains("meta reference \"meta.yml:bad\\q\" has an invalid key path"), escape);
assertReadable(escape);
String expression = assertThrows(DecodeException.class, () -> context.load(Float.class, "1 +")).getMessage();
assertTrue(expression.contains("Invalid expression"), expression);
String include = assertThrows(DecodeException.class, () -> context.resolve(map("<<", List.of("meta.yml:list")))).getMessage();
assertTrue(include.contains("MetaMap injection candidate must be map, is type java.util."), include);
}
@Test
void nullMetaTargets() {
Configuration nulls = new Configuration() {
@Override
public Object get(@NotNull String key) {
return null;
}
@Override
public boolean contains(@NotNull String key) {
return true;
}
@Override
public String getName() {
return "null.yml";
}
};
DecodeContext context = context(Map.of("null.yml", nulls));
String string = assertThrows(DecodeException.class, () -> context.resolve("${null.yml:x}")).getMessage();
assertTrue(string.contains("must be string or primitive, is null"), string);
String list = assertThrows(DecodeException.class, () -> context.resolve(List.of("<< null.yml:x"))).getMessage();
assertTrue(list.contains("'null.yml:x' points to null"), list);
String include = assertThrows(DecodeException.class, () -> context.resolve(map("<<", List.of("null.yml:x")))).getMessage();
assertTrue(include.contains("must be map, is null"), include);
}
@Test
void preprocessorRuntimeExceptions() {
ConfigLoader loader = new ConfigLoader();
loader.registerPreprocessor(Meta.class, new ValuePreprocessor<Meta>() {
@Override
public @NotNull <T> Result<T> process(AnnotatedType t, T c, ConfigLoader l, Meta annotation, DepthTracker depthTracker) {
throw new IllegalStateException("java.lang.Boom");
}
});
DecodeContext context = context(loader);
String message = assertThrows(DecodeException.class, () -> context.resolve("x")).getMessage();
assertTrue(message.contains("config preprocessing failed"), message);
assertReadable(message);
}
private static void assertReadable(String message) {
assertFalse(message.contains("java."), message);
assertFalse(message.contains("Exception"), message);
}
}
@@ -0,0 +1,40 @@
package com.dfsek.terra.addons.attribute;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ScheduleIdsTest {
@Test
void referenceNamespace() {
assertEquals(Either.left(RegistryKey.parse("mypack:seasons")), ScheduleIds.reference("mypack:seasons"));
assertEquals(Either.right(TagKey.parse("#mypack:in_overworld")), ScheduleIds.reference("#mypack:in_overworld"));
assertEquals("a namespace is required, as in \"namespace:seasons\"",
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.reference("seasons")).getMessage());
assertEquals("invalid tag \"#in_overworld\": a namespace is required, as in \"#namespace:in_overworld\"",
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.reference("#in_overworld")).getMessage());
}
@Test
void claim() {
Set<RegistryKey> claimed = new HashSet<>();
assertEquals(RegistryKey.parse("mypack:seasons"), ScheduleIds.claim("mypack:seasons", claimed));
assertEquals("duplicate schedule ID",
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("mypack:seasons", claimed)).getMessage());
assertEquals(RegistryKey.parse("MyPack:Seasons"), ScheduleIds.claim("MyPack:Seasons", claimed));
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("mypack:", claimed));
assertEquals("schedule IDs must include a namespace, e.g. \"mypack:seasons\"",
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("seasons", claimed)).getMessage());
assertEquals("schedule IDs must not be tags",
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("#mypack:seasons", claimed)).getMessage());
}
}
@@ -2,4 +2,6 @@ version = version("1.0.0")
dependencies {
compileOnlyApi(project(":common:addons:manifest-addon-loader"))
testImplementation("com.dfsek.tectonic", "common", Versions.Libraries.tectonic)
}
@@ -11,6 +11,7 @@ import com.dfsek.tectonic.api.config.template.ValidatedConfigTemplate;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Final;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.exception.ValidationException;
import java.util.Collections;
import java.util.HashSet;
@@ -21,6 +22,7 @@ import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.config.AbstractableTemplate;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.config.meta.Meta;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.world.biome.PlatformBiome;
@@ -48,13 +50,29 @@ public class BiomeTemplate implements AbstractableTemplate, ValidatedConfigTempl
@Default
private @Meta Set<@Meta String> tags = new HashSet<>();
private Set<RegistryKey> platformTags = Set.of();
public BiomeTemplate(ConfigPack pack, Platform platform) {
this.pack = pack;
}
@Override
public boolean validate() {
public boolean validate() throws ValidationException {
color |= 0xff000000; // Alpha adjustment
Set<RegistryKey> parsed = new HashSet<>();
for(String tag : tags) {
int colon = tag.indexOf(':');
if(colon < 0) continue;
// RegistryKey.parse accepts an empty namespace or ID.
if(colon == 0) throw new ValidationException("Invalid namespaced biome tag \"" + tag + "\": the namespace is empty");
if(colon == tag.length() - 1) throw new ValidationException("Invalid namespaced biome tag \"" + tag + "\": the ID is empty");
try {
parsed.add(RegistryKey.parse(tag));
} catch(IllegalArgumentException e) {
throw new ValidationException("Invalid namespaced biome tag \"" + tag + "\": " + e.getMessage());
}
}
platformTags = Set.copyOf(parsed);
return true;
}
@@ -66,6 +84,10 @@ public class BiomeTemplate implements AbstractableTemplate, ValidatedConfigTempl
return tags;
}
public Set<RegistryKey> getPlatformTags() {
return platformTags;
}
public int getColor() {
return color;
}
@@ -7,10 +7,11 @@
package com.dfsek.terra.addons.biome;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import com.dfsek.terra.api.properties.Context;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.api.world.biome.PlatformBiome;
@@ -24,6 +25,7 @@ public class UserDefinedBiome implements Biome {
private final BiomeTemplate config;
private final int color;
private final Set<String> tags;
private final Set<RegistryKey> platformTags;
private final Context context = new Context();
private final int intID;
@@ -33,10 +35,12 @@ public class UserDefinedBiome implements Biome {
this.id = config.getID();
this.config = config;
this.color = config.getColor();
this.tags = config.getTags();
this.intID = INT_ID_COUNTER.getAndIncrement();
tags.add("BIOME:" + id);
tags.add("ALL");
Set<String> allTags = new HashSet<>(config.getTags());
allTags.add("BIOME:" + id);
allTags.add("ALL");
this.tags = Set.copyOf(allTags);
this.platformTags = Set.copyOf(config.getPlatformTags());
this.intID = config.getPack().getBiomeTagIndex().register(tags);
}
@Override
@@ -64,6 +68,11 @@ public class UserDefinedBiome implements Biome {
return tags;
}
@Override
public Set<RegistryKey> getPlatformTags() {
return platformTags;
}
@Override
public int getIntID() {
return intID;
@@ -0,0 +1,120 @@
{
"id": "config-biome",
"docVersion": 1,
"description": "Registered biome configurations and a height-indexed palette-holder loader. Other addons contribute terrain, decoration and platform fields.",
"types": {
"terra:Biome": {
"kind": "object",
"fields": {
"id": {
"schema": {
"kind": "string",
"pattern": "^[a-zA-Z0-9_-]*$"
},
"required": true,
"summary": "Registry identifier; must be present on this file even when inherited."
},
"extends": {
"schema": {
"kind": "list",
"element": {
"kind": "string"
},
"nullable": true
},
"required": false,
"default": [],
"summary": "Parent configuration identifiers. This field is final and is read from the current file."
},
"vanilla": {
"schema": {
"kind": "type",
"target": "terra:PlatformBiome"
},
"required": true,
"summary": "Platform biome used for vanilla behavior."
},
"color": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 0,
"summary": "Biome mapping color; runtime forces the alpha byte to 0xff. Final: not inherited."
},
"tags": {
"schema": {
"kind": "set",
"element": {
"kind": "type",
"target": "terra:Tag"
},
"nullable": true
},
"required": false,
"default": [],
"summary": "User tags; runtime also adds ALL and BIOME:<id>."
}
}
},
"PaletteHolder": {
"kind": "list",
"element": {
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:PaletteReference"
},
"values": {
"kind": "integer"
}
},
"description": "Sequence of palette-reference to inclusive upper-Y maps. This loader reads raw integer map values, without numeric expression preprocessing. Heights select the first upper boundary at or above Y; duplicate heights replace earlier entries. Empty input cannot build a holder."
},
"terra:PaletteReference": {
"kind": "oneOf",
"options": [
{
"kind": "ref",
"target": "terra:Palette"
}
]
}
},
"files": {
"BIOME": {
"kind": "object",
"fields": {
"type": {
"schema": {
"kind": "literal",
"value": "BIOME"
},
"required": true
},
"abstract": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false,
"summary": "Abstract configurations are inherited rather than registered."
}
},
"extends": [
"terra:Biome"
]
}
}
}
@@ -0,0 +1,68 @@
package biome;
import com.dfsek.tectonic.api.exception.ValidationException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.lang.reflect.Field;
import java.lang.reflect.Proxy;
import java.util.HashSet;
import java.util.Set;
import com.dfsek.terra.addons.biome.BiomeTemplate;
import com.dfsek.terra.addons.biome.UserDefinedBiome;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PlatformTagsTest {
private static BiomeTemplate template(String... tags) throws ReflectiveOperationException {
BiomeTagIndex index = new BiomeTagIndex();
ConfigPack pack = (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class<?>[]{ ConfigPack.class },
(proxy, method, args) -> {
if(method.getName().equals("getBiomeTagIndex")) return index;
throw new UnsupportedOperationException(method.getName());
});
BiomeTemplate template = new BiomeTemplate(pack, null);
set(template, "id", "TEST");
set(template, "tags", new HashSet<>(Set.of(tags)));
return template;
}
private static void set(BiomeTemplate template, String field, Object value) throws ReflectiveOperationException {
Field f = BiomeTemplate.class.getDeclaredField(field);
f.setAccessible(true);
f.set(template, value);
}
@Test
void platformTags() throws Exception {
BiomeTemplate template = template("USE_RIVER", "minecraft:is_forest", "c:hot");
template.validate();
UserDefinedBiome biome = new UserDefinedBiome(null, template);
assertEquals(Set.of(RegistryKey.parse("minecraft:is_forest"), RegistryKey.parse("c:hot")), biome.getPlatformTags());
assertEquals(Set.of("USE_RIVER", "minecraft:is_forest", "c:hot", "BIOME:TEST", "ALL"), biome.getTags());
assertThrows(UnsupportedOperationException.class, () -> biome.getTags().add("X"));
assertFalse(template.getTags().contains("BIOME:TEST"));
}
@ParameterizedTest(name = "{0}")
@CsvSource(delimiter = '|', value = {
"minecraft:Bad Tag | minecraft:Bad Tag",
":is_forest | empty",
"minecraft: | empty",
})
void invalidNamespacedTag(String tag, String reasonPart) throws Exception {
ValidationException e = assertThrows(ValidationException.class, template(tag)::validate);
assertTrue(e.getMessage().contains("\"" + tag + "\""), e.getMessage());
assertTrue(e.getMessage().contains(reasonPart), e.getMessage());
}
}
@@ -0,0 +1,206 @@
{
"id": "config-distributors",
"docVersion": 1,
"description": "Eight registered distributor variants and explicit x/z point objects.",
"types": {
"terra:Distributor": {
"kind": "union",
"discriminator": "type",
"values": {
"AND": {
"kind": "object",
"fields": {
"distributors": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "terra:Distributor"
},
"minItems": 1
},
"required": true
}
},
"description": "Combines a nonempty list of distributor predicates using AND."
},
"OR": {
"kind": "object",
"fields": {
"distributors": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "terra:Distributor"
},
"minItems": 1
},
"required": true
}
},
"description": "Combines a nonempty list of distributor predicates using OR."
},
"XOR": {
"kind": "object",
"fields": {
"distributors": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "terra:Distributor"
},
"minItems": 1
},
"required": true
}
},
"description": "Combines a nonempty list of distributor predicates using XOR."
},
"YES": {
"kind": "object",
"fields": {},
"description": "Accepts every column."
},
"NO": {
"kind": "object",
"fields": {},
"description": "Rejects every column."
},
"SAMPLER": {
"kind": "object",
"fields": {
"threshold": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "float"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 0
},
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler"
},
"required": true
}
},
"description": "Accepts a column when its 2D sampler value is strictly less than threshold."
},
"POINTS": {
"kind": "object",
"fields": {
"points": {
"schema": {
"kind": "set",
"element": {
"kind": "type",
"target": "Point"
}
},
"required": true
}
},
"description": "Matches the configured x/z positions."
},
"PADDED_GRID": {
"kind": "object",
"fields": {
"width": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
]
},
"required": true
},
"padding": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
]
},
"required": true
},
"salt": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
]
},
"required": true
}
},
"description": "Chooses a seeded point inside each width-sized square separated by padding. No template numeric bounds are enforced; zero width or cell width can fail during sampling."
}
}
},
"Point": {
"kind": "object",
"fields": {
"x": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
]
},
"required": true
},
"z": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
]
},
"required": true
}
}
}
}
}
@@ -0,0 +1,183 @@
{
"id": "config-feature",
"docVersion": 1,
"description": "FEATURE files register configured placement features, with inline distributor/locator definitions and weighted raw structure references.",
"types": {
"terra:Feature": {
"kind": "object",
"fields": {
"id": {
"schema": {
"kind": "string",
"pattern": "^[a-zA-Z0-9_-]*$"
},
"required": true,
"summary": "Registry identifier; final and not inherited."
},
"distributor": {
"schema": {
"kind": "type",
"target": "terra:Distributor"
},
"required": true
},
"locator": {
"schema": {
"kind": "type",
"target": "terra:Locator"
},
"required": true
},
"structures": {
"schema": {
"kind": "object",
"fields": {
"distribution": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler"
},
"required": true,
"summary": "Sampler that chooses a structure from the weighted collection."
},
"structures": {
"schema": {
"kind": "type",
"target": "WeightedStructures"
},
"required": true
}
}
},
"required": true
}
}
},
"terra:StructureReference": {
"kind": "oneOf",
"options": [
{
"kind": "ref",
"target": "terra:Structure"
}
]
},
"WeightedStructures": {
"kind": "oneOf",
"description": "A raw structure reference, reference-to-weight map, or list of maps. Singleton weights are ignored; all other weights are raw integers.",
"options": [
{
"kind": "type",
"target": "terra:StructureReference"
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:StructureReference"
},
"values": {
"kind": "any",
"name": "Ignored singleton weight"
},
"maxEntries": 1
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:StructureReference"
},
"values": {
"kind": "integer"
},
"minEntries": 2
},
{
"kind": "list",
"element": {
"kind": "oneOf",
"options": [
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:StructureReference"
},
"values": {
"kind": "any",
"name": "Ignored singleton weight"
},
"maxEntries": 1
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:StructureReference"
},
"values": {
"kind": "integer"
},
"minEntries": 2
}
]
},
"maxItems": 1
},
{
"kind": "list",
"element": {
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:StructureReference"
},
"values": {
"kind": "integer"
}
},
"minItems": 2
}
]
}
},
"files": {
"FEATURE": {
"kind": "object",
"fields": {
"type": {
"schema": {
"kind": "literal",
"value": "FEATURE"
},
"required": true
},
"extends": {
"schema": {
"kind": "list",
"element": {
"kind": "string"
},
"nullable": true
},
"required": false,
"default": [],
"summary": "Parent configuration IDs; non-final fields may be inherited."
},
"abstract": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false,
"summary": "Abstract configurations supply inherited values and are not registered."
}
},
"extends": [
"terra:Feature"
]
}
}
}
@@ -0,0 +1,207 @@
{
"id": "config-flora",
"docVersion": 1,
"description": "FLORA configurations register layered block structures in the raw structure registry.",
"types": {
"Flora": {
"kind": "object",
"fields": {
"id": {
"schema": {
"kind": "string",
"pattern": "^[a-zA-Z0-9_-]*$"
},
"required": true,
"summary": "Registry identifier; final and not inherited."
},
"rotatable": {
"schema": {
"kind": "type",
"target": "terra:MaterialSet",
"nullable": true
},
"required": false,
"default": [],
"summary": "Block types whose states may be rotated."
},
"physics": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false
},
"ceiling": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false
},
"layers": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "BlockLayer"
}
},
"required": true
},
"layer-distribution": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler"
},
"required": true
}
}
},
"BlockLayer": {
"kind": "object",
"fields": {
"layers": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
]
},
"required": true
},
"materials": {
"schema": {
"kind": "type",
"target": "WeightedBlocks"
},
"required": true
}
}
},
"WeightedBlocks": {
"kind": "oneOf",
"description": "A block state, block-to-weight map, or list of maps. Singleton weights are ignored; all other weights are raw integers.",
"options": [
{
"kind": "type",
"target": "terra:Block"
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:Block"
},
"values": {
"kind": "any",
"name": "Ignored singleton weight"
},
"maxEntries": 1
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:Block"
},
"values": {
"kind": "integer"
},
"minEntries": 2
},
{
"kind": "list",
"element": {
"kind": "oneOf",
"options": [
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:Block"
},
"values": {
"kind": "any",
"name": "Ignored singleton weight"
},
"maxEntries": 1
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:Block"
},
"values": {
"kind": "integer"
},
"minEntries": 2
}
]
},
"maxItems": 1
},
{
"kind": "list",
"element": {
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:Block"
},
"values": {
"kind": "integer"
}
},
"minItems": 2
}
]
}
},
"files": {
"FLORA": {
"kind": "object",
"fields": {
"type": {
"schema": {
"kind": "literal",
"value": "FLORA"
},
"required": true
},
"extends": {
"schema": {
"kind": "list",
"element": {
"kind": "string"
},
"nullable": true
},
"required": false,
"default": [],
"summary": "Parent configuration IDs; non-final fields may be inherited."
},
"abstract": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false,
"summary": "Abstract configurations supply inherited values and are not registered."
}
},
"extends": [
"Flora"
]
}
}
}
@@ -0,0 +1,388 @@
{
"id": "config-locators",
"docVersion": 1,
"description": "Eleven registered vertical locator variants and eight inline block-pattern variants.",
"types": {
"terra:Locator": {
"kind": "union",
"discriminator": "type",
"values": {
"SURFACE": {
"kind": "object",
"fields": {
"range": {
"schema": {
"kind": "type",
"target": "terra:Range"
},
"required": true
}
},
"description": "Finds air above a non-air block within the search range. May return multiple surfaces."
},
"TOP": {
"kind": "object",
"fields": {
"range": {
"schema": {
"kind": "type",
"target": "terra:Range"
},
"required": true
}
},
"description": "Finds air above a non-air block within the search range. Returns only the top result; its implementation starts at range.max inclusively."
},
"RANDOM": {
"kind": "object",
"fields": {
"height": {
"schema": {
"kind": "type",
"target": "terra:Range"
},
"required": true
},
"amount": {
"schema": {
"kind": "type",
"target": "terra:Range"
},
"required": true
},
"salt": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 0
}
},
"description": "Chooses seeded heights using a uniform distribution."
},
"GAUSSIAN_RANDOM": {
"kind": "object",
"fields": {
"height": {
"schema": {
"kind": "type",
"target": "terra:Range"
},
"required": true
},
"amount": {
"schema": {
"kind": "type",
"target": "terra:Range"
},
"required": true
},
"salt": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 0
},
"standard-deviation": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "float"
},
{
"kind": "type",
"target": "terra:Expression"
}
]
},
"required": true
}
},
"description": "Chooses seeded heights using a Gaussian distribution."
},
"PATTERN": {
"kind": "object",
"fields": {
"range": {
"schema": {
"kind": "type",
"target": "terra:Range"
},
"required": true
},
"pattern": {
"schema": {
"kind": "type",
"target": "Pattern"
},
"required": true
}
}
},
"ADJACENT_PATTERN": {
"kind": "object",
"fields": {
"range": {
"schema": {
"kind": "type",
"target": "terra:Range"
},
"required": true
},
"pattern": {
"schema": {
"kind": "type",
"target": "Pattern"
},
"required": true
},
"match-all": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false,
"summary": "Require all four horizontal neighbors instead of at least one."
}
}
},
"SAMPLER": {
"kind": "object",
"fields": {
"samplers": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "terra:NoiseSampler"
}
},
"required": true
}
},
"description": "Each 2D sampler output is floored to a height; results outside the column are discarded."
},
"SAMPLER_3D": {
"kind": "object",
"fields": {
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler"
},
"required": true
}
},
"description": "Accepts each height where the 3D sampler returns a value greater than zero."
},
"AND": {
"kind": "object",
"fields": {
"locators": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "terra:Locator"
},
"minItems": 1
},
"required": true
}
},
"description": "Combines a nonempty list of locator results using AND."
},
"OR": {
"kind": "object",
"fields": {
"locators": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "terra:Locator"
},
"minItems": 1
},
"required": true
}
},
"description": "Combines a nonempty list of locator results using OR."
},
"XOR": {
"kind": "object",
"fields": {
"locators": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "terra:Locator"
},
"minItems": 1
},
"required": true
}
},
"description": "Combines a nonempty list of locator results using XOR."
}
}
},
"Pattern": {
"kind": "union",
"discriminator": "type",
"values": {
"MATCH_AIR": {
"kind": "object",
"fields": {
"offset": {
"schema": {
"kind": "type",
"target": "terra:Range"
},
"required": true
}
},
"description": "Checks air in the relative offset range."
},
"MATCH_SOLID": {
"kind": "object",
"fields": {
"offset": {
"schema": {
"kind": "type",
"target": "terra:Range"
},
"required": true
}
},
"description": "Checks solid blocks in the relative offset range."
},
"MATCH": {
"kind": "object",
"fields": {
"block": {
"schema": {
"kind": "type",
"target": "terra:Block"
},
"required": true
},
"offset": {
"schema": {
"kind": "type",
"target": "terra:Range"
},
"required": true
}
}
},
"MATCH_SET": {
"kind": "object",
"fields": {
"blocks": {
"schema": {
"kind": "type",
"target": "terra:MaterialSet"
},
"required": true
},
"offset": {
"schema": {
"kind": "type",
"target": "terra:Range"
},
"required": true
}
}
},
"AND": {
"kind": "object",
"fields": {
"patterns": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "Pattern"
},
"minItems": 1
},
"required": true
}
},
"description": "Combines a nonempty list of patterns using AND."
},
"OR": {
"kind": "object",
"fields": {
"patterns": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "Pattern"
},
"minItems": 1
},
"required": true
}
},
"description": "Combines a nonempty list of patterns using OR."
},
"XOR": {
"kind": "object",
"fields": {
"patterns": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "Pattern"
},
"minItems": 1
},
"required": true
}
},
"description": "Combines a nonempty list of patterns using XOR."
},
"NOT": {
"kind": "object",
"fields": {
"pattern": {
"schema": {
"kind": "type",
"target": "Pattern"
},
"required": true
}
}
}
}
}
}
}
@@ -0,0 +1,16 @@
{
"id": "config-number-predicate",
"docVersion": 1,
"description": "Loads numeric predicates from Paralithic expression strings.",
"types": {
"NumberPredicate": {
"kind": "expr",
"name": "Paralithic",
"description": "String expression with invocation variable value. Evaluation is true when the numeric result is nonzero. YAML booleans and numeric values are rejected. Uses pack expression parse options, but this loader does not inject pack variables or noise functions.",
"examples": [
"value > 3",
"value >= 0 && value < 1"
]
}
}
}
@@ -0,0 +1,253 @@
{
"id": "config-ore",
"docVersion": 1,
"description": "ORE and SCATTERED_ORE configurations register raw structures. Scattered size remains required despite its field initializer.",
"types": {
"Ore": {
"kind": "object",
"fields": {
"id": {
"schema": {
"kind": "string",
"pattern": "^[a-zA-Z0-9_-]*$"
},
"required": true,
"summary": "Registry identifier; final and not inherited."
},
"material": {
"schema": {
"kind": "type",
"target": "terra:Block"
},
"required": true
},
"material-overrides": {
"schema": {
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:Block"
},
"values": {
"kind": "type",
"target": "terra:Block"
},
"nullable": true
},
"required": false,
"default": {},
"summary": "Override material by replaced block type. Key state properties are reduced to the block type."
},
"replace": {
"schema": {
"kind": "type",
"target": "terra:MaterialSet"
},
"required": true
},
"physics": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false
},
"size": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "float"
},
{
"kind": "type",
"target": "terra:Expression"
}
]
},
"required": true,
"summary": "Ore vein size."
},
"exposed": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "float"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 1,
"summary": "Chance of accepting ore bordering air: 0 rejects, 1 accepts. Source does not enforce a 0\u20131 bound."
}
}
},
"ScatteredOre": {
"kind": "object",
"fields": {
"id": {
"schema": {
"kind": "string",
"pattern": "^[a-zA-Z0-9_-]*$"
},
"required": true,
"summary": "Registry identifier; final and not inherited."
},
"material": {
"schema": {
"kind": "type",
"target": "terra:Block"
},
"required": true
},
"material-overrides": {
"schema": {
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:Block"
},
"values": {
"kind": "type",
"target": "terra:Block"
},
"nullable": true
},
"required": false,
"default": {},
"summary": "Override material by replaced block type. Key state properties are reduced to the block type."
},
"replace": {
"schema": {
"kind": "type",
"target": "terra:MaterialSet"
},
"required": true
},
"physics": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false
},
"size": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
]
},
"required": true,
"summary": "Required size, loaded into both an integer spread and the inherited double vein size. The initializer 7 is not a default."
},
"exposed": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "float"
},
{
"kind": "type",
"target": "terra:Expression"
}
],
"nullable": true
},
"required": false,
"default": 1,
"summary": "Chance of accepting ore bordering air: 0 rejects, 1 accepts. Source does not enforce a 0\u20131 bound."
}
}
}
},
"files": {
"ORE": {
"kind": "object",
"fields": {
"type": {
"schema": {
"kind": "literal",
"value": "ORE"
},
"required": true
},
"extends": {
"schema": {
"kind": "list",
"element": {
"kind": "string"
},
"nullable": true
},
"required": false,
"default": [],
"summary": "Parent configuration IDs; non-final fields may be inherited."
},
"abstract": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false,
"summary": "Abstract configurations supply inherited values and are not registered."
}
},
"extends": [
"Ore"
]
},
"SCATTERED_ORE": {
"kind": "object",
"fields": {
"type": {
"schema": {
"kind": "literal",
"value": "SCATTERED_ORE"
},
"required": true
},
"extends": {
"schema": {
"kind": "list",
"element": {
"kind": "string"
},
"nullable": true
},
"required": false,
"default": [],
"summary": "Parent configuration IDs; non-final fields may be inherited."
},
"abstract": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false,
"summary": "Abstract configurations supply inherited values and are not registered."
}
},
"extends": [
"ScatteredOre"
]
}
}
}
@@ -0,0 +1,204 @@
{
"id": "config-palette",
"docVersion": 1,
"description": "Registered palette configurations and their weighted block layers.",
"types": {
"terra:Palette": {
"kind": "object",
"fields": {
"id": {
"schema": {
"kind": "string",
"pattern": "^[a-zA-Z0-9_-]*$"
},
"required": true,
"summary": "Registry identifier; must be present on this file even when inherited."
},
"layers": {
"schema": {
"kind": "list",
"element": {
"kind": "type",
"target": "PaletteLayer"
}
},
"required": true,
"summary": "Layers in order from the surface inward."
},
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler",
"nullable": true
},
"required": false,
"summary": "Defaults to an internal sampler returning zero."
}
}
},
"terra:PaletteReference": {
"kind": "oneOf",
"options": [
{
"kind": "ref",
"target": "terra:Palette"
}
]
},
"PaletteLayer": {
"kind": "object",
"fields": {
"materials": {
"schema": {
"kind": "type",
"target": "WeightedBlocks"
},
"required": true
},
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler",
"nullable": true
},
"required": false,
"summary": "When absent or YAML null, use the palette-level sampler.",
"default": null
},
"layers": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
]
},
"required": true,
"summary": "Number of depth layers using these materials; the runtime does not enforce a positive minimum."
}
}
},
"WeightedBlocks": {
"kind": "oneOf",
"description": "A block, a block-to-weight map, or a list of such maps. A singleton entry ignores its weight.",
"options": [
{
"kind": "type",
"target": "terra:Block"
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:Block"
},
"values": {
"kind": "any",
"name": "Ignored singleton weight"
},
"maxEntries": 1
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:Block"
},
"values": {
"kind": "integer"
},
"minEntries": 2
},
{
"kind": "list",
"element": {
"kind": "oneOf",
"options": [
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:Block"
},
"values": {
"kind": "any",
"name": "Ignored singleton weight"
},
"maxEntries": 1
},
{
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:Block"
},
"values": {
"kind": "integer"
},
"minEntries": 2
}
]
},
"maxItems": 1
},
{
"kind": "list",
"element": {
"kind": "keyMap",
"keys": {
"kind": "type",
"target": "terra:Block"
},
"values": {
"kind": "integer"
}
},
"minItems": 2
}
]
}
},
"files": {
"PALETTE": {
"kind": "object",
"fields": {
"type": {
"schema": {
"kind": "literal",
"value": "PALETTE"
},
"required": true
},
"extends": {
"schema": {
"kind": "list",
"element": {
"kind": "string"
},
"nullable": true
},
"required": false,
"default": [],
"summary": "Parent configuration identifiers; non-final fields can be inherited."
},
"abstract": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false,
"summary": "Abstract configurations are available for inheritance and are not registered."
}
},
"extends": [
"terra:Palette"
]
}
}
}
@@ -0,0 +1,99 @@
{
"id": "generation-stage-feature",
"docVersion": 1,
"description": "FEATURE generation stages and the per-stage feature lists contributed to biome configurations.",
"types": {
"terra:GenerationStage": {
"kind": "union",
"values": {
"FEATURE": {
"kind": "object",
"fields": {
"id": {
"schema": {
"kind": "string"
},
"required": true,
"summary": "Stage identifier used to load biome features.<id> lists. IDs containing dots are interpreted as nested YAML paths by the runtime."
},
"resolution": {
"schema": {
"kind": "enum",
"values": [
1,
2,
4,
8,
16
],
"nullable": true
},
"required": false,
"default": 4,
"summary": "Biome column sample resolution; must be one of these powers of two."
},
"blend": {
"schema": {
"kind": "object",
"fields": {
"sampler": {
"schema": {
"kind": "type",
"target": "terra:NoiseSampler",
"nullable": true
},
"required": false,
"summary": "Coordinate-warping sampler; defaults to an internal zero sampler."
},
"amplitude": {
"schema": {
"kind": "float",
"nullable": true
},
"required": false,
"default": 0
}
},
"nullable": true
},
"required": false
}
},
"description": "Runs feature placement using biome lists indexed by this stage ID."
}
}
},
"terra:Biome": {
"kind": "object",
"fields": {
"features": {
"schema": {
"kind": "keyMap",
"keys": {
"kind": "string"
},
"values": {
"kind": "list",
"element": {
"kind": "ref",
"target": "terra:Feature"
}
},
"nullable": true
},
"required": false,
"summary": "Maps configured FEATURE stage IDs to ordered feature identifiers. Missing lists default to empty. Only IDs present in pack stages are loaded; v1 cannot derive or restrict these keys. Dotted stage IDs require nested maps and are not fully represented by this keyMap."
}
}
}
},
"files": {
"BIOME": {
"kind": "object",
"fields": {},
"extends": [
"terra:Biome"
]
}
}
}
@@ -0,0 +1,520 @@
{
"id": "library-image",
"docVersion": 1,
"description": "Inline bitmap images, color samplers, two numeric image sampler variants and pack image-cache options.",
"types": {
"Image": {
"kind": "union",
"discriminator": "type",
"values": {
"BITMAP": {
"kind": "object",
"fields": {
"path": {
"schema": {
"kind": "string"
},
"required": true,
"summary": "Path resolved against the pack root and read by ImageIO."
}
}
},
"STITCHED_BITMAP": {
"kind": "object",
"fields": {
"path-format": {
"schema": {
"kind": "string",
"pattern": "^(?=[\\s\\S]*\\{row\\})(?=[\\s\\S]*\\{column\\})[\\s\\S]*$"
},
"required": true,
"summary": "Must contain {row} and {column}; the first occurrence of each is substituted."
},
"rows": {
"schema": {
"kind": "integer",
"minimum": 1
},
"required": true
},
"columns": {
"schema": {
"kind": "integer",
"minimum": 1
},
"required": true
},
"zero-indexed": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false,
"summary": "Use tile indices starting at 0 rather than 1."
}
}
}
}
},
"ColorSampler": {
"kind": "union",
"discriminator": "type",
"values": {
"COLOR": {
"kind": "object",
"fields": {
"color": {
"schema": {
"kind": "type",
"target": "Color"
},
"required": true
}
}
},
"SINGLE_IMAGE": {
"kind": "object",
"fields": {
"image": {
"schema": {
"kind": "type",
"target": "Image"
},
"required": true
},
"align": {
"schema": {
"kind": "enum",
"values": [
"NONE",
"CENTER"
],
"nullable": true
},
"required": false,
"default": "NONE"
},
"outside-sampler": {
"schema": {
"kind": "type",
"target": "ColorSampler"
},
"required": true,
"summary": "Required fallback sampler for positions outside the image."
}
}
},
"TILED_IMAGE": {
"kind": "object",
"fields": {
"image": {
"schema": {
"kind": "type",
"target": "Image"
},
"required": true
},
"align": {
"schema": {
"kind": "enum",
"values": [
"NONE",
"CENTER"
],
"nullable": true
},
"required": false,
"default": "NONE"
}
}
},
"ROTATE": {
"kind": "object",
"fields": {
"color-sampler": {
"schema": {
"kind": "type",
"target": "ColorSampler"
},
"required": true
},
"angle": {
"schema": {
"kind": "float"
},
"required": true,
"summary": "Rotation angle in degrees."
}
}
},
"TRANSLATE": {
"kind": "object",
"fields": {
"color-sampler": {
"schema": {
"kind": "type",
"target": "ColorSampler"
},
"required": true
},
"x": {
"schema": {
"kind": "integer"
},
"required": true
},
"z": {
"schema": {
"kind": "integer"
},
"required": true
}
}
}
}
},
"Color": {
"kind": "string",
"minLength": 1,
"description": "Quoted color string: RRGGBB or AARRGGBB hex, optionally prefixed with #; or comma-separated red,green,blue / alpha,red,green,blue channels. Numeric channels use Integer.decode (decimal, hexadecimal or octal) and must be 0\u2013255.",
"examples": [
"#ff0000",
"80ff0000",
"255,0,0",
"128,255,0,0"
]
},
"terra:NoiseSampler": {
"kind": "union",
"discriminator": "type",
"values": {
"CHANNEL": {
"kind": "object",
"fields": {
"color-sampler": {
"schema": {
"kind": "type",
"target": "ColorSampler"
},
"required": true
},
"channel": {
"schema": {
"kind": "enum",
"values": [
"RED",
"GREEN",
"BLUE",
"GRAYSCALE",
"ALPHA"
]
},
"required": true
},
"normalize": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": true,
"summary": "Normalize output into [-1, 1] instead of channel values."
},
"premultiply": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false,
"summary": "Multiply RGB by alpha before reading the channel."
}
}
},
"DISTANCE_TRANSFORM": {
"kind": "object",
"fields": {
"image": {
"schema": {
"kind": "type",
"target": "Image"
},
"required": true
},
"threshold": {
"schema": {
"kind": "integer",
"nullable": true
},
"required": false,
"default": 127,
"summary": "Channel threshold used by binary cost functions."
},
"clamp-to-max-edge": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false
},
"channel": {
"schema": {
"kind": "enum",
"values": [
"RED",
"GREEN",
"BLUE",
"GRAYSCALE",
"ALPHA"
],
"nullable": true
},
"required": false,
"default": "GRAYSCALE"
},
"cost-function": {
"schema": {
"kind": "enum",
"values": [
"Channel",
"Threshold",
"ThresholdEdge",
"ThresholdEdgeSigned"
],
"nullable": true
},
"required": false,
"default": "Channel"
},
"invert-threshold": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false
},
"normalization": {
"schema": {
"kind": "enum",
"values": [
"None",
"Linear",
"SmoothPreserveZero"
],
"nullable": true
},
"required": false,
"default": "None"
}
}
}
}
},
"config-noise-function:DimensionedSampler": {
"kind": "union",
"discriminator": "type",
"values": {
"CHANNEL": {
"kind": "object",
"fields": {
"color-sampler": {
"schema": {
"kind": "type",
"target": "ColorSampler"
},
"required": true
},
"channel": {
"schema": {
"kind": "enum",
"values": [
"RED",
"GREEN",
"BLUE",
"GRAYSCALE",
"ALPHA"
]
},
"required": true
},
"normalize": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": true,
"summary": "Normalize output into [-1, 1] instead of channel values."
},
"premultiply": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false,
"summary": "Multiply RGB by alpha before reading the channel."
},
"dimensions": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
]
},
"required": true,
"summary": "Required by the expression sampler wrapper; 2 selects 2D, other integers select 3D."
}
}
},
"DISTANCE_TRANSFORM": {
"kind": "object",
"fields": {
"image": {
"schema": {
"kind": "type",
"target": "Image"
},
"required": true
},
"threshold": {
"schema": {
"kind": "integer",
"nullable": true
},
"required": false,
"default": 127,
"summary": "Channel threshold used by binary cost functions."
},
"clamp-to-max-edge": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false
},
"channel": {
"schema": {
"kind": "enum",
"values": [
"RED",
"GREEN",
"BLUE",
"GRAYSCALE",
"ALPHA"
],
"nullable": true
},
"required": false,
"default": "GRAYSCALE"
},
"cost-function": {
"schema": {
"kind": "enum",
"values": [
"Channel",
"Threshold",
"ThresholdEdge",
"ThresholdEdgeSigned"
],
"nullable": true
},
"required": false,
"default": "Channel"
},
"invert-threshold": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false
},
"normalization": {
"schema": {
"kind": "enum",
"values": [
"None",
"Linear",
"SmoothPreserveZero"
],
"nullable": true
},
"required": false,
"default": "None"
},
"dimensions": {
"schema": {
"kind": "oneOf",
"options": [
{
"kind": "integer"
},
{
"kind": "type",
"target": "terra:Expression"
}
]
},
"required": true,
"summary": "Required by the expression sampler wrapper; 2 selects 2D, other integers select 3D."
}
}
}
}
}
},
"files": {
"pack.yml": {
"kind": "object",
"fields": {
"images": {
"schema": {
"kind": "object",
"fields": {
"cache": {
"schema": {
"kind": "object",
"fields": {
"load-on-use": {
"schema": {
"kind": "boolean",
"nullable": true
},
"required": false,
"default": false,
"summary": "Load images when first used rather than during pack loading."
},
"timeout": {
"schema": {
"kind": "integer",
"nullable": true
},
"required": false,
"default": 0,
"summary": "Seconds after last use before unloading; values <= 0 keep images cached."
}
},
"nullable": true
},
"required": false
}
},
"nullable": true
},
"required": false
}
}
}
}
}
@@ -0,0 +1,26 @@
{
"id": "locator-slant-noise-3d",
"docVersion": 1,
"description": "SLANT locator tests the noise generator's slant value with a numeric predicate.",
"types": {
"terra:Locator": {
"kind": "union",
"discriminator": "type",
"values": {
"SLANT": {
"kind": "object",
"fields": {
"condition": {
"schema": {
"kind": "type",
"target": "config-number-predicate:NumberPredicate"
},
"required": true
}
},
"description": "Requires a numeric predicate loader and a world using NoiseChunkGenerator3D; sampling casts the world generator to that implementation."
}
}
}
}
}
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-2025 Polyhedral Development
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,8 @@
version = version("1.0.0")
dependencies {
compileOnlyApi(project(":common:addons:manifest-addon-loader"))
testImplementation(project(":common:implementation:base"))
testImplementation(project(":common:addons:manifest-addon-loader"))
}
@@ -0,0 +1,6 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.world.attribute.RawValue;
public record AmbientParticle(RawValue particle, float probability) { }
@@ -0,0 +1,18 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.List;
import java.util.Optional;
public record AmbientSounds(Optional<SoundRef> loop, Optional<Mood> mood, List<Additions> additions) {
public static final AmbientSounds EMPTY = new AmbientSounds(Optional.empty(), Optional.empty(), List.of());
public AmbientSounds {
additions = List.copyOf(additions);
}
public record Mood(SoundRef sound, int tickDelay, int blockSearchExtent, double offset) { }
public record Additions(SoundRef sound, double tickChance) { }
}
@@ -0,0 +1,8 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Optional;
public record BackgroundMusic(Optional<Music> defaultMusic, Optional<Music> creative, Optional<Music> underwater) {
public static final BackgroundMusic EMPTY = new BackgroundMusic(Optional.empty(), Optional.empty(), Optional.empty());
}
@@ -0,0 +1,26 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Optional;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
import com.dfsek.terra.api.world.attribute.RawValue;
public record BedRule(Rule canSleep, Rule canSetSpawn, boolean destroyOnUse, boolean destroyOnLeave, Optional<RawValue> errorMessage) {
public enum Rule implements StringIdentifiable {
ALWAYS("always"),
WHEN_DARK("when_dark"),
NEVER("never");
private final String id;
Rule(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
}
@@ -0,0 +1,20 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum CardinalLight implements StringIdentifiable {
DEFAULT("default"),
NETHER("nether");
private final String id;
CardinalLight(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,21 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum GrassColorModifier implements StringIdentifiable {
NONE("none"),
DARK_FOREST("dark_forest"),
SWAMP("swamp");
private final String id;
GrassColorModifier(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,15 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Optional;
import java.util.OptionalInt;
import com.dfsek.terra.api.world.attribute.RawValue;
public record IntProviderValue(OptionalInt constant, Optional<RawValue> provider) {
public IntProviderValue {
if(constant.isPresent() == provider.isPresent()) {
throw new IllegalArgumentException("an int provider value needs exactly one of a constant and a provider");
}
}
}
@@ -0,0 +1,159 @@
package com.dfsek.terra.addons.attribute.minecraft;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeType;
import com.dfsek.terra.api.world.attribute.AttributeTypes;
import com.dfsek.terra.api.world.attribute.RawValue;
import com.dfsek.terra.api.world.attribute.value.Color;
import com.dfsek.terra.api.world.attribute.value.TriState;
public final class MinecraftAttributeTable {
private static final RawValue NO_SLEEP_MESSAGE = new RawValue(Map.of("translate", "block.minecraft.bed.no_sleep"));
private static final BedRule CAN_SLEEP_WHEN_DARK = new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.ALWAYS, false, false,
Optional.of(NO_SLEEP_MESSAGE));
private static final BedRule DESTROY_ON_LEAVE = new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.NEVER, false, true,
Optional.of(NO_SLEEP_MESSAGE));
private static final IntProviderValue MONSTER_SPAWN_LIGHT_LEVEL = new IntProviderValue(OptionalInt.empty(), Optional.of(
new RawValue(Map.of("type", "minecraft:uniform", "min_inclusive", 0, "max_inclusive", 7))));
private MinecraftAttributeTable() { }
public static List<Attribute<?>> create(AttributeHandle handle) {
AttributeTypes t = handle.types();
MinecraftAttributeTypes m = new MinecraftAttributeTypes(handle);
AttributeType<TemperatureModifier> temperatureModifier = t.enumType("temperature_modifier", TemperatureModifier.class);
AttributeType<GrassColorModifier> grassColorModifier = t.enumType("grass_color_modifier", GrassColorModifier.class);
AttributeType<Skybox> skybox = t.enumType("skybox", Skybox.class);
AttributeType<CardinalLight> cardinalLight = t.enumType("cardinal_light", CardinalLight.class);
Table table = new Table(handle);
table.row(MinecraftAttributes.VISUAL_FOG_COLOR, t.rgbColor(), Color.rgb(0x000000));
table.row(MinecraftAttributes.VISUAL_FOG_START_DISTANCE, t.floatType(), 0f);
table.row(MinecraftAttributes.VISUAL_FOG_END_DISTANCE, t.floatType(), 1024f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_SKY_FOG_END_DISTANCE, t.floatType(), 512f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_CLOUD_FOG_END_DISTANCE, t.floatType(), 2048f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_WATER_FOG_COLOR, t.rgbColor(), Color.rgb(0x050533));
table.row(MinecraftAttributes.VISUAL_WATER_FOG_START_DISTANCE, t.floatType(), -8f);
table.row(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE, t.floatType(), 96f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_SKY_COLOR, t.rgbColor(), Color.rgb(0x000000));
table.row(MinecraftAttributes.VISUAL_SUNRISE_SUNSET_COLOR, t.argbColor(), Color.argb(0));
table.row(MinecraftAttributes.VISUAL_CLOUD_COLOR, t.argbColor(), Color.argb(0));
table.row(MinecraftAttributes.VISUAL_CLOUD_HEIGHT, t.floatType(), 192.33f);
table.row(MinecraftAttributes.VISUAL_SUN_ANGLE, t.angleDegrees(), 0f);
table.row(MinecraftAttributes.VISUAL_MOON_ANGLE, t.angleDegrees(), 0f);
table.row(MinecraftAttributes.VISUAL_STAR_ANGLE, t.angleDegrees(), 0f);
table.row(MinecraftAttributes.VISUAL_MOON_PHASE, m.moonPhase(), MoonPhase.FULL_MOON);
table.row(MinecraftAttributes.VISUAL_STAR_BRIGHTNESS, t.floatType(), 0f).range(0, 1);
table.row(MinecraftAttributes.VISUAL_BLOCK_LIGHT_TINT, t.rgbColor(), Color.rgb(0xffd88c));
table.row(MinecraftAttributes.VISUAL_SKY_LIGHT_COLOR, t.rgbColor(), Color.rgb(0xffffff));
table.row(MinecraftAttributes.VISUAL_SKY_LIGHT_FACTOR, t.floatType(), 1f).range(0, 1);
table.row(MinecraftAttributes.VISUAL_NIGHT_VISION_COLOR, t.rgbColor(), Color.rgb(0x999999));
table.row(MinecraftAttributes.VISUAL_AMBIENT_LIGHT_COLOR, t.rgbColor(), Color.rgb(0x000000));
table.row(MinecraftAttributes.VISUAL_DEFAULT_DRIPSTONE_PARTICLE, m.particle(),
new RawValue(Map.of("type", "minecraft:dripping_dripstone_water")));
table.row(MinecraftAttributes.VISUAL_AMBIENT_PARTICLES, m.ambientParticles(), List.of());
table.row(MinecraftAttributes.AUDIO_BACKGROUND_MUSIC, m.backgroundMusic(), BackgroundMusic.EMPTY);
table.row(MinecraftAttributes.AUDIO_MUSIC_VOLUME, t.floatType(), 1f).range(0, 1);
table.row(MinecraftAttributes.AUDIO_AMBIENT_SOUNDS, m.ambientSounds(), AmbientSounds.EMPTY);
table.row(MinecraftAttributes.AUDIO_FIREFLY_BUSH_SOUNDS, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_SKY_LIGHT_LEVEL, t.floatType(), 15f).range(0, 15).packOnly();
table.row(MinecraftAttributes.GAMEPLAY_CAN_START_RAID, t.booleanType(), true);
table.row(MinecraftAttributes.GAMEPLAY_WATER_EVAPORATES, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_BED_RULE, m.bedRule(), CAN_SLEEP_WHEN_DARK);
table.row(MinecraftAttributes.GAMEPLAY_STRAW_BED_RULE, m.bedRule(), DESTROY_ON_LEAVE);
table.row(MinecraftAttributes.GAMEPLAY_RESPAWN_ANCHOR_WORKS, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_NETHER_PORTAL_SPAWNS_PIGLIN, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_FAST_LAVA, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.GAMEPLAY_INCREASED_FIRE_BURNOUT, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_EYEBLOSSOM_OPEN, t.triState(), TriState.DEFAULT);
table.row(MinecraftAttributes.GAMEPLAY_TURTLE_EGG_HATCH_CHANCE, t.floatType(), 0.002f).range(0, 1);
table.row(MinecraftAttributes.GAMEPLAY_PIGLINS_ZOMBIFY, t.booleanType(), true);
table.row(MinecraftAttributes.GAMEPLAY_SNOW_GOLEM_MELTS, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_CREAKING_ACTIVE, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_SURFACE_SLIME_SPAWN_CHANCE, t.floatType(), 0f).range(0, 1);
table.row(MinecraftAttributes.GAMEPLAY_CAT_WAKING_UP_GIFT_CHANCE, t.floatType(), 0f).range(0, 1);
table.row(MinecraftAttributes.GAMEPLAY_BEES_STAY_IN_HIVE, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_MONSTERS_BURN, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_CAN_PILLAGER_PATROL_SPAWN, t.booleanType(), true);
table.row(MinecraftAttributes.GAMEPLAY_NATURAL_MOB_SPAWNS, m.mobSpawnSettings(), MobSpawnSettings.EMPTY);
table.row(MinecraftAttributes.GAMEPLAY_CREATURE_WORLD_GEN_SPAWN_PROBABILITY, t.floatType(), 0.1f).range(0, 0.9999999);
table.row(MinecraftAttributes.GAMEPLAY_VILLAGER_ACTIVITY, m.identifier(), RegistryKey.parse("minecraft:idle"));
table.row(MinecraftAttributes.GAMEPLAY_BABY_VILLAGER_ACTIVITY, m.identifier(), RegistryKey.parse("minecraft:idle"));
table.row(MinecraftAttributes.BIOME_HAS_PRECIPITATION, t.booleanType(), true);
table.row(MinecraftAttributes.BIOME_TEMPERATURE, t.floatType(), 0.5f);
table.row(MinecraftAttributes.BIOME_TEMPERATURE_MODIFIER, temperatureModifier, TemperatureModifier.NONE);
table.row(MinecraftAttributes.BIOME_DOWNFALL, t.floatType(), 0.5f);
table.row(MinecraftAttributes.BIOME_WATER_COLOR, t.rgbColor(), Color.rgb(0x3f76e4));
table.row(MinecraftAttributes.BIOME_FOLIAGE_COLOR, t.rgbColor(), null);
table.row(MinecraftAttributes.BIOME_DRY_FOLIAGE_COLOR, t.rgbColor(), null);
table.row(MinecraftAttributes.BIOME_GRASS_COLOR, t.rgbColor(), null);
table.row(MinecraftAttributes.BIOME_GRASS_COLOR_MODIFIER, grassColorModifier, GrassColorModifier.NONE);
table.row(MinecraftAttributes.BIOME_VILLAGER_TYPE, m.identifier(), RegistryKey.parse("minecraft:plains"));
table.row(MinecraftAttributes.DIMENSION_HAS_FIXED_TIME, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.DIMENSION_HAS_SKYLIGHT, t.booleanType(), true).packOnly();
table.row(MinecraftAttributes.DIMENSION_HAS_CEILING, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.DIMENSION_HAS_ENDER_DRAGON_FIGHT, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.DIMENSION_COORDINATE_SCALE, t.floatType(), 1f).packOnly().range(1e-5, 3e7);
table.row(MinecraftAttributes.DIMENSION_MIN_Y, t.integerOverrideOnly(), -64).packOnly().range(-2032, 2031).multipleOf(16);
table.row(MinecraftAttributes.DIMENSION_HEIGHT, t.integerOverrideOnly(), 384).packOnly().range(16, 4064).multipleOf(16);
table.row(MinecraftAttributes.DIMENSION_LOGICAL_HEIGHT, t.integerOverrideOnly(), 384).packOnly().range(0, 4064);
table.row(MinecraftAttributes.DIMENSION_INFINIBURN, m.identifierOrTag(),
Either.right(TagKey.parse("#minecraft:infiniburn_overworld"))).packOnly();
table.row(MinecraftAttributes.DIMENSION_AMBIENT_LIGHT, t.floatType(), 0f).packOnly();
table.row(MinecraftAttributes.DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL, m.intProvider(), MONSTER_SPAWN_LIGHT_LEVEL).packOnly();
table.row(MinecraftAttributes.DIMENSION_MONSTER_SPAWN_BLOCK_LIGHT_LIMIT, t.integer(), 0).packOnly().range(0, 15);
table.row(MinecraftAttributes.DIMENSION_SKYBOX, skybox, Skybox.OVERWORLD).packOnly();
table.row(MinecraftAttributes.DIMENSION_CARDINAL_LIGHT, cardinalLight, CardinalLight.DEFAULT).packOnly();
table.row(MinecraftAttributes.DIMENSION_DEFAULT_CLOCK, m.identifier(), RegistryKey.parse("minecraft:overworld")).packOnly();
table.row(MinecraftAttributes.WORLD_SEA_LEVEL, t.integer(), 63).packOnly();
table.row(MinecraftAttributes.WORLD_SPAWN_HEIGHT, t.integer(), 64).packOnly();
table.row(MinecraftAttributes.WORLD_MOB_GENERATION, t.booleanType(), true).packOnly();
List<Attribute<?>> attributes = table.build();
if(!attributes.stream().map(Attribute::key).toList().equals(MinecraftAttributes.all())) {
throw new IllegalStateException("the Minecraft attribute table does not match MinecraftAttributes.all()");
}
return attributes;
}
private static final class Table {
private final AttributeHandle handle;
private final List<Attribute.Builder<?>> rows = new ArrayList<>();
private Table(AttributeHandle handle) {
this.handle = handle;
}
private <T> Attribute.Builder<T> row(AttributeKey<T> key, AttributeType<T> type, @Nullable T defaultValue) {
MinecraftIds.requireLowerCase(key.getRegistryKey());
Attribute.Builder<T> builder = handle.attributeBuilder(key, type, defaultValue);
rows.add(builder);
return builder;
}
private List<Attribute<?>> build() {
List<Attribute<?>> built = new ArrayList<>(rows.size());
for(Attribute.Builder<?> row : rows) built.add(row.build());
return List.copyOf(built);
}
}
}
@@ -0,0 +1,111 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeType;
import com.dfsek.terra.api.world.attribute.Operation;
import com.dfsek.terra.api.world.attribute.RawValue;
public final class MinecraftAttributeTypes {
private final AttributeType<MoonPhase> moonPhase;
private final AttributeType<BedRule> bedRule;
private final AttributeType<RawValue> particle;
private final AttributeType<List<AmbientParticle>> ambientParticles;
private final AttributeType<BackgroundMusic> backgroundMusic;
private final AttributeType<AmbientSounds> ambientSounds;
private final AttributeType<MobSpawnSettings> mobSpawnSettings;
private final AttributeType<RegistryKey> identifier;
private final AttributeType<Either<RegistryKey, TagKey>> identifierOrTag;
private final AttributeType<IntProviderValue> intProvider;
public MinecraftAttributeTypes(AttributeHandle handle) {
MinecraftCodecs codecs = new MinecraftCodecs(handle);
this.moonPhase = handle.typeBuilder("moon_phase", codecs.moonPhase()).build();
this.bedRule = handle.typeBuilder("bed_rule", codecs.bedRule()).build();
this.particle = handle.typeBuilder("particle", codecs.particle()).build();
this.ambientParticles = handle.typeBuilder("ambient_particles", codecs.ambientParticles())
.op(Operation.APPEND, codecs.ambientParticles(), MinecraftAttributeTypes::append)
.composable(Operation.APPEND, MinecraftAttributeTypes::append)
.build();
this.backgroundMusic = handle.typeBuilder("background_music", codecs.backgroundMusic()).build();
this.ambientSounds = handle.typeBuilder("ambient_sounds", codecs.ambientSounds()).build();
this.mobSpawnSettings = handle.typeBuilder("mob_spawn_settings", codecs.mobSpawnSettings())
.op(Operation.OVERLAY, codecs.mobSpawnSettings(), MinecraftAttributeTypes::overlay)
.composable(Operation.OVERLAY, MinecraftAttributeTypes::overlay)
.build();
this.identifier = handle.typeBuilder("identifier", codecs.identifier()).build();
this.identifierOrTag = handle.typeBuilder("identifier_or_tag", codecs.identifierOrTag()).build();
this.intProvider = handle.typeBuilder("int_provider", codecs.intProvider()).build();
}
public AttributeType<MoonPhase> moonPhase() {
return moonPhase;
}
public AttributeType<BedRule> bedRule() {
return bedRule;
}
public AttributeType<RawValue> particle() {
return particle;
}
public AttributeType<List<AmbientParticle>> ambientParticles() {
return ambientParticles;
}
public AttributeType<BackgroundMusic> backgroundMusic() {
return backgroundMusic;
}
public AttributeType<AmbientSounds> ambientSounds() {
return ambientSounds;
}
public AttributeType<MobSpawnSettings> mobSpawnSettings() {
return mobSpawnSettings;
}
public AttributeType<RegistryKey> identifier() {
return identifier;
}
public AttributeType<Either<RegistryKey, TagKey>> identifierOrTag() {
return identifierOrTag;
}
public AttributeType<IntProviderValue> intProvider() {
return intProvider;
}
private static List<AmbientParticle> append(List<AmbientParticle> s, List<AmbientParticle> a) {
if(a.isEmpty()) return s;
if(s.isEmpty()) return a;
List<AmbientParticle> out = new ArrayList<>(s.size() + a.size());
out.addAll(s);
out.addAll(a);
return List.copyOf(out);
}
private static MobSpawnSettings overlay(MobSpawnSettings first, MobSpawnSettings second) {
if(first.spawnsByCategory().isEmpty() && first.spawnCosts().isEmpty()) return second;
if(second.spawnsByCategory().isEmpty() && second.spawnCosts().isEmpty()) return first;
if(second.spawnsByCategory().keySet().containsAll(first.spawnsByCategory().keySet())
&& second.spawnCosts().keySet().containsAll(first.spawnCosts().keySet())) {
return second;
}
Map<String, List<MobSpawnSettings.Spawner>> categories = new LinkedHashMap<>(first.spawnsByCategory());
categories.putAll(second.spawnsByCategory());
Map<RegistryKey, MobSpawnSettings.Cost> costs = new LinkedHashMap<>(first.spawnCosts());
costs.putAll(second.spawnCosts());
return new MobSpawnSettings(categories, costs);
}
}
@@ -0,0 +1,128 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.ArrayList;
import java.util.List;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.RawValue;
import com.dfsek.terra.api.world.attribute.value.Color;
import com.dfsek.terra.api.world.attribute.value.TriState;
public final class MinecraftAttributes {
private static List<AttributeKey<?>> building = new ArrayList<>();
public static final AttributeKey<Color> VISUAL_FOG_COLOR = vanilla("visual/fog_color");
public static final AttributeKey<Float> VISUAL_FOG_START_DISTANCE = vanilla("visual/fog_start_distance");
public static final AttributeKey<Float> VISUAL_FOG_END_DISTANCE = vanilla("visual/fog_end_distance");
public static final AttributeKey<Float> VISUAL_SKY_FOG_END_DISTANCE = vanilla("visual/sky_fog_end_distance");
public static final AttributeKey<Float> VISUAL_CLOUD_FOG_END_DISTANCE = vanilla("visual/cloud_fog_end_distance");
public static final AttributeKey<Color> VISUAL_WATER_FOG_COLOR = vanilla("visual/water_fog_color");
public static final AttributeKey<Float> VISUAL_WATER_FOG_START_DISTANCE = vanilla("visual/water_fog_start_distance");
public static final AttributeKey<Float> VISUAL_WATER_FOG_END_DISTANCE = vanilla("visual/water_fog_end_distance");
public static final AttributeKey<Color> VISUAL_SKY_COLOR = vanilla("visual/sky_color");
public static final AttributeKey<Color> VISUAL_SUNRISE_SUNSET_COLOR = vanilla("visual/sunrise_sunset_color");
public static final AttributeKey<Color> VISUAL_CLOUD_COLOR = vanilla("visual/cloud_color");
public static final AttributeKey<Float> VISUAL_CLOUD_HEIGHT = vanilla("visual/cloud_height");
public static final AttributeKey<Float> VISUAL_SUN_ANGLE = vanilla("visual/sun_angle");
public static final AttributeKey<Float> VISUAL_MOON_ANGLE = vanilla("visual/moon_angle");
public static final AttributeKey<Float> VISUAL_STAR_ANGLE = vanilla("visual/star_angle");
public static final AttributeKey<MoonPhase> VISUAL_MOON_PHASE = vanilla("visual/moon_phase");
public static final AttributeKey<Float> VISUAL_STAR_BRIGHTNESS = vanilla("visual/star_brightness");
public static final AttributeKey<Color> VISUAL_BLOCK_LIGHT_TINT = vanilla("visual/block_light_tint");
public static final AttributeKey<Color> VISUAL_SKY_LIGHT_COLOR = vanilla("visual/sky_light_color");
public static final AttributeKey<Float> VISUAL_SKY_LIGHT_FACTOR = vanilla("visual/sky_light_factor");
public static final AttributeKey<Color> VISUAL_NIGHT_VISION_COLOR = vanilla("visual/night_vision_color");
public static final AttributeKey<Color> VISUAL_AMBIENT_LIGHT_COLOR = vanilla("visual/ambient_light_color");
public static final AttributeKey<RawValue> VISUAL_DEFAULT_DRIPSTONE_PARTICLE = vanilla("visual/default_dripstone_particle");
public static final AttributeKey<List<AmbientParticle>> VISUAL_AMBIENT_PARTICLES = vanilla("visual/ambient_particles");
public static final AttributeKey<BackgroundMusic> AUDIO_BACKGROUND_MUSIC = vanilla("audio/background_music");
public static final AttributeKey<Float> AUDIO_MUSIC_VOLUME = vanilla("audio/music_volume");
public static final AttributeKey<AmbientSounds> AUDIO_AMBIENT_SOUNDS = vanilla("audio/ambient_sounds");
public static final AttributeKey<Boolean> AUDIO_FIREFLY_BUSH_SOUNDS = vanilla("audio/firefly_bush_sounds");
public static final AttributeKey<Float> GAMEPLAY_SKY_LIGHT_LEVEL = vanilla("gameplay/sky_light_level");
public static final AttributeKey<Boolean> GAMEPLAY_CAN_START_RAID = vanilla("gameplay/can_start_raid");
public static final AttributeKey<Boolean> GAMEPLAY_WATER_EVAPORATES = vanilla("gameplay/water_evaporates");
public static final AttributeKey<BedRule> GAMEPLAY_BED_RULE = vanilla("gameplay/bed_rule");
public static final AttributeKey<BedRule> GAMEPLAY_STRAW_BED_RULE = vanilla("gameplay/straw_bed_rule");
public static final AttributeKey<Boolean> GAMEPLAY_RESPAWN_ANCHOR_WORKS = vanilla("gameplay/respawn_anchor_works");
public static final AttributeKey<Boolean> GAMEPLAY_NETHER_PORTAL_SPAWNS_PIGLIN = vanilla("gameplay/nether_portal_spawns_piglin");
public static final AttributeKey<Boolean> GAMEPLAY_FAST_LAVA = vanilla("gameplay/fast_lava");
public static final AttributeKey<Boolean> GAMEPLAY_INCREASED_FIRE_BURNOUT = vanilla("gameplay/increased_fire_burnout");
public static final AttributeKey<TriState> GAMEPLAY_EYEBLOSSOM_OPEN = vanilla("gameplay/eyeblossom_open");
public static final AttributeKey<Float> GAMEPLAY_TURTLE_EGG_HATCH_CHANCE = vanilla("gameplay/turtle_egg_hatch_chance");
public static final AttributeKey<Boolean> GAMEPLAY_PIGLINS_ZOMBIFY = vanilla("gameplay/piglins_zombify");
public static final AttributeKey<Boolean> GAMEPLAY_SNOW_GOLEM_MELTS = vanilla("gameplay/snow_golem_melts");
public static final AttributeKey<Boolean> GAMEPLAY_CREAKING_ACTIVE = vanilla("gameplay/creaking_active");
public static final AttributeKey<Float> GAMEPLAY_SURFACE_SLIME_SPAWN_CHANCE = vanilla("gameplay/surface_slime_spawn_chance");
public static final AttributeKey<Float> GAMEPLAY_CAT_WAKING_UP_GIFT_CHANCE = vanilla("gameplay/cat_waking_up_gift_chance");
public static final AttributeKey<Boolean> GAMEPLAY_BEES_STAY_IN_HIVE = vanilla("gameplay/bees_stay_in_hive");
public static final AttributeKey<Boolean> GAMEPLAY_MONSTERS_BURN = vanilla("gameplay/monsters_burn");
public static final AttributeKey<Boolean> GAMEPLAY_CAN_PILLAGER_PATROL_SPAWN = vanilla("gameplay/can_pillager_patrol_spawn");
public static final AttributeKey<MobSpawnSettings> GAMEPLAY_NATURAL_MOB_SPAWNS = vanilla("gameplay/natural_mob_spawns");
public static final AttributeKey<Float> GAMEPLAY_CREATURE_WORLD_GEN_SPAWN_PROBABILITY =
vanilla("gameplay/creature_world_gen_spawn_probability");
public static final AttributeKey<RegistryKey> GAMEPLAY_VILLAGER_ACTIVITY = vanilla("gameplay/villager_activity");
public static final AttributeKey<RegistryKey> GAMEPLAY_BABY_VILLAGER_ACTIVITY = vanilla("gameplay/baby_villager_activity");
public static final AttributeKey<Boolean> BIOME_HAS_PRECIPITATION = terra("biome/has_precipitation");
public static final AttributeKey<Float> BIOME_TEMPERATURE = terra("biome/temperature");
public static final AttributeKey<TemperatureModifier> BIOME_TEMPERATURE_MODIFIER = terra("biome/temperature_modifier");
public static final AttributeKey<Float> BIOME_DOWNFALL = terra("biome/downfall");
public static final AttributeKey<Color> BIOME_WATER_COLOR = terra("biome/water_color");
public static final AttributeKey<Color> BIOME_FOLIAGE_COLOR = terra("biome/foliage_color");
public static final AttributeKey<Color> BIOME_DRY_FOLIAGE_COLOR = terra("biome/dry_foliage_color");
public static final AttributeKey<Color> BIOME_GRASS_COLOR = terra("biome/grass_color");
public static final AttributeKey<GrassColorModifier> BIOME_GRASS_COLOR_MODIFIER = terra("biome/grass_color_modifier");
public static final AttributeKey<RegistryKey> BIOME_VILLAGER_TYPE = terra("biome/villager_type");
public static final AttributeKey<Boolean> DIMENSION_HAS_FIXED_TIME = terra("dimension/has_fixed_time");
public static final AttributeKey<Boolean> DIMENSION_HAS_SKYLIGHT = terra("dimension/has_skylight");
public static final AttributeKey<Boolean> DIMENSION_HAS_CEILING = terra("dimension/has_ceiling");
public static final AttributeKey<Boolean> DIMENSION_HAS_ENDER_DRAGON_FIGHT = terra("dimension/has_ender_dragon_fight");
public static final AttributeKey<Float> DIMENSION_COORDINATE_SCALE = terra("dimension/coordinate_scale");
public static final AttributeKey<Integer> DIMENSION_MIN_Y = terra("dimension/min_y");
public static final AttributeKey<Integer> DIMENSION_HEIGHT = terra("dimension/height");
public static final AttributeKey<Integer> DIMENSION_LOGICAL_HEIGHT = terra("dimension/logical_height");
public static final AttributeKey<Either<RegistryKey, TagKey>> DIMENSION_INFINIBURN = terra("dimension/infiniburn");
public static final AttributeKey<Float> DIMENSION_AMBIENT_LIGHT = terra("dimension/ambient_light");
public static final AttributeKey<IntProviderValue> DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL = terra("dimension/monster_spawn_light_level");
public static final AttributeKey<Integer> DIMENSION_MONSTER_SPAWN_BLOCK_LIGHT_LIMIT =
terra("dimension/monster_spawn_block_light_limit");
public static final AttributeKey<Skybox> DIMENSION_SKYBOX = terra("dimension/skybox");
public static final AttributeKey<CardinalLight> DIMENSION_CARDINAL_LIGHT = terra("dimension/cardinal_light");
public static final AttributeKey<RegistryKey> DIMENSION_DEFAULT_CLOCK = terra("dimension/default_clock");
public static final AttributeKey<Integer> WORLD_SEA_LEVEL = terra("world/sea_level");
public static final AttributeKey<Integer> WORLD_SPAWN_HEIGHT = terra("world/spawn_height");
public static final AttributeKey<Boolean> WORLD_MOB_GENERATION = terra("world/mob_generation");
private static final List<AttributeKey<?>> VIEW = seal();
private MinecraftAttributes() { }
public static List<AttributeKey<?>> all() {
return VIEW;
}
private static List<AttributeKey<?>> seal() {
List<AttributeKey<?>> view = List.copyOf(building);
building = null;
return view;
}
private static <T> AttributeKey<T> vanilla(String path) {
return add(RegistryKey.of("minecraft", path));
}
private static <T> AttributeKey<T> terra(String path) {
return add(RegistryKey.of("terra", path));
}
private static <T> AttributeKey<T> add(RegistryKey key) {
AttributeKey<T> attributeKey = AttributeKey.of(key);
building.add(attributeKey);
return attributeKey;
}
}
@@ -0,0 +1,35 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.List;
import com.dfsek.terra.addons.manifest.api.AddonInitializer;
import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
import com.dfsek.terra.api.inject.annotations.Inject;
import com.dfsek.terra.api.registry.CheckedRegistry;
import com.dfsek.terra.api.world.attribute.Attribute;
public class MinecraftAttributesAddon implements AddonInitializer {
@Inject
private Platform platform;
@Inject
private BaseAddon addon;
@Override
public void initialize() {
List<Attribute<?>> attributes = MinecraftAttributeTable.create(platform.getAttributeHandle());
platform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(addon, ConfigPackPreLoadEvent.class)
.then(event -> {
CheckedRegistry<Attribute<?>> registry = event.getPack().getOrCreateRegistry(Attribute.REGISTRY_TYPE);
for(Attribute<?> attribute : attributes) registry.register(attribute.getRegistryKey(), attribute);
})
.failThrough();
}
}
@@ -0,0 +1,349 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.Set;
import java.util.TreeSet;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.AttributeCodec;
import com.dfsek.terra.api.world.attribute.AttributeCodecs;
import com.dfsek.terra.api.world.attribute.AttributeCodecs.ObjectReader;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.DecodeContext;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.api.world.attribute.RawValue;
public final class MinecraftCodecs {
public static final String NAMESPACE = "minecraft";
// Same wording as the core identifier codec.
private static final String EXPECTED_IDENTIFIER = "expected an identifier like \"" + NAMESPACE + ":id\"";
private static final Set<String> MOB_CATEGORIES = Set.of("monster", "creature", "ambient", "axolotls", "underground_water_creature",
"water_creature", "water_ambient", "misc");
private final AttributeCodecs codecs;
private final DecodeContext plain;
private final AttributeCodec<String> idString;
private final AttributeCodec<RegistryKey> identifier;
private final AttributeCodec<Either<RegistryKey, TagKey>> identifierOrTag;
private final AttributeCodec<MoonPhase> moonPhase;
private final AttributeCodec<RawValue> particle;
private final AttributeCodec<AmbientParticle> ambientParticle;
private final AttributeCodec<List<AmbientParticle>> ambientParticles;
private final AttributeCodec<IntProviderValue> intProvider;
private final AttributeCodec<SoundRef> soundRef;
private final AttributeCodec<Music> music;
private final AttributeCodec<BackgroundMusic> backgroundMusic;
private final AttributeCodec<AmbientSounds.Mood> mood;
private final AttributeCodec<List<AmbientSounds.Additions>> additions;
private final AttributeCodec<AmbientSounds> ambientSounds;
private final AttributeCodec<BedRule.Rule> bedRuleRule;
private final AttributeCodec<BedRule> bedRule;
private final AttributeCodec<List<MobSpawnSettings.Spawner>> spawners;
private final AttributeCodec<MobSpawnSettings.Cost> spawnCost;
private final AttributeCodec<Map<String, List<MobSpawnSettings.Spawner>>> spawnsByCategory;
private final AttributeCodec<Map<RegistryKey, MobSpawnSettings.Cost>> spawnCosts;
private final AttributeCodec<MobSpawnSettings> mobSpawnSettings;
public MinecraftCodecs(AttributeHandle handle) {
AttributeCodecs c = handle.codecs();
this.codecs = c;
this.plain = handle.plainContext();
this.idString = c.string(EXPECTED_IDENTIFIER);
AttributeCodec<RegistryKey> coreIdentifier = c.identifier(NAMESPACE);
this.identifier = c.of((raw, context) -> {
String s = idString.decode(raw, context);
return lowerCase(coreIdentifier.decode(s, plain), s);
}, coreIdentifier::encode);
AttributeCodec<Either<RegistryKey, TagKey>> coreIdentifierOrTag = c.identifierOrTag(NAMESPACE);
this.identifierOrTag = c.of((raw, context) -> {
String s = idString.decode(raw, context);
Either<RegistryKey, TagKey> id = coreIdentifierOrTag.decode(s, plain);
lowerCase(id.hasLeft() ? id.getLeft().orElseThrow() : id.getRight().orElseThrow().key(), s);
return id;
}, coreIdentifierOrTag::encode);
this.moonPhase = c.enumCodec("moon phase", MoonPhase.class);
this.particle = c.of((raw, context) -> {
Object value = context.resolve(raw);
if(!(value instanceof Map<?, ?> map) || !map.containsKey("type")) {
throw new DecodeException("expected a particle object with a \"type\" key, got " + c.describe(value));
}
if(map.get("type") instanceof String type) {
try {
identifier.decode(type, plain);
} catch(DecodeException e) {
throw new DecodeException("\"type\" of particle: " + e.getMessage(), e);
}
}
return c.raw().decode(value, context);
}, RawValue::value);
this.ambientParticle = c.of((raw, context) -> {
ObjectReader f = c.reader("ambient particle", raw, context);
RawValue value = f.required("particle", this.particle);
float probability = f.required("probability", c.unitFloat());
f.finish();
return new AmbientParticle(value, probability);
}, value -> c.writer()
.put("particle", particle, value.particle())
.put("probability", c.unitFloat(), value.probability())
.map());
this.ambientParticles = c.list(ambientParticle);
this.intProvider = c.of((raw, context) -> {
String expected = "expected an integer or an int provider object";
Object value = context.resolve(raw);
if(value instanceof Map<?, ?> map) {
if(!map.containsKey("type")) throw new DecodeException("int provider object is missing \"type\"");
return new IntProviderValue(OptionalInt.empty(), Optional.of(c.raw().decode(value, context)));
}
if(value instanceof Number) return new IntProviderValue(OptionalInt.of(c.intCodec().decode(value, context)), Optional.empty());
if(value instanceof String) {
try {
return new IntProviderValue(OptionalInt.of(c.intCodec().decode(value, context)), Optional.empty());
} catch(DecodeException e) {
throw new DecodeException(expected + ", got " + c.describe(value), e);
}
}
throw new DecodeException(expected + ", got " + c.describe(value));
}, value -> value.constant().isPresent() ? (Object) value.constant().getAsInt() : value.provider().orElseThrow().value());
this.soundRef = c.of((raw, context) -> {
Object value = context.resolve(raw);
if(value instanceof String) return new SoundRef(identifier.decode(value, context), OptionalDouble.empty());
if(value instanceof Map<?, ?>) {
ObjectReader f = c.reader("sound", value, context);
RegistryKey id = f.required("sound_id", identifier);
Optional<Double> range = f.optional("range", c.doubleCodec());
f.finish();
return new SoundRef(id, range.map(OptionalDouble::of).orElse(OptionalDouble.empty()));
}
throw new DecodeException("expected a sound ID or a {sound_id, range} object, got " + c.describe(value));
}, value -> {
if(value.range().isEmpty()) return identifier.encode(value.id());
return c.writer()
.put("sound_id", identifier, value.id())
.put("range", c.doubleCodec(), value.range().getAsDouble())
.map();
});
this.music = c.of((raw, context) -> {
ObjectReader f = c.reader("music", raw, context);
SoundRef sound = f.required("sound", soundRef);
int min = f.required("min_delay", c.nonNegativeInt());
int max = f.required("max_delay", c.nonNegativeInt());
boolean replace = f.orDefault("replace_current_music", c.booleanCodec(), false);
f.finish();
return new Music(sound, min, max, replace);
}, value -> c.writer()
.put("sound", soundRef, value.sound())
.put("min_delay", c.nonNegativeInt(), value.minDelay())
.put("max_delay", c.nonNegativeInt(), value.maxDelay())
.put("replace_current_music", c.booleanCodec(), value.replaceCurrentMusic())
.map());
this.backgroundMusic = c.of((raw, context) -> {
ObjectReader f = c.reader("background music", raw, context);
Optional<Music> def = f.optional("default", music);
Optional<Music> creative = f.optional("creative", music);
Optional<Music> underwater = f.optional("underwater", music);
f.finish();
return new BackgroundMusic(def, creative, underwater);
}, value -> c.writer()
.optional("default", music, value.defaultMusic())
.optional("creative", music, value.creative())
.optional("underwater", music, value.underwater())
.map());
this.mood = c.of((raw, context) -> {
ObjectReader f = c.reader("ambient mood", raw, context);
SoundRef sound = f.required("sound", soundRef);
int tickDelay = f.required("tick_delay", c.intCodec());
int extent = f.required("block_search_extent", c.intCodec());
double offset = f.required("offset", c.doubleCodec());
f.finish();
return new AmbientSounds.Mood(sound, tickDelay, extent, offset);
}, value -> c.writer()
.put("sound", soundRef, value.sound())
.put("tick_delay", c.intCodec(), value.tickDelay())
.put("block_search_extent", c.intCodec(), value.blockSearchExtent())
.put("offset", c.doubleCodec(), value.offset())
.map());
this.additions = c.compactList(c.of((raw, context) -> {
ObjectReader f = c.reader("ambient additions", raw, context);
SoundRef sound = f.required("sound", soundRef);
double chance = f.required("tick_chance", c.doubleCodec());
f.finish();
return new AmbientSounds.Additions(sound, chance);
}, value -> c.writer()
.put("sound", soundRef, value.sound())
.put("tick_chance", c.doubleCodec(), value.tickChance())
.map()));
this.ambientSounds = c.of((raw, context) -> {
ObjectReader f = c.reader("ambient sounds", raw, context);
Optional<SoundRef> loop = f.optional("loop", soundRef);
Optional<AmbientSounds.Mood> moodValue = f.optional("mood", mood);
List<AmbientSounds.Additions> additionsValue = f.orDefault("additions", additions, List.of());
f.finish();
return new AmbientSounds(loop, moodValue, additionsValue);
}, value -> c.writer()
.optional("loop", soundRef, value.loop())
.optional("mood", mood, value.mood())
.put("additions", additions, value.additions())
.map());
this.bedRuleRule = c.enumCodec("bed rule", BedRule.Rule.class);
this.bedRule = c.of((raw, context) -> {
ObjectReader f = c.reader("bed rule", raw, context);
BedRule.Rule canSleep = f.required("can_sleep", bedRuleRule);
BedRule.Rule canSetSpawn = f.required("can_set_spawn", bedRuleRule);
boolean onUse = f.orDefault("destroy_on_use", c.booleanCodec(), false);
boolean onLeave = f.orDefault("destroy_on_leave", c.booleanCodec(), false);
Optional<RawValue> message = f.optional("error_message", c.raw());
f.finish();
return new BedRule(canSleep, canSetSpawn, onUse, onLeave, message);
}, value -> c.writer()
.put("can_sleep", bedRuleRule, value.canSleep())
.put("can_set_spawn", bedRuleRule, value.canSetSpawn())
.put("destroy_on_use", c.booleanCodec(), value.destroyOnUse())
.put("destroy_on_leave", c.booleanCodec(), value.destroyOnLeave())
.optional("error_message", c.raw(), value.errorMessage())
.map());
this.spawners = c.list(c.of((raw, context) -> {
ObjectReader f = c.reader("mob spawner", raw, context);
RegistryKey type = f.required("type", identifier);
int weight = f.required("weight", c.nonNegativeInt());
IntProviderValue count = f.required("count", intProvider);
f.finish();
return new MobSpawnSettings.Spawner(type, weight, count);
}, value -> c.writer()
.put("type", identifier, value.type())
.put("weight", c.nonNegativeInt(), value.weight())
.put("count", intProvider, value.count())
.map()));
this.spawnCost = c.of((raw, context) -> {
ObjectReader f = c.reader("spawn cost", raw, context);
double budget = f.required("energy_budget", c.doubleCodec());
double charge = f.required("charge", c.doubleCodec());
f.finish();
return new MobSpawnSettings.Cost(budget, charge);
}, value -> c.writer()
.put("energy_budget", c.doubleCodec(), value.energyBudget())
.put("charge", c.doubleCodec(), value.charge())
.map());
this.spawnsByCategory = c.of((raw, context) -> {
ObjectReader categories = c.reader("spawns_by_category", raw, context);
Map<String, List<MobSpawnSettings.Spawner>> out = new LinkedHashMap<>();
for(String key : categories.keys()) {
if(!MOB_CATEGORIES.contains(key)) {
throw new DecodeException("unknown mob category \"" + key + "\", expected one of " + new TreeSet<>(MOB_CATEGORIES));
}
out.put(key, categories.required(key, spawners));
}
categories.finish();
return out;
}, value -> {
Map<String, Object> out = new LinkedHashMap<>();
value.forEach((category, list) -> out.put(category, spawners.encode(list)));
return out;
});
// Map keys are never preprocessed.
this.spawnCosts = c.of((raw, context) -> {
ObjectReader costs = c.reader("spawn_costs", raw, context);
Map<RegistryKey, MobSpawnSettings.Cost> out = new LinkedHashMap<>();
for(String key : costs.keys()) {
out.put(identifier.decode(key, plain), costs.required(key, spawnCost));
}
costs.finish();
return out;
}, value -> {
Map<String, Object> out = new LinkedHashMap<>();
value.forEach((entity, cost) -> out.put((String) identifier.encode(entity), spawnCost.encode(cost)));
return out;
});
this.mobSpawnSettings = c.of((raw, context) -> {
ObjectReader f = c.reader("mob spawn settings", raw, context);
Map<String, List<MobSpawnSettings.Spawner>> byCategory = f.required("spawns_by_category", spawnsByCategory);
Map<RegistryKey, MobSpawnSettings.Cost> costs = f.required("spawn_costs", spawnCosts);
f.finish();
return new MobSpawnSettings(byCategory, costs);
}, value -> c.writer()
.put("spawns_by_category", spawnsByCategory, value.spawnsByCategory())
.put("spawn_costs", spawnCosts, value.spawnCosts())
.map());
}
private RegistryKey lowerCase(RegistryKey key, String written) throws DecodeException {
try {
return MinecraftIds.requireLowerCase(key, written);
} catch(IllegalArgumentException e) {
throw new DecodeException(EXPECTED_IDENTIFIER + ", got " + codecs.describe(written), e);
}
}
public AttributeCodec<RegistryKey> identifier() {
return identifier;
}
public AttributeCodec<Either<RegistryKey, TagKey>> identifierOrTag() {
return identifierOrTag;
}
public AttributeCodec<MoonPhase> moonPhase() {
return moonPhase;
}
public AttributeCodec<RawValue> particle() {
return particle;
}
public AttributeCodec<List<AmbientParticle>> ambientParticles() {
return ambientParticles;
}
public AttributeCodec<IntProviderValue> intProvider() {
return intProvider;
}
public AttributeCodec<SoundRef> soundRef() {
return soundRef;
}
public AttributeCodec<BackgroundMusic> backgroundMusic() {
return backgroundMusic;
}
public AttributeCodec<AmbientSounds> ambientSounds() {
return ambientSounds;
}
public AttributeCodec<BedRule> bedRule() {
return bedRule;
}
public AttributeCodec<MobSpawnSettings> mobSpawnSettings() {
return mobSpawnSettings;
}
}
@@ -0,0 +1,29 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.regex.Pattern;
import com.dfsek.terra.api.registry.key.RegistryKey;
public final class MinecraftIds {
private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9_.-]+");
private static final Pattern PATH = Pattern.compile("[a-z0-9_./-]+");
private MinecraftIds() { }
public static RegistryKey requireLowerCase(RegistryKey key) {
return requireLowerCase(key, key.toString());
}
public static RegistryKey requireLowerCase(RegistryKey key, String written) {
if(!NAMESPACE.matcher(key.getNamespace()).matches()) {
throw new IllegalArgumentException(
"invalid ID \"" + written + "\": the namespace must be non-empty and use only a-z, 0-9, _, . and -");
}
if(!PATH.matcher(key.getID()).matches()) {
throw new IllegalArgumentException(
"invalid ID \"" + written + "\": the path must be non-empty and use only a-z, 0-9, _, ., / and -");
}
return key;
}
}
@@ -0,0 +1,25 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.api.registry.key.RegistryKey;
public record MobSpawnSettings(Map<String, List<Spawner>> spawnsByCategory, Map<RegistryKey, Cost> spawnCosts) {
public static final MobSpawnSettings EMPTY = new MobSpawnSettings(Map.of(), Map.of());
public MobSpawnSettings {
Map<String, List<Spawner>> copy = new LinkedHashMap<>();
spawnsByCategory.forEach((k, v) -> copy.put(k, List.copyOf(v)));
spawnsByCategory = Collections.unmodifiableMap(copy);
spawnCosts = Collections.unmodifiableMap(new LinkedHashMap<>(spawnCosts));
}
public record Spawner(RegistryKey type, int weight, IntProviderValue count) { }
public record Cost(double energyBudget, double charge) { }
}
@@ -0,0 +1,26 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum MoonPhase implements StringIdentifiable {
FULL_MOON("full_moon"),
WANING_GIBBOUS("waning_gibbous"),
THIRD_QUARTER("third_quarter"),
WANING_CRESCENT("waning_crescent"),
NEW_MOON("new_moon"),
WAXING_CRESCENT("waxing_crescent"),
FIRST_QUARTER("first_quarter"),
WAXING_GIBBOUS("waxing_gibbous");
private final String id;
MoonPhase(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,3 @@
package com.dfsek.terra.addons.attribute.minecraft;
public record Music(SoundRef sound, int minDelay, int maxDelay, boolean replaceCurrentMusic) { }
@@ -0,0 +1,21 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum Skybox implements StringIdentifiable {
NONE("none"),
OVERWORLD("overworld"),
END("end");
private final String id;
Skybox(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,8 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.OptionalDouble;
import com.dfsek.terra.api.registry.key.RegistryKey;
public record SoundRef(RegistryKey id, OptionalDouble range) { }
@@ -0,0 +1,20 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum TemperatureModifier implements StringIdentifiable {
NONE("none"),
FROZEN("frozen");
private final String id;
TemperatureModifier(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -1,12 +1,12 @@
schema-version: 1
contributors:
- Terra contributors
id: biome-query-api
id: minecraft-attributes
version: @VERSION@
entrypoints:
- "com.dfsek.terra.addons.biome.query.BiomeQueryAPIAddon"
- "com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributesAddon"
website:
issues: https://github.com/PolyhedralDev/Terra/issues
source: https://github.com/PolyhedralDev/Terra
docs: https://terra.polydev.org
license: MIT License
license: MIT License
@@ -0,0 +1,450 @@
package attribute.minecraft;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.Set;
import java.util.stream.Stream;
import com.dfsek.terra.addons.attribute.minecraft.AmbientParticle;
import com.dfsek.terra.addons.attribute.minecraft.AmbientSounds;
import com.dfsek.terra.addons.attribute.minecraft.BackgroundMusic;
import com.dfsek.terra.addons.attribute.minecraft.BedRule;
import com.dfsek.terra.addons.attribute.minecraft.CardinalLight;
import com.dfsek.terra.addons.attribute.minecraft.GrassColorModifier;
import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTypes;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftCodecs;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftIds;
import com.dfsek.terra.addons.attribute.minecraft.MobSpawnSettings;
import com.dfsek.terra.addons.attribute.minecraft.MoonPhase;
import com.dfsek.terra.addons.attribute.minecraft.Music;
import com.dfsek.terra.addons.attribute.minecraft.Skybox;
import com.dfsek.terra.addons.attribute.minecraft.SoundRef;
import com.dfsek.terra.addons.attribute.minecraft.TemperatureModifier;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeType;
import com.dfsek.terra.api.world.attribute.DecodeContext;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.api.world.attribute.Operation;
import com.dfsek.terra.api.world.attribute.RawValue;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.*;
class MinecraftAttributeTypesTest {
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
private static final MinecraftAttributeTypes TYPES = new MinecraftAttributeTypes(HANDLE);
private static final DecodeContext PLAIN = HANDLE.plainContext();
private static final MinecraftCodecs CODECS = new MinecraftCodecs(HANDLE);
private static <T> T mod(AttributeType<T> type, Operation op, T subject, Object rawArg) throws DecodeException {
return type.apply(op, subject, type.decodeArgument(op, rawArg, PLAIN));
}
private static Map<String, Object> map(Object... kv) {
Map<String, Object> m = new LinkedHashMap<>();
for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]);
return m;
}
private static RegistryKey id(String id) {
return RegistryKey.parse(id);
}
private static SoundRef sound(String id) {
return new SoundRef(id(id), OptionalDouble.empty());
}
private static IntProviderValue constant(int value) {
return new IntProviderValue(OptionalInt.of(value), Optional.empty());
}
private static IntProviderValue provider(Map<String, Object> raw) {
return new IntProviderValue(OptionalInt.empty(), Optional.of(new RawValue(raw)));
}
private static MobSpawnSettings spawns(Map<String, Object> raw) throws DecodeException {
return TYPES.mobSpawnSettings().decode(raw, PLAIN);
}
private static Map<String, Object> spawner(String type, int weight, int count) {
return map("type", type, "weight", weight, "count", count);
}
@Test
void operationSets() {
for(AttributeType<?> t : List.of(TYPES.moonPhase(), TYPES.bedRule(), TYPES.particle(), TYPES.backgroundMusic(),
TYPES.ambientSounds(), TYPES.identifier(), TYPES.identifierOrTag(), TYPES.intProvider())) {
assertEquals(EnumSet.of(Operation.OVERRIDE), t.operations(), t.id());
}
assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.APPEND), TYPES.ambientParticles().operations());
assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.OVERLAY), TYPES.mobSpawnSettings().operations());
}
@Test
void enumIds() {
assertEquals(List.of("full_moon", "waning_gibbous", "third_quarter", "waning_crescent", "new_moon", "waxing_crescent",
"first_quarter", "waxing_gibbous"), ids(MoonPhase.values()));
assertEquals(List.of("always", "when_dark", "never"), ids(BedRule.Rule.values()));
assertEquals(List.of("none", "dark_forest", "swamp"), ids(GrassColorModifier.values()));
assertEquals(List.of("none", "frozen"), ids(TemperatureModifier.values()));
assertEquals(List.of("none", "overworld", "end"), ids(Skybox.values()));
assertEquals(List.of("default", "nether"), ids(CardinalLight.values()));
}
private static List<String> ids(StringIdentifiable[] values) {
return Arrays.stream(values).map(StringIdentifiable::getID).toList();
}
@Test
void valueRecordInvariants() {
assertThrows(IllegalArgumentException.class, () -> new IntProviderValue(OptionalInt.empty(), Optional.empty()));
assertThrows(IllegalArgumentException.class,
() -> new IntProviderValue(OptionalInt.of(1), Optional.of(new RawValue(Map.of("type", "minecraft:constant")))));
LinkedHashMap<RegistryKey, MobSpawnSettings.Cost> costs = new LinkedHashMap<>();
for(String n : new String[]{ "zombie", "alpha", "mid", "bat", "creeper", "ender" }) {
costs.put(RegistryKey.of("minecraft", n), new MobSpawnSettings.Cost(1, 1));
}
MobSpawnSettings s = new MobSpawnSettings(Map.of(), costs);
assertEquals(List.copyOf(costs.keySet()), List.copyOf(s.spawnCosts().keySet()));
assertThrows(UnsupportedOperationException.class, () -> s.spawnCosts().clear());
}
static Stream<Arguments> vanillaValues() {
Map<String, Object> uniform = map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3);
return Stream.of(
Arguments.of("moon phase", TYPES.moonPhase(), "new_moon", MoonPhase.NEW_MOON),
Arguments.of("identifier", TYPES.identifier(), "minecraft:idle", id("minecraft:idle")),
Arguments.of("bare identifier", TYPES.identifier(), "idle", id("minecraft:idle")),
Arguments.of("bare identifier or tag", TYPES.identifierOrTag(), "stone", Either.left(id("minecraft:stone"))),
Arguments.of("bare tag", TYPES.identifierOrTag(), "#logs", Either.right(TagKey.parse("#minecraft:logs"))),
Arguments.of("particle", TYPES.particle(), map("type", "minecraft:dripping_dripstone_lava"),
new RawValue(map("type", "minecraft:dripping_dripstone_lava"))),
Arguments.of("int constant", TYPES.intProvider(), 7, constant(7)),
Arguments.of("int provider", TYPES.intProvider(), uniform, provider(uniform)),
Arguments.of("crimson forest particles", TYPES.ambientParticles(),
List.of(map("particle", map("type", "minecraft:crimson_spore"), "probability", 0.025)),
List.of(new AmbientParticle(new RawValue(map("type", "minecraft:crimson_spore")), 0.025f))),
Arguments.of("straw bed rule", TYPES.bedRule(), map("can_set_spawn", "never", "can_sleep", "when_dark",
"destroy_on_leave", true, "error_message", map("translate", "block.minecraft.bed.no_sleep")),
new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.NEVER, false, true,
Optional.of(new RawValue(map("translate", "block.minecraft.bed.no_sleep"))))),
Arguments.of("bed rule defaults", TYPES.bedRule(), map("can_set_spawn", "always", "can_sleep", "always"),
new BedRule(BedRule.Rule.ALWAYS, BedRule.Rule.ALWAYS, false, false, Optional.empty())),
Arguments.of("warm ocean music", TYPES.backgroundMusic(), map(
"creative", map("max_delay", 24000, "min_delay", 12000, "sound", "minecraft:music.creative"),
"default", map("max_delay", 24000, "min_delay", 12000, "sound", "minecraft:music.game",
"replace_current_music", true),
"underwater", map("max_delay", 24000, "min_delay", 12000, "sound", "minecraft:music.under_water")),
new BackgroundMusic(Optional.of(new Music(sound("minecraft:music.game"), 12000, 24000, true)),
Optional.of(new Music(sound("minecraft:music.creative"), 12000, 24000, false)),
Optional.of(new Music(sound("minecraft:music.under_water"), 12000, 24000, false)))),
Arguments.of("no music", TYPES.backgroundMusic(), map(), BackgroundMusic.EMPTY),
Arguments.of("crimson forest sounds", TYPES.ambientSounds(), map(
"additions", map("sound", "minecraft:ambient.crimson_forest.additions", "tick_chance", 0.0111),
"loop", "minecraft:ambient.crimson_forest.loop",
"mood", map("block_search_extent", 8, "offset", 2.0, "sound", "minecraft:ambient.crimson_forest.mood",
"tick_delay", 6000)),
new AmbientSounds(Optional.of(sound("minecraft:ambient.crimson_forest.loop")),
Optional.of(new AmbientSounds.Mood(sound("minecraft:ambient.crimson_forest.mood"), 6000, 8, 2.0)),
List.of(new AmbientSounds.Additions(sound("minecraft:ambient.crimson_forest.additions"), 0.0111)))),
Arguments.of("addition list and ranged loop", TYPES.ambientSounds(), map(
"loop", map("sound_id", "a:b", "range", 16),
"additions", List.of(map("sound", "a:b", "tick_chance", 0.1), map("sound", "ambient.cave", "tick_chance", 0.2))),
new AmbientSounds(Optional.of(new SoundRef(id("a:b"), OptionalDouble.of(16))), Optional.empty(),
List.of(new AmbientSounds.Additions(sound("a:b"), 0.1), new AmbientSounds.Additions(sound("minecraft:ambient.cave"), 0.2)))),
Arguments.of("unranged sound object", TYPES.ambientSounds(), map("loop", map("sound_id", "a:b")),
new AmbientSounds(Optional.of(sound("a:b")), Optional.empty(), List.of())),
Arguments.of("no sounds", TYPES.ambientSounds(), map(), AmbientSounds.EMPTY),
Arguments.of("mob spawns", TYPES.mobSpawnSettings(), map(
"spawns_by_category", map("ambient", List.of(spawner("minecraft:bat", 10, 8)),
"monster", List.of(map("type", "minecraft:zombie", "weight", 5, "count", uniform))),
"spawn_costs", map("minecraft:enderman", map("energy_budget", 0.7, "charge", 0.15))),
new MobSpawnSettings(
Map.of("ambient", List.of(new MobSpawnSettings.Spawner(id("minecraft:bat"), 10, constant(8))),
"monster", List.of(new MobSpawnSettings.Spawner(id("minecraft:zombie"), 5, provider(uniform)))),
Map.of(id("minecraft:enderman"), new MobSpawnSettings.Cost(0.7, 0.15)))));
}
@ParameterizedTest(name = "{0}")
@MethodSource("vanillaValues")
void decodesVanillaValues(String name, AttributeType<?> type, Object raw, Object expected) throws DecodeException {
assertEquals(expected, type.decode(raw, PLAIN));
}
static Stream<Arguments> invalidValues() {
Map<String, Object> noCosts = map("spawns_by_category", map());
return Stream.of(
Arguments.of("moon phase", TYPES.moonPhase(), "blue_moon"),
Arguments.of("identifier with a space", TYPES.identifier(), "Not Valid"),
Arguments.of("identifier number", TYPES.identifier(), 3),
Arguments.of("identifier given a tag", TYPES.identifier(), "#minecraft:logs"),
Arguments.of("empty tag", TYPES.identifierOrTag(), "#"),
Arguments.of("particle without type", TYPES.particle(), map("color", 1)),
Arguments.of("particle string", TYPES.particle(), "minecraft:flame"),
Arguments.of("int provider string", TYPES.intProvider(), "x"),
Arguments.of("int provider fraction", TYPES.intProvider(), 1.5),
Arguments.of("int provider overflow", TYPES.intProvider(), 99999999999L),
Arguments.of("int provider without type", TYPES.intProvider(), map("min_inclusive", 0, "max_inclusive", 7)),
Arguments.of("probability above 1", TYPES.ambientParticles(), List.of(map("particle", map("type", "x"), "probability", 1.5))),
Arguments.of("missing probability", TYPES.ambientParticles(), List.of(map("particle", map("type", "x")))),
Arguments.of("particle not an object", TYPES.ambientParticles(), List.of(map("particle", "x", "probability", 0.5))),
Arguments.of("extra particle key", TYPES.ambientParticles(),
List.of(map("particle", map("type", "x"), "probability", 0.5, "extra", 1))),
Arguments.of("particles not a list", TYPES.ambientParticles(), map("particle", map("type", "x"), "probability", 0.5)),
Arguments.of("bed rule missing can_set_spawn", TYPES.bedRule(), map("can_sleep", "always")),
Arguments.of("extra bed rule key", TYPES.bedRule(), map("can_sleep", "always", "can_set_spawn", "always", "nope", 1)),
Arguments.of("unknown music key", TYPES.backgroundMusic(), map("bogus", 1)),
Arguments.of("music missing max_delay", TYPES.backgroundMusic(), map("default", map("sound", "a:b", "min_delay", 1))),
Arguments.of("negative delay", TYPES.backgroundMusic(),
map("default", map("sound", "a:b", "min_delay", -1, "max_delay", 1))),
Arguments.of("misspelled sounds key", TYPES.ambientSounds(), map("looop", "a:b")),
Arguments.of("incomplete mood", TYPES.ambientSounds(), map("mood", map("sound", "a:b"))),
Arguments.of("sound number", TYPES.ambientSounds(), map("loop", 5)),
Arguments.of("sound with a space", TYPES.ambientSounds(), map("loop", "Not Valid")),
Arguments.of("sound object without ID", TYPES.ambientSounds(), map("loop", map("range", 1))),
Arguments.of("unknown mob category", TYPES.mobSpawnSettings(),
map("spawns_by_category", map("bogus", List.of()), "spawn_costs", map())),
Arguments.of("missing spawn_costs", TYPES.mobSpawnSettings(), noCosts),
Arguments.of("extra spawn settings key", TYPES.mobSpawnSettings(),
map("spawns_by_category", map(), "spawn_costs", map(), "x", 1)),
Arguments.of("fractional weight", TYPES.mobSpawnSettings(), map("spawns_by_category",
map("monster", List.of(map("type", "minecraft:zombie", "weight", 1.5, "count", 1))), "spawn_costs", map())));
}
@ParameterizedTest(name = "{0}")
@MethodSource("invalidValues")
void rejectsInvalidValues(String name, AttributeType<?> type, Object raw) {
assertThrows(DecodeException.class, () -> type.decode(raw, PLAIN));
}
@Test
void nestedDecodeFailures() {
String bedRule = assertThrows(DecodeException.class,
() -> TYPES.bedRule().decode(map("can_sleep", "sometimes", "can_set_spawn", "always"), PLAIN)).getMessage();
assertEquals("\"can_sleep\" of bed rule: unknown bed rule \"sometimes\", expected one of [always, when_dark, never]", bedRule);
}
@Test
void ambientParticlesAppend() throws DecodeException {
AttributeType<List<AmbientParticle>> t = TYPES.ambientParticles();
List<AmbientParticle> one = t.decode(List.of(map("particle", map("type", "minecraft:crimson_spore"), "probability", 0.025)), PLAIN);
List<AmbientParticle> two = t.decode(List.of(map("particle", map("type", "minecraft:white_ash"), "probability", 0.1)), PLAIN);
assertEquals(one, t.apply(Operation.APPEND, one, List.of()));
assertEquals(two, t.apply(Operation.APPEND, List.of(), two));
assertEquals(List.of(one.get(0), two.get(0)),
mod(t, Operation.APPEND, one, List.of(map("particle", map("type", "minecraft:white_ash"), "probability", 0.1))));
}
@Test
void mobSpawnOverlay() throws DecodeException {
AttributeType<MobSpawnSettings> t = TYPES.mobSpawnSettings();
MobSpawnSettings empty = MobSpawnSettings.EMPTY;
MobSpawnSettings a = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1))),
"spawn_costs", map()));
assertSame(a, t.apply(Operation.OVERLAY, empty, a));
assertSame(a, t.apply(Operation.OVERLAY, a, empty));
MobSpawnSettings sup = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:husk", 1, 1)),
"creature", List.of(spawner("minecraft:pig", 1, 1))), "spawn_costs", map()));
assertSame(sup, t.apply(Operation.OVERLAY, a, sup));
MobSpawnSettings s = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1)),
"creature", List.of(spawner("minecraft:cow", 1, 1))),
"spawn_costs", map("minecraft:a", map("energy_budget", 1, "charge", 1))));
MobSpawnSettings r = mod(t, Operation.OVERLAY, s, map("spawns_by_category", map("ambient", List.of(spawner("minecraft:bat", 1, 1)),
"creature", List.of(spawner("minecraft:pig", 1, 1))),
"spawn_costs", map("minecraft:b", map("energy_budget", 2, "charge", 2))));
assertEquals(id("minecraft:zombie"), r.spawnsByCategory().get("monster").get(0).type());
assertEquals(id("minecraft:pig"), r.spawnsByCategory().get("creature").get(0).type());
assertEquals(id("minecraft:bat"), r.spawnsByCategory().get("ambient").get(0).type());
assertEquals(Set.of(id("minecraft:a"), id("minecraft:b")), r.spawnCosts().keySet());
MobSpawnSettings cleared = mod(t, Operation.OVERLAY, s, map("spawns_by_category", map("monster", List.of()), "spawn_costs", map()));
assertTrue(cleared.spawnsByCategory().get("monster").isEmpty());
assertEquals(1, cleared.spawnsByCategory().get("creature").size());
}
private static final List<String> ALL_CATEGORIES = List.of("monster", "creature", "ambient", "axolotls",
"underground_water_creature", "water_creature", "water_ambient", "misc");
private static MobSpawnSettings spawnsIn(String type, List<String> categories, String... costs) throws DecodeException {
Map<String, Object> byCategory = new LinkedHashMap<>();
for(String category : categories) byCategory.put(category, List.of(spawner(type, 1, 1)));
Map<String, Object> costMap = new LinkedHashMap<>();
for(String cost : costs) costMap.put(cost, map("energy_budget", 1, "charge", 1));
return spawns(map("spawns_by_category", byCategory, "spawn_costs", costMap));
}
private static <T> void assertComposesLikeApplyingBoth(AttributeType<T> t, Operation op, List<T> subjects, List<T> arguments) {
for(T s : subjects) {
for(T a : arguments) {
for(T b : arguments) {
Object composed = t.compose(op, a, b).orElseThrow();
assertEquals(t.apply(op, t.apply(op, s, a), b), t.apply(op, s, composed), s + " then " + a + " then " + b);
}
}
}
}
@Test
void composeEqualsApply() throws DecodeException {
assertComposesLikeApplyingBoth(TYPES.mobSpawnSettings(), Operation.OVERLAY,
List.of(MobSpawnSettings.EMPTY,
spawnsIn("minecraft:zombie", List.of("monster", "creature"), "minecraft:a"),
spawnsIn("minecraft:zombie", ALL_CATEGORIES, "minecraft:a", "minecraft:b")),
List.of(MobSpawnSettings.EMPTY,
spawnsIn("minecraft:husk", List.of("monster", "ambient"), "minecraft:b"),
spawnsIn("minecraft:pig", List.of("creature"), "minecraft:c"),
spawnsIn("minecraft:bat", ALL_CATEGORIES, "minecraft:a"),
spawns(map("spawns_by_category", map("monster", List.of()), "spawn_costs", map()))));
AttributeType<List<AmbientParticle>> particles = TYPES.ambientParticles();
List<AmbientParticle> one = particles.decode(List.of(map("particle", map("type", "minecraft:crimson_spore"), "probability", 0.025)),
PLAIN);
List<AmbientParticle> two = particles.decode(List.of(map("particle", map("type", "minecraft:white_ash"), "probability", 0.1),
map("particle", map("type", "minecraft:ash"), "probability", 0.5)), PLAIN);
List<List<AmbientParticle>> lists = List.of(List.of(), one, two);
assertComposesLikeApplyingBoth(particles, Operation.APPEND, lists, lists);
}
private static String path(String written) {
return "invalid ID \"" + written + "\": the path must be non-empty and use only a-z, 0-9, _, ., / and -";
}
private static String namespace(String written) {
return "invalid ID \"" + written + "\": the namespace must be non-empty and use only a-z, 0-9, _, . and -";
}
private static String lowerCaseFailure(Executable decode) {
Throwable t = assertThrows(DecodeException.class, decode);
while(t != null && !(t instanceof IllegalArgumentException)) t = t.getCause();
assertNotNull(t, "no lower-case rule failure in the cause chain");
return t.getMessage();
}
@Test
void requireLowerCase() {
RegistryKey key = id("minecraft:visual/fog_color");
assertSame(key, MinecraftIds.requireLowerCase(key));
assertSame(key, MinecraftIds.requireLowerCase(key, "visual/fog_color"));
assertEquals(namespace("Mod:thing"),
assertThrows(IllegalArgumentException.class, () -> MinecraftIds.requireLowerCase(id("Mod:thing"))).getMessage());
assertEquals(path("mod:Thing"),
assertThrows(IllegalArgumentException.class, () -> MinecraftIds.requireLowerCase(id("mod:Thing"))).getMessage());
assertEquals(path("Thing"), assertThrows(IllegalArgumentException.class,
() -> MinecraftIds.requireLowerCase(id("minecraft:Thing"), "Thing")).getMessage());
DecodeException e = assertThrows(DecodeException.class, () -> CODECS.soundRef().decode("minecraft:Ambient.Cave", PLAIN));
assertEquals("expected an identifier like \"minecraft:id\", got \"minecraft:Ambient.Cave\"", e.getMessage());
assertEquals(path("minecraft:Ambient.Cave"), e.getCause().getMessage());
}
@Test
void lowerCaseIds() {
assertEquals(namespace("Minecraft:x"), lowerCaseFailure(() -> CODECS.soundRef().decode("Minecraft:x", PLAIN)));
assertEquals(path("minecraft:Music.Game"),
lowerCaseFailure(() -> TYPES.ambientSounds().decode(Map.of("loop", "minecraft:Music.Game"), PLAIN)));
assertEquals(path("Music.Game"), lowerCaseFailure(() -> TYPES.backgroundMusic().decode(
map("default", map("sound", "Music.Game", "min_delay", 1, "max_delay", 2)), PLAIN)));
assertEquals(path("minecraft:Flame"), lowerCaseFailure(() -> TYPES.particle().decode(map("type", "minecraft:Flame"), PLAIN)));
assertEquals(path("Idle"), lowerCaseFailure(() -> TYPES.identifier().decode("Idle", PLAIN)));
assertEquals(path("#minecraft:Logs"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("#minecraft:Logs", PLAIN)));
assertEquals(path("#Logs"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("#Logs", PLAIN)));
assertEquals(namespace("Minecraft:stone"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("Minecraft:stone", PLAIN)));
assertEquals(path("minecraft:Zombie"), lowerCaseFailure(() -> spawns(map(
"spawns_by_category", map("monster", List.of(spawner("minecraft:Zombie", 1, 1))), "spawn_costs", map()))));
assertEquals(namespace("Minecraft:enderman"), lowerCaseFailure(() -> spawns(map("spawns_by_category", map(),
"spawn_costs", map("Minecraft:enderman", map("energy_budget", 1, "charge", 1))))));
}
@Test
void nestedDecodeContext() throws DecodeException {
List<Object> seen = new ArrayList<>();
DecodeContext recording = new DecodeContext() {
@Override
public <V> V load(Type type, Object raw) throws DecodeException {
seen.add(raw);
return PLAIN.load(type, raw);
}
@Override
public Object resolve(Object raw) {
return raw;
}
};
Map<String, Object> music = map("sound", "minecraft:music.game", "min_delay", 1, "max_delay", 2);
TYPES.backgroundMusic().decode(map("default", music), recording);
assertTrue(seen.containsAll(List.of("minecraft:music.game", 1, 2, music)), seen.toString());
}
private static DecodeContext referencing(Map<String, Object> targets) {
return new DecodeContext() {
@Override
public <V> V load(Type type, Object raw) throws DecodeException {
return PLAIN.load(type, raw);
}
@Override
public Object resolve(Object raw) {
if(raw instanceof String s && targets.containsKey(s)) return resolve(targets.get(s));
if(raw instanceof Map<?, ?> m) {
Map<String, Object> out = new LinkedHashMap<>();
m.forEach((k, v) -> out.put((String) k, resolve(v)));
return out;
}
if(raw instanceof List<?> l) return l.stream().map(this::resolve).toList();
return raw;
}
};
}
@Test
void resolveBeforeShape() throws DecodeException {
DecodeContext context = referencing(map(
"@sound", map("sound_id", "minecraft:ambient.cave", "range", 4.0),
"@additions", List.of(map("sound", "minecraft:a", "tick_chance", 0.5), map("sound", "minecraft:b", "tick_chance", 0.25)),
"@provider", map("type", "minecraft:uniform", "min_inclusive", "@min", "max_inclusive", 4),
"@min", 1,
"@flame", "minecraft:flame",
"@message", map("translate", "@key"),
"@key", "block.minecraft.bed.no_sleep",
"minecraft:zombie", "minecraft:cow"));
AmbientSounds sounds = TYPES.ambientSounds().decode(map("loop", "@sound", "additions", "@additions"), context);
assertEquals(4.0, sounds.loop().orElseThrow().range().orElseThrow());
assertEquals(2, sounds.additions().size());
IntProviderValue provider = TYPES.intProvider().decode("@provider", context);
assertEquals(new RawValue(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 4)),
provider.provider().orElseThrow());
List<AmbientParticle> particles = TYPES.ambientParticles().decode(
List.of(map("particle", map("type", "@flame"), "probability", 0.5)), context);
assertEquals(new RawValue(map("type", "minecraft:flame")), particles.get(0).particle());
BedRule rule = TYPES.bedRule().decode(map("can_sleep", "never", "can_set_spawn", "never", "error_message", "@message"),
context);
assertEquals(new RawValue(map("translate", "block.minecraft.bed.no_sleep")), rule.errorMessage().orElseThrow());
MobSpawnSettings settings = TYPES.mobSpawnSettings().decode(map(
"spawns_by_category", map(),
"spawn_costs", map("minecraft:zombie", map("energy_budget", 1.0, "charge", 0.5))), context);
assertEquals(List.of(id("minecraft:zombie")), List.copyOf(settings.spawnCosts().keySet()));
}
}
@@ -0,0 +1,99 @@
package attribute.minecraft;
import ca.solostudios.strata.Versions;
import ca.solostudios.strata.version.Version;
import ca.solostudios.strata.version.VersionRange;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributesAddon;
import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.event.EventManager;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.inject.Injector;
import com.dfsek.terra.api.registry.CheckedRegistry;
import com.dfsek.terra.api.util.reflection.TypeKey;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.event.EventManagerImpl;
import com.dfsek.terra.registry.CheckedRegistryImpl;
import com.dfsek.terra.registry.OpenRegistryImpl;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MinecraftAttributesAddonTest {
private static final BaseAddon ADDON = new BaseAddon() {
@Override
public String getID() {
return "minecraft-attributes";
}
@Override
public Version getVersion() {
return null;
}
};
private static final VersionRange ONE = Versions.getVersionRange(Versions.getVersion(1, 0, 0), true, Versions.getVersion(2, 0, 0),
false);
private static Platform platform(EventManager events, AttributeHandle handle) {
return (Platform) Proxy.newProxyInstance(Platform.class.getClassLoader(), new Class<?>[]{ Platform.class },
(proxy, method, args) -> switch(method.getName()) {
case "getEventManager" -> events;
case "getAttributeHandle" -> handle;
default -> throw new UnsupportedOperationException(method.getName());
});
}
private static ConfigPack pack(Map<BaseAddon, VersionRange> addons) {
Map<TypeKey<?>, CheckedRegistry<?>> registries = new HashMap<>();
return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class<?>[]{ ConfigPack.class },
(proxy, method, args) -> switch(method.getName()) {
case "addons" -> addons;
case "getOrCreateRegistry" -> registries.computeIfAbsent((TypeKey<?>) args[0],
type -> new CheckedRegistryImpl<>(new OpenRegistryImpl<>(type)));
default -> throw new UnsupportedOperationException(method.getName());
});
}
@Test
void dependentPacksOnly() {
EventManager events = new EventManagerImpl();
AttributeHandle handle = new AttributeHandleImpl();
MinecraftAttributesAddon initializer = new MinecraftAttributesAddon();
Injector<Platform> platformInjector = Injector.get(platform(events, handle));
platformInjector.addExplicitTarget(Platform.class);
platformInjector.inject(initializer);
Injector<BaseAddon> addonInjector = Injector.get(ADDON);
addonInjector.addExplicitTarget(BaseAddon.class);
addonInjector.inject(initializer);
initializer.initialize();
ConfigPack dependent = pack(Map.of(ADDON, ONE));
ConfigPack other = pack(Map.of());
events.callEvent(new ConfigPackPreLoadEvent(dependent, template -> { }));
events.callEvent(new ConfigPackPreLoadEvent(other, template -> { }));
CheckedRegistry<Attribute<?>> registered = dependent.getOrCreateRegistry(Attribute.REGISTRY_TYPE);
assertEquals(79, registered.entries().size());
assertTrue(other.getOrCreateRegistry(Attribute.REGISTRY_TYPE).entries().isEmpty());
Attribute<?> fog = MinecraftAttributes.VISUAL_FOG_COLOR.lookup(registered).orElseThrow();
assertSame(fog, registered.get(fog.getRegistryKey()).orElseThrow());
ConfigPack second = pack(Map.of(ADDON, ONE));
events.callEvent(new ConfigPackPreLoadEvent(second, template -> { }));
assertSame(fog, MinecraftAttributes.VISUAL_FOG_COLOR.lookup(second.getOrCreateRegistry(Attribute.REGISTRY_TYPE)).orElseThrow());
assertEquals(79, handle.attributeCount());
}
}
Loaded 100 of 440 files, more files were not shown because too many files have changed in this diff. Show more