From 4e37c361ea043ab83f44b055f30971dea25062fc Mon Sep 17 00:00:00 2001 From: Zoe Gidiere Date: Sun, 8 Nov 2026 03:51:22 -0700 Subject: [PATCH] feat: add environment attribute system --- buildSrc/build.gradle.kts | 8 +- buildSrc/src/main/kotlin/Versions.kt | 2 +- common/addons/config-attributes/LICENSE | 21 + .../addons/config-attributes/build.gradle.kts | 10 + .../addons/attribute/AttributeAddon.java | 194 ++++++++ .../addons/attribute/AttributeReader.java | 86 ++++ .../attribute/BiomeAttributeEntries.java | 13 + .../attribute/BiomeAttributesTemplate.java | 23 + .../addons/attribute/ConfigDecodeContext.java | 135 ++++++ .../addons/attribute/LazyConfigValue.java | 19 + .../addons/attribute/PackAttributesImpl.java | 133 ++++++ .../attribute/PackAttributesTemplate.java | 60 +++ .../attribute/RegistryAttributeLookup.java | 60 +++ .../terra/addons/attribute/ScheduleIds.java | 30 ++ .../resources/META-INF/api/config.terradoc | 122 +++++ .../src/main/resources/terra.addon.yml | 14 + .../java/attribute/AttributeReaderTest.java | 193 ++++++++ .../attribute/PackAttributesImplTest.java | 160 +++++++ .../attribute/ConfigDecodeContextTest.java | 186 ++++++++ .../addons/attribute/ScheduleIdsTest.java | 40 ++ common/addons/minecraft-attributes/LICENSE | 21 + .../minecraft-attributes/build.gradle.kts | 8 + .../attribute/minecraft/AmbientParticle.java | 6 + .../attribute/minecraft/AmbientSounds.java | 18 + .../attribute/minecraft/BackgroundMusic.java | 8 + .../addons/attribute/minecraft/BedRule.java | 26 + .../attribute/minecraft/CardinalLight.java | 20 + .../minecraft/GrassColorModifier.java | 21 + .../attribute/minecraft/IntProviderValue.java | 15 + .../minecraft/MinecraftAttributeTable.java | 159 +++++++ .../minecraft/MinecraftAttributeTypes.java | 109 +++++ .../minecraft/MinecraftAttributes.java | 128 +++++ .../minecraft/MinecraftAttributesAddon.java | 35 ++ .../attribute/minecraft/MinecraftCodecs.java | 349 ++++++++++++++ .../attribute/minecraft/MinecraftIds.java | 29 ++ .../attribute/minecraft/MobSpawnSettings.java | 25 + .../addons/attribute/minecraft/MoonPhase.java | 26 + .../addons/attribute/minecraft/Music.java | 3 + .../addons/attribute/minecraft/Skybox.java | 21 + .../addons/attribute/minecraft/SoundRef.java | 8 + .../minecraft/TemperatureModifier.java | 20 + .../src/main/resources/terra.addon.yml | 12 + .../MinecraftAttributeTypesTest.java | 450 ++++++++++++++++++ .../MinecraftAttributesAddonTest.java | 99 ++++ .../minecraft/MinecraftAttributesTest.java | 194 ++++++++ .../MinecraftCodecRoundTripTest.java | 177 +++++++ .../java/com/dfsek/terra/api/Platform.java | 15 + .../dfsek/terra/api/properties/Context.java | 8 + .../terra/api/registry/key/RegistryKey.java | 48 +- .../dfsek/terra/api/registry/key/TagKey.java | 63 +++ .../terra/api/world/attribute/Attribute.java | 63 +++ .../api/world/attribute/AttributeCodec.java | 14 + .../api/world/attribute/AttributeCodecs.java | 127 +++++ .../api/world/attribute/AttributeEntry.java | 43 ++ .../api/world/attribute/AttributeHandle.java | 110 +++++ .../api/world/attribute/AttributeKey.java | 71 +++ .../api/world/attribute/AttributeLookup.java | 9 + .../api/world/attribute/AttributeMap.java | 103 ++++ .../world/attribute/AttributeModifier.java | 6 + .../api/world/attribute/AttributeParents.java | 33 ++ .../api/world/attribute/AttributeScope.java | 6 + .../api/world/attribute/AttributeType.java | 61 +++ .../api/world/attribute/AttributeTypes.java | 68 +++ .../api/world/attribute/DecodeContext.java | 17 + .../api/world/attribute/DecodeException.java | 14 + .../terra/api/world/attribute/Operation.java | 44 ++ .../api/world/attribute/PackAttributes.java | 64 +++ .../terra/api/world/attribute/RawValue.java | 34 ++ .../attribute/schedule/AttributeSchedule.java | 21 + .../api/world/attribute/schedule/Easing.java | 29 ++ .../world/attribute/schedule/Keyframe.java | 6 + .../schedule/ScheduleDecodeResult.java | 20 + .../attribute/schedule/ScheduleTrack.java | 12 + .../world/attribute/schedule/TimeMarker.java | 3 + .../world/attribute/value/BlendToGray.java | 6 + .../api/world/attribute/value/Color.java | 97 ++++ .../world/attribute/value/FloatWithAlpha.java | 6 + .../api/world/attribute/value/TriState.java | 21 + .../api/registry/key/RegistryKeyTest.java | 113 +++++ .../api/world/attribute/AttributeMapTest.java | 72 +++ .../api/world/attribute/ValueTypesTest.java | 132 +++++ .../com/dfsek/terra/AbstractPlatform.java | 9 + .../MetaListLikePreprocessor.java | 3 +- .../preprocessor/MetaMapPreprocessor.java | 2 +- .../config/preprocessor/MetaPreprocessor.java | 19 +- .../preprocessor/MetaStringPreprocessor.java | 4 +- .../world/attribute/AttributeCodecsImpl.java | 107 +++++ .../world/attribute/AttributeHandleImpl.java | 137 ++++++ .../terra/world/attribute/AttributeImpl.java | 159 +++++++ .../world/attribute/AttributeLayers.java | 60 +++ .../world/attribute/AttributeTypeImpl.java | 155 ++++++ .../world/attribute/AttributeTypesImpl.java | 186 ++++++++ .../world/attribute/PlainDecodeContext.java | 63 +++ .../terra/world/attribute/ValueDecoders.java | 412 ++++++++++++++++ .../world/attribute/format/EntryFormat.java | 73 +++ .../attribute/format/ScheduleFormat.java | 299 ++++++++++++ .../AttributeCodecRoundTripTest.java | 163 +++++++ .../world/attribute/AttributeCodecsTest.java | 119 +++++ .../world/attribute/AttributeComposeTest.java | 151 ++++++ .../world/attribute/AttributeIndexTest.java | 51 ++ .../world/attribute/AttributeLayersTest.java | 88 ++++ .../world/attribute/AttributeTypesTest.java | 382 +++++++++++++++ .../world/attribute/EntryFormatTest.java | 79 +++ .../attribute/FixedArityResolveTest.java | 67 +++ .../world/attribute/ScheduleFormatTest.java | 416 ++++++++++++++++ platforms/cli/build.gradle.kts | 4 +- .../dfsek/terra/cli/AttributePackTest.java | 410 ++++++++++++++++ .../dfsek/terra/cli/FeatureStagePackTest.java | 56 +++ .../packs/attribute-test/biomes/bad.yml | 7 + .../packs/attribute-test/biomes/base.yml | 9 + .../packs/attribute-test/biomes/chain.yml | 11 + .../packs/attribute-test/biomes/child.yml | 6 + .../packs/attribute-test/biomes/expr.yml | 31 ++ .../packs/attribute-test/biomes/expr_bad.yml | 11 + .../packs/attribute-test/biomes/foggy.yml | 8 + .../packs/attribute-test/biomes/ground.yml | 14 + .../attribute-test/biomes/meta_child.yml | 8 + .../attribute-test/biomes/meta_include.yml | 8 + .../packs/attribute-test/biomes/nulled.yml | 6 + .../packs/attribute-test/biomes/plain.yml | 3 + .../resources/packs/attribute-test/meta.yml | 22 + .../resources/packs/attribute-test/pack.yml | 43 ++ .../packs/feature-stage-test/biomes/plain.yml | 19 + .../feature-stage-test/features/rock.yml | 15 + .../packs/feature-stage-test/pack.yml | 30 ++ .../packs/schedule-test/biomes/plain.yml | 12 + .../resources/packs/schedule-test/pack.yml | 49 ++ 127 files changed, 9022 insertions(+), 19 deletions(-) create mode 100644 common/addons/config-attributes/LICENSE create mode 100644 common/addons/config-attributes/build.gradle.kts create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeAddon.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeReader.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributeEntries.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributesTemplate.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ConfigDecodeContext.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/LazyConfigValue.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesImpl.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesTemplate.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/RegistryAttributeLookup.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ScheduleIds.java create mode 100644 common/addons/config-attributes/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/config-attributes/src/main/resources/terra.addon.yml create mode 100644 common/addons/config-attributes/src/test/java/attribute/AttributeReaderTest.java create mode 100644 common/addons/config-attributes/src/test/java/attribute/PackAttributesImplTest.java create mode 100644 common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ConfigDecodeContextTest.java create mode 100644 common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ScheduleIdsTest.java create mode 100644 common/addons/minecraft-attributes/LICENSE create mode 100644 common/addons/minecraft-attributes/build.gradle.kts create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientParticle.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientSounds.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BackgroundMusic.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BedRule.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/CardinalLight.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/GrassColorModifier.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/IntProviderValue.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTable.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTypes.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributes.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributesAddon.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftCodecs.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftIds.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MobSpawnSettings.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MoonPhase.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Music.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Skybox.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/SoundRef.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/TemperatureModifier.java create mode 100644 common/addons/minecraft-attributes/src/main/resources/terra.addon.yml create mode 100644 common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributeTypesTest.java create mode 100644 common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesAddonTest.java create mode 100644 common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesTest.java create mode 100644 common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftCodecRoundTripTest.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/registry/key/TagKey.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/Attribute.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodec.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodecs.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeEntry.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeHandle.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeKey.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeLookup.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeMap.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeModifier.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeParents.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeScope.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeType.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeTypes.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeContext.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeException.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/Operation.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/PackAttributes.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/RawValue.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/AttributeSchedule.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Easing.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Keyframe.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleDecodeResult.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleTrack.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/TimeMarker.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/BlendToGray.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/Color.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/FloatWithAlpha.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/TriState.java create mode 100644 common/api/src/test/java/com/dfsek/terra/api/registry/key/RegistryKeyTest.java create mode 100644 common/api/src/test/java/com/dfsek/terra/api/world/attribute/AttributeMapTest.java create mode 100644 common/api/src/test/java/com/dfsek/terra/api/world/attribute/ValueTypesTest.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeCodecsImpl.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeHandleImpl.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeImpl.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeLayers.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypeImpl.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypesImpl.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/PlainDecodeContext.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/ValueDecoders.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/EntryFormat.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/ScheduleFormat.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecRoundTripTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecsTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeComposeTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeIndexTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeLayersTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeTypesTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/EntryFormatTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/FixedArityResolveTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/ScheduleFormatTest.java create mode 100644 platforms/cli/src/test/java/com/dfsek/terra/cli/AttributePackTest.java create mode 100644 platforms/cli/src/test/java/com/dfsek/terra/cli/FeatureStagePackTest.java create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/bad.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/base.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/chain.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/child.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/expr.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/expr_bad.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/foggy.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/ground.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_child.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_include.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/nulled.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/plain.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/meta.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/pack.yml create mode 100644 platforms/cli/src/test/resources/packs/feature-stage-test/biomes/plain.yml create mode 100644 platforms/cli/src/test/resources/packs/feature-stage-test/features/rock.yml create mode 100644 platforms/cli/src/test/resources/packs/feature-stage-test/pack.yml create mode 100644 platforms/cli/src/test/resources/packs/schedule-test/biomes/plain.yml create mode 100644 platforms/cli/src/test/resources/packs/schedule-test/pack.yml diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 34721c9fd..594f03e1b 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -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") { @@ -26,6 +32,6 @@ dependencies { 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") } \ No newline at end of file diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index eb75413fa..bdfec58ce 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -7,7 +7,7 @@ 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" diff --git a/common/addons/config-attributes/LICENSE b/common/addons/config-attributes/LICENSE new file mode 100644 index 000000000..da43ecc81 --- /dev/null +++ b/common/addons/config-attributes/LICENSE @@ -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. \ No newline at end of file diff --git a/common/addons/config-attributes/build.gradle.kts b/common/addons/config-attributes/build.gradle.kts new file mode 100644 index 000000000..172601515 --- /dev/null +++ b/common/addons/config-attributes/build.gradle.kts @@ -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) +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeAddon.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeAddon.java new file mode 100644 index 000000000..7288e69c8 --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeAddon.java @@ -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 biomeKey = Context.create(BiomeAttributeEntries.class); + PropertyKey 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 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 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> attributes = pack.getRegistry(Attribute.REGISTRY_TYPE); + PackAttributesTemplate template = event.loadTemplate(new PackAttributesTemplate()); + List 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 parents = new LinkedHashMap<>(); + parent(parents, VANILLA, template.getVanilla(), pack, warnings); + parent(parents, VANILLA_GENERATION, template.getVanillaGeneration(), pack, warnings); + + List> 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 definitions = new LinkedHashMap<>(); + Set 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 raw = (Map) 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 biomeKey) { + Registry 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 parents, String key, Optional value, ConfigPack pack, List 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(); + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeReader.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeReader.java new file mode 100644 index 000000000..68d74bce0 --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeReader.java @@ -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> registry, AttributeHandle handle) { + this.lookup = new RegistryAttributeLookup(registry); + this.handle = handle; + } + + public enum Scope { BIOME, PACK } + + + public record Result(AttributeMap map, List problems) { } + + + public record Problem(String key, String reason) { } + + + private record Value(Object raw, DecodeContext context) { } + + public Result read(Map raw, Scope scope) { + DecodeContext plain = handle.plainContext(); + Map values = new LinkedHashMap<>(); + raw.forEach((key, value) -> values.put(key, new Value(value, plain))); + return readValues(values, scope); + } + + Result readConfig(Map config, Scope scope) { + DecodeContext plain = handle.plainContext(); + Map 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 raw, Scope scope) { + AttributeMap.Builder builder = AttributeMap.builder(); + List problems = new ArrayList<>(); + for(Map.Entry 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 void put(AttributeMap.Builder builder, Attribute attribute, Object value, DecodeContext context) + throws DecodeException { + builder.put(attribute.key(), handle.decodeEntry(attribute, value, context)); + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributeEntries.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributeEntries.java new file mode 100644 index 000000000..ed1840534 --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributeEntries.java @@ -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 warnings) implements Properties { + BiomeAttributeEntries { + warnings = List.copyOf(warnings); + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributesTemplate.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributesTemplate.java new file mode 100644 index 000000000..981b828dc --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributesTemplate.java @@ -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 getAttributes() { + return Collections.unmodifiableMap(attributes); + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ConfigDecodeContext.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ConfigDecodeContext.java new file mode 100644 index 000000000..78ece4d03 --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ConfigDecodeContext.java @@ -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. + *

+ * Not thread safe: include preprocessors mutate the {@link DepthTracker}. + */ +final class ConfigDecodeContext implements DecodeContext { + static final List> 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>() { }.getAnnotatedType(); + private static final AnnotatedType LIST = new TypeKey<@Meta ListShape>() { }.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 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 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 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 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 extends AbstractMap { } + + + private abstract static class ListShape extends AbstractList { } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/LazyConfigValue.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/LazyConfigValue.java new file mode 100644 index 000000000..25fbe9542 --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/LazyConfigValue.java @@ -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 LOADER = (type, o, loader, depthTracker) -> new LazyConfigValue(o, loader, depthTracker); + + DecodeContext context(DecodeContext plain) { + return new ConfigDecodeContext(loader, tracker, plain); + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesImpl.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesImpl.java new file mode 100644 index 000000000..0f4a45511 --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesImpl.java @@ -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 parents; + private final List> scheduleRefs; + private final Map scheduleDefinitions; + private final List warnings; + + public PackAttributesImpl(AttributeHandle handle, AttributeParents attributeParents, @Nullable Registry> attributes, + AttributeMap entries, Map parents, + List> scheduleRefs, Map scheduleDefinitions, + AttributeMap[] biomeEntries, List 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> 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 parents() { + return parents; + } + + @Override + public List> scheduleRefs() { + return scheduleRefs; + } + + @Override + public Map scheduleDefinitions() { + return scheduleDefinitions; + } + + @Override + @SuppressWarnings("unchecked") + public @Nullable AttributeEntry biomeEntryOrNull(Attribute 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) 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 @Nullable AttributeEntry packEntryOrNull(Attribute attribute) { + int index = attribute.index(); + return index < packEntries.length ? (AttributeEntry) packEntries[index] : null; + } + + @Override + public @Nullable T resolve(Attribute attribute, Biome biome) { + return handle.resolve(attribute, attributeParents.packOrNull(this, attribute), packEntryOrNull(attribute), + attributeParents.biomeOrNull(biome, attribute), biomeEntryOrNull(attribute, biome)); + } + + @Override + public @Nullable T resolvePack(Attribute attribute) { + return handle.resolve(attribute, attributeParents.packOrNull(this, attribute), packEntryOrNull(attribute), null); + } + + public List warnings() { + return warnings; + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesTemplate.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesTemplate.java new file mode 100644 index 000000000..7909d75db --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesTemplate.java @@ -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 getAttributes() { + return Collections.unmodifiableMap(attributes); + } + + public List getSchedules() { + return schedules; + } + + Map getScheduleDefinitions() { + return Collections.unmodifiableMap(scheduleDefinitions); + } + + public Optional getVanilla() { + return string(vanilla); + } + + public Optional getVanillaGeneration() { + return string(vanillaGeneration); + } + + private static Optional string(LazyConfigValue value) { + return value != null && value.raw() instanceof String s ? Optional.of(s) : Optional.empty(); + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/RegistryAttributeLookup.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/RegistryAttributeLookup.java new file mode 100644 index 000000000..c6e8a089e --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/RegistryAttributeLookup.java @@ -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 NAMESPACE_ADDONS = Map.of( + "minecraft", "minecraft-attributes", + "terra", "minecraft-attributes"); + + private final @Nullable Registry> registry; + + public RegistryAttributeLookup(@Nullable Registry> 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"; + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ScheduleIds.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ScheduleIds.java new file mode 100644 index 000000000..8a12ef604 --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ScheduleIds.java @@ -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 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 reference(String value) { + if(value.startsWith("#")) return Either.right(TagKey.parse(value)); + return Either.left(RegistryKey.parseNamespaced(value)); + } +} diff --git a/common/addons/config-attributes/src/main/resources/META-INF/api/config.terradoc b/common/addons/config-attributes/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..f9e0ade98 --- /dev/null +++ b/common/addons/config-attributes/src/main/resources/META-INF/api/config.terradoc @@ -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." + } + } + } + } +} diff --git a/common/addons/config-attributes/src/main/resources/terra.addon.yml b/common/addons/config-attributes/src/main/resources/terra.addon.yml new file mode 100644 index 000000000..3859bc59e --- /dev/null +++ b/common/addons/config-attributes/src/main/resources/terra.addon.yml @@ -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.+" diff --git a/common/addons/config-attributes/src/test/java/attribute/AttributeReaderTest.java b/common/addons/config-attributes/src/test/java/attribute/AttributeReaderTest.java new file mode 100644 index 000000000..a0a97b393 --- /dev/null +++ b/common/addons/config-attributes/src/test/java/attribute/AttributeReaderTest.java @@ -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> 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> registry() { + OpenRegistryImpl> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE); + for(Attribute attribute : MinecraftAttributeTable.create(HANDLE)) registry.register(attribute.getRegistryKey(), attribute); + return registry; + } + + private static Map map(Object... kv) { + Map 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 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 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 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 track = Map.of("keyframes", List.of(Map.of("ticks", 0, "value", 10.0))); + Map 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()); + } +} diff --git a/common/addons/config-attributes/src/test/java/attribute/PackAttributesImplTest.java b/common/addons/config-attributes/src/test/java/attribute/PackAttributesImplTest.java new file mode 100644 index 000000000..da454001a --- /dev/null +++ b/common/addons/config-attributes/src/test/java/attribute/PackAttributesImplTest.java @@ -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 COUNT = HANDLE.attributeBuilder(AttributeKey.parse("test:count"), HANDLE.types().integer(), + 10).build(); + private static final Attribute OTHER = HANDLE.attributeBuilder(AttributeKey.parse("test:other"), HANDLE.types().integer(), + 0).build(); + private static final Registry> REGISTRY = registry(COUNT, OTHER); + + private static Registry> registry(Attribute... attributes) { + OpenRegistryImpl> 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 attribute, AttributeEntry entry) { + return AttributeMap.builder().put(attribute.key(), entry).build(); + } + + @Test + void resolveUsesParents() { + AttributeParents parents = new AttributeParents() { + @Override + @SuppressWarnings("unchecked") + public @Nullable AttributeEntry biomeOrNull(Biome biome, Attribute attribute) { + return attribute == COUNT ? (AttributeEntry) AttributeEntry.override(5) : null; + } + + @Override + @SuppressWarnings("unchecked") + public @Nullable AttributeEntry packOrNull(PackAttributes pack, Attribute attribute) { + return attribute == COUNT ? (AttributeEntry) 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 small1 = AttributeEntry.override(1); + AttributeEntry large1 = AttributeEntry.override(2); + AttributeEntry 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 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 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 parents = new LinkedHashMap<>(); + parents.put("vanilla-generation", RegistryKey.parse("test:generation")); + parents.put("vanilla", RegistryKey.parse("test:dimension")); + List ids = List.of("terra:z", "terra:a", "terra:m", "terra:b", "terra:y", "terra:c", "terra:x", "terra:d"); + Map 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()); + } +} diff --git a/common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ConfigDecodeContextTest.java b/common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ConfigDecodeContextTest.java new file mode 100644 index 000000000..cc2f06fa0 --- /dev/null +++ b/common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ConfigDecodeContextTest.java @@ -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 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 map(Object... kv) { + Map 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 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.load(Integer.class, "2 * 6000")); + assertEquals(1.5f, context.load(Float.class, "${meta.yml:n} / 2")); + assertEquals(3.0, context.load(Double.class, "$meta.yml:n")); + assertEquals(0.5f, context.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 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() { + @Override + public @NotNull Result 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); + } +} diff --git a/common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ScheduleIdsTest.java b/common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ScheduleIdsTest.java new file mode 100644 index 000000000..f01a31451 --- /dev/null +++ b/common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ScheduleIdsTest.java @@ -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 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()); + } +} diff --git a/common/addons/minecraft-attributes/LICENSE b/common/addons/minecraft-attributes/LICENSE new file mode 100644 index 000000000..da43ecc81 --- /dev/null +++ b/common/addons/minecraft-attributes/LICENSE @@ -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. \ No newline at end of file diff --git a/common/addons/minecraft-attributes/build.gradle.kts b/common/addons/minecraft-attributes/build.gradle.kts new file mode 100644 index 000000000..c98a1c4b2 --- /dev/null +++ b/common/addons/minecraft-attributes/build.gradle.kts @@ -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")) +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientParticle.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientParticle.java new file mode 100644 index 000000000..1f3827b61 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientParticle.java @@ -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) { } diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientSounds.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientSounds.java new file mode 100644 index 000000000..e5d4463fc --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientSounds.java @@ -0,0 +1,18 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import java.util.List; +import java.util.Optional; + + +public record AmbientSounds(Optional loop, Optional mood, List 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) { } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BackgroundMusic.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BackgroundMusic.java new file mode 100644 index 000000000..576cd0f06 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BackgroundMusic.java @@ -0,0 +1,8 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import java.util.Optional; + + +public record BackgroundMusic(Optional defaultMusic, Optional creative, Optional underwater) { + public static final BackgroundMusic EMPTY = new BackgroundMusic(Optional.empty(), Optional.empty(), Optional.empty()); +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BedRule.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BedRule.java new file mode 100644 index 000000000..d52a464ad --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BedRule.java @@ -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 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; + } + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/CardinalLight.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/CardinalLight.java new file mode 100644 index 000000000..440552eec --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/CardinalLight.java @@ -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; + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/GrassColorModifier.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/GrassColorModifier.java new file mode 100644 index 000000000..d7fe13f89 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/GrassColorModifier.java @@ -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; + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/IntProviderValue.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/IntProviderValue.java new file mode 100644 index 000000000..c6144ef94 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/IntProviderValue.java @@ -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 provider) { + public IntProviderValue { + if(constant.isPresent() == provider.isPresent()) { + throw new IllegalArgumentException("an int provider value needs exactly one of a constant and a provider"); + } + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTable.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTable.java new file mode 100644 index 000000000..f1221dcd8 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTable.java @@ -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> create(AttributeHandle handle) { + AttributeTypes t = handle.types(); + MinecraftAttributeTypes m = new MinecraftAttributeTypes(handle); + AttributeType temperatureModifier = t.enumType("temperature_modifier", TemperatureModifier.class); + AttributeType grassColorModifier = t.enumType("grass_color_modifier", GrassColorModifier.class); + AttributeType skybox = t.enumType("skybox", Skybox.class); + AttributeType 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> 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> rows = new ArrayList<>(); + + private Table(AttributeHandle handle) { + this.handle = handle; + } + + private Attribute.Builder row(AttributeKey key, AttributeType type, @Nullable T defaultValue) { + MinecraftIds.requireLowerCase(key.getRegistryKey()); + Attribute.Builder builder = handle.attributeBuilder(key, type, defaultValue); + rows.add(builder); + return builder; + } + + private List> build() { + List> built = new ArrayList<>(rows.size()); + for(Attribute.Builder row : rows) built.add(row.build()); + return List.copyOf(built); + } + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTypes.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTypes.java new file mode 100644 index 000000000..405931447 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTypes.java @@ -0,0 +1,109 @@ +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; + private final AttributeType bedRule; + private final AttributeType particle; + private final AttributeType> ambientParticles; + private final AttributeType backgroundMusic; + private final AttributeType ambientSounds; + private final AttributeType mobSpawnSettings; + private final AttributeType identifier; + private final AttributeType> identifierOrTag; + private final AttributeType 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) + .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) + .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() { + return moonPhase; + } + + public AttributeType bedRule() { + return bedRule; + } + + public AttributeType particle() { + return particle; + } + + public AttributeType> ambientParticles() { + return ambientParticles; + } + + public AttributeType backgroundMusic() { + return backgroundMusic; + } + + public AttributeType ambientSounds() { + return ambientSounds; + } + + public AttributeType mobSpawnSettings() { + return mobSpawnSettings; + } + + public AttributeType identifier() { + return identifier; + } + + public AttributeType> identifierOrTag() { + return identifierOrTag; + } + + public AttributeType intProvider() { + return intProvider; + } + + private static List append(List s, List a) { + if(a.isEmpty()) return s; + if(s.isEmpty()) return a; + List 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> categories = new LinkedHashMap<>(first.spawnsByCategory()); + categories.putAll(second.spawnsByCategory()); + Map costs = new LinkedHashMap<>(first.spawnCosts()); + costs.putAll(second.spawnCosts()); + return new MobSpawnSettings(categories, costs); + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributes.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributes.java new file mode 100644 index 000000000..3a3138ee4 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributes.java @@ -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> building = new ArrayList<>(); + + public static final AttributeKey VISUAL_FOG_COLOR = vanilla("visual/fog_color"); + public static final AttributeKey VISUAL_FOG_START_DISTANCE = vanilla("visual/fog_start_distance"); + public static final AttributeKey VISUAL_FOG_END_DISTANCE = vanilla("visual/fog_end_distance"); + public static final AttributeKey VISUAL_SKY_FOG_END_DISTANCE = vanilla("visual/sky_fog_end_distance"); + public static final AttributeKey VISUAL_CLOUD_FOG_END_DISTANCE = vanilla("visual/cloud_fog_end_distance"); + public static final AttributeKey VISUAL_WATER_FOG_COLOR = vanilla("visual/water_fog_color"); + public static final AttributeKey VISUAL_WATER_FOG_START_DISTANCE = vanilla("visual/water_fog_start_distance"); + public static final AttributeKey VISUAL_WATER_FOG_END_DISTANCE = vanilla("visual/water_fog_end_distance"); + public static final AttributeKey VISUAL_SKY_COLOR = vanilla("visual/sky_color"); + public static final AttributeKey VISUAL_SUNRISE_SUNSET_COLOR = vanilla("visual/sunrise_sunset_color"); + public static final AttributeKey VISUAL_CLOUD_COLOR = vanilla("visual/cloud_color"); + public static final AttributeKey VISUAL_CLOUD_HEIGHT = vanilla("visual/cloud_height"); + public static final AttributeKey VISUAL_SUN_ANGLE = vanilla("visual/sun_angle"); + public static final AttributeKey VISUAL_MOON_ANGLE = vanilla("visual/moon_angle"); + public static final AttributeKey VISUAL_STAR_ANGLE = vanilla("visual/star_angle"); + public static final AttributeKey VISUAL_MOON_PHASE = vanilla("visual/moon_phase"); + public static final AttributeKey VISUAL_STAR_BRIGHTNESS = vanilla("visual/star_brightness"); + public static final AttributeKey VISUAL_BLOCK_LIGHT_TINT = vanilla("visual/block_light_tint"); + public static final AttributeKey VISUAL_SKY_LIGHT_COLOR = vanilla("visual/sky_light_color"); + public static final AttributeKey VISUAL_SKY_LIGHT_FACTOR = vanilla("visual/sky_light_factor"); + public static final AttributeKey VISUAL_NIGHT_VISION_COLOR = vanilla("visual/night_vision_color"); + public static final AttributeKey VISUAL_AMBIENT_LIGHT_COLOR = vanilla("visual/ambient_light_color"); + public static final AttributeKey VISUAL_DEFAULT_DRIPSTONE_PARTICLE = vanilla("visual/default_dripstone_particle"); + public static final AttributeKey> VISUAL_AMBIENT_PARTICLES = vanilla("visual/ambient_particles"); + public static final AttributeKey AUDIO_BACKGROUND_MUSIC = vanilla("audio/background_music"); + public static final AttributeKey AUDIO_MUSIC_VOLUME = vanilla("audio/music_volume"); + public static final AttributeKey AUDIO_AMBIENT_SOUNDS = vanilla("audio/ambient_sounds"); + public static final AttributeKey AUDIO_FIREFLY_BUSH_SOUNDS = vanilla("audio/firefly_bush_sounds"); + public static final AttributeKey GAMEPLAY_SKY_LIGHT_LEVEL = vanilla("gameplay/sky_light_level"); + public static final AttributeKey GAMEPLAY_CAN_START_RAID = vanilla("gameplay/can_start_raid"); + public static final AttributeKey GAMEPLAY_WATER_EVAPORATES = vanilla("gameplay/water_evaporates"); + public static final AttributeKey GAMEPLAY_BED_RULE = vanilla("gameplay/bed_rule"); + public static final AttributeKey GAMEPLAY_STRAW_BED_RULE = vanilla("gameplay/straw_bed_rule"); + public static final AttributeKey GAMEPLAY_RESPAWN_ANCHOR_WORKS = vanilla("gameplay/respawn_anchor_works"); + public static final AttributeKey GAMEPLAY_NETHER_PORTAL_SPAWNS_PIGLIN = vanilla("gameplay/nether_portal_spawns_piglin"); + public static final AttributeKey GAMEPLAY_FAST_LAVA = vanilla("gameplay/fast_lava"); + public static final AttributeKey GAMEPLAY_INCREASED_FIRE_BURNOUT = vanilla("gameplay/increased_fire_burnout"); + public static final AttributeKey GAMEPLAY_EYEBLOSSOM_OPEN = vanilla("gameplay/eyeblossom_open"); + public static final AttributeKey GAMEPLAY_TURTLE_EGG_HATCH_CHANCE = vanilla("gameplay/turtle_egg_hatch_chance"); + public static final AttributeKey GAMEPLAY_PIGLINS_ZOMBIFY = vanilla("gameplay/piglins_zombify"); + public static final AttributeKey GAMEPLAY_SNOW_GOLEM_MELTS = vanilla("gameplay/snow_golem_melts"); + public static final AttributeKey GAMEPLAY_CREAKING_ACTIVE = vanilla("gameplay/creaking_active"); + public static final AttributeKey GAMEPLAY_SURFACE_SLIME_SPAWN_CHANCE = vanilla("gameplay/surface_slime_spawn_chance"); + public static final AttributeKey GAMEPLAY_CAT_WAKING_UP_GIFT_CHANCE = vanilla("gameplay/cat_waking_up_gift_chance"); + public static final AttributeKey GAMEPLAY_BEES_STAY_IN_HIVE = vanilla("gameplay/bees_stay_in_hive"); + public static final AttributeKey GAMEPLAY_MONSTERS_BURN = vanilla("gameplay/monsters_burn"); + public static final AttributeKey GAMEPLAY_CAN_PILLAGER_PATROL_SPAWN = vanilla("gameplay/can_pillager_patrol_spawn"); + public static final AttributeKey GAMEPLAY_NATURAL_MOB_SPAWNS = vanilla("gameplay/natural_mob_spawns"); + public static final AttributeKey GAMEPLAY_CREATURE_WORLD_GEN_SPAWN_PROBABILITY = + vanilla("gameplay/creature_world_gen_spawn_probability"); + public static final AttributeKey GAMEPLAY_VILLAGER_ACTIVITY = vanilla("gameplay/villager_activity"); + public static final AttributeKey GAMEPLAY_BABY_VILLAGER_ACTIVITY = vanilla("gameplay/baby_villager_activity"); + + public static final AttributeKey BIOME_HAS_PRECIPITATION = terra("biome/has_precipitation"); + public static final AttributeKey BIOME_TEMPERATURE = terra("biome/temperature"); + public static final AttributeKey BIOME_TEMPERATURE_MODIFIER = terra("biome/temperature_modifier"); + public static final AttributeKey BIOME_DOWNFALL = terra("biome/downfall"); + public static final AttributeKey BIOME_WATER_COLOR = terra("biome/water_color"); + public static final AttributeKey BIOME_FOLIAGE_COLOR = terra("biome/foliage_color"); + public static final AttributeKey BIOME_DRY_FOLIAGE_COLOR = terra("biome/dry_foliage_color"); + public static final AttributeKey BIOME_GRASS_COLOR = terra("biome/grass_color"); + public static final AttributeKey BIOME_GRASS_COLOR_MODIFIER = terra("biome/grass_color_modifier"); + public static final AttributeKey BIOME_VILLAGER_TYPE = terra("biome/villager_type"); + public static final AttributeKey DIMENSION_HAS_FIXED_TIME = terra("dimension/has_fixed_time"); + public static final AttributeKey DIMENSION_HAS_SKYLIGHT = terra("dimension/has_skylight"); + public static final AttributeKey DIMENSION_HAS_CEILING = terra("dimension/has_ceiling"); + public static final AttributeKey DIMENSION_HAS_ENDER_DRAGON_FIGHT = terra("dimension/has_ender_dragon_fight"); + public static final AttributeKey DIMENSION_COORDINATE_SCALE = terra("dimension/coordinate_scale"); + public static final AttributeKey DIMENSION_MIN_Y = terra("dimension/min_y"); + public static final AttributeKey DIMENSION_HEIGHT = terra("dimension/height"); + public static final AttributeKey DIMENSION_LOGICAL_HEIGHT = terra("dimension/logical_height"); + public static final AttributeKey> DIMENSION_INFINIBURN = terra("dimension/infiniburn"); + public static final AttributeKey DIMENSION_AMBIENT_LIGHT = terra("dimension/ambient_light"); + public static final AttributeKey DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL = terra("dimension/monster_spawn_light_level"); + public static final AttributeKey DIMENSION_MONSTER_SPAWN_BLOCK_LIGHT_LIMIT = + terra("dimension/monster_spawn_block_light_limit"); + public static final AttributeKey DIMENSION_SKYBOX = terra("dimension/skybox"); + public static final AttributeKey DIMENSION_CARDINAL_LIGHT = terra("dimension/cardinal_light"); + public static final AttributeKey DIMENSION_DEFAULT_CLOCK = terra("dimension/default_clock"); + public static final AttributeKey WORLD_SEA_LEVEL = terra("world/sea_level"); + public static final AttributeKey WORLD_SPAWN_HEIGHT = terra("world/spawn_height"); + public static final AttributeKey WORLD_MOB_GENERATION = terra("world/mob_generation"); + + private static final List> VIEW = seal(); + + private MinecraftAttributes() { } + + public static List> all() { + return VIEW; + } + + private static List> seal() { + List> view = List.copyOf(building); + building = null; + return view; + } + + private static AttributeKey vanilla(String path) { + return add(RegistryKey.of("minecraft", path)); + } + + private static AttributeKey terra(String path) { + return add(RegistryKey.of("terra", path)); + } + + private static AttributeKey add(RegistryKey key) { + AttributeKey attributeKey = AttributeKey.of(key); + building.add(attributeKey); + return attributeKey; + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributesAddon.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributesAddon.java new file mode 100644 index 000000000..846afd075 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributesAddon.java @@ -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> attributes = MinecraftAttributeTable.create(platform.getAttributeHandle()); + + platform.getEventManager() + .getHandler(FunctionalEventHandler.class) + .register(addon, ConfigPackPreLoadEvent.class) + .then(event -> { + CheckedRegistry> registry = event.getPack().getOrCreateRegistry(Attribute.REGISTRY_TYPE); + for(Attribute attribute : attributes) registry.register(attribute.getRegistryKey(), attribute); + }) + .failThrough(); + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftCodecs.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftCodecs.java new file mode 100644 index 000000000..8919d3158 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftCodecs.java @@ -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 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 idString; + private final AttributeCodec identifier; + private final AttributeCodec> identifierOrTag; + private final AttributeCodec moonPhase; + private final AttributeCodec particle; + private final AttributeCodec ambientParticle; + private final AttributeCodec> ambientParticles; + private final AttributeCodec intProvider; + private final AttributeCodec soundRef; + private final AttributeCodec music; + private final AttributeCodec backgroundMusic; + private final AttributeCodec mood; + private final AttributeCodec> additions; + private final AttributeCodec ambientSounds; + private final AttributeCodec bedRuleRule; + private final AttributeCodec bedRule; + private final AttributeCodec> spawners; + private final AttributeCodec spawnCost; + private final AttributeCodec>> spawnsByCategory; + private final AttributeCodec> spawnCosts; + private final AttributeCodec mobSpawnSettings; + + public MinecraftCodecs(AttributeHandle handle) { + AttributeCodecs c = handle.codecs(); + this.codecs = c; + this.plain = handle.plainContext(); + this.idString = c.string(EXPECTED_IDENTIFIER); + + AttributeCodec 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> coreIdentifierOrTag = c.identifierOrTag(NAMESPACE); + this.identifierOrTag = c.of((raw, context) -> { + String s = idString.decode(raw, context); + Either 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 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 def = f.optional("default", music); + Optional creative = f.optional("creative", music); + Optional 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 loop = f.optional("loop", soundRef); + Optional moodValue = f.optional("mood", mood); + List 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 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> 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 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 out = new LinkedHashMap<>(); + for(String key : costs.keys()) { + out.put(identifier.decode(key, plain), costs.required(key, spawnCost)); + } + costs.finish(); + return out; + }, value -> { + Map 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> byCategory = f.required("spawns_by_category", spawnsByCategory); + Map 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 identifier() { + return identifier; + } + + public AttributeCodec> identifierOrTag() { + return identifierOrTag; + } + + public AttributeCodec moonPhase() { + return moonPhase; + } + + public AttributeCodec particle() { + return particle; + } + + public AttributeCodec> ambientParticles() { + return ambientParticles; + } + + public AttributeCodec intProvider() { + return intProvider; + } + + public AttributeCodec soundRef() { + return soundRef; + } + + public AttributeCodec backgroundMusic() { + return backgroundMusic; + } + + public AttributeCodec ambientSounds() { + return ambientSounds; + } + + public AttributeCodec bedRule() { + return bedRule; + } + + public AttributeCodec mobSpawnSettings() { + return mobSpawnSettings; + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftIds.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftIds.java new file mode 100644 index 000000000..44739214f --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftIds.java @@ -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; + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MobSpawnSettings.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MobSpawnSettings.java new file mode 100644 index 000000000..4bc8a1822 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MobSpawnSettings.java @@ -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> spawnsByCategory, Map spawnCosts) { + public static final MobSpawnSettings EMPTY = new MobSpawnSettings(Map.of(), Map.of()); + + public MobSpawnSettings { + Map> 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) { } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MoonPhase.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MoonPhase.java new file mode 100644 index 000000000..95087c733 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MoonPhase.java @@ -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; + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Music.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Music.java new file mode 100644 index 000000000..27e1c0895 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Music.java @@ -0,0 +1,3 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +public record Music(SoundRef sound, int minDelay, int maxDelay, boolean replaceCurrentMusic) { } diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Skybox.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Skybox.java new file mode 100644 index 000000000..7ec311ffd --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Skybox.java @@ -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; + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/SoundRef.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/SoundRef.java new file mode 100644 index 000000000..014ff5da0 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/SoundRef.java @@ -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) { } diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/TemperatureModifier.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/TemperatureModifier.java new file mode 100644 index 000000000..77937199c --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/TemperatureModifier.java @@ -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; + } +} diff --git a/common/addons/minecraft-attributes/src/main/resources/terra.addon.yml b/common/addons/minecraft-attributes/src/main/resources/terra.addon.yml new file mode 100644 index 000000000..c58b7b5e8 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/resources/terra.addon.yml @@ -0,0 +1,12 @@ +schema-version: 1 +contributors: + - Terra contributors +id: minecraft-attributes +version: @VERSION@ +entrypoints: + - "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 diff --git a/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributeTypesTest.java b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributeTypesTest.java new file mode 100644 index 000000000..de2997da7 --- /dev/null +++ b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributeTypesTest.java @@ -0,0 +1,450 @@ +package attribute.minecraft; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +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.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.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.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 float EPS = 1e-6f; + 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 mod(AttributeType type, Operation op, T subject, Object rawArg) throws DecodeException { + return type.apply(op, subject, type.decodeArgument(op, rawArg, PLAIN)); + } + + private static Map map(Object... kv) { + Map m = new LinkedHashMap<>(); + for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]); + return m; + } + + @Test + void everyTypeSupportsOverride() { + List> all = List.of(TYPES.moonPhase(), TYPES.bedRule(), TYPES.particle(), TYPES.ambientParticles(), + TYPES.backgroundMusic(), TYPES.ambientSounds(), TYPES.mobSpawnSettings(), TYPES.identifier(), TYPES.identifierOrTag(), + TYPES.intProvider()); + for(AttributeType t : all) assertTrue(t.operations().contains(Operation.OVERRIDE), t.id()); + } + + @Test + void operationSets() { + assertEquals(EnumSet.of(Operation.OVERRIDE), TYPES.identifier().operations()); + assertEquals(EnumSet.of(Operation.OVERRIDE), TYPES.identifierOrTag().operations()); + assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.APPEND), TYPES.ambientParticles().operations()); + assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.OVERLAY), TYPES.mobSpawnSettings().operations()); + } + + @Test + void idsAreVanillaTypeIds() { + assertEquals("moon_phase", TYPES.moonPhase().id()); + assertEquals("bed_rule", TYPES.bedRule().id()); + assertEquals("particle", TYPES.particle().id()); + assertEquals("ambient_particles", TYPES.ambientParticles().id()); + assertEquals("background_music", TYPES.backgroundMusic().id()); + assertEquals("ambient_sounds", TYPES.ambientSounds().id()); + assertEquals("mob_spawn_settings", TYPES.mobSpawnSettings().id()); + assertEquals("identifier", TYPES.identifier().id()); + assertEquals("identifier_or_tag", TYPES.identifierOrTag().id()); + assertEquals("int_provider", TYPES.intProvider().id()); + } + + @Test + void decodeFailuresReadTheSameEverywhere() { + 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); + String moonPhase = assertThrows(DecodeException.class, () -> TYPES.moonPhase().decode("x", PLAIN)).getMessage(); + assertTrue(moonPhase.startsWith("unknown moon phase \"x\", expected one of [full_moon, "), moonPhase); + } + + @Test + void enumsAreStringIdentifiable() { + assertEquals("waxing_gibbous", MoonPhase.WAXING_GIBBOUS.getID()); + assertEquals("when_dark", BedRule.Rule.WHEN_DARK.getID()); + assertEquals("new_moon", TYPES.moonPhase().encode(MoonPhase.NEW_MOON)); + } + + @Test + void ambientParticlesAppend() throws DecodeException { + AttributeType> t = TYPES.ambientParticles(); + List one = t.decode(List.of(map("particle", map("type", "minecraft:crimson_spore"), "probability", 0.025)), PLAIN); + List two = t.decode(List.of(map("particle", map("type", "minecraft:white_ash"), "probability", 0.1)), PLAIN); + assertEquals(1, one.size()); + assertEquals(0.025f, one.get(0).probability(), EPS); + assertEquals(new RawValue(map("type", "minecraft:crimson_spore")), one.get(0).particle()); + 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)), t.apply(Operation.APPEND, one, 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 ambientParticleValidation() { + AttributeType> t = TYPES.ambientParticles(); + assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", map("type", "x"), "probability", 1.5)), PLAIN)); + assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", map("type", "x"))), PLAIN)); + assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", "x", "probability", 0.5)), PLAIN)); + assertThrows(DecodeException.class, + () -> t.decode(List.of(map("particle", map("type", "x"), "probability", 0.5, "extra", 1)), PLAIN)); + assertThrows(DecodeException.class, () -> t.decode(map("particle", map("type", "x"), "probability", 0.5), PLAIN)); + } + + private static MobSpawnSettings spawns(Map raw) throws DecodeException { + return TYPES.mobSpawnSettings().decode(raw, PLAIN); + } + + private static Map spawner(String type, int weight, int count) { + return map("type", type, "weight", weight, "count", count); + } + + @Test + void mobSpawnDecode() throws DecodeException { + MobSpawnSettings s = spawns(map( + "spawns_by_category", map("ambient", List.of(spawner("minecraft:bat", 10, 8))), + "spawn_costs", map("minecraft:enderman", map("energy_budget", 0.7, "charge", 0.15)))); + MobSpawnSettings.Spawner sp = s.spawnsByCategory().get("ambient").get(0); + assertEquals(RegistryKey.parse("minecraft:bat"), sp.type()); + assertEquals(10, sp.weight()); + assertEquals(8, sp.count().constant().getAsInt()); + assertEquals(0.7, s.spawnCosts().get(RegistryKey.parse("minecraft:enderman")).energyBudget(), 1e-9); + assertEquals(0.15, s.spawnCosts().get(RegistryKey.parse("minecraft:enderman")).charge(), 1e-9); + assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map("bogus", List.of()), "spawn_costs", map()))); + assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map()))); + assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map(), "spawn_costs", map(), "x", 1))); + } + + @Test + void mobSpawnCountMapIsKeptRaw() throws DecodeException { + MobSpawnSettings s = spawns(map("spawns_by_category", map("monster", List.of( + map("type", "minecraft:zombie", "weight", 5, + "count", map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3)))), + "spawn_costs", map())); + IntProviderValue c = s.spawnsByCategory().get("monster").get(0).count(); + assertTrue(c.constant().isEmpty()); + assertTrue(c.provider().isPresent()); + } + + @Test + void mobSpawnOverlayRules() throws DecodeException { + AttributeType 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 arg = spawns(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)))); + MobSpawnSettings r = t.apply(Operation.OVERLAY, s, arg); + assertEquals(RegistryKey.parse("minecraft:zombie"), r.spawnsByCategory().get("monster").get(0).type()); + assertEquals(RegistryKey.parse("minecraft:pig"), r.spawnsByCategory().get("creature").get(0).type()); + assertEquals(RegistryKey.parse("minecraft:bat"), r.spawnsByCategory().get("ambient").get(0).type()); + assertEquals(Set.of(RegistryKey.parse("minecraft:a"), RegistryKey.parse("minecraft:b")), r.spawnCosts().keySet()); + } + + @Test + void mobSpawnOverlayEmptyCategoryClears() throws DecodeException { + AttributeType t = TYPES.mobSpawnSettings(); + 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())); + MobSpawnSettings arg = spawns(map("spawns_by_category", map("monster", List.of()), "spawn_costs", map())); + MobSpawnSettings r = mod(t, Operation.OVERLAY, s, map("spawns_by_category", map("monster", List.of()), "spawn_costs", map())); + assertTrue(r.spawnsByCategory().get("monster").isEmpty()); + assertEquals(1, r.spawnsByCategory().get("creature").size()); + assertEquals(r, t.apply(Operation.OVERLAY, s, arg)); + } + + @Test + void ambientSoundsDecode() throws DecodeException { + AmbientSounds a = TYPES.ambientSounds().decode(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)), + PLAIN); + assertEquals(1, a.additions().size()); + assertEquals(0.0111, a.additions().get(0).tickChance(), 1e-9); + assertEquals(RegistryKey.parse("minecraft:ambient.crimson_forest.loop"), a.loop().orElseThrow().id()); + assertEquals(6000, a.mood().orElseThrow().tickDelay()); + assertEquals(8, a.mood().orElseThrow().blockSearchExtent()); + assertEquals(2.0, a.mood().orElseThrow().offset(), 1e-9); + + AmbientSounds list = TYPES.ambientSounds().decode(map( + "additions", List.of(map("sound", "a:b", "tick_chance", 0.1), map("sound", "a:c", "tick_chance", 0.2))), PLAIN); + assertEquals(2, list.additions().size()); + assertTrue(list.loop().isEmpty()); + assertEquals(AmbientSounds.EMPTY, TYPES.ambientSounds().decode(map(), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("looop", "a:b"), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("mood", map("sound", "a:b")), PLAIN)); + } + + @Test + void soundRefForms() throws DecodeException { + AmbientSounds a = TYPES.ambientSounds().decode(map("loop", map("sound_id", "a:b", "range", 16)), PLAIN); + assertEquals(RegistryKey.parse("a:b"), a.loop().orElseThrow().id()); + assertEquals(16.0, a.loop().orElseThrow().range().getAsDouble(), 1e-9); + AmbientSounds b = TYPES.ambientSounds().decode(map("loop", map("sound_id", "a:b")), PLAIN); + assertTrue(b.loop().orElseThrow().range().isEmpty()); + assertEquals(RegistryKey.parse("minecraft:ambient.cave"), + TYPES.ambientSounds().decode(map("loop", "ambient.cave"), PLAIN).loop().orElseThrow().id()); + assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", 5), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", "Not Valid"), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", map("range", 1)), PLAIN)); + } + + @Test + void upperCaseIdRejected() { + 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()); + assertEquals(namespace("Minecraft:x"), lowerCaseFailure(() -> CODECS.soundRef().decode("Minecraft:x", PLAIN))); + } + + 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 lowerCaseIds() { + 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 requireLowerCase() { + RegistryKey key = RegistryKey.parse("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(RegistryKey.parse("Mod:thing"))).getMessage()); + assertEquals(path("mod:Thing"), + assertThrows(IllegalArgumentException.class, () -> MinecraftIds.requireLowerCase(RegistryKey.parse("mod:Thing"))).getMessage()); + assertEquals(path("Thing"), assertThrows(IllegalArgumentException.class, + () -> MinecraftIds.requireLowerCase(RegistryKey.parse("minecraft:Thing"), "Thing")).getMessage()); + } + + @Test + void integersFollowTheCoreRule() { + String weight = assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", + map("monster", List.of(map("type", "minecraft:zombie", "weight", 1.5, "count", 1))), "spawn_costs", map()))).getMessage(); + assertTrue(weight.endsWith("\"weight\" of mob spawner: expected an integer, got 1.5"), weight); + assertThrows(DecodeException.class, () -> TYPES.intProvider().decode(99999999999L, PLAIN)); + } + + @Test + void backgroundMusicDecode() throws DecodeException { + BackgroundMusic m = TYPES.backgroundMusic().decode(map( + "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")), PLAIN); + assertTrue(m.defaultMusic().orElseThrow().replaceCurrentMusic()); + assertFalse(m.underwater().orElseThrow().replaceCurrentMusic()); + assertEquals(12000, m.underwater().orElseThrow().minDelay()); + assertEquals(24000, m.underwater().orElseThrow().maxDelay()); + assertTrue(m.creative().isEmpty()); + assertEquals(BackgroundMusic.EMPTY, TYPES.backgroundMusic().decode(map(), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.backgroundMusic().decode(map("bogus", 1), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.backgroundMusic().decode(map("default", map("sound", "a:b", "min_delay", 1)), PLAIN)); + assertThrows(DecodeException.class, + () -> TYPES.backgroundMusic().decode(map("default", map("sound", "a:b", "min_delay", -1, "max_delay", 1)), PLAIN)); + } + + @Test + void bedRuleDecode() throws DecodeException { + BedRule r = TYPES.bedRule().decode(map("can_set_spawn", "never", "can_sleep", "when_dark", "destroy_on_leave", true, + "error_message", map("translate", "block.minecraft.bed.no_sleep")), PLAIN); + assertEquals(BedRule.Rule.WHEN_DARK, r.canSleep()); + assertEquals(BedRule.Rule.NEVER, r.canSetSpawn()); + assertFalse(r.destroyOnUse()); + assertTrue(r.destroyOnLeave()); + assertTrue(r.errorMessage().isPresent()); + BedRule plain = TYPES.bedRule().decode(map("can_set_spawn", "always", "can_sleep", "always"), PLAIN); + assertTrue(plain.errorMessage().isEmpty()); + assertThrows(DecodeException.class, () -> TYPES.bedRule().decode(map("can_sleep", "always"), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.bedRule().decode(map("can_sleep", "sometimes", "can_set_spawn", "always"), PLAIN)); + assertThrows(DecodeException.class, + () -> TYPES.bedRule().decode(map("can_sleep", "always", "can_set_spawn", "always", "nope", 1), PLAIN)); + } + + @Test + void simpleTypesDecode() throws DecodeException { + assertEquals(MoonPhase.NEW_MOON, TYPES.moonPhase().decode("new_moon", PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.moonPhase().decode("blue_moon", PLAIN)); + assertEquals(RegistryKey.parse("minecraft:idle"), TYPES.identifier().decode("minecraft:idle", PLAIN)); + assertEquals(RegistryKey.parse("minecraft:idle"), TYPES.identifier().decode("idle", PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.identifier().decode("Not Valid", PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.identifier().decode(3, PLAIN)); + assertEquals("expected an identifier, not a tag, got \"#minecraft:logs\"", + assertThrows(DecodeException.class, () -> TYPES.identifier().decode("#minecraft:logs", PLAIN)).getMessage()); + assertEquals(Either.left(RegistryKey.parse("minecraft:stone")), TYPES.identifierOrTag().decode("stone", PLAIN)); + assertEquals(Either.right(TagKey.parse("#minecraft:logs")), TYPES.identifierOrTag().decode("#logs", PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.identifierOrTag().decode("#", PLAIN)); + } + + @Test + void particleDecode() throws DecodeException { + RawValue p = TYPES.particle().decode(map("type", "minecraft:dripping_dripstone_lava"), PLAIN); + assertEquals(new RawValue(map("type", "minecraft:dripping_dripstone_lava")), p); + assertThrows(DecodeException.class, () -> TYPES.particle().decode(map("color", 1), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.particle().decode("minecraft:flame", PLAIN)); + } + + @Test + void intProviderDecode() throws DecodeException { + IntProviderValue c = TYPES.intProvider().decode(7, PLAIN); + assertEquals(7, c.constant().getAsInt()); + assertTrue(c.provider().isEmpty()); + IntProviderValue p = TYPES.intProvider().decode(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3), PLAIN); + assertTrue(p.constant().isEmpty()); + assertTrue(p.provider().isPresent()); + assertThrows(DecodeException.class, () -> TYPES.intProvider().decode("x", PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.intProvider().decode(1.5, PLAIN)); + } + + @Test + void overrideArgumentDecodesWithValueDecoder() throws DecodeException { + assertEquals(MoonPhase.NEW_MOON, mod(TYPES.moonPhase(), Operation.OVERRIDE, MoonPhase.FULL_MOON, "new_moon")); + } + + @Test + void nestedDecodeContext() throws DecodeException { + List seen = new ArrayList<>(); + DecodeContext recording = new DecodeContext() { + @Override + public 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 music = map("sound", "minecraft:music.game", "min_delay", 1, "max_delay", 2); + TYPES.backgroundMusic().decode(map("default", music), recording); + assertTrue(seen.contains("minecraft:music.game"), seen.toString()); + assertTrue(seen.contains(1), seen.toString()); + assertTrue(seen.contains(2), seen.toString()); + assertTrue(seen.contains(music), seen.toString()); + } + + private static DecodeContext referencing(Map targets) { + return new DecodeContext() { + @Override + public 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 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")); + + 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 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()); + } + + @Test + void mapKeysInsideValuesAreNotPreprocessed() throws DecodeException { + DecodeContext context = referencing(map("minecraft:zombie", "minecraft:cow")); + 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(RegistryKey.parse("minecraft:zombie")), List.copyOf(settings.spawnCosts().keySet())); + } +} diff --git a/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesAddonTest.java b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesAddonTest.java new file mode 100644 index 000000000..ccefbdcc0 --- /dev/null +++ b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesAddonTest.java @@ -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 addons) { + Map, 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 platformInjector = Injector.get(platform(events, handle)); + platformInjector.addExplicitTarget(Platform.class); + platformInjector.inject(initializer); + Injector 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> 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()); + } +} diff --git a/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesTest.java b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesTest.java new file mode 100644 index 000000000..d336dd70b --- /dev/null +++ b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesTest.java @@ -0,0 +1,194 @@ +package attribute.minecraft; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +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.CheckedRegistry; +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.AttributeScope; +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.api.world.attribute.value.Color; +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class MinecraftAttributesTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final List> ALL = MinecraftAttributeTable.create(HANDLE); + private static final CheckedRegistry> REGISTRY = registry(); + + private static CheckedRegistry> registry() { + CheckedRegistry> registry = new CheckedRegistryImpl<>(new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE)); + ALL.forEach(attribute -> registry.register(attribute.getRegistryKey(), attribute)); + return registry; + } + + private static Attribute byId(String id) { + return REGISTRY.get(RegistryKey.parse(id)).orElseThrow(); + } + + @SuppressWarnings("unchecked") + private static Attribute typed(String id) { + return (Attribute) byId(id); + } + + @Test + void tableOrder() { + assertEquals(MinecraftAttributes.all(), ALL.stream().map(Attribute::key).toList()); + int first = ALL.get(0).index(); + for(int i = 0; i < ALL.size(); i++) { + assertEquals(first + i, ALL.get(i).index(), ALL.get(i).key().toString()); + assertSame(ALL.get(i), REGISTRY.get(ALL.get(i).getRegistryKey()).orElseThrow()); + } + assertTrue(HANDLE.attributeCount() >= first + ALL.size()); + } + + @Test + void scopes() { + Set packOnly = ALL.stream().filter(a -> a.key().getNamespace().equals("minecraft")) + .filter(a -> a.scope() == AttributeScope.PACK_ONLY).map(a -> a.key().toString()).collect(Collectors.toSet()); + assertEquals(Set.of("minecraft:gameplay/sky_light_level", "minecraft:gameplay/fast_lava"), packOnly); + for(Attribute a : ALL) { + if(!a.key().getNamespace().equals("terra")) continue; + boolean packWide = a.key().getID().startsWith("dimension/") || a.key().getID().startsWith("world/"); + assertEquals(packWide ? AttributeScope.PACK_ONLY : AttributeScope.ANYWHERE, a.scope(), a.key().toString()); + } + } + + @Test + void terraDefaults() { + assertNull(byId("terra:biome/foliage_color").defaultValue()); + assertNull(byId("terra:biome/dry_foliage_color").defaultValue()); + assertNull(byId("terra:biome/grass_color").defaultValue()); + assertEquals(Color.rgb(0x3f76e4), byId("terra:biome/water_color").defaultValue()); + assertEquals(-64, byId("terra:dimension/min_y").defaultValue()); + assertEquals(384, byId("terra:dimension/height").defaultValue()); + assertEquals(Either.right(TagKey.parse("#minecraft:infiniburn_overworld")), + byId("terra:dimension/infiniburn").defaultValue()); + assertEquals(RegistryKey.parse("minecraft:plains"), byId("terra:biome/villager_type").defaultValue()); + assertEquals(RegistryKey.parse("minecraft:overworld"), byId("terra:dimension/default_clock").defaultValue()); + IntProviderValue light = (IntProviderValue) byId("terra:dimension/monster_spawn_light_level").defaultValue(); + assertEquals(Optional.of(new RawValue(Map.of("type", "minecraft:uniform", "min_inclusive", 0, "max_inclusive", 7))), + light.provider()); + } + + @Test + void rangeValidation() throws Exception { + Attribute spawn = typed("minecraft:gameplay/creature_world_gen_spawn_probability"); + assertEquals(0.5f, spawn.validate(0.5f)); + assertThrows(DecodeException.class, () -> spawn.validate(1.0f)); + assertThrows(DecodeException.class, () -> spawn.validate(-0.1f)); + assertThrows(DecodeException.class, () -> spawn.validate(Float.NaN)); + + Attribute unit = typed("minecraft:audio/music_volume"); + assertEquals("value 2.0 is outside [0, 1]", assertThrows(DecodeException.class, () -> unit.validate(2f)).getMessage()); + + Attribute fogEnd = typed("minecraft:visual/fog_end_distance"); + assertThrows(DecodeException.class, () -> fogEnd.validate(-1f)); + assertEquals(1e9f, fogEnd.validate(1e9f)); + assertEquals(-5f, typed("minecraft:visual/fog_start_distance").validate(-5f)); + + Attribute scale = typed("terra:dimension/coordinate_scale"); + assertEquals(1f, scale.validate(1f)); + assertThrows(DecodeException.class, () -> scale.validate(0f)); + Attribute light = typed("terra:dimension/monster_spawn_block_light_limit"); + assertThrows(DecodeException.class, () -> light.validate(16)); + } + + @Test + void dimensionGeometry() throws Exception { + for(String id : List.of("terra:dimension/min_y", "terra:dimension/height", "terra:dimension/logical_height")) { + assertEquals(EnumSet.of(Operation.OVERRIDE), byId(id).type().operations(), id); + } + Attribute minY = typed("terra:dimension/min_y"); + assertEquals(-2032, minY.validate(-2032)); + assertThrows(DecodeException.class, () -> minY.validate(-2048)); + assertThrows(DecodeException.class, () -> minY.validate(2032)); + assertThrows(DecodeException.class, () -> minY.validate(-60)); + Attribute height = typed("terra:dimension/height"); + assertEquals(16, height.validate(16)); + assertThrows(DecodeException.class, () -> height.validate(0)); + assertEquals("value 100 is not a multiple of 16", assertThrows(DecodeException.class, () -> height.validate(100)).getMessage()); + assertEquals(37, typed("terra:dimension/logical_height").validate(37)); + } + + @Test + void sanitizeClamps() { + Attribute sky = typed("minecraft:gameplay/sky_light_level"); + assertEquals(15f, sky.sanitize(20f)); + assertEquals(0f, sky.sanitize(-3f)); + assertEquals(7f, sky.sanitize(7f)); + Attribute flag = typed("minecraft:gameplay/can_start_raid"); + assertEquals(true, flag.sanitize(true)); + Attribute height = typed("terra:dimension/height"); + assertEquals(4064, height.sanitize(9999)); + } + + @Test + void typedKeys() throws ReflectiveOperationException { + Set> constants = new HashSet<>(); + for(Field field : MinecraftAttributes.class.getFields()) { + if(!Modifier.isStatic(field.getModifiers()) || field.getType() != AttributeKey.class) continue; + AttributeKey key = (AttributeKey) field.get(null); + Type argument = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; + Class valueClass = (Class) (argument instanceof ParameterizedType p ? p.getRawType() : argument); + + Attribute attribute = key.lookup(REGISTRY).orElseThrow(() -> new AssertionError("Not registered: " + key)); + assertSame(key, attribute.key(), field.getName()); + Object defaultValue = attribute.defaultValue(); + if(defaultValue != null) { + assertTrue(valueClass.isInstance(defaultValue), + field.getName() + ": " + defaultValue.getClass() + " is not a " + valueClass); + } + constants.add(key); + } + assertEquals(79, constants.size()); + assertEquals(Set.copyOf(MinecraftAttributes.all()), constants); + assertEquals(79, ALL.size()); + } + + @Test + void typedLookup() { + AttributeKey lookalike = AttributeKey.parse("minecraft:visual/fog_color"); + assertEquals(MinecraftAttributes.VISUAL_FOG_COLOR, lookalike); + assertTrue(lookalike.lookup(REGISTRY).isEmpty()); + assertTrue(REGISTRY.get(lookalike.getRegistryKey()).isPresent()); + } + + @Test + void keyIds() { + for(AttributeKey key : MinecraftAttributes.all()) { + String namespace = key.getRegistryKey().getNamespace(); + String path = key.getRegistryKey().getID(); + assertTrue(namespace.matches("[a-z0-9_.-]+") && path.matches("[a-z0-9_./-]+"), key.toString()); + } + } +} diff --git a/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftCodecRoundTripTest.java b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftCodecRoundTripTest.java new file mode 100644 index 000000000..f51d895c0 --- /dev/null +++ b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftCodecRoundTripTest.java @@ -0,0 +1,177 @@ +package attribute.minecraft; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +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 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.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.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.AttributeTypes; +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.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + + +class MinecraftCodecRoundTripTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final AttributeTypes CORE = HANDLE.types(); + private static final MinecraftAttributeTypes TYPES = new MinecraftAttributeTypes(HANDLE); + private static final DecodeContext PLAIN = HANDLE.plainContext(); + + private static final RawValue FLAME = new RawValue(map("type", "minecraft:flame")); + private static final RawValue UNIFORM = new RawValue(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3)); + private static final SoundRef SOUND = new SoundRef(RegistryKey.parse("minecraft:music.game"), OptionalDouble.empty()); + private static final SoundRef RANGED_SOUND = new SoundRef(RegistryKey.parse("minecraft:ambient.cave"), OptionalDouble.of(16)); + + private static Map map(Object... kv) { + Map m = new LinkedHashMap<>(); + for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]); + return m; + } + + private record Case(AttributeType type, List values, Map> arguments) { } + + private static Case of(AttributeType type, List values, Object... opArgs) { + Map> arguments = new LinkedHashMap<>(); + for(int i = 0; i < opArgs.length; i += 2) arguments.put((Operation) opArgs[i], (List) opArgs[i + 1]); + return new Case<>(type, values, arguments); + } + + private static List> cases() { + MobSpawnSettings spawns = new MobSpawnSettings( + Map.of("monster", List.of( + new MobSpawnSettings.Spawner(RegistryKey.parse("minecraft:zombie"), 95, + new IntProviderValue(OptionalInt.of(4), Optional.empty())), + new MobSpawnSettings.Spawner(RegistryKey.parse("minecraft:husk"), 5, + new IntProviderValue(OptionalInt.empty(), Optional.of(UNIFORM)))), + "ambient", List.of()), + Map.of(RegistryKey.parse("minecraft:enderman"), new MobSpawnSettings.Cost(0.7, 0.15))); + + return List.of( + of(TYPES.moonPhase(), List.of(MoonPhase.values())), + of(TYPES.bedRule(), List.of( + new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.NEVER, true, false, + Optional.of(new RawValue(map("translate", "block.minecraft.bed.no_sleep")))), + new BedRule(BedRule.Rule.ALWAYS, BedRule.Rule.ALWAYS, false, true, Optional.empty()))), + of(TYPES.particle(), List.of(FLAME, new RawValue(map("type", "minecraft:dust", "color", List.of(1.0, 0.5, 0.0), "scale", 2)))), + of(TYPES.ambientParticles(), List.of(List.of(), List.of(new AmbientParticle(FLAME, 0.025f))), + Operation.APPEND, List.of(List.of(new AmbientParticle(FLAME, 0.5f), new AmbientParticle(FLAME, 1f)))), + of(TYPES.backgroundMusic(), List.of(BackgroundMusic.EMPTY, + new BackgroundMusic(Optional.of(new Music(SOUND, 12000, 24000, true)), Optional.empty(), + Optional.of(new Music(RANGED_SOUND, 0, 1, false))))), + of(TYPES.ambientSounds(), List.of(AmbientSounds.EMPTY, + new AmbientSounds(Optional.of(RANGED_SOUND), Optional.of(new AmbientSounds.Mood(SOUND, 6000, 8, 2.0)), + List.of(new AmbientSounds.Additions(SOUND, 0.0111), new AmbientSounds.Additions(RANGED_SOUND, 0.5))))), + of(TYPES.mobSpawnSettings(), List.of(MobSpawnSettings.EMPTY, spawns), + Operation.OVERLAY, List.of(MobSpawnSettings.EMPTY, spawns)), + of(TYPES.identifier(), List.of(RegistryKey.parse("minecraft:stone"), RegistryKey.parse("my.pack:a/b"))), + of(TYPES.identifierOrTag(), List.>of( + Either.left(RegistryKey.parse("minecraft:stone")), Either.right(TagKey.parse("#my.pack:logs")))), + of(TYPES.intProvider(), List.of(new IntProviderValue(OptionalInt.of(-4), Optional.empty()), + new IntProviderValue(OptionalInt.empty(), Optional.of(UNIFORM)))), + of(CORE.enumType("skybox", Skybox.class), List.of(Skybox.values())), + of(CORE.enumType("cardinal_light", CardinalLight.class), List.of(CardinalLight.values())), + of(CORE.enumType("grass_color_modifier", GrassColorModifier.class), List.of(GrassColorModifier.values())), + of(CORE.enumType("temperature_modifier", TemperatureModifier.class), List.of(TemperatureModifier.values()))); + } + + private static void assertPlain(Object encoded, String where) { + if(encoded == null || encoded instanceof Number || encoded instanceof Boolean || encoded instanceof String) return; + if(encoded instanceof List list) { + for(Object element : list) assertPlain(element, where); + return; + } + if(encoded instanceof Map m) { + m.forEach((k, v) -> { + assertTrue(k instanceof String, where + ": map key " + k + " is not a string"); + assertPlain(v, where); + }); + return; + } + fail(where + ": encoded a " + encoded.getClass().getName() + ": " + encoded); + } + + private static void assertValuesRoundTrip(Case c) throws DecodeException { + for(T value : c.values()) { + Object encoded = c.type().encode(value); + assertPlain(encoded, c.type().id()); + assertEquals(value, c.type().decode(encoded, PLAIN), c.type().id() + " via " + encoded); + } + } + + @Test + void everyMinecraftType() throws DecodeException { + for(Case c : cases()) assertValuesRoundTrip(c); + } + + @Test + void everyArgument() throws DecodeException { + for(Case c : cases()) { + AttributeType type = c.type(); + List unsampled = new ArrayList<>(type.operations()); + unsampled.remove(Operation.OVERRIDE); + unsampled.removeAll(c.arguments().keySet()); + assertTrue(unsampled.isEmpty(), type.id() + " has no sample argument for " + unsampled); + + Map> arguments = new LinkedHashMap<>(c.arguments()); + arguments.put(Operation.OVERRIDE, c.values()); + for(Map.Entry> e : arguments.entrySet()) { + for(Object argument : e.getValue()) { + Object encoded = type.encodeArgument(e.getKey(), argument); + assertPlain(encoded, type.id() + " " + e.getKey().getID()); + assertEquals(argument, type.decodeArgument(e.getKey(), encoded, PLAIN), + type.id() + " " + e.getKey().getID() + " via " + encoded); + } + } + } + } + + @Test + void canonicalForms() { + assertEquals("minecraft:stone", TYPES.identifier().encode(RegistryKey.parse("minecraft:stone"))); + assertEquals("#minecraft:logs", TYPES.identifierOrTag().encode(Either.right(TagKey.parse("#minecraft:logs")))); + assertEquals("minecraft:stone", TYPES.identifierOrTag().encode(Either.left(RegistryKey.parse("minecraft:stone")))); + assertEquals("new_moon", TYPES.moonPhase().encode(MoonPhase.NEW_MOON)); + assertEquals("end", CORE.enumType("skybox", Skybox.class).encode(Skybox.END)); + assertEquals(map("type", "minecraft:flame"), TYPES.particle().encode(FLAME)); + assertEquals(7, TYPES.intProvider().encode(new IntProviderValue(OptionalInt.of(7), Optional.empty()))); + Map plainLoop = (Map) TYPES.ambientSounds().encode(new AmbientSounds(Optional.of(SOUND), Optional.empty(), List.of())); + assertEquals("minecraft:music.game", plainLoop.get("loop")); + Map rangedLoop = (Map) TYPES.ambientSounds().encode( + new AmbientSounds(Optional.of(RANGED_SOUND), Optional.empty(), List.of())); + assertEquals(map("sound_id", "minecraft:ambient.cave", "range", 16.0), rangedLoop.get("loop")); + Map bedRule = (Map) TYPES.bedRule().encode( + new BedRule(BedRule.Rule.NEVER, BedRule.Rule.NEVER, false, false, Optional.empty())); + assertFalse(bedRule.containsKey("error_message")); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/Platform.java b/common/api/src/main/java/com/dfsek/terra/api/Platform.java index 217b4dd69..5bda18bb4 100644 --- a/common/api/src/main/java/com/dfsek/terra/api/Platform.java +++ b/common/api/src/main/java/com/dfsek/terra/api/Platform.java @@ -23,6 +23,8 @@ import com.dfsek.terra.api.profiler.Profiler; import com.dfsek.terra.api.registry.CheckedRegistry; import com.dfsek.terra.api.registry.Registry; import com.dfsek.terra.api.tectonic.LoaderRegistrar; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeParents; /** @@ -89,4 +91,17 @@ public interface Platform extends LoaderRegistrar { @Contract(pure = true) int getGenerationThreads(); + + @NotNull + @Contract(pure = true) + AttributeHandle getAttributeHandle(); + + /** + * Each pack reads these once, when it loads. + */ + @NotNull + @Contract(pure = true) + default AttributeParents getAttributeParents() { + return AttributeParents.NONE; + } } diff --git a/common/api/src/main/java/com/dfsek/terra/api/properties/Context.java b/common/api/src/main/java/com/dfsek/terra/api/properties/Context.java index c8f5d807f..4643d3115 100644 --- a/common/api/src/main/java/com/dfsek/terra/api/properties/Context.java +++ b/common/api/src/main/java/com/dfsek/terra/api/properties/Context.java @@ -52,6 +52,14 @@ public class Context { return (T) list[key.key]; } + /** + * Unlike {@link #get(PropertyKey)}, safe for keys created after this context last stored a value. + */ + public boolean has(PropertyKey key) { + Properties[] current = list; + return key.key < current.length && current[key.key] != null; + } + public boolean has(Class test) { return map.containsKey(test); } diff --git a/common/api/src/main/java/com/dfsek/terra/api/registry/key/RegistryKey.java b/common/api/src/main/java/com/dfsek/terra/api/registry/key/RegistryKey.java index ebcf4b0a4..64262f515 100644 --- a/common/api/src/main/java/com/dfsek/terra/api/registry/key/RegistryKey.java +++ b/common/api/src/main/java/com/dfsek/terra/api/registry/key/RegistryKey.java @@ -1,29 +1,31 @@ package com.dfsek.terra.api.registry.key; -import java.util.Objects; import java.util.regex.Pattern; public final class RegistryKey implements StringIdentifiable, Namespaced { - private static final Pattern ID_PATTERN = Pattern.compile("^[a-zA-Z0-9_-]*$"); + private static final Pattern NAMESPACE_PATTERN = Pattern.compile("^[a-zA-Z0-9_.-]*$"); + private static final Pattern ID_PATTERN = Pattern.compile("^[a-zA-Z0-9_./-]*$"); private final String namespace; private final String id; + private final int hash; private RegistryKey(String namespace, String id) { - if(!ID_PATTERN.matcher(namespace).matches()) { + if(!NAMESPACE_PATTERN.matcher(namespace).matches()) { throw new IllegalArgumentException( - "Namespace must only contain alphanumeric characters, hyphens, and underscores. \"" + namespace + + "Namespace must only contain alphanumeric characters, hyphens, underscores, and periods. \"" + namespace + "\" is not a valid namespace."); } if(!ID_PATTERN.matcher(id).matches()) { throw new IllegalArgumentException( - "ID must only contain alphanumeric characters, hyphens, and underscores. \"" + id + + "ID must only contain alphanumeric characters, hyphens, underscores, periods, and slashes. \"" + id + "\" is not a valid ID."); } this.namespace = namespace; this.id = id; + this.hash = 31 * (31 + namespace.hashCode()) + id.hashCode(); } public static RegistryKey parse(String key) { @@ -36,6 +38,37 @@ public final class RegistryKey implements StringIdentifiable, Namespaced { return new RegistryKey(namespace, id); } + /** + * Parses {@code namespace:id}, or {@code id} in {@code defaultNamespace}. + * + * @throws IllegalArgumentException if a part is empty or invalid, or the key holds more than one {@code :} + */ + public static RegistryKey parse(String key, String defaultNamespace) { + // Shown to users in config warnings: no Java type names. + if(key == null) throw new IllegalArgumentException("malformed ID: none given"); + int colon = key.indexOf(':'); + if(colon != key.lastIndexOf(':')) throw new IllegalArgumentException(malformed(key, "more than one ':'")); + String namespace = colon < 0 ? defaultNamespace : key.substring(0, colon); + String id = key.substring(colon + 1); + if(namespace == null || namespace.isEmpty()) throw new IllegalArgumentException(malformed(key, "empty namespace")); + if(id.isEmpty()) throw new IllegalArgumentException(malformed(key, "empty ID")); + return new RegistryKey(namespace, id); + } + + private static String malformed(String key, String reason) { + return "malformed ID \"" + key + "\": " + reason; + } + + /** + * @throws IllegalArgumentException if the key has no namespace or is otherwise invalid + */ + public static RegistryKey parseNamespaced(String key) { + if(key != null && key.indexOf(':') < 0) { + throw new IllegalArgumentException("a namespace is required, as in \"namespace:" + key + "\""); + } + return parse(key, ""); + } + public static RegistryKey of(String namespace, String id) { return new RegistryKey(namespace, id); } @@ -52,13 +85,14 @@ public final class RegistryKey implements StringIdentifiable, Namespaced { @Override public int hashCode() { - return Objects.hash(namespace, id); + return hash; } @Override public boolean equals(Object obj) { + if(this == obj) return true; if(obj instanceof RegistryKey that) { - return this.id.equals(that.id) && this.namespace.equals(that.namespace); + return this.hash == that.hash && this.id.equals(that.id) && this.namespace.equals(that.namespace); } return false; } diff --git a/common/api/src/main/java/com/dfsek/terra/api/registry/key/TagKey.java b/common/api/src/main/java/com/dfsek/terra/api/registry/key/TagKey.java new file mode 100644 index 000000000..1b09e52ae --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/registry/key/TagKey.java @@ -0,0 +1,63 @@ +package com.dfsek.terra.api.registry.key; + +public final class TagKey { + private final RegistryKey key; + + private TagKey(RegistryKey key) { + this.key = key; + } + + public static TagKey of(RegistryKey key) { + return new TagKey(key); + } + + /** + * @throws IllegalArgumentException if the string does not start with {@code #}, has no namespace, or is not a valid + * {@link RegistryKey} + */ + public static TagKey parse(String tag) { + String body = body(tag); + try { + return new TagKey(RegistryKey.parseNamespaced(body)); + } catch(IllegalArgumentException e) { + if(body.indexOf(':') < 0) { + throw new IllegalArgumentException( + "invalid tag \"" + tag + "\": a namespace is required, as in \"#namespace:" + body + "\"", e); + } + throw e; + } + } + + /** + * Parses {@code #namespace:id}, or {@code #id} in {@code defaultNamespace}. + * + * @throws IllegalArgumentException if the string does not start with {@code #} or is not a valid {@link RegistryKey} + */ + public static TagKey parse(String tag, String defaultNamespace) { + return new TagKey(RegistryKey.parse(body(tag), defaultNamespace)); + } + + private static String body(String tag) { + if(tag == null || !tag.startsWith("#")) throw new IllegalArgumentException("invalid tag (expected #namespace:id): \"" + tag + "\""); + return tag.substring(1); + } + + public RegistryKey key() { + return key; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof TagKey that && key.equals(that.key); + } + + @Override + public int hashCode() { + return key.hashCode(); + } + + @Override + public String toString() { + return "#" + key; + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/Attribute.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/Attribute.java new file mode 100644 index 000000000..3a114bcf6 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/Attribute.java @@ -0,0 +1,63 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; + +import com.dfsek.terra.api.registry.key.Keyed; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.util.reflection.TypeKey; + + +/** + * Build each attribute once and register the same instance in every pack: every build takes a new {@link #index()}. + */ +public interface Attribute extends Keyed> { + TypeKey> REGISTRY_TYPE = new TypeKey<>() { }; + + AttributeKey key(); + + AttributeType type(); + + /** + * {@code null} means no override. + */ + @Nullable + T defaultValue(); + + AttributeScope scope(); + + /** + * @throws DecodeException if the value is outside this attribute's range or not a required multiple + */ + T validate(T value) throws DecodeException; + + /** + * Clamps numeric values to this attribute's range; returns other values unchanged. + */ + T sanitize(T value); + + /** + * Dense, from 0, below {@link AttributeHandle#attributeCount()}. + */ + @ApiStatus.Internal + int index(); + + @Override + default RegistryKey getRegistryKey() { + return key().getRegistryKey(); + } + + + interface Builder { + /** + * Values must lie in {@code [min, max]}; resolved values are clamped to it. + */ + Builder range(Number min, Number max); + + Builder multipleOf(int multipleOf); + + Builder packOnly(); + + Attribute build(); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodec.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodec.java new file mode 100644 index 000000000..88fc7b898 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodec.java @@ -0,0 +1,14 @@ +package com.dfsek.terra.api.world.attribute; + +public interface AttributeCodec { + /** + * @param raw a number, string, boolean, list, string-keyed map, or {@code null} + */ + T decode(Object raw, DecodeContext context) throws DecodeException; + + /** + * Returns a number, boolean, string, list or string-keyed map of those, or {@code null}. {@link #decode} must read it + * back to an equal value. + */ + Object encode(T value); +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodecs.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodecs.java new file mode 100644 index 000000000..de18a0b8d --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodecs.java @@ -0,0 +1,127 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +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; + + +public interface AttributeCodecs { + @FunctionalInterface + interface Decoder { + T decode(Object raw, DecodeContext context) throws DecodeException; + } + + + @FunctionalInterface + interface Encoder { + Object encode(T value); + } + + + /** + * Not thread safe. + */ + interface ObjectReader { + /** + * In config order. + */ + List keys(); + + /** + * @throws DecodeException if the key is missing or its value does not decode + */ + V required(String key, AttributeCodec codec) throws DecodeException; + + Optional optional(String key, AttributeCodec codec) throws DecodeException; + + V orDefault(String key, AttributeCodec codec, V fallback) throws DecodeException; + + /** + * @throws DecodeException if the object has a key that was not read + */ + void finish() throws DecodeException; + } + + + /** + * Not thread safe. Keeps fields in the order written. + */ + interface ObjectWriter { + ObjectWriter put(String key, AttributeCodec codec, V value); + + ObjectWriter optional(String key, AttributeCodec codec, Optional value); + + Map map(); + } + + AttributeCodec of(Decoder decoder, Encoder encoder); + + /** + * Names {@code value} for messages, such as {@code "text"}, {@code an object} or {@code nothing}. + */ + String describe(@Nullable Object value); + + AttributeCodec booleanCodec(); + + AttributeCodec floatCodec(); + + AttributeCodec doubleCodec(); + + /** + * Rejects fractions and values outside the {@code int} range. + */ + AttributeCodec intCodec(); + + AttributeCodec nonNegativeInt(); + + AttributeCodec unitFloat(); + + /** + * @param expected the start of the message when the value is not a string, as in {@code expected a sound ID} + */ + AttributeCodec string(String expected); + + AttributeCodec raw(); + + AttributeCodec> list(AttributeCodec element); + + /** + * Also reads a single element as a list of one. Always encodes a list. + */ + AttributeCodec> compactList(AttributeCodec element); + + /** + * Reads constants by {@link StringIdentifiable#getID() ID}. + * + * @param name names the enum in messages, such as {@code moon phase} + * + * @throws IllegalArgumentException if two constants share an ID + */ + & StringIdentifiable> AttributeCodec enumCodec(String name, Class type); + + /** + * A bare ID takes {@code defaultNamespace}. Tags are rejected. + */ + AttributeCodec identifier(String defaultNamespace); + + /** + * A bare ID takes {@code defaultNamespace}. + */ + AttributeCodec> identifierOrTag(String defaultNamespace); + + /** + * @param what names the object in messages, such as {@code music} + * + * @throws DecodeException if {@code raw} is not an object, or has a key that is not a string + */ + ObjectReader reader(String what, Object raw, DecodeContext context) throws DecodeException; + + ObjectWriter writer(); +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeEntry.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeEntry.java new file mode 100644 index 000000000..65a6cf740 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeEntry.java @@ -0,0 +1,43 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; + + +public record AttributeEntry(@NotNull Operation operation, @Nullable Object argument) { + /** + * @throws IllegalArgumentException if {@code argument} is {@code null} and {@code operation} is not {@link Operation#OVERRIDE} + */ + public AttributeEntry { + Objects.requireNonNull(operation, "operation"); + if(argument == null && operation != Operation.OVERRIDE) { + throw new IllegalArgumentException("modifier " + operation.getID() + " needs an argument"); + } + } + + @NotNull + @Contract("_ -> new") + public static AttributeEntry override(@Nullable T value) { + return new AttributeEntry<>(Operation.OVERRIDE, value); + } + + /** + * @throws IllegalArgumentException if {@code argument} is {@code null} and {@code op} is not {@link Operation#OVERRIDE} + */ + @NotNull + @Contract("_, _ -> new") + public static AttributeEntry of(@NotNull Operation op, @Nullable Object argument) { + return new AttributeEntry<>(op, argument); + } + + public T apply(@NotNull AttributeType type, T subject) { + return type.apply(operation, subject, argument); + } + + public boolean isOverride() { + return operation == Operation.OVERRIDE; + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeHandle.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeHandle.java new file mode 100644 index 000000000..fc20d02fc --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeHandle.java @@ -0,0 +1,110 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.Optional; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult; + + +public interface AttributeHandle { + @NotNull + @Contract(pure = true) + AttributeTypes types(); + + /** + * Applies no config preprocessing. + */ + @NotNull + @Contract(pure = true) + DecodeContext plainContext(); + + @NotNull + @Contract(pure = true) + AttributeCodecs codecs(); + + @NotNull + @Contract("_, _ -> new") + AttributeType.Builder typeBuilder(@NotNull String id, @NotNull AttributeCodec codec); + + @NotNull + @Contract("_, _, _ -> new") + Attribute.Builder attributeBuilder(@NotNull AttributeKey key, @NotNull AttributeType type, @Nullable T defaultValue); + + /** + * Only grows. Every {@link Attribute#index()} is below it. + */ + @ApiStatus.Internal + int attributeCount(); + + /** + * Applies each non-null layer, bottom first, to the default, then sanitizes. A {@code null} value only changes on an override. + */ + @SuppressWarnings("unchecked") + @Contract(pure = true) + @Nullable T resolve(@NotNull Attribute attribute, AttributeEntry... layersBottomToTop); + + /** + * Allocation-free {@link #resolve(Attribute, AttributeEntry[])}, bottom layer first. + */ + @Contract(pure = true) + @Nullable T resolve(@NotNull Attribute attribute, @Nullable AttributeEntry first, @Nullable AttributeEntry second, + @Nullable AttributeEntry third); + + /** + * Allocation-free {@link #resolve(Attribute, AttributeEntry[])}, bottom layer first. + */ + @Contract(pure = true) + @Nullable T resolve(@NotNull Attribute attribute, @Nullable AttributeEntry first, @Nullable AttributeEntry second, + @Nullable AttributeEntry third, @Nullable AttributeEntry fourth); + + /** + * Composes two layers into one entry that applies like {@code lower} then {@code upper}. Empty when both are {@code null} + * or they don't compose; fall back to an override of the {@link #resolve resolved} value. Float results may differ by rounding. + */ + @NotNull + @Contract(pure = true) + Optional> compose(@NotNull Attribute attribute, @Nullable AttributeEntry lower, + @Nullable AttributeEntry upper); + + /** + * Reads a bare value as an override, or a {@code modifier} and {@code argument} map. Resolves {@code raw} first. + */ + @NotNull + AttributeEntry decodeEntry(@NotNull Attribute attribute, @Nullable Object raw, @NotNull DecodeContext context) + throws DecodeException; + + /** + * @throws IllegalArgumentException if {@code entry} is an override of {@code null} + */ + @NotNull + @Contract(pure = true) + Object encodeEntry(@NotNull Attribute attribute, @NotNull AttributeEntry entry); + + /** + * {@code raw} must already be {@link DecodeContext#resolve resolved}. A bad track is dropped; other problems skip the schedule. + */ + @NotNull + ScheduleDecodeResult decodeSchedule(@NotNull RegistryKey id, @NotNull Map raw, @NotNull AttributeLookup attributes, + @NotNull DecodeContext context); + + /** + * @throws IllegalArgumentException if a keyframe's argument is {@code null} + */ + @NotNull + @Contract(pure = true) + Map encodeSchedule(@NotNull AttributeSchedule schedule); + + /** + * Empty unless the {@code config-attributes} addon loaded {@code pack}. + */ + @NotNull + Optional pack(@NotNull ConfigPack pack); +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeKey.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeKey.java new file mode 100644 index 000000000..e79bc04b1 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeKey.java @@ -0,0 +1,71 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; + +import com.dfsek.terra.api.registry.Registry; +import com.dfsek.terra.api.registry.key.Keyed; +import com.dfsek.terra.api.registry.key.RegistryKey; + + +public final class AttributeKey implements Keyed> { + private final RegistryKey key; + + private AttributeKey(RegistryKey key) { + this.key = key; + } + + @NotNull + public static AttributeKey of(@NotNull RegistryKey key) { + return new AttributeKey<>(key); + } + + /** + * {@code T} is unchecked: {@link #lookup} returns empty for a key made here. + * + * @throws IllegalArgumentException if the key has no namespace or is not a valid {@link RegistryKey} + */ + @NotNull + public static AttributeKey parse(@NotNull String key) { + if(key == null) throw new IllegalArgumentException("invalid attribute key: null"); + try { + return new AttributeKey<>(RegistryKey.parseNamespaced(key)); + } catch(IllegalArgumentException e) { + if(key.indexOf(':') < 0) throw new IllegalArgumentException("invalid attribute key \"" + key + "\": " + e.getMessage(), e); + throw new IllegalArgumentException("invalid attribute key: \"" + key + "\"", e); + } + } + + /** + * Empty unless the registered attribute's {@link Attribute#key()} is this instance. + */ + @SuppressWarnings("unchecked") + @NotNull + public Optional> lookup(@NotNull Registry> registry) { + Optional> attribute = registry.get(key); + if(attribute.isEmpty() || attribute.get().key() != this) return Optional.empty(); + return Optional.of((Attribute) attribute.get()); + } + + @Override + public RegistryKey getRegistryKey() { + return key; + } + + @Override + public boolean equals(Object obj) { + if(this == obj) return true; + return obj instanceof AttributeKey that && key.equals(that.key); + } + + @Override + public int hashCode() { + return key.hashCode(); + } + + @Override + public String toString() { + return key.toString(); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeLookup.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeLookup.java new file mode 100644 index 000000000..d18cde027 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeLookup.java @@ -0,0 +1,9 @@ +package com.dfsek.terra.api.world.attribute; + +@FunctionalInterface +public interface AttributeLookup { + /** + * @throws DecodeException if {@code key} names no usable attribute; the message is reported as the reason + */ + Attribute find(String key) throws DecodeException; +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeMap.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeMap.java new file mode 100644 index 000000000..820f7e355 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeMap.java @@ -0,0 +1,103 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + + +public final class AttributeMap { + private static final AttributeMap EMPTY = new AttributeMap(Map.of()); + + private final Map, AttributeEntry> entries; + + private AttributeMap(Map, AttributeEntry> entries) { + this.entries = entries; + } + + @NotNull + @Contract(pure = true) + public static AttributeMap empty() { + return EMPTY; + } + + @NotNull + @Contract("-> new") + public static Builder builder() { + return new Builder(); + } + + @NotNull + @SuppressWarnings("unchecked") + public Optional> get(@NotNull AttributeKey key) { + return Optional.ofNullable((AttributeEntry) entries.get(key)); + } + + /** + * In insertion order. Unmodifiable. + */ + @NotNull + public Set> keys() { + return entries.keySet(); + } + + public boolean isEmpty() { + return entries.isEmpty(); + } + + /** + * {@code top}'s entries replace this map's per key. + */ + @NotNull + public AttributeMap overlay(@NotNull AttributeMap top) { + Objects.requireNonNull(top, "top"); + if(top.entries.isEmpty()) return this; + if(entries.isEmpty()) return top; + Map, AttributeEntry> merged = new LinkedHashMap<>(entries); + merged.putAll(top.entries); + return new AttributeMap(Collections.unmodifiableMap(merged)); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof AttributeMap that && entries.equals(that.entries); + } + + @Override + public int hashCode() { + return entries.hashCode(); + } + + @Override + public String toString() { + return "AttributeMap" + entries; + } + + + public static final class Builder { + private final Map, AttributeEntry> entries = new LinkedHashMap<>(); + + private Builder() { + } + + public Builder put(AttributeKey key, AttributeEntry entry) { + entries.put(Objects.requireNonNull(key, "key"), Objects.requireNonNull(entry, "entry")); + return this; + } + + public Builder remove(AttributeKey key) { + entries.remove(key); + return this; + } + + public AttributeMap build() { + if(entries.isEmpty()) return EMPTY; + return new AttributeMap(Collections.unmodifiableMap(new LinkedHashMap<>(entries))); + } + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeModifier.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeModifier.java new file mode 100644 index 000000000..a56e6d6ad --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeModifier.java @@ -0,0 +1,6 @@ +package com.dfsek.terra.api.world.attribute; + +@FunctionalInterface +public interface AttributeModifier { + T apply(T subject, A argument); +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeParents.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeParents.java new file mode 100644 index 000000000..fd2bb50aa --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeParents.java @@ -0,0 +1,33 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.Nullable; + +import com.dfsek.terra.api.world.biome.Biome; + + +/** + * Called on read paths: must not allocate. + */ +public interface AttributeParents { + AttributeParents NONE = new AttributeParents() { + @Override + public @Nullable AttributeEntry biomeOrNull(Biome biome, Attribute attribute) { + return null; + } + + @Override + public @Nullable AttributeEntry packOrNull(PackAttributes pack, Attribute attribute) { + return null; + } + }; + + /** + * Sits between the pack entry and the biome's own entry. + */ + @Nullable AttributeEntry biomeOrNull(Biome biome, Attribute attribute); + + /** + * Sits between the attribute's default and the pack entry. + */ + @Nullable AttributeEntry packOrNull(PackAttributes pack, Attribute attribute); +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeScope.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeScope.java new file mode 100644 index 000000000..46d97a72e --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeScope.java @@ -0,0 +1,6 @@ +package com.dfsek.terra.api.world.attribute; + +public enum AttributeScope { + ANYWHERE, + PACK_ONLY +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeType.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeType.java new file mode 100644 index 000000000..99204bea5 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeType.java @@ -0,0 +1,61 @@ +package com.dfsek.terra.api.world.attribute; + +import java.util.Optional; +import java.util.Set; +import java.util.function.BinaryOperator; + + +public interface AttributeType { + String id(); + + /** + * Always includes {@link Operation#OVERRIDE}. Unmodifiable. + */ + Set operations(); + + T decode(Object raw, DecodeContext context) throws DecodeException; + + Object encode(T value); + + /** + * @throws DecodeException if {@code op} is not valid for this type, or the argument does not decode + */ + Object decodeArgument(Operation op, Object raw, DecodeContext context) throws DecodeException; + + /** + * @throws IllegalArgumentException if {@code op} is not valid for this type + */ + Object encodeArgument(Operation op, Object argument); + + /** + * @throws IllegalArgumentException if {@code op} is not valid for this type + */ + T apply(Operation op, T subject, Object argument); + + /** + * @return empty when the type has no composer for {@code op} + * + * @throws NullPointerException if the composer returns {@code null} + */ + Optional compose(Operation op, Object lower, Object upper); + + + interface Builder { + /** + * Replaces an earlier {@code op} and drops its composer. + * + * @throws IllegalArgumentException if {@code op} is {@link Operation#OVERRIDE} + */ + Builder op(Operation op, AttributeCodec argumentCodec, AttributeModifier modifier); + + /** + * {@code combine(lower, upper)} must apply like {@code lower} then {@code upper}. {@code A} must be the argument type + * {@code op} was added with. + * + * @throws IllegalArgumentException if {@code op} is {@link Operation#OVERRIDE} or was not added first + */ + Builder composable(Operation op, BinaryOperator combine); + + AttributeType build(); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeTypes.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeTypes.java new file mode 100644 index 000000000..f9fd2f693 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeTypes.java @@ -0,0 +1,68 @@ +package com.dfsek.terra.api.world.attribute; + +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.value.Color; +import com.dfsek.terra.api.world.attribute.value.TriState; + + +public interface AttributeTypes { + /** + * {@code and}, {@code nand}, {@code or}, {@code nor}, {@code xor}, {@code xnor}. + */ + AttributeType booleanType(); + + /** + * Override only. + */ + AttributeType triState(); + + /** + * {@code alpha_blend}, {@code add}, {@code subtract}, {@code multiply}, {@code minimum}, {@code maximum}. + */ + AttributeType floatType(); + + /** + * The {@link #floatType()} library. + */ + AttributeType angleDegrees(); + + /** + * {@code alpha_blend}, {@code add}, {@code subtract}, {@code multiply}, {@code blend_to_gray}. + */ + AttributeType rgbColor(); + + /** + * {@code alpha_blend}, {@code add}, {@code subtract}, {@code multiply}, {@code blend_to_gray}. + */ + AttributeType argbColor(); + + /** + * {@code add}, {@code subtract}, {@code multiply}, {@code minimum}, {@code maximum}. + */ + AttributeType integer(); + + /** + * Override only. + */ + AttributeType integerOverrideOnly(); + + /** + * Any ID; a bare ID takes {@code defaultNamespace}. Tags are rejected. Override only. + */ + AttributeType identifier(String defaultNamespace); + + /** + * An ID or a {@code #tag}; a bare ID takes {@code defaultNamespace}. Override only. + */ + AttributeType> identifierOrTag(String defaultNamespace); + + /** + * An enum identified by its {@link StringIdentifiable#getID() ID}. Override only. + * + * @param type its constants' IDs must be distinct + */ + & StringIdentifiable> AttributeType enumType(String id, Class type); +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeContext.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeContext.java new file mode 100644 index 000000000..4446b4ff5 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeContext.java @@ -0,0 +1,17 @@ +package com.dfsek.terra.api.world.attribute; + +import java.lang.reflect.Type; + + +public interface DecodeContext { + /** + * {@code type} is {@code Float}, {@code Integer}, {@code Double}, {@code Boolean}, {@code String}, {@code List}, + * {@code Map} or {@code Object}. + */ + V load(Type type, Object raw) throws DecodeException; + + /** + * Call before checking a value's shape. Numeric expressions stay strings; {@link #load} evaluates them. + */ + Object resolve(Object raw) throws DecodeException; +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeException.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeException.java new file mode 100644 index 000000000..06af170cb --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeException.java @@ -0,0 +1,14 @@ +package com.dfsek.terra.api.world.attribute; + +/** + * The message is shown to users in config warnings. + */ +public class DecodeException extends Exception { + public DecodeException(String message) { + super(message); + } + + public DecodeException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/Operation.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/Operation.java new file mode 100644 index 000000000..91e557ee8 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/Operation.java @@ -0,0 +1,44 @@ +package com.dfsek.terra.api.world.attribute; + +import com.dfsek.terra.api.registry.key.StringIdentifiable; + + +public enum Operation implements StringIdentifiable { + OVERRIDE("override"), + ALPHA_BLEND("alpha_blend"), + ADD("add"), + SUBTRACT("subtract"), + MULTIPLY("multiply"), + BLEND_TO_GRAY("blend_to_gray"), + MINIMUM("minimum"), + MAXIMUM("maximum"), + AND("and"), + NAND("nand"), + OR("or"), + NOR("nor"), + XOR("xor"), + XNOR("xnor"), + APPEND("append"), + OVERLAY("overlay"); + + private final String id; + + Operation(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } + + /** + * @throws IllegalArgumentException if no operation has this {@link #getID() ID} + */ + public static Operation parse(String name) { + for(Operation value : values()) { + if(value.id.equals(name)) return value; + } + throw new IllegalArgumentException("unknown modifier \"" + name + "\""); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/PackAttributes.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/PackAttributes.java new file mode 100644 index 000000000..a22882288 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/PackAttributes.java @@ -0,0 +1,64 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.properties.Properties; +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.schedule.AttributeSchedule; +import com.dfsek.terra.api.world.biome.Biome; + + +/** + * Reads resolve the static layers only; schedules are not applied. + */ +public interface PackAttributes extends Properties { + @NotNull + AttributeMap entries(); + + /** + * By config key, in config order. Unmodifiable. + */ + @NotNull + Map parents(); + + /** + * In config order. + */ + @NotNull + List> scheduleRefs(); + + /** + * By ID, in config order. Unmodifiable. + */ + @NotNull + Map scheduleDefinitions(); + + /** + * {@code null} if the biome is not from this pack. Allocation-free. + */ + @Nullable + AttributeEntry biomeEntryOrNull(@NotNull Attribute attribute, @NotNull Biome biome); + + /** + * Merged across the biome's {@code extends} chain. Empty if the biome is not from this pack. + */ + @NotNull + AttributeMap biomeEntries(@NotNull Biome biome); + + /** + * Layers, bottom first: default, {@link AttributeParents#packOrNull pack parent}, pack entry, + * {@link AttributeParents#biomeOrNull biome parent}, biome entry. + */ + @Nullable T resolve(@NotNull Attribute attribute, @NotNull Biome biome); + + /** + * Layers, bottom first: default, {@link AttributeParents#packOrNull pack parent}, pack entry. + */ + @Nullable T resolvePack(@NotNull Attribute attribute); +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/RawValue.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/RawValue.java new file mode 100644 index 000000000..ad45ce155 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/RawValue.java @@ -0,0 +1,34 @@ +package com.dfsek.terra.api.world.attribute; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + + +public record RawValue(Object value) { + public RawValue { + value = copy(value); + } + + private static Object copy(Object o) { + if(o == null || o instanceof String || o instanceof Number || o instanceof Boolean) return o; + if(o instanceof List list) { + List out = new ArrayList<>(list.size()); + for(Object e : list) out.add(copy(e)); + return Collections.unmodifiableList(out); + } + if(o instanceof Map map) { + Map out = new LinkedHashMap<>(); + for(Map.Entry e : map.entrySet()) { + if(!(e.getKey() instanceof String key)) { + throw new IllegalArgumentException("unsupported value: map keys must be strings"); + } + out.put(key, copy(e.getValue())); + } + return Collections.unmodifiableMap(out); + } + throw new IllegalArgumentException("unsupported value"); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/AttributeSchedule.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/AttributeSchedule.java new file mode 100644 index 000000000..d37c81276 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/AttributeSchedule.java @@ -0,0 +1,21 @@ +package com.dfsek.terra.api.world.attribute.schedule; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.OptionalInt; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.attribute.Attribute; + + +/** + * Both maps are unmodifiable copies in the given order. + */ +public record AttributeSchedule(RegistryKey clock, OptionalInt periodTicks, Map, ScheduleTrack> tracks, + Map timeMarkers) { + public AttributeSchedule { + tracks = Collections.unmodifiableMap(new LinkedHashMap<>(tracks)); + timeMarkers = Collections.unmodifiableMap(new LinkedHashMap<>(timeMarkers)); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Easing.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Easing.java new file mode 100644 index 000000000..44f3dd80b --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Easing.java @@ -0,0 +1,29 @@ +package com.dfsek.terra.api.world.attribute.schedule; + +import java.util.Set; + + +public sealed interface Easing { + Set NAMES = Set.of( + "constant", "linear", + "in_back", "in_bounce", "in_circ", "in_cubic", "in_elastic", "in_expo", "in_quad", "in_quart", "in_quint", "in_sine", + "in_out_back", "in_out_bounce", "in_out_circ", "in_out_cubic", "in_out_elastic", "in_out_expo", "in_out_quad", + "in_out_quart", "in_out_quint", "in_out_sine", + "out_back", "out_bounce", "out_circ", "out_cubic", "out_elastic", "out_expo", "out_quad", "out_quart", "out_quint", + "out_sine"); + + + record Named(String name) implements Easing { + public Named { + if(!NAMES.contains(name)) throw new IllegalArgumentException("unknown easing \"" + name + "\""); + } + } + + + record CubicBezier(float x1, float y1, float x2, float y2) implements Easing { + public CubicBezier { + if(!(x1 >= 0f && x1 <= 1f)) throw new IllegalArgumentException("cubic_bezier x1 is outside [0, 1]"); + if(!(x2 >= 0f && x2 <= 1f)) throw new IllegalArgumentException("cubic_bezier x2 is outside [0, 1]"); + } + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Keyframe.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Keyframe.java new file mode 100644 index 000000000..13cb04aa2 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Keyframe.java @@ -0,0 +1,6 @@ +package com.dfsek.terra.api.world.attribute.schedule; + +/** + * {@code argument} comes from {@link com.dfsek.terra.api.world.attribute.AttributeType#decodeArgument}. + */ +public record Keyframe(int ticks, Object argument) { } diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleDecodeResult.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleDecodeResult.java new file mode 100644 index 000000000..8daeb1b2f --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleDecodeResult.java @@ -0,0 +1,20 @@ +package com.dfsek.terra.api.world.attribute.schedule; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; + + +public record ScheduleDecodeResult(Optional schedule, List droppedTracks, Optional skipped) { + public ScheduleDecodeResult { + Objects.requireNonNull(schedule, "schedule"); + droppedTracks = List.copyOf(droppedTracks); + Objects.requireNonNull(skipped, "skipped"); + if(schedule.isPresent() == skipped.isPresent()) { + throw new IllegalArgumentException("exactly one of schedule and skipped must be present"); + } + } + + + public record Problem(String key, String reason) { } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleTrack.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleTrack.java new file mode 100644 index 000000000..84c53a784 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleTrack.java @@ -0,0 +1,12 @@ +package com.dfsek.terra.api.world.attribute.schedule; + +import java.util.List; + +import com.dfsek.terra.api.world.attribute.Operation; + + +public record ScheduleTrack(Operation operation, List keyframes, Easing ease) { + public ScheduleTrack { + keyframes = List.copyOf(keyframes); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/TimeMarker.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/TimeMarker.java new file mode 100644 index 000000000..400a7af49 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/TimeMarker.java @@ -0,0 +1,3 @@ +package com.dfsek.terra.api.world.attribute.schedule; + +public record TimeMarker(int ticks, boolean showInCommands) { } diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/BlendToGray.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/BlendToGray.java new file mode 100644 index 000000000..5d52aa695 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/BlendToGray.java @@ -0,0 +1,6 @@ +package com.dfsek.terra.api.world.attribute.value; + +/** + * Both in [0, 1]. + */ +public record BlendToGray(float brightness, float factor) { } diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/Color.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/Color.java new file mode 100644 index 000000000..096e9077c --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/Color.java @@ -0,0 +1,97 @@ +package com.dfsek.terra.api.world.attribute.value; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.List; +import java.util.regex.Pattern; + + +/** + * Channels are in [0, 1]. + */ +public record Color(float r, float g, float b, float a) { + private static final Pattern HEX6 = Pattern.compile("#[0-9a-fA-F]{6}"); + private static final Pattern HEX8 = Pattern.compile("#[0-9a-fA-F]{8}"); + + public static Color rgb(int rgb) { + return new Color(((rgb >> 16) & 0xFF) / 255f, ((rgb >> 8) & 0xFF) / 255f, (rgb & 0xFF) / 255f, 1f); + } + + public static Color argb(int argb) { + return new Color(((argb >> 16) & 0xFF) / 255f, ((argb >> 8) & 0xFF) / 255f, (argb & 0xFF) / 255f, ((argb >>> 24) & 0xFF) / 255f); + } + + /** + * Accepts {@code "#rrggbb"}, a list of 3 floats, or an integer {@code 0xRRGGBB} (alpha bits ignored). + */ + public static Color parseRgb(Object o) { + if(o instanceof String s) { + if(!HEX6.matcher(s).matches()) throw new IllegalArgumentException("invalid RGB color (expected #rrggbb): \"" + s + "\""); + return rgb(Integer.parseInt(s.substring(1), 16)); + } + if(o instanceof List l) { + if(l.size() != 3) throw new IllegalArgumentException("color list must have 3 elements, got " + l); + return new Color(channel(l.get(0)), channel(l.get(1)), channel(l.get(2)), 1f); + } + if(o instanceof Number n) return rgb(integral(n, Integer.MAX_VALUE)); + throw new IllegalArgumentException("invalid RGB color: " + o); + } + + /** + * Accepts {@code "#aarrggbb"}, a list of 4 floats (r, g, b, a), or an integer {@code 0xAARRGGBB}, signed or unsigned. + */ + public static Color parseArgb(Object o) { + if(o instanceof String s) { + if(!HEX8.matcher(s).matches()) throw new IllegalArgumentException("invalid ARGB color (expected #aarrggbb): \"" + s + "\""); + return argb((int) Long.parseLong(s.substring(1), 16)); + } + if(o instanceof List l) { + if(l.size() != 4) throw new IllegalArgumentException("color list must have 4 elements, got " + l); + return new Color(channel(l.get(0)), channel(l.get(1)), channel(l.get(2)), channel(l.get(3))); + } + if(o instanceof Number n) return argb(integral(n, 0xFFFFFFFFL)); + throw new IllegalArgumentException("invalid ARGB color: " + o); + } + + private static int integral(Number n, long max) { + BigInteger value; + try { + value = exact(n).toBigIntegerExact(); + } catch(ArithmeticException | NumberFormatException e) { + throw new IllegalArgumentException("color integer must be integral: " + n); + } + if(value.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0 || value.compareTo(BigInteger.valueOf(max)) > 0) { + throw new IllegalArgumentException("value " + n + " is outside [" + Integer.MIN_VALUE + ", " + max + "]"); + } + return value.intValue(); + } + + private static BigDecimal exact(Number n) { + if(n instanceof Integer || n instanceof Long || n instanceof Short || n instanceof Byte) return BigDecimal.valueOf(n.longValue()); + if(n instanceof BigDecimal d) return d; + if(n instanceof BigInteger i) return new BigDecimal(i); + if(n instanceof Double || n instanceof Float) { + double d = n.doubleValue(); + if(!Double.isFinite(d)) throw new NumberFormatException(); + return new BigDecimal(d); + } + return new BigDecimal(n.toString()); + } + + private static float channel(Object o) { + if(o instanceof Number n) return n.floatValue(); + throw new IllegalArgumentException("color channel must be a number: " + o); + } + + private static int to255(float c) { + return Math.max(0, Math.min(255, Math.round(c * 255))); + } + + public int toRgbInt() { + return (to255(r) << 16) | (to255(g) << 8) | to255(b); + } + + public int toArgbInt() { + return (to255(a) << 24) | toRgbInt(); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/FloatWithAlpha.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/FloatWithAlpha.java new file mode 100644 index 000000000..735d32cf6 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/FloatWithAlpha.java @@ -0,0 +1,6 @@ +package com.dfsek.terra.api.world.attribute.value; + +/** + * {@code alpha} is in [0, 1]. + */ +public record FloatWithAlpha(float value, float alpha) { } diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/TriState.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/TriState.java new file mode 100644 index 000000000..51b19cde0 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/TriState.java @@ -0,0 +1,21 @@ +package com.dfsek.terra.api.world.attribute.value; + +import com.dfsek.terra.api.registry.key.StringIdentifiable; + + +public enum TriState implements StringIdentifiable { + TRUE("true"), + FALSE("false"), + DEFAULT("default"); + + private final String id; + + TriState(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } +} diff --git a/common/api/src/test/java/com/dfsek/terra/api/registry/key/RegistryKeyTest.java b/common/api/src/test/java/com/dfsek/terra/api/registry/key/RegistryKeyTest.java new file mode 100644 index 000000000..f5aa9be5c --- /dev/null +++ b/common/api/src/test/java/com/dfsek/terra/api/registry/key/RegistryKeyTest.java @@ -0,0 +1,113 @@ +package com.dfsek.terra.api.registry.key; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.Objects; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +public class RegistryKeyTest { + @ParameterizedTest + @CsvSource({ + "mypack:visual/fog_color, mypack, visual/fog_color", + "mypack:ambient.cave, mypack, ambient.cave", + "my.pack:thing, my.pack, thing", + "terra:overworld_biome-1, terra, overworld_biome-1", + "MyPack:Seasons, MyPack, Seasons", + }) + void validKeysParse(String key, String namespace, String id) { + RegistryKey parsed = RegistryKey.parse(key); + assertEquals(RegistryKey.of(namespace, id), parsed); + assertEquals(namespace, parsed.getNamespace()); + assertEquals(id, parsed.getID()); + assertEquals(key, parsed.toString()); + assertEquals(parsed, RegistryKey.parse(key, "other")); + assertEquals(parsed, RegistryKey.parseNamespaced(key)); + } + + @ParameterizedTest + @ValueSource(strings = { "a/b:thing", "bad key", "a:b:c", "a:b c", "a b:c" }) + void invalidKeysAreRejected(String key) { + assertThrows(IllegalArgumentException.class, () -> RegistryKey.parse(key)); + } + + @Test + void invalidCharacterMessage() { + String id = assertThrows(IllegalArgumentException.class, () -> RegistryKey.of("a", "b c")).getMessage(); + assertTrue(id.contains("slashes") && id.contains("periods") && id.contains("\"b c\""), id); + String ns = assertThrows(IllegalArgumentException.class, () -> RegistryKey.of("a b", "c")).getMessage(); + assertTrue(ns.contains("periods") && !ns.contains("slashes") && ns.contains("\"a b\""), ns); + } + + @Test + void hashAndEquals() { + RegistryKey key = RegistryKey.parse("mypack:visual/fog_color"); + RegistryKey same = RegistryKey.of("mypack", "visual/fog_color"); + assertEquals(Objects.hash("mypack", "visual/fog_color"), key.hashCode()); + assertEquals(key, same); + assertEquals(key.hashCode(), same.hashCode()); + assertNotEquals(key, RegistryKey.of("mypack", "visual/sky_color")); + assertNotEquals(key, RegistryKey.of("terra", "visual/fog_color")); + assertNotEquals(RegistryKey.of("a", "bc"), RegistryKey.of("ab", "c")); + assertNotEquals(key, "mypack:visual/fog_color"); + } + + @Test + void parseWithDefaultNamespace() { + assertEquals(RegistryKey.of("mypack", "fog"), RegistryKey.parse("fog", "mypack")); + assertEquals(RegistryKey.of("my.pack", "a/b"), RegistryKey.parse("my.pack:a/b", "mypack")); + } + + @ParameterizedTest + @CsvSource(nullValues = "NULL", value = { + ":x, mypack, 'malformed ID \":x\": empty namespace'", + "x:, mypack, 'malformed ID \"x:\": empty ID'", + "'', mypack, 'malformed ID \"\": empty ID'", + "NULL, mypack, 'malformed ID: none given'", + "x, NULL, 'malformed ID \"x\": empty namespace'", + "a:b:c, mypack, 'malformed ID \"a:b:c\": more than one '':'''", + }) + void parseWithDefaultNamespaceRejects(String key, String defaultNamespace, String message) { + assertEquals(message, assertThrows(IllegalArgumentException.class, () -> RegistryKey.parse(key, defaultNamespace)).getMessage()); + } + + @Test + void parseNamespacedWithoutNamespace() { + assertEquals("a namespace is required, as in \"namespace:overworld\"", + assertThrows(IllegalArgumentException.class, () -> RegistryKey.parseNamespaced("overworld")).getMessage()); + } + + @ParameterizedTest + @NullSource + @ValueSource(strings = { "mypack:Bad Id", "#mypack:tag", "mypack:", ":overworld", "a:b:c" }) + void parseNamespacedRejects(String key) { + assertThrows(IllegalArgumentException.class, () -> RegistryKey.parseNamespaced(key)); + } + + @Test + void tagKey() { + TagKey tag = TagKey.parse("#mypack:infiniburn"); + assertEquals(RegistryKey.parse("mypack:infiniburn"), tag.key()); + assertEquals("#mypack:infiniburn", tag.toString()); + assertEquals(tag, TagKey.parse("#infiniburn", "mypack")); + assertEquals(tag, TagKey.of(RegistryKey.parse("mypack:infiniburn"))); + assertEquals(RegistryKey.of("mypack", "Music.Game"), TagKey.parse("#mypack:Music.Game").key()); + assertEquals(RegistryKey.of("MyPack", "Logs"), TagKey.parse("#Logs", "MyPack").key()); + assertEquals("invalid tag \"#stone\": a namespace is required, as in \"#namespace:stone\"", + assertThrows(IllegalArgumentException.class, () -> TagKey.parse("#stone")).getMessage()); + } + + @ParameterizedTest + @ValueSource(strings = { "mypack:stone", "#mypack:", "#mypack:bad id" }) + void tagKeyRejects(String tag) { + assertThrows(IllegalArgumentException.class, () -> TagKey.parse(tag)); + } +} diff --git a/common/api/src/test/java/com/dfsek/terra/api/world/attribute/AttributeMapTest.java b/common/api/src/test/java/com/dfsek/terra/api/world/attribute/AttributeMapTest.java new file mode 100644 index 000000000..19c51aefb --- /dev/null +++ b/common/api/src/test/java/com/dfsek/terra/api/world/attribute/AttributeMapTest.java @@ -0,0 +1,72 @@ +package com.dfsek.terra.api.world.attribute; + +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class AttributeMapTest { + private static final AttributeKey A = AttributeKey.parse("test:a"); + private static final AttributeKey B = AttributeKey.parse("test:b"); + + @Test + void emptyIsShared() { + assertSame(AttributeMap.empty(), AttributeMap.builder().build()); + assertSame(AttributeMap.empty(), AttributeMap.builder().put(A, AttributeEntry.override(1)).remove(A).build()); + assertTrue(AttributeMap.empty().get(A).isEmpty()); + } + + @Test + void overlayReplacesPerKey() { + AttributeEntry bottomA = AttributeEntry.override(1); + AttributeMap bottom = AttributeMap.builder().put(A, bottomA).put(B, AttributeEntry.override(2)).build(); + AttributeMap top = AttributeMap.builder().put(B, AttributeEntry.override(3)).build(); + AttributeMap merged = bottom.overlay(top); + assertEquals(List.of(A, B), List.copyOf(merged.keys())); + assertSame(bottomA, merged.get(A).orElseThrow()); + assertEquals(AttributeEntry.override(3), merged.get(B).orElseThrow()); + assertEquals(AttributeEntry.override(2), bottom.get(B).orElseThrow()); + } + + @Test + void builderRemove() { + AttributeMap map = AttributeMap.builder().put(A, AttributeEntry.override(1)).put(B, AttributeEntry.override(2)).remove(A).build(); + assertEquals(Set.of(B), map.keys()); + assertTrue(map.get(AttributeKey.parse("test:b")).isPresent()); + assertThrows(UnsupportedOperationException.class, () -> map.keys().clear()); + } + + @Test + void nullsThrow() { + AttributeMap.Builder builder = AttributeMap.builder(); + assertThrows(NullPointerException.class, () -> builder.put(null, AttributeEntry.override(1))); + assertThrows(NullPointerException.class, () -> builder.put(A, null)); + assertEquals("top", assertThrows(NullPointerException.class, () -> AttributeMap.empty().overlay(null)).getMessage()); + } + + @Test + void nullArgument() { + assertNull(AttributeEntry.override(null).argument()); + assertNull(AttributeEntry.of(Operation.OVERRIDE, null).argument()); + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> AttributeEntry.of(Operation.ADD, null)); + assertEquals("modifier add needs an argument", e.getMessage()); + assertThrows(IllegalArgumentException.class, () -> new AttributeEntry(Operation.MULTIPLY, null)); + } + + @Test + void equalByContent() { + AttributeMap one = AttributeMap.builder().put(A, AttributeEntry.override(1)).build(); + AttributeMap two = AttributeMap.builder().put(A, AttributeEntry.override(1)).build(); + assertEquals(one, two); + assertEquals(one.hashCode(), two.hashCode()); + assertNotEquals(one, AttributeMap.builder().put(A, AttributeEntry.override(2)).build()); + } +} diff --git a/common/api/src/test/java/com/dfsek/terra/api/world/attribute/ValueTypesTest.java b/common/api/src/test/java/com/dfsek/terra/api/world/attribute/ValueTypesTest.java new file mode 100644 index 000000000..7ef9856ba --- /dev/null +++ b/common/api/src/test/java/com/dfsek/terra/api/world/attribute/ValueTypesTest.java @@ -0,0 +1,132 @@ +package com.dfsek.terra.api.world.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 org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Stream; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.attribute.schedule.Easing; +import com.dfsek.terra.api.world.attribute.value.Color; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.params.provider.Arguments.arguments; + + +public class ValueTypesTest { + @Test + public void attributeKey() { + RegistryKey registryKey = RegistryKey.parse("my.pack:visual/Fog_Color"); + AttributeKey key = AttributeKey.parse("my.pack:visual/Fog_Color"); + assertEquals(registryKey, key.getRegistryKey()); + assertEquals("my.pack:visual/Fog_Color", key.toString()); + AttributeKey wrapped = AttributeKey.of(registryKey); + assertSame(registryKey, wrapped.getRegistryKey()); + assertEquals(wrapped, key); + assertEquals(registryKey.hashCode(), key.hashCode()); + assertNotEquals(key, AttributeKey.parse("my.pack:visual/other")); + assertEquals("invalid attribute key \"visual/fog_color\": a namespace is required, as in \"namespace:visual/fog_color\"", + assertThrows(IllegalArgumentException.class, () -> AttributeKey.parse("visual/fog_color")).getMessage()); + } + + @ParameterizedTest + @NullSource + @ValueSource(strings = { "Bad Key", "mypack:", ":visual/fog_color", "a:b:c" }) + public void attributeKeyRejects(String key) { + assertThrows(IllegalArgumentException.class, () -> AttributeKey.parse(key)); + } + + @Test + public void parseFailureMessages() { + assertEquals("unknown modifier \"frobnicate\"", + assertThrows(IllegalArgumentException.class, () -> Operation.parse("frobnicate")).getMessage()); + assertEquals("unknown easing \"x\"", + assertThrows(IllegalArgumentException.class, () -> new Easing.Named("x")).getMessage()); + for(Operation op : Operation.values()) assertSame(op, Operation.parse(op.getID())); + } + + private static Arguments rgb(Object raw, int expected) { + return arguments(raw, (Function) Color::parseRgb, Color.rgb(expected)); + } + + private static Arguments argb(Object raw, int expected) { + return arguments(raw, (Function) Color::parseArgb, Color.argb(expected)); + } + + static Stream colors() { + return Stream.of( + rgb("#050533", 0x050533), + arguments(List.of(1.0, 0.5, 0.0), (Function) Color::parseRgb, new Color(1f, 0.5f, 0f, 1f)), + rgb(16777215, 0xFFFFFF), + rgb(16777215L, 0xFFFFFF), + rgb(1.6777215E7, 0xFFFFFF), + rgb(BigInteger.valueOf(0x102030), 0x102030), + rgb(new BigDecimal("1056816.0"), 0x102030), + rgb(0xFF102030, 0x102030), + argb("#80ff0000", 0x80FF0000), + argb(0xFF102030L, 0xFF102030), + argb(0xFF102030, 0xFF102030), + argb(BigInteger.valueOf(0xFFFFFFFFL), 0xFFFFFFFF)); + } + + @ParameterizedTest + @MethodSource + public void colors(Object raw, Function parser, Color expected) { + assertEquals(expected, parser.apply(raw)); + } + + private static Arguments rejectRgb(Object raw, String message) { + return arguments(raw, (Function) Color::parseRgb, message); + } + + private static Arguments rejectArgb(Object raw, String message) { + return arguments(raw, (Function) Color::parseArgb, message); + } + + static Stream colorsRejected() { + return Stream.of( + rejectRgb("#12345", null), + rejectRgb(0.5, null), + rejectArgb(0.5, null), + rejectRgb(new BigDecimal("1.5"), "color integer must be integral: 1.5"), + rejectArgb(new BigDecimal("1.5"), null), + rejectRgb(Double.NaN, null), + rejectRgb(Double.POSITIVE_INFINITY, null), + rejectRgb(0xFFFFFFFFL, "value 4294967295 is outside [-2147483648, 2147483647]"), + rejectRgb(new BigInteger("100000000000"), null), + rejectArgb(0x100000000L, "value 4294967296 is outside [-2147483648, 4294967295]"), + rejectArgb(-2147483649L, null)); + } + + @ParameterizedTest + @MethodSource + public void colorsRejected(Object raw, Function parser, String message) { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> parser.apply(raw)); + if(message != null) assertEquals(message, e.getMessage()); + } + + @Test + public void rawValueDeepCopy() { + Map inner = new HashMap<>(); + inner.put("a", 1); + Map map = new HashMap<>(); + map.put("inner", inner); + RawValue raw = new RawValue(map); + map.put("b", 2); + inner.put("c", 3); + @SuppressWarnings("unchecked") + Map copy = (Map) raw.value(); + assertEquals(1, copy.size()); + assertEquals(Map.of("a", 1), copy.get("inner")); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java b/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java index 9a4097108..8a3ce64b5 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java @@ -67,6 +67,7 @@ import com.dfsek.terra.api.registry.key.StringIdentifiable; import com.dfsek.terra.api.util.generic.pair.Pair; import com.dfsek.terra.api.util.mutable.MutableBoolean; import com.dfsek.terra.api.util.reflection.TypeKey; +import com.dfsek.terra.api.world.attribute.AttributeHandle; import com.dfsek.terra.config.GenericLoaders; import com.dfsek.terra.config.PluginConfigImpl; import com.dfsek.terra.event.EventManagerImpl; @@ -77,6 +78,7 @@ import com.dfsek.terra.registry.OpenRegistryImpl; import com.dfsek.terra.registry.master.ConfigRegistry; import com.dfsek.terra.registry.master.ConfigRegistry.PackLoadFailuresException; import com.dfsek.terra.registry.master.MetaConfigRegistry; +import com.dfsek.terra.world.attribute.AttributeHandleImpl; /** @@ -103,6 +105,8 @@ public abstract class AbstractPlatform implements Platform { private final GenericLoaders loaders = new GenericLoaders(this); private final PluginConfigImpl config = new PluginConfigImpl(); private final CheckedRegistry addonRegistry = new CheckedRegistryImpl<>(new OpenRegistryImpl<>(TypeKey.of(BaseAddon.class))); + // Must exist before addons initialize: it creates the attribute context keys. + private final AttributeHandle attributeHandle = new AttributeHandleImpl(); private final Registry lockedAddonRegistry = new LockedRegistryImpl<>(addonRegistry); public static int getGenerationThreadsWithReflection(String className, String fieldName, String project) { @@ -434,6 +438,11 @@ public abstract class AbstractPlatform implements Platform { return profiler; } + @Override + public @NotNull AttributeHandle getAttributeHandle() { + return attributeHandle; + } + @Override public int getGenerationThreads() { return 1; diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaListLikePreprocessor.java b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaListLikePreprocessor.java index 2e6707c9d..6ccf27cd7 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaListLikePreprocessor.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaListLikePreprocessor.java @@ -68,8 +68,7 @@ public class MetaListLikePreprocessor extends MetaPreprocessor { if(!(metaValue instanceof List)) { throw new LoadException( - "Meta list / set injection (via <<) must point to a list. '" + meta + "' points to type " + - metaValue.getClass().getCanonicalName(), + "Meta list / set injection (via <<) must point to a list. '" + meta + "' points to " + describe(metaValue), depthTracker); } diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaMapPreprocessor.java b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaMapPreprocessor.java index 3a05e8112..96f5f8a9a 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaMapPreprocessor.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaMapPreprocessor.java @@ -63,7 +63,7 @@ public class MetaMapPreprocessor extends MetaPreprocessor { Object meta = pair.getRight(); if(!(meta instanceof Map)) { throw new LoadException( - "MetaMap injection candidate must be list, is type " + meta.getClass().getCanonicalName(), + "MetaMap injection candidate must be map, is " + describe(meta), depthTracker); } newMap.putAll((Map) meta); diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaPreprocessor.java b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaPreprocessor.java index 2f4b0d231..def8a608e 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaPreprocessor.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaPreprocessor.java @@ -35,8 +35,13 @@ public abstract class MetaPreprocessor implements ValuePre this.configs = configs; } + protected static String describe(Object value) { + return value == null ? "null" : "type " + value.getClass().getCanonicalName(); + } + protected Pair getMetaValue(String meta, DepthTracker depthTracker) { int sep = meta.indexOf(':'); + if(sep < 0) throw new LoadException("meta reference \"" + meta + "\" must have the form file:key", depthTracker); String file = meta.substring(0, sep); String key = meta.substring(sep + 1); @@ -44,10 +49,16 @@ public abstract class MetaPreprocessor implements ValuePre Configuration config = configs.get(file); - if(!config.contains(key)) { - throw new LoadException("Cannot fetch metavalue: No such key " + key + " in configuration " + config.getName(), depthTracker); + try { + if(!config.contains(key)) { + throw new LoadException("Cannot fetch metavalue: No such key " + key + " in configuration " + config.getName(), + depthTracker); + } + return Pair.of(config, config.get(key)); + } catch(IllegalArgumentException e) { + // Tectonic's key path messages are Java-style. + throw new LoadException("meta reference \"" + meta + "\" has an invalid key path: use \\. for a dot in a key and \\\\ " + + "for a backslash", e, depthTracker); } - - return Pair.of(config, config.get(key)); } } diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaStringPreprocessor.java b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaStringPreprocessor.java index 8869a0228..dcb37e068 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaStringPreprocessor.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaStringPreprocessor.java @@ -43,8 +43,8 @@ public class MetaStringPreprocessor extends MetaPreprocessor { StringSubstitutor substitutor = new StringSubstitutor(key -> { Object meta = getMetaValue(key, depthTracker).getRight(); if(!(meta instanceof String) && !(meta instanceof Number) && !(meta instanceof Character) && !(meta instanceof Boolean)) { - throw new LoadException("MetaString template injection candidate must be string or primitive, is type " + - meta.getClass().getCanonicalName(), depthTracker); + throw new LoadException("MetaString template injection candidate must be string or primitive, is " + describe(meta), + depthTracker); } return meta.toString(); }); diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeCodecsImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeCodecsImpl.java new file mode 100644 index 000000000..9f90e5d1b --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeCodecsImpl.java @@ -0,0 +1,107 @@ +package com.dfsek.terra.world.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +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.AttributeCodec; +import com.dfsek.terra.api.world.attribute.AttributeCodecs; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.RawValue; + + +final class AttributeCodecsImpl implements AttributeCodecs { + static final AttributeCodecsImpl INSTANCE = new AttributeCodecsImpl(); + + private AttributeCodecsImpl() { } + + @Override + public AttributeCodec of(Decoder decoder, Encoder encoder) { + return ValueDecoders.codec(decoder, encoder); + } + + @Override + public String describe(@Nullable Object value) { + return ValueDecoders.got(value); + } + + @Override + public AttributeCodec booleanCodec() { + return ValueDecoders.BOOLEAN; + } + + @Override + public AttributeCodec floatCodec() { + return ValueDecoders.FLOAT; + } + + @Override + public AttributeCodec doubleCodec() { + return ValueDecoders.DOUBLE; + } + + @Override + public AttributeCodec intCodec() { + return ValueDecoders.INT; + } + + @Override + public AttributeCodec nonNegativeInt() { + return ValueDecoders.NON_NEGATIVE_INT; + } + + @Override + public AttributeCodec unitFloat() { + return ValueDecoders.UNIT_FLOAT; + } + + @Override + public AttributeCodec string(String expected) { + return ValueDecoders.string(expected); + } + + @Override + public AttributeCodec raw() { + return ValueDecoders.RAW; + } + + @Override + public AttributeCodec> list(AttributeCodec element) { + return ValueDecoders.list(element); + } + + @Override + public AttributeCodec> compactList(AttributeCodec element) { + return ValueDecoders.compactList(element); + } + + @Override + public & StringIdentifiable> AttributeCodec enumCodec(String name, Class type) { + return ValueDecoders.identifiableEnum(name, type); + } + + @Override + public AttributeCodec identifier(String defaultNamespace) { + return ValueDecoders.identifier(defaultNamespace); + } + + @Override + public AttributeCodec> identifierOrTag(String defaultNamespace) { + return ValueDecoders.identifierOrTag(defaultNamespace); + } + + @Override + public ObjectReader reader(String what, Object raw, DecodeContext context) throws DecodeException { + return new ValueDecoders.Fields(what, raw, context); + } + + @Override + public ObjectWriter writer() { + return new ValueDecoders.Encoded(); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeHandleImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeHandleImpl.java new file mode 100644 index 000000000..40f90fc0a --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeHandleImpl.java @@ -0,0 +1,137 @@ +package com.dfsek.terra.world.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.properties.Properties; +import com.dfsek.terra.api.properties.PropertyKey; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeCodec; +import com.dfsek.terra.api.world.attribute.AttributeCodecs; +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.AttributeLookup; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.AttributeTypes; +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.PackAttributes; +import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult; +import com.dfsek.terra.world.attribute.format.EntryFormat; +import com.dfsek.terra.world.attribute.format.ScheduleFormat; + + +/** + * Create one per platform, at construction: {@link Context#create} is not thread safe. + */ +public final class AttributeHandleImpl implements AttributeHandle { + private final PropertyKey packKey = Context.create(PackAttributes.class); + private final AtomicInteger attributeIndices = new AtomicInteger(); + + private static Optional read(Context context, PropertyKey key) { + if(!context.has(key)) return Optional.empty(); + return Optional.ofNullable(context.get(key)); + } + + @Override + public AttributeTypes types() { + return AttributeTypesImpl.INSTANCE; + } + + @Override + public AttributeCodecs codecs() { + return AttributeCodecsImpl.INSTANCE; + } + + @Override + public DecodeContext plainContext() { + return PlainDecodeContext.INSTANCE; + } + + @Override + public AttributeType.Builder typeBuilder(String id, AttributeCodec codec) { + return AttributeTypeImpl.builder(id, codec); + } + + @Override + public Attribute.Builder attributeBuilder(AttributeKey key, AttributeType type, @Nullable T defaultValue) { + return AttributeImpl.builder(key, type, defaultValue, attributeIndices); + } + + @Override + public int attributeCount() { + return attributeIndices.get(); + } + + @Override + @SafeVarargs + @SuppressWarnings("varargs") + public final @Nullable T resolve(Attribute attribute, AttributeEntry... layersBottomToTop) { + return AttributeLayers.resolve(attribute, layersBottomToTop); + } + + @Override + public @Nullable T resolve(Attribute attribute, @Nullable AttributeEntry first, @Nullable AttributeEntry second, + @Nullable AttributeEntry third) { + return AttributeLayers.resolve(attribute, first, second, third, null); + } + + @Override + public @Nullable T resolve(Attribute attribute, @Nullable AttributeEntry first, @Nullable AttributeEntry second, + @Nullable AttributeEntry third, @Nullable AttributeEntry fourth) { + return AttributeLayers.resolve(attribute, first, second, third, fourth); + } + + @Override + @SuppressWarnings("unchecked") + public Optional> compose(Attribute attribute, @Nullable AttributeEntry lower, + @Nullable AttributeEntry upper) { + if(lower == null) return Optional.ofNullable(upper); + if(upper == null) return Optional.of(lower); + if(upper.isOverride()) return Optional.of(upper); + if(lower.isOverride()) { + T value = (T) lower.argument(); + if(value == null) return Optional.of(lower); + return Optional.of(AttributeEntry.override(upper.apply(attribute.type(), value))); + } + Operation op = upper.operation(); + if(op != lower.operation()) return Optional.empty(); + return attribute.type().compose(op, lower.argument(), upper.argument()).map(argument -> AttributeEntry.of(op, argument)); + } + + @Override + public AttributeEntry decodeEntry(Attribute attribute, @Nullable Object raw, DecodeContext context) + throws DecodeException { + return EntryFormat.decode(attribute, raw, context); + } + + @Override + public Object encodeEntry(Attribute attribute, AttributeEntry entry) { + return EntryFormat.encode(attribute, entry); + } + + @Override + public ScheduleDecodeResult decodeSchedule(RegistryKey id, Map raw, AttributeLookup attributes, + DecodeContext context) { + return ScheduleFormat.decode(id, raw, attributes, context); + } + + @Override + public Map encodeSchedule(AttributeSchedule schedule) { + return ScheduleFormat.encode(schedule); + } + + @Override + public Optional pack(ConfigPack pack) { + return read(pack.getContext(), packKey); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeImpl.java new file mode 100644 index 000000000..fc81f8b25 --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeImpl.java @@ -0,0 +1,159 @@ +package com.dfsek.terra.world.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeScope; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.DecodeException; + + +final class AttributeImpl implements Attribute { + private final AttributeKey key; + private final AttributeType type; + private final @Nullable T defaultValue; + private final AttributeScope scope; + private final boolean ranged; + private final double min; + private final double max; + private final int multipleOf; + private final int index; + + private AttributeImpl(Builder builder, int index) { + this.key = builder.key; + this.type = builder.type; + this.defaultValue = builder.defaultValue; + this.scope = builder.scope; + this.ranged = builder.ranged; + this.min = builder.min; + this.max = builder.max; + this.multipleOf = builder.multipleOf; + this.index = index; + } + + static Builder builder(AttributeKey key, AttributeType type, @Nullable T defaultValue, AtomicInteger indices) { + return new Builder<>(key, type, defaultValue, indices); + } + + @Override + public AttributeKey key() { + return key; + } + + @Override + public AttributeType type() { + return type; + } + + @Override + public @Nullable T defaultValue() { + return defaultValue; + } + + @Override + public AttributeScope scope() { + return scope; + } + + @Override + public int index() { + return index; + } + + @Override + public T validate(T value) throws DecodeException { + if(value instanceof Number number) { + if(ranged && !inRange(number)) { + throw new DecodeException("value " + value + " is outside " + rangeString()); + } + if(multipleOf > 1 && number.intValue() % multipleOf != 0) { + throw new DecodeException("value " + value + " is not a multiple of " + multipleOf); + } + } + return value; + } + + @Override + @SuppressWarnings("unchecked") + public T sanitize(T value) { + if(!ranged) return value; + if(value instanceof Float f) { + if(f.isNaN()) return value; + return (T) Float.valueOf(Math.max((float) min, Math.min((float) max, f))); + } + if(value instanceof Integer i) { + return (T) Integer.valueOf((int) Math.max(min, Math.min(max, i))); + } + return value; + } + + private boolean inRange(Number number) { + if(number instanceof Float f) return f >= (float) min && f <= (float) max; + double d = number.doubleValue(); + return d >= min && d <= max; + } + + private String rangeString() { + String upper = Double.isInfinite(max) ? "∞)" : format(max) + "]"; + return "[" + format(min) + ", " + upper; + } + + private static String format(double d) { + if(d == Math.rint(d) && Math.abs(d) < 1e15) return Long.toString((long) d); + return Double.toString(d); + } + + @Override + public String toString() { + return "Attribute[" + key + "]"; + } + + + static final class Builder implements Attribute.Builder { + private final AttributeKey key; + private final AttributeType type; + private final @Nullable T defaultValue; + private final AtomicInteger indices; + private AttributeScope scope = AttributeScope.ANYWHERE; + private boolean ranged; + private double min; + private double max; + private int multipleOf = 1; + + private Builder(AttributeKey key, AttributeType type, @Nullable T defaultValue, AtomicInteger indices) { + this.key = Objects.requireNonNull(key, "key"); + this.type = Objects.requireNonNull(type, "type"); + this.defaultValue = defaultValue; + this.indices = indices; + } + + @Override + public Builder range(Number min, Number max) { + this.ranged = true; + this.min = min.doubleValue(); + this.max = max.doubleValue(); + return this; + } + + @Override + public Builder multipleOf(int multipleOf) { + this.multipleOf = multipleOf; + return this; + } + + @Override + public Builder packOnly() { + this.scope = AttributeScope.PACK_ONLY; + return this; + } + + @Override + public Attribute build() { + return new AttributeImpl<>(this, indices.getAndIncrement()); + } + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeLayers.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeLayers.java new file mode 100644 index 000000000..c0eaa73aa --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeLayers.java @@ -0,0 +1,60 @@ +package com.dfsek.terra.world.attribute; + +import org.jetbrains.annotations.Nullable; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; + + +final class AttributeLayers { + private AttributeLayers() { } + + @SafeVarargs + static @Nullable T resolve(Attribute attribute, AttributeEntry... layersBottomToTop) { + T value = attribute.defaultValue(); + boolean applied = false; + for(AttributeEntry entry : layersBottomToTop) { + if(entry == null) continue; + if(value == null) { + if(!entry.isOverride()) continue; + value = entry.apply(attribute.type(), null); + } else { + value = entry.apply(attribute.type(), value); + } + applied = true; + } + if(value == null || !applied) return value; + return attribute.sanitize(value); + } + + /** + * Unrolled to allocate nothing. + */ + static @Nullable T resolve(Attribute attribute, @Nullable AttributeEntry first, @Nullable AttributeEntry second, + @Nullable AttributeEntry third, @Nullable AttributeEntry fourth) { + T value = attribute.defaultValue(); + boolean applied = false; + if(applies(value, first)) { + value = first.apply(attribute.type(), value); + applied = true; + } + if(applies(value, second)) { + value = second.apply(attribute.type(), value); + applied = true; + } + if(applies(value, third)) { + value = third.apply(attribute.type(), value); + applied = true; + } + if(applies(value, fourth)) { + value = fourth.apply(attribute.type(), value); + applied = true; + } + if(value == null || !applied) return value; + return attribute.sanitize(value); + } + + private static boolean applies(@Nullable T value, @Nullable AttributeEntry entry) { + return entry != null && (value != null || entry.isOverride()); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypeImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypeImpl.java new file mode 100644 index 000000000..94cfa19c7 --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypeImpl.java @@ -0,0 +1,155 @@ +package com.dfsek.terra.world.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.Collections; +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.BinaryOperator; + +import com.dfsek.terra.api.world.attribute.AttributeCodec; +import com.dfsek.terra.api.world.attribute.AttributeModifier; +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; + + +final class AttributeTypeImpl implements AttributeType { + private record Op(AttributeCodec argumentCodec, AttributeModifier modifier, + @Nullable BinaryOperator composer) { + Op withComposer(BinaryOperator composer) { + return new Op<>(argumentCodec, modifier, composer); + } + } + + + private static final Operation[] OPERATIONS = Operation.values(); + + private final String id; + private final AttributeCodec codec; + private final Op[] ops; + private final Set operations; + + @SuppressWarnings("unchecked") + private AttributeTypeImpl(String id, AttributeCodec codec, Map> ops) { + this.id = id; + this.codec = codec; + this.ops = (Op[]) new Op[OPERATIONS.length]; + ops.forEach((op, o) -> this.ops[op.ordinal()] = o); + this.operations = Collections.unmodifiableSet(EnumSet.copyOf(ops.keySet())); + } + + static Builder builder(String id, AttributeCodec codec) { + return new Builder<>(id, codec); + } + + @Override + public String id() { + return id; + } + + @Override + public Set operations() { + return operations; + } + + @Override + public T decode(Object raw, DecodeContext context) throws DecodeException { + return codec.decode(raw, context); + } + + @Override + public Object encode(T value) { + return codec.encode(value); + } + + @Override + public Object decodeArgument(Operation op, Object raw, DecodeContext context) throws DecodeException { + Op o = ops[op.ordinal()]; + if(o == null) throw new DecodeException(invalid(op)); + return o.argumentCodec().decode(raw, context); + } + + @Override + public Object encodeArgument(Operation op, Object argument) { + return op(op).argumentCodec().encode(argument); + } + + @Override + public T apply(Operation op, T subject, Object argument) { + return op(op).modifier().apply(subject, argument); + } + + @Override + public Optional compose(Operation op, Object lower, Object upper) { + Op o = ops[op.ordinal()]; + if(o == null || o.composer() == null) return Optional.empty(); + Object composed = o.composer().apply(lower, upper); + if(composed == null) throw new NullPointerException("composer for " + op.getID() + " of " + id + " returned null"); + return Optional.of(composed); + } + + private Op op(Operation op) { + Op o = ops[op.ordinal()]; + if(o == null) throw new IllegalArgumentException(invalid(op)); + return o; + } + + private String invalid(Operation op) { + return "modifier " + op.getID() + " is not valid for " + id; + } + + @Override + public String toString() { + return "AttributeType[" + id + "]"; + } + + + static final class Builder implements AttributeType.Builder { + private final String id; + private final AttributeCodec codec; + private final Map> ops = new EnumMap<>(Operation.class); + + @SuppressWarnings("unchecked") + private Builder(String id, AttributeCodec codec) { + this.id = Objects.requireNonNull(id, "id"); + this.codec = Objects.requireNonNull(codec, "codec"); + ops.put(Operation.OVERRIDE, new Op<>((AttributeCodec) codec, (s, a) -> (T) a, null)); + } + + @Override + @SuppressWarnings("unchecked") + public Builder op(Operation op, AttributeCodec argumentCodec, AttributeModifier modifier) { + if(op == Operation.OVERRIDE) { + throw new IllegalArgumentException("modifier override cannot be replaced"); + } + Objects.requireNonNull(argumentCodec, "argumentCodec"); + Objects.requireNonNull(modifier, "modifier"); + ops.put(op, new Op<>((AttributeCodec) argumentCodec, (s, a) -> modifier.apply(s, (A) a), null)); + return this; + } + + @Override + @SuppressWarnings("unchecked") + public Builder composable(Operation op, BinaryOperator combine) { + if(op == Operation.OVERRIDE) { + throw new IllegalArgumentException("modifier override cannot be composed"); + } + Objects.requireNonNull(combine, "combine"); + Op o = ops.get(op); + if(o == null) throw new IllegalArgumentException("modifier " + op.getID() + " must be added before it is made composable"); + ops.put(op, o.withComposer((a, b) -> combine.apply((A) a, (A) b))); + return this; + } + + @Override + public AttributeType build() { + return new AttributeTypeImpl<>(id, codec, ops); + } + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypesImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypesImpl.java new file mode 100644 index 000000000..5084d9ca9 --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypesImpl.java @@ -0,0 +1,186 @@ +package com.dfsek.terra.world.attribute; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.StringIdentifiable; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.AttributeTypes; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.world.attribute.value.BlendToGray; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.api.world.attribute.value.TriState; + + +final class AttributeTypesImpl implements AttributeTypes { + static final AttributeTypesImpl INSTANCE = new AttributeTypesImpl(); + + private final AttributeType booleanType = AttributeTypeImpl.builder("boolean", ValueDecoders.BOOLEAN) + .op(Operation.AND, ValueDecoders.BOOLEAN, (s, a) -> a && s) + .op(Operation.NAND, ValueDecoders.BOOLEAN, (s, a) -> !a || !s) + .op(Operation.OR, ValueDecoders.BOOLEAN, (s, a) -> a || s) + .op(Operation.NOR, ValueDecoders.BOOLEAN, (s, a) -> !a && !s) + .op(Operation.XOR, ValueDecoders.BOOLEAN, (s, a) -> a ^ s) + .op(Operation.XNOR, ValueDecoders.BOOLEAN, (s, a) -> a == s) + .build(); + + private final AttributeType triState = AttributeTypeImpl.builder("tri_state", ValueDecoders.TRI_STATE).build(); + + private final AttributeType floatType = floatType("float"); + + private final AttributeType angleDegrees = floatType("angle_degrees"); + + private final AttributeType rgbColor = AttributeTypeImpl.builder("rgb_color", ValueDecoders.RGB) + .op(Operation.ALPHA_BLEND, ValueDecoders.ARGB, AttributeTypesImpl::rgbAlphaBlend) + .op(Operation.ADD, ValueDecoders.RGB, (s, a) -> new Color(Math.min(s.r() + a.r(), 1f), Math.min(s.g() + a.g(), 1f), + Math.min(s.b() + a.b(), 1f), 1f)) + .op(Operation.SUBTRACT, ValueDecoders.RGB, (s, a) -> new Color(Math.max(s.r() - a.r(), 0f), Math.max(s.g() - a.g(), 0f), + Math.max(s.b() - a.b(), 0f), 1f)) + .op(Operation.MULTIPLY, ValueDecoders.RGB, (s, a) -> multiply(s, a, false)) + .op(Operation.BLEND_TO_GRAY, ValueDecoders.BLEND_TO_GRAY, AttributeTypesImpl::blendToGray) + .build(); + + private final AttributeType argbColor = AttributeTypeImpl.builder("argb_color", ValueDecoders.ARGB) + .op(Operation.ALPHA_BLEND, ValueDecoders.ARGB, AttributeTypesImpl::argbAlphaBlend) + .op(Operation.ADD, ValueDecoders.RGB, (s, a) -> new Color(Math.min(s.r() + a.r(), 1f), Math.min(s.g() + a.g(), 1f), + Math.min(s.b() + a.b(), 1f), s.a())) + .op(Operation.SUBTRACT, ValueDecoders.RGB, (s, a) -> new Color(Math.max(s.r() - a.r(), 0f), Math.max(s.g() - a.g(), 0f), + Math.max(s.b() - a.b(), 0f), s.a())) + .op(Operation.MULTIPLY, ValueDecoders.ARGB, (s, a) -> multiply(s, a, true)) + .op(Operation.BLEND_TO_GRAY, ValueDecoders.BLEND_TO_GRAY, AttributeTypesImpl::blendToGray) + .build(); + + private final AttributeType integer = integerType("integer"); + + private final AttributeType integerOverrideOnly = AttributeTypeImpl.builder("integer_override_only", ValueDecoders.INT) + .build(); + + private final Map> identifiers = new ConcurrentHashMap<>(); + + private final Map>> identifiersOrTags = new ConcurrentHashMap<>(); + + private AttributeTypesImpl() { } + + @Override + public AttributeType booleanType() { + return booleanType; + } + + @Override + public AttributeType triState() { + return triState; + } + + @Override + public AttributeType floatType() { + return floatType; + } + + @Override + public AttributeType angleDegrees() { + return angleDegrees; + } + + @Override + public AttributeType rgbColor() { + return rgbColor; + } + + @Override + public AttributeType argbColor() { + return argbColor; + } + + @Override + public AttributeType integer() { + return integer; + } + + @Override + public AttributeType integerOverrideOnly() { + return integerOverrideOnly; + } + + @Override + public AttributeType identifier(String defaultNamespace) { + return identifiers.computeIfAbsent(defaultNamespace, + ns -> AttributeTypeImpl.builder("identifier", ValueDecoders.identifier(ns)).build()); + } + + @Override + public AttributeType> identifierOrTag(String defaultNamespace) { + return identifiersOrTags.computeIfAbsent(defaultNamespace, + ns -> AttributeTypeImpl.builder("identifier_or_tag", ValueDecoders.identifierOrTag(ns)).build()); + } + + @Override + public & StringIdentifiable> AttributeType enumType(String id, Class type) { + return AttributeTypeImpl.builder(id, ValueDecoders.identifiableEnum(id.replace('_', ' '), type)).build(); + } + + private static AttributeType floatType(String id) { + return AttributeTypeImpl.builder(id, ValueDecoders.FLOAT) + .op(Operation.ALPHA_BLEND, ValueDecoders.FLOAT_WITH_ALPHA, (s, a) -> s + a.alpha() * (a.value() - s)) + .op(Operation.ADD, ValueDecoders.FLOAT, (s, a) -> s + a) + .op(Operation.SUBTRACT, ValueDecoders.FLOAT, (s, a) -> s - a) + .op(Operation.MULTIPLY, ValueDecoders.FLOAT, (s, a) -> s * a) + .op(Operation.MINIMUM, ValueDecoders.FLOAT, (s, a) -> Math.min(s, a)) + .op(Operation.MAXIMUM, ValueDecoders.FLOAT, (s, a) -> Math.max(s, a)) + .composable(Operation.ADD, Float::sum) + .composable(Operation.MULTIPLY, (a, b) -> a * b) + .build(); + } + + private static AttributeType integerType(String id) { + return AttributeTypeImpl.builder(id, ValueDecoders.INT) + .op(Operation.ADD, ValueDecoders.INT, (s, a) -> s + a) + .op(Operation.SUBTRACT, ValueDecoders.INT, (s, a) -> s - a) + .op(Operation.MULTIPLY, ValueDecoders.INT, (s, a) -> s * a) + .op(Operation.MINIMUM, ValueDecoders.INT, (s, a) -> Math.min(s, a)) + .op(Operation.MAXIMUM, ValueDecoders.INT, (s, a) -> Math.max(s, a)) + .composable(Operation.ADD, Integer::sum) + .composable(Operation.MULTIPLY, (a, b) -> a * b) + .build(); + } + + private static float lerp(float t, float from, float to) { + return from + t * (to - from); + } + + private static float clamp01(float v) { + return Math.max(0f, Math.min(1f, v)); + } + + private static boolean white(Color c, boolean withAlpha) { + return c.r() == 1f && c.g() == 1f && c.b() == 1f && (!withAlpha || c.a() == 1f); + } + + private static Color multiply(Color s, Color a, boolean withAlpha) { + if(white(s, withAlpha)) return a; + if(white(a, withAlpha)) return s; + return new Color(s.r() * a.r(), s.g() * a.g(), s.b() * a.b(), withAlpha ? s.a() * a.a() : 1f); + } + + private static Color rgbAlphaBlend(Color dst, Color src) { + if(src.a() == 0f) return dst; + return new Color(lerp(src.a(), dst.r(), src.r()), lerp(src.a(), dst.g(), src.g()), lerp(src.a(), dst.b(), src.b()), 1f); + } + + private static Color argbAlphaBlend(Color dst, Color src) { + float sa = src.a(); + if(sa == 1f) return src; + if(sa == 0f) return dst; + float a = sa + dst.a() * (1f - sa); + return new Color((src.r() * sa + dst.r() * (a - sa)) / a, (src.g() * sa + dst.g() * (a - sa)) / a, + (src.b() * sa + dst.b() * (a - sa)) / a, a); + } + + private static Color blendToGray(Color s, BlendToGray arg) { + float g = 0.3f * s.r() + 0.59f * s.g() + 0.11f * s.b(); + float grey = clamp01(g * arg.brightness()); + return new Color(lerp(arg.factor(), s.r(), grey), lerp(arg.factor(), s.g(), grey), lerp(arg.factor(), s.b(), grey), s.a()); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/PlainDecodeContext.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/PlainDecodeContext.java new file mode 100644 index 000000000..58c15787d --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/PlainDecodeContext.java @@ -0,0 +1,63 @@ +package com.dfsek.terra.world.attribute; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; + +import static com.dfsek.terra.world.attribute.ValueDecoders.got; + + +final class PlainDecodeContext implements DecodeContext { + static final PlainDecodeContext INSTANCE = new PlainDecodeContext(); + + private PlainDecodeContext() { } + + private static Class rawClass(Type type) { + if(type instanceof Class c) return c; + if(type instanceof ParameterizedType p && p.getRawType() instanceof Class c) return c; + return null; + } + + @Override + public Object resolve(Object raw) { + return raw; + } + + @Override + @SuppressWarnings("unchecked") + public V load(Type type, Object raw) throws DecodeException { + Class c = rawClass(type); + Object value; + if(c == Object.class) value = raw; + else if(c == Float.class) value = number(raw).floatValue(); + else if(c == Double.class) value = number(raw).doubleValue(); + else if(c == Integer.class) { + if(!(raw instanceof Number n)) throw new DecodeException("expected an integer, got " + got(raw)); + value = ValueDecoders.integer(n, raw); + } else if(c == Boolean.class) { + if(!(raw instanceof Boolean)) throw new DecodeException("expected a boolean (true or false), got " + got(raw)); + value = raw; + } else if(c == String.class) { + if(!(raw instanceof String)) throw new DecodeException("expected a string, got " + got(raw)); + value = raw; + } else if(c == List.class) { + if(!(raw instanceof List)) throw new DecodeException("expected a list, got " + got(raw)); + value = raw; + } else if(c == Map.class) { + if(!(raw instanceof Map)) throw new DecodeException("expected an object, got " + got(raw)); + value = raw; + } else { + throw new DecodeException("cannot load this kind of value"); + } + return (V) value; + } + + private static Number number(Object raw) throws DecodeException { + if(raw instanceof Number n) return n; + throw new DecodeException("expected a number, got " + got(raw)); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/ValueDecoders.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/ValueDecoders.java new file mode 100644 index 000000000..48d5c5ae0 --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/ValueDecoders.java @@ -0,0 +1,412 @@ +package com.dfsek.terra.world.attribute; + +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +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.util.reflection.TypeKey; +import com.dfsek.terra.api.world.attribute.AttributeCodec; +import com.dfsek.terra.api.world.attribute.AttributeCodecs.Decoder; +import com.dfsek.terra.api.world.attribute.AttributeCodecs.Encoder; +import com.dfsek.terra.api.world.attribute.AttributeCodecs.ObjectReader; +import com.dfsek.terra.api.world.attribute.AttributeCodecs.ObjectWriter; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.RawValue; +import com.dfsek.terra.api.world.attribute.value.BlendToGray; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.api.world.attribute.value.FloatWithAlpha; +import com.dfsek.terra.api.world.attribute.value.TriState; + + +/** + * Colours encode as hex, or as float channels when a channel isn't a multiple of 1/255. + */ +final class ValueDecoders { + private static final Type LIST = new TypeKey>() { }.getType(); + private static final Type MAP = new TypeKey>() { }.getType(); + + private ValueDecoders() { } + + private record Codec(Decoder decoder, Encoder encoder) implements AttributeCodec { + @Override + public T decode(Object raw, DecodeContext context) throws DecodeException { + return decoder.decode(raw, context); + } + + @Override + public Object encode(T value) { + return encoder.encode(value); + } + } + + static AttributeCodec codec(Decoder decoder, Encoder encoder) { + return new Codec<>(decoder, encoder); + } + + private static Object identity(T value) { + return value; + } + + static String got(Object o) { + if(o == null) return "nothing"; + if(o instanceof String s) return "\"" + s + "\""; + if(o instanceof Map) return "an object"; + if(o instanceof List) return "a list"; + return String.valueOf(o); + } + + static int integer(Number n, Object raw) throws DecodeException { + if(n instanceof Integer || n instanceof Short || n instanceof Byte) return n.intValue(); + if(n instanceof Long l) { + if(l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) throw new DecodeException("expected an integer, got " + l); + return (int) (long) l; + } + try { + return exact(n).intValueExact(); + } catch(ArithmeticException | NumberFormatException e) { + throw new DecodeException("expected an integer, got " + got(raw)); + } + } + + private static BigDecimal exact(Number n) { + if(n instanceof BigDecimal d) return d; + if(n instanceof BigInteger i) return new BigDecimal(i); + if(n instanceof Double || n instanceof Float) { + double d = n.doubleValue(); + if(!Double.isFinite(d)) throw new NumberFormatException(); + return new BigDecimal(d); + } + return new BigDecimal(n.toString()); + } + + private static String string(Object raw, DecodeContext context, String expected) throws DecodeException { + Object value = context.resolve(raw); + if(!(value instanceof String)) throw new DecodeException(expected + ", got " + got(value)); + return context.load(String.class, value); + } + + static AttributeCodec string(String expected) { + return codec((raw, context) -> string(raw, context, expected), ValueDecoders::identity); + } + + private static List loadList(Object raw, DecodeContext context, String expected) throws DecodeException { + Object value = context.resolve(raw); + try { + return context.load(LIST, value); + } catch(DecodeException e) { + if(value instanceof List) throw e; + throw new DecodeException(expected + ", got " + got(value), e); + } + } + + private static Map loadMap(Object raw, DecodeContext context, String expected) throws DecodeException { + Object value = context.resolve(raw); + try { + return context.load(MAP, value); + } catch(DecodeException e) { + if(value instanceof Map) throw e; + throw new DecodeException(expected + ", got " + got(value), e); + } + } + + static final AttributeCodec BOOLEAN = codec((raw, context) -> context.load(Boolean.class, raw), ValueDecoders::identity); + + static final AttributeCodec FLOAT = codec((raw, context) -> context.load(Float.class, raw), ValueDecoders::identity); + + static final AttributeCodec DOUBLE = codec((raw, context) -> context.load(Double.class, raw), ValueDecoders::identity); + + static final AttributeCodec INT = codec((raw, context) -> { + Object value = context.resolve(raw); + if(value instanceof Number n) integer(n, value); + return context.load(Integer.class, value); + }, ValueDecoders::identity); + + static final AttributeCodec NON_NEGATIVE_INT = codec((raw, context) -> { + int i = INT.decode(raw, context); + if(i < 0) throw new DecodeException("expected a non-negative integer, got " + i); + return i; + }, ValueDecoders::identity); + + static final AttributeCodec UNIT_FLOAT = codec((raw, context) -> { + float f = FLOAT.decode(raw, context); + if(!(f >= 0f && f <= 1f)) throw new DecodeException("value " + f + " is outside [0, 1]"); + return f; + }, ValueDecoders::identity); + + static final AttributeCodec RAW = codec((raw, context) -> { + Object value = context.resolve(raw); + try { + return new RawValue(value); + } catch(IllegalArgumentException e) { + throw new DecodeException(e.getMessage(), e); + } + }, RawValue::value); + + private static String expectedIdentifier(String defaultNamespace) { + return "expected an identifier like \"" + defaultNamespace + ":id\""; + } + + static AttributeCodec identifier(String defaultNamespace) { + String expected = expectedIdentifier(defaultNamespace); + return codec((raw, context) -> { + String s = string(raw, context, expected); + if(s.startsWith("#")) throw new DecodeException("expected an identifier, not a tag, got " + got(s)); + try { + return RegistryKey.parse(s, defaultNamespace); + } catch(IllegalArgumentException e) { + throw new DecodeException(expected + ", got " + got(s), e); + } + }, RegistryKey::toString); + } + + static AttributeCodec> identifierOrTag(String defaultNamespace) { + String expected = expectedIdentifier(defaultNamespace); + return codec((raw, context) -> { + String s = string(raw, context, expected); + try { + if(s.startsWith("#")) return Either.right(TagKey.parse(s, defaultNamespace)); + return Either.left(RegistryKey.parse(s, defaultNamespace)); + } catch(IllegalArgumentException e) { + throw new DecodeException(expected + ", got " + got(s), e); + } + }, either -> either.hasLeft() ? either.getLeft().orElseThrow().toString() : either.getRight().orElseThrow().toString()); + } + + private static Object colorParts(Object value, DecodeContext context) throws DecodeException { + if(value instanceof String) return context.load(String.class, value); + if(value instanceof Number) return context.load(Double.class, value); + if(value instanceof List) { + List channels = context.load(LIST, value); + List out = new ArrayList<>(channels.size()); + for(Object channel : channels) out.add(context.load(Float.class, channel)); + return out; + } + return value; + } + + private static boolean hexExact(float channel) { + return channel >= 0f && channel <= 1f && Math.round(channel * 255) / 255f == channel; + } + + static final AttributeCodec RGB = codec((raw, context) -> { + Object value = context.resolve(raw); + try { + return Color.parseRgb(colorParts(value, context)); + } catch(IllegalArgumentException | DecodeException e) { + throw new DecodeException("expected a color like \"#rrggbb\", got " + got(value), e); + } + }, color -> hexExact(color.r()) && hexExact(color.g()) && hexExact(color.b()) + ? String.format(Locale.ROOT, "#%06x", color.toRgbInt()) + : List.of(color.r(), color.g(), color.b())); + + static final AttributeCodec ARGB = codec((raw, context) -> { + Object value = context.resolve(raw); + try { + return Color.parseArgb(colorParts(value, context)); + } catch(IllegalArgumentException | DecodeException e) { + throw new DecodeException("expected a color like \"#aarrggbb\", got " + got(value), e); + } + }, color -> hexExact(color.r()) && hexExact(color.g()) && hexExact(color.b()) && hexExact(color.a()) + ? String.format(Locale.ROOT, "#%08x", color.toArgbInt()) + : List.of(color.r(), color.g(), color.b(), color.a())); + + @FunctionalInterface + interface Parser { + E parse(String name); + } + + static AttributeCodec stringEnum(String what, Parser parser, Encoder encoder) { + return codec((raw, context) -> { + String s = string(raw, context, "expected a " + what + " name"); + try { + return parser.parse(s); + } catch(IllegalArgumentException e) { + throw new DecodeException(e.getMessage(), e); + } + }, encoder); + } + + static & StringIdentifiable> AttributeCodec identifiableEnum(String what, Class type) { + Map byId = new LinkedHashMap<>(); + for(E constant : type.getEnumConstants()) { + E previous = byId.put(constant.getID(), constant); + if(previous != null) { + throw new IllegalArgumentException(type.getCanonicalName() + " constants " + previous + " and " + constant + + " share the ID \"" + constant.getID() + "\""); + } + } + Map ids = Collections.unmodifiableMap(byId); + return stringEnum(what, name -> { + E value = ids.get(name); + if(value == null) throw new IllegalArgumentException("unknown " + what + " \"" + name + "\", expected one of " + ids.keySet()); + return value; + }, StringIdentifiable::getID); + } + + static final AttributeCodec TRI_STATE = triState(identifiableEnum("tri-state", TriState.class)); + + private static AttributeCodec triState(AttributeCodec byId) { + return codec((raw, context) -> { + Object resolved = context.resolve(raw); + if(resolved instanceof Boolean) return context.load(Boolean.class, resolved) ? TriState.TRUE : TriState.FALSE; + if(resolved instanceof String) return byId.decode(resolved, context); + throw new DecodeException("expected true, false or a tri-state name (\"true\", \"false\", \"default\"), got " + got(resolved)); + }, value -> switch(value) { + case TRUE -> true; + case FALSE -> false; + case DEFAULT -> byId.encode(value); + }); + } + + static final class Fields implements ObjectReader { + private final String what; + private final DecodeContext context; + private final Map map; + private final Set used = new LinkedHashSet<>(); + + Fields(String what, Object raw, DecodeContext context) throws DecodeException { + this.what = what; + this.context = context; + Map m = loadMap(raw, context, "expected an object for " + what); + Map copy = new LinkedHashMap<>(); + for(Map.Entry e : m.entrySet()) { + if(!(e.getKey() instanceof String k)) { + throw new DecodeException("keys of " + what + " must be strings, got " + got(e.getKey())); + } + copy.put(k, e.getValue()); + } + this.map = copy; + } + + @Override + public List keys() { + return List.copyOf(map.keySet()); + } + + @Override + public V required(String key, AttributeCodec codec) throws DecodeException { + if(!map.containsKey(key)) throw new DecodeException(what + " is missing required key \"" + key + "\""); + return read(key, codec); + } + + @Override + public Optional optional(String key, AttributeCodec codec) throws DecodeException { + if(!map.containsKey(key)) return Optional.empty(); + return Optional.of(read(key, codec)); + } + + @Override + public V orDefault(String key, AttributeCodec codec, V fallback) throws DecodeException { + if(!map.containsKey(key)) return fallback; + return read(key, codec); + } + + private V read(String key, AttributeCodec codec) throws DecodeException { + used.add(key); + try { + return codec.decode(map.get(key), context); + } catch(DecodeException e) { + throw new DecodeException("\"" + key + "\" of " + what + ": " + e.getMessage(), e); + } + } + + @Override + public void finish() throws DecodeException { + for(String k : map.keySet()) { + if(!used.contains(k)) throw new DecodeException("unknown key \"" + k + "\" in " + what); + } + } + } + + static final class Encoded implements ObjectWriter { + private final Map map = new LinkedHashMap<>(); + + @Override + public Encoded put(String key, AttributeCodec codec, V value) { + map.put(key, codec.encode(value)); + return this; + } + + @Override + public Encoded optional(String key, AttributeCodec codec, Optional value) { + value.ifPresent(v -> map.put(key, codec.encode(v))); + return this; + } + + @Override + public Map map() { + return map; + } + } + + static AttributeCodec> list(AttributeCodec element) { + return codec((raw, context) -> { + List l = loadList(raw, context, "expected a list"); + List out = new ArrayList<>(l.size()); + for(int i = 0; i < l.size(); i++) { + try { + out.add(element.decode(l.get(i), context)); + } catch(DecodeException e) { + throw new DecodeException("element " + i + ": " + e.getMessage(), e); + } + } + return Collections.unmodifiableList(out); + }, values -> { + List out = new ArrayList<>(values.size()); + for(V value : values) out.add(element.encode(value)); + return out; + }); + } + + static AttributeCodec> compactList(AttributeCodec element) { + AttributeCodec> asList = list(element); + return codec((raw, context) -> { + Object value = context.resolve(raw); + return value instanceof List ? asList.decode(value, context) : List.of(element.decode(value, context)); + }, asList::encode); + } + + static final AttributeCodec FLOAT_WITH_ALPHA = codec((raw, context) -> { + Object resolved = context.resolve(raw); + if(resolved instanceof Map) { + Fields f = new Fields("alpha_blend argument", resolved, context); + float value = f.required("value", FLOAT); + float alpha = f.orDefault("alpha", UNIT_FLOAT, 1f); + f.finish(); + return new FloatWithAlpha(value, alpha); + } + try { + return new FloatWithAlpha(FLOAT.decode(resolved, context), 1f); + } catch(DecodeException e) { + throw new DecodeException("expected a number or a {value, alpha} object, got " + got(resolved), e); + } + }, value -> new Encoded() + .put("value", FLOAT, value.value()) + .put("alpha", UNIT_FLOAT, value.alpha()) + .map()); + + static final AttributeCodec BLEND_TO_GRAY = codec((raw, context) -> { + Fields f = new Fields("blend_to_gray argument", raw, context); + float brightness = f.required("brightness", UNIT_FLOAT); + float factor = f.required("factor", UNIT_FLOAT); + f.finish(); + return new BlendToGray(brightness, factor); + }, value -> new Encoded() + .put("brightness", UNIT_FLOAT, value.brightness()) + .put("factor", UNIT_FLOAT, value.factor()) + .map()); +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/EntryFormat.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/EntryFormat.java new file mode 100644 index 000000000..5548b22b1 --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/EntryFormat.java @@ -0,0 +1,73 @@ +package com.dfsek.terra.world.attribute.format; + +import org.jetbrains.annotations.Nullable; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; + + +public final class EntryFormat { + private static final String MODIFIER = "modifier"; + private static final String ARGUMENT = "argument"; + private static final Set MODIFIER_KEYS = Set.of(MODIFIER, ARGUMENT); + + private EntryFormat() { } + + public static AttributeEntry decode(Attribute attribute, @Nullable Object raw, DecodeContext context) + throws DecodeException { + if(raw == null) throw new DecodeException("missing value"); + Object value = context.resolve(raw); + if(value == null) throw new DecodeException("missing value"); + if(value instanceof Map map && map.containsKey(MODIFIER)) { + return decodeModifier(attribute, map, context); + } + return AttributeEntry.override(attribute.validate(attribute.type().decode(value, context))); + } + + @SuppressWarnings("unchecked") + public static Object encode(Attribute attribute, AttributeEntry entry) { + if(entry.isOverride()) { + if(entry.argument() == null) { + throw new IllegalArgumentException("a null override has no pack-format form"); + } + return attribute.type().encode((T) entry.argument()); + } + Map encoded = new LinkedHashMap<>(); + encoded.put(MODIFIER, entry.operation().getID()); + encoded.put(ARGUMENT, attribute.type().encodeArgument(entry.operation(), entry.argument())); + return encoded; + } + + private static AttributeEntry decodeModifier(Attribute attribute, Map map, DecodeContext context) + throws DecodeException { + if(!map.keySet().equals(MODIFIER_KEYS)) { + throw new DecodeException("modifier entry must have exactly the keys \"modifier\" and \"argument\""); + } + Operation operation; + try { + operation = Operation.parse(context.load(String.class, map.get(MODIFIER))); + } catch(IllegalArgumentException e) { + throw new DecodeException(e.getMessage(), e); + } catch(DecodeException e) { + throw new DecodeException("\"modifier\": " + e.getMessage(), e); + } + if(!attribute.type().operations().contains(operation)) { + throw new DecodeException("modifier " + operation.getID() + " is not valid for " + attribute.key()); + } + Object argument = attribute.type().decodeArgument(operation, map.get(ARGUMENT), context); + if(argument == null && operation != Operation.OVERRIDE) throw new DecodeException("\"argument\": missing value"); + if(operation == Operation.OVERRIDE) { + @SuppressWarnings("unchecked") + T value = (T) argument; + attribute.validate(value); + } + return AttributeEntry.of(operation, argument); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/ScheduleFormat.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/ScheduleFormat.java new file mode 100644 index 000000000..f64fda2bb --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/ScheduleFormat.java @@ -0,0 +1,299 @@ +package com.dfsek.terra.world.attribute.format; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +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.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeLookup; +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.schedule.AttributeSchedule; +import com.dfsek.terra.api.world.attribute.schedule.Easing; +import com.dfsek.terra.api.world.attribute.schedule.Keyframe; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult.Problem; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleTrack; +import com.dfsek.terra.api.world.attribute.schedule.TimeMarker; + + +public final class ScheduleFormat { + private static final String CLOCK = "clock"; + private static final String PERIOD_TICKS = "period_ticks"; + private static final String TIME_MARKERS = "time_markers"; + private static final String TRACKS = "tracks"; + private static final String TICKS = "ticks"; + private static final String SHOW_IN_COMMANDS = "show_in_commands"; + private static final String MODIFIER = "modifier"; + private static final String EASE = "ease"; + private static final String CUBIC_BEZIER = "cubic_bezier"; + private static final String KEYFRAMES = "keyframes"; + private static final String VALUE = "value"; + private static final Easing LINEAR = new Easing.Named("linear"); + + private ScheduleFormat() { } + + + private static final class Invalid extends Exception { + Invalid(String message) { + super(message, null, false, false); + } + } + + + private static final class TrackDropped extends Exception { + TrackDropped(String message) { + super(message, null, false, false); + } + } + + public static ScheduleDecodeResult decode(RegistryKey id, Map raw, AttributeLookup attributes, + DecodeContext context) { + List dropped = new ArrayList<>(); + try { + AttributeSchedule schedule = readDefinition(raw, attributes, context, dropped); + return new ScheduleDecodeResult(Optional.of(schedule), dropped, Optional.empty()); + } catch(Invalid e) { + return new ScheduleDecodeResult(Optional.empty(), dropped, Optional.of(new Problem(id.toString(), e.getMessage()))); + } + } + + public static Map encode(AttributeSchedule schedule) { + Map encoded = new LinkedHashMap<>(); + encoded.put(CLOCK, schedule.clock().toString()); + schedule.periodTicks().ifPresent(period -> encoded.put(PERIOD_TICKS, period)); + if(!schedule.tracks().isEmpty()) { + Map tracks = new LinkedHashMap<>(); + schedule.tracks().forEach((attribute, track) -> tracks.put(attribute.getRegistryKey().toString(), encodeTrack(attribute, track))); + encoded.put(TRACKS, tracks); + } + if(!schedule.timeMarkers().isEmpty()) { + Map markers = new LinkedHashMap<>(); + schedule.timeMarkers().forEach((key, marker) -> { + Map encodedMarker = new LinkedHashMap<>(); + encodedMarker.put(TICKS, marker.ticks()); + if(marker.showInCommands()) encodedMarker.put(SHOW_IN_COMMANDS, true); + markers.put(key.toString(), encodedMarker); + }); + encoded.put(TIME_MARKERS, markers); + } + return encoded; + } + + private static AttributeSchedule readDefinition(Map raw, AttributeLookup attributes, DecodeContext context, + List dropped) throws Invalid { + RegistryKey clock = identifier(raw.get(CLOCK), "clock"); + + OptionalInt period = OptionalInt.empty(); + if(raw.get(PERIOD_TICKS) != null) { + int ticks = integer(raw.get(PERIOD_TICKS), "period_ticks", context); + if(ticks <= 0) throw new Invalid("period_ticks must be positive"); + period = OptionalInt.of(ticks); + } + + Map markers = new LinkedHashMap<>(); + if(raw.get(TIME_MARKERS) != null) { + for(Map.Entry entry : map(raw.get(TIME_MARKERS), "time_markers").entrySet()) { + RegistryKey marker = identifier(entry.getKey(), "time marker key"); + markers.put(marker, marker(marker, entry.getValue(), period, context)); + } + } + + Map, ScheduleTrack> tracks = new LinkedHashMap<>(); + if(raw.get(TRACKS) != null) { + for(Map.Entry entry : map(raw.get(TRACKS), "tracks").entrySet()) { + String keyString = String.valueOf(entry.getKey()); + Attribute attribute; + try { + attribute = attributes.find(keyString); + } catch(DecodeException e) { + dropped.add(new Problem(keyString, e.getMessage())); + continue; + } + try { + tracks.put(attribute, track(attribute, map(entry.getValue(), "track " + keyString), period, context)); + } catch(TrackDropped e) { + dropped.add(new Problem(keyString, e.getMessage())); + } + } + } + return new AttributeSchedule(clock, period, tracks, markers); + } + + private static TimeMarker marker(RegistryKey key, Object value, OptionalInt period, DecodeContext context) throws Invalid { + int ticks; + boolean show = false; + if(value instanceof Map map) { + if(!map.containsKey(TICKS) || !map.keySet().stream().allMatch(k -> TICKS.equals(k) || SHOW_IN_COMMANDS.equals(k))) { + throw new Invalid("time marker " + key + " must have \"ticks\" and optionally \"show_in_commands\""); + } + ticks = integer(map.get(TICKS), "time marker " + key + " ticks", context); + Object flag = map.get(SHOW_IN_COMMANDS); + if(flag != null) { + if(!(flag instanceof Boolean b)) throw new Invalid("time marker " + key + " show_in_commands must be a boolean"); + show = b; + } + } else { + ticks = integer(value, "time marker " + key, context); + } + if(ticks < 0) throw new Invalid("time marker " + key + " ticks must not be negative"); + if(period.isPresent() && ticks >= period.getAsInt()) { + throw new Invalid("time marker " + key + " ticks " + ticks + " must be less than period_ticks " + period.getAsInt()); + } + return new TimeMarker(ticks, show); + } + + private static ScheduleTrack track(Attribute attribute, Map raw, OptionalInt period, DecodeContext context) + throws Invalid, TrackDropped { + Operation operation = Operation.OVERRIDE; + if(raw.get(MODIFIER) != null) { + try { + operation = Operation.parse(String.valueOf(raw.get(MODIFIER))); + } catch(IllegalArgumentException e) { + throw new Invalid(e.getMessage()); + } + } + Easing ease = raw.get(EASE) == null ? LINEAR : easing(raw.get(EASE), context); + + if(!(raw.get(KEYFRAMES) instanceof List frames)) throw new Invalid("keyframes must be a list"); + if(frames.isEmpty()) throw new Invalid("keyframes must not be empty"); + List ticksList = new ArrayList<>(frames.size()); + int previous = Integer.MIN_VALUE; + int sameTick = 0; + for(Object frame : frames) { + if(!(frame instanceof Map map) || !map.containsKey(TICKS) || !map.containsKey(VALUE) + || !map.keySet().stream().allMatch(k -> TICKS.equals(k) || VALUE.equals(k))) { + throw new Invalid("each keyframe must have exactly \"ticks\" and \"value\""); + } + int ticks = integer(map.get(TICKS), "keyframe ticks", context); + if(ticks < 0) throw new Invalid("keyframe ticks must not be negative"); + if(ticks < previous) throw new Invalid("keyframes must be sorted by ticks"); + sameTick = ticks == previous ? sameTick + 1 : 1; + if(sameTick > 2) throw new Invalid("at most 2 keyframes may share tick " + ticks); + if(period.isPresent() && ticks > period.getAsInt()) { + throw new Invalid("keyframe ticks " + ticks + " must be within period_ticks " + period.getAsInt()); + } + previous = ticks; + ticksList.add(ticks); + } + + // From here on, a failure drops only this track. + if(!attribute.type().operations().contains(operation)) { + throw new TrackDropped("modifier " + operation.getID() + " is not valid for " + attribute.key()); + } + List decoded = new ArrayList<>(frames.size()); + for(int i = 0; i < frames.size(); i++) { + Object rawValue = ((Map) frames.get(i)).get(VALUE); + decoded.add(new Keyframe(ticksList.get(i), argument(attribute, operation, rawValue, context))); + } + return new ScheduleTrack<>(operation, decoded, ease); + } + + private static Object argument(Attribute attribute, Operation operation, Object raw, DecodeContext context) + throws TrackDropped { + try { + if(raw == null) throw new DecodeException("missing keyframe value"); + Object argument = attribute.type().decodeArgument(operation, raw, context); + if(operation == Operation.OVERRIDE) { + @SuppressWarnings("unchecked") + T value = (T) argument; + attribute.validate(value); + } + return argument; + } catch(DecodeException | RuntimeException e) { + throw new TrackDropped(e.getMessage() == null ? "unexpected error" : e.getMessage()); + } + } + + private static Easing easing(Object raw, DecodeContext context) throws Invalid { + if(raw instanceof String name) { + try { + return new Easing.Named(name); + } catch(IllegalArgumentException e) { + throw new Invalid(e.getMessage()); + } + } + if(raw instanceof Map map && map.size() == 1 && map.containsKey(CUBIC_BEZIER) + && map.get(CUBIC_BEZIER) instanceof List list && list.size() == 4) { + float[] v = new float[4]; + for(int i = 0; i < 4; i++) { + Object element = list.get(i); + float f; + if(element instanceof Number n) { + f = n.floatValue(); + } else if(element instanceof String) { + try { + f = context.load(Float.class, element); + } catch(DecodeException e) { + throw new Invalid("cubic_bezier must be a list of 4 numbers: " + e.getMessage()); + } + } else { + throw new Invalid("cubic_bezier must be a list of 4 numbers"); + } + if(!Float.isFinite(f)) throw new Invalid("cubic_bezier must be a list of 4 numbers"); + v[i] = f; + } + try { + return new Easing.CubicBezier(v[0], v[1], v[2], v[3]); + } catch(IllegalArgumentException e) { + throw new Invalid(e.getMessage()); + } + } + throw new Invalid("ease must be an easing name or {cubic_bezier: [x1, y1, x2, y2]}"); + } + + private static RegistryKey identifier(Object raw, String what) throws Invalid { + if(!(raw instanceof String string)) throw new Invalid(what + " must be an identifier string"); + if(string.startsWith("#")) throw new Invalid(what + " must not be a tag"); + try { + return RegistryKey.parseNamespaced(string); + } catch(IllegalArgumentException e) { + throw new Invalid(what + ": " + e.getMessage()); + } + } + + private static int integer(Object raw, String what, DecodeContext context) throws Invalid { + try { + return context.load(Integer.class, raw); + } catch(DecodeException e) { + throw new Invalid(what + " must be an integer: " + e.getMessage()); + } + } + + private static Map map(Object raw, String what) throws Invalid { + if(raw instanceof Map map) return map; + throw new Invalid(what + " must be a map"); + } + + private static Map encodeTrack(Attribute attribute, ScheduleTrack track) { + Map encoded = new LinkedHashMap<>(); + Operation operation = track.operation(); + if(operation != Operation.OVERRIDE) encoded.put(MODIFIER, operation.getID()); + if(!track.ease().equals(LINEAR)) encoded.put(EASE, encodeEasing(track.ease())); + List keyframes = new ArrayList<>(track.keyframes().size()); + for(int i = 0; i < track.keyframes().size(); i++) { + Keyframe keyframe = track.keyframes().get(i); + if(keyframe.argument() == null) { + throw new IllegalArgumentException("keyframe " + i + " of " + attribute.key() + ": a null value has no pack-format form"); + } + Map frame = new LinkedHashMap<>(); + frame.put(TICKS, keyframe.ticks()); + frame.put(VALUE, attribute.type().encodeArgument(operation, keyframe.argument())); + keyframes.add(frame); + } + encoded.put(KEYFRAMES, keyframes); + return encoded; + } + + private static Object encodeEasing(Easing ease) { + return switch(ease) { + case Easing.Named named -> named.name(); + case Easing.CubicBezier bezier -> Map.of(CUBIC_BEZIER, List.of(bezier.x1(), bezier.y1(), bezier.x2(), bezier.y2())); + }; + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecRoundTripTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecRoundTripTest.java new file mode 100644 index 000000000..0bcb70593 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecRoundTripTest.java @@ -0,0 +1,163 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; + +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.StringIdentifiable; +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.AttributeTypes; +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.registry.key.TagKey; +import com.dfsek.terra.api.world.attribute.value.BlendToGray; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.api.world.attribute.value.FloatWithAlpha; +import com.dfsek.terra.api.world.attribute.value.TriState; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + + +class AttributeCodecRoundTripTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final AttributeTypes TYPES = HANDLE.types(); + private static final DecodeContext PLAIN = HANDLE.plainContext(); + + record Case(AttributeType type, List values, Map> arguments) { } + + private static Case of(AttributeType type, List values, Object... opArgs) { + Map> arguments = new LinkedHashMap<>(); + for(int i = 0; i < opArgs.length; i += 2) arguments.put((Operation) opArgs[i], (List) opArgs[i + 1]); + return new Case<>(type, values, arguments); + } + + static List> cases() { + List floats = List.of(0.25f, -3f, 1.5e7f); + List withAlpha = List.of(new FloatWithAlpha(2f, 0.5f), new FloatWithAlpha(3f, 1f)); + List rgb = List.of(Color.rgb(0x102030), Color.rgb(0xFFFFFF), new Color(0.1f, 0.2f, 0.3f, 1f)); + List argb = List.of(Color.argb(0x80112233), Color.argb(0x00000000), new Color(0.1f, 0.2f, 0.3f, 0.4f)); + List gray = List.of(new BlendToGray(0.6f, 0.75f)); + List ints = List.of(7, -2, Integer.MAX_VALUE); + List bools = List.of(true, false); + + return List.of( + of(TYPES.booleanType(), bools, + Operation.AND, bools, Operation.NAND, bools, Operation.OR, bools, Operation.NOR, bools, Operation.XOR, bools, + Operation.XNOR, bools), + of(TYPES.triState(), List.of(TriState.TRUE, TriState.FALSE, TriState.DEFAULT)), + of(TYPES.floatType(), floats, + Operation.ALPHA_BLEND, withAlpha, Operation.ADD, floats, Operation.SUBTRACT, floats, Operation.MULTIPLY, floats, + Operation.MINIMUM, floats, Operation.MAXIMUM, floats), + of(TYPES.angleDegrees(), floats, + Operation.ALPHA_BLEND, withAlpha, Operation.ADD, floats, Operation.SUBTRACT, floats, Operation.MULTIPLY, floats, + Operation.MINIMUM, floats, Operation.MAXIMUM, floats), + of(TYPES.rgbColor(), rgb, + Operation.ALPHA_BLEND, argb, Operation.ADD, rgb, Operation.SUBTRACT, rgb, Operation.MULTIPLY, rgb, + Operation.BLEND_TO_GRAY, gray), + of(TYPES.argbColor(), argb, + Operation.ALPHA_BLEND, argb, Operation.ADD, rgb, Operation.SUBTRACT, rgb, Operation.MULTIPLY, argb, + Operation.BLEND_TO_GRAY, gray), + of(TYPES.integer(), ints, + Operation.ADD, ints, Operation.SUBTRACT, ints, Operation.MULTIPLY, ints, Operation.MINIMUM, ints, Operation.MAXIMUM, ints), + of(TYPES.integerOverrideOnly(), ints), + of(TYPES.identifier("mypack"), List.of(RegistryKey.parse("mypack:stone"), RegistryKey.parse("my.pack:A/b"))), + of(TYPES.identifierOrTag("mypack"), List.>of( + Either.left(RegistryKey.parse("mypack:stone")), Either.right(TagKey.parse("#my.pack:logs")))), + of(TYPES.enumType("test_weather", Weather.class), List.of(Weather.values()))); + } + + private enum Weather implements StringIdentifiable { + CLEAR("sunny"), + STORM("thunder"); + + private final String id; + + Weather(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } + } + + private static void assertPlain(Object encoded, String where) { + if(encoded == null || encoded instanceof Number || encoded instanceof Boolean || encoded instanceof String) return; + if(encoded instanceof List list) { + for(Object element : list) assertPlain(element, where); + return; + } + if(encoded instanceof Map m) { + m.forEach((k, v) -> { + assertTrue(k instanceof String, where + ": map key " + k + " is not a string"); + assertPlain(v, where); + }); + return; + } + fail(where + ": encoded a " + encoded.getClass().getName() + ": " + encoded); + } + + private static void assertValuesRoundTrip(Case c) throws DecodeException { + for(T value : c.values()) { + Object encoded = c.type().encode(value); + assertPlain(encoded, c.type().id()); + assertEquals(value, c.type().decode(encoded, PLAIN), c.type().id() + " via " + encoded); + } + } + + @Test + void everyCoreType() throws DecodeException { + for(Case c : cases()) assertValuesRoundTrip(c); + } + + @Test + void everyArgument() throws DecodeException { + for(Case c : cases()) { + AttributeType type = c.type(); + List unsampled = new ArrayList<>(type.operations()); + unsampled.remove(Operation.OVERRIDE); + unsampled.removeAll(c.arguments().keySet()); + assertTrue(unsampled.isEmpty(), type.id() + " has no sample argument for " + unsampled); + + Map> arguments = new LinkedHashMap<>(c.arguments()); + arguments.put(Operation.OVERRIDE, c.values()); + for(Map.Entry> e : arguments.entrySet()) { + for(Object argument : e.getValue()) { + Object encoded = type.encodeArgument(e.getKey(), argument); + assertPlain(encoded, type.id() + " " + e.getKey().getID()); + assertEquals(argument, type.decodeArgument(e.getKey(), encoded, PLAIN), + type.id() + " " + e.getKey().getID() + " via " + encoded); + } + } + } + } + + @Test + void encodeArgumentInvalidOperation() { + assertThrows(IllegalArgumentException.class, () -> TYPES.booleanType().encodeArgument(Operation.ADD, 1f)); + } + + @Test + void canonicalForms() { + assertEquals("#102030", TYPES.rgbColor().encode(Color.rgb(0x102030))); + assertEquals("#80112233", TYPES.argbColor().encode(Color.argb(0x80112233))); + assertEquals("#abcdef", TYPES.rgbColor().encode(Color.rgb(0xABCDEF))); + assertEquals("mypack:stone", TYPES.identifier("mypack").encode(RegistryKey.parse("mypack:stone"))); + assertEquals("#mypack:logs", TYPES.identifierOrTag("mypack").encode(Either.right(TagKey.parse("#mypack:logs")))); + assertEquals("mypack:stone", TYPES.identifierOrTag("mypack").encode(Either.left(RegistryKey.parse("mypack:stone")))); + assertEquals("thunder", TYPES.enumType("test_weather", Weather.class).encode(Weather.STORM)); + assertEquals(true, TYPES.triState().encode(TriState.TRUE)); + assertEquals("default", TYPES.triState().encode(TriState.DEFAULT)); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecsTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecsTest.java new file mode 100644 index 000000000..21c36baf3 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecsTest.java @@ -0,0 +1,119 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import com.dfsek.terra.api.registry.key.StringIdentifiable; +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 static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + + +class AttributeCodecsTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final AttributeCodecs CODECS = HANDLE.codecs(); + private static final DecodeContext PLAIN = HANDLE.plainContext(); + + private record Point(int x, float weight) { } + + + private static final AttributeCodec POINT = CODECS.of((raw, context) -> { + ObjectReader f = CODECS.reader("point", raw, context); + int x = f.required("x", CODECS.intCodec()); + float weight = f.orDefault("weight", CODECS.unitFloat(), 1f); + f.finish(); + return new Point(x, weight); + }, value -> CODECS.writer() + .put("x", CODECS.intCodec(), value.x()) + .put("weight", CODECS.unitFloat(), value.weight()) + .optional("label", CODECS.string("expected a label"), Optional.empty()) + .map()); + + private enum Weather implements StringIdentifiable { + CLEAR("sunny"), + STORM("thunder"); + + private final String id; + + Weather(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } + } + + private static Map map(Object... kv) { + Map m = new LinkedHashMap<>(); + for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]); + return m; + } + + @Test + void ofRoundTrips() throws DecodeException { + Point point = new Point(3, 0.5f); + Object encoded = POINT.encode(point); + assertEquals(map("x", 3, "weight", 0.5f), encoded); + assertEquals(point, POINT.decode(encoded, PLAIN)); + assertEquals(new Point(4, 1f), POINT.decode(map("x", 4), PLAIN)); + + AttributeCodec> points = CODECS.compactList(POINT); + assertEquals(List.of(point), points.decode(encoded, PLAIN)); + assertEquals(List.of(encoded), points.encode(List.of(point))); + } + + @Test + void intFailures() { + assertEquals("\"x\" of point: expected an integer, got 1.5", + assertThrows(DecodeException.class, () -> POINT.decode(map("x", 1.5), PLAIN)).getMessage()); + assertEquals("expected a non-negative integer, got -1", + assertThrows(DecodeException.class, () -> CODECS.nonNegativeInt().decode(-1, PLAIN)).getMessage()); + } + + @Test + void readerUnknownField() { + assertEquals("unknown key \"y\" in point", + assertThrows(DecodeException.class, () -> POINT.decode(map("x", 1, "y", 2), PLAIN)).getMessage()); + assertEquals("point is missing required key \"x\"", + assertThrows(DecodeException.class, () -> POINT.decode(map(), PLAIN)).getMessage()); + assertEquals("expected an object for point, got a list", + assertThrows(DecodeException.class, () -> POINT.decode(List.of(), PLAIN)).getMessage()); + } + + @Test + void enumUnknownId() throws DecodeException { + AttributeCodec weather = CODECS.enumCodec("weather", Weather.class); + assertSame(Weather.STORM, weather.decode("thunder", PLAIN)); + assertEquals("thunder", weather.encode(Weather.STORM)); + assertEquals("unknown weather \"storm\", expected one of [sunny, thunder]", + assertThrows(DecodeException.class, () -> weather.decode("storm", PLAIN)).getMessage()); + } + + @Test + void listFailingElement() { + assertEquals("element 1: expected an integer, got 2.5", + assertThrows(DecodeException.class, () -> CODECS.list(CODECS.intCodec()).decode(List.of(1, 2.5), PLAIN)).getMessage()); + } + + @Test + void describeValues() { + assertEquals("\"a\"", CODECS.describe("a")); + assertEquals("an object", CODECS.describe(Map.of())); + assertEquals("a list", CODECS.describe(List.of())); + assertEquals("nothing", CODECS.describe(null)); + assertEquals("3", CODECS.describe(3)); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeComposeTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeComposeTest.java new file mode 100644 index 000000000..4ac849b92 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeComposeTest.java @@ -0,0 +1,151 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeCodec; +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.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.value.Color; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class AttributeComposeTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final AttributeTypes TYPES = HANDLE.types(); + + private static final Attribute FOG_END = attribute("test:fog_end", TYPES.floatType(), 1024f).range(0, Double.POSITIVE_INFINITY) + .build(); + private static final Attribute SUN_ANGLE = attribute("test:sun_angle", TYPES.angleDegrees(), 0f).build(); + private static final Attribute SEA_LEVEL = attribute("test:sea_level", TYPES.integer(), 63).build(); + private static final Attribute FOG_COLOR = attribute("test:fog_color", TYPES.rgbColor(), Color.rgb(0)).build(); + private static final Attribute GRASS_COLOR = attribute("test:grass_color", TYPES.rgbColor(), null).build(); + + private static Attribute.Builder attribute(String key, AttributeType type, T defaultValue) { + return HANDLE.attributeBuilder(AttributeKey.parse(key), type, defaultValue); + } + + private static AttributeEntry composed(Attribute attribute, AttributeEntry lower, AttributeEntry upper) { + return HANDLE.compose(attribute, lower, upper).orElseThrow(() -> new AssertionError("empty")); + } + + private static void assertEntry(Operation operation, Object argument, AttributeEntry entry) { + assertEquals(operation, entry.operation()); + assertEquals(argument, entry.argument()); + } + + @Test + void nullOrUpperOverride() { + assertTrue(HANDLE.compose(FOG_END, null, null).isEmpty()); + AttributeEntry lower = AttributeEntry.override(10f); + AttributeEntry upper = AttributeEntry.of(Operation.MULTIPLY, 2f); + assertSame(lower, composed(FOG_END, lower, null)); + assertSame(upper, composed(FOG_END, null, upper)); + AttributeEntry override = AttributeEntry.override(5f); + assertSame(override, composed(FOG_END, lower, override)); + assertSame(override, composed(FOG_END, AttributeEntry.of(Operation.ADD, 3f), override)); + } + + @Test + void lowerOverride() { + assertEntry(Operation.OVERRIDE, 30f, composed(FOG_END, AttributeEntry.override(10f), AttributeEntry.of(Operation.MULTIPLY, 3f))); + assertEntry(Operation.OVERRIDE, 13f, composed(FOG_END, AttributeEntry.override(10f), AttributeEntry.of(Operation.ADD, 3f))); + assertEntry(Operation.OVERRIDE, 2000f, composed(FOG_END, AttributeEntry.override(1000f), AttributeEntry.of(Operation.MULTIPLY, 2f))); + Color base = Color.parseRgb("#102030"); + Color add = Color.parseRgb("#010101"); + assertEntry(Operation.OVERRIDE, FOG_COLOR.type().apply(Operation.ADD, base, add), + composed(FOG_COLOR, AttributeEntry.override(base), AttributeEntry.of(Operation.ADD, add))); + } + + @Test + void lowerNullOverride() { + AttributeEntry lower = AttributeEntry.override(null); + assertSame(lower, composed(GRASS_COLOR, lower, AttributeEntry.of(Operation.MULTIPLY, Color.parseRgb("#808080")))); + } + + @Test + void builtinTypesCompose() { + assertEntry(Operation.ADD, 5f, composed(FOG_END, AttributeEntry.of(Operation.ADD, 2f), AttributeEntry.of(Operation.ADD, 3f))); + assertEntry(Operation.MULTIPLY, 6f, + composed(FOG_END, AttributeEntry.of(Operation.MULTIPLY, 2f), AttributeEntry.of(Operation.MULTIPLY, 3f))); + assertEntry(Operation.ADD, 50f, composed(SUN_ANGLE, AttributeEntry.of(Operation.ADD, 20f), AttributeEntry.of(Operation.ADD, 30f))); + assertEntry(Operation.MULTIPLY, 1.5f, + composed(SUN_ANGLE, AttributeEntry.of(Operation.MULTIPLY, 0.5f), AttributeEntry.of(Operation.MULTIPLY, 3f))); + assertEntry(Operation.ADD, 7, composed(SEA_LEVEL, AttributeEntry.of(Operation.ADD, 3), AttributeEntry.of(Operation.ADD, 4))); + assertEntry(Operation.MULTIPLY, 12, + composed(SEA_LEVEL, AttributeEntry.of(Operation.MULTIPLY, 3), AttributeEntry.of(Operation.MULTIPLY, 4))); + } + + private static final AttributeCodec INT_CODEC = new AttributeCodec<>() { + @Override + public Integer decode(Object raw, DecodeContext context) throws DecodeException { + return context.load(Integer.class, raw); + } + + @Override + public Object encode(Integer value) { + return value; + } + }; + + private static Attribute counter(AttributeType type) { + return HANDLE.attributeBuilder(AttributeKey.parse("test:counter"), type, 0).build(); + } + + @Test + void addonTypeComposes() { + AttributeType composable = HANDLE.typeBuilder("test:counter", INT_CODEC) + .op(Operation.ADD, INT_CODEC, Integer::sum) + .composable(Operation.ADD, Integer::sum) + .build(); + assertEntry(Operation.ADD, 5, composed(counter(composable), AttributeEntry.of(Operation.ADD, 2), AttributeEntry.of(Operation.ADD, 3))); + + AttributeType plain = HANDLE.typeBuilder("test:counter", INT_CODEC).op(Operation.ADD, INT_CODEC, Integer::sum).build(); + assertTrue(HANDLE.compose(counter(plain), AttributeEntry.of(Operation.ADD, 2), AttributeEntry.of(Operation.ADD, 3)).isEmpty()); + } + + @Test + void composerReturningNull() { + AttributeType broken = HANDLE.typeBuilder("test:counter", INT_CODEC) + .op(Operation.ADD, INT_CODEC, Integer::sum) + .composable(Operation.ADD, (a, b) -> null) + .build(); + NullPointerException e = assertThrows(NullPointerException.class, () -> broken.compose(Operation.ADD, 2, 3)); + assertEquals("composer for add of test:counter returned null", e.getMessage()); + } + + @Test + void composableWithoutOperation() { + AttributeType.Builder builder = HANDLE.typeBuilder("test:counter", INT_CODEC); + assertThrows(IllegalArgumentException.class, () -> builder.composable(Operation.ADD, Integer::sum)); + assertThrows(IllegalArgumentException.class, () -> builder.composable(Operation.OVERRIDE, (a, b) -> b)); + } + + @Test + @SuppressWarnings("unchecked") + void composedResolvesLikeLayers() { + AttributeEntry pack = AttributeEntry.override(60); + AttributeEntry lower = AttributeEntry.of(Operation.ADD, 3); + AttributeEntry upper = AttributeEntry.of(Operation.ADD, -10); + assertEquals(HANDLE.resolve(SEA_LEVEL, pack, lower, upper), HANDLE.resolve(SEA_LEVEL, pack, composed(SEA_LEVEL, lower, upper))); + } + + @Test + void notComposable() { + assertTrue(HANDLE.compose(FOG_END, AttributeEntry.of(Operation.ADD, 2f), AttributeEntry.of(Operation.MULTIPLY, 3f)).isEmpty()); + assertTrue(HANDLE.compose(FOG_END, AttributeEntry.of(Operation.MINIMUM, 2f), AttributeEntry.of(Operation.MINIMUM, 3f)).isEmpty()); + assertTrue(HANDLE.compose(FOG_END, AttributeEntry.of(Operation.SUBTRACT, 2f), AttributeEntry.of(Operation.SUBTRACT, 3f)).isEmpty()); + Color add = Color.parseRgb("#010101"); + assertTrue(HANDLE.compose(FOG_COLOR, AttributeEntry.of(Operation.ADD, add), AttributeEntry.of(Operation.ADD, add)).isEmpty()); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeIndexTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeIndexTest.java new file mode 100644 index 000000000..7cf013bc2 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeIndexTest.java @@ -0,0 +1,51 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; + +import java.util.Set; + +import com.dfsek.terra.api.registry.CheckedRegistry; +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.registry.CheckedRegistryImpl; +import com.dfsek.terra.registry.OpenRegistryImpl; + +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 AttributeIndexTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + + private static Attribute build(String key) { + return HANDLE.attributeBuilder(AttributeKey.parse(key), HANDLE.types().floatType(), 0f).build(); + } + + @Test + void denseIndices() { + Attribute a = build("test:a"); + Attribute b = build("test:b"); + Attribute c = build("test:c"); + assertEquals(3, Set.of(a.index(), b.index(), c.index()).size()); + assertEquals(a.index() + 1, b.index()); + assertEquals(b.index() + 1, c.index()); + assertTrue(a.index() >= 0); + assertTrue(HANDLE.attributeCount() >= c.index() + 1, () -> HANDLE.attributeCount() + " <= " + c.index()); + } + + @Test + void lookupIsTyped() { + CheckedRegistry> registry = new CheckedRegistryImpl<>(new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE)); + Attribute fog = build("test:visual/fog"); + registry.register(fog.getRegistryKey(), fog); + + assertSame(fog, fog.key().lookup(registry).orElseThrow()); + AttributeKey lookalike = AttributeKey.parse("test:visual/fog"); + assertEquals(fog.key(), lookalike); + assertTrue(lookalike.lookup(registry).isEmpty()); + assertSame(fog, registry.get(lookalike.getRegistryKey()).orElseThrow()); + assertTrue(AttributeKey.parse("test:nothing").lookup(registry).isEmpty()); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeLayersTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeLayersTest.java new file mode 100644 index 000000000..d9c52515e --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeLayersTest.java @@ -0,0 +1,88 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Proxy; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.properties.Context; +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.AttributeParents; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.AttributeTypes; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.PackAttributes; +import com.dfsek.terra.api.world.attribute.value.Color; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +@SuppressWarnings("unchecked") +class AttributeLayersTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final AttributeTypes TYPES = HANDLE.types(); + + private static final Attribute FOG_END = attribute("test:fog_end", TYPES.floatType(), 1024f) + .range(0, Double.POSITIVE_INFINITY).build(); + private static final Attribute WATER_FOG_END = attribute("test:water_fog_end", TYPES.floatType(), 96f) + .range(0, Double.POSITIVE_INFINITY).build(); + private static final Attribute FOG_COLOR = attribute("test:fog_color", TYPES.rgbColor(), Color.rgb(0)).build(); + private static final Attribute FOLIAGE_COLOR = attribute("test:foliage_color", TYPES.rgbColor(), null).build(); + private static final Attribute STAR_BRIGHTNESS = attribute("test:star_brightness", TYPES.floatType(), 0f).range(0, 1).build(); + + private static Attribute.Builder attribute(String key, AttributeType type, T defaultValue) { + return HANDLE.attributeBuilder(AttributeKey.parse(key), type, defaultValue); + } + + @Test + void layerOrder() { + assertEquals(1024f, HANDLE.resolve(FOG_END), "default alone"); + assertEquals(5f, HANDLE.resolve(FOG_END, null, AttributeEntry.override(5f), null), "null layers are skipped"); + assertEquals(1f, HANDLE.resolve(STAR_BRIGHTNESS, AttributeEntry.override(2f)), "the range clamps the result"); + assertEquals(81.6f, HANDLE.resolve(WATER_FOG_END, AttributeEntry.override(96f), AttributeEntry.of(Operation.MULTIPLY, 0.85f)), + 1e-3f, "pack then biome multiply"); + + AttributeEntry pack = AttributeEntry.override(Color.rgb(0x808080)); + AttributeEntry vanilla = AttributeEntry.override(Color.rgb(0xc0d8ff)); + AttributeEntry terra = AttributeEntry.of(Operation.ADD, Color.rgb(0x101010)); + assertEquals(0xc0d8ff, HANDLE.resolve(FOG_COLOR, pack, vanilla).toRgbInt(), "vanilla parent wins over the pack override"); + assertEquals(0xd0e8ff, HANDLE.resolve(FOG_COLOR, pack, vanilla, terra).toRgbInt(), "Terra modifier on the vanilla parent"); + } + + @Test + void modifiersOnNull() { + AttributeEntry add = AttributeEntry.of(Operation.ADD, Color.rgb(0x101010)); + assertNull(HANDLE.resolve(FOLIAGE_COLOR)); + assertNull(HANDLE.resolve(FOLIAGE_COLOR, add)); + assertEquals(0x305070, HANDLE.resolve(FOLIAGE_COLOR, add, AttributeEntry.override(Color.rgb(0x204060)), add).toRgbInt()); + } + + @Test + void parentsNoneIsEmpty() { + assertNull(AttributeParents.NONE.biomeOrNull(null, FOG_END)); + assertNull(AttributeParents.NONE.packOrNull(null, FOG_END)); + } + + @Test + void packAttributesFromContext() { + Context context = new Context(); + ConfigPack pack = (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class[]{ ConfigPack.class }, + (proxy, method, args) -> switch(method.getName()) { + case "getContext" -> context; + default -> throw new UnsupportedOperationException(method.getName()); + }); + assertTrue(HANDLE.pack(pack).isEmpty()); + PackAttributes attributes = (PackAttributes) Proxy.newProxyInstance(PackAttributes.class.getClassLoader(), + new Class[]{ PackAttributes.class }, (proxy, method, args) -> { + throw new UnsupportedOperationException(method.getName()); + }); + context.put(Context.create(PackAttributes.class), attributes); + assertSame(attributes, HANDLE.pack(pack).orElseThrow()); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeTypesTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeTypesTest.java new file mode 100644 index 000000000..cc713e826 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeTypesTest.java @@ -0,0 +1,382 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Named; +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.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +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.AttributeCodec; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.AttributeTypes; +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.value.Color; +import com.dfsek.terra.api.world.attribute.value.TriState; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.params.provider.Arguments.arguments; + + +public class AttributeTypesTest { + private static final float EPS = 1e-6f; + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final AttributeTypes TYPES = HANDLE.types(); + private static final DecodeContext PLAIN = HANDLE.plainContext(); + private static final AttributeType WEATHER = TYPES.enumType("test_weather", Weather.class); + private static final AttributeCodec FLOAT = new AttributeCodec<>() { + @Override + public Float decode(Object raw, DecodeContext context) throws DecodeException { + return context.load(Float.class, raw); + } + + @Override + public Object encode(Float value) { + return value; + } + }; + + private enum Weather implements StringIdentifiable { + CLEAR("sunny"), + STORM("thunder"); + + private final String id; + + Weather(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } + } + + private static T mod(AttributeType type, Operation op, T subject, Object rawArg) throws DecodeException { + return type.apply(op, subject, type.decodeArgument(op, rawArg, PLAIN)); + } + + private static void assertColor(float r, float g, float b, float a, Color c) { + assertEquals(r, c.r(), EPS, "r"); + assertEquals(g, c.g(), EPS, "g"); + assertEquals(b, c.b(), EPS, "b"); + assertEquals(a, c.a(), EPS, "a"); + } + + private static void assertValue(Object expected, Object actual) { + if(expected instanceof Color e && actual instanceof Color c) assertColor(e.r(), e.g(), e.b(), e.a(), c); + else if(expected instanceof Float e && actual instanceof Float f) assertEquals(e, f, EPS); + else assertEquals(expected, actual); + } + + private static Map map(Object... kv) { + Map m = new LinkedHashMap<>(); + for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]); + return m; + } + + private static Named> named(AttributeType type) { + return Named.of(type.id(), type); + } + + private static Color color(float r, float g, float b, float a) { + return new Color(r, g, b, a); + } + + @Test + public void booleanOps() throws DecodeException { + AttributeType t = TYPES.booleanType(); + for(boolean s : new boolean[]{ true, false }) { + for(boolean a : new boolean[]{ true, false }) { + assertEquals(a && s, mod(t, Operation.AND, s, a)); + assertEquals(!a || !s, mod(t, Operation.NAND, s, a)); + assertEquals(a || s, mod(t, Operation.OR, s, a)); + assertEquals(!a && !s, mod(t, Operation.NOR, s, a)); + assertEquals(a ^ s, mod(t, Operation.XOR, s, a)); + assertEquals(a == s, mod(t, Operation.XNOR, s, a)); + } + } + assertEquals(true, mod(t, Operation.OVERRIDE, false, true)); + } + + private static Arguments modifier(AttributeType type, Operation op, Object subject, Object rawArg, Object expected) { + return arguments(named(type), op, subject, rawArg, expected); + } + + static Stream modifiers() { + float sa = 0.5f; + float da = 0.2f; + float a = sa + da * (1 - sa); + Color dst = color(0.8f, 0.2f, 0.4f, 0.2f); + return Stream.of( + modifier(TYPES.floatType(), Operation.ADD, 5f, 2.5, 7.5f), + modifier(TYPES.floatType(), Operation.SUBTRACT, 5f, 2.5, 2.5f), + modifier(TYPES.floatType(), Operation.MULTIPLY, 5f, 2, 10f), + modifier(TYPES.floatType(), Operation.MINIMUM, 5f, 2.5, 2.5f), + modifier(TYPES.floatType(), Operation.MAXIMUM, 5f, 2.5, 5f), + modifier(TYPES.angleDegrees(), Operation.ADD, 1f, 0.5, 1.5f), + modifier(TYPES.floatType(), Operation.ALPHA_BLEND, 2f, 8, 8f), + modifier(TYPES.floatType(), Operation.ALPHA_BLEND, 2f, map("value", 6, "alpha", 0.5), 4f), + modifier(TYPES.floatType(), Operation.ALPHA_BLEND, 2f, map("value", 6), 6f), + modifier(TYPES.integer(), Operation.ADD, 5, 3, 8), + modifier(TYPES.integer(), Operation.SUBTRACT, 5, 3, 2), + modifier(TYPES.integer(), Operation.MULTIPLY, 5, 3, 15), + modifier(TYPES.integer(), Operation.MINIMUM, 5, 3, 3), + modifier(TYPES.integer(), Operation.MAXIMUM, 5, 3, 5), + modifier(TYPES.rgbColor(), Operation.ADD, color(0.5f, 0.9f, 0.1f, 1f), List.of(0.25, 0.25, 0.5), color(0.75f, 1f, 0.6f, 1f)), + modifier(TYPES.rgbColor(), Operation.SUBTRACT, color(0.5f, 0.9f, 0.1f, 1f), List.of(0.25, 0.25, 0.5), + color(0.25f, 0.65f, 0f, 1f)), + modifier(TYPES.rgbColor(), Operation.MULTIPLY, color(0.5f, 0.5f, 0.6f, 1f), List.of(0.8, 0.8, 0.8), + color(0.4f, 0.4f, 0.48f, 1f)), + modifier(TYPES.rgbColor(), Operation.MULTIPLY, color(0.3f, 0.4f, 0.5f, 1f), List.of(1, 1, 1), color(0.3f, 0.4f, 0.5f, 1f)), + modifier(TYPES.rgbColor(), Operation.MULTIPLY, color(1f, 1f, 1f, 1f), List.of(0.3, 0.4, 0.5), color(0.3f, 0.4f, 0.5f, 1f)), + modifier(TYPES.rgbColor(), Operation.ALPHA_BLEND, color(0f, 0f, 1f, 1f), List.of(1, 0, 0, 0), color(0f, 0f, 1f, 1f)), + modifier(TYPES.rgbColor(), Operation.ALPHA_BLEND, color(0f, 0f, 1f, 1f), List.of(1, 0, 0, 0.5), color(0.5f, 0f, 0.5f, 1f)), + modifier(TYPES.rgbColor(), Operation.ALPHA_BLEND, color(0f, 0f, 1f, 1f), "#ffff0000", color(1f, 0f, 0f, 1f)), + modifier(TYPES.rgbColor(), Operation.BLEND_TO_GRAY, color(1f, 0f, 0f, 1f), map("brightness", 0.6, "factor", 0.75), + color(0.385f, 0.135f, 0.135f, 1f)), + modifier(TYPES.argbColor(), Operation.ADD, color(0.5f, 0.5f, 0.5f, 0.3f), List.of(0.25, 0.25, 0.75), + color(0.75f, 0.75f, 1f, 0.3f)), + modifier(TYPES.argbColor(), Operation.SUBTRACT, color(0.5f, 0.5f, 0.5f, 0.3f), List.of(0.25, 0.25, 0.75), + color(0.25f, 0.25f, 0f, 0.3f)), + modifier(TYPES.argbColor(), Operation.MULTIPLY, color(0.5f, 0.5f, 0.5f, 0.5f), List.of(0.5, 0.5, 0.5, 0.3), + color(0.25f, 0.25f, 0.25f, 0.15f)), + modifier(TYPES.argbColor(), Operation.MULTIPLY, color(0.2f, 0.3f, 0.4f, 0.5f), List.of(1, 1, 1, 1), + color(0.2f, 0.3f, 0.4f, 0.5f)), + modifier(TYPES.argbColor(), Operation.MULTIPLY, color(1f, 1f, 1f, 1f), List.of(0.2, 0.3, 0.4, 0.5), + color(0.2f, 0.3f, 0.4f, 0.5f)), + modifier(TYPES.argbColor(), Operation.ALPHA_BLEND, dst, List.of(0, 1, 0, 1), color(0f, 1f, 0f, 1f)), + modifier(TYPES.argbColor(), Operation.ALPHA_BLEND, dst, List.of(0, 1, 0, 0), dst), + modifier(TYPES.argbColor(), Operation.ALPHA_BLEND, dst, List.of(0, 1, 0, 0.5), + color((0f * sa + 0.8f * (a - sa)) / a, (1f * sa + 0.2f * (a - sa)) / a, (0f * sa + 0.4f * (a - sa)) / a, a)), + modifier(TYPES.argbColor(), Operation.BLEND_TO_GRAY, color(1f, 0f, 0f, 0.7f), map("brightness", 0.6, "factor", 0.75), + color(0.385f, 0.135f, 0.135f, 0.7f)), + modifier(TYPES.rgbColor(), Operation.OVERRIDE, color(0f, 0f, 0f, 1f), "#ff0000", color(1f, 0f, 0f, 1f)), + modifier(WEATHER, Operation.OVERRIDE, Weather.CLEAR, "thunder", Weather.STORM)); + } + + @ParameterizedTest + @MethodSource + @SuppressWarnings("unchecked") + public void modifiers(AttributeType type, Operation op, Object subject, Object rawArg, Object expected) + throws DecodeException { + assertValue(expected, mod(type, op, subject, rawArg)); + } + + private static Arguments invalid(AttributeType type, Operation op, Object raw, String message) { + return arguments(named(type), op, raw, message); + } + + static Stream invalidArguments() { + return Stream.of( + invalid(TYPES.booleanType(), Operation.MULTIPLY, true, "modifier multiply is not valid for boolean"), + invalid(TYPES.floatType(), Operation.AND, true, null), + invalid(TYPES.triState(), Operation.ADD, 1, null), + invalid(TYPES.floatType(), Operation.ALPHA_BLEND, map("value", 6, "alpha", 1.5), null), + invalid(TYPES.floatType(), Operation.ALPHA_BLEND, map("value", 6, "bogus", 1), null), + invalid(TYPES.floatType(), Operation.ALPHA_BLEND, map("alpha", 0.5), null), + invalid(TYPES.rgbColor(), Operation.BLEND_TO_GRAY, map("brightness", 1.5, "factor", 0.5), null), + invalid(TYPES.rgbColor(), Operation.BLEND_TO_GRAY, map("brightness", 0.5), null), + invalid(TYPES.rgbColor(), Operation.BLEND_TO_GRAY, map("brightness", 0.5, "factor", 0.5, "extra", 1), null), + invalid(TYPES.argbColor(), Operation.ADD, List.of(0.1, 0.1, 0.1, 0.1), null)); + } + + @ParameterizedTest + @MethodSource + public void invalidArguments(AttributeType type, Operation op, Object raw, String message) { + DecodeException e = assertThrows(DecodeException.class, () -> type.decodeArgument(op, raw, PLAIN)); + if(message != null) assertEquals(message, e.getMessage()); + } + + private static Arguments decode(AttributeType type, Object raw, Object expected) { + return arguments(named(type), raw, expected); + } + + static Stream decodes() { + return Stream.of( + decode(TYPES.integer(), 7, 7), + decode(TYPES.integer(), 7L, 7), + decode(TYPES.integer(), (short) 7, 7), + decode(TYPES.integer(), (byte) 7, 7), + decode(TYPES.integer(), 7.0, 7), + decode(TYPES.integer(), 7.0f, 7), + decode(TYPES.integer(), BigInteger.valueOf(7), 7), + decode(TYPES.integer(), new BigDecimal("7.00"), 7), + decode(TYPES.integer(), (double) Integer.MIN_VALUE, Integer.MIN_VALUE), + decode(TYPES.integer(), BigInteger.valueOf(Integer.MAX_VALUE), Integer.MAX_VALUE), + decode(TYPES.floatType(), 3, 3f), + decode(TYPES.floatType(), 0.25, 0.25f), + decode(TYPES.rgbColor(), "#050533", Color.rgb(0x050533)), + decode(TYPES.rgbColor(), List.of(0.1, 0.2, 0.3), color(0.1f, 0.2f, 0.3f, 1f)), + decode(TYPES.rgbColor(), 0xFF0000, color(1f, 0f, 0f, 1f)), + decode(TYPES.argbColor(), "#44112233", Color.argb(0x44112233)), + decode(TYPES.triState(), "default", TriState.DEFAULT), + decode(TYPES.triState(), true, TriState.TRUE), + decode(TYPES.identifier("mypack"), "mypack:idle", RegistryKey.parse("mypack:idle")), + decode(TYPES.identifier("mypack"), "idle", RegistryKey.parse("mypack:idle")), + decode(TYPES.identifier("mypack"), "other:idle", RegistryKey.parse("other:idle")), + decode(TYPES.identifier("mypack"), "Mod:Music.Game", RegistryKey.parse("Mod:Music.Game")), + decode(TYPES.identifierOrTag("mypack"), "stone", Either.left(RegistryKey.parse("mypack:stone"))), + decode(TYPES.identifierOrTag("mypack"), "#logs", Either.right(TagKey.parse("#mypack:logs"))), + decode(TYPES.identifierOrTag("mypack"), "#Mod:Logs", Either.right(TagKey.parse("#Mod:Logs"))), + decode(WEATHER, "sunny", Weather.CLEAR), + decode(WEATHER, "thunder", Weather.STORM)); + } + + @ParameterizedTest + @MethodSource + public void decodes(AttributeType type, Object raw, Object expected) throws DecodeException { + assertValue(expected, type.decode(raw, PLAIN)); + } + + private static Arguments reject(AttributeType type, Object raw, String message) { + return arguments(named(type), raw, message); + } + + static Stream decodeFailures() { + return Stream.of( + reject(TYPES.integer(), 4.5, "expected an integer, got 4.5"), + reject(TYPES.integer(), 99999999999L, "expected an integer, got 99999999999"), + reject(TYPES.integer(), new BigDecimal("1.5"), "expected an integer, got 1.5"), + reject(TYPES.integer(), BigInteger.valueOf(1L << 31), "expected an integer, got 2147483648"), + reject(TYPES.integer(), new BigInteger("100000000000000000000"), null), + reject(TYPES.integer(), 2147483648.0, null), + reject(TYPES.integer(), Double.NaN, null), + reject(TYPES.integer(), Float.POSITIVE_INFINITY, null), + reject(TYPES.integer(), 1.5f, null), + reject(TYPES.integer(), "4", null), + reject(TYPES.floatType(), "1.0", null), + reject(TYPES.floatType(), true, null), + reject(TYPES.booleanType(), "yes", "expected a boolean (true or false), got \"yes\""), + reject(TYPES.booleanType(), 1, null), + reject(TYPES.rgbColor(), true, "expected a color like \"#rrggbb\", got true"), + reject(TYPES.rgbColor(), "#12345", null), + reject(TYPES.rgbColor(), 0.5, null), + reject(TYPES.triState(), "maybe", null), + reject(TYPES.identifier("mypack"), "Not Valid", "expected an identifier like \"mypack:id\", got \"Not Valid\""), + reject(TYPES.identifier("mypack"), "#mypack:logs", "expected an identifier, not a tag, got \"#mypack:logs\""), + reject(TYPES.identifier("mypack"), "mypack:", null), + reject(TYPES.identifier("mypack"), 3, null), + reject(TYPES.identifierOrTag("mypack"), "#", null), + reject(WEATHER, "storm", "unknown test weather \"storm\", expected one of [sunny, thunder]"), + reject(WEATHER, "CLEAR", null), + reject(WEATHER, 1, null)); + } + + @ParameterizedTest + @MethodSource + public void decodeFailures(AttributeType type, Object raw, String message) { + DecodeException e = assertThrows(DecodeException.class, () -> type.decode(raw, PLAIN)); + if(message != null) assertEquals(message, e.getMessage()); + } + + @Test + public void builder() throws DecodeException { + AttributeType.Builder builder = HANDLE.typeBuilder("test", FLOAT); + assertThrows(IllegalArgumentException.class, () -> builder.op(Operation.OVERRIDE, FLOAT, (s, a) -> a)); + AttributeType built = builder.build(); + assertEquals(EnumSet.of(Operation.OVERRIDE), built.operations()); + builder.op(Operation.ADD, FLOAT, Float::sum); + assertEquals(EnumSet.of(Operation.OVERRIDE), built.operations()); + assertThrows(UnsupportedOperationException.class, () -> built.operations().add(Operation.ADD)); + assertThrows(DecodeException.class, () -> built.decodeArgument(Operation.ADD, 1, PLAIN)); + assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.ADD), builder.build().operations()); + assertEquals(3f, builder.build().apply(Operation.ADD, 1f, 2f), EPS); + } + + @Test + public void nestedLoads() throws DecodeException { + List seen = new ArrayList<>(); + DecodeContext recording = new DecodeContext() { + @Override + public V load(Type type, Object raw) throws DecodeException { + seen.add(raw); + return HANDLE.plainContext().load(type, raw); + } + + @Override + public Object resolve(Object raw) { + return raw; + } + }; + Map argument = map("value", 6, "alpha", 0.5); + TYPES.floatType().decodeArgument(Operation.ALPHA_BLEND, argument, recording); + TYPES.identifier("mypack").decode("mypack:thing", recording); + assertTrue(seen.contains(argument), seen.toString()); + assertTrue(seen.contains(6), seen.toString()); + assertTrue(seen.contains(0.5), seen.toString()); + assertTrue(seen.contains("mypack:thing"), seen.toString()); + } + + private static DecodeContext referencing(Map targets) { + return new DecodeContext() { + @Override + public V load(Type type, Object raw) throws DecodeException { + return HANDLE.plainContext().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 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 + public void resolveBeforeShape() throws DecodeException { + DecodeContext context = referencing(map( + "@alpha", map("value", "@two", "alpha", 0.5), + "@two", 2, + "@yes", true, + "@channels", List.of(1, 0, 0), + "@gray", map("brightness", 0.6, "factor", 0.75))); + + AttributeType floats = TYPES.floatType(); + assertEquals(1.5f, floats.apply(Operation.ALPHA_BLEND, 1f, floats.decodeArgument(Operation.ALPHA_BLEND, "@alpha", context)), EPS); + assertEquals(TriState.TRUE, TYPES.triState().decode("@yes", context)); + assertColor(1, 0, 0, 1, TYPES.rgbColor().decode("@channels", context)); + AttributeType rgb = TYPES.rgbColor(); + assertColor(0.385f, 0.135f, 0.135f, 1f, + rgb.apply(Operation.BLEND_TO_GRAY, new Color(1f, 0f, 0f, 1f), rgb.decodeArgument(Operation.BLEND_TO_GRAY, "@gray", context))); + } + + @Test + public void plainContext() throws DecodeException { + DecodeContext plain = HANDLE.plainContext(); + Map value = map("a", List.of("$meta.yml:b")); + assertSame(value, plain.resolve(value)); + assertEquals(3f, plain.load(Float.class, 3), EPS); + assertEquals(3.0, plain.load(Double.class, 3)); + assertEquals(4, plain.load(Integer.class, 4.0)); + assertEquals("a", plain.load(String.class, "a")); + assertEquals(true, plain.load(Boolean.class, true)); + assertEquals(List.of(1), plain.load(List.class, List.of(1))); + assertEquals(Map.of("a", 1), plain.load(Map.class, Map.of("a", 1))); + assertEquals("expected a number, got \"${1}\"", + assertThrows(DecodeException.class, () -> plain.load(Float.class, "${1}")).getMessage()); + assertThrows(DecodeException.class, () -> plain.load(String.class, 1)); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/EntryFormatTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/EntryFormatTest.java new file mode 100644 index 000000000..cfe1f3c94 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/EntryFormatTest.java @@ -0,0 +1,79 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +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.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.world.attribute.AttributeCodecRoundTripTest.Case; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + + +class EntryFormatTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + + private static Attribute attribute(Case c) { + return HANDLE.attributeBuilder(AttributeKey.parse("test:" + c.type().id()), c.type(), null).build(); + } + + private static void assertRoundTrip(Case c) throws DecodeException { + Attribute attribute = attribute(c); + Map> arguments = new LinkedHashMap<>(c.arguments()); + arguments.put(Operation.OVERRIDE, c.values()); + assertEquals(c.type().operations(), arguments.keySet(), c.type().id() + " samples every operation"); + for(Map.Entry> e : arguments.entrySet()) { + for(Object argument : e.getValue()) { + AttributeEntry entry = AttributeEntry.of(e.getKey(), argument); + Object encoded = HANDLE.encodeEntry(attribute, entry); + assertEquals(entry, HANDLE.decodeEntry(attribute, encoded, HANDLE.plainContext()), + c.type().id() + " " + e.getKey().getID() + " via " + encoded); + } + } + } + + @Test + void roundTrip() throws DecodeException { + for(Case c : AttributeCodecRoundTripTest.cases()) assertRoundTrip(c); + } + + @Test + void encodeForms() { + Attribute fog = HANDLE.attributeBuilder(AttributeKey.parse("test:fog"), HANDLE.types().rgbColor(), null).build(); + assertEquals("#102030", HANDLE.encodeEntry(fog, AttributeEntry.override(Color.rgb(0x102030)))); + Attribute fogEnd = HANDLE.attributeBuilder(AttributeKey.parse("test:fog_end"), HANDLE.types().floatType(), 0f) + .build(); + assertEquals(Map.of("modifier", "multiply", "argument", 0.85f), + HANDLE.encodeEntry(fogEnd, AttributeEntry.of(Operation.MULTIPLY, 0.85f))); + } + + @Test + void encodeNullOverride() { + Attribute colour = HANDLE.attributeBuilder(AttributeKey.parse("test:sky"), HANDLE.types().rgbColor(), null).build(); + Attribute number = HANDLE.attributeBuilder(AttributeKey.parse("test:height"), HANDLE.types().floatType(), null) + .build(); + for(Attribute attribute : List.of(colour, number)) { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, + () -> HANDLE.encodeEntry(attribute, AttributeEntry.override(null))); + assertEquals("a null override has no pack-format form", e.getMessage()); + } + } + + @Test + void decodeInvalidModifier() { + Attribute flag = HANDLE.attributeBuilder(AttributeKey.parse("test:flag"), HANDLE.types().booleanType(), false) + .build(); + DecodeException e = assertThrows(DecodeException.class, + () -> HANDLE.decodeEntry(flag, Map.of("modifier", "add", "argument", 1), HANDLE.plainContext())); + assertEquals("modifier add is not valid for test:flag", e.getMessage()); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/FixedArityResolveTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/FixedArityResolveTest.java new file mode 100644 index 000000000..5af6974c4 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/FixedArityResolveTest.java @@ -0,0 +1,67 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +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.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.value.Color; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +@SuppressWarnings("unchecked") +class FixedArityResolveTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final DecodeContext PLAIN = HANDLE.plainContext(); + + private static List> choices(AttributeType type, T override, Object... modifiers) throws DecodeException { + List> choices = new ArrayList<>(Arrays.asList(null, AttributeEntry.override(override))); + for(int i = 0; i < modifiers.length; i += 2) { + Operation op = (Operation) modifiers[i]; + choices.add(AttributeEntry.of(op, type.decodeArgument(op, modifiers[i + 1], PLAIN))); + } + return choices; + } + + private static T varargs(Attribute attribute, AttributeEntry... layers) { + return HANDLE.resolve(attribute, (AttributeEntry[]) layers); + } + + private static void assertSameLayering(Attribute attribute, List> choices) { + for(AttributeEntry a : choices) { + for(AttributeEntry b : choices) { + for(AttributeEntry c : choices) { + assertEquals(varargs(attribute, a, b, c), HANDLE.resolve(attribute, a, b, c)); + for(AttributeEntry d : choices) { + assertEquals(varargs(attribute, a, b, c, d), HANDLE.resolve(attribute, a, b, c, d), + () -> List.of(String.valueOf(a), String.valueOf(b), String.valueOf(c), String.valueOf(d)).toString()); + } + } + } + } + } + + @Test + void withDefault() throws DecodeException { + AttributeType type = HANDLE.types().floatType(); + Attribute attribute = HANDLE.attributeBuilder(AttributeKey.parse("test:float"), type, 1f).range(0, 10).build(); + assertSameLayering(attribute, choices(type, 4f, Operation.ADD, 3.0, Operation.MULTIPLY, 2.0)); + } + + @Test + void withoutDefault() throws DecodeException { + AttributeType type = HANDLE.types().rgbColor(); + Attribute attribute = HANDLE.attributeBuilder(AttributeKey.parse("test:color"), type, null).build(); + assertSameLayering(attribute, choices(type, Color.parseRgb("#102030"), Operation.ADD, "#010101")); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/ScheduleFormatTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/ScheduleFormatTest.java new file mode 100644 index 000000000..3832141c1 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/ScheduleFormatTest.java @@ -0,0 +1,416 @@ +package com.dfsek.terra.world.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.lang.reflect.Type; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.OptionalInt; +import java.util.Set; +import java.util.stream.Stream; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.StringIdentifiable; +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.AttributeLookup; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.AttributeTypes; +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.schedule.AttributeSchedule; +import com.dfsek.terra.api.world.attribute.schedule.Easing; +import com.dfsek.terra.api.world.attribute.schedule.Keyframe; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult.Problem; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleTrack; +import com.dfsek.terra.api.world.attribute.schedule.TimeMarker; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Named.named; +import static org.junit.jupiter.params.provider.Arguments.arguments; + + +class ScheduleFormatTest { + private static final RegistryKey ID = RegistryKey.parse("terra:test"); + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final AttributeTypes TYPES = HANDLE.types(); + private static final Map> ATTRIBUTES = new LinkedHashMap<>(); + private static final Attribute SUN_ANGLE = attribute("minecraft:visual/sun_angle", TYPES.angleDegrees(), 0f); + private static final Attribute MOON_PHASE = attribute("minecraft:visual/moon_phase", + TYPES.enumType("moon_phase", MoonPhase.class), MoonPhase.FULL_MOON); + private static final Attribute PATROL = attribute("minecraft:gameplay/can_pillager_patrol_spawn", TYPES.booleanType(), + true); + private static final Attribute STAR_BRIGHTNESS = HANDLE.attributeBuilder( + AttributeKey.parse("minecraft:visual/star_brightness"), TYPES.floatType(), 0f).range(0, 1).build(); + private static final AttributeLookup LOOKUP = ScheduleFormatTest::find; + private static final List ORDERED_TRACKS = List.of("minecraft:visual/water_fog_start_distance", + "minecraft:visual/sun_angle", "minecraft:visual/fog_start_distance", "minecraft:visual/star_angle", + "minecraft:visual/moon_angle", "minecraft:visual/fog_end_distance", "minecraft:visual/cloud_fog_end_distance", + "minecraft:visual/sky_fog_end_distance"); + private static final List ORDERED_MARKERS = List.of("terra:z", "terra:a", "terra:m", "terra:b", "terra:y", "terra:c", + "terra:x", "terra:d"); + + static { + ATTRIBUTES.put(STAR_BRIGHTNESS.key().toString(), STAR_BRIGHTNESS); + for(String id : ORDERED_TRACKS) { + if(!ATTRIBUTES.containsKey(id)) attribute(id, TYPES.floatType(), 0f); + } + } + + private static Attribute attribute(String key, AttributeType type, T defaultValue) { + Attribute attribute = HANDLE.attributeBuilder(AttributeKey.parse(key), type, defaultValue).build(); + ATTRIBUTES.put(key, attribute); + return attribute; + } + + private static Attribute find(String key) throws DecodeException { + Attribute attribute = ATTRIBUTES.get(key); + if(attribute == null) throw new DecodeException("unknown attribute"); + return attribute; + } + + private enum MoonPhase implements StringIdentifiable { + FULL_MOON("full_moon"), + WANING_GIBBOUS("waning_gibbous"); + + private final String id; + + MoonPhase(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } + } + + private static ScheduleDecodeResult read(Map raw) { + return HANDLE.decodeSchedule(ID, raw, LOOKUP, HANDLE.plainContext()); + } + + private static Map keyframe(int ticks, Object value) { + return Map.of("ticks", ticks, "value", value); + } + + private static Map schedule(Object period, Map tracks) { + Map raw = new LinkedHashMap<>(); + raw.put("clock", "minecraft:overworld"); + if(period != null) raw.put("period_ticks", period); + raw.put("tracks", tracks); + return raw; + } + + private static Map sunTrack(Object... frames) { + return Map.of("keyframes", List.of(frames)); + } + + private static Map easedTrack(Object ease, Object... frames) { + return Map.of("keyframes", List.of(frames), "ease", ease); + } + + private static void assertRejected(ScheduleDecodeResult r, String reasonPart) { + assertTrue(r.schedule().isEmpty(), "schedule should be skipped"); + assertTrue(r.droppedTracks().isEmpty(), r.droppedTracks().toString()); + Problem skipped = r.skipped().orElseThrow(); + assertTrue(skipped.reason().contains(reasonPart), skipped.reason()); + } + + private static void assertClean(ScheduleDecodeResult r) { + assertTrue(r.droppedTracks().isEmpty(), r.droppedTracks().toString()); + assertTrue(r.skipped().isEmpty(), r.skipped().toString()); + } + + private static DecodeContext expressions(Map values) { + return new DecodeContext() { + @Override + public V load(Type type, Object raw) throws DecodeException { + return HANDLE.plainContext().load(type, raw instanceof String s && values.containsKey(s) ? values.get(s) : raw); + } + + @Override + public Object resolve(Object raw) { + return raw; + } + }; + } + + private static final DecodeContext EXPRESSIONS = expressions( + Map.of("20 * 60 * 20", 24000.0, "1 / 10", 0.1, "6000 * 2", 12000.0, "3000 * 2", 6000)); + + private static Map earlyGameSchedule() { + return Map.of( + "clock", "minecraft:overworld", + "tracks", Map.of("minecraft:gameplay/can_pillager_patrol_spawn", Map.of( + "modifier", "and", + "keyframes", List.of(keyframe(0, false), keyframe(120000, true))))); + } + + private static Map dayStyle() { + Map raw = schedule(24000, Map.of("minecraft:visual/sun_angle", + sunTrack(keyframe(0, 270.0), keyframe(6000, 360.0), keyframe(6000, 0.0), keyframe(18000, 180.0)))); + raw.put("time_markers", Map.of( + "minecraft:noon", Map.of("ticks", 6000, "show_in_commands", true), + "minecraft:wake_up_from_sleep", 0)); + return raw; + } + + private static Map moonStyle() { + return schedule(192000, Map.of("minecraft:visual/moon_phase", + easedTrack("constant", keyframe(0, "full_moon"), keyframe(24000, "waning_gibbous")))); + } + + private static Map cubicBezier() { + return schedule(null, Map.of("minecraft:visual/sun_angle", + easedTrack(Map.of("cubic_bezier", List.of(0.25, 0.1, 1, 1.0)), keyframe(0, 0.0), keyframe(10, 90.0)))); + } + + private static Map keyframeAtPeriod() { + return schedule(100, Map.of("minecraft:visual/sun_angle", sunTrack(keyframe(0, 0.0), keyframe(100, 1.0)))); + } + + private static Map upperCaseClock() { + return Map.of("clock", "minecraft:Overworld", "tracks", Map.of()); + } + + private static Map ordered() { + Map tracks = new LinkedHashMap<>(); + for(String id : ORDERED_TRACKS) tracks.put(id, sunTrack(keyframe(0, 10.0))); + Map markers = new LinkedHashMap<>(); + for(int i = 0; i < ORDERED_MARKERS.size(); i++) markers.put(ORDERED_MARKERS.get(i), i * 100); + Map raw = schedule(24000, tracks); + raw.put("time_markers", markers); + return raw; + } + + private static Map expressionSchedule() { + Map raw = schedule("20 * 60 * 20", Map.of("minecraft:visual/sun_angle", + easedTrack(Map.of("cubic_bezier", List.of(0.25, "1 / 10", 0.25, 1)), keyframe(0, 270.0), + Map.of("ticks", "6000 * 2", "value", 0.0)))); + raw.put("time_markers", Map.of("minecraft:noon", Map.of("ticks", "3000 * 2"), "minecraft:dusk", "6000 * 2")); + return raw; + } + + @Test + void numberExpressions() { + ScheduleDecodeResult r = HANDLE.decodeSchedule(ID, expressionSchedule(), LOOKUP, EXPRESSIONS); + assertClean(r); + AttributeSchedule def = r.schedule().orElseThrow(); + assertEquals(24000, def.periodTicks().orElseThrow()); + assertEquals(new TimeMarker(6000, false), def.timeMarkers().get(RegistryKey.parse("minecraft:noon"))); + assertEquals(new TimeMarker(12000, false), def.timeMarkers().get(RegistryKey.parse("minecraft:dusk"))); + ScheduleTrack track = def.tracks().get(SUN_ANGLE); + assertEquals(12000, track.keyframes().get(1).ticks()); + assertEquals(new Easing.CubicBezier(0.25f, 0.1f, 0.25f, 1f), track.ease()); + } + + @Test + void integralDouble() { + ScheduleDecodeResult r = read(schedule(24000.0, Map.of("minecraft:visual/sun_angle", sunTrack(keyframe(0, 270.0))))); + assertClean(r); + assertEquals(24000, r.schedule().orElseThrow().periodTicks().orElseThrow()); + Map raw = schedule(24000, Map.of("minecraft:visual/sun_angle", sunTrack(Map.of("ticks", 6000.0, "value", 0.0)))); + raw.put("time_markers", Map.of("minecraft:noon", 6000L)); + AttributeSchedule def = read(raw).schedule().orElseThrow(); + assertEquals(6000, def.tracks().get(SUN_ANGLE).keyframes().getFirst().ticks()); + assertEquals(new TimeMarker(6000, false), def.timeMarkers().get(RegistryKey.parse("minecraft:noon"))); + } + + @Test + void decodesVanillaStyleSchedules() { + ScheduleDecodeResult early = read(earlyGameSchedule()); + assertClean(early); + AttributeSchedule def = early.schedule().orElseThrow(); + assertEquals(RegistryKey.parse("minecraft:overworld"), def.clock()); + assertTrue(def.periodTicks().isEmpty()); + ScheduleTrack patrol = def.tracks().get(PATROL); + assertEquals(Operation.AND, patrol.operation()); + assertEquals(new Easing.Named("linear"), patrol.ease()); + assertEquals(List.of(new Keyframe(0, false), new Keyframe(120000, true)), patrol.keyframes()); + + ScheduleDecodeResult day = read(dayStyle()); + assertClean(day); + def = day.schedule().orElseThrow(); + assertEquals(24000, def.periodTicks().orElseThrow()); + assertEquals(Operation.OVERRIDE, def.tracks().get(SUN_ANGLE).operation()); + assertEquals(4, def.tracks().get(SUN_ANGLE).keyframes().size()); + assertEquals(new TimeMarker(6000, true), def.timeMarkers().get(RegistryKey.parse("minecraft:noon"))); + assertEquals(new TimeMarker(0, false), def.timeMarkers().get(RegistryKey.parse("minecraft:wake_up_from_sleep"))); + + ScheduleDecodeResult moon = read(moonStyle()); + assertClean(moon); + ScheduleTrack phase = moon.schedule().orElseThrow().tracks().get(MOON_PHASE); + assertEquals(new Keyframe(24000, MoonPhase.WANING_GIBBOUS), phase.keyframes().get(1)); + assertEquals(new Easing.Named("constant"), phase.ease()); + + assertEquals(new Easing.CubicBezier(0.25f, 0.1f, 1f, 1f), read(cubicBezier()).schedule().orElseThrow().tracks().get(SUN_ANGLE).ease()); + assertEquals(RegistryKey.parse("minecraft:Overworld"), read(upperCaseClock()).schedule().orElseThrow().clock()); + } + + private static Map withMarkers(Map raw, Map markers) { + raw.put("time_markers", markers); + return raw; + } + + static Stream rejected() { + DecodeContext plain = HANDLE.plainContext(); + Map sun = Map.of("minecraft:visual/sun_angle", sunTrack(keyframe(0, 270.0))); + return Stream.of( + arguments(named("expression that is not an integer", schedule("5 / 2", sun)), expressions(Map.of("5 / 2", 2.5)), + "period_ticks must be an integer"), + arguments(named("fractional period", schedule(24000.5, sun)), plain, "period_ticks must be an integer"), + arguments(named("expression in a plain context", schedule("20 * 60 * 20", sun)), plain, "period_ticks must be an integer"), + arguments(named("non-positive period", schedule(0, Map.of())), plain, "period_ticks"), + arguments(named("unsorted keyframes", schedule(null, Map.of("minecraft:visual/sun_angle", + sunTrack(keyframe(10, 0.0), keyframe(5, 1.0))))), plain, "sorted"), + arguments(named("three keyframes on one tick", schedule(null, Map.of("minecraft:visual/sun_angle", + sunTrack(keyframe(5, 0.0), keyframe(5, 1.0), keyframe(5, 2.0))))), plain, "tick"), + arguments(named("no keyframes", schedule(null, Map.of("minecraft:visual/sun_angle", sunTrack()))), plain, "keyframes"), + arguments(named("keyframe beyond the period", schedule(100, Map.of("minecraft:visual/sun_angle", + sunTrack(keyframe(0, 0.0), keyframe(101, 1.0))))), plain, "period"), + arguments(named("marker equal to the period", withMarkers(schedule(100, Map.of()), Map.of("minecraft:noon", 100))), plain, + "period"), + arguments(named("bezier x out of range", schedule(null, Map.of("minecraft:visual/sun_angle", + easedTrack(Map.of("cubic_bezier", List.of(1.5, 0, 0.5, 1)), keyframe(0, 0.0), keyframe(10, 1.0))))), plain, + "cubic_bezier"), + arguments(named("unknown easing", schedule(null, Map.of("minecraft:visual/sun_angle", + easedTrack("wobbly", keyframe(0, 0.0), keyframe(10, 1.0))))), plain, "wobbly"), + arguments(named("missing clock", Map.of("tracks", Map.of())), plain, "clock"), + arguments(named("tag clock", Map.of("clock", "#minecraft:clocks", "tracks", Map.of())), plain, "clock must not be a tag"), + arguments(named("bare clock", Map.of("clock", "overworld", "tracks", Map.of())), plain, + "clock: a namespace is required, as in \"namespace:overworld\""), + arguments(named("bare time marker", withMarkers(schedule(24000, Map.of()), Map.of("noon", 6000))), plain, + "time marker key: a namespace is required, as in \"namespace:noon\"")); + } + + @ParameterizedTest + @MethodSource + void rejected(Map raw, DecodeContext context, String reasonPart) { + ScheduleDecodeResult r = HANDLE.decodeSchedule(ID, raw, LOOKUP, context); + assertRejected(r, reasonPart); + assertEquals("terra:test", r.skipped().orElseThrow().key()); + } + + static Stream droppedTrack() { + return Stream.of( + arguments(named("unknown attribute", sunTrack(keyframe(0, 0.0))), "minecraft:visual/not_real", "unknown attribute"), + arguments(named("bad keyframe value", sunTrack(keyframe(0, "not_a_phase"))), "minecraft:visual/moon_phase", + "unknown moon phase \"not_a_phase\", expected one of [full_moon, waning_gibbous]"), + arguments(named("modifier not valid for the type", Map.of("modifier", "add", "keyframes", List.of(keyframe(0, "full_moon")))), + "minecraft:visual/moon_phase", "modifier add is not valid for minecraft:visual/moon_phase"), + arguments(named("override out of range", sunTrack(keyframe(0, 5.0))), "minecraft:visual/star_brightness", + "value 5.0 is outside [0, 1]")); + } + + @ParameterizedTest + @MethodSource + void droppedTrack(Map track, String key, String reason) { + ScheduleDecodeResult r = read(schedule(null, Map.of(key, track, "minecraft:visual/sun_angle", sunTrack(keyframe(0, 0.0))))); + assertEquals(List.of(new Problem(key, reason)), r.droppedTracks()); + assertTrue(r.skipped().isEmpty()); + assertEquals(Set.of(SUN_ANGLE), r.schedule().orElseThrow().tracks().keySet()); + } + + @Test + void droppedTracksOnSkip() { + Map tracks = new LinkedHashMap<>(); + tracks.put("minecraft:visual/not_real", sunTrack(keyframe(0, 0.0))); + tracks.put("minecraft:visual/sun_angle", sunTrack(keyframe(0, 0.0), keyframe(200, 1.0))); + ScheduleDecodeResult r = read(schedule(100, tracks)); + assertTrue(r.schedule().isEmpty()); + assertEquals(List.of(new Problem("minecraft:visual/not_real", "unknown attribute")), r.droppedTracks()); + assertEquals(new Problem("terra:test", "keyframe ticks 200 must be within period_ticks 100"), r.skipped().orElseThrow()); + } + + @Test + void configOrder() { + ScheduleDecodeResult r = read(ordered()); + assertClean(r); + AttributeSchedule def = r.schedule().orElseThrow(); + assertEquals(ORDERED_TRACKS, def.tracks().keySet().stream().map(attribute -> attribute.getRegistryKey().toString()).toList()); + assertEquals(ORDERED_MARKERS, def.timeMarkers().keySet().stream().map(RegistryKey::toString).toList()); + } + + private static AttributeSchedule decode(Map raw, DecodeContext context) { + ScheduleDecodeResult r = HANDLE.decodeSchedule(ID, raw, LOOKUP, context); + assertClean(r); + return r.schedule().orElseThrow(); + } + + @Test + void roundTrip() { + Map> fixtures = new LinkedHashMap<>(); + fixtures.put("earlyGame", earlyGameSchedule()); + fixtures.put("dayStyle", dayStyle()); + fixtures.put("moonStyle", moonStyle()); + fixtures.put("cubicBezier", cubicBezier()); + fixtures.put("keyframeAtPeriod", keyframeAtPeriod()); + fixtures.put("upperCaseClock", upperCaseClock()); + fixtures.put("ordered", ordered()); + fixtures.forEach((name, raw) -> { + AttributeSchedule schedule = decode(raw, HANDLE.plainContext()); + Map encoded = HANDLE.encodeSchedule(schedule); + AttributeSchedule again = decode(encoded, HANDLE.plainContext()); + assertEquals(schedule, again, name + " via " + encoded); + assertEquals(List.copyOf(schedule.tracks().keySet()), List.copyOf(again.tracks().keySet()), name + " track order"); + assertEquals(List.copyOf(schedule.timeMarkers().keySet()), List.copyOf(again.timeMarkers().keySet()), + name + " marker order"); + }); + AttributeSchedule evaluated = decode(expressionSchedule(), EXPRESSIONS); + assertEquals(evaluated, decode(HANDLE.encodeSchedule(evaluated), HANDLE.plainContext())); + } + + @Test + void encodeOmitsDefaults() { + AttributeSchedule schedule = new AttributeSchedule(RegistryKey.parse("minecraft:overworld"), OptionalInt.empty(), + Map.of(SUN_ANGLE, new ScheduleTrack(Operation.OVERRIDE, List.of(new Keyframe(0, 270f)), new Easing.Named("linear"))), + Map.of(RegistryKey.parse("minecraft:noon"), new TimeMarker(6000, false))); + assertEquals(Map.of( + "clock", "minecraft:overworld", + "tracks", Map.of("minecraft:visual/sun_angle", Map.of("keyframes", List.of(Map.of("ticks", 0, "value", 270f)))), + "time_markers", Map.of("minecraft:noon", Map.of("ticks", 6000))), + HANDLE.encodeSchedule(schedule)); + AttributeSchedule empty = new AttributeSchedule(RegistryKey.parse("minecraft:overworld"), OptionalInt.empty(), Map.of(), Map.of()); + assertEquals(Map.of("clock", "minecraft:overworld"), HANDLE.encodeSchedule(empty)); + } + + @Test + void encodeNullKeyframe() { + AttributeSchedule schedule = new AttributeSchedule(RegistryKey.parse("mypack:day"), OptionalInt.empty(), + Map.of(SUN_ANGLE, new ScheduleTrack(Operation.OVERRIDE, List.of(new Keyframe(0, null)), new Easing.Named("linear"))), + Map.of()); + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> HANDLE.encodeSchedule(schedule)); + assertEquals("keyframe 0 of minecraft:visual/sun_angle: a null value has no pack-format form", e.getMessage()); + } + + @Test + void encodeNonDefaults() { + AttributeSchedule schedule = new AttributeSchedule(RegistryKey.parse("mypack:day"), OptionalInt.of(24000), + Map.of(SUN_ANGLE, new ScheduleTrack(Operation.ADD, List.of(new Keyframe(0, 1f), new Keyframe(10, 2f)), + new Easing.CubicBezier(0.25f, 0.1f, 1f, 1f)), + MOON_PHASE, new ScheduleTrack(Operation.OVERRIDE, List.of(new Keyframe(0, MoonPhase.WANING_GIBBOUS)), + new Easing.Named("constant"))), + Map.of(RegistryKey.parse("mypack:noon"), new TimeMarker(6000, true))); + Map encoded = HANDLE.encodeSchedule(schedule); + assertEquals("mypack:day", encoded.get("clock")); + assertEquals(24000, encoded.get("period_ticks")); + assertEquals(Map.of("mypack:noon", Map.of("ticks", 6000, "show_in_commands", true)), encoded.get("time_markers")); + Map tracks = (Map) encoded.get("tracks"); + assertEquals(Map.of( + "modifier", "add", + "ease", Map.of("cubic_bezier", List.of(0.25f, 0.1f, 1f, 1f)), + "keyframes", List.of(Map.of("ticks", 0, "value", 1f), Map.of("ticks", 10, "value", 2f))), + tracks.get("minecraft:visual/sun_angle")); + assertEquals(Map.of( + "ease", "constant", + "keyframes", List.of(Map.of("ticks", 0, "value", "waning_gibbous"))), + tracks.get("minecraft:visual/moon_phase")); + } +} diff --git a/platforms/cli/build.gradle.kts b/platforms/cli/build.gradle.kts index c28c25f17..caa5bb1f5 100644 --- a/platforms/cli/build.gradle.kts +++ b/platforms/cli/build.gradle.kts @@ -17,7 +17,9 @@ dependencies { shadedImplementation("ch.qos.logback", "logback-classic", Versions.CLI.logback) - + // Addon class loaders find minecraft-attributes on the test class path first; its entrypoint needs the manifest addon API. + testImplementation(project(":common:addons:minecraft-attributes")) + testImplementation(project(":common:addons:manifest-addon-loader")) } tasks.withType { diff --git a/platforms/cli/src/test/java/com/dfsek/terra/cli/AttributePackTest.java b/platforms/cli/src/test/java/com/dfsek/terra/cli/AttributePackTest.java new file mode 100644 index 000000000..a713a2d01 --- /dev/null +++ b/platforms/cli/src/test/java/com/dfsek/terra/cli/AttributePackTest.java @@ -0,0 +1,410 @@ +package com.dfsek.terra.cli; + +import org.jetbrains.annotations.Nullable; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +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.lang.management.ManagementFactory; +import java.lang.reflect.Method; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.OptionalDouble; +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.MinecraftAttributes; +import com.dfsek.terra.addons.attribute.minecraft.Music; +import com.dfsek.terra.addons.attribute.minecraft.SoundRef; +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent; +import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.properties.Properties; +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.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.attribute.schedule.ScheduleTrack; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.config.pack.ConfigPackImpl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class AttributePackTest { + private static volatile AttributeParents parents = AttributeParents.NONE; + + private static final AttributeParents FORWARDING = new AttributeParents() { + @Override + public @Nullable AttributeEntry biomeOrNull(Biome biome, Attribute attribute) { + return parents.biomeOrNull(biome, attribute); + } + + @Override + public @Nullable AttributeEntry packOrNull(PackAttributes pack, Attribute attribute) { + return parents.packOrNull(pack, attribute); + } + }; + + private static CLIPlatform platform; + private static AttributeHandle handle; + private static ConfigPack pack; + + @BeforeAll + static void setUp() throws Exception { + platform = new CLIPlatform() { + @Override + public AttributeParents getAttributeParents() { + return FORWARDING; + } + }; + platform.getEventManager().callEvent(new PlatformInitializationEvent()); + handle = platform.getAttributeHandle(); + pack = load(); + } + + @AfterEach + void resetParents() { + parents = AttributeParents.NONE; + } + + private static Path fixture() throws URISyntaxException { + return Path.of(AttributePackTest.class.getResource("/packs/attribute-test/pack.yml").toURI()).getParent(); + } + + private static ConfigPack load() throws Exception { + return new ConfigPackImpl(fixture(), platform); + } + + private static Biome biome(ConfigPack pack, String id) { + return pack.getRegistry(Biome.class).getByID(id).orElseThrow(() -> new AssertionError("No biome " + id)); + } + + private static PackAttributes packAttributes(ConfigPack pack) { + return handle.pack(pack).orElseThrow(() -> new AssertionError("No PackAttributes on " + pack.getID())); + } + + private static AttributeMap biomeEntries(ConfigPack pack, String id) { + return packAttributes(pack).biomeEntries(biome(pack, id)); + } + + private static Registry> attributes(ConfigPack pack) { + return pack.getRegistry(Attribute.REGISTRY_TYPE); + } + + private static Attribute attribute(AttributeKey key) { + return key.lookup(attributes(pack)).orElseThrow(() -> new AssertionError("No attribute " + key)); + } + + @SuppressWarnings("unchecked") + private static List warnings(PackAttributes attributes) throws ReflectiveOperationException { + return (List) attributes.getClass().getMethod("warnings").invoke(attributes); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static List biomeWarnings(String biome) throws ReflectiveOperationException { + Class type = packAttributes(pack).getClass().getClassLoader() + .loadClass("com.dfsek.terra.addons.attribute.BiomeAttributeEntries"); + PropertyKey key = Context.create((Class) type.asSubclass(Properties.class)); + Object entries = biome(pack, biome).getContext().get(key); + Method warnings = type.getDeclaredMethod("warnings"); + warnings.setAccessible(true); + return (List) warnings.invoke(entries); + } + + private static T declared(String biome, AttributeKey key) { + AttributeEntry entry = biomeEntries(pack, biome).get(key).orElseThrow(() -> new AssertionError(biome + " has no " + key)); + assertEquals(Operation.OVERRIDE, entry.operation()); + @SuppressWarnings("unchecked") + T value = (T) entry.argument(); + return value; + } + + private static AttributeMap overrides(Object... keysAndValues) { + AttributeMap.Builder builder = AttributeMap.builder(); + for(int i = 0; i < keysAndValues.length; i += 2) put(builder, (AttributeKey) keysAndValues[i], keysAndValues[i + 1]); + return builder.build(); + } + + @SuppressWarnings("unchecked") + private static void put(AttributeMap.Builder builder, AttributeKey key, Object value) { + builder.put(key, AttributeEntry.override((T) value)); + } + + private static Stream declaredEntries() { + Color child = Color.parseRgb("#a0b0c0"); + Color base = Color.parseRgb("#405060"); + Color white = Color.parseRgb("#ffffff"); + Color shared = Color.parseRgb("#0a0b0c"); + return Stream.of( + Arguments.of("PLAIN", overrides()), + Arguments.of("CHILD", overrides(MinecraftAttributes.VISUAL_FOG_COLOR, child, MinecraftAttributes.VISUAL_SKY_COLOR, base, + MinecraftAttributes.BIOME_TEMPERATURE, 0.8f)), + Arguments.of("NULLED", overrides(MinecraftAttributes.VISUAL_FOG_COLOR, child, MinecraftAttributes.BIOME_TEMPERATURE, 0.8f)), + Arguments.of("META", overrides(MinecraftAttributes.VISUAL_FOG_COLOR, white, MinecraftAttributes.VISUAL_SKY_COLOR, shared, + MinecraftAttributes.BIOME_DOWNFALL, 0.25f)), + Arguments.of("META_CHILD", overrides(MinecraftAttributes.VISUAL_FOG_COLOR, white, MinecraftAttributes.VISUAL_SKY_COLOR, + shared, MinecraftAttributes.BIOME_DOWNFALL, 0.75f, MinecraftAttributes.BIOME_WATER_COLOR, + Color.parseRgb("#112233")))); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("declaredEntries") + void declaredEntriesFollowInheritanceAndMeta(String biome, AttributeMap expected) throws ReflectiveOperationException { + assertEquals(expected, biomeEntries(pack, biome)); + assertEquals(List.of(), biomeWarnings(biome)); + } + + @Test + void metaInsideValues() throws ReflectiveOperationException { + Music music = declared("EXPR", MinecraftAttributes.AUDIO_BACKGROUND_MUSIC).defaultMusic().orElseThrow(); + assertEquals(RegistryKey.parse("minecraft:music.game"), music.sound().id()); + assertEquals(12000, music.minDelay()); + assertEquals(24000, music.maxDelay()); + + AttributeEntry fog = biomeEntries(pack, "EXPR").get(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE).orElseThrow(); + assertEquals(Operation.MULTIPLY, fog.operation()); + assertEquals(0.5f, fog.argument()); + assertEquals(48f, packAttributes(pack).resolve(attribute(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE), + biome(pack, "EXPR"))); + + AmbientSounds sounds = declared("EXPR", MinecraftAttributes.AUDIO_AMBIENT_SOUNDS); + assertEquals(RegistryKey.parse("minecraft:ambient.cave"), sounds.loop().orElseThrow().id()); + AmbientSounds.Mood mood = sounds.mood().orElseThrow(); + assertEquals(RegistryKey.parse("minecraft:ambient.cave"), mood.sound().id()); + assertEquals(6000, mood.tickDelay()); + assertEquals(8, mood.blockSearchExtent()); + assertEquals(2.0, mood.offset()); + assertEquals(List.of( + new AmbientSounds.Additions(new SoundRef(RegistryKey.parse("minecraft:ambient.crimson_forest.additions"), + OptionalDouble.empty()), 0.0111), + new AmbientSounds.Additions(new SoundRef(RegistryKey.parse("minecraft:ambient.basalt_deltas.additions"), + OptionalDouble.empty()), 0.5)), sounds.additions()); + + AmbientParticle particle = declared("EXPR", MinecraftAttributes.VISUAL_AMBIENT_PARTICLES).get(0); + assertEquals(0.025f, particle.probability(), 1e-6f); + Map body = (Map) particle.particle().value(); + assertEquals(Map.of("type", "minecraft:dust", "color", List.of(1.0, 0.0, 0.0), "scale", 1.0), body); + + assertEquals(List.of(), biomeWarnings("EXPR")); + } + + @Test + void chainedReferenceResolvesOnce() throws ReflectiveOperationException { + assertTrue(biomeEntries(pack, "CHAIN").isEmpty()); + List warnings = biomeWarnings("CHAIN"); + assertEquals(2, warnings.size(), warnings.toString()); + for(String key : List.of("minecraft:visual/sky_color", "minecraft:visual/fog_color")) { + String warning = warnings.stream().filter(w -> w.contains("\"" + key + "\"")).findFirst() + .orElseThrow(() -> new AssertionError(warnings.toString())); + assertTrue(warning.contains("got \"$meta.yml:sky-hex\""), warning); + } + } + + @Test + void tectonicErrorBecomesWarning() throws ReflectiveOperationException { + assertEquals(overrides(MinecraftAttributes.VISUAL_FOG_COLOR, Color.parseRgb("#123456")), biomeEntries(pack, "EXPR_BAD")); + + List warnings = biomeWarnings("EXPR_BAD"); + assertEquals(2, warnings.size(), warnings.toString()); + String missingKey = warnings.stream().filter(w -> w.contains("\"minecraft:visual/fog_start_distance\"")).findFirst() + .orElseThrow(() -> new AssertionError(warnings.toString())); + assertTrue(missingKey.contains("No such key no-such-key"), missingKey); + String malformed = warnings.stream().filter(w -> w.contains("\"minecraft:visual/sky_fog_end_distance\"")).findFirst() + .orElseThrow(() -> new AssertionError(warnings.toString())); + assertTrue(malformed.contains("\"EXPR_BAD\""), malformed); + assertTrue(malformed.contains("meta reference \"2 * 6000\" must have the form file:key"), malformed); + assertFalse(malformed.contains("java."), malformed); + assertFalse(malformed.contains("Exception"), malformed); + } + + @Test + void badEntryIsSkippedWithWarning() throws ReflectiveOperationException { + assertEquals(overrides(MinecraftAttributes.VISUAL_FOG_COLOR, Color.parseRgb("#00ff00")), biomeEntries(pack, "BAD")); + assertEquals(List.of("Pack \"ATTRIBUTE_TEST\", config \"BAD\": attribute \"minecraft:visual/sky_color\" skipped: " + + "expected a color like \"#rrggbb\", got \"not a colour\""), biomeWarnings("BAD")); + } + + @Test + void packLevelFields() throws ReflectiveOperationException { + PackAttributes attributes = packAttributes(pack); + assertEquals(overrides(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE, 96f, MinecraftAttributes.GAMEPLAY_FAST_LAVA, true), + attributes.entries()); + assertEquals(true, attributes.resolvePack(attribute(MinecraftAttributes.GAMEPLAY_FAST_LAVA))); + assertEquals(Map.of("vanilla", RegistryKey.parse("minecraft:overworld"), + "vanilla-generation", RegistryKey.parse("minecraft:overworld")), attributes.parents()); + assertEquals(List.of(Either.right(TagKey.parse("#minecraft:in_overworld"))), attributes.scheduleRefs()); + assertEquals(List.of(), warnings(attributes)); + } + + @Test + void scheduleDefinitionLoads() { + PackAttributes attributes = packAttributes(pack); + assertEquals(Set.of(RegistryKey.parse("terra:test_cycle")), attributes.scheduleDefinitions().keySet()); + AttributeSchedule definition = attributes.scheduleDefinitions().get(RegistryKey.parse("terra:test_cycle")); + assertEquals(RegistryKey.parse("minecraft:overworld"), definition.clock()); + assertEquals(24000, definition.periodTicks().orElseThrow()); + ScheduleTrack track = definition.tracks().get(attribute(MinecraftAttributes.VISUAL_SKY_COLOR)); + assertEquals(Operation.OVERRIDE, track.operation()); + assertEquals(2, track.keyframes().size()); + assertEquals(Color.parseRgb("#000000"), track.keyframes().get(0).argument()); + assertEquals(12000, track.keyframes().get(1).ticks()); + assertEquals(Color.parseRgb("#ffffff"), track.keyframes().get(1).argument()); + } + + @Test + void resolveWithoutParents() { + PackAttributes attributes = packAttributes(pack); + Biome plain = biome(pack, "PLAIN"); + Attribute precipitation = attribute(MinecraftAttributes.BIOME_HAS_PRECIPITATION); + assertNull(attributes.biomeEntryOrNull(precipitation, plain)); + assertEquals(precipitation.defaultValue(), attributes.resolve(precipitation, plain)); + Attribute temperature = attribute(MinecraftAttributes.BIOME_TEMPERATURE); + assertNull(attributes.biomeEntryOrNull(temperature, plain)); + assertEquals(0.5f, attributes.resolve(temperature, plain)); + Attribute sky = attribute(MinecraftAttributes.VISUAL_SKY_COLOR); + assertNull(attributes.biomeEntryOrNull(sky, biome(pack, "NULLED"))); + assertEquals(sky.defaultValue(), attributes.resolve(sky, biome(pack, "NULLED"))); + + assertEquals(81.6f, attributes.resolve(attribute(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE), biome(pack, "FOGGY")), + 1e-4f); + } + + @Test + void layersApplyInOrder() { + PackAttributes attributes = packAttributes(pack); + Biome child = biome(pack, "CHILD"); + parents = new AttributeParents() { + @Override + @SuppressWarnings("unchecked") + public @Nullable AttributeEntry biomeOrNull(Biome biome, Attribute attribute) { + if(biome != child) return null; + AttributeKey key = attribute.key(); + if(key == MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE) return (AttributeEntry) AttributeEntry.override(50f); + if(key == MinecraftAttributes.VISUAL_FOG_COLOR) return (AttributeEntry) AttributeEntry.override(Color.rgb(0x111111)); + return null; + } + + @Override + @SuppressWarnings("unchecked") + public @Nullable AttributeEntry packOrNull(PackAttributes pack, Attribute attribute) { + assertEquals(RegistryKey.parse("minecraft:overworld"), pack.parents().get("vanilla")); + AttributeKey key = attribute.key(); + if(key == MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE) return (AttributeEntry) AttributeEntry.override(40f); + if(key == MinecraftAttributes.VISUAL_SKY_FOG_END_DISTANCE) return (AttributeEntry) AttributeEntry.override(30f); + return null; + } + }; + Attribute waterFogEnd = attribute(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE); + Attribute skyFogEnd = attribute(MinecraftAttributes.VISUAL_SKY_FOG_END_DISTANCE); + assertEquals(50f, attributes.resolve(waterFogEnd, child)); + assertEquals(Color.parseRgb("#a0b0c0"), attributes.resolve(attribute(MinecraftAttributes.VISUAL_FOG_COLOR), child)); + assertEquals(30f, attributes.resolve(skyFogEnd, biome(pack, "PLAIN"))); + assertEquals(96f, attributes.resolve(waterFogEnd, biome(pack, "PLAIN"))); + assertEquals(96f, attributes.resolvePack(waterFogEnd)); + assertEquals(30f, attributes.resolvePack(skyFogEnd)); + } + + @Test + void columnsAreIdenticalAcrossLoads() throws Exception { + Map, AttributeEntry>> first = null; + for(int i = 0; i < 20; i++) { + ConfigPack loaded = load(); + Map, AttributeEntry>> columns = columns(loaded); + assertFalse(columns.get("CHILD").isEmpty()); + if(first == null) first = columns; + else assertEquals(first, columns, "Load " + i + " differs"); + } + } + + private static Map, AttributeEntry>> columns(ConfigPack loaded) { + PackAttributes attributes = packAttributes(loaded); + Map, AttributeEntry>> columns = new HashMap<>(); + loaded.getRegistry(Biome.class).forEach((key, biome) -> { + Map, AttributeEntry> row = new HashMap<>(); + AttributeMap declared = attributes.biomeEntries(biome); + for(Attribute attribute : attributes(loaded).entries()) { + AttributeEntry entry = attributes.biomeEntryOrNull(attribute, biome); + assertEquals(declared.get(attribute.key()).orElse(null), entry, biome.getID() + " " + attribute.key()); + if(entry != null) row.put(attribute.key(), entry); + } + assertEquals(declared.keys(), row.keySet(), biome.getID()); + columns.put(biome.getID(), row); + }); + return columns; + } + + @Test + void resolveAllocatesNothing() { + PackAttributes attributes = packAttributes(pack); + Biome child = biome(pack, "CHILD"); + Biome plain = biome(pack, "PLAIN"); + Attribute fogColor = attribute(MinecraftAttributes.VISUAL_FOG_COLOR); + Attribute precipitation = attribute(MinecraftAttributes.BIOME_HAS_PRECIPITATION); + Attribute fastLava = attribute(MinecraftAttributes.GAMEPLAY_FAST_LAVA); + com.sun.management.ThreadMXBean threads = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean(); + long thread = Thread.currentThread().threadId(); + + int sink = 0; + for(int i = 0; i < 100_000; i++) sink += reads(attributes, child, plain, fogColor, precipitation, fastLava); + long before = threads.getThreadAllocatedBytes(thread); + for(int i = 0; i < 10_000; i++) sink += reads(attributes, child, plain, fogColor, precipitation, fastLava); + long allocated = threads.getThreadAllocatedBytes(thread) - before; + + assertTrue(sink != 0); + assertTrue(allocated < 1024, allocated + " bytes allocated"); + } + + private static int reads(PackAttributes attributes, Biome child, Biome plain, Attribute fogColor, + Attribute precipitation, Attribute fastLava) { + int hash = System.identityHashCode(attributes.resolve(fogColor, child)); + hash += attributes.resolve(precipitation, plain) ? 1 : 2; + hash += attributes.resolvePack(fastLava) ? 1 : 2; + hash += attributes.biomeEntryOrNull(fogColor, child) == null ? 0 : 1; + return hash; + } + + @Test + void scheduleIdsAreChecked() throws Exception { + PackAttributes attributes = packAttributes(new ConfigPackImpl(scheduleFixture(), platform)); + assertEquals(List.of(Either.right(TagKey.parse("#minecraft:in_overworld"))), attributes.scheduleRefs()); + assertEquals(Set.of(RegistryKey.parse("mypack:seasons"), RegistryKey.parse("mypack:dropping")), + attributes.scheduleDefinitions().keySet()); + List warnings = warnings(attributes); + assertEquals(List.of( + "Pack \"SCHEDULE_TEST\": schedule \"seasons\" skipped: schedule IDs must include a namespace, e.g. \"mypack:seasons\"", + "Pack \"SCHEDULE_TEST\": schedule \"#mypack:tagged\" skipped: schedule IDs must not be tags"), + warnings.stream().filter(w -> w.contains("skipped: schedule IDs")).toList()); + assertEquals(4, warnings.size(), warnings.toString()); + assertTrue(warnings.contains("Pack \"SCHEDULE_TEST\": schedule \"mypack:dropping\" track \"minecraft:visual/moon_phase\" " + + "dropped: modifier add is not valid for minecraft:visual/moon_phase"), warnings.toString()); + assertTrue(warnings.stream().anyMatch(w -> w.startsWith("Pack \"SCHEDULE_TEST\": schedule \"mypack:not valid\" skipped: ")), + warnings.toString()); + } + + private static Path scheduleFixture() throws URISyntaxException { + return Path.of(AttributePackTest.class.getResource("/packs/schedule-test/pack.yml").toURI()).getParent(); + } +} diff --git a/platforms/cli/src/test/java/com/dfsek/terra/cli/FeatureStagePackTest.java b/platforms/cli/src/test/java/com/dfsek/terra/cli/FeatureStagePackTest.java new file mode 100644 index 000000000..66900af1b --- /dev/null +++ b/platforms/cli/src/test/java/com/dfsek/terra/cli/FeatureStagePackTest.java @@ -0,0 +1,56 @@ +package com.dfsek.terra.cli; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent; +import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.properties.Properties; +import com.dfsek.terra.api.properties.PropertyKey; +import com.dfsek.terra.api.registry.key.StringIdentifiable; +import com.dfsek.terra.api.structure.feature.Feature; +import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.chunk.generation.stage.GenerationStage; +import com.dfsek.terra.config.pack.ConfigPackImpl; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +class FeatureStagePackTest { + private static ConfigPack pack; + + @BeforeAll + static void setUp() throws Exception { + CLIPlatform platform = new CLIPlatform(); + platform.getEventManager().callEvent(new PlatformInitializationEvent()); + Path fixture = Path.of(FeatureStagePackTest.class.getResource("/packs/feature-stage-test/pack.yml").toURI()).getParent(); + pack = new ConfigPackImpl(fixture, platform); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static Map> featuresByStage(Biome biome) throws ReflectiveOperationException { + GenerationStage stage = pack.getStages().getFirst(); + Class biomeFeatures = stage.getClass().getClassLoader() + .loadClass("com.dfsek.terra.addons.generation.feature.config.BiomeFeatures"); + PropertyKey key = Context.create((Class) biomeFeatures.asSubclass(Properties.class)); + Object properties = biome.getContext().get(key); + Map> features = (Map>) biomeFeatures.getMethod("getFeatures").invoke(properties); + Map> byId = new HashMap<>(); + features.forEach((s, list) -> byId.put(((StringIdentifiable) s).getID(), list.stream().map(Feature::getID).toList())); + return byId; + } + + @Test + void dottedStageIdReadsNestedPath() throws ReflectiveOperationException { + Biome plain = pack.getRegistry(Biome.class).getByID("PLAIN").orElseThrow(); + Map> features = featuresByStage(plain); + assertEquals(List.of("ROCK"), features.get("nested.stage")); + assertEquals(List.of("ROCK"), features.get("flat")); + } +} diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/bad.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/bad.yml new file mode 100644 index 000000000..65f922c2d --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/bad.yml @@ -0,0 +1,7 @@ +id: BAD +type: BIOME +extends: GROUND + +attributes: + minecraft:visual/fog_color: "#00ff00" + minecraft:visual/sky_color: "not a colour" diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/base.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/base.yml new file mode 100644 index 000000000..ef1ca037a --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/base.yml @@ -0,0 +1,9 @@ +id: BASE +type: BIOME +abstract: true +extends: GROUND + +attributes: + minecraft:visual/fog_color: "#102030" + minecraft:visual/sky_color: "#405060" + terra:biome/temperature: 0.8 diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/chain.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/chain.yml new file mode 100644 index 000000000..24c2b30e5 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/chain.yml @@ -0,0 +1,11 @@ +# A reference to a reference is followed once, at the top level and nested alike, as for a @Meta String field: both entries +# get the literal "$meta.yml:sky-hex", which is not a colour, and are skipped with a warning. +id: CHAIN +type: BIOME +extends: GROUND + +attributes: + minecraft:visual/sky_color: "$meta.yml:chained-color" + minecraft:visual/fog_color: + modifier: override + argument: "$meta.yml:chained-color" diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/child.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/child.yml new file mode 100644 index 000000000..0fab86440 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/child.yml @@ -0,0 +1,6 @@ +id: CHILD +type: BIOME +extends: BASE + +attributes: + minecraft:visual/fog_color: "#a0b0c0" diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/expr.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/expr.yml new file mode 100644 index 000000000..276292c84 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/expr.yml @@ -0,0 +1,31 @@ +# Meta features inside attribute values: number expressions, "${file:key}" interpolation, "$file:key" references and "<<" includes +# at every depth of a value, including a modifier argument and an opaque particle body. +id: EXPR +type: BIOME +extends: GROUND + +attributes: + minecraft:audio/background_music: + default: + sound: minecraft:music.game + min_delay: "2 * 6000" + max_delay: "${meta.yml:music-delay} * 4" + minecraft:visual/water_fog_end_distance: + modifier: multiply + argument: "$meta.yml:fog-scale" + minecraft:audio/ambient_sounds: + loop: "$meta.yml:cave-loop" + mood: + "<<": + - meta.yml:cave-mood + tick_delay: "3000 * 2" + additions: + - "<< meta.yml:cave-additions" + - sound: minecraft:ambient.basalt_deltas.additions + tick_chance: 0.5 + minecraft:visual/ambient_particles: + - particle: + "<<": + - meta.yml:particle-options + type: "minecraft:${meta.yml:particle-name}" + probability: "1 / 40" diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/expr_bad.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/expr_bad.yml new file mode 100644 index 000000000..37846ba99 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/expr_bad.yml @@ -0,0 +1,11 @@ +# Config preprocessing errors inside attribute values: each warns once for its entry, and the other entries still load. +id: EXPR_BAD +type: BIOME +extends: GROUND + +attributes: + minecraft:visual/fog_color: "#123456" + minecraft:visual/fog_start_distance: "${meta.yml:no-such-key} * 2" + minecraft:visual/sky_fog_end_distance: + modifier: add + argument: "${2 * 6000}" diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/foggy.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/foggy.yml new file mode 100644 index 000000000..643a35e04 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/foggy.yml @@ -0,0 +1,8 @@ +id: FOGGY +type: BIOME +extends: GROUND + +attributes: + minecraft:visual/water_fog_end_distance: + modifier: multiply + argument: 0.85 diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/ground.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/ground.yml new file mode 100644 index 000000000..fe9379f24 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/ground.yml @@ -0,0 +1,14 @@ +# Terrain and palette shared by every fixture biome, kept apart from BASE so that only BASE's children inherit its attributes. +id: GROUND +type: BIOME +abstract: true + +vanilla: minecraft:plains + +terrain: + sampler: + type: CONSTANT + value: 0 + +palette: + - BLOCK:minecraft:stone: 319 diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_child.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_child.yml new file mode 100644 index 000000000..8406b5755 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_child.yml @@ -0,0 +1,8 @@ +# Extends META, so META's meta include is expanded while it is an inherited layer. The water colour is a "$file:key" meta value. +id: META_CHILD +type: BIOME +extends: META + +attributes: + terra:biome/downfall: 0.75 + terra:biome/water_color: $meta.yml:shared-water-color diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_include.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_include.yml new file mode 100644 index 000000000..a6f63d6ef --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_include.yml @@ -0,0 +1,8 @@ +id: META +type: BIOME +extends: GROUND + +attributes: + "<<": + - meta.yml:shared-attributes + minecraft:visual/fog_color: "#ffffff" diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/nulled.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/nulled.yml new file mode 100644 index 000000000..fe8457fc9 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/nulled.yml @@ -0,0 +1,6 @@ +id: NULLED +type: BIOME +extends: CHILD + +attributes: + minecraft:visual/sky_color: null diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/plain.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/plain.yml new file mode 100644 index 000000000..aa1136d6f --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/plain.yml @@ -0,0 +1,3 @@ +id: PLAIN +type: BIOME +extends: GROUND diff --git a/platforms/cli/src/test/resources/packs/attribute-test/meta.yml b/platforms/cli/src/test/resources/packs/attribute-test/meta.yml new file mode 100644 index 000000000..376ba4365 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/meta.yml @@ -0,0 +1,22 @@ +shared-attributes: + minecraft:visual/fog_color: "#010203" + minecraft:visual/sky_color: "#0a0b0c" + terra:biome/downfall: 0.25 +shared-water-color: "#112233" +music-delay: 6000 +fog-scale: 0.5 +cave-loop: minecraft:ambient.cave +cave-mood: + sound: minecraft:ambient.cave + block_search_extent: 8 + offset: 2.0 +cave-additions: + - sound: minecraft:ambient.crimson_forest.additions + tick_chance: 0.0111 +particle-name: dust +particle-options: + color: [1.0, 0.0, 0.0] + scale: 1.0 +night-sky: "#000000" +chained-color: "$meta.yml:sky-hex" +sky-hex: "#0a0b0c" diff --git a/platforms/cli/src/test/resources/packs/attribute-test/pack.yml b/platforms/cli/src/test/resources/packs/attribute-test/pack.yml new file mode 100644 index 000000000..9008b1946 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/pack.yml @@ -0,0 +1,43 @@ +id: ATTRIBUTE_TEST +version: 1.0.0 +author: Terra contributors + +generator: NOISE_3D + +vanilla: minecraft:overworld +vanilla-generation: minecraft:overworld + +addons: + biome-provider-single: "1.+" + chunk-generator-noise-3d: "1.+" + config-attributes: "1.+" + config-biome: "1.+" + config-noise-function: "1.+" + config-palette: "1.+" + language-yaml: "1.+" + minecraft-attributes: "1.+" + palette-block-shortcut: "1.+" + +biomes: + type: SINGLE + biome: PLAIN + +attributes: + minecraft:visual/water_fog_end_distance: 96 + minecraft:gameplay/fast_lava: true + minecraft:visual/fog_color: null + +schedules: + - "#minecraft:in_overworld" + +schedule-definitions: + terra:test_cycle: + clock: minecraft:overworld + period_ticks: "20 * 60 * 20" + tracks: + minecraft:visual/sky_color: + keyframes: + - ticks: 0 + value: "$meta.yml:night-sky" + - ticks: "6000 * 2" + value: "#ffffff" diff --git a/platforms/cli/src/test/resources/packs/feature-stage-test/biomes/plain.yml b/platforms/cli/src/test/resources/packs/feature-stage-test/biomes/plain.yml new file mode 100644 index 000000000..afe5ab7ed --- /dev/null +++ b/platforms/cli/src/test/resources/packs/feature-stage-test/biomes/plain.yml @@ -0,0 +1,19 @@ +id: PLAIN +type: BIOME + +vanilla: minecraft:plains + +terrain: + sampler: + type: CONSTANT + value: 0 + +palette: + - BLOCK:minecraft:stone: 319 + +features: + nested: + stage: + - ROCK + flat: + - ROCK diff --git a/platforms/cli/src/test/resources/packs/feature-stage-test/features/rock.yml b/platforms/cli/src/test/resources/packs/feature-stage-test/features/rock.yml new file mode 100644 index 000000000..a9d7acc6c --- /dev/null +++ b/platforms/cli/src/test/resources/packs/feature-stage-test/features/rock.yml @@ -0,0 +1,15 @@ +id: ROCK +type: FEATURE + +distributor: + type: "NO" + +locator: + type: SURFACE + range: 0 + +structures: + distribution: + type: CONSTANT + value: 0 + structures: BLOCK:minecraft:stone diff --git a/platforms/cli/src/test/resources/packs/feature-stage-test/pack.yml b/platforms/cli/src/test/resources/packs/feature-stage-test/pack.yml new file mode 100644 index 000000000..2a44f9495 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/feature-stage-test/pack.yml @@ -0,0 +1,30 @@ +id: FEATURE_STAGE_TEST +version: 1.0.0 +author: Terra contributors + +generator: NOISE_3D + +addons: + biome-provider-single: "1.+" + chunk-generator-noise-3d: "1.+" + config-biome: "1.+" + config-distributors: "1.+" + config-feature: "1.+" + config-locators: "1.+" + config-noise-function: "1.+" + config-palette: "1.+" + generation-stage-feature: "1.+" + language-yaml: "1.+" + palette-block-shortcut: "1.+" + structure-block-shortcut: "1.+" + +biomes: + type: SINGLE + biome: PLAIN + +# A dotted stage ID reads a nested path in biome configs: "nested.stage" reads features.nested.stage. +stages: + - id: nested.stage + type: FEATURE + - id: flat + type: FEATURE diff --git a/platforms/cli/src/test/resources/packs/schedule-test/biomes/plain.yml b/platforms/cli/src/test/resources/packs/schedule-test/biomes/plain.yml new file mode 100644 index 000000000..0693ad28f --- /dev/null +++ b/platforms/cli/src/test/resources/packs/schedule-test/biomes/plain.yml @@ -0,0 +1,12 @@ +id: PLAIN +type: BIOME + +vanilla: minecraft:plains + +terrain: + sampler: + type: CONSTANT + value: 0 + +palette: + - BLOCK:minecraft:stone: 319 diff --git a/platforms/cli/src/test/resources/packs/schedule-test/pack.yml b/platforms/cli/src/test/resources/packs/schedule-test/pack.yml new file mode 100644 index 000000000..1bcf8f2b7 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/schedule-test/pack.yml @@ -0,0 +1,49 @@ +id: SCHEDULE_TEST +version: 1.0.0 +author: Terra contributors + +generator: NOISE_3D + +vanilla: minecraft:overworld +vanilla-generation: minecraft:overworld + +addons: + biome-provider-single: "1.+" + chunk-generator-noise-3d: "1.+" + config-attributes: "1.+" + config-biome: "1.+" + config-noise-function: "1.+" + config-palette: "1.+" + language-yaml: "1.+" + minecraft-attributes: "1.+" + palette-block-shortcut: "1.+" + +biomes: + type: SINGLE + biome: PLAIN + +schedules: "#minecraft:in_overworld" + +schedule-definitions: + mypack:seasons: + clock: minecraft:overworld + period_ticks: 24000 + tracks: + minecraft:visual/sky_color: + keyframes: + - ticks: 0 + value: "#000000" + seasons: + clock: minecraft:overworld + "#mypack:tagged": + clock: minecraft:overworld + "mypack:not valid": + clock: minecraft:overworld + mypack:dropping: + clock: minecraft:overworld + tracks: + minecraft:visual/moon_phase: + modifier: add + keyframes: + - ticks: 0 + value: full_moon