From bebcb775fc82441c50010b9719c16b78439d4d48 Mon Sep 17 00:00:00 2001 From: Zoe Gidiere Date: Sun, 8 Nov 2026 19:37:29 -0700 Subject: [PATCH] feat: build Fabric biomes, dimensions and timelines from environment attributes --- .../minecraft/MinecraftAttributeTypes.java | 2 + .../MinecraftAttributeTypesTest.java | 500 +++++++++--------- platforms/mixin-common/build.gradle.kts | 3 + .../com/dfsek/terra/mod/MinecraftAddon.java | 20 - .../java/com/dfsek/terra/mod/ModPlatform.java | 54 +- .../terra/mod/attribute/AttributeReport.java | 68 +++ .../terra/mod/attribute/AttributeSlots.java | 36 ++ .../attribute/MinecraftAttributeParents.java | 171 ++++++ .../mod/attribute/MinecraftBiomeFactory.java | 164 ++++++ .../attribute/MinecraftDimensionFactory.java | 173 ++++++ .../mod/attribute/MinecraftTimelines.java | 270 ++++++++++ .../mod/attribute/PackAttributeTable.java | 165 ++++++ .../terra/mod/attribute/PackParents.java | 87 +++ .../mod/attribute/VanillaAttributeMaps.java | 65 +++ .../terra/mod/attribute/VanillaCodecs.java | 37 ++ .../terra/mod/attribute/VanillaContext.java | 88 +++ .../dfsek/terra/mod/attribute/VanillaIds.java | 19 + .../mod/attribute/VanillaParentReader.java | 101 ++++ .../config/BiomeAdditionsSoundTemplate.java | 28 - .../mod/config/BiomeMoodSoundTemplate.java | 36 -- .../config/BiomeParticleConfigTemplate.java | 40 -- .../terra/mod/config/EntityTypeTemplate.java | 20 - .../mod/config/MonsterSettingsConfig.java | 48 -- .../terra/mod/config/MusicSoundTemplate.java | 34 -- .../terra/mod/config/ProtoPlatformBiome.java | 12 + .../terra/mod/config/SoundEventTemplate.java | 29 - .../terra/mod/config/SpawnCostConfig.java | 38 -- .../terra/mod/config/SpawnEntryConfig.java | 38 -- .../mod/config/SpawnSettingsTemplate.java | 43 -- .../terra/mod/config/SpawnTypeConfig.java | 32 -- .../mod/config/VanillaBiomeProperties.java | 181 ------- .../mod/config/VanillaWorldProperties.java | 179 ------- .../mod/config/VillagerTypeTemplate.java | 21 - .../terra/mod/mixin/access/BiomeAccessor.java | 12 - .../ReloadableServerResourcesMixin.java | 2 + .../com/dfsek/terra/mod/util/BiomeUtil.java | 11 +- .../dfsek/terra/mod/util/DimensionUtil.java | 22 - .../com/dfsek/terra/mod/util/PresetUtil.java | 47 +- .../com/dfsek/terra/mod/util/TagUtil.java | 98 ++-- .../src/main/resources/terra.accesswidener | 1 + .../main/resources/terra.common.mixins.json | 1 - .../mod/attribute/FakePackAttributes.java | 120 +++++ .../MinecraftAttributeParentsTest.java | 400 ++++++++++++++ .../attribute/MinecraftBiomeFactoryTest.java | 466 ++++++++++++++++ .../MinecraftDimensionFactoryTest.java | 358 +++++++++++++ .../mod/attribute/MinecraftTestSupport.java | 73 +++ .../mod/attribute/MinecraftTimelinesTest.java | 416 +++++++++++++++ .../terra/mod/attribute/TagUtilTest.java | 106 ++++ .../dfsek/terra/mod/attribute/TestBiome.java | 67 +++ .../attribute/VanillaCodecHarnessTest.java | 308 +++++++++++ .../mod/attribute/VanillaContextTest.java | 97 ++++ .../attribute/VanillaParentReaderTest.java | 374 +++++++++++++ .../terra/lifecycle/LifecyclePlatform.java | 41 +- .../mixin/RegistryLoadTaskMixin.java | 28 + .../lifecycle/RegistryDataLoaderMixin.java | 24 +- .../lifecycle/util/LifecycleBiomeUtil.java | 105 ++-- .../terra/lifecycle/util/LifecycleUtil.java | 44 +- .../lifecycle/util/LoadContextHolder.java | 13 + .../resources/terra.lifecycle.mixins.json | 1 + 59 files changed, 4773 insertions(+), 1264 deletions(-) create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeReport.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeSlots.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParents.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactory.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactory.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftTimelines.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackAttributeTable.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackParents.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaAttributeMaps.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaCodecs.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaContext.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaIds.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaParentReader.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeAdditionsSoundTemplate.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeMoodSoundTemplate.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeParticleConfigTemplate.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/EntityTypeTemplate.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/MonsterSettingsConfig.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/MusicSoundTemplate.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SoundEventTemplate.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnCostConfig.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnEntryConfig.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnSettingsTemplate.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnTypeConfig.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/VanillaBiomeProperties.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/VanillaWorldProperties.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/VillagerTypeTemplate.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/BiomeAccessor.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/DimensionUtil.java create mode 100644 platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/FakePackAttributes.java create mode 100644 platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParentsTest.java create mode 100644 platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactoryTest.java create mode 100644 platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactoryTest.java create mode 100644 platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTestSupport.java create mode 100644 platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTimelinesTest.java create mode 100644 platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TagUtilTest.java create mode 100644 platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TestBiome.java create mode 100644 platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaCodecHarnessTest.java create mode 100644 platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaContextTest.java create mode 100644 platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaParentReaderTest.java create mode 100644 platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RegistryLoadTaskMixin.java create mode 100644 platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LoadContextHolder.java 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 index 405931447..54858306b 100644 --- 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 @@ -33,11 +33,13 @@ public final class MinecraftAttributeTypes { this.particle = handle.typeBuilder("particle", codecs.particle()).build(); this.ambientParticles = handle.typeBuilder("ambient_particles", codecs.ambientParticles()) .op(Operation.APPEND, codecs.ambientParticles(), MinecraftAttributeTypes::append) + .composable(Operation.APPEND, MinecraftAttributeTypes::append) .build(); this.backgroundMusic = handle.typeBuilder("background_music", codecs.backgroundMusic()).build(); this.ambientSounds = handle.typeBuilder("ambient_sounds", codecs.ambientSounds()).build(); this.mobSpawnSettings = handle.typeBuilder("mob_spawn_settings", codecs.mobSpawnSettings()) .op(Operation.OVERLAY, codecs.mobSpawnSettings(), MinecraftAttributeTypes::overlay) + .composable(Operation.OVERLAY, MinecraftAttributeTypes::overlay) .build(); this.identifier = handle.typeBuilder("identifier", codecs.identifier()).build(); this.identifierOrTag = handle.typeBuilder("identifier_or_tag", codecs.identifierOrTag()).build(); 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 index de2997da7..6b9310b23 100644 --- a/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributeTypesTest.java +++ b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributeTypesTest.java @@ -2,26 +2,41 @@ package attribute.minecraft; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.lang.reflect.Type; import java.util.ArrayList; +import java.util.Arrays; import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.OptionalDouble; +import java.util.OptionalInt; import java.util.Set; +import java.util.stream.Stream; import com.dfsek.terra.addons.attribute.minecraft.AmbientParticle; import com.dfsek.terra.addons.attribute.minecraft.AmbientSounds; import com.dfsek.terra.addons.attribute.minecraft.BackgroundMusic; import com.dfsek.terra.addons.attribute.minecraft.BedRule; +import com.dfsek.terra.addons.attribute.minecraft.CardinalLight; +import com.dfsek.terra.addons.attribute.minecraft.GrassColorModifier; import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue; import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTypes; import com.dfsek.terra.addons.attribute.minecraft.MinecraftCodecs; import com.dfsek.terra.addons.attribute.minecraft.MinecraftIds; import com.dfsek.terra.addons.attribute.minecraft.MobSpawnSettings; import com.dfsek.terra.addons.attribute.minecraft.MoonPhase; +import com.dfsek.terra.addons.attribute.minecraft.Music; +import com.dfsek.terra.addons.attribute.minecraft.Skybox; +import com.dfsek.terra.addons.attribute.minecraft.SoundRef; +import com.dfsek.terra.addons.attribute.minecraft.TemperatureModifier; import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.StringIdentifiable; import com.dfsek.terra.api.registry.key.TagKey; import com.dfsek.terra.api.util.generic.either.Either; import com.dfsek.terra.api.world.attribute.AttributeHandle; @@ -36,7 +51,6 @@ 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(); @@ -52,76 +66,20 @@ class MinecraftAttributeTypesTest { 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()); + private static RegistryKey id(String id) { + return RegistryKey.parse(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()); + private static SoundRef sound(String id) { + return new SoundRef(id(id), OptionalDouble.empty()); } - @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()); + private static IntProviderValue constant(int value) { + return new IntProviderValue(OptionalInt.of(value), Optional.empty()); } - @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 IntProviderValue provider(Map raw) { + return new IntProviderValue(OptionalInt.empty(), Optional.of(new RawValue(raw))); } private static MobSpawnSettings spawns(Map raw) throws DecodeException { @@ -133,34 +91,172 @@ class MinecraftAttributeTypesTest { } @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))); + void operationSets() { + for(AttributeType t : List.of(TYPES.moonPhase(), TYPES.bedRule(), TYPES.particle(), TYPES.backgroundMusic(), + TYPES.ambientSounds(), TYPES.identifier(), TYPES.identifierOrTag(), TYPES.intProvider())) { + assertEquals(EnumSet.of(Operation.OVERRIDE), t.operations(), t.id()); + } + assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.APPEND), TYPES.ambientParticles().operations()); + assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.OVERLAY), TYPES.mobSpawnSettings().operations()); } @Test - void 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()); + void enumIds() { + assertEquals(List.of("full_moon", "waning_gibbous", "third_quarter", "waning_crescent", "new_moon", "waxing_crescent", + "first_quarter", "waxing_gibbous"), ids(MoonPhase.values())); + assertEquals(List.of("always", "when_dark", "never"), ids(BedRule.Rule.values())); + assertEquals(List.of("none", "dark_forest", "swamp"), ids(GrassColorModifier.values())); + assertEquals(List.of("none", "frozen"), ids(TemperatureModifier.values())); + assertEquals(List.of("none", "overworld", "end"), ids(Skybox.values())); + assertEquals(List.of("default", "nether"), ids(CardinalLight.values())); + } + + private static List ids(StringIdentifiable[] values) { + return Arrays.stream(values).map(StringIdentifiable::getID).toList(); } @Test - void mobSpawnOverlayRules() throws DecodeException { + void valueRecordInvariants() { + assertThrows(IllegalArgumentException.class, () -> new IntProviderValue(OptionalInt.empty(), Optional.empty())); + assertThrows(IllegalArgumentException.class, + () -> new IntProviderValue(OptionalInt.of(1), Optional.of(new RawValue(Map.of("type", "minecraft:constant"))))); + LinkedHashMap costs = new LinkedHashMap<>(); + for(String n : new String[]{ "zombie", "alpha", "mid", "bat", "creeper", "ender" }) { + costs.put(RegistryKey.of("minecraft", n), new MobSpawnSettings.Cost(1, 1)); + } + MobSpawnSettings s = new MobSpawnSettings(Map.of(), costs); + assertEquals(List.copyOf(costs.keySet()), List.copyOf(s.spawnCosts().keySet())); + assertThrows(UnsupportedOperationException.class, () -> s.spawnCosts().clear()); + } + + static Stream vanillaValues() { + Map uniform = map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3); + return Stream.of( + Arguments.of("moon phase", TYPES.moonPhase(), "new_moon", MoonPhase.NEW_MOON), + Arguments.of("identifier", TYPES.identifier(), "minecraft:idle", id("minecraft:idle")), + Arguments.of("bare identifier", TYPES.identifier(), "idle", id("minecraft:idle")), + Arguments.of("bare identifier or tag", TYPES.identifierOrTag(), "stone", Either.left(id("minecraft:stone"))), + Arguments.of("bare tag", TYPES.identifierOrTag(), "#logs", Either.right(TagKey.parse("#minecraft:logs"))), + Arguments.of("particle", TYPES.particle(), map("type", "minecraft:dripping_dripstone_lava"), + new RawValue(map("type", "minecraft:dripping_dripstone_lava"))), + Arguments.of("int constant", TYPES.intProvider(), 7, constant(7)), + Arguments.of("int provider", TYPES.intProvider(), uniform, provider(uniform)), + Arguments.of("crimson forest particles", TYPES.ambientParticles(), + List.of(map("particle", map("type", "minecraft:crimson_spore"), "probability", 0.025)), + List.of(new AmbientParticle(new RawValue(map("type", "minecraft:crimson_spore")), 0.025f))), + Arguments.of("straw bed rule", TYPES.bedRule(), map("can_set_spawn", "never", "can_sleep", "when_dark", + "destroy_on_leave", true, "error_message", map("translate", "block.minecraft.bed.no_sleep")), + new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.NEVER, false, true, + Optional.of(new RawValue(map("translate", "block.minecraft.bed.no_sleep"))))), + Arguments.of("bed rule defaults", TYPES.bedRule(), map("can_set_spawn", "always", "can_sleep", "always"), + new BedRule(BedRule.Rule.ALWAYS, BedRule.Rule.ALWAYS, false, false, Optional.empty())), + Arguments.of("warm ocean music", TYPES.backgroundMusic(), map( + "creative", map("max_delay", 24000, "min_delay", 12000, "sound", "minecraft:music.creative"), + "default", map("max_delay", 24000, "min_delay", 12000, "sound", "minecraft:music.game", + "replace_current_music", true), + "underwater", map("max_delay", 24000, "min_delay", 12000, "sound", "minecraft:music.under_water")), + new BackgroundMusic(Optional.of(new Music(sound("minecraft:music.game"), 12000, 24000, true)), + Optional.of(new Music(sound("minecraft:music.creative"), 12000, 24000, false)), + Optional.of(new Music(sound("minecraft:music.under_water"), 12000, 24000, false)))), + Arguments.of("no music", TYPES.backgroundMusic(), map(), BackgroundMusic.EMPTY), + Arguments.of("crimson forest sounds", TYPES.ambientSounds(), map( + "additions", map("sound", "minecraft:ambient.crimson_forest.additions", "tick_chance", 0.0111), + "loop", "minecraft:ambient.crimson_forest.loop", + "mood", map("block_search_extent", 8, "offset", 2.0, "sound", "minecraft:ambient.crimson_forest.mood", + "tick_delay", 6000)), + new AmbientSounds(Optional.of(sound("minecraft:ambient.crimson_forest.loop")), + Optional.of(new AmbientSounds.Mood(sound("minecraft:ambient.crimson_forest.mood"), 6000, 8, 2.0)), + List.of(new AmbientSounds.Additions(sound("minecraft:ambient.crimson_forest.additions"), 0.0111)))), + Arguments.of("addition list and ranged loop", TYPES.ambientSounds(), map( + "loop", map("sound_id", "a:b", "range", 16), + "additions", List.of(map("sound", "a:b", "tick_chance", 0.1), map("sound", "ambient.cave", "tick_chance", 0.2))), + new AmbientSounds(Optional.of(new SoundRef(id("a:b"), OptionalDouble.of(16))), Optional.empty(), + List.of(new AmbientSounds.Additions(sound("a:b"), 0.1), new AmbientSounds.Additions(sound("minecraft:ambient.cave"), 0.2)))), + Arguments.of("unranged sound object", TYPES.ambientSounds(), map("loop", map("sound_id", "a:b")), + new AmbientSounds(Optional.of(sound("a:b")), Optional.empty(), List.of())), + Arguments.of("no sounds", TYPES.ambientSounds(), map(), AmbientSounds.EMPTY), + Arguments.of("mob spawns", TYPES.mobSpawnSettings(), map( + "spawns_by_category", map("ambient", List.of(spawner("minecraft:bat", 10, 8)), + "monster", List.of(map("type", "minecraft:zombie", "weight", 5, "count", uniform))), + "spawn_costs", map("minecraft:enderman", map("energy_budget", 0.7, "charge", 0.15))), + new MobSpawnSettings( + Map.of("ambient", List.of(new MobSpawnSettings.Spawner(id("minecraft:bat"), 10, constant(8))), + "monster", List.of(new MobSpawnSettings.Spawner(id("minecraft:zombie"), 5, provider(uniform)))), + Map.of(id("minecraft:enderman"), new MobSpawnSettings.Cost(0.7, 0.15))))); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("vanillaValues") + void decodesVanillaValues(String name, AttributeType type, Object raw, Object expected) throws DecodeException { + assertEquals(expected, type.decode(raw, PLAIN)); + } + + static Stream invalidValues() { + Map noCosts = map("spawns_by_category", map()); + return Stream.of( + Arguments.of("moon phase", TYPES.moonPhase(), "blue_moon"), + Arguments.of("identifier with a space", TYPES.identifier(), "Not Valid"), + Arguments.of("identifier number", TYPES.identifier(), 3), + Arguments.of("identifier given a tag", TYPES.identifier(), "#minecraft:logs"), + Arguments.of("empty tag", TYPES.identifierOrTag(), "#"), + Arguments.of("particle without type", TYPES.particle(), map("color", 1)), + Arguments.of("particle string", TYPES.particle(), "minecraft:flame"), + Arguments.of("int provider string", TYPES.intProvider(), "x"), + Arguments.of("int provider fraction", TYPES.intProvider(), 1.5), + Arguments.of("int provider overflow", TYPES.intProvider(), 99999999999L), + Arguments.of("int provider without type", TYPES.intProvider(), map("min_inclusive", 0, "max_inclusive", 7)), + Arguments.of("probability above 1", TYPES.ambientParticles(), List.of(map("particle", map("type", "x"), "probability", 1.5))), + Arguments.of("missing probability", TYPES.ambientParticles(), List.of(map("particle", map("type", "x")))), + Arguments.of("particle not an object", TYPES.ambientParticles(), List.of(map("particle", "x", "probability", 0.5))), + Arguments.of("extra particle key", TYPES.ambientParticles(), + List.of(map("particle", map("type", "x"), "probability", 0.5, "extra", 1))), + Arguments.of("particles not a list", TYPES.ambientParticles(), map("particle", map("type", "x"), "probability", 0.5)), + Arguments.of("bed rule missing can_set_spawn", TYPES.bedRule(), map("can_sleep", "always")), + Arguments.of("extra bed rule key", TYPES.bedRule(), map("can_sleep", "always", "can_set_spawn", "always", "nope", 1)), + Arguments.of("unknown music key", TYPES.backgroundMusic(), map("bogus", 1)), + Arguments.of("music missing max_delay", TYPES.backgroundMusic(), map("default", map("sound", "a:b", "min_delay", 1))), + Arguments.of("negative delay", TYPES.backgroundMusic(), + map("default", map("sound", "a:b", "min_delay", -1, "max_delay", 1))), + Arguments.of("misspelled sounds key", TYPES.ambientSounds(), map("looop", "a:b")), + Arguments.of("incomplete mood", TYPES.ambientSounds(), map("mood", map("sound", "a:b"))), + Arguments.of("sound number", TYPES.ambientSounds(), map("loop", 5)), + Arguments.of("sound with a space", TYPES.ambientSounds(), map("loop", "Not Valid")), + Arguments.of("sound object without ID", TYPES.ambientSounds(), map("loop", map("range", 1))), + Arguments.of("unknown mob category", TYPES.mobSpawnSettings(), + map("spawns_by_category", map("bogus", List.of()), "spawn_costs", map())), + Arguments.of("missing spawn_costs", TYPES.mobSpawnSettings(), noCosts), + Arguments.of("extra spawn settings key", TYPES.mobSpawnSettings(), + map("spawns_by_category", map(), "spawn_costs", map(), "x", 1)), + Arguments.of("fractional weight", TYPES.mobSpawnSettings(), map("spawns_by_category", + map("monster", List.of(map("type", "minecraft:zombie", "weight", 1.5, "count", 1))), "spawn_costs", map()))); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("invalidValues") + void rejectsInvalidValues(String name, AttributeType type, Object raw) { + assertThrows(DecodeException.class, () -> type.decode(raw, PLAIN)); + } + + @Test + void nestedDecodeFailures() { + String bedRule = assertThrows(DecodeException.class, + () -> TYPES.bedRule().decode(map("can_sleep", "sometimes", "can_set_spawn", "always"), PLAIN)).getMessage(); + assertEquals("\"can_sleep\" of bed rule: unknown bed rule \"sometimes\", expected one of [always, when_dark, never]", bedRule); + } + + @Test + void ambientParticlesAppend() throws DecodeException { + AttributeType> 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(one, t.apply(Operation.APPEND, one, List.of())); + assertEquals(two, t.apply(Operation.APPEND, List.of(), two)); + assertEquals(List.of(one.get(0), two.get(0)), + mod(t, Operation.APPEND, one, List.of(map("particle", map("type", "minecraft:white_ash"), "probability", 0.1)))); + } + + @Test + void mobSpawnOverlay() throws DecodeException { AttributeType t = TYPES.mobSpawnSettings(); MobSpawnSettings empty = MobSpawnSettings.EMPTY; MobSpawnSettings a = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1))), @@ -173,71 +269,59 @@ class MinecraftAttributeTypesTest { 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)), + MobSpawnSettings r = mod(t, Operation.OVERLAY, s, map("spawns_by_category", map("ambient", List.of(spawner("minecraft:bat", 1, 1)), "creature", List.of(spawner("minecraft:pig", 1, 1))), "spawn_costs", map("minecraft:b", map("energy_budget", 2, "charge", 2)))); - 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()); + assertEquals(id("minecraft:zombie"), r.spawnsByCategory().get("monster").get(0).type()); + assertEquals(id("minecraft:pig"), r.spawnsByCategory().get("creature").get(0).type()); + assertEquals(id("minecraft:bat"), r.spawnsByCategory().get("ambient").get(0).type()); + assertEquals(Set.of(id("minecraft:a"), id("minecraft:b")), r.spawnCosts().keySet()); + MobSpawnSettings cleared = mod(t, Operation.OVERLAY, s, map("spawns_by_category", map("monster", List.of()), "spawn_costs", map())); + assertTrue(cleared.spawnsByCategory().get("monster").isEmpty()); + assertEquals(1, cleared.spawnsByCategory().get("creature").size()); + } + + private static final List ALL_CATEGORIES = List.of("monster", "creature", "ambient", "axolotls", + "underground_water_creature", "water_creature", "water_ambient", "misc"); + + private static MobSpawnSettings spawnsIn(String type, List categories, String... costs) throws DecodeException { + Map byCategory = new LinkedHashMap<>(); + for(String category : categories) byCategory.put(category, List.of(spawner(type, 1, 1))); + Map costMap = new LinkedHashMap<>(); + for(String cost : costs) costMap.put(cost, map("energy_budget", 1, "charge", 1)); + return spawns(map("spawns_by_category", byCategory, "spawn_costs", costMap)); + } + + private static void assertComposesLikeApplyingBoth(AttributeType t, Operation op, List subjects, List arguments) { + for(T s : subjects) { + for(T a : arguments) { + for(T b : arguments) { + Object composed = t.compose(op, a, b).orElseThrow(); + assertEquals(t.apply(op, t.apply(op, s, a), b), t.apply(op, s, composed), s + " then " + a + " then " + b); + } + } + } } @Test - void 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)); - } + void composeEqualsApply() throws DecodeException { + assertComposesLikeApplyingBoth(TYPES.mobSpawnSettings(), Operation.OVERLAY, + List.of(MobSpawnSettings.EMPTY, + spawnsIn("minecraft:zombie", List.of("monster", "creature"), "minecraft:a"), + spawnsIn("minecraft:zombie", ALL_CATEGORIES, "minecraft:a", "minecraft:b")), + List.of(MobSpawnSettings.EMPTY, + spawnsIn("minecraft:husk", List.of("monster", "ambient"), "minecraft:b"), + spawnsIn("minecraft:pig", List.of("creature"), "minecraft:c"), + spawnsIn("minecraft:bat", ALL_CATEGORIES, "minecraft:a"), + spawns(map("spawns_by_category", map("monster", List.of()), "spawn_costs", map())))); - @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)), + AttributeType> particles = TYPES.ambientParticles(); + List one = particles.decode(List.of(map("particle", map("type", "minecraft:crimson_spore"), "probability", 0.025)), 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))); + List two = particles.decode(List.of(map("particle", map("type", "minecraft:white_ash"), "probability", 0.1), + map("particle", map("type", "minecraft:ash"), "probability", 0.5)), PLAIN); + List> lists = List.of(List.of(), one, two); + assertComposesLikeApplyingBoth(particles, Operation.APPEND, lists, lists); } private static String path(String written) { @@ -255,8 +339,25 @@ class MinecraftAttributeTypesTest { return t.getMessage(); } + @Test + void requireLowerCase() { + RegistryKey key = id("minecraft:visual/fog_color"); + assertSame(key, MinecraftIds.requireLowerCase(key)); + assertSame(key, MinecraftIds.requireLowerCase(key, "visual/fog_color")); + assertEquals(namespace("Mod:thing"), + assertThrows(IllegalArgumentException.class, () -> MinecraftIds.requireLowerCase(id("Mod:thing"))).getMessage()); + assertEquals(path("mod:Thing"), + assertThrows(IllegalArgumentException.class, () -> MinecraftIds.requireLowerCase(id("mod:Thing"))).getMessage()); + assertEquals(path("Thing"), assertThrows(IllegalArgumentException.class, + () -> MinecraftIds.requireLowerCase(id("minecraft:Thing"), "Thing")).getMessage()); + DecodeException e = assertThrows(DecodeException.class, () -> CODECS.soundRef().decode("minecraft:Ambient.Cave", PLAIN)); + assertEquals("expected an identifier like \"minecraft:id\", got \"minecraft:Ambient.Cave\"", e.getMessage()); + assertEquals(path("minecraft:Ambient.Cave"), e.getCause().getMessage()); + } + @Test void lowerCaseIds() { + assertEquals(namespace("Minecraft:x"), lowerCaseFailure(() -> CODECS.soundRef().decode("Minecraft:x", PLAIN))); assertEquals(path("minecraft:Music.Game"), lowerCaseFailure(() -> TYPES.ambientSounds().decode(Map.of("loop", "minecraft:Music.Game"), PLAIN))); assertEquals(path("Music.Game"), lowerCaseFailure(() -> TYPES.backgroundMusic().decode( @@ -272,101 +373,6 @@ class MinecraftAttributeTypesTest { "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<>(); @@ -384,10 +390,7 @@ class MinecraftAttributeTypesTest { }; 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()); + assertTrue(seen.containsAll(List.of("minecraft:music.game", 1, 2, music)), seen.toString()); } private static DecodeContext referencing(Map targets) { @@ -420,7 +423,8 @@ class MinecraftAttributeTypesTest { "@min", 1, "@flame", "minecraft:flame", "@message", map("translate", "@key"), - "@key", "block.minecraft.bed.no_sleep")); + "@key", "block.minecraft.bed.no_sleep", + "minecraft:zombie", "minecraft:cow")); AmbientSounds sounds = TYPES.ambientSounds().decode(map("loop", "@sound", "additions", "@additions"), context); assertEquals(4.0, sounds.loop().orElseThrow().range().orElseThrow()); @@ -437,14 +441,10 @@ class MinecraftAttributeTypesTest { 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())); + assertEquals(List.of(id("minecraft:zombie")), List.copyOf(settings.spawnCosts().keySet())); } } diff --git a/platforms/mixin-common/build.gradle.kts b/platforms/mixin-common/build.gradle.kts index 0f8b4c399..2d3848be4 100644 --- a/platforms/mixin-common/build.gradle.kts +++ b/platforms/mixin-common/build.gradle.kts @@ -13,6 +13,9 @@ dependencies { compileOnly("net.fabricmc:sponge-mixin:${Versions.Mod.mixin}") minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") + + // Tests only: the addon ships as its own jar. + testImplementation(project(":common:addons:minecraft-attributes")) } architectury { diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/MinecraftAddon.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/MinecraftAddon.java index 4586dce2a..e823155d2 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/MinecraftAddon.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/MinecraftAddon.java @@ -23,15 +23,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.dfsek.terra.api.addon.BaseAddon; -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.world.biome.Biome; import com.dfsek.terra.mod.config.PostLoadCompatibilityOptions; import com.dfsek.terra.mod.config.PreLoadCompatibilityOptions; -import com.dfsek.terra.mod.config.VanillaBiomeProperties; -import com.dfsek.terra.mod.config.VanillaWorldProperties; public abstract class MinecraftAddon implements BaseAddon { @@ -45,12 +41,6 @@ public abstract class MinecraftAddon implements BaseAddon { @Override public void initialize() { - modPlatform.getEventManager() - .getHandler(FunctionalEventHandler.class) - .register(this, ConfigPackPostLoadEvent.class) - .then(event -> event.getPack().getContext().put(event.loadTemplate(new VanillaWorldProperties()))) - .priority(100) - .global(); modPlatform.getEventManager() .getHandler(FunctionalEventHandler.class) .register(this, ConfigPackPreLoadEvent.class) @@ -63,16 +53,6 @@ public abstract class MinecraftAddon implements BaseAddon { .then(event -> event.getPack().getContext().put(event.loadTemplate(new PostLoadCompatibilityOptions()))) .priority(100) .global(); - - modPlatform.getEventManager() - .getHandler(FunctionalEventHandler.class) - .register(this, ConfigurationLoadEvent.class) - .then(event -> { - if(event.is(Biome.class)) { - event.getLoadedObject(Biome.class).getContext().put(event.load(new VanillaBiomeProperties())); - } - }) - .global(); } @Override diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/ModPlatform.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/ModPlatform.java index b2c815776..503eb9c4a 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/ModPlatform.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/ModPlatform.java @@ -6,20 +6,8 @@ import com.dfsek.tectonic.api.exception.LoadException; import net.minecraft.core.Registry; import net.minecraft.resources.Identifier; import net.minecraft.server.MinecraftServer; -import net.minecraft.sounds.Music; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.world.attribute.AmbientAdditionsSettings; -import net.minecraft.world.attribute.AmbientMoodSettings; -import net.minecraft.world.attribute.AmbientParticle; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.MobCategory; -import net.minecraft.world.entity.npc.villager.VillagerType; import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.Biome.Precipitation; -import net.minecraft.world.level.biome.Biome.TemperatureModifier; -import net.minecraft.world.level.biome.BiomeSpecialEffects.GrassColorModifier; -import net.minecraft.world.level.biome.MobSpawnSettings; import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterList; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; @@ -34,19 +22,10 @@ import com.dfsek.terra.AbstractPlatform; import com.dfsek.terra.api.addon.BaseAddon; import com.dfsek.terra.api.handle.ItemHandle; import com.dfsek.terra.api.handle.WorldHandle; +import com.dfsek.terra.api.world.attribute.AttributeParents; import com.dfsek.terra.api.world.biome.PlatformBiome; -import com.dfsek.terra.mod.config.BiomeAdditionsSoundTemplate; -import com.dfsek.terra.mod.config.BiomeMoodSoundTemplate; -import com.dfsek.terra.mod.config.BiomeParticleConfigTemplate; -import com.dfsek.terra.mod.config.EntityTypeTemplate; -import com.dfsek.terra.mod.config.MusicSoundTemplate; +import com.dfsek.terra.mod.attribute.MinecraftAttributeParents; import com.dfsek.terra.mod.config.ProtoPlatformBiome; -import com.dfsek.terra.mod.config.SoundEventTemplate; -import com.dfsek.terra.mod.config.SpawnCostConfig; -import com.dfsek.terra.mod.config.SpawnEntryConfig; -import com.dfsek.terra.mod.config.SpawnSettingsTemplate; -import com.dfsek.terra.mod.config.SpawnTypeConfig; -import com.dfsek.terra.mod.config.VillagerTypeTemplate; import com.dfsek.terra.mod.handle.MinecraftItemHandle; import com.dfsek.terra.mod.handle.MinecraftWorldHandle; import com.dfsek.terra.mod.util.PresetUtil; @@ -55,6 +34,7 @@ import com.dfsek.terra.mod.util.PresetUtil; public abstract class ModPlatform extends AbstractPlatform { private final ItemHandle itemHandle = new MinecraftItemHandle(); private final WorldHandle worldHandle = new MinecraftWorldHandle(); + private final MinecraftAttributeParents attributeParents = new MinecraftAttributeParents(getAttributeHandle()); public abstract MinecraftServer getServer(); @@ -80,24 +60,7 @@ public abstract class ModPlatform extends AbstractPlatform { if(identifier == null) throw new LoadException("Invalid identifier: " + o, depthTracker); return identifier; - }) - .registerLoader(Precipitation.class, (type, o, loader, depthTracker) -> Precipitation.valueOf(((String) o).toUpperCase())) - .registerLoader(GrassColorModifier.class, - (type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase())) - .registerLoader(TemperatureModifier.class, - (type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase())) - .registerLoader(MobCategory.class, (type, o, loader, depthTracker) -> MobCategory.valueOf((String) o)) - .registerLoader(AmbientParticle.class, BiomeParticleConfigTemplate::new) - .registerLoader(SoundEvent.class, SoundEventTemplate::new) - .registerLoader(AmbientMoodSettings.class, BiomeMoodSoundTemplate::new) - .registerLoader(AmbientAdditionsSettings.class, BiomeAdditionsSoundTemplate::new) - .registerLoader(Music.class, MusicSoundTemplate::new) - .registerLoader(EntityType.class, EntityTypeTemplate::new) - .registerLoader(SpawnCostConfig.class, SpawnCostConfig::new) - .registerLoader(SpawnEntryConfig.class, SpawnEntryConfig::new) - .registerLoader(SpawnTypeConfig.class, SpawnTypeConfig::new) - .registerLoader(MobSpawnSettings.class, SpawnSettingsTemplate::new) - .registerLoader(VillagerType.class, VillagerTypeTemplate::new); + }); } private ProtoPlatformBiome parseBiome(String id, DepthTracker tracker) throws LoadException { @@ -133,5 +96,14 @@ public abstract class ModPlatform extends AbstractPlatform { return itemHandle; } + @Override + public @NotNull AttributeParents getAttributeParents() { + return attributeParents; + } + + public MinecraftAttributeParents attributeParents() { + return attributeParents; + } + } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeReport.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeReport.java new file mode 100644 index 000000000..ac10cbf38 --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeReport.java @@ -0,0 +1,68 @@ +package com.dfsek.terra.mod.attribute; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; + +import com.dfsek.terra.api.config.ConfigPack; + + +/** + * Thread safe. + */ +public final class AttributeReport { + private static final Logger LOGGER = LoggerFactory.getLogger(AttributeReport.class); + private static final String NOT_A_MINECRAFT_TAG = "no such tag in the minecraft namespace"; + + private final String pack; + private final Consumer warn; + private final Consumer debug; + private final Set notApplied = ConcurrentHashMap.newKeySet(); + + public AttributeReport(String pack, Consumer warn, Consumer debug) { + this.pack = Objects.requireNonNull(pack, "pack"); + this.warn = Objects.requireNonNull(warn, "warn"); + this.debug = Objects.requireNonNull(debug, "debug"); + } + + public static AttributeReport logging(ConfigPack pack) { + return logging(pack, LOGGER); + } + + public static AttributeReport logging(ConfigPack pack, Logger logger) { + return new AttributeReport(pack.getID(), logger::warn, logger::debug); + } + + public void attributeSkipped(String config, String key, String reason) { + warn.accept("Pack \"" + pack + "\", config \"" + config + "\": attribute \"" + key + "\" skipped: " + reason); + } + + public void scheduleSkipped(String schedule, String reason) { + warn.accept("Pack \"" + pack + "\": schedule \"" + schedule + "\" skipped: " + reason); + } + + public void trackDropped(String schedule, String key, String reason) { + warn.accept("Pack \"" + pack + "\": schedule \"" + schedule + "\" track \"" + key + "\" dropped: " + reason); + } + + public void timeMarkerDropped(String schedule, String marker, String clock) { + warn.accept("Pack \"" + pack + "\": schedule \"" + schedule + "\" time marker \"" + marker + "\" dropped: already defined for " + + "clock \"" + clock + "\""); + } + + public void ignored(String config, String key, String reason) { + warn.accept("Pack \"" + pack + "\", config \"" + config + "\": \"" + key + "\" ignored: " + reason); + } + + public void tagCreated(String config, String tag) { + warn.accept("Pack \"" + pack + "\", config \"" + config + "\": tag \"" + tag + "\" created: " + NOT_A_MINECRAFT_TAG); + } + + public void notApplied(String key) { + if(notApplied.add(key)) debug.accept("Pack \"" + pack + "\": attribute \"" + key + "\" is not applied on this platform"); + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeSlots.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeSlots.java new file mode 100644 index 000000000..067f03c80 --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeSlots.java @@ -0,0 +1,36 @@ +package com.dfsek.terra.mod.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; + + +/** + * An attribute built after the slots were sized reads as absent. + */ +public final class AttributeSlots { + public static final AttributeSlots EMPTY = new AttributeSlots(new AttributeEntry[0]); + + private final AttributeEntry[] entries; + + private AttributeSlots(AttributeEntry[] entries) { + this.entries = entries; + } + + /** + * Keeps {@code entries} without copying: the caller must not change the array afterwards. + */ + public static AttributeSlots of(AttributeEntry[] entries) { + return new AttributeSlots(Objects.requireNonNull(entries, "entries")); + } + + @SuppressWarnings("unchecked") + public @Nullable AttributeEntry get(Attribute attribute) { + int index = attribute.index(); + AttributeEntry[] entries = this.entries; + return index < entries.length ? (AttributeEntry) entries[index] : null; + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParents.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParents.java new file mode 100644 index 000000000..6950dc9ca --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParents.java @@ -0,0 +1,171 @@ +package com.dfsek.terra.mod.attribute; + +import net.minecraft.core.HolderGetter; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.BiConsumer; + +import com.dfsek.terra.api.config.ConfigPack; +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.AttributeParents; +import com.dfsek.terra.api.world.attribute.PackAttributes; +import com.dfsek.terra.mod.config.ProtoPlatformBiome; + + +public final class MinecraftAttributeParents implements AttributeParents { + private static final String PACK_CONFIG = "pack.yml"; + private static final String VANILLA = "vanilla"; + private static final String VANILLA_GENERATION = "vanilla-generation"; + private static final PackParents[] NO_PACKS = new PackParents[0]; + + private final AttributeHandle handle; + // Replaced, never mutated: a read sees one load's context and packs together. + private volatile State state = new State(null, NO_PACKS, 0); + + public MinecraftAttributeParents(AttributeHandle handle) { + this.handle = Objects.requireNonNull(handle, "handle"); + } + + public synchronized void beginLoad(VanillaContext context) { + state = new State(Objects.requireNonNull(context, "context"), NO_PACKS, 0); + MinecraftTimelines.clear(); + } + + public synchronized void clearPacks() { + state = new State(state.context(), NO_PACKS, 0); + } + + /** + * Old packs keep their parents until {@link #endPackReload}; worlds may still be generating with them. + */ + public synchronized void beginPackReload() { + State current = state; + state = new State(current.context(), current.packs(), current.packs().length); + } + + public synchronized void endPackReload() { + State current = state; + state = new State(current.context(), Arrays.copyOfRange(current.packs(), current.reloadedFrom(), current.packs().length), 0); + } + + public @Nullable VanillaContext context() { + return state.context(); + } + + public synchronized PackParents prepare(ConfigPack pack, Optional attributes, AttributeReport report) { + State current = state; + VanillaContext context = current.context(); + if(context == null) throw new IllegalStateException("no registry load has begun"); + PackAttributes packAttributes = attributes.orElse(null); + PackParents[] prepared = current.packs(); + for(int i = current.reloadedFrom(); i < prepared.length; i++) { + if(prepared[i].pack() == pack && prepared[i].attributes() == packAttributes) return prepared[i]; + } + + ResourceKey dimensionKey = parent(packAttributes, VANILLA, Registries.DIMENSION_TYPE, context.dimensionTypes(), + BuiltinDimensionTypes.OVERWORLD, "dimension type", report); + ResourceKey generationKey = parent(packAttributes, VANILLA_GENERATION, Registries.NOISE_SETTINGS, + context.noiseSettings(), NoiseGeneratorSettings.OVERWORLD, "noise settings", report); + DimensionType dimension = context.dimensionTypes().getOrThrow(dimensionKey).value(); + NoiseGeneratorSettings generation = context.noiseSettings().getOrThrow(generationKey).value(); + + PackAttributeTable table = PackAttributeTable.of(pack.getRegistry(Attribute.REGISTRY_TYPE)); + VanillaParentReader reader = new VanillaParentReader(handle, context); + AttributeSlots dimensionSlots = reader.dimension(dimension, table, parentSkipped(report, dimensionKey.identifier().toString())); + AttributeSlots generationSlots = reader.generation(generation, table); + + PackParents parents = new PackParents(pack, dimensionKey, dimension, generationKey, generation, table, + fold(table, dimensionSlots, generationSlots), packAttributes, report, reader); + PackParents[] packs = Arrays.copyOf(prepared, prepared.length + 1); + packs[packs.length - 1] = parents; + state = new State(context, packs, current.reloadedFrom()); + return parents; + } + + public AttributeSlots biomeEntries(PackParents pack, ResourceKey key, Biome biome) { + AttributeSlots cached = pack.biomeEntries().get(key); + if(cached != null) return cached; + // Warn outside the map's bin lock, and only for the read that gets cached. + record Skipped(Attribute attribute, String reason) { } + List skipped = new ArrayList<>(0); + AttributeSlots read = pack.reader().biome(key, biome, pack.table(), + (attribute, reason) -> skipped.add(new Skipped(attribute, reason))); + AttributeSlots raced = pack.biomeEntries().putIfAbsent(key, read); + if(raced != null) return raced; + BiConsumer, String> report = parentSkipped(pack.report(), key.identifier().toString()); + for(Skipped s : skipped) report.accept(s.attribute(), s.reason()); + return read; + } + + @Override + public @Nullable AttributeEntry biomeOrNull(com.dfsek.terra.api.world.biome.Biome biome, Attribute attribute) { + return biome.getPlatformBiome() instanceof ProtoPlatformBiome proto ? proto.parentEntries().get(attribute) : null; + } + + @Override + public @Nullable AttributeEntry packOrNull(PackAttributes pack, Attribute attribute) { + PackParents[] packs = state.packs(); + for(PackParents prepared : packs) { + if(prepared.attributes() == pack) return prepared.packEntries().get(attribute); + } + return null; + } + + private static ResourceKey parent(@Nullable PackAttributes attributes, String configKey, + ResourceKey> registry, HolderGetter getter, + ResourceKey fallback, String what, AttributeReport report) { + RegistryKey id = attributes == null ? null : attributes.parents().get(configKey); + if(id == null) return fallback; + ResourceKey key; + try { + key = ResourceKey.create(registry, VanillaIds.identifier(id)); + } catch(IllegalArgumentException e) { + report.ignored(PACK_CONFIG, configKey, e.getMessage()); + return fallback; + } + if(getter.get(key).isPresent()) return key; + report.ignored(PACK_CONFIG, configKey, "no such " + what + " \"" + key.identifier() + "\""); + return fallback; + } + + private AttributeSlots fold(PackAttributeTable table, AttributeSlots dimension, AttributeSlots generation) { + AttributeEntry[] slots = new AttributeEntry[handle.attributeCount()]; + for(PackAttributeTable.Bound bound : table.environment()) fold(bound.attribute(), dimension, generation, slots); + for(PackAttributeTable.Field field : table.dimension()) fold(field.attribute(), dimension, generation, slots); + if(table.seaLevel() != null) fold(table.seaLevel(), dimension, generation, slots); + if(table.mobGeneration() != null) fold(table.mobGeneration(), dimension, generation, slots); + return AttributeSlots.of(slots); + } + + private void fold(Attribute attribute, AttributeSlots dimension, AttributeSlots generation, AttributeEntry[] slots) { + AttributeEntry lower = dimension.get(attribute); + AttributeEntry upper = generation.get(attribute); + if(lower == null && upper == null) return; + slots[attribute.index()] = handle.compose(attribute, lower, upper) + .orElseGet(() -> AttributeEntry.override(handle.resolve(attribute, lower, upper, null))); + } + + static BiConsumer, String> parentSkipped(AttributeReport report, String parent) { + return (attribute, reason) -> report.attributeSkipped(PACK_CONFIG, attribute.getRegistryKey().toString(), + "vanilla parent \"" + parent + "\": " + reason); + } + + + // reloadedFrom: the first pack prepared since a pack reload began, or 0 outside one. + private record State(@Nullable VanillaContext context, PackParents[] packs, int reloadedFrom) { } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactory.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactory.java new file mode 100644 index 000000000..7b4e5a331 --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactory.java @@ -0,0 +1,164 @@ +package com.dfsek.terra.mod.attribute; + +import com.mojang.serialization.Codec; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.attribute.EnvironmentAttributeMap; +import net.minecraft.world.entity.npc.villager.VillagerType; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeSpecialEffects; +import org.jetbrains.annotations.Nullable; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +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.DecodeException; +import com.dfsek.terra.api.world.attribute.PackAttributes; +import com.dfsek.terra.mod.config.ProtoPlatformBiome; + + +public final class MinecraftBiomeFactory { + private final AttributeHandle handle; + private final VanillaContext context; + private final VanillaAttributeMaps maps; + + public MinecraftBiomeFactory(AttributeHandle handle, VanillaContext context) { + this.handle = Objects.requireNonNull(handle, "handle"); + this.context = Objects.requireNonNull(context, "context"); + this.maps = new VanillaAttributeMaps(handle, context); + } + + /** + * {@code terraBiome}'s parent entries must already be set from {@link MinecraftAttributeParents#biomeEntries}. + */ + public Built create(ResourceKey parentKey, Biome parent, com.dfsek.terra.api.world.biome.Biome terraBiome, PackParents pack, + AttributeReport report) { + String config = terraBiome.getID(); + PackAttributes attributes = pack.attributes(); + PackAttributeTable table = pack.table(); + + Biome.ClimateSettings climate = parent.climateSettings; + BiomeSpecialEffects effects = parent.getSpecialEffects(); + EnvironmentAttributeMap environment = parent.getAttributes(); + ResourceKey villagerType = null; + if(attributes != null) { + climate = fields(Biome.ClimateSettings.CODEC.codec(), climate, table.climate(), attributes, terraBiome, config, report); + effects = fields(BiomeSpecialEffects.CODEC, effects, table.effects(), attributes, terraBiome, config, report); + environment = environment(environment, table, attributes, terraBiome, config, report); + if(table.villagerType() != null) villagerType = villagerType(table.villagerType(), attributes, terraBiome, config, report); + for(Attribute unapplied : table.unapplied()) { + if(attributes.biomeEntryOrNull(unapplied, terraBiome) != null) report.notApplied(unapplied.getRegistryKey().toString()); + } + } + if(villagerType == null) villagerType = Objects.requireNonNullElse(context.villagerTypes().apply(parentKey), VillagerType.PLAINS); + + Biome biome = new Biome.BiomeBuilder() + .hasPrecipitation(climate.hasPrecipitation()) + .temperature(climate.temperature()) + .temperatureAdjustment(climate.temperatureModifier()) + .downfall(climate.downfall()) + .specialEffects(effects) + .putAttributes(environment) + .generationSettings(parent.getGenerationSettings()) + .build(); + return new Built(biome, villagerType); + } + + private V fields(Codec codec, V parent, List fields, PackAttributes attributes, + com.dfsek.terra.api.world.biome.Biome terraBiome, String config, AttributeReport report) { + if(fields.isEmpty()) return parent; + Map original = (Map) VanillaCodecs.encode(codec, parent, context.ops()); + Map all = new LinkedHashMap<>(original); + for(PackAttributeTable.Field field : fields) set(all, field, attributes, terraBiome); + // Parsing it again would give colours an opaque alpha. + if(all.equals(original)) return parent; + try { + return VanillaCodecs.parse(codec, all, context.ops()); + } catch(DecodeException whole) { + V value = parent; + Map accepted = new LinkedHashMap<>(original); + for(PackAttributeTable.Field field : fields) { + Map trial = new LinkedHashMap<>(accepted); + set(trial, field, attributes, terraBiome); + if(trial.equals(accepted)) continue; + try { + value = VanillaCodecs.parse(codec, trial, context.ops()); + accepted = trial; + } catch(DecodeException e) { + report.attributeSkipped(config, field.attribute().getRegistryKey().toString(), e.getMessage()); + } + } + return value; + } + } + + private static void set(Map fields, PackAttributeTable.Field field, PackAttributes attributes, + com.dfsek.terra.api.world.biome.Biome terraBiome) { + Object value = resolveEncoded(field.attribute(), attributes, terraBiome); + if(value == null) { + fields.remove(field.name()); + } else { + fields.put(field.name(), value); + } + } + + private static @Nullable Object resolveEncoded(Attribute attribute, PackAttributes attributes, + com.dfsek.terra.api.world.biome.Biome biome) { + T value = attributes.resolve(attribute, biome); + return value == null ? null : attribute.type().encode(value); + } + + private EnvironmentAttributeMap environment(EnvironmentAttributeMap parent, PackAttributeTable table, PackAttributes attributes, + com.dfsek.terra.api.world.biome.Biome terraBiome, String config, + AttributeReport report) { + AttributeSlots parentSlots = terraBiome.getPlatformBiome() instanceof ProtoPlatformBiome proto + ? proto.parentEntries() + : AttributeSlots.EMPTY; + Map, AttributeEntry> entries = new LinkedHashMap<>(); + for(PackAttributeTable.Bound bound : table.environment()) { + AttributeEntry entry = entry(bound.attribute(), parentSlots, attributes, terraBiome); + if(entry != null) entries.put(bound.attribute(), entry); + } + if(entries.isEmpty()) return parent; + return maps.toVanilla(parent, entries, true, + (attribute, reason) -> report.attributeSkipped(config, attribute.getRegistryKey().toString(), reason)); + } + + private @Nullable AttributeEntry entry(Attribute attribute, AttributeSlots parentSlots, PackAttributes attributes, + com.dfsek.terra.api.world.biome.Biome terraBiome) { + AttributeEntry entry = attributes.biomeEntryOrNull(attribute, terraBiome); + if(entry == null) return null; + return handle.compose(attribute, parentSlots.get(attribute), entry) + .orElseGet(() -> AttributeEntry.override(attributes.resolve(attribute, terraBiome))); + } + + private static @Nullable ResourceKey villagerType(Attribute attribute, PackAttributes attributes, + com.dfsek.terra.api.world.biome.Biome terraBiome, String config, + AttributeReport report) { + Object encoded = resolveEncoded(attribute, attributes, terraBiome); + if(encoded == null) return null; + String key = attribute.getRegistryKey().toString(); + Identifier id; + try { + id = VanillaIds.identifier(RegistryKey.parseNamespaced(String.valueOf(encoded))); + } catch(IllegalArgumentException e) { + report.attributeSkipped(config, key, e.getMessage()); + return null; + } + ResourceKey type = ResourceKey.create(Registries.VILLAGER_TYPE, id); + if(BuiltInRegistries.VILLAGER_TYPE.containsKey(type)) return type; + report.attributeSkipped(config, key, "no such villager type \"" + id + "\""); + return null; + } + + + public record Built(Biome biome, ResourceKey villagerType) { } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactory.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactory.java new file mode 100644 index 000000000..cd0163fc6 --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactory.java @@ -0,0 +1,173 @@ +package com.dfsek.terra.mod.attribute; + +import net.minecraft.tags.TagKey; +import net.minecraft.world.attribute.EnvironmentAttributeMap; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.timeline.Timeline; +import org.jetbrains.annotations.Nullable; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +import com.dfsek.terra.api.util.range.ConstantRange; +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.DecodeException; +import com.dfsek.terra.api.world.attribute.PackAttributes; +import com.dfsek.terra.mod.generation.GenerationSettings; + + +public final class MinecraftDimensionFactory { + private static final String PACK_CONFIG = "pack.yml"; + private static final String ATTRIBUTES = "attributes"; + private static final String TIMELINES = "timelines"; + private static final String SCHEDULES = "schedules"; + private static final int DEFAULT_SPAWN_HEIGHT = 64; + + private final AttributeHandle handle; + private final VanillaContext context; + private final VanillaAttributeMaps maps; + + public MinecraftDimensionFactory(AttributeHandle handle, VanillaContext context) { + this.handle = Objects.requireNonNull(handle, "handle"); + this.context = Objects.requireNonNull(context, "context"); + this.maps = new VanillaAttributeMaps(handle, context); + } + + public DimensionType create(PackParents pack, @Nullable TagKey timelines) { + DimensionType parent = pack.dimension(); + PackAttributes attributes = pack.attributes(); + PackAttributeTable table = pack.table(); + AttributeReport report = pack.report(); + + Map original = (Map) VanillaCodecs.encode(DimensionType.DIRECT_CODEC, parent, context.ops()); + Map all = new LinkedHashMap<>(original); + if(attributes != null) { + for(PackAttributeTable.Field field : table.dimension()) set(all, field, attributes); + all.put(ATTRIBUTES, environment(parent.attributes(), pack, attributes, report)); + for(Attribute unapplied : table.unapplied()) { + if(attributes.entries().get(unapplied.key()).isPresent()) report.notApplied(unapplied.getRegistryKey().toString()); + } + } + if(timelines != null) all.put(TIMELINES, "#" + timelines.location()); + if(all.equals(original)) return copy(parent); + + DimensionType built; + try { + built = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, all, context.ops()); + } catch(DecodeException whole) { + built = fieldByField(parent, original, all, table.dimension(), attributes, timelines, report); + } + // Terra may encode a field in another number type, e.g. coordinate_scale as a float. + return original.equals(VanillaCodecs.encode(DimensionType.DIRECT_CODEC, built, context.ops())) ? copy(parent) : built; + } + + // A registry refuses the same value under a second key. + private static DimensionType copy(DimensionType parent) { + return new DimensionType(parent.hasFixedTime(), parent.hasSkyLight(), parent.hasCeiling(), parent.hasEnderDragonFight(), + parent.coordinateScale(), parent.minY(), parent.height(), parent.logicalHeight(), parent.infiniburn(), parent.ambientLight(), + parent.monsterSettings(), parent.skybox(), parent.cardinalLightType(), parent.attributes(), parent.timelines(), + parent.defaultClock()); + } + + private DimensionType fieldByField(DimensionType parent, Map original, Map all, + List fields, @Nullable PackAttributes attributes, + @Nullable TagKey timelines, AttributeReport report) { + DimensionType value = parent; + Map accepted = new LinkedHashMap<>(original); + if(all.containsKey(ATTRIBUTES)) { + Map trial = new LinkedHashMap<>(accepted); + trial.put(ATTRIBUTES, all.get(ATTRIBUTES)); + try { + value = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, trial, context.ops()); + accepted = trial; + } catch(DecodeException e) { + report.ignored(PACK_CONFIG, ATTRIBUTES, e.getMessage()); + } + } + if(attributes != null) { + for(PackAttributeTable.Field field : fields) { + if(attributes.entries().get(field.attribute().key()).isEmpty()) continue; + Map trial = new LinkedHashMap<>(accepted); + set(trial, field, attributes); + if(trial.equals(accepted)) continue; + try { + value = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, trial, context.ops()); + accepted = trial; + } catch(DecodeException e) { + report.attributeSkipped(PACK_CONFIG, field.attribute().getRegistryKey().toString(), e.getMessage()); + } + } + } + if(timelines != null) { + Map trial = new LinkedHashMap<>(accepted); + trial.put(TIMELINES, all.get(TIMELINES)); + try { + value = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, trial, context.ops()); + } catch(DecodeException e) { + report.ignored(PACK_CONFIG, SCHEDULES, e.getMessage()); + } + } + return value; + } + + private static void set(Map fields, PackAttributeTable.Field field, PackAttributes attributes) { + Object value = resolveEncoded(field.attribute(), attributes); + if(value == null) { + fields.remove(field.name()); + } else { + fields.put(field.name(), value); + } + } + + private static @Nullable Object resolveEncoded(Attribute attribute, PackAttributes attributes) { + T value = attributes.resolvePack(attribute); + return value == null ? null : attribute.type().encode(value); + } + + private Object environment(EnvironmentAttributeMap parent, PackParents pack, PackAttributes attributes, AttributeReport report) { + Map, AttributeEntry> entries = new LinkedHashMap<>(); + for(PackAttributeTable.Bound bound : pack.table().environment()) { + AttributeEntry entry = entry(bound.attribute(), pack.packEntries(), attributes); + if(entry != null) entries.put(bound.attribute(), entry); + } + EnvironmentAttributeMap map = entries.isEmpty() ? parent : maps.toVanilla(parent, entries, false, + (attribute, reason) -> report.attributeSkipped(PACK_CONFIG, attribute.getRegistryKey().toString(), reason)); + return VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, map, context.ops()); + } + + private @Nullable AttributeEntry entry(Attribute attribute, AttributeSlots packEntries, PackAttributes attributes) { + Optional> entry = attributes.entries().get(attribute.key()); + if(entry.isEmpty()) return null; + return handle.compose(attribute, packEntries.get(attribute), entry.get()) + .orElseGet(() -> AttributeEntry.override(attributes.resolvePack(attribute))); + } + + @SuppressWarnings("deprecation") // disableMobGeneration is still what vanilla's settings carry + public GenerationSettings generationSettings(PackParents pack, DimensionType dimension) { + PackAttributes attributes = pack.attributes(); + PackAttributeTable table = pack.table(); + int minY = dimension.minY(); + int height = dimension.height(); + int seaLevel = pack.generation().seaLevel(); + boolean mobGeneration = !pack.generation().disableMobGeneration(); + int spawnHeight = DEFAULT_SPAWN_HEIGHT; + if(attributes != null) { + seaLevel = intValue(table.seaLevel(), attributes, seaLevel); + spawnHeight = intValue(table.spawnHeight(), attributes, spawnHeight); + if(table.mobGeneration() != null && resolveEncoded(table.mobGeneration(), attributes) instanceof Boolean value) { + mobGeneration = value; + } + } + return new GenerationSettings(new ConstantRange(minY, minY + height), seaLevel, mobGeneration, spawnHeight); + } + + private static int intValue(@Nullable Attribute attribute, PackAttributes attributes, int fallback) { + if(attribute == null) return fallback; + return resolveEncoded(attribute, attributes) instanceof Number value ? value.intValue() : fallback; + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftTimelines.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftTimelines.java new file mode 100644 index 000000000..f512d27e8 --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftTimelines.java @@ -0,0 +1,270 @@ +package com.dfsek.terra.mod.attribute; + +import com.mojang.datafixers.util.Either; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderGetter; +import net.minecraft.core.HolderSet; +import net.minecraft.core.RegistrationInfo; +import net.minecraft.core.Registry; +import net.minecraft.core.WritableRegistry; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.TagKey; +import net.minecraft.world.clock.WorldClock; +import net.minecraft.world.timeline.Timeline; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +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.config.ConfigPack; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +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.ScheduleTrack; +import com.dfsek.terra.api.world.attribute.schedule.TimeMarker; + + +public final class MinecraftTimelines { + private static final Logger LOGGER = LoggerFactory.getLogger(MinecraftTimelines.class); + private static final String TERRA = "terra"; + private static final String EXISTS = "a timeline with this ID already exists"; + private static final String NO_TIMELINE = "no such timeline"; + private static final String NO_TAG = "no such timeline tag"; + private static final String PACK_CONFIG = "pack.yml"; + private static final String SCHEDULES = "schedules"; + private static final String NO_VALID_SCHEDULE = "no valid schedule; the parent's timelines are kept"; + + private static final Map, Pending> PENDING = new LinkedHashMap<>(); + // Holders stay unbound until the registry freezes. + private static final Map, Timeline> REGISTERED = new IdentityHashMap<>(); + + private MinecraftTimelines() { } + + public static @Nullable Timeline create(RegistryKey id, AttributeSchedule schedule, PackAttributeTable table, AttributeHandle handle, + VanillaContext context, AttributeReport report) { + String name = id.toString(); + ResourceKey clock; + try { + VanillaIds.identifier(id); + clock = ResourceKey.create(Registries.WORLD_CLOCK, VanillaIds.identifier(schedule.clock())); + for(RegistryKey marker : schedule.timeMarkers().keySet()) VanillaIds.identifier(marker); + } catch(IllegalArgumentException e) { + report.scheduleSkipped(name, e.getMessage()); + return null; + } + Optional> clocks = context.ops().getter(Registries.WORLD_CLOCK); + if(clocks.isEmpty() || clocks.get().get(clock).isEmpty()) { + report.scheduleSkipped(name, "no such clock \"" + clock.identifier() + "\""); + return null; + } + + try { + return VanillaCodecs.parse(Timeline.DIRECT_CODEC, handle.encodeSchedule(vanillaTracks(schedule, table, report)), + context.ops()); + } catch(DecodeException | IllegalArgumentException e) { + report.scheduleSkipped(name, e.getMessage()); + return null; + } + } + + private static AttributeSchedule vanillaTracks(AttributeSchedule schedule, PackAttributeTable table, AttributeReport report) { + Set> vanilla = new HashSet<>(); + for(PackAttributeTable.Bound bound : table.environment()) vanilla.add(bound.attribute()); + Map, ScheduleTrack> tracks = new LinkedHashMap<>(); + schedule.tracks().forEach((attribute, track) -> { + if(vanilla.contains(attribute)) { + tracks.put(attribute, track); + } else { + report.notApplied(attribute.getRegistryKey().toString()); + } + }); + if(tracks.size() == schedule.tracks().size()) return schedule; + return new AttributeSchedule(schedule.clock(), schedule.periodTicks(), tracks, schedule.timeMarkers()); + } + + public static void register(ConfigPack pack, PackParents parents, WritableRegistry timelines, AttributeHandle handle, + VanillaContext context) { + PackAttributes attributes = parents.attributes(); + if(attributes == null) return; + AttributeReport report = parents.report(); + for(Map.Entry entry : attributes.scheduleDefinitions().entrySet()) { + RegistryKey id = entry.getKey(); + Identifier location; + try { + location = VanillaIds.identifier(id); + } catch(IllegalArgumentException e) { + report.scheduleSkipped(id.toString(), e.getMessage()); + continue; + } + if(timelines.containsKey(location)) { + report.scheduleSkipped(id.toString(), EXISTS); + continue; + } + AttributeSchedule schedule = withoutClashingMarkers(id.toString(), entry.getValue(), timelines, report); + Timeline timeline = create(id, schedule, parents.table(), handle, context, report); + if(timeline == null) continue; + Holder.Reference holder = timelines.register(ResourceKey.create(Registries.TIMELINE, location), timeline, + RegistrationInfo.BUILT_IN); + synchronized(REGISTERED) { + REGISTERED.put(holder, timeline); + } + LOGGER.debug("Registered timeline {} from pack {}", location, pack.getID()); + } + } + + // Vanilla fails the whole load on a time marker its clock already has. + private static AttributeSchedule withoutClashingMarkers(String name, AttributeSchedule schedule, Registry timelines, + AttributeReport report) { + if(schedule.timeMarkers().isEmpty()) return schedule; + ResourceKey clock; + try { + clock = ResourceKey.create(Registries.WORLD_CLOCK, VanillaIds.identifier(schedule.clock())); + } catch(IllegalArgumentException e) { + return schedule; + } + Set defined = markersOn(clock, timelines); + Map kept = new LinkedHashMap<>(); + schedule.timeMarkers().forEach((id, marker) -> { + Identifier location; + try { + location = VanillaIds.identifier(id); + } catch(IllegalArgumentException e) { + kept.put(id, marker); + return; + } + if(defined.contains(location)) { + report.timeMarkerDropped(name, id.toString(), clock.identifier().toString()); + } else { + kept.put(id, marker); + } + }); + if(kept.size() == schedule.timeMarkers().size()) return schedule; + return new AttributeSchedule(schedule.clock(), schedule.periodTicks(), schedule.tracks(), kept); + } + + private static Set markersOn(ResourceKey clock, Registry timelines) { + Set markers = new HashSet<>(); + Optional> wanted = Optional.of(clock); + for(Holder.Reference holder : timelines.listElements().toList()) { + Timeline other; + if(holder.isBound()) { + other = holder.value(); + } else { + synchronized(REGISTERED) { + other = REGISTERED.get(holder); + } + } + if(other != null && other.clock().unwrapKey().equals(wanted)) { + other.registerTimeMarkers((key, marker) -> markers.add(key.identifier())); + } + } + return markers; + } + + public static @Nullable TagKey tagFor(ConfigPack pack, PackParents parents) { + PackAttributes attributes = parents.attributes(); + if(attributes == null || attributes.scheduleRefs().isEmpty()) return null; + AttributeReport report = parents.report(); + List>> refs = new ArrayList<>(); + for(com.dfsek.terra.api.util.generic.either.Either ref + : attributes.scheduleRefs()) { + Optional id = ref.getLeft(); + Optional tag = ref.getRight(); + try { + if(id.isPresent()) { + refs.add(Either.left(VanillaIds.identifier(id.get()))); + } else if(tag.isPresent()) { + refs.add(Either.right(TagKey.create(Registries.TIMELINE, VanillaIds.identifier(tag.get().key())))); + } + } catch(IllegalArgumentException e) { + report.scheduleSkipped(id.map(Object::toString).orElseGet(() -> String.valueOf(tag.orElse(null))), e.getMessage()); + } + } + TagKey key = TagKey.create(Registries.TIMELINE, + Identifier.fromNamespaceAndPath(TERRA, pack.getID().toLowerCase(Locale.ROOT))); + synchronized(PENDING) { + PENDING.put(key, new Pending(report, refs, parents.dimension().timelines())); + } + return key; + } + + /** + * Vanilla won't freeze a registry with an unbound tag. + */ + public static void bindPendingTags(WritableRegistry timelines) { + HolderGetter registration = timelines.createRegistrationLookup(); + Map, List>> unbound = new HashMap<>(); + synchronized(PENDING) { + for(TagKey key : PENDING.keySet()) { + if(!registration.getOrThrow(key).isBound()) unbound.put(key, List.of()); + } + } + timelines.bindTags(unbound); + } + + public static void fillTags(Map, List>> collect, Registry registry) { + synchronized(PENDING) { + PENDING.forEach((key, pending) -> { + Set> contents = new LinkedHashSet<>(); + for(Either> ref : pending.refs()) { + ref.ifLeft(id -> registry.get(id).ifPresentOrElse(contents::add, + () -> pending.report().scheduleSkipped(id.toString(), NO_TIMELINE))) + .ifRight(tag -> { + List> members = collect.get(tag); + if(members == null) { + pending.report().scheduleSkipped("#" + tag.location(), NO_TAG); + } else { + contents.addAll(members); + } + }); + } + if(contents.isEmpty()) { + pending.report().ignored(PACK_CONFIG, SCHEDULES, NO_VALID_SCHEDULE); + parentTimelines(pending.parent(), collect, registry, contents); + } + collect.put(key, List.copyOf(contents)); + }); + } + } + + private static void parentTimelines(HolderSet parent, Map, List>> collect, + Registry registry, Set> contents) { + parent.unwrap() + .ifLeft(tag -> contents.addAll(collect.getOrDefault(tag, List.of()))) + .ifRight(direct -> { + for(Holder holder : direct) holder.unwrapKey().flatMap(registry::get).ifPresent(contents::add); + }); + } + + static void clear() { + synchronized(PENDING) { + PENDING.clear(); + } + synchronized(REGISTERED) { + REGISTERED.clear(); + } + } + + + public record Pending(AttributeReport report, List>> refs, HolderSet parent) { + public Pending { + refs = List.copyOf(refs); + } + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackAttributeTable.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackAttributeTable.java new file mode 100644 index 000000000..dfafb53e4 --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackAttributeTable.java @@ -0,0 +1,165 @@ +package com.dfsek.terra.mod.attribute; + +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.world.attribute.EnvironmentAttribute; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +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; + + +public final class PackAttributeTable { + public static final PackAttributeTable EMPTY = new PackAttributeTable(List.of(), List.of(), List.of(), List.of(), null, null, null, + null, List.of()); + + private static final String MINECRAFT = "minecraft"; + private static final String TERRA = "terra"; + private static final String BIOME = "biome/"; + private static final String DIMENSION = "dimension/"; + private static final Set CLIMATE_FIELDS = Set.of("has_precipitation", "temperature", "temperature_modifier", "downfall"); + private static final Set EFFECTS_FIELDS = Set.of("water_color", "foliage_color", "dry_foliage_color", "grass_color", + "grass_color_modifier"); + private static final RegistryKey VILLAGER_TYPE = AttributeKey.parse("terra:biome/villager_type").getRegistryKey(); + private static final RegistryKey SEA_LEVEL = AttributeKey.parse("terra:world/sea_level").getRegistryKey(); + private static final RegistryKey SPAWN_HEIGHT = AttributeKey.parse("terra:world/spawn_height").getRegistryKey(); + private static final RegistryKey MOB_GENERATION = AttributeKey.parse("terra:world/mob_generation").getRegistryKey(); + + private final List environment; + private final List climate; + private final List effects; + private final List dimension; + private final @Nullable Attribute villagerType; + private final @Nullable Attribute seaLevel; + private final @Nullable Attribute spawnHeight; + private final @Nullable Attribute mobGeneration; + private final List> unapplied; + + private PackAttributeTable(List environment, List climate, List effects, List dimension, + @Nullable Attribute villagerType, @Nullable Attribute seaLevel, @Nullable Attribute spawnHeight, + @Nullable Attribute mobGeneration, List> unapplied) { + this.environment = environment; + this.climate = climate; + this.effects = effects; + this.dimension = dimension; + this.villagerType = villagerType; + this.seaLevel = seaLevel; + this.spawnHeight = spawnHeight; + this.mobGeneration = mobGeneration; + this.unapplied = unapplied; + } + + public static PackAttributeTable of(@Nullable Registry> registry) { + if(registry == null) return EMPTY; + Builder builder = new Builder(); + registry.forEach(builder::add); + return builder.build(); + } + + public List environment() { + return environment; + } + + public List climate() { + return climate; + } + + public List effects() { + return effects; + } + + public List dimension() { + return dimension; + } + + public @Nullable Attribute villagerType() { + return villagerType; + } + + public @Nullable Attribute seaLevel() { + return seaLevel; + } + + public @Nullable Attribute spawnHeight() { + return spawnHeight; + } + + public @Nullable Attribute mobGeneration() { + return mobGeneration; + } + + public List> unapplied() { + return unapplied; + } + + + public record Bound(Attribute attribute, EnvironmentAttribute vanilla) { } + + + public record Field(Attribute attribute, String name) { } + + + private static final class Builder { + private final List environment = new ArrayList<>(); + private final List climate = new ArrayList<>(); + private final List effects = new ArrayList<>(); + private final List dimension = new ArrayList<>(); + private final List> unapplied = new ArrayList<>(); + private @Nullable Attribute villagerType; + private @Nullable Attribute seaLevel; + private @Nullable Attribute spawnHeight; + private @Nullable Attribute mobGeneration; + + private void add(RegistryKey key, Attribute attribute) { + String namespace = key.getNamespace(); + String path = key.getID(); + if(namespace.equals(MINECRAFT)) { + // tryBuild returns null for the upper case Terra allows. + Identifier id = Identifier.tryBuild(namespace, path); + EnvironmentAttribute vanilla = id == null ? null : BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.getValue(id); + if(vanilla != null) { + environment.add(new Bound(attribute, vanilla)); + return; + } + } else if(namespace.equals(TERRA)) { + if(key.equals(VILLAGER_TYPE)) { + villagerType = attribute; + return; + } else if(key.equals(SEA_LEVEL)) { + seaLevel = attribute; + return; + } else if(key.equals(SPAWN_HEIGHT)) { + spawnHeight = attribute; + return; + } else if(key.equals(MOB_GENERATION)) { + mobGeneration = attribute; + return; + } else if(path.startsWith(BIOME)) { + String name = path.substring(BIOME.length()); + if(CLIMATE_FIELDS.contains(name)) { + climate.add(new Field(attribute, name)); + return; + } else if(EFFECTS_FIELDS.contains(name)) { + effects.add(new Field(attribute, name)); + return; + } + } else if(path.startsWith(DIMENSION) && path.length() > DIMENSION.length()) { + dimension.add(new Field(attribute, path.substring(DIMENSION.length()))); + return; + } + } + unapplied.add(attribute); + } + + private PackAttributeTable build() { + return new PackAttributeTable(List.copyOf(environment), List.copyOf(climate), List.copyOf(effects), List.copyOf(dimension), + villagerType, seaLevel, spawnHeight, mobGeneration, List.copyOf(unapplied)); + } + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackParents.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackParents.java new file mode 100644 index 000000000..4c08d03a3 --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackParents.java @@ -0,0 +1,87 @@ +package com.dfsek.terra.mod.attribute; + +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.world.attribute.PackAttributes; + + +public final class PackParents { + private final ConfigPack pack; + private final ResourceKey dimensionKey; + private final DimensionType dimension; + private final ResourceKey generationKey; + private final NoiseGeneratorSettings generation; + private final PackAttributeTable table; + private final AttributeSlots packEntries; + private final @Nullable PackAttributes attributes; + private final AttributeReport report; + private final VanillaParentReader reader; + private final Map, AttributeSlots> biomeEntries = new ConcurrentHashMap<>(); + + PackParents(ConfigPack pack, ResourceKey dimensionKey, DimensionType dimension, + ResourceKey generationKey, NoiseGeneratorSettings generation, PackAttributeTable table, + AttributeSlots packEntries, @Nullable PackAttributes attributes, AttributeReport report, VanillaParentReader reader) { + this.pack = pack; + this.dimensionKey = dimensionKey; + this.dimension = dimension; + this.generationKey = generationKey; + this.generation = generation; + this.table = table; + this.packEntries = packEntries; + this.attributes = attributes; + this.report = report; + this.reader = reader; + } + + public ResourceKey dimensionKey() { + return dimensionKey; + } + + public DimensionType dimension() { + return dimension; + } + + public ResourceKey generationKey() { + return generationKey; + } + + public NoiseGeneratorSettings generation() { + return generation; + } + + public PackAttributeTable table() { + return table; + } + + public AttributeSlots packEntries() { + return packEntries; + } + + public @Nullable PackAttributes attributes() { + return attributes; + } + + public AttributeReport report() { + return report; + } + + ConfigPack pack() { + return pack; + } + + VanillaParentReader reader() { + return reader; + } + + Map, AttributeSlots> biomeEntries() { + return biomeEntries; + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaAttributeMaps.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaAttributeMaps.java new file mode 100644 index 000000000..537b490bb --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaAttributeMaps.java @@ -0,0 +1,65 @@ +package com.dfsek.terra.mod.attribute; + +import com.mojang.serialization.Codec; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.attribute.EnvironmentAttributeMap; + +import java.util.Map; +import java.util.function.BiConsumer; + +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.DecodeException; + + +final class VanillaAttributeMaps { + private final AttributeHandle handle; + private final VanillaContext context; + + VanillaAttributeMaps(AttributeHandle handle, VanillaContext context) { + this.handle = handle; + this.context = context; + } + + void toTerra(EnvironmentAttributeMap map, PackAttributeTable table, AttributeEntry[] into, + BiConsumer, String> unreadable) { + if(map.keySet().isEmpty() || table.environment().isEmpty()) return; + Map encoded = (Map) VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, map, context.ops()); + for(PackAttributeTable.Bound bound : table.environment()) { + if(!map.contains(bound.vanilla())) continue; + Object raw = encoded.get(String.valueOf(BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.getKey(bound.vanilla()))); + Attribute attribute = bound.attribute(); + try { + into[attribute.index()] = handle.decodeEntry(attribute, raw, handle.plainContext()); + } catch(DecodeException e) { + unreadable.accept(attribute, e.getMessage()); + } + } + } + + EnvironmentAttributeMap toVanilla(EnvironmentAttributeMap base, Map, AttributeEntry> entries, boolean positionalOnly, + BiConsumer, String> skipped) { + Codec codec = positionalOnly + ? EnvironmentAttributeMap.CODEC_ONLY_POSITIONAL + : EnvironmentAttributeMap.CODEC; + EnvironmentAttributeMap.Builder builder = EnvironmentAttributeMap.builder().putAll(base); + for(Map.Entry, AttributeEntry> entry : entries.entrySet()) { + Attribute attribute = entry.getKey(); + AttributeEntry value = entry.getValue(); + if(value == null || (value.isOverride() && value.argument() == null)) continue; + Map single = Map.of(attribute.getRegistryKey().toString(), encode(attribute, value)); + try { + builder.putAll(VanillaCodecs.parse(codec, single, context.ops())); + } catch(DecodeException e) { + skipped.accept(attribute, e.getMessage()); + } + } + return builder.build(); + } + + @SuppressWarnings("unchecked") + private Object encode(Attribute attribute, AttributeEntry entry) { + return handle.encodeEntry(attribute, (AttributeEntry) entry); + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaCodecs.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaCodecs.java new file mode 100644 index 000000000..b0cd768c2 --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaCodecs.java @@ -0,0 +1,37 @@ +package com.dfsek.terra.mod.attribute; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import net.minecraft.resources.RegistryOps; + +import java.util.Optional; + +import com.dfsek.terra.api.world.attribute.DecodeException; + + +public final class VanillaCodecs { + private static final String CAUGHT = "Caught exception decoding "; + + private VanillaCodecs() { } + + public static Object encode(Codec codec, V value, RegistryOps ops) { + return codec.encodeStart(ops, value).getOrThrow(IllegalStateException::new); + } + + public static V parse(Codec codec, Object raw, RegistryOps ops) throws DecodeException { + DataResult result = codec.parse(ops, raw); + Optional> error = result.error(); + if(error.isPresent()) { + String message = error.get().message(); + // ExtraCodecs.catchDecoderException's form; only the outermost one names raw itself. + String caught = CAUGHT + raw + ": "; + throw new DecodeException(lowerFirst(message.startsWith(caught) ? message.substring(caught.length()) : message)); + } + return result.getOrThrow(); + } + + private static String lowerFirst(String reason) { + if(reason.isEmpty()) return reason; + return Character.toLowerCase(reason.charAt(0)) + reason.substring(1); + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaContext.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaContext.java new file mode 100644 index 000000000..48bfeac6b --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaContext.java @@ -0,0 +1,88 @@ +package com.dfsek.terra.mod.attribute; + +import com.mojang.serialization.JavaOps; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderGetter; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.HolderOwner; +import net.minecraft.core.HolderSet; +import net.minecraft.core.Registry; +import net.minecraft.core.WritableRegistry; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.TagKey; +import net.minecraft.world.entity.npc.villager.VillagerType; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; + + +public record VanillaContext(RegistryOps ops, HolderGetter dimensionTypes, + HolderGetter noiseSettings, HolderGetter biomes, + Function, @Nullable ResourceKey> villagerTypes) { + public static VanillaContext of(HolderLookup.Provider registries, + Function, @Nullable ResourceKey> villagerTypes) { + return new VanillaContext(registries.createSerializationContext(JavaOps.INSTANCE), + registries.lookupOrThrow(Registries.DIMENSION_TYPE), + registries.lookupOrThrow(Registries.NOISE_SETTINGS), + registries.lookupOrThrow(Registries.BIOME), + villagerTypes); + } + + /** + * {@code context} must be the list vanilla's loader received: until the load finishes, only it has the static registries' + * new tags. + */ + public static VanillaContext ofLoad(List> loaded, List> context, + Function, @Nullable ResourceKey> villagerTypes) { + Map, HolderGetter> getters = new HashMap<>(); + // Vanilla's order: the context first, then the registries being loaded over it. + for(HolderLookup.RegistryLookup lookup : context) getters.put(lookup.key(), lookup); + for(WritableRegistry registry : loaded) getters.put(registry.key(), loadGetter(registry)); + RegistryOps.RegistryInfoLookup lookup = new RegistryOps.RegistryInfoLookup() { + @Override + @SuppressWarnings("unchecked") + public Optional> lookup(ResourceKey> key) { + return Optional.ofNullable((HolderGetter) getters.get(key)); + } + }; + return new VanillaContext(RegistryOps.create(JavaOps.INSTANCE, lookup), + loadedGetter(lookup, Registries.DIMENSION_TYPE), + loadedGetter(lookup, Registries.NOISE_SETTINGS), + loadedGetter(lookup, Registries.BIOME), + villagerTypes); + } + + // The registration lookup makes a holder for any key, and an unbound one fails Registry.freeze() for the whole load. + private static HolderGetter loadGetter(WritableRegistry registry) { + HolderGetter registration = registry.createRegistrationLookup(); + return new HolderGetter<>() { + @Override + public Optional> get(ResourceKey key) { + return registry.get(key.identifier()); + } + + @Override + public Optional> get(TagKey key) { + return registration.get(key); + } + + @Override + public boolean canSerialize(HolderOwner owner) { + return registration.canSerialize(owner); + } + }; + } + + private static HolderGetter loadedGetter(RegistryOps.RegistryInfoLookup lookup, ResourceKey> key) { + return lookup.lookup(key).orElseThrow(() -> new IllegalArgumentException("registry " + key.identifier() + " is not loaded")); + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaIds.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaIds.java new file mode 100644 index 000000000..5bb5f35dc --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaIds.java @@ -0,0 +1,19 @@ +package com.dfsek.terra.mod.attribute; + +import net.minecraft.resources.Identifier; + +import com.dfsek.terra.api.registry.key.RegistryKey; + + +public final class VanillaIds { + private VanillaIds() { } + + public static Identifier identifier(RegistryKey key) { + Identifier identifier = Identifier.tryBuild(key.getNamespace(), key.getID()); + if(identifier == null) { + throw new IllegalArgumentException( + "invalid ID \"" + key + "\": Minecraft IDs use only lower-case a-z, 0-9, _, . and -, and / in the path"); + } + return identifier; + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaParentReader.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaParentReader.java new file mode 100644 index 000000000..e1400c0de --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaParentReader.java @@ -0,0 +1,101 @@ +package com.dfsek.terra.mod.attribute; + +import com.mojang.serialization.Codec; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.entity.npc.villager.VillagerType; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeSpecialEffects; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; + +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; + +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.DecodeException; + + +final class VanillaParentReader { + private static final String DEFAULT_CLOCK = "default_clock"; + + private final AttributeHandle handle; + private final VanillaContext context; + private final VanillaAttributeMaps maps; + + VanillaParentReader(AttributeHandle handle, VanillaContext context) { + this.handle = handle; + this.context = context; + this.maps = new VanillaAttributeMaps(handle, context); + } + + AttributeSlots biome(ResourceKey key, Biome biome, PackAttributeTable table, BiConsumer, String> unreadable) { + AttributeEntry[] slots = slots(); + maps.toTerra(biome.getAttributes(), table, slots, unreadable); + if(!table.climate().isEmpty()) { + readFields(encode(Biome.ClimateSettings.CODEC.codec(), biome.climateSettings), table.climate(), slots, unreadable); + } + if(!table.effects().isEmpty()) { + readFields(encode(BiomeSpecialEffects.CODEC, biome.getSpecialEffects()), table.effects(), slots, unreadable); + } + Attribute villagerType = table.villagerType(); + if(villagerType != null) { + ResourceKey type = context.villagerTypes().apply(key); + if(type != null) read(villagerType, type.identifier().toString(), slots, unreadable); + } + return AttributeSlots.of(slots); + } + + AttributeSlots dimension(DimensionType type, PackAttributeTable table, BiConsumer, String> unreadable) { + AttributeEntry[] slots = slots(); + maps.toTerra(type.attributes(), table, slots, unreadable); + if(!table.dimension().isEmpty()) { + Map fields = encode(DimensionType.DIRECT_CODEC, type); + for(PackAttributeTable.Field field : table.dimension()) { + Object raw = fields.get(field.name()); + if(raw != null) { + read(field.attribute(), raw, slots, unreadable); + } else if(field.name().equals(DEFAULT_CLOCK)) { + slots[field.attribute().index()] = AttributeEntry.override(null); + } + } + } + return AttributeSlots.of(slots); + } + + @SuppressWarnings("deprecation") // disableMobGeneration is still what vanilla's settings carry + AttributeSlots generation(NoiseGeneratorSettings settings, PackAttributeTable table) { + AttributeEntry[] slots = slots(); + Attribute seaLevel = table.seaLevel(); + if(seaLevel != null) read(seaLevel, settings.seaLevel(), slots, (attribute, reason) -> { }); + Attribute mobGeneration = table.mobGeneration(); + if(mobGeneration != null) read(mobGeneration, !settings.disableMobGeneration(), slots, (attribute, reason) -> { }); + return AttributeSlots.of(slots); + } + + private AttributeEntry[] slots() { + return new AttributeEntry[handle.attributeCount()]; + } + + private void readFields(Map fields, List table, AttributeEntry[] slots, + BiConsumer, String> unreadable) { + for(PackAttributeTable.Field field : table) { + Object raw = fields.get(field.name()); + if(raw != null) read(field.attribute(), raw, slots, unreadable); + } + } + + private void read(Attribute attribute, Object raw, AttributeEntry[] slots, BiConsumer, String> unreadable) { + try { + slots[attribute.index()] = AttributeEntry.override(attribute.type().decode(raw, handle.plainContext())); + } catch(DecodeException e) { + unreadable.accept(attribute, e.getMessage()); + } + } + + private Map encode(Codec codec, V value) { + return (Map) VanillaCodecs.encode(codec, value, context.ops()); + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeAdditionsSoundTemplate.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeAdditionsSoundTemplate.java deleted file mode 100644 index 6ff620d53..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeAdditionsSoundTemplate.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.dfsek.terra.mod.config; - -import com.dfsek.tectonic.api.config.template.annotations.Default; -import com.dfsek.tectonic.api.config.template.annotations.Value; -import com.dfsek.tectonic.api.config.template.object.ObjectTemplate; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.world.attribute.AmbientAdditionsSettings; - - -public class BiomeAdditionsSoundTemplate implements ObjectTemplate { - @Value("sound") - @Default - private SoundEvent sound = null; - - @Value("sound-chance") - @Default - private Double soundChance = null; - - @Override - public AmbientAdditionsSettings get() { - if(sound == null || soundChance == null) { - return null; - } else { - return new AmbientAdditionsSettings(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(sound), soundChance); - } - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeMoodSoundTemplate.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeMoodSoundTemplate.java deleted file mode 100644 index 3b76a7a2b..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeMoodSoundTemplate.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.dfsek.terra.mod.config; - -import com.dfsek.tectonic.api.config.template.annotations.Default; -import com.dfsek.tectonic.api.config.template.annotations.Value; -import com.dfsek.tectonic.api.config.template.object.ObjectTemplate; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.world.attribute.AmbientMoodSettings; - - -public class BiomeMoodSoundTemplate implements ObjectTemplate { - @Value("sound") - @Default - private SoundEvent sound = null; - - @Value("cultivation-ticks") - @Default - private Integer soundCultivationTicks = null; - - @Value("spawn-range") - @Default - private Integer soundSpawnRange = null; - - @Value("extra-distance") - @Default - private Double soundExtraDistance = null; - - @Override - public AmbientMoodSettings get() { - if(sound == null || soundCultivationTicks == null || soundSpawnRange == null || soundExtraDistance == null) { - return null; - } else { - return new AmbientMoodSettings(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(sound), soundCultivationTicks, soundSpawnRange, soundExtraDistance); - } - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeParticleConfigTemplate.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeParticleConfigTemplate.java deleted file mode 100644 index e1ace6607..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeParticleConfigTemplate.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.dfsek.terra.mod.config; - -import com.dfsek.tectonic.api.config.template.annotations.Default; -import com.dfsek.tectonic.api.config.template.annotations.Value; -import com.dfsek.tectonic.api.config.template.object.ObjectTemplate; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.commands.arguments.ParticleArgument; -import net.minecraft.core.HolderLookup; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.world.attribute.AmbientParticle; - -import java.util.stream.Stream; - - -public class BiomeParticleConfigTemplate implements ObjectTemplate { - @Value("particle") - @Default - private String particle = null; - - @Value("probability") - @Default - private Float probability = 0.1f; - - @Override - public AmbientParticle get() { - if(particle == null) { - return null; - } - - try { - return new AmbientParticle( - ParticleArgument.readParticle(new StringReader(particle), - HolderLookup.Provider.create(Stream.of(BuiltInRegistries.PARTICLE_TYPE))), - probability); - } catch(CommandSyntaxException e) { - throw new RuntimeException(e); - } - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/EntityTypeTemplate.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/EntityTypeTemplate.java deleted file mode 100644 index 88c3ed1d9..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/EntityTypeTemplate.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.dfsek.terra.mod.config; - -import com.dfsek.tectonic.api.config.template.annotations.Default; -import com.dfsek.tectonic.api.config.template.annotations.Value; -import com.dfsek.tectonic.api.config.template.object.ObjectTemplate; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.Identifier; -import net.minecraft.world.entity.EntityType; - - -public class EntityTypeTemplate implements ObjectTemplate> { - @Value("id") - @Default - private Identifier id = null; - - @Override - public EntityType get() { - return BuiltInRegistries.ENTITY_TYPE.get(id).orElseThrow().value(); - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/MonsterSettingsConfig.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/MonsterSettingsConfig.java deleted file mode 100644 index 4f5740e3c..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/MonsterSettingsConfig.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.dfsek.terra.mod.config; - -import com.dfsek.tectonic.api.config.template.annotations.Default; -import com.dfsek.tectonic.api.config.template.annotations.Value; -import com.dfsek.tectonic.api.config.template.object.ObjectTemplate; - -import com.dfsek.terra.api.util.range.Range; - - -public class MonsterSettingsConfig implements ObjectTemplate { - @Value("piglin-safe") - @Default - private Boolean piglinSafe = null; - - @Value("has-raids") - @Default - private Boolean hasRaids = null; - - @Value("monster-spawn-light") - @Default - private Range monsterSpawnLight = null; - - @Value("monster-spawn-block-light-limit") - @Default - private Integer monsterSpawnBlockLightLimit = null; - - public Boolean getPiglinSafe() { - return piglinSafe; - } - - public Boolean getHasRaids() { - return hasRaids; - } - - public Range getMonsterSpawnLight() { - return monsterSpawnLight; - } - - public Integer getMonsterSpawnBlockLightLimit() { - return monsterSpawnBlockLightLimit; - } - - - @Override - public MonsterSettingsConfig get() { - return this; - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/MusicSoundTemplate.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/MusicSoundTemplate.java deleted file mode 100644 index 92c8f91da..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/MusicSoundTemplate.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.dfsek.terra.mod.config; - -import com.dfsek.tectonic.api.config.template.annotations.Default; -import com.dfsek.tectonic.api.config.template.annotations.Value; -import com.dfsek.tectonic.api.config.template.object.ObjectTemplate; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.sounds.Music; -import net.minecraft.sounds.SoundEvent; - -import com.dfsek.terra.api.util.range.Range; - - -public class MusicSoundTemplate implements ObjectTemplate { - @Value("sound") - @Default - private SoundEvent sound = null; - - @Value("delay") - @Default - private Range delay = null; - - @Value("replace-current-music") - @Default - private Boolean replaceCurrentMusic = null; - - @Override - public Music get() { - if(sound == null || delay == null || replaceCurrentMusic == null) { - return null; - } else { - return new Music(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(sound), delay.getMin(), delay.getMax(), replaceCurrentMusic); - } - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/ProtoPlatformBiome.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/ProtoPlatformBiome.java index 980257bfe..e2bc1703f 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/ProtoPlatformBiome.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/ProtoPlatformBiome.java @@ -26,6 +26,7 @@ import net.minecraft.world.level.biome.Biome; import java.util.Objects; import com.dfsek.terra.api.world.biome.PlatformBiome; +import com.dfsek.terra.mod.attribute.AttributeSlots; import com.dfsek.terra.mod.util.MinecraftUtil; @@ -34,6 +35,9 @@ public class ProtoPlatformBiome implements PlatformBiome { private Holder delegate; + // Volatile for generation threads; AttributeSlots is immutable. + private volatile AttributeSlots parentEntries = AttributeSlots.EMPTY; + public ProtoPlatformBiome(Identifier identifier) { this.identifier = identifier; } @@ -54,4 +58,12 @@ public class ProtoPlatformBiome implements PlatformBiome { public void setDelegate(Holder delegate) { this.delegate = Objects.requireNonNull(delegate); } + + public AttributeSlots parentEntries() { + return parentEntries; + } + + public void setParentEntries(AttributeSlots parentEntries) { + this.parentEntries = Objects.requireNonNull(parentEntries); + } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SoundEventTemplate.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SoundEventTemplate.java deleted file mode 100644 index d312c8b91..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SoundEventTemplate.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.dfsek.terra.mod.config; - -import com.dfsek.tectonic.api.config.template.annotations.Default; -import com.dfsek.tectonic.api.config.template.annotations.Value; -import com.dfsek.tectonic.api.config.template.object.ObjectTemplate; -import net.minecraft.resources.Identifier; -import net.minecraft.sounds.SoundEvent; - - -public class SoundEventTemplate implements ObjectTemplate { - @Value("id") - @Default - private Identifier id = null; - - @Value("distance-to-travel") - @Default - private Float distanceToTravel = null; - - @Override - public SoundEvent get() { - if(id == null) { - return null; - } else if(distanceToTravel == null) { - return SoundEvent.createVariableRangeEvent(id); - } else { - return SoundEvent.createFixedRangeEvent(id, distanceToTravel); - } - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnCostConfig.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnCostConfig.java deleted file mode 100644 index 2f2339aed..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnCostConfig.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.dfsek.terra.mod.config; - -import com.dfsek.tectonic.api.config.template.annotations.Default; -import com.dfsek.tectonic.api.config.template.annotations.Value; -import com.dfsek.tectonic.api.config.template.object.ObjectTemplate; -import net.minecraft.world.entity.EntityType; - - -public class SpawnCostConfig implements ObjectTemplate { - @Value("type") - @Default - private EntityType type = null; - - @Value("mass") - @Default - private Double mass = null; - - @Value("gravity") - @Default - private Double gravity = null; - - public EntityType getType() { - return type; - } - - public Double getMass() { - return mass; - } - - public Double getGravity() { - return gravity; - } - - @Override - public SpawnCostConfig get() { - return this; - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnEntryConfig.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnEntryConfig.java deleted file mode 100644 index e1cae45d5..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnEntryConfig.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.dfsek.terra.mod.config; - -import com.dfsek.tectonic.api.config.template.annotations.Default; -import com.dfsek.tectonic.api.config.template.annotations.Value; -import com.dfsek.tectonic.api.config.template.object.ObjectTemplate; -import net.minecraft.util.valueproviders.UniformInt; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.level.biome.MobSpawnSettings.SpawnerData; - -import com.dfsek.terra.api.util.range.Range; - - -public class SpawnEntryConfig implements ObjectTemplate { - @Value("type") - @Default - private EntityType type = null; - - @Value("weight") - @Default - private Integer weight = null; - - @Value("group-size") - @Default - private Range groupSize = null; - - public Integer getWeight() { - return weight; - } - - public SpawnerData getSpawnEntry() { - return new SpawnerData(type, UniformInt.of(groupSize.getMin(), groupSize.getMax())); - } - - @Override - public SpawnEntryConfig get() { - return this; - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnSettingsTemplate.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnSettingsTemplate.java deleted file mode 100644 index bd3bbbb7f..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnSettingsTemplate.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.dfsek.terra.mod.config; - -import com.dfsek.tectonic.api.config.template.annotations.Default; -import com.dfsek.tectonic.api.config.template.annotations.Value; -import com.dfsek.tectonic.api.config.template.object.ObjectTemplate; -import net.minecraft.world.entity.MobCategory; -import net.minecraft.world.level.biome.MobSpawnSettings; - -import java.util.List; - - -public class SpawnSettingsTemplate implements ObjectTemplate { - @Value("spawns") - @Default - private List spawns = null; - - @Value("costs") - @Default - private List costs = null; - - @Value("probability") - @Default - private Float probability = null; - - @Override - public MobSpawnSettings get() { - MobSpawnSettings.Builder builder = new MobSpawnSettings.Builder(); - for(SpawnTypeConfig spawn : spawns) { - MobCategory group = spawn.getGroup(); - for(SpawnEntryConfig entry : spawn.getEntries()) { - MobSpawnSettings.SpawnerData spawnEntry = entry.getSpawnEntry(); - builder.addSpawn(spawnEntry.type(), group, entry.getWeight(), spawnEntry.count()); - } - } - for(SpawnCostConfig cost : costs) { - builder.addMobSpawnCost(cost.getType(), cost.getMass(), cost.getGravity()); - } - // TODO: environment attributes. Creature generation probability is now the - // gameplay/creature_world_gen_spawn_probability biome attribute, so it is ignored here. - - return builder.build(); - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnTypeConfig.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnTypeConfig.java deleted file mode 100644 index 676fa2476..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnTypeConfig.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.dfsek.terra.mod.config; - -import com.dfsek.tectonic.api.config.template.annotations.Default; -import com.dfsek.tectonic.api.config.template.annotations.Value; -import com.dfsek.tectonic.api.config.template.object.ObjectTemplate; -import net.minecraft.world.entity.MobCategory; - -import java.util.List; - - -public class SpawnTypeConfig implements ObjectTemplate { - @Value("group") - @Default - private MobCategory group = null; - - @Value("entries") - @Default - private List entries = null; - - public MobCategory getGroup() { - return group; - } - - public List getEntries() { - return entries; - } - - @Override - public SpawnTypeConfig get() { - return this; - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/VanillaBiomeProperties.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/VanillaBiomeProperties.java deleted file mode 100644 index 910243a58..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/VanillaBiomeProperties.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.dfsek.terra.mod.config; - -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 net.minecraft.resources.ResourceKey; -import net.minecraft.sounds.Music; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.world.attribute.AmbientAdditionsSettings; -import net.minecraft.world.attribute.AmbientMoodSettings; -import net.minecraft.world.attribute.AmbientParticle; -import net.minecraft.world.entity.npc.villager.VillagerType; -import net.minecraft.world.level.biome.Biome.TemperatureModifier; -import net.minecraft.world.level.biome.BiomeSpecialEffects.GrassColorModifier; -import net.minecraft.world.level.biome.MobSpawnSettings; - -import com.dfsek.terra.api.properties.Properties; - - -public class VanillaBiomeProperties implements ConfigTemplate, Properties { - @Value("colors.grass") - @Default - private Integer grassColor = null; - - @Value("colors.fog") - @Default - private Integer fogColor = null; - - @Value("colors.water") - @Default - private Integer waterColor = null; - - @Value("colors.water-fog") - @Default - private Integer waterFogColor = null; - - @Value("colors.foliage") - @Default - private Integer foliageColor = null; - - @Value("colors.dry-foliage") - @Default - private Integer dryFoliageColor = null; - - @Value("colors.sky") - @Default - private Integer skyColor = null; - - @Value("colors.modifier") - @Default - private GrassColorModifier grassColorModifier = null; - - @Value("particles") - @Default - private AmbientParticle particleConfig = null; - - @Value("climate.precipitation") - @Default - private Boolean precipitation = null; - - @Value("climate.temperature") - @Default - private Float temperature = null; - - @Value("climate.temperature-modifier") - @Default - private TemperatureModifier temperatureModifier = null; - - @Value("climate.downfall") - @Default - private Float downfall = null; - - @Value("sound.loop-sound.sound") - @Default - private SoundEvent loopSound = null; - - @Value("sound.mood-sound") - @Default - private AmbientMoodSettings moodSound = null; - - @Value("sound.additions-sound") - @Default - private AmbientAdditionsSettings additionsSound = null; - - @Value("sound.music") - @Default - private Music music = null; - - @Value("sound.music-volume") - @Default - private Float musicVolume = null; - - @Value("spawning") - @Default - private MobSpawnSettings spawnSettings = null; - - @Value("villager-type") - @Default - private - ResourceKey villagerType = null; - - public Integer getGrassColor() { - return grassColor; - } - - public Integer getFogColor() { - return fogColor; - } - - public Integer getWaterColor() { - return waterColor; - } - - public Integer getWaterFogColor() { - return waterFogColor; - } - - public Integer getFoliageColor() { - return foliageColor; - } - - public Integer getDryFoliageColor() { - return dryFoliageColor; - } - - public Integer getSkyColor() { - return skyColor; - } - - public GrassColorModifier getGrassColorModifier() { - return grassColorModifier; - } - - public AmbientParticle getParticleConfig() { - return particleConfig; - } - - public Boolean getPrecipitation() { - return precipitation; - } - - public Float getTemperature() { - return temperature; - } - - public TemperatureModifier getTemperatureModifier() { - return temperatureModifier; - } - - public Float getDownfall() { - return downfall; - } - - public SoundEvent getLoopSound() { - return loopSound; - } - - public AmbientMoodSettings getMoodSound() { - return moodSound; - } - - public AmbientAdditionsSettings getAdditionsSound() { - return additionsSound; - } - - public Music getMusic() { - return music; - } - - public Float getMusicVolume() { - return musicVolume; - } - - public MobSpawnSettings getSpawnSettings() { - return spawnSettings; - } - - public ResourceKey getVillagerType() { - return villagerType; - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/VanillaWorldProperties.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/VanillaWorldProperties.java deleted file mode 100644 index 58a7c7cab..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/VanillaWorldProperties.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.dfsek.terra.mod.config; - -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 net.minecraft.resources.Identifier; - -import com.dfsek.terra.api.properties.Properties; -import com.dfsek.terra.api.util.range.ConstantRange; -import com.dfsek.terra.api.util.range.Range; - - -public class VanillaWorldProperties implements ConfigTemplate, Properties { - - @Value("vanilla") - @Default - private String vanillaDimension = "minecraft:overworld"; - - @Value("vanilla-generation") - @Default - private String vanillaGeneration = vanillaDimension; - - @Value("minecraft.fixed-time") - @Default - private Long fixedTime = null; - - @Value("minecraft.has-sky-light") - @Default - private Boolean hasSkyLight = null; - - @Value("minecraft.has-ceiling") - @Default - private Boolean hasCeiling = null; - - @Value("minecraft.ultra-warm") - @Default - private Boolean ultraWarm = null; - - @Value("minecraft.natural") - @Default - private Boolean natural = null; - - @Value("minecraft.coordinate-scale") - @Default - private Double coordinateScale = null; - - @Value("minecraft.bed-works") - @Default - private Boolean bedWorks = null; - - @Value("minecraft.respawn-anchor-works") - @Default - private Boolean respawnAnchorWorks = null; - - @Value("minecraft.height") - @Default - private Range height = null; - - @Value("minecraft.height.logical") - @Default - private Integer logicalHeight = null; - - @Value("minecraft.infiniburn") - @Default - private Identifier infiniburn = null; - - @Value("minecraft.effects") - @Default - private Identifier effects = null; - - @Value("minecraft.ambient-light") - @Default - private Float ambientLight = null; - - @Value("minecraft.cloud-height") - @Default - private Integer cloudHeight = null; - - @Value("minecraft.monster-settings") - @Default - private MonsterSettingsConfig monsterSettings = null; - - @Value("minecraft.mob-generation") - @Default - private Boolean mobGeneration = null; - - @Value("minecraft.sealevel") - @Default - private Integer sealevel = null; - - @Value("minecraft.spawn-height") - @Default - private Integer spawnHeight = 64; - - public String getVanillaDimension() { - return vanillaDimension; - } - - public String getVanillaGeneration() { - return vanillaGeneration; - } - - public Long getFixedTime() { - return fixedTime; - } - - public Boolean getHasSkyLight() { - return hasSkyLight; - } - - public Boolean getHasCeiling() { - return hasCeiling; - } - - public Boolean getUltraWarm() { - return ultraWarm; - } - - public Boolean getNatural() { - return natural; - } - - public Double getCoordinateScale() { - return coordinateScale; - } - - public Boolean getBedWorks() { - return bedWorks; - } - - public Boolean getRespawnAnchorWorks() { - return respawnAnchorWorks; - } - - public ConstantRange getHeight() { - //TODO THIS IS BAD - if(height != null) { - return new ConstantRange(height.getMin(), height.getMax()); - } else { - return null; - } - } - - public Integer getLogicalHeight() { - return logicalHeight; - } - - public Identifier getInfiniburn() { - return infiniburn; - } - - public Identifier getEffects() { - return effects; - } - - public Float getAmbientLight() { - return ambientLight; - } - - public Integer getCloudHeight() { - return cloudHeight; - } - - public MonsterSettingsConfig getMonsterSettings() { - return monsterSettings; - } - - public Boolean getMobGeneration() { - return mobGeneration; - } - - public Integer getSealevel() { - return sealevel; - } - - public Integer getSpawnHeight() { - return spawnHeight; - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/VillagerTypeTemplate.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/VillagerTypeTemplate.java deleted file mode 100644 index f50d8963e..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/VillagerTypeTemplate.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.dfsek.terra.mod.config; - -import com.dfsek.tectonic.api.config.template.annotations.Default; -import com.dfsek.tectonic.api.config.template.annotations.Value; -import com.dfsek.tectonic.api.config.template.object.ObjectTemplate; -import net.minecraft.core.registries.Registries; -import net.minecraft.resources.Identifier; -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.entity.npc.villager.VillagerType; - - -public class VillagerTypeTemplate implements ObjectTemplate> { - @Value("id") - @Default - private Identifier id = null; - - @Override - public ResourceKey get() { - return ResourceKey.create(Registries.VILLAGER_TYPE, id); - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/BiomeAccessor.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/BiomeAccessor.java deleted file mode 100644 index 3af401b10..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/BiomeAccessor.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.dfsek.terra.mod.mixin.access; - -import net.minecraft.world.level.biome.Biome; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - - -@Mixin(Biome.class) -public interface BiomeAccessor { - @Accessor("climateSettings") - Biome.ClimateSettings getWeather(); -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/lifecycle/ReloadableServerResourcesMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/lifecycle/ReloadableServerResourcesMixin.java index f98731561..b7ba1b81f 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/lifecycle/ReloadableServerResourcesMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/lifecycle/ReloadableServerResourcesMixin.java @@ -48,6 +48,8 @@ public class ReloadableServerResourcesMixin { RegistryAccess.Frozen dynamicRegistryManager = dynamicRegistries.compositeAccess(); TagUtil.registerWorldPresetTags(dynamicRegistryManager.lookupOrThrow(Registries.WORLD_PRESET)); + TagUtil.registerTimelineTags(dynamicRegistryManager.lookupOrThrow(Registries.TIMELINE)); + Registry biomeRegistry = dynamicRegistryManager.lookupOrThrow(Registries.BIOME); TagUtil.registerBiomeTags(biomeRegistry); MinecraftUtil.registerFlora(biomeRegistry); diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/BiomeUtil.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/BiomeUtil.java index c035e45f9..54079e095 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/BiomeUtil.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/BiomeUtil.java @@ -1,7 +1,6 @@ package com.dfsek.terra.mod.util; import net.minecraft.resources.Identifier; -import net.minecraft.world.level.biome.Biome; import java.util.HashMap; import java.util.List; @@ -9,16 +8,14 @@ import java.util.Locale; import java.util.Map; import com.dfsek.terra.api.config.ConfigPack; -import com.dfsek.terra.mod.config.VanillaBiomeProperties; public class BiomeUtil { public static final Map> TERRA_BIOME_MAP = new HashMap<>(); - public static Biome createBiome(Biome vanilla, VanillaBiomeProperties vanillaBiomeProperties) { - throw new UnsupportedOperationException("TODO: environment attributes"); - } + public static final Map + TERRA_BIOME_PLATFORM_TAGS = new HashMap<>(); public static String createBiomeID(ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey biomeID) { return pack.getID() @@ -28,4 +25,8 @@ public class BiomeUtil { public static Map> getTerraBiomeMap() { return Map.copyOf(TERRA_BIOME_MAP); } + + public static Map getTerraBiomePlatformTags() { + return Map.copyOf(TERRA_BIOME_PLATFORM_TAGS); + } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/DimensionUtil.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/DimensionUtil.java deleted file mode 100644 index 3f1f93bde..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/DimensionUtil.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.dfsek.terra.mod.util; - -import net.minecraft.world.level.dimension.DimensionType; -import net.minecraft.world.level.dimension.DimensionType.MonsterSettings; -import org.jetbrains.annotations.NotNull; - -import com.dfsek.terra.mod.ModPlatform; -import com.dfsek.terra.mod.config.MonsterSettingsConfig; -import com.dfsek.terra.mod.config.VanillaWorldProperties; - - -public class DimensionUtil { - public static DimensionType createDimension(VanillaWorldProperties vanillaWorldProperties, DimensionType defaultDimension, - ModPlatform platform) { - throw new UnsupportedOperationException("TODO: environment attributes"); - } - - @NotNull - private static MonsterSettings getMonsterSettings(DimensionType defaultDimension, MonsterSettingsConfig monsterSettingsConfig) { - throw new UnsupportedOperationException("TODO: environment attributes"); - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/PresetUtil.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/PresetUtil.java index 9f1c064fa..8fe0a3307 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/PresetUtil.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/PresetUtil.java @@ -28,9 +28,13 @@ import java.util.Locale; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.config.MetaPack; import com.dfsek.terra.api.util.generic.pair.Pair; -import com.dfsek.terra.api.util.range.ConstantRange; import com.dfsek.terra.mod.ModPlatform; -import com.dfsek.terra.mod.config.VanillaWorldProperties; +import com.dfsek.terra.mod.attribute.AttributeReport; +import com.dfsek.terra.mod.attribute.MinecraftAttributeParents; +import com.dfsek.terra.mod.attribute.MinecraftDimensionFactory; +import com.dfsek.terra.mod.attribute.MinecraftTimelines; +import com.dfsek.terra.mod.attribute.PackParents; +import com.dfsek.terra.mod.attribute.VanillaContext; import com.dfsek.terra.mod.generation.GenerationSettings; import com.dfsek.terra.mod.generation.MinecraftChunkGeneratorWrapper; import com.dfsek.terra.mod.generation.TerraBiomeSource; @@ -56,8 +60,7 @@ public class PresetUtil { HashMap, LevelStem> dimensionMap = new HashMap<>(); - insertCustom(platform, "minecraft:overworld", pack, dimensionTypeRegistry, chunkGeneratorSettingsRegistry, dimensionMap, - packInMetapack); + insertCustom(platform, "minecraft:overworld", pack, dimensionTypeRegistry, dimensionMap, packInMetapack); insertDefaults(dimensionTypeRegistry, chunkGeneratorSettingsRegistry, multiNoiseBiomeSourceParameterLists, platform.biomeRegistry(), dimensionMap); @@ -82,7 +85,7 @@ public class PresetUtil { HashMap, LevelStem> dimensionMap = new HashMap<>(); metaPack.packs().forEach((key, pack) -> { - insertCustom(platform, key, pack, dimensionTypeRegistry, chunkGeneratorSettingsRegistry, dimensionMap, false); + insertCustom(platform, key, pack, dimensionTypeRegistry, dimensionMap, false); }); insertDefaults(dimensionTypeRegistry, chunkGeneratorSettingsRegistry, multiNoiseBiomeSourceParameterLists, platform.biomeRegistry(), @@ -94,27 +97,20 @@ public class PresetUtil { } private static void insertCustom(ModPlatform platform, String key, ConfigPack pack, Registry dimensionTypeRegistry, - Registry chunkGeneratorSettingsRegistry, HashMap, LevelStem> dimensionMap, boolean packInMetapack) { Identifier demensionIdentifier = Identifier.parse(key); - VanillaWorldProperties vanillaWorldProperties; - - if(pack.getContext().has(VanillaWorldProperties.class)) { - vanillaWorldProperties = pack.getContext().get(VanillaWorldProperties.class); - } else { - vanillaWorldProperties = new VanillaWorldProperties(); - } - - DimensionType defaultDimension = dimensionTypeRegistry.getValue(Identifier.parse(vanillaWorldProperties.getVanillaDimension())); - - assert defaultDimension != null; + MinecraftAttributeParents parents = platform.attributeParents(); + VanillaContext context = parents.context(); + if(context == null) throw new IllegalStateException("no registry load has begun"); + PackParents packParents = parents.prepare(pack, platform.getAttributeHandle().pack(pack), AttributeReport.logging(pack)); + MinecraftDimensionFactory factory = new MinecraftDimensionFactory(platform.getAttributeHandle(), context); Identifier dimensionTypeID = Identifier.fromNamespaceAndPath("terra", pack.getID().toLowerCase(Locale.ROOT)); DimensionType dimensionType; if(!packInMetapack) { - dimensionType = DimensionUtil.createDimension(vanillaWorldProperties, defaultDimension, platform); + dimensionType = factory.create(packParents, MinecraftTimelines.tagFor(pack, packParents)); ResourceKey dimensionTypeRegistryKey = MinecraftUtil.registerDimensionTypeKey( dimensionTypeID); @@ -127,20 +123,7 @@ public class PresetUtil { TerraBiomeSource biomeSource = new TerraBiomeSource(pack); - Holder defaultGeneratorSettings = chunkGeneratorSettingsRegistry.wrapAsHolder( - chunkGeneratorSettingsRegistry.getValue(Identifier.parse(vanillaWorldProperties.getVanillaGeneration()))); - - GenerationSettings generatorSettings = new GenerationSettings( - vanillaWorldProperties.getHeight() == null ? new ConstantRange( - defaultGeneratorSettings.value().noiseSettings().minY(), - defaultGeneratorSettings.value().noiseSettings().height()) : vanillaWorldProperties.getHeight(), - vanillaWorldProperties.getSealevel() == null - ? defaultGeneratorSettings.value().seaLevel() - : vanillaWorldProperties.getSealevel(), - vanillaWorldProperties.getMobGeneration() == null - ? !defaultGeneratorSettings.value().disableMobGeneration() - : vanillaWorldProperties.getMobGeneration(), - vanillaWorldProperties.getSpawnHeight()); + GenerationSettings generatorSettings = factory.generationSettings(packParents, dimensionType); ChunkGenerator generator = new MinecraftChunkGeneratorWrapper(biomeSource, pack, generatorSettings); diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/TagUtil.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/TagUtil.java index 0716d2b89..bd65a7045 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/TagUtil.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/TagUtil.java @@ -2,20 +2,32 @@ package com.dfsek.terra.mod.util; import net.minecraft.core.Holder; import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; import net.minecraft.tags.TagLoader.LoadResult; import net.minecraft.tags.WorldPresetTags; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.levelgen.presets.WorldPreset; +import net.minecraft.world.timeline.Timeline; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; import java.util.stream.Collectors; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.mod.attribute.AttributeReport; +import com.dfsek.terra.mod.attribute.MinecraftTimelines; +import com.dfsek.terra.mod.attribute.VanillaIds; + public final class TagUtil { private static final Logger logger = LoggerFactory.getLogger(TagUtil.class); @@ -58,45 +70,21 @@ public final class TagUtil { } } + public static void registerTimelineTags(Registry registry) { + logger.info("Registering timeline tags."); + Map, List>> collect = tagsToMutableMap(registry); + MinecraftTimelines.fillTags(collect, registry); + registry.prepareTagReload(new LoadResult<>(registry.key(), collect)).apply(); + } + + public record PlatformTagSource(AttributeReport report, String config, Set tags) { } + public static void registerBiomeTags(Registry registry) { logger.info("Doing biome tag garbage...."); Map, List>> collect = tagsToMutableMap(registry); - BiomeUtil - .getTerraBiomeMap() - .forEach((vb, terraBiomes) -> - MinecraftUtil - .getEntry(registry, vb) - .ifPresentOrElse( - vanilla -> terraBiomes - .forEach(tb -> MinecraftUtil - .getEntry(registry, tb) - .ifPresentOrElse( - terra -> { - logger.debug( - vanilla.unwrapKey() - .orElseThrow() - .identifier() + - " (vanilla for " + - terra.unwrapKey() - .orElseThrow() - .identifier() + - ": " + - vanilla.tags() - .toList()); - - vanilla.tags() - .forEach( - tag -> collect - .computeIfAbsent( - tag, - t -> new ArrayList<>()) - .add(terra)); - }, - () -> logger.error( - "No such biome: {}", - tb))), - () -> logger.error("No vanilla biome: {}", vb))); + addTerraBiomes(collect, id -> MinecraftUtil.getEntry(registry, id), BiomeUtil.getTerraBiomeMap(), + BiomeUtil.getTerraBiomePlatformTags()); registry.prepareTagReload(new LoadResult<>(registry.key(), collect)).apply(); @@ -107,4 +95,44 @@ public final class TagUtil { .forEach(logger::debug); } } + + public static void addTerraBiomes(Map, List>> collect, + Function>> lookup, + Map> byParent, Map platformTags) { + byParent.forEach((vb, terraBiomes) -> + lookup.apply(vb).ifPresentOrElse( + vanilla -> terraBiomes.forEach(tb -> lookup.apply(tb).ifPresentOrElse( + terra -> { + logger.debug(vanilla.unwrapKey().orElseThrow().identifier() + " (vanilla for " + + terra.unwrapKey().orElseThrow().identifier() + ": " + vanilla.tags().toList()); + vanilla.tags().forEach(tag -> collect.computeIfAbsent(tag, t -> new ArrayList<>()).add(terra)); + }, + () -> logger.error("No such biome: {}", tb))), + () -> logger.error("No vanilla biome: {}", vb))); + + Set> existing = new HashSet<>(collect.keySet()); + platformTags.forEach((tb, source) -> { + if(source.tags().isEmpty()) return; + Optional> terra = lookup.apply(tb); + if(terra.isEmpty()) { + logger.error("No such biome: {}", tb); + return; + } + for(RegistryKey key : source.tags()) { + Identifier id; + try { + id = VanillaIds.identifier(key); + } catch(IllegalArgumentException e) { + source.report().ignored(source.config(), key.toString(), e.getMessage()); + continue; + } + TagKey tag = TagKey.create(Registries.BIOME, id); + if(!existing.contains(tag) && id.getNamespace().equals(Identifier.DEFAULT_NAMESPACE)) { + source.report().tagCreated(source.config(), key.toString()); + } + List> biomes = collect.computeIfAbsent(tag, t -> new ArrayList<>()); + if(!biomes.contains(terra.get())) biomes.add(terra.get()); + } + }); + } } diff --git a/platforms/mixin-common/src/main/resources/terra.accesswidener b/platforms/mixin-common/src/main/resources/terra.accesswidener index 49ee5c2e9..f0194d12c 100644 --- a/platforms/mixin-common/src/main/resources/terra.accesswidener +++ b/platforms/mixin-common/src/main/resources/terra.accesswidener @@ -4,3 +4,4 @@ accessible class net/minecraft/world/level/levelgen/presets/WorldPresets$Bootstr accessible field net/minecraft/world/level/levelgen/WorldDimensions BUILTIN_ORDER Ljava/util/Set; extendable class net/minecraft/nbt/Tag accessible field net/minecraft/world/level/block/entity/BlockEntity TYPE_CODEC Lcom/mojang/serialization/Codec; +accessible field net/minecraft/world/level/biome/Biome climateSettings Lnet/minecraft/world/level/biome/Biome$ClimateSettings; diff --git a/platforms/mixin-common/src/main/resources/terra.common.mixins.json b/platforms/mixin-common/src/main/resources/terra.common.mixins.json index c5f1fcdb6..a5c47c1b9 100644 --- a/platforms/mixin-common/src/main/resources/terra.common.mixins.json +++ b/platforms/mixin-common/src/main/resources/terra.common.mixins.json @@ -4,7 +4,6 @@ "package": "com.dfsek.terra.mod.mixin", "compatibilityLevel": "JAVA_25", "mixins": [ - "access.BiomeAccessor", "access.BaseSpawnerAccessor", "access.StructureManagerAccessor", "access.VillagerTypeAccessor", diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/FakePackAttributes.java b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/FakePackAttributes.java new file mode 100644 index 000000000..aa200aff6 --- /dev/null +++ b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/FakePackAttributes.java @@ -0,0 +1,120 @@ +package com.dfsek.terra.mod.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; +import java.util.Collections; +import java.util.IdentityHashMap; +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.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +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; + + +final class FakePackAttributes implements PackAttributes { + private static final AttributeEntry UNREAD = AttributeEntry.override(new Object()); + + private final AttributeHandle handle; + private final AttributeParents platformParents; + private final AttributeMap pack; + private final Map parents; + private final Map biomes; + private final List> scheduleRefs; + private final Map scheduleDefinitions; + private final AttributeEntry[] packSlots; + private final IdentityHashMap[]> biomeSlots = new IdentityHashMap<>(); + + FakePackAttributes(AttributeHandle handle, AttributeParents platformParents, AttributeMap pack, Map parents, + Map biomes) { + this(handle, platformParents, pack, parents, biomes, List.of(), Map.of()); + } + + FakePackAttributes(AttributeHandle handle, AttributeParents platformParents, AttributeMap pack, Map parents, + Map biomes, List> scheduleRefs, + Map scheduleDefinitions) { + this.handle = handle; + this.platformParents = platformParents; + this.pack = pack; + this.parents = Map.copyOf(parents); + this.biomes = Map.copyOf(biomes); + this.scheduleRefs = List.copyOf(scheduleRefs); + this.scheduleDefinitions = Collections.unmodifiableMap(new LinkedHashMap<>(scheduleDefinitions)); + this.packSlots = unread(); + for(Biome biome : biomes.keySet()) biomeSlots.put(biome, unread()); + } + + private AttributeEntry[] unread() { + AttributeEntry[] slots = new AttributeEntry[handle.attributeCount()]; + Arrays.fill(slots, UNREAD); + return slots; + } + + @SuppressWarnings("unchecked") + private static @Nullable AttributeEntry slot(AttributeEntry[] slots, AttributeMap map, Attribute attribute) { + int index = attribute.index(); + if(index >= slots.length) return map.get(attribute.key()).orElse(null); + AttributeEntry entry = slots[index]; + if(entry == UNREAD) { + entry = map.get(attribute.key()).orElse(null); + slots[index] = entry; + } + return (AttributeEntry) entry; + } + + private @Nullable AttributeEntry packEntryOrNull(Attribute attribute) { + return slot(packSlots, pack, attribute); + } + + @Override + public AttributeMap entries() { + return pack; + } + + @Override + public Map parents() { + return parents; + } + + @Override + public List> scheduleRefs() { + return scheduleRefs; + } + + @Override + public Map scheduleDefinitions() { + return scheduleDefinitions; + } + + @Override + public @Nullable AttributeEntry biomeEntryOrNull(Attribute attribute, Biome biome) { + AttributeEntry[] slots = biomeSlots.get(biome); + return slots == null ? null : slot(slots, biomes.get(biome), attribute); + } + + @Override + public AttributeMap biomeEntries(Biome biome) { + return biomes.getOrDefault(biome, AttributeMap.empty()); + } + + @Override + public @Nullable T resolve(Attribute attribute, Biome biome) { + return handle.resolve(attribute, platformParents.packOrNull(this, attribute), packEntryOrNull(attribute), + platformParents.biomeOrNull(biome, attribute), biomeEntryOrNull(attribute, biome)); + } + + @Override + public @Nullable T resolvePack(Attribute attribute) { + return handle.resolve(attribute, platformParents.packOrNull(this, attribute), packEntryOrNull(attribute), null); + } +} diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParentsTest.java b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParentsTest.java new file mode 100644 index 000000000..fa9558f87 --- /dev/null +++ b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParentsTest.java @@ -0,0 +1,400 @@ +package com.dfsek.terra.mod.attribute; + +import com.mojang.serialization.Lifecycle; +import net.minecraft.core.MappedRegistry; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.Biomes; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; +import org.junit.jupiter.api.Test; + +import java.lang.management.ManagementFactory; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.BiConsumer; + +import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes; +import com.dfsek.terra.api.config.ConfigPack; +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.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeMap; +import com.dfsek.terra.api.world.biome.PlatformBiome; + +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +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; +import static org.junit.jupiter.api.Assertions.fail; + + +class MinecraftAttributeParentsTest { + private static final com.dfsek.terra.api.registry.Registry> REGISTRY = registry(); + private static final ConfigPack PACK = pack("test", REGISTRY); + + private static final Attribute RESPAWN_ANCHOR = attr(MinecraftAttributes.GAMEPLAY_RESPAWN_ANCHOR_WORKS); + private static final Attribute SKY_LIGHT = attr(MinecraftAttributes.GAMEPLAY_SKY_LIGHT_LEVEL); + private static final Attribute HAS_CEILING = attr(MinecraftAttributes.DIMENSION_HAS_CEILING); + private static final Attribute SEA_LEVEL = attr(MinecraftAttributes.WORLD_SEA_LEVEL); + private static final Attribute PRECIPITATION = attr(MinecraftAttributes.BIOME_HAS_PRECIPITATION); + + private static final BiConsumer, String> FAIL = (attribute, reason) -> fail(attribute.getRegistryKey() + ": " + reason); + + private final List warnings = new ArrayList<>(); + private final List debugs = new ArrayList<>(); + private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add); + private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE); + + private static Attribute attr(AttributeKey key) { + return attribute(key.getRegistryKey().toString()); + } + + static ConfigPack pack(String id, com.dfsek.terra.api.registry.Registry> attributes) { + return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class[]{ ConfigPack.class }, + (proxy, method, args) -> switch(method.getName()) { + case "getID" -> id; + case "getRegistry" -> attributes; + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == args[0]; + case "toString" -> "ConfigPack[" + id + "]"; + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + + private FakePackAttributes fake(Map parentIds) { + return new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), parentIds, Map.of()); + } + + private static T value(ResourceKey> registry, ResourceKey key) { + return REGISTRIES.lookupOrThrow(registry).getOrThrow(key).value(); + } + + private static PackAttributeTable table() { + return PackAttributeTable.of(REGISTRY); + } + + @Test + void reportFormats() { + report.attributeSkipped("BIOME", "minecraft:visual/fog_color", "not a colour"); + report.scheduleSkipped("mypack:seasons", "no clock"); + report.trackDropped("mypack:seasons", "minecraft:visual/fog_color", "bad keyframe"); + report.timeMarkerDropped("mypack:seasons", "minecraft:noon", "minecraft:overworld"); + report.ignored("pack.yml", "vanilla", "no such dimension type \"minecraft:nope\""); + report.tagCreated("BIOME", "minecraft:is_custom"); + report.notApplied("test:custom"); + report.notApplied("test:custom"); + report.notApplied("test:other"); + + assertEquals(List.of( + "Pack \"test\", config \"BIOME\": attribute \"minecraft:visual/fog_color\" skipped: not a colour", + "Pack \"test\": schedule \"mypack:seasons\" skipped: no clock", + "Pack \"test\": schedule \"mypack:seasons\" track \"minecraft:visual/fog_color\" dropped: bad keyframe", + "Pack \"test\": schedule \"mypack:seasons\" time marker \"minecraft:noon\" dropped: already defined for clock " + + "\"minecraft:overworld\"", + "Pack \"test\", config \"pack.yml\": \"vanilla\" ignored: no such dimension type \"minecraft:nope\"", + "Pack \"test\", config \"BIOME\": tag \"minecraft:is_custom\" created: no such tag in the minecraft namespace"), warnings); + assertEquals(List.of( + "Pack \"test\": attribute \"test:custom\" is not applied on this platform", + "Pack \"test\": attribute \"test:other\" is not applied on this platform"), debugs); + } + + @Test + void unreadableParentValueNamesTheParent() { + MinecraftAttributeParents.parentSkipped(report, "minecraft:plains").accept(HAS_CEILING, "not a boolean"); + + assertEquals(List.of("Pack \"test\", config \"pack.yml\": attribute \"" + HAS_CEILING.getRegistryKey() + + "\" skipped: vanilla parent \"minecraft:plains\": not a boolean"), warnings); + } + + @Test + void overworldByDefault() { + parents.beginLoad(CONTEXT); + FakePackAttributes fake = fake(Map.of()); + PackParents pack = parents.prepare(PACK, Optional.of(fake), report); + + DimensionType overworld = value(Registries.DIMENSION_TYPE, BuiltinDimensionTypes.OVERWORLD); + AttributeSlots expected = new VanillaParentReader(HANDLE, CONTEXT).dimension(overworld, table(), FAIL); + assertEquals(expected.get(RESPAWN_ANCHOR), parents.packOrNull(fake, RESPAWN_ANCHOR)); + assertFalse(fake.resolvePack(RESPAWN_ANCHOR)); + assertEquals(AttributeEntry.override(false), parents.packOrNull(fake, HAS_CEILING)); + assertEquals(AttributeEntry.override(63), parents.packOrNull(fake, SEA_LEVEL)); + + assertEquals(BuiltinDimensionTypes.OVERWORLD, pack.dimensionKey()); + assertSame(overworld, pack.dimension()); + assertEquals(NoiseGeneratorSettings.OVERWORLD, pack.generationKey()); + assertSame(value(Registries.NOISE_SETTINGS, NoiseGeneratorSettings.OVERWORLD), pack.generation()); + assertSame(fake, pack.attributes()); + assertSame(report, pack.report()); + assertEquals(List.of(), warnings); + + PackParents bare = parents.prepare(pack("bare", REGISTRY), Optional.empty(), report); + assertNull(bare.attributes()); + assertEquals(BuiltinDimensionTypes.OVERWORLD, bare.dimensionKey()); + assertEquals(NoiseGeneratorSettings.OVERWORLD, bare.generationKey()); + assertEquals(AttributeEntry.override(63), bare.packEntries().get(SEA_LEVEL)); + } + + @Test + void vanillaParentIsUsed() { + parents.beginLoad(CONTEXT); + FakePackAttributes fake = fake(Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))); + PackParents pack = parents.prepare(PACK, Optional.of(fake), report); + + assertEquals(BuiltinDimensionTypes.NETHER, pack.dimensionKey()); + assertSame(value(Registries.DIMENSION_TYPE, BuiltinDimensionTypes.NETHER), pack.dimension()); + assertEquals(AttributeEntry.override(true), parents.packOrNull(fake, HAS_CEILING)); + assertEquals(AttributeEntry.override(4f), parents.packOrNull(fake, SKY_LIGHT)); + assertEquals(NoiseGeneratorSettings.OVERWORLD, pack.generationKey()); + assertEquals(AttributeEntry.override(63), parents.packOrNull(fake, SEA_LEVEL)); + assertEquals(List.of(), warnings); + } + + @Test + void generationParentSuppliesWorld() { + parents.beginLoad(CONTEXT); + FakePackAttributes fake = fake(Map.of("vanilla-generation", RegistryKey.parse("minecraft:nether"))); + PackParents pack = parents.prepare(PACK, Optional.of(fake), report); + + assertEquals(NoiseGeneratorSettings.NETHER, pack.generationKey()); + assertEquals(AttributeEntry.override(32), parents.packOrNull(fake, SEA_LEVEL)); + assertEquals(BuiltinDimensionTypes.OVERWORLD, pack.dimensionKey()); + assertEquals(List.of(), warnings); + } + + @Test + void badParentWarnsAndFallsBack() { + parents.beginLoad(CONTEXT); + PackParents upper = parents.prepare(PACK, Optional.of(fake(Map.of("vanilla", RegistryKey.parse("minecraft:The_Nether")))), + report); + PackParents unknown = parents.prepare(PACK, Optional.of(fake(Map.of("vanilla", RegistryKey.parse("minecraft:nope"), + "vanilla-generation", RegistryKey.parse("minecraft:nope")))), + report); + + assertEquals(List.of( + "Pack \"test\", config \"pack.yml\": \"vanilla\" ignored: invalid ID \"minecraft:The_Nether\": Minecraft IDs use only " + + "lower-case a-z, 0-9, _, . and -, and / in the path", + "Pack \"test\", config \"pack.yml\": \"vanilla\" ignored: no such dimension type \"minecraft:nope\"", + "Pack \"test\", config \"pack.yml\": \"vanilla-generation\" ignored: no such noise settings \"minecraft:nope\""), + warnings); + for(PackParents pack : List.of(upper, unknown)) { + assertEquals(BuiltinDimensionTypes.OVERWORLD, pack.dimensionKey()); + assertEquals(NoiseGeneratorSettings.OVERWORLD, pack.generationKey()); + assertEquals(AttributeEntry.override(false), pack.packEntries().get(HAS_CEILING)); + } + } + + @Test + void unknownParentCreatesNoHolder() { + MappedRegistry dimensionTypes = VanillaContextTest.copy(Registries.DIMENSION_TYPE); + MappedRegistry noiseSettings = VanillaContextTest.copy(Registries.NOISE_SETTINGS); + MappedRegistry biomes = new MappedRegistry<>(Registries.BIOME, Lifecycle.stable()); + VanillaContext load = VanillaContext.ofLoad(List.of(dimensionTypes, noiseSettings, biomes), MinecraftTestSupport.loadContext(), + key -> null); + parents.beginLoad(new VanillaContext(CONTEXT.ops(), load.dimensionTypes(), load.noiseSettings(), load.biomes(), key -> null)); + dimensionTypes.freeze(); + noiseSettings.freeze(); + + PackParents pack = parents.prepare(PACK, Optional.of(fake(Map.of("vanilla", RegistryKey.parse("minecraft:nope"), + "vanilla-generation", RegistryKey.parse("minecraft:nope")))), + report); + + assertEquals(BuiltinDimensionTypes.OVERWORLD, pack.dimensionKey()); + assertEquals(NoiseGeneratorSettings.OVERWORLD, pack.generationKey()); + assertEquals(2, warnings.size(), warnings.toString()); + assertFalse(dimensionTypes.containsKey(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse("minecraft:nope")))); + assertFalse(noiseSettings.containsKey(ResourceKey.create(Registries.NOISE_SETTINGS, Identifier.parse("minecraft:nope")))); + } + + @Test + void biomeOrNullReadsProtoBiome() { + parents.beginLoad(CONTEXT); + PackParents pack = parents.prepare(PACK, Optional.empty(), report); + TestBiome biome = new TestBiome("BIOME", 0, Biomes.DESERT.identifier()); + assertSame(AttributeSlots.EMPTY, biome.proto().parentEntries()); + assertNull(parents.biomeOrNull(biome, PRECIPITATION)); + + AttributeSlots desert = parents.biomeEntries(pack, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)); + assertSame(desert, parents.biomeEntries(pack, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)), "cached per parent key"); + biome.proto().setParentEntries(desert); + + assertEquals(AttributeEntry.override(false), parents.biomeOrNull(biome, PRECIPITATION)); + PlatformBiome other = () -> "other"; + assertNull(parents.biomeOrNull(new TestBiome("OTHER", 1, other), PRECIPITATION)); + assertEquals(List.of(), warnings); + } + + @Test + void unreadableBiomeParentIsReportedOnce() { + Attribute downfall = HANDLE.attributeBuilder(AttributeKey.parse("terra:biome/downfall"), + HANDLE.types().identifier("minecraft"), + RegistryKey.parse("minecraft:none")).build(); + parents.beginLoad(CONTEXT); + PackParents pack = parents.prepare(pack("test", registry(downfall)), Optional.empty(), report); + Biome plains = value(Registries.BIOME, Biomes.PLAINS); + + AttributeSlots first = parents.biomeEntries(pack, Biomes.PLAINS, plains); + assertSame(first, parents.biomeEntries(pack, Biomes.PLAINS, plains)); + + assertEquals(1, warnings.size(), warnings.toString()); + assertTrue(warnings.getFirst().startsWith("Pack \"test\", config \"pack.yml\": attribute \"terra:biome/downfall\" skipped: " + + "vanilla parent \"minecraft:plains\": "), warnings.getFirst()); + assertNull(first.get(downfall)); + } + + @Test + void readsAllocateNothing() { + parents.beginLoad(CONTEXT); + parents.prepare(PACK, Optional.of(fake(Map.of())), report); + parents.prepare(pack("other", REGISTRY), Optional.empty(), report); + TestBiome biome = new TestBiome("BIOME", 0, Biomes.DESERT.identifier()); + TestBiome plain = new TestBiome("PLAIN", 1, (PlatformBiome) () -> "plain"); + FakePackAttributes fake = new FakePackAttributes(HANDLE, parents, + AttributeMap.builder().put(RESPAWN_ANCHOR.key(), AttributeEntry.override(true)).build(), + Map.of("vanilla", RegistryKey.parse("minecraft:the_nether")), + Map.of(biome, AttributeMap.builder().put(HAS_CEILING.key(), AttributeEntry.override(true)).build())); + PackParents pack = parents.prepare(PACK, Optional.of(fake), report); + biome.proto().setParentEntries(parents.biomeEntries(pack, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT))); + FakePackAttributes unprepared = fake(Map.of()); + assertEquals(List.of(), warnings); + assertEquals(1023, reads(fake, unprepared, biome, plain), "every read sees the expected entry or value"); + + 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(fake, unprepared, biome, plain); + long before = threads.getThreadAllocatedBytes(thread); + for(int i = 0; i < 10_000; i++) sink += reads(fake, unprepared, biome, plain); + long allocated = threads.getThreadAllocatedBytes(thread) - before; + + assertEquals(110_000 * 1023, sink); + assertTrue(allocated < 1024, allocated + " bytes allocated"); + System.out.println("readsAllocateNothing: " + allocated + " bytes over 10000 measured iterations"); + } + + private int reads(FakePackAttributes fake, FakePackAttributes unprepared, TestBiome biome, TestBiome plain) { + int hash = 0; + hash += parents.biomeOrNull(biome, PRECIPITATION) == null ? 0 : 1; + hash += parents.biomeOrNull(plain, PRECIPITATION) == null ? 2 : 0; + hash += parents.packOrNull(fake, HAS_CEILING) == null ? 0 : 4; + hash += parents.packOrNull(fake, SKY_LIGHT) == null ? 0 : 8; + hash += parents.packOrNull(unprepared, SKY_LIGHT) == null ? 16 : 0; + hash += fake.resolve(PRECIPITATION, biome) ? 0 : 32; + hash += fake.resolve(HAS_CEILING, plain) ? 64 : 0; + hash += fake.resolve(HAS_CEILING, biome) ? 128 : 0; + hash += fake.resolvePack(RESPAWN_ANCHOR) ? 256 : 0; + hash += fake.resolvePack(HAS_CEILING) ? 512 : 0; + return hash; + } + + @Test + void beginLoadDropsOldPacks() { + parents.beginLoad(CONTEXT); + FakePackAttributes fake = fake(Map.of()); + PackParents first = parents.prepare(PACK, Optional.of(fake), report); + assertNotNull(parents.packOrNull(fake, HAS_CEILING)); + + parents.beginLoad(CONTEXT); + assertNull(parents.packOrNull(fake, HAS_CEILING)); + PackParents second = parents.prepare(PACK, Optional.of(fake), report); + assertNotSame(first, second); + assertEquals(AttributeEntry.override(false), parents.packOrNull(fake, HAS_CEILING)); + + parents.clearPacks(); + assertSame(CONTEXT, parents.context()); + assertNull(parents.packOrNull(fake, HAS_CEILING)); + } + + @Test + void packReloadKeepsOldPacks() { + parents.beginLoad(CONTEXT); + FakePackAttributes fake = fake(Map.of()); + PackParents first = parents.prepare(PACK, Optional.of(fake), report); + + parents.beginPackReload(); + assertSame(CONTEXT, parents.context()); + assertEquals(AttributeEntry.override(false), parents.packOrNull(fake, HAS_CEILING), "the old pack keeps its parents"); + FakePackAttributes reloaded = fake(Map.of()); + PackParents second = parents.prepare(PACK, Optional.of(reloaded), report); + assertNotSame(first, second); + assertNotSame(first, parents.prepare(PACK, Optional.of(fake), report), "prepared fresh during the reload"); + assertEquals(AttributeEntry.override(false), parents.packOrNull(reloaded, HAS_CEILING)); + assertNotNull(parents.packOrNull(fake, HAS_CEILING)); + + parents.endPackReload(); + assertSame(second, parents.prepare(PACK, Optional.of(reloaded), report)); + assertEquals(AttributeEntry.override(false), parents.packOrNull(reloaded, HAS_CEILING)); + assertNotNull(parents.packOrNull(fake, HAS_CEILING), "re-prepared during the reload, so kept"); + assertEquals(List.of(), warnings); + + parents.beginPackReload(); + parents.endPackReload(); + assertNull(parents.packOrNull(reloaded, HAS_CEILING), "not prepared again, so dropped"); + } + + @Test + void prepareAfterClearPacksIsFresh() { + parents.beginLoad(CONTEXT); + FakePackAttributes fake = fake(Map.of()); + PackParents first = parents.prepare(PACK, Optional.of(fake), report); + AttributeSlots desert = parents.biomeEntries(first, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)); + + parents.clearPacks(); + FakePackAttributes reloaded = fake(Map.of()); + assertNull(parents.packOrNull(reloaded, HAS_CEILING)); + PackParents second = parents.prepare(PACK, Optional.of(reloaded), report); + + assertNotSame(first, second); + assertSame(second, parents.prepare(PACK, Optional.of(reloaded), report)); + assertEquals(AttributeEntry.override(false), parents.packOrNull(reloaded, HAS_CEILING)); + assertNull(parents.packOrNull(fake, HAS_CEILING), "the old pack's attributes get no parents"); + AttributeSlots again = parents.biomeEntries(second, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)); + assertNotSame(desert, again, "biome entries are read again for the new pack"); + assertEquals(AttributeEntry.override(false), again.get(PRECIPITATION)); + assertEquals(List.of(), warnings); + } + + @Test + void unpreparedPackHasNoParents() { + FakePackAttributes fake = fake(Map.of()); + assertNull(parents.context()); + assertNull(parents.packOrNull(fake, HAS_CEILING)); + assertThrows(IllegalStateException.class, () -> parents.prepare(PACK, Optional.of(fake), report)); + + parents.beginLoad(CONTEXT); + assertSame(CONTEXT, parents.context()); + assertNull(parents.packOrNull(fake, HAS_CEILING)); + } + + @Test + void prepareIsIdempotent() { + parents.beginLoad(CONTEXT); + FakePackAttributes fake = fake(Map.of("vanilla", RegistryKey.parse("minecraft:nope"))); + PackParents first = parents.prepare(PACK, Optional.of(fake), report); + assertEquals(1, warnings.size()); + + assertSame(first, parents.prepare(PACK, Optional.of(fake), report)); + assertEquals(1, warnings.size()); + + PackParents bare = parents.prepare(PACK, Optional.empty(), report); + assertNotSame(first, bare); + assertSame(bare, parents.prepare(PACK, Optional.empty(), report)); + } +} diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactoryTest.java b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactoryTest.java new file mode 100644 index 000000000..e041dfbc0 --- /dev/null +++ b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactoryTest.java @@ -0,0 +1,466 @@ +package com.dfsek.terra.mod.attribute; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.Lifecycle; +import net.minecraft.core.MappedRegistry; +import net.minecraft.core.RegistrationInfo; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.attribute.EnvironmentAttribute; +import net.minecraft.world.attribute.EnvironmentAttributeMap; +import net.minecraft.world.attribute.EnvironmentAttributes; +import net.minecraft.world.entity.npc.villager.VillagerType; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeSpecialEffects; +import net.minecraft.world.level.biome.Biomes; +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.function.BiConsumer; + +import com.dfsek.terra.api.config.ConfigPack; +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.AttributeKey; +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.value.Color; +import com.dfsek.terra.registry.OpenRegistryImpl; + +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.ATTRIBUTES; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +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; +import static org.junit.jupiter.api.Assertions.fail; + + +class MinecraftBiomeFactoryTest { + private static final Registry> REGISTRY = registry(); + private static final ConfigPack PACK = MinecraftAttributeParentsTest.pack("test", REGISTRY); + private static final RegistryOps OPS = CONTEXT.ops(); + private static final DecodeContext PLAIN = HANDLE.plainContext(); + private static final VanillaAttributeMaps MAPS = new VanillaAttributeMaps(HANDLE, CONTEXT); + + private static final String CONFIG = "BIOME"; + private static final String FOG_COLOR = "minecraft:visual/fog_color"; + private static final String SKY_COLOR = "minecraft:visual/sky_color"; + private static final String AMBIENT_PARTICLES = "minecraft:visual/ambient_particles"; + private static final String SPAWN_PROBABILITY = "minecraft:gameplay/creature_world_gen_spawn_probability"; + private static final String VILLAGER_TYPE = "terra:biome/villager_type"; + + private static final BiConsumer, String> FAIL = (attribute, reason) -> fail(attribute.getRegistryKey() + ": " + reason); + + private final List warnings = new ArrayList<>(); + private final List debugs = new ArrayList<>(); + private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add); + private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE); + + private static Biome biome(ResourceKey key) { + return REGISTRIES.lookupOrThrow(Registries.BIOME).getOrThrow(key).value(); + } + + @SuppressWarnings("unchecked") + private static Object encode(Codec codec, Object value) { + return VanillaCodecs.encode(codec, (V) value, OPS); + } + + private static Object climate(Biome biome) { + return encode(Biome.ClimateSettings.CODEC.codec(), biome.climateSettings); + } + + private static Object effects(Biome biome) { + return encode(BiomeSpecialEffects.CODEC, biome.getSpecialEffects()); + } + + private static Map environment(Biome biome) { + return (Map) encode(EnvironmentAttributeMap.CODEC, biome.getAttributes()); + } + + private static AttributeEntry decoded(String id, Object raw) { + try { + return HANDLE.decodeEntry(attribute(id), raw, PLAIN); + } catch(DecodeException e) { + throw new AssertionError(id + ": " + e.getMessage(), e); + } + } + + @SuppressWarnings("unchecked") + private static void put(AttributeMap.Builder builder, Attribute attribute, AttributeEntry entry) { + builder.put(attribute.key(), (AttributeEntry) entry); + } + + private record Fixture(TestBiome biome, FakePackAttributes attributes, PackParents pack, MinecraftBiomeFactory factory, + ResourceKey parentKey, Biome parent) { + MinecraftBiomeFactory.Built create(AttributeReport report) { + return factory.create(parentKey, parent, biome, pack, report); + } + } + + private Fixture fixture(ResourceKey parentKey, Biome parent, Map, AttributeEntry> entries) { + return fixture(CONTEXT, PACK, parentKey, parent, entries); + } + + private Fixture fixture(VanillaContext context, ConfigPack pack, ResourceKey parentKey, Biome parent, + Map, AttributeEntry> entries) { + TestBiome biome = new TestBiome(CONFIG, 0, parentKey.identifier()); + AttributeMap.Builder builder = AttributeMap.builder(); + entries.forEach((attribute, entry) -> put(builder, attribute, entry)); + FakePackAttributes attributes = new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(), + Map.of(biome, builder.build())); + parents.beginLoad(context); + PackParents prepared = parents.prepare(pack, Optional.of(attributes), report); + biome.proto().setParentEntries(parents.biomeEntries(prepared, parentKey, parent)); + return new Fixture(biome, attributes, prepared, new MinecraftBiomeFactory(HANDLE, context), parentKey, parent); + } + + private static Map, AttributeEntry> entries(Object... idsAndRaw) { + Map, AttributeEntry> entries = new LinkedHashMap<>(); + for(int i = 0; i < idsAndRaw.length; i += 2) { + String id = (String) idsAndRaw[i]; + entries.put(attribute(id), decoded(id, idsAndRaw[i + 1])); + } + return entries; + } + + private static void assertMatches(Biome expected, Biome actual) { + assertEquals(expected.hasPrecipitation(), actual.hasPrecipitation()); + assertEquals(expected.getBaseTemperature(), actual.getBaseTemperature()); + assertEquals(expected.climateSettings, actual.climateSettings); + assertEquals(climate(expected), climate(actual)); + assertEquals(effects(expected), effects(actual)); + assertEquals(expected.getAttributes().keySet(), actual.getAttributes().keySet()); + assertEquals(environment(expected), environment(actual)); + assertSame(expected.getGenerationSettings(), actual.getGenerationSettings()); + } + + @Test + void noEntriesMatchesParent() { + Biome plains = biome(Biomes.PLAINS); + MinecraftBiomeFactory.Built built = fixture(Biomes.PLAINS, plains, Map.of()).create(report); + + assertMatches(plains, built.biome()); + assertNotSame(plains, built.biome()); + assertEquals(VillagerType.PLAINS, built.villagerType()); + assertEquals(List.of(), warnings); + assertEquals(List.of(), debugs); + } + + @Test + void createdBiomeRegistersBesideItsParent() { + Biome plains = biome(Biomes.PLAINS); + Biome built = fixture(Biomes.PLAINS, plains, Map.of()).create(report).biome(); + MappedRegistry registry = new MappedRegistry<>(Registries.BIOME, Lifecycle.stable()); + registry.register(Biomes.PLAINS, plains, RegistrationInfo.BUILT_IN); + ResourceKey key = ResourceKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("terra", "test")); + + assertDoesNotThrow(() -> registry.register(key, built, RegistrationInfo.BUILT_IN)); + } + + @Test + void noAttributesMatchesTheParent() { + Biome plains = biome(Biomes.PLAINS); + parents.beginLoad(CONTEXT); + PackParents bare = parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report); + assertNull(bare.attributes()); + assertSame(PackAttributeTable.EMPTY, bare.table()); + TestBiome biome = new TestBiome(CONFIG, 0, Biomes.PLAINS.identifier()); + biome.proto().setParentEntries(parents.biomeEntries(bare, Biomes.PLAINS, plains)); + + MinecraftBiomeFactory.Built built = new MinecraftBiomeFactory(HANDLE, CONTEXT).create(Biomes.PLAINS, plains, biome, bare, report); + + assertMatches(plains, built.biome()); + assertNotSame(plains, built.biome()); + assertEquals(VillagerType.PLAINS, built.villagerType()); + assertEquals(List.of(), warnings); + assertEquals(List.of(), debugs); + } + + @Test + void equivalentInputMatchesVanilla() { + Biome plains = biome(Biomes.PLAINS); + Biome desert = biome(Biomes.DESERT); + PackAttributeTable table = PackAttributeTable.of(REGISTRY); + AttributeSlots desertSlots = new VanillaParentReader(HANDLE, CONTEXT).biome(Biomes.DESERT, desert, table, FAIL); + Map, AttributeEntry> entries = new LinkedHashMap<>(); + List> attributes = new ArrayList<>(); + table.environment().forEach(bound -> attributes.add(bound.attribute())); + table.climate().forEach(field -> attributes.add(field.attribute())); + table.effects().forEach(field -> attributes.add(field.attribute())); + for(Attribute attribute : attributes) { + AttributeEntry entry = desertSlots.get(attribute); + if(entry != null) entries.put(attribute, entry); + } + assertTrue(entries.size() > 5, "desert has few entries: " + entries.size()); + + Biome built = fixture(Biomes.PLAINS, plains, entries).create(report).biome(); + + assertEquals(desert.climateSettings, built.climateSettings); + assertEquals(climate(desert), climate(built)); + assertEquals(effects(desert), effects(built)); + Map expected = environment(desert); + Map parent = environment(plains); + Map actual = environment(built); + for(PackAttributeTable.Bound bound : table.environment()) { + String id = bound.attribute().getRegistryKey().toString(); + if(desert.getAttributes().contains(bound.vanilla())) { + assertEquals(expected.get(id), actual.get(id), id); + } else { + assertEquals(parent.get(id), actual.get(id), id + ": a key desert lacks keeps the plains parent's value"); + } + } + assertEquals(List.of(), warnings); + } + + @Test + void desertParentKeepsNoPrecipitation() { + Biome desert = biome(Biomes.DESERT); + assertFalse(desert.hasPrecipitation()); + Biome built = fixture(Biomes.DESERT, desert, entries(FOG_COLOR, "#123456")).create(report).biome(); + + assertFalse(built.hasPrecipitation()); + assertEquals(desert.climateSettings, built.climateSettings); + assertEquals(List.of(), warnings); + } + + @Test + void spawnProbabilityIsApplied() { + Biome plains = biome(Biomes.PLAINS); + Biome built = fixture(Biomes.PLAINS, plains, entries(SPAWN_PROBABILITY, 0.2)).create(report).biome(); + + assertTrue(built.getAttributes().contains(EnvironmentAttributes.CREATURE_WORLD_GEN_SPAWN_PROBABILITY)); + assertEquals(0.2f, built.getAttributes().applyModifier(EnvironmentAttributes.CREATURE_WORLD_GEN_SPAWN_PROBABILITY, 0.5f)); + assertEquals(List.of(), warnings); + } + + @Test + void nonComposableFallsBackToResolved() throws DecodeException { + Attribute fog = attribute(FOG_COLOR); + Biome plains = biome(Biomes.PLAINS); + AttributeEntry blend = HANDLE.decodeEntry(fog, Map.of("modifier", "alpha_blend", "argument", "#80ff0000"), PLAIN); + Biome parent = new Biome.BiomeBuilder() + .hasPrecipitation(true) + .temperature(0.8f) + .downfall(0.4f) + .putAttributes(MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(fog, blend), true, FAIL)) + .specialEffects(plains.getSpecialEffects()) + .generationSettings(plains.getGenerationSettings()) + .build(); + ResourceKey parentKey = ResourceKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("test", "blended")); + AttributeEntry multiply = decoded(FOG_COLOR, Map.of("modifier", "multiply", "argument", "#808080")); + + Fixture fixture = fixture(parentKey, parent, Map.of(fog, multiply)); + assertEquals(blend, fixture.biome().proto().parentEntries().get(fog), "the parent's modifier is read"); + assertTrue(composed(fog, blend, multiply).isEmpty(), "alpha_blend then multiply has no single entry"); + Biome built = fixture.create(report).biome(); + + Color resolved = fixture.attributes().resolve(fog, fixture.biome()); + assertNotNull(resolved); + EnvironmentAttributeMap expected = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(fog, AttributeEntry.override(resolved)), + true, FAIL); + assertEquals(expected.get(EnvironmentAttributes.FOG_COLOR), built.getAttributes().get(EnvironmentAttributes.FOG_COLOR)); + assertEquals(List.of(), warnings); + } + + @SuppressWarnings("unchecked") + private static Optional> composed(Attribute attribute, AttributeEntry lower, AttributeEntry upper) { + return HANDLE.compose(attribute, (AttributeEntry) lower, (AttributeEntry) upper); + } + + @Test + void badEntryIsSkippedAlone() { + Biome plains = biome(Biomes.PLAINS); + Object oldParticle = Map.of("type", "minecraft:falling_dust", "block_state", Map.of("Name", "minecraft:sand")); + Map, AttributeEntry> entries = entries( + AMBIENT_PARTICLES, List.of(Map.of("particle", oldParticle, "probability", 0.01)), + FOG_COLOR, "#123456"); + + Biome built = fixture(Biomes.PLAINS, plains, entries).create(report).biome(); + + String reason = rejection(AMBIENT_PARTICLES, entries.get(attribute(AMBIENT_PARTICLES))); + assertEquals(List.of("Pack \"test\", config \"BIOME\": attribute \"" + AMBIENT_PARTICLES + "\" skipped: " + reason), warnings); + assertEquals(plains.getAttributes().contains(EnvironmentAttributes.AMBIENT_PARTICLES), + built.getAttributes().contains(EnvironmentAttributes.AMBIENT_PARTICLES)); + assertFogApplied(entries.get(attribute(FOG_COLOR)), built); + } + + private static void assertFogApplied(AttributeEntry fog, Biome built) { + EnvironmentAttributeMap expected = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(attribute(FOG_COLOR), fog), true, FAIL); + assertEquals(expected.get(EnvironmentAttributes.FOG_COLOR), built.getAttributes().get(EnvironmentAttributes.FOG_COLOR)); + } + + @SuppressWarnings("unchecked") + private static String rejection(String id, AttributeEntry entry) { + Attribute attribute = attribute(id); + Object raw = HANDLE.encodeEntry(attribute, (AttributeEntry) entry); + DecodeException e = assertThrows(DecodeException.class, + () -> VanillaCodecs.parse(EnvironmentAttributeMap.CODEC_ONLY_POSITIONAL, Map.of(id, raw), OPS)); + assertFalse(e.getMessage().isBlank()); + return e.getMessage(); + } + + @Test + void badFieldIsSkippedAlone() { + Attribute downfall = HANDLE.attributeBuilder(AttributeKey.parse("terra:biome/downfall"), + HANDLE.types().identifier("minecraft"), + RegistryKey.parse("minecraft:none")).build(); + OpenRegistryImpl> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE); + for(Attribute attribute : ATTRIBUTES) { + if(!attribute.getRegistryKey().equals(downfall.getRegistryKey())) registry.register(attribute.getRegistryKey(), attribute); + } + registry.register(downfall.getRegistryKey(), downfall); + Map, AttributeEntry> entries = new LinkedHashMap<>(entries("terra:biome/temperature", 0.3)); + entries.put(downfall, AttributeEntry.override(RegistryKey.parse("minecraft:wet"))); + Biome plains = biome(Biomes.PLAINS); + + Biome built = fixture(CONTEXT, MinecraftAttributeParentsTest.pack("test", registry), Biomes.PLAINS, plains, entries) + .create(report).biome(); + + assertEquals(2, warnings.size(), warnings.toString()); + assertTrue(warnings.get(0).startsWith("Pack \"test\", config \"pack.yml\": attribute \"terra:biome/downfall\" " + + "skipped: vanilla parent \"minecraft:plains\": "), warnings.get(0)); + assertTrue(warnings.get(1).startsWith("Pack \"test\", config \"BIOME\": attribute \"terra:biome/downfall\" skipped: "), + warnings.get(1)); + assertEquals(0.3f, built.getBaseTemperature()); + assertEquals(plains.climateSettings.downfall(), built.climateSettings.downfall()); + assertEquals(plains.hasPrecipitation(), built.hasPrecipitation()); + } + + @Test + void nonPositionalOnBiomeIsSkipped() { + PackAttributeTable.Bound bound = PackAttributeTable.of(REGISTRY).environment().stream() + .filter(b -> !b.vanilla().isPositional() && b.attribute().defaultValue() != null) + .findFirst().orElseThrow(); + String id = bound.attribute().getRegistryKey().toString(); + Map, AttributeEntry> entries = new LinkedHashMap<>(); + entries.put(bound.attribute(), AttributeEntry.override(bound.attribute().defaultValue())); + entries.putAll(entries(FOG_COLOR, "#123456")); + Biome plains = biome(Biomes.PLAINS); + + Biome built = fixture(Biomes.PLAINS, plains, entries).create(report).biome(); + + assertEquals(List.of("Pack \"test\", config \"BIOME\": attribute \"" + id + "\" skipped: " + + rejection(id, entries.get(bound.attribute()))), warnings); + assertFalse(built.getAttributes().contains(bound.vanilla())); + assertFogApplied(entries.get(attribute(FOG_COLOR)), built); + } + + @Test + void unknownParentAttributeIsKept() { + OpenRegistryImpl> withoutSky = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE); + for(Attribute attribute : ATTRIBUTES) { + if(!attribute.getRegistryKey().toString().equals(SKY_COLOR)) withoutSky.register(attribute.getRegistryKey(), attribute); + } + Biome plains = biome(Biomes.PLAINS); + EnvironmentAttribute sky = vanilla(SKY_COLOR); + assertTrue(plains.getAttributes().contains(sky)); + Map, AttributeEntry> entries = entries(FOG_COLOR, "#123456"); + + Fixture fixture = fixture(CONTEXT, MinecraftAttributeParentsTest.pack("nosky", withoutSky), Biomes.PLAINS, plains, entries); + assertNull(fixture.biome().proto().parentEntries().get(attribute(SKY_COLOR)), "the pack does not know sky colour"); + Biome built = fixture.create(report).biome(); + + assertSame(plains.getAttributes().get(sky), built.getAttributes().get(sky)); + assertFogApplied(entries.get(attribute(FOG_COLOR)), built); + assertEquals(List.of(), warnings); + } + + @Test + void addonAttributeIsDebugLogged() { + Attribute custom = HANDLE.attributeBuilder(AttributeKey.parse("test:custom"), HANDLE.types().floatType(), 0f) + .build(); + Attribute unset = HANDLE.attributeBuilder(AttributeKey.parse("test:unset"), HANDLE.types().floatType(), 0f) + .build(); + ConfigPack pack = MinecraftAttributeParentsTest.pack("test", registry(custom, unset)); + Biome plains = biome(Biomes.PLAINS); + + Biome built = fixture(CONTEXT, pack, Biomes.PLAINS, plains, Map.of(custom, AttributeEntry.override(1f))).create(report).biome(); + + assertEquals(List.of("Pack \"test\": attribute \"test:custom\" is not applied on this platform"), debugs); + assertEquals(List.of(), warnings); + assertMatches(plains, built); + } + + @Test + void villagerTypeFallsBackToParent() { + VanillaContext villagers = VanillaContext.of(REGISTRIES, key -> key == Biomes.DESERT ? VillagerType.DESERT : null); + Biome desert = biome(Biomes.DESERT); + + assertEquals(VillagerType.DESERT, fixture(villagers, PACK, Biomes.DESERT, desert, Map.of()).create(report).villagerType()); + assertEquals(VillagerType.SNOW, fixture(villagers, PACK, Biomes.DESERT, desert, entries(VILLAGER_TYPE, "minecraft:snow")) + .create(report).villagerType()); + assertEquals(List.of(), warnings); + + assertEquals(VillagerType.DESERT, fixture(villagers, PACK, Biomes.DESERT, desert, entries(VILLAGER_TYPE, "minecraft:nope")) + .create(report).villagerType()); + assertEquals(List.of("Pack \"test\", config \"BIOME\": attribute \"terra:biome/villager_type\" skipped: " + + "no such villager type \"minecraft:nope\""), warnings); + + assertEquals(VillagerType.PLAINS, fixture(villagers, PACK, Biomes.PLAINS, biome(Biomes.PLAINS), Map.of()) + .create(report).villagerType()); + parents.beginLoad(villagers); + PackParents bare = parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report); + TestBiome biome = new TestBiome(CONFIG, 0, Biomes.DESERT.identifier()); + biome.proto().setParentEntries(parents.biomeEntries(bare, Biomes.DESERT, desert)); + assertEquals(VillagerType.DESERT, + new MinecraftBiomeFactory(HANDLE, villagers).create(Biomes.DESERT, desert, biome, bare, report).villagerType()); + } + + @Test + void upperCaseVillagerTypeWarns() { + VanillaContext villagers = VanillaContext.of(REGISTRIES, key -> key == Biomes.DESERT ? VillagerType.DESERT : null); + Map, AttributeEntry> entries = Map.of(attribute(VILLAGER_TYPE), + AttributeEntry.override(RegistryKey.of("minecraft", "Snow"))); + assertEquals(VillagerType.DESERT, fixture(villagers, PACK, Biomes.DESERT, biome(Biomes.DESERT), entries).create(report) + .villagerType()); + assertEquals(1, warnings.size(), warnings.toString()); + assertTrue(warnings.getFirst().startsWith("Pack \"test\", config \"BIOME\": attribute \"terra:biome/villager_type\" skipped: " + + "invalid ID \"minecraft:Snow\""), warnings.getFirst()); + } + + @Test + void reloadBuildsEqualBiome() { + Biome plains = biome(Biomes.PLAINS); + Map, AttributeEntry> entries = entries(FOG_COLOR, "#123456", "terra:biome/temperature", 0.3); + Fixture before = fixture(Biomes.PLAINS, plains, entries); + Biome first = before.create(report).biome(); + + parents.clearPacks(); + assertNull(parents.packOrNull(before.attributes(), attribute(FOG_COLOR))); + TestBiome biome = new TestBiome(CONFIG, 0, Biomes.PLAINS.identifier()); + AttributeMap.Builder builder = AttributeMap.builder(); + entries.forEach((attribute, entry) -> put(builder, attribute, entry)); + FakePackAttributes reloaded = new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(), + Map.of(biome, builder.build())); + PackParents again = parents.prepare(PACK, Optional.of(reloaded), report); + assertNotSame(before.pack(), again); + biome.proto().setParentEntries(parents.biomeEntries(again, Biomes.PLAINS, plains)); + Biome second = new MinecraftBiomeFactory(HANDLE, CONTEXT).create(Biomes.PLAINS, plains, biome, again, report).biome(); + + assertEquals(0.3f, second.getBaseTemperature()); + assertEquals(climate(first), climate(second)); + assertEquals(effects(first), effects(second)); + assertEquals(environment(first), environment(second)); + assertEquals(List.of(), warnings); + } +} diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactoryTest.java b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactoryTest.java new file mode 100644 index 000000000..7f5a03565 --- /dev/null +++ b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactoryTest.java @@ -0,0 +1,358 @@ +package com.dfsek.terra.mod.attribute; + +import com.mojang.serialization.Lifecycle; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.HolderSet; +import net.minecraft.core.MappedRegistry; +import net.minecraft.core.RegistrationInfo; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.TagKey; +import net.minecraft.world.attribute.EnvironmentAttributeMap; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.timeline.Timeline; +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.function.BiConsumer; + +import com.dfsek.terra.api.config.ConfigPack; +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.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeMap; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.mod.generation.GenerationSettings; +import com.dfsek.terra.registry.OpenRegistryImpl; + +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.ATTRIBUTES; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + + +class MinecraftDimensionFactoryTest { + private static final Registry> REGISTRY = registry(); + private static final ConfigPack PACK = MinecraftAttributeParentsTest.pack("test", REGISTRY); + private static final RegistryOps OPS = CONTEXT.ops(); + private static final BiConsumer, String> FAIL = (attribute, reason) -> fail(attribute.getRegistryKey() + ": " + reason); + + private final List warnings = new ArrayList<>(); + private final List debugs = new ArrayList<>(); + private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add); + private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE); + private final MinecraftDimensionFactory factory = new MinecraftDimensionFactory(HANDLE, CONTEXT); + + private static DimensionType dimensionType(ResourceKey key) { + return REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(key).value(); + } + + private static Map environment(EnvironmentAttributeMap map) { + return (Map) VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, map, OPS); + } + + @SuppressWarnings("unchecked") + private static void put(AttributeMap.Builder builder, Attribute attribute, AttributeEntry entry) { + builder.put(attribute.key(), (AttributeEntry) entry); + } + + private static AttributeEntry decoded(String id, Object raw) { + try { + return HANDLE.decodeEntry(attribute(id), raw, HANDLE.plainContext()); + } catch(DecodeException e) { + throw new AssertionError(id + ": " + e.getMessage(), e); + } + } + + private PackParents prepare(ConfigPack pack, Map, AttributeEntry> entries, Map parentIds) { + AttributeMap.Builder builder = AttributeMap.builder(); + entries.forEach((attribute, entry) -> put(builder, attribute, entry)); + FakePackAttributes attributes = new FakePackAttributes(HANDLE, parents, builder.build(), parentIds, Map.of()); + parents.beginLoad(CONTEXT); + return parents.prepare(pack, Optional.of(attributes), report); + } + + private PackParents prepare(Map, AttributeEntry> entries) { + return prepare(PACK, entries, Map.of()); + } + + private PackParents bare() { + parents.beginLoad(CONTEXT); + return parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report); + } + + @Test + void noEntriesMatchesParent() { + DimensionType overworld = dimensionType(BuiltinDimensionTypes.OVERWORLD); + DimensionType built = factory.create(prepare(Map.of()), null); + + assertEquals(overworld, built); + assertNotSame(overworld, built); + assertEquals(List.of(), warnings); + assertEquals(List.of(), debugs); + } + + @Test + void noAttributesMatchesTheParent() { + DimensionType overworld = dimensionType(BuiltinDimensionTypes.OVERWORLD); + DimensionType built = factory.create(bare(), null); + + assertEquals(overworld, built); + assertNotSame(overworld, built); + assertEquals(List.of(), warnings); + assertEquals(List.of(), debugs); + } + + @Test + void createdTypeRegistersBesideItsParent() { + assertRegistersBesideOverworld(factory.create(prepare(Map.of()), null)); + assertRegistersBesideOverworld(factory.create(bare(), null)); + } + + private static void assertRegistersBesideOverworld(DimensionType built) { + MappedRegistry registry = new MappedRegistry<>(Registries.DIMENSION_TYPE, Lifecycle.stable()); + registry.register(BuiltinDimensionTypes.OVERWORLD, dimensionType(BuiltinDimensionTypes.OVERWORLD), RegistrationInfo.BUILT_IN); + ResourceKey key = ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.fromNamespaceAndPath("terra", "test")); + assertDoesNotThrow(() -> registry.register(key, built, RegistrationInfo.BUILT_IN)); + } + + @Test + void equivalentInputMatchesVanilla() { + DimensionType nether = dimensionType(BuiltinDimensionTypes.NETHER); + PackAttributeTable table = PackAttributeTable.of(REGISTRY); + AttributeSlots netherSlots = new VanillaParentReader(HANDLE, CONTEXT).dimension(nether, table, FAIL); + Map, AttributeEntry> entries = new LinkedHashMap<>(); + List> attributes = new ArrayList<>(); + table.environment().forEach(bound -> attributes.add(bound.attribute())); + table.dimension().forEach(field -> attributes.add(field.attribute())); + for(Attribute attribute : attributes) { + AttributeEntry entry = netherSlots.get(attribute); + if(entry != null) entries.put(attribute, entry); + } + assertTrue(entries.size() > 5, "the nether has few entries: " + entries.size()); + + DimensionType built = factory.create(prepare(entries), null); + + assertEquals(nether.hasFixedTime(), built.hasFixedTime()); + assertEquals(nether.hasSkyLight(), built.hasSkyLight()); + assertEquals(nether.hasCeiling(), built.hasCeiling()); + assertEquals(nether.hasEnderDragonFight(), built.hasEnderDragonFight()); + assertEquals(nether.coordinateScale(), built.coordinateScale()); + assertEquals(nether.minY(), built.minY()); + assertEquals(nether.height(), built.height()); + assertEquals(nether.logicalHeight(), built.logicalHeight()); + assertEquals(nether.infiniburn().unwrapKey(), built.infiniburn().unwrapKey()); + assertEquals(nether.ambientLight(), built.ambientLight()); + assertEquals(nether.monsterSettings(), built.monsterSettings()); + assertEquals(nether.skybox(), built.skybox()); + assertEquals(nether.cardinalLightType(), built.cardinalLightType()); + assertEquals(Optional.empty(), built.defaultClock()); + assertEquals(nether.defaultClock(), built.defaultClock()); + + Map expected = environment(nether.attributes()); + Map actual = environment(built.attributes()); + for(Object key : expected.keySet()) assertEquals(expected.get(key), actual.get(key), String.valueOf(key)); + assertEquals(List.of(), warnings); + } + + @Test + void netherParentHasNoClock() { + PackParents pack = prepare(PACK, Map.of(), Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))); + DimensionType built = factory.create(pack, null); + + assertEquals(Optional.empty(), built.defaultClock()); + assertEquals(dimensionType(BuiltinDimensionTypes.NETHER), built); + assertEquals(List.of(), warnings); + } + + @Test + void packEntriesGoOnTheDimension() { + String fastLava = "minecraft:gameplay/fast_lava"; + DimensionType built = factory.create(prepare(Map.of(attribute(fastLava), decoded(fastLava, true))), null); + + assertTrue(built.attributes().contains(vanilla(fastLava))); + assertEquals(true, environment(built.attributes()).get(fastLava)); + assertEquals(List.of(), warnings); + } + + @Test + void invalidHeightIsSkippedAlone() { + String ambientLight = "terra:dimension/ambient_light"; + Map, AttributeEntry> entries = new LinkedHashMap<>(); + entries.put(attribute("terra:dimension/height"), AttributeEntry.override(100)); + entries.put(attribute(ambientLight), decoded(ambientLight, 0.5)); + + PackParents pack = prepare(entries); + DimensionType built = factory.create(pack, null); + + assertEquals(List.of("Pack \"test\", config \"pack.yml\": attribute \"terra:dimension/height\" skipped: " + + "logical_height cannot be higher than height"), warnings); + assertEquals(384, built.height()); + assertEquals(0.5f, built.ambientLight()); + assertEquals(384, factory.generationSettings(pack, built).height().getRange()); + } + + @Test + void invalidHeightKeepsThePacksAttributes() { + String fastLava = "minecraft:gameplay/fast_lava"; + String height = "terra:dimension/height"; + Map, AttributeEntry> entries = new LinkedHashMap<>(); + entries.put(attribute(height), AttributeEntry.override(100)); + entries.put(attribute(fastLava), decoded(fastLava, true)); + assertInvalidHeightKeepsFastLava(prepare(entries), fastLava); + + warnings.clear(); + OpenRegistryImpl> narrow = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE); + narrow.register(attribute(height).getRegistryKey(), attribute(height)); + narrow.register(attribute(fastLava).getRegistryKey(), attribute(fastLava)); + assertInvalidHeightKeepsFastLava(prepare(MinecraftAttributeParentsTest.pack("test", narrow), entries, Map.of()), fastLava); + } + + private void assertInvalidHeightKeepsFastLava(PackParents pack, String fastLava) { + DimensionType built = factory.create(pack, null); + + assertEquals(List.of("Pack \"test\", config \"pack.yml\": attribute \"terra:dimension/height\" skipped: " + + "logical_height cannot be higher than height"), warnings); + assertEquals(384, built.height()); + assertTrue(built.attributes().contains(vanilla(fastLava))); + assertEquals(true, environment(built.attributes()).get(fastLava)); + } + + @Test + void validHeightOverrideReachesBoth() { + String minY = "terra:dimension/min_y"; + String height = "terra:dimension/height"; + Map, AttributeEntry> entries = new LinkedHashMap<>(); + entries.put(attribute(minY), decoded(minY, -128)); + entries.put(attribute(height), decoded(height, 512)); + PackParents pack = prepare(entries); + + DimensionType built = factory.create(pack, null); + GenerationSettings settings = factory.generationSettings(pack, built); + + assertEquals(-128, built.minY()); + assertEquals(512, built.height()); + assertEquals(-128, settings.height().getMin()); + assertEquals(512, settings.height().getRange()); + assertEquals(List.of(), warnings); + } + + @Test + void timelineTagIsUsed() { + TagKey tag = TagKey.create(Registries.TIMELINE, Identifier.parse("minecraft:in_overworld")); + DimensionType nether = dimensionType(BuiltinDimensionTypes.NETHER); + assertNotEquals(Optional.of(tag), nether.timelines().unwrapKey()); + PackParents pack = prepare(PACK, Map.of(), Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))); + DimensionType built = factory.create(pack, tag); + + assertTrue(built.timelines() instanceof HolderSet.Named, String.valueOf(built.timelines())); + assertEquals(Optional.of(tag), built.timelines().unwrapKey()); + assertEquals(List.of(), warnings); + } + + @Test + void rejectedTimelineTag() { + TagKey tag = TagKey.create(Registries.TIMELINE, Identifier.parse("terra:nope")); + HolderLookup.RegistryLookup timelines = REGISTRIES.lookupOrThrow(Registries.TIMELINE); + HolderLookup.RegistryLookup withoutTag = new HolderLookup.RegistryLookup.Delegate<>() { + @Override + public HolderLookup.RegistryLookup parent() { + return timelines; + } + + @Override + public Optional> get(TagKey key) { + return key.equals(tag) ? Optional.empty() : timelines.get(key); + } + }; + HolderLookup.Provider registries = HolderLookup.Provider.create(REGISTRIES.listRegistries() + .map(lookup -> lookup.key().equals(Registries.TIMELINE) ? withoutTag : lookup)); + MinecraftDimensionFactory strict = new MinecraftDimensionFactory(HANDLE, VanillaContext.of(registries, key -> null)); + + DimensionType built = strict.create(prepare(Map.of()), tag); + + assertEquals(1, warnings.size(), String.valueOf(warnings)); + String prefix = "Pack \"test\", config \"pack.yml\": \"schedules\" ignored: "; + assertTrue(warnings.getFirst().startsWith(prefix), warnings.getFirst()); + assertTrue(Character.isLowerCase(warnings.getFirst().charAt(prefix.length())), warnings.getFirst()); + assertEquals(dimensionType(BuiltinDimensionTypes.OVERWORLD).timelines().unwrapKey(), built.timelines().unwrapKey()); + } + + @Test + void unappliedPackEntriesAreDebugLogged() { + Attribute own = HANDLE.attributeBuilder(AttributeKey.parse("addon:own"), + HANDLE.types().integer(), 0).build(); + Registry> registry = registry(own); + PackParents pack = prepare(MinecraftAttributeParentsTest.pack("test", registry), Map.of(own, AttributeEntry.override(3)), + Map.of()); + factory.create(pack, null); + + assertEquals(List.of("Pack \"test\": attribute \"addon:own\" is not applied on this platform"), debugs); + } + + private static void assertOverworldGeneration(GenerationSettings settings) { + assertEquals(-64, settings.height().getMin()); + assertEquals(384, settings.height().getRange()); + assertEquals(63, settings.sealevel()); + assertEquals(true, settings.mobGeneration()); + assertEquals(64, settings.spawnHeight()); + } + + private GenerationSettings generation(PackParents pack) { + return factory.generationSettings(pack, factory.create(pack, null)); + } + + @Test + void generationSettingsFromAttributes() { + assertOverworldGeneration(generation(prepare(Map.of()))); + + String seaLevel = "terra:world/sea_level"; + String spawnHeight = "terra:world/spawn_height"; + String mobGeneration = "terra:world/mob_generation"; + Map, AttributeEntry> entries = new LinkedHashMap<>(); + entries.put(attribute(seaLevel), decoded(seaLevel, 40)); + entries.put(attribute(spawnHeight), decoded(spawnHeight, 90)); + entries.put(attribute(mobGeneration), decoded(mobGeneration, false)); + GenerationSettings settings = generation(prepare(entries)); + + assertEquals(40, settings.sealevel()); + assertEquals(90, settings.spawnHeight()); + assertEquals(false, settings.mobGeneration()); + assertEquals(-64, settings.height().getMin()); + assertEquals(384, settings.height().getRange()); + assertEquals(List.of(), warnings); + } + + @Test + void generationWithoutAttributes() { + assertOverworldGeneration(generation(bare())); + + OpenRegistryImpl> noWorld = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE); + ATTRIBUTES.stream() + .filter(attribute -> !attribute.getRegistryKey().toString().startsWith("terra:world/")) + .forEach(attribute -> noWorld.register(attribute.getRegistryKey(), attribute)); + PackParents pack = prepare(MinecraftAttributeParentsTest.pack("noworld", noWorld), Map.of(), Map.of()); + assertNull(pack.table().seaLevel()); + assertOverworldGeneration(generation(pack)); + assertEquals(List.of(), warnings); + } +} diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTestSupport.java b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTestSupport.java new file mode 100644 index 000000000..4cba2c23f --- /dev/null +++ b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTestSupport.java @@ -0,0 +1,73 @@ +package com.dfsek.terra.mod.attribute; + +import net.minecraft.SharedConstants; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.data.registries.VanillaRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.server.Bootstrap; +import net.minecraft.tags.TagLoader; +import net.minecraft.world.attribute.EnvironmentAttribute; + +import java.util.List; + +import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTable; +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.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeLookup; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.registry.OpenRegistryImpl; +import com.dfsek.terra.world.attribute.AttributeHandleImpl; + + +final class MinecraftTestSupport { + static { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + } + + static final HolderLookup.Provider REGISTRIES = VanillaRegistries.createWorldLookup(); + static final VanillaContext CONTEXT = VanillaContext.of(REGISTRIES, key -> null); + static final AttributeHandle HANDLE = new AttributeHandleImpl(); + static final List> ATTRIBUTES = MinecraftAttributeTable.create(HANDLE); + + private static final Registry> TABLE = registry(); + + static final AttributeLookup LOOKUP = key -> { + RegistryKey id; + try { + id = RegistryKey.parseNamespaced(key); + } catch(IllegalArgumentException e) { + throw new DecodeException("unknown attribute", e); + } + return TABLE.get(id).orElseThrow(() -> new DecodeException("unknown attribute")); + }; + + private MinecraftTestSupport() { } + + static List> loadContext(net.minecraft.core.Registry.PendingTags... pending) { + return TagLoader.buildUpdatedLookups(RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY), List.of(pending)); + } + + static Registry> registry(Attribute... extra) { + OpenRegistryImpl> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE); + ATTRIBUTES.forEach(attribute -> registry.register(attribute.getRegistryKey(), attribute)); + for(Attribute attribute : extra) registry.register(attribute.getRegistryKey(), attribute); + return registry; + } + + @SuppressWarnings("unchecked") + static Attribute attribute(String id) { + AttributeKey key = AttributeKey.parse(id); + return (Attribute) TABLE.get(key.getRegistryKey()).orElseThrow(() -> new IllegalArgumentException("no attribute " + id)); + } + + static EnvironmentAttribute vanilla(String id) { + return BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.getOptional(Identifier.parse(id)) + .orElseThrow(() -> new IllegalArgumentException("no vanilla attribute " + id)); + } +} diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTimelinesTest.java b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTimelinesTest.java new file mode 100644 index 000000000..0e0200e98 --- /dev/null +++ b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTimelinesTest.java @@ -0,0 +1,416 @@ +package com.dfsek.terra.mod.attribute; + +import net.minecraft.core.Holder; +import net.minecraft.core.HolderSet; +import net.minecraft.core.MappedRegistry; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.TagKey; +import net.minecraft.tags.TimelineTags; +import net.minecraft.world.clock.WorldClock; +import net.minecraft.world.timeline.Timeline; +import net.minecraft.world.timeline.Timelines; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalInt; +import java.util.Set; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeMap; +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.ScheduleTrack; +import com.dfsek.terra.api.world.attribute.schedule.TimeMarker; +import com.dfsek.terra.mod.util.TagUtil; + +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla; +import static com.dfsek.terra.mod.attribute.VanillaContextTest.copy; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class MinecraftTimelinesTest { + private static final com.dfsek.terra.api.registry.Registry> REGISTRY = registry(); + private static final ConfigPack PACK = MinecraftAttributeParentsTest.pack("test", REGISTRY); + private static final PackAttributeTable TABLE = PackAttributeTable.of(REGISTRY); + private static final RegistryKey SEASONS = RegistryKey.parse("mypack:seasons"); + private static final RegistryKey OVERWORLD = RegistryKey.parse("minecraft:overworld"); + private static final String SKY_COLOR = "minecraft:visual/sky_color"; + private static final TagKey TERRA_TEST = TagKey.create(Registries.TIMELINE, Identifier.parse("terra:test")); + + private final List warnings = new ArrayList<>(); + private final List debugs = new ArrayList<>(); + private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add); + private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE); + + private static Object argument(Attribute attribute, Object raw) { + try { + return attribute.type().decodeArgument(Operation.OVERRIDE, raw, HANDLE.plainContext()); + } catch(DecodeException e) { + throw new AssertionError(attribute.getRegistryKey() + ": " + e.getMessage(), e); + } + } + + private static ScheduleTrack track(Attribute attribute, Object first, Object second) { + return new ScheduleTrack<>(Operation.OVERRIDE, List.of(new Keyframe(0, argument(attribute, first)), + new Keyframe(12000, argument(attribute, second))), + new Easing.Named("linear")); + } + + private static AttributeSchedule schedule(RegistryKey clock, Map markers) { + Attribute sky = attribute(SKY_COLOR); + return new AttributeSchedule(clock, OptionalInt.of(24000), Map.of(sky, track(sky, "#78a7ff", "#000000")), markers); + } + + private static AttributeSchedule skySchedule() { + return schedule(OVERWORLD, Map.of()); + } + + private record Load(MappedRegistry timelines, MappedRegistry clocks, VanillaContext context) { + static Load create() { + MappedRegistry clocks = bound(copy(Registries.WORLD_CLOCK)); + MappedRegistry timelines = bound(copy(Registries.TIMELINE)); + VanillaContext context = VanillaContext.ofLoad(List.of(copy(Registries.DIMENSION_TYPE), copy(Registries.NOISE_SETTINGS), + copy(Registries.BIOME), clocks, timelines), + MinecraftTestSupport.loadContext(), key -> null); + timelines.bindTags(Map.of(TimelineTags.IN_OVERWORLD, List.of(timelines.get(Timelines.OVERWORLD_DAY).orElseThrow(), + timelines.get(Timelines.MOON).orElseThrow()), + TimelineTags.UNIVERSAL, List.of())); + return new Load(timelines, clocks, context); + } + + private static MappedRegistry bound(MappedRegistry registry) { + try { + Method bind = Holder.Reference.class.getDeclaredMethod("bindValue", Object.class); + bind.setAccessible(true); + for(Map.Entry, T> entry : registered(registry).entrySet()) { + bind.invoke(registry.get(entry.getKey()).orElseThrow(), entry.getValue()); + } + } catch(ReflectiveOperationException e) { + throw new AssertionError(e); + } + return registry; + } + + @SuppressWarnings("unchecked") + private static Map, T> registered(MappedRegistry registry) throws ReflectiveOperationException { + java.lang.reflect.Field byValue = MappedRegistry.class.getDeclaredField("byValue"); + byValue.setAccessible(true); + Map, T> values = new LinkedHashMap<>(); + ((Map>) byValue.get(registry)).forEach((value, holder) -> values.put(holder.key(), value)); + return values; + } + + Holder.Reference timeline(ResourceKey key) { + return timelines.get(key).orElseThrow(); + } + } + + private PackParents prepare(List> refs, + Map definitions) { + FakePackAttributes attributes = new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(), Map.of(), refs, + definitions); + parents.beginLoad(CONTEXT); + return parents.prepare(PACK, Optional.of(attributes), report); + } + + private static Either id(String id) { + return Either.left(RegistryKey.parse(id)); + } + + private static Either tag(String namespace, String id) { + return Either.right(com.dfsek.terra.api.registry.key.TagKey.of(RegistryKey.of(namespace, id))); + } + + private static String skipped(String schedule, String reason) { + return "Pack \"test\": schedule \"" + schedule + "\" skipped: " + reason; + } + + private void assertOneWarningStartingWith(String prefix) { + assertEquals(1, warnings.size(), String.valueOf(warnings)); + assertTrue(warnings.getFirst().startsWith(prefix), warnings.getFirst()); + } + + @Test + void definitionParses() { + Timeline timeline = MinecraftTimelines.create(SEASONS, skySchedule(), TABLE, HANDLE, CONTEXT, report); + + assertNotNull(timeline, String.valueOf(warnings)); + assertEquals(Optional.of(24000), timeline.periodTicks()); + assertEquals(Set.of(vanilla(SKY_COLOR)), timeline.attributes()); + assertEquals(Optional.of(ResourceKey.create(Registries.WORLD_CLOCK, Identifier.parse("minecraft:overworld"))), + timeline.clock().unwrapKey()); + assertEquals(List.of(), warnings); + assertEquals(List.of(), debugs); + } + + @Test + void upperCaseIdsWarn() { + assertNull(assertDoesNotThrow(() -> MinecraftTimelines.create(RegistryKey.parse("mypack:Seasons"), skySchedule(), TABLE, HANDLE, + CONTEXT, report))); + assertOneWarningStartingWith(skipped("mypack:Seasons", "invalid ID \"mypack:Seasons\"")); + + warnings.clear(); + assertNull(assertDoesNotThrow(() -> MinecraftTimelines.create(SEASONS, schedule(RegistryKey.parse("minecraft:Overworld"), + Map.of()), TABLE, HANDLE, CONTEXT, report))); + assertOneWarningStartingWith(skipped("mypack:seasons", "invalid ID \"minecraft:Overworld\"")); + + warnings.clear(); + AttributeSchedule upperMarker = schedule(OVERWORLD, Map.of(RegistryKey.parse("mypack:Noon"), new TimeMarker(6000, false))); + assertNull(assertDoesNotThrow(() -> MinecraftTimelines.create(SEASONS, upperMarker, TABLE, HANDLE, CONTEXT, report))); + assertOneWarningStartingWith(skipped("mypack:seasons", "invalid ID \"mypack:Noon\"")); + } + + @Test + void unknownClockIsSkipped() { + assertNull(MinecraftTimelines.create(SEASONS, schedule(RegistryKey.parse("test:nope"), Map.of()), TABLE, HANDLE, CONTEXT, report)); + assertEquals(List.of(skipped("mypack:seasons", "no such clock \"test:nope\"")), warnings); + } + + @Test + void terraTracksAreDropped() { + Attribute sky = attribute(SKY_COLOR); + Attribute temperature = attribute("terra:biome/temperature"); + Map, ScheduleTrack> tracks = new LinkedHashMap<>(); + tracks.put(sky, track(sky, "#78a7ff", "#000000")); + tracks.put(temperature, track(temperature, 0.5, 1.0)); + AttributeSchedule schedule = new AttributeSchedule(OVERWORLD, OptionalInt.of(24000), tracks, Map.of()); + + Timeline timeline = MinecraftTimelines.create(SEASONS, schedule, TABLE, HANDLE, CONTEXT, report); + + assertNotNull(timeline, String.valueOf(warnings)); + assertEquals(Set.of(vanilla(SKY_COLOR)), timeline.attributes()); + assertEquals(List.of(), warnings); + assertEquals(List.of("Pack \"test\": attribute \"terra:biome/temperature\" is not applied on this platform"), debugs); + } + + @Test + void definitionsAreRegistered() { + Load load = Load.create(); + int before = load.timelines().size(); + PackParents pack = prepare(List.of(), Map.of(SEASONS, skySchedule())); + + MinecraftTimelines.register(PACK, pack, load.timelines(), HANDLE, load.context()); + + assertEquals(List.of(), warnings); + assertEquals(before + 1, load.timelines().size()); + assertDoesNotThrow(load.timelines()::freeze); + Timeline seasons = load.timelines().getValue(Identifier.parse("mypack:seasons")); + assertNotNull(seasons); + assertEquals(Set.of(vanilla(SKY_COLOR)), seasons.attributes()); + assertSame(load.clocks().get(Identifier.parse("minecraft:overworld")).orElseThrow(), seasons.clock()); + } + + @Test + void existingIdIsNotReplaced() { + Load load = Load.create(); + int before = load.timelines().size(); + PackParents pack = prepare(List.of(), Map.of(RegistryKey.parse("minecraft:day"), skySchedule())); + + MinecraftTimelines.register(PACK, pack, load.timelines(), HANDLE, load.context()); + + assertEquals(List.of(skipped("minecraft:day", "a timeline with this ID already exists")), warnings); + assertEquals(before, load.timelines().size()); + load.timelines().freeze(); + assertSame(REGISTRIES.lookupOrThrow(Registries.TIMELINE).getOrThrow(Timelines.OVERWORLD_DAY).value(), + load.timelines().getValue(Timelines.OVERWORLD_DAY)); + } + + @Test + void duplicateTimeMarkerIsDropped() { + Load load = Load.create(); + int before = load.timelines().size(); + Map seasonsMarkers = new LinkedHashMap<>(); + seasonsMarkers.put(RegistryKey.parse("minecraft:noon"), new TimeMarker(6000, true)); + seasonsMarkers.put(RegistryKey.parse("mypack:dawn"), new TimeMarker(0, false)); + Map definitions = new LinkedHashMap<>(); + definitions.put(SEASONS, schedule(OVERWORLD, seasonsMarkers)); + definitions.put(RegistryKey.parse("mypack:first"), schedule(OVERWORLD, Map.of(RegistryKey.parse("mypack:dusk"), + new TimeMarker(13000, false)))); + definitions.put(RegistryKey.parse("mypack:second"), schedule(OVERWORLD, Map.of(RegistryKey.parse("mypack:dusk"), + new TimeMarker(14000, false)))); + PackParents pack = prepare(List.of(), definitions); + + MinecraftTimelines.register(PACK, pack, load.timelines(), HANDLE, load.context()); + + assertEquals(List.of(markerDropped("mypack:seasons", "minecraft:noon"), markerDropped("mypack:second", "mypack:dusk")), + warnings); + assertEquals(before + 3, load.timelines().size()); + load.timelines().freeze(); + Map, Exception> errors = new HashMap<>(); + Timeline.validateRegistry(load.timelines(), errors); + assertEquals(Map.of(), errors); + assertEquals(Set.of("mypack:dawn"), markers(load.timelines().getValue(Identifier.parse("mypack:seasons")))); + assertEquals(Set.of("mypack:dusk"), markers(load.timelines().getValue(Identifier.parse("mypack:first")))); + Timeline second = load.timelines().getValue(Identifier.parse("mypack:second")); + assertEquals(Set.of(), markers(second)); + assertEquals(Set.of(vanilla(SKY_COLOR)), second.attributes(), "the tracks stay"); + } + + private static String markerDropped(String schedule, String marker) { + return "Pack \"test\": schedule \"" + schedule + "\" time marker \"" + marker + + "\" dropped: already defined for clock \"minecraft:overworld\""; + } + + private static Set markers(Timeline timeline) { + Set markers = new HashSet<>(); + timeline.registerTimeMarkers((key, marker) -> markers.add(key.identifier().toString())); + return markers; + } + + @Test + void noRefsMeansNoTag() { + assertNull(MinecraftTimelines.tagFor(PACK, prepare(List.of(), Map.of()))); + parents.beginLoad(CONTEXT); + assertNull(MinecraftTimelines.tagFor(PACK, parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), + report))); + assertEquals(List.of(), warnings); + } + + @Test + void upperCaseRefIsSkipped() { + Load load = Load.create(); + PackParents pack = prepare(List.of(tag("Mypack", "Tag"), id("minecraft:day")), Map.of()); + + TagKey tag = assertDoesNotThrow(() -> MinecraftTimelines.tagFor(PACK, pack)); + + assertEquals(TERRA_TEST, tag); + assertOneWarningStartingWith(skipped("#Mypack:Tag", "invalid ID \"Mypack:Tag\"")); + Map, List>> collect = new HashMap<>(); + MinecraftTimelines.fillTags(collect, load.timelines()); + assertEquals(List.of(load.timeline(Timelines.OVERWORLD_DAY)), collect.get(TERRA_TEST)); + assertEquals(1, warnings.size()); + } + + @Test + void tagsAreFilled() { + Load load = Load.create(); + Holder.Reference day = load.timeline(Timelines.OVERWORLD_DAY); + Holder.Reference moon = load.timeline(Timelines.MOON); + Holder.Reference villagers = load.timeline(Timelines.VILLAGER_SCHEDULE); + PackParents pack = prepare(List.of(id("minecraft:day"), tag("minecraft", "in_overworld"), id("minecraft:nope"), + tag("minecraft", "nope")), Map.of()); + assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(PACK, pack)); + assertEquals(List.of(), warnings); + + Map, List>> collect = new HashMap<>(); + collect.put(TimelineTags.IN_OVERWORLD, List.of(day, moon, villagers)); + MinecraftTimelines.fillTags(collect, load.timelines()); + + assertEquals(List.of(day, moon, villagers), collect.get(TERRA_TEST)); + assertEquals(List.of(day, moon, villagers), collect.get(TimelineTags.IN_OVERWORLD)); + assertEquals(List.of(skipped("minecraft:nope", "no such timeline"), skipped("#minecraft:nope", "no such timeline tag")), + warnings); + } + + @Test + void invalidRefsKeepParentTimelines() { + Load load = Load.create(); + Holder.Reference day = load.timeline(Timelines.OVERWORLD_DAY); + Holder.Reference moon = load.timeline(Timelines.MOON); + PackParents pack = prepare(List.of(tag("Mypack", "Tag"), id("minecraft:nope"), tag("minecraft", "nope")), Map.of()); + assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(PACK, pack)); + assertOneWarningStartingWith(skipped("#Mypack:Tag", "invalid ID \"Mypack:Tag\"")); + warnings.clear(); + + Map, List>> collect = new HashMap<>(); + collect.put(TimelineTags.IN_OVERWORLD, List.of(day, moon)); + MinecraftTimelines.fillTags(collect, load.timelines()); + + assertEquals(List.of(day, moon), collect.get(TERRA_TEST)); + assertTrue(collect.get(TERRA_TEST).contains(day), "the day cycle"); + assertEquals(List.of(skipped("minecraft:nope", "no such timeline"), skipped("#minecraft:nope", "no such timeline tag"), + "Pack \"test\", config \"pack.yml\": \"schedules\" ignored: no valid schedule; " + + "the parent's timelines are kept"), + warnings); + } + + @Test + void tagRefillsOnReload() { + Load load = Load.create(); + Registry timelines = load.timelines(); + Holder.Reference day = load.timeline(Timelines.OVERWORLD_DAY); + Holder.Reference moon = load.timeline(Timelines.MOON); + PackParents pack = prepare(List.of(id("mypack:seasons"), tag("minecraft", "in_overworld")), + Map.of(SEASONS, skySchedule())); + + MinecraftTimelines.register(PACK, pack, load.timelines(), HANDLE, load.context()); + TagKey tag = MinecraftTimelines.tagFor(PACK, pack); + assertEquals(TERRA_TEST, tag); + HolderSet.Named dimensionTimelines = load.context().ops().getter(Registries.TIMELINE).orElseThrow().get(tag) + .orElseThrow(); + assertFalse(dimensionTimelines.isBound()); + MinecraftTimelines.bindPendingTags(load.timelines()); + assertDoesNotThrow(load.timelines()::freeze); + Map, Exception> errors = new HashMap<>(); + Timeline.validateRegistry(timelines, errors); + assertEquals(Map.of(), errors); + + TagUtil.registerTimelineTags(timelines); + Holder.Reference seasons = timelines.get(Identifier.parse("mypack:seasons")).orElseThrow(); + assertEquals(List.of(seasons, day, moon), dimensionTimelines.stream().toList()); + assertSame(dimensionTimelines, timelines.get(TERRA_TEST).orElseThrow()); + assertEquals(List.of(day, moon), timelines.get(TimelineTags.IN_OVERWORLD).orElseThrow().stream().toList()); + assertTrue(seasons.is(TERRA_TEST)); + + int tagsBefore = frozenTags(load.timelines()).size(); + parents.beginPackReload(); + parents.prepare(PACK, Optional.of(new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(), Map.of(), + List.of(id("mypack:seasons"), tag("minecraft", "in_overworld")), + Map.of(SEASONS, skySchedule()))), report); + TagUtil.registerTimelineTags(timelines); + parents.endPackReload(); + assertSame(dimensionTimelines, timelines.get(TERRA_TEST).orElseThrow()); + assertEquals(List.of(seasons, day, moon), dimensionTimelines.stream().toList()); + assertEquals(tagsBefore, frozenTags(load.timelines()).size(), "the reload created no tag"); + assertEquals(List.of(), warnings); + } + + private static Map frozenTags(MappedRegistry registry) { + try { + java.lang.reflect.Field field = MappedRegistry.class.getDeclaredField("frozenTags"); + field.setAccessible(true); + return (Map) field.get(registry); + } catch(ReflectiveOperationException e) { + throw new AssertionError(e); + } + } + + @Test + void beginLoadDropsPendingTags() { + Load load = Load.create(); + PackParents pack = prepare(List.of(id("minecraft:day")), Map.of()); + assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(PACK, pack)); + + parents.beginLoad(CONTEXT); + Map, List>> collect = new HashMap<>(); + MinecraftTimelines.fillTags(collect, load.timelines()); + assertFalse(collect.containsKey(TERRA_TEST)); + } +} diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TagUtilTest.java b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TagUtilTest.java new file mode 100644 index 000000000..5b2ee4bcb --- /dev/null +++ b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TagUtilTest.java @@ -0,0 +1,106 @@ +package com.dfsek.terra.mod.attribute; + +import net.minecraft.core.Holder; +import net.minecraft.core.MappedRegistry; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.BiomeTags; +import net.minecraft.tags.TagKey; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.Biomes; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.mod.util.TagUtil; +import com.dfsek.terra.mod.util.TagUtil.PlatformTagSource; + +import static com.dfsek.terra.mod.attribute.VanillaContextTest.copy; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class TagUtilTest { + private static final Identifier TERRA_ID = Identifier.parse("terra:test/biome"); + private static final TagKey HAS_SNOW = tag("mypack:has_snow"); + + private final List warnings = new ArrayList<>(); + private final AttributeReport report = new AttributeReport("test", warnings::add, m -> { }); + private final MappedRegistry registry = copy(Registries.BIOME); + private final Holder terra = registry.get(Biomes.DESERT).orElseThrow(); + private final Map, List>> collect = new HashMap<>(); + + private static TagKey tag(String id) { + return TagKey.create(Registries.BIOME, Identifier.parse(id)); + } + + private Optional> lookup(Identifier id) { + return id.equals(TERRA_ID) ? Optional.of(terra) : registry.get(ResourceKey.create(Registries.BIOME, id)) + .map(h -> h); + } + + private void add(Map> byParent, String... tags) { + Set keys = new LinkedHashSet<>(); + for(String t : tags) keys.add(RegistryKey.parse(t)); + TagUtil.addTerraBiomes(collect, this::lookup, byParent, Map.of(TERRA_ID, new PlatformTagSource(report, "BIOME", keys))); + } + + private static void bindTags(Holder holder, TagKey tag) throws ReflectiveOperationException { + Method bind = Holder.Reference.class.getDeclaredMethod("bindTags", Collection.class); + bind.setAccessible(true); + bind.invoke(holder, List.of(tag)); + } + + @Test + void platformTagsAreAdded() { + Holder forest = registry.get(Biomes.FOREST).orElseThrow(); + collect.put(BiomeTags.IS_FOREST, new ArrayList<>(List.of(forest))); + + add(Map.of(), "mypack:has_snow", "minecraft:is_forest"); + + assertEquals(List.of(terra), collect.get(HAS_SNOW)); + assertEquals(List.of(forest, terra), collect.get(BiomeTags.IS_FOREST)); + assertEquals(List.of(), warnings); + } + + @Test + void inheritedTagsStillApply() throws ReflectiveOperationException { + Holder forest = registry.get(Biomes.FOREST).orElseThrow(); + bindTags(forest, BiomeTags.IS_FOREST); + Identifier forestId = Biomes.FOREST.identifier(); + + add(Map.of(forestId, List.of(TERRA_ID))); + + assertEquals(List.of(terra), collect.get(BiomeTags.IS_FOREST)); + assertEquals(List.of(), warnings); + } + + @Test + void upperCaseTagIsIgnored() { + add(Map.of(), "mypack:Has_Snow"); + + assertTrue(collect.isEmpty(), collect.toString()); + assertEquals(1, warnings.size(), warnings.toString()); + assertTrue(warnings.getFirst().startsWith("Pack \"test\", config \"BIOME\": \"mypack:Has_Snow\" ignored: invalid ID "), + warnings.getFirst()); + } + + @Test + void missingMinecraftTagWarnsAndIsCreated() { + add(Map.of(), "minecraft:is_forrest"); + + assertEquals(List.of("Pack \"test\", config \"BIOME\": tag \"minecraft:is_forrest\" created: no such tag in the minecraft namespace"), + warnings); + assertEquals(List.of(terra), collect.get(tag("minecraft:is_forrest"))); + } +} diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TestBiome.java b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TestBiome.java new file mode 100644 index 000000000..32eb2c046 --- /dev/null +++ b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TestBiome.java @@ -0,0 +1,67 @@ +package com.dfsek.terra.mod.attribute; + +import net.minecraft.resources.Identifier; + +import java.util.Set; + +import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.biome.PlatformBiome; +import com.dfsek.terra.mod.config.ProtoPlatformBiome; + + +final class TestBiome implements Biome { + private final String id; + private final int intId; + private final PlatformBiome platformBiome; + private final Context context = new Context(); + + TestBiome(String id, int intId, Identifier parent) { + this(id, intId, new ProtoPlatformBiome(parent)); + } + + TestBiome(String id, int intId, PlatformBiome platformBiome) { + this.id = id; + this.intId = intId; + this.platformBiome = platformBiome; + } + + ProtoPlatformBiome proto() { + return (ProtoPlatformBiome) platformBiome; + } + + @Override + public PlatformBiome getPlatformBiome() { + return platformBiome; + } + + @Override + public int getColor() { + return 0; + } + + @Override + public Set getTags() { + return Set.of(); + } + + @Override + public int getIntID() { + return intId; + } + + @Override + public String getID() { + return id; + } + + @Override + public Context getContext() { + return context; + } + + @Override + public String toString() { + return "TestBiome[" + id + "]"; + } +} diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaCodecHarnessTest.java b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaCodecHarnessTest.java new file mode 100644 index 000000000..26e85d2c4 --- /dev/null +++ b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaCodecHarnessTest.java @@ -0,0 +1,308 @@ +package com.dfsek.terra.mod.attribute; + +import com.mojang.serialization.Codec; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceKey; +import net.minecraft.util.ARGB; +import net.minecraft.world.attribute.EnvironmentAttribute; +import net.minecraft.world.attribute.EnvironmentAttributeMap; +import net.minecraft.world.level.biome.Biomes; +import net.minecraft.world.timeline.Timeline; +import org.joml.Vector3f; +import org.joml.Vector3fc; +import org.joml.Vector4f; +import org.joml.Vector4fc; +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.OptionalInt; +import java.util.Set; +import java.util.TreeSet; + +import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes; +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.AttributeKey; +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.ScheduleTrack; +import com.dfsek.terra.api.world.attribute.schedule.TimeMarker; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.api.world.attribute.value.TriState; + +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.LOOKUP; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class VanillaCodecHarnessTest { + private static final RegistryOps OPS = CONTEXT.ops(); + private static final DecodeContext PLAIN = HANDLE.plainContext(); + + private static final String FOG_COLOR = "minecraft:visual/fog_color"; + private static final String CLOUD_COLOR = "minecraft:visual/cloud_color"; + private static final String SKY_COLOR = "minecraft:visual/sky_color"; + private static final String STAR_BRIGHTNESS = "minecraft:visual/star_brightness"; + private static final String WATER_FOG_END = "minecraft:visual/water_fog_end_distance"; + private static final String EYEBLOSSOM_OPEN = "minecraft:gameplay/eyeblossom_open"; + private static final String SURFACE_SLIME_SPAWN_CHANCE = "minecraft:gameplay/surface_slime_spawn_chance"; + + private static final RegistryKey OVERWORLD = RegistryKey.parse("minecraft:overworld"); + private static final RegistryKey NOON = RegistryKey.parse("mypack:noon"); + private static final RegistryKey DUSK = RegistryKey.parse("mypack:dusk"); + + @SuppressWarnings("unchecked") + private static Codec codec(String id) { + return (Codec) vanilla(id).valueCodec(); + } + + @SuppressWarnings("unchecked") + private static Map asMap(Object raw) { + return (Map) assertInstanceOf(Map.class, raw); + } + + private static float c(int n) { + return (n + 0.25f) / 255f; + } + + private static Object argument(Attribute attribute, Operation operation, Object raw) throws DecodeException { + return attribute.type().decodeArgument(operation, raw, PLAIN); + } + + @Test + void bootstrapsVanilla() { + assertTrue(REGISTRIES.lookupOrThrow(Registries.BIOME).get(Biomes.PLAINS).isPresent()); + assertTrue(REGISTRIES.lookupOrThrow(Registries.WORLD_CLOCK) + .get(ResourceKey.create(Registries.WORLD_CLOCK, Identifier.withDefaultNamespace("overworld"))).isPresent()); + assertTrue(REGISTRIES.lookupOrThrow(Registries.TIMELINE) + .get(ResourceKey.create(Registries.TIMELINE, Identifier.withDefaultNamespace("day"))).isPresent()); + } + + @Test + void hexColorsMatchVanilla() throws DecodeException { + Attribute fog = attribute(FOG_COLOR); + Object fogForm = fog.type().encode(fog.type().decode("#c0d8ff", PLAIN)); + assertEquals("#c0d8ff", fogForm); + Codec fogCodec = codec(FOG_COLOR); + assertEquals(ARGB.vector3fFromRGB24(0xc0d8ff), VanillaCodecs.parse(fogCodec, fogForm, OPS)); + + Attribute cloud = attribute(CLOUD_COLOR); + Object cloudForm = cloud.type().encode(cloud.type().decode("#80ff0000", PLAIN)); + assertEquals("#80ff0000", cloudForm); + Codec cloudCodec = codec(CLOUD_COLOR); + assertEquals(ARGB.vector4fFromARGB32(0x80ff0000), VanillaCodecs.parse(cloudCodec, cloudForm, OPS)); + + assertEquals(Color.rgb(0xc0d8ff), fog.type().decode(VanillaCodecs.encode(fogCodec, ARGB.vector3fFromRGB24(0xc0d8ff), OPS), PLAIN)); + assertEquals(Color.argb(0x80ff0000), + cloud.type().decode(VanillaCodecs.encode(cloudCodec, ARGB.vector4fFromARGB32(0x80ff0000), OPS), PLAIN)); + } + + @Test + void floatListColorsMatchVanilla() throws DecodeException { + Attribute fog = attribute(FOG_COLOR); + Object fogForm = fog.type().encode(new Color(c(51), c(102), c(153), 1f)); + assertEquals(3, assertInstanceOf(List.class, fogForm).size()); + Vector3fc fogValue = VanillaCodecs.parse(VanillaCodecHarnessTest.codec(FOG_COLOR), fogForm, OPS); + assertEquals(0x336699, ARGB.colorFromVector3f(fogValue) & 0xFFFFFF); + assertEquals(new Vector3f(c(51), c(102), c(153)), fogValue, "vanilla keeps the float channels exactly"); + + Attribute cloud = attribute(CLOUD_COLOR); + Object cloudForm = cloud.type().encode(new Color(c(51), c(102), c(153), c(204))); + List cloudList = assertInstanceOf(List.class, cloudForm); + assertEquals(4, cloudList.size()); + assertEquals(c(204), cloudList.get(3), "alpha is last"); + Vector4fc cloudValue = VanillaCodecs.parse(VanillaCodecHarnessTest.codec(CLOUD_COLOR), cloudForm, OPS); + assertEquals(0xcc336699, ARGB.colorFromVector4f(cloudValue)); + assertEquals(new Vector4f(c(51), c(102), c(153), c(204)), cloudValue, "vanilla keeps the float channels exactly"); + } + + @Test + void triStateMatchesVanilla() throws DecodeException { + Attribute eyeblossom = attribute(EYEBLOSSOM_OPEN); + Codec codec = codec(EYEBLOSSOM_OPEN); + Map forms = Map.of(TriState.TRUE, true, TriState.FALSE, false, TriState.DEFAULT, "default"); + Map vanillaValues = Map.of( + TriState.TRUE, net.minecraft.util.TriState.TRUE, + TriState.FALSE, net.minecraft.util.TriState.FALSE, + TriState.DEFAULT, net.minecraft.util.TriState.DEFAULT); + for(TriState value : TriState.values()) { + Object form = eyeblossom.type().encode(value); + assertEquals(forms.get(value), form, value.name()); + assertEquals(vanillaValues.get(value), VanillaCodecs.parse(codec, form, OPS), value.name()); + assertEquals(value, eyeblossom.type().decode(VanillaCodecs.encode(codec, vanillaValues.get(value), OPS), PLAIN), + value.name()); + } + } + + @Test + void everyDefaultMatchesVanilla() { + List mismatches = new ArrayList<>(); + Set checked = new TreeSet<>(); + for(AttributeKey key : MinecraftAttributes.all()) { + if(!key.getRegistryKey().getNamespace().equals("minecraft")) continue; + String id = key.toString(); + String mismatch = defaultMismatch(attribute(id), vanilla(id)); + if(mismatch != null) mismatches.add(id + ": " + mismatch); + checked.add(id); + } + assertEquals(List.of(), mismatches); + Set vanillaIds = new TreeSet<>(); + BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.keySet().forEach(id -> vanillaIds.add(id.toString())); + assertEquals(vanillaIds, checked, "every vanilla attribute has a Terra key in the minecraft namespace"); + } + + private static String defaultMismatch(Attribute attribute, EnvironmentAttribute vanilla) { + if(attribute.defaultValue() == null) return "Terra has no default"; + Object terraForm = attribute.type().encode(attribute.defaultValue()); + Codec codec = vanilla.valueCodec(); + Object expected = VanillaCodecs.encode(codec, vanilla.defaultValue(), OPS); + Object actual; + try { + actual = VanillaCodecs.encode(codec, VanillaCodecs.parse(codec, terraForm, OPS), OPS); + } catch(DecodeException e) { + return "vanilla rejects " + terraForm + ": " + e.getMessage(); + } + return expected.equals(actual) ? null : "Terra " + terraForm + " reads as " + actual + ", vanilla default is " + expected; + } + + @Test + void modifierEntriesParse() throws DecodeException { + Attribute water = attribute(WATER_FOG_END); + Object multiply = HANDLE.encodeEntry(water, AttributeEntry.of(Operation.MULTIPLY, argument(water, Operation.MULTIPLY, 0.85))); + EnvironmentAttributeMap waterMap = VanillaCodecs.parse(EnvironmentAttributeMap.CODEC, Map.of(WATER_FOG_END, multiply), OPS); + @SuppressWarnings("unchecked") + EnvironmentAttribute vanillaWater = (EnvironmentAttribute) vanilla(WATER_FOG_END); + assertTrue(waterMap.contains(vanillaWater)); + assertEquals(85f, waterMap.applyModifier(vanillaWater, 100f), 1e-4f); + + Attribute fog = attribute(FOG_COLOR); + Object blend = HANDLE.encodeEntry(fog, AttributeEntry.of(Operation.ALPHA_BLEND, argument(fog, Operation.ALPHA_BLEND, "#80ff0000"))); + EnvironmentAttributeMap fogMap = VanillaCodecs.parse(EnvironmentAttributeMap.CODEC, Map.of(FOG_COLOR, blend), OPS); + @SuppressWarnings("unchecked") + EnvironmentAttribute vanillaFog = (EnvironmentAttribute) vanilla(FOG_COLOR); + assertTrue(fogMap.contains(vanillaFog)); + float alpha = 128 / 255f; + Vector3fc blended = fogMap.applyModifier(vanillaFog, new Vector3f(0, 0, 1)); + assertEquals(alpha, blended.x(), 1e-3f, blended.toString()); + assertEquals(0, blended.y(), 1e-3f, blended.toString()); + assertEquals(1 - alpha, blended.z(), 1e-3f, blended.toString()); + } + + private static AttributeSchedule clockOnly() { + return new AttributeSchedule(OVERWORLD, OptionalInt.empty(), Map.of(), Map.of()); + } + + private static AttributeSchedule periodic(Map, ScheduleTrack> tracks, Map markers) { + return new AttributeSchedule(OVERWORLD, OptionalInt.of(24000), tracks, markers); + } + + private static AttributeSchedule withMarkers() { + Map markers = new LinkedHashMap<>(); + markers.put(NOON, new TimeMarker(12000, false)); + markers.put(DUSK, new TimeMarker(13000, true)); + return periodic(Map.of(), markers); + } + + private static AttributeSchedule withTrack(String id, Operation operation, Easing ease, Object first, Object second) + throws DecodeException { + Attribute attribute = attribute(id); + List keyframes = List.of(new Keyframe(0, argument(attribute, operation, first)), + new Keyframe(12000, argument(attribute, operation, second))); + return periodic(Map.of(attribute, new ScheduleTrack<>(operation, keyframes, ease)), Map.of()); + } + + private static AttributeSchedule skyColorTrack() throws DecodeException { + return withTrack(SKY_COLOR, Operation.OVERRIDE, new Easing.Named("linear"), "#78a7ff", "#000000"); + } + + private static Map schedules() throws DecodeException { + Map schedules = new LinkedHashMap<>(); + schedules.put("a: clock only", clockOnly()); + schedules.put("b: period", periodic(Map.of(), Map.of())); + schedules.put("c: time markers", withMarkers()); + schedules.put("d: override, linear", skyColorTrack()); + schedules.put("e: maximum, constant", withTrack(SURFACE_SLIME_SPAWN_CHANCE, Operation.MAXIMUM, new Easing.Named("constant"), + 0.25, 0.75)); + schedules.put("f: cubic bezier", withTrack(STAR_BRIGHTNESS, Operation.OVERRIDE, new Easing.CubicBezier(0.25f, 0.1f, 0.25f, 1f), + 1.0, 0.0)); + return schedules; + } + + @Test + void schedulesParseAsTimelines() throws DecodeException { + for(Map.Entry entry : schedules().entrySet()) { + String name = entry.getKey(); + AttributeSchedule schedule = entry.getValue(); + Timeline timeline = VanillaCodecs.parse(Timeline.DIRECT_CODEC, HANDLE.encodeSchedule(schedule), OPS); + Object vanillaForm = VanillaCodecs.encode(Timeline.DIRECT_CODEC, timeline, OPS); + ScheduleDecodeResult result = HANDLE.decodeSchedule(RegistryKey.parse("mypack:schedule"), asMap(vanillaForm), LOOKUP, + PLAIN); + assertEquals(List.of(), result.droppedTracks(), name); + assertEquals(Optional.empty(), result.skipped(), name); + assertEquals(Optional.of(schedule), result.schedule(), name); + } + } + + @Test + void encodedSchedulesOmitDefaults() throws DecodeException { + Map clockOnly = HANDLE.encodeSchedule(clockOnly()); + assertEquals(Map.of("clock", "minecraft:overworld"), clockOnly); + VanillaCodecs.parse(Timeline.DIRECT_CODEC, clockOnly, OPS); + + Map markers = HANDLE.encodeSchedule(withMarkers()); + Map encodedMarkers = asMap(markers.get("time_markers")); + assertFalse(asMap(encodedMarkers.get("mypack:noon")).containsKey("show_in_commands")); + assertEquals(true, asMap(encodedMarkers.get("mypack:dusk")).get("show_in_commands")); + VanillaCodecs.parse(Timeline.DIRECT_CODEC, markers, OPS); + + Map track = HANDLE.encodeSchedule(skyColorTrack()); + Map encodedTrack = asMap(asMap(track.get("tracks")).get(SKY_COLOR)); + assertFalse(encodedTrack.containsKey("modifier")); + assertFalse(encodedTrack.containsKey("ease")); + VanillaCodecs.parse(Timeline.DIRECT_CODEC, track, OPS); + } + + @Test + void vanillaTimelinesRoundTrip() throws DecodeException { + List> timelines = REGISTRIES.lookupOrThrow(Registries.TIMELINE).listElements().toList(); + assertFalse(timelines.isEmpty()); + for(Holder.Reference holder : timelines) { + String name = holder.key().identifier().toString(); + Object first = VanillaCodecs.encode(Timeline.DIRECT_CODEC, holder.value(), OPS); + ScheduleDecodeResult result = HANDLE.decodeSchedule(RegistryKey.parse(name), asMap(first), LOOKUP, PLAIN); + assertEquals(List.of(), result.droppedTracks(), name); + assertEquals(Optional.empty(), result.skipped(), name); + Map terraForm = HANDLE.encodeSchedule(result.schedule().orElseThrow()); + Timeline reparsed = VanillaCodecs.parse(Timeline.DIRECT_CODEC, terraForm, OPS); + assertEquals(first, VanillaCodecs.encode(Timeline.DIRECT_CODEC, reparsed, OPS), name); + } + } + + @Test + void reasonsStartLowerCase() { + DecodeException e = assertThrows(DecodeException.class, () -> VanillaCodecs.parse(Codec.INT, "x", OPS)); + assertEquals("not a number: x", e.getMessage()); + } +} diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaContextTest.java b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaContextTest.java new file mode 100644 index 000000000..71ab528c7 --- /dev/null +++ b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaContextTest.java @@ -0,0 +1,97 @@ +package com.dfsek.terra.mod.attribute; + +import com.mojang.serialization.Lifecycle; +import net.minecraft.core.Holder; +import net.minecraft.core.MappedRegistry; +import net.minecraft.core.RegistrationInfo; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.BlockTags; +import net.minecraft.tags.TagKey; +import net.minecraft.tags.TagLoader; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class VanillaContextTest { + static MappedRegistry copy(ResourceKey> key) { + MappedRegistry registry = new MappedRegistry<>(key, Lifecycle.stable()); + REGISTRIES.lookupOrThrow(key).listElements() + .forEach(holder -> registry.register(holder.key(), holder.value(), RegistrationInfo.BUILT_IN)); + return registry; + } + + @Test + void unknownIdsKeepLoadFreezable() { + MappedRegistry dimensionTypes = copy(Registries.DIMENSION_TYPE); + MappedRegistry noiseSettings = copy(Registries.NOISE_SETTINGS); + MappedRegistry biomes = copy(Registries.BIOME); + VanillaContext context = VanillaContext.ofLoad(List.of(dimensionTypes, noiseSettings, biomes), MinecraftTestSupport.loadContext(), + key -> null); + + ResourceKey nope = ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse("minecraft:nope")); + assertFalse(context.dimensionTypes().get(nope).isPresent()); + assertFalse(context.noiseSettings().get(ResourceKey.create(Registries.NOISE_SETTINGS, Identifier.parse("minecraft:nope"))) + .isPresent()); + assertFalse(context.biomes().get(ResourceKey.create(Registries.BIOME, Identifier.parse("minecraft:nope"))).isPresent()); + assertFalse(context.ops().getter(Registries.DIMENSION_TYPE).orElseThrow().get(nope).isPresent()); + + Holder.Reference overworld = context.dimensionTypes().getOrThrow(BuiltinDimensionTypes.OVERWORLD); + assertSame(dimensionTypes.get(BuiltinDimensionTypes.OVERWORLD).orElseThrow(), overworld); + assertTrue(overworld.canSerializeIn(context.dimensionTypes())); + assertTrue(overworld.canSerializeIn(context.ops().getter(Registries.DIMENSION_TYPE).orElseThrow())); + + assertDoesNotThrow(dimensionTypes::freeze); + assertDoesNotThrow(noiseSettings::freeze); + assertDoesNotThrow(biomes::freeze); + assertEquals(REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).listElementIds().count(), dimensionTypes.size()); + assertSame(REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(BuiltinDimensionTypes.OVERWORLD).value(), + overworld.value()); + } + + @Test + void tagsAreCreatedOnDemand() { + VanillaContext context = VanillaContext.ofLoad(List.of(copy(Registries.DIMENSION_TYPE), copy(Registries.NOISE_SETTINGS), + copy(Registries.BIOME)), MinecraftTestSupport.loadContext(), + key -> null); + TagKey tag = TagKey.create(Registries.BIOME, Identifier.parse("terra:pack")); + assertTrue(context.ops().getter(Registries.BIOME).orElseThrow().get(tag).isPresent()); + } + + @Test + void staticTagsResolveThroughLoadContext() { + DimensionType overworld = REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(BuiltinDimensionTypes.OVERWORLD).value(); + TagKey infiniburn = BlockTags.INFINIBURN_OVERWORLD; + assertTrue(BuiltInRegistries.BLOCK.get(infiniburn).isEmpty(), "the built-in registry already has the tag"); + Registry.PendingTags pending = BuiltInRegistries.BLOCK.prepareTagReload( + new TagLoader.LoadResult<>(Registries.BLOCK, Map.of(infiniburn, List.of(Blocks.NETHERRACK.builtInRegistryHolder())))); + VanillaContext context = VanillaContext.ofLoad(List.of(copy(Registries.DIMENSION_TYPE), copy(Registries.NOISE_SETTINGS), + copy(Registries.BIOME), copy(Registries.WORLD_CLOCK), + copy(Registries.TIMELINE)), + MinecraftTestSupport.loadContext(pending), key -> null); + Map encoded = (Map) VanillaCodecs.encode(DimensionType.DIRECT_CODEC, overworld, CONTEXT.ops()); + assertEquals("#minecraft:infiniburn_overworld", encoded.get("infiniburn")); + + DimensionType parsed = assertDoesNotThrow(() -> VanillaCodecs.parse(DimensionType.DIRECT_CODEC, encoded, context.ops())); + assertEquals(infiniburn, parsed.infiniburn().unwrapKey().orElseThrow()); + } +} diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaParentReaderTest.java b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaParentReaderTest.java new file mode 100644 index 000000000..b4f8c6072 --- /dev/null +++ b/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaParentReaderTest.java @@ -0,0 +1,374 @@ +package com.dfsek.terra.mod.attribute; + +import com.mojang.serialization.Codec; +import net.minecraft.core.Holder; +import net.minecraft.core.particles.BlockParticleOption; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.attribute.EnvironmentAttribute; +import net.minecraft.world.attribute.EnvironmentAttributeMap; +import net.minecraft.world.attribute.EnvironmentAttributes; +import net.minecraft.world.entity.npc.villager.VillagerType; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeSpecialEffects; +import net.minecraft.world.level.biome.Biomes; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.BiConsumer; + +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.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeScope; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.value.Color; + +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.ATTRIBUTES; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry; +import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + + +class VanillaParentReaderTest { + private static final RegistryOps OPS = CONTEXT.ops(); + private static final DecodeContext PLAIN = HANDLE.plainContext(); + private static final PackAttributeTable TABLE = PackAttributeTable.of(registry()); + private static final VanillaAttributeMaps MAPS = new VanillaAttributeMaps(HANDLE, CONTEXT); + private static final VanillaParentReader READER = new VanillaParentReader(HANDLE, CONTEXT); + + private static final String AMBIENT_PARTICLES = "minecraft:visual/ambient_particles"; + private static final String FOG_COLOR = "minecraft:visual/fog_color"; + private static final String DEFAULT_CLOCK = "default_clock"; + + private static final BiConsumer, String> FAIL = (attribute, reason) -> fail(attribute.getRegistryKey() + ": " + reason); + + private static Biome biome(ResourceKey key) { + return REGISTRIES.lookupOrThrow(Registries.BIOME).getOrThrow(key).value(); + } + + private static DimensionType dimensionType(ResourceKey key) { + return REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(key).value(); + } + + private static List> biomes() { + return REGISTRIES.lookupOrThrow(Registries.BIOME).listElements().toList(); + } + + private static List> dimensionTypes() { + return REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).listElements().toList(); + } + + @SuppressWarnings("unchecked") + private static Map encodeMap(Codec codec, Object value) { + Object raw = VanillaCodecs.encode((Codec) codec, value, OPS); + return new LinkedHashMap<>((Map) assertInstanceOf(Map.class, raw)); + } + + private static Map climate(Biome biome) { + return encodeMap(Biome.ClimateSettings.CODEC.codec(), biome.climateSettings); + } + + private static Map effects(Biome biome) { + return encodeMap(BiomeSpecialEffects.CODEC, biome.getSpecialEffects()); + } + + private static void assertNoEntries(AttributeSlots slots, String what) { + for(Attribute attribute : ATTRIBUTES) assertNull(slots.get(attribute), what + ": " + attribute.getRegistryKey()); + } + + @Test + void everyVanillaAttributeInTable() { + Set> bound = new HashSet<>(); + for(PackAttributeTable.Bound b : TABLE.environment()) { + assertEquals(String.valueOf(BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.getKey(b.vanilla())), + b.attribute().getRegistryKey().toString()); + bound.add(b.vanilla()); + } + assertEquals(Set.copyOf(BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.stream().toList()), bound); + assertEquals(51, bound.size()); + assertEquals(51, TABLE.environment().size()); + assertEquals(List.of(), TABLE.unapplied()); + + assertEquals(4, TABLE.climate().size()); + assertEquals(5, TABLE.effects().size()); + assertEquals(15, TABLE.dimension().size()); + assertEquals(attribute("terra:biome/villager_type"), TABLE.villagerType()); + assertEquals(attribute("terra:world/sea_level"), TABLE.seaLevel()); + assertEquals(attribute("terra:world/spawn_height"), TABLE.spawnHeight()); + assertEquals(attribute("terra:world/mob_generation"), TABLE.mobGeneration()); + } + + @Test + void terraScopeMatchesVanillaPositional() { + List mismatches = new ArrayList<>(); + for(PackAttributeTable.Bound b : TABLE.environment()) { + boolean anywhere = b.attribute().scope() == AttributeScope.ANYWHERE; + if(anywhere != b.vanilla().isPositional()) { + mismatches.add(b.attribute().getRegistryKey() + ": Terra " + b.attribute().scope() + ", vanilla positional " + + b.vanilla().isPositional()); + } + } + assertEquals(List.of(), mismatches); + } + + @Test + void noRegistryMeansEmptyTable() { + PackAttributeTable table = PackAttributeTable.of(null); + assertEquals(List.of(), table.environment()); + assertEquals(List.of(), table.climate()); + assertEquals(List.of(), table.effects()); + assertEquals(List.of(), table.dimension()); + assertEquals(List.of(), table.unapplied()); + assertNull(table.villagerType()); + assertNull(table.seaLevel()); + assertNull(table.spawnHeight()); + assertNull(table.mobGeneration()); + + VanillaParentReader reader = new VanillaParentReader(HANDLE, VanillaContext.of(REGISTRIES, key -> VillagerType.DESERT)); + assertNoEntries(reader.biome(Biomes.PLAINS, biome(Biomes.PLAINS), table, FAIL), "biome"); + assertNoEntries(reader.dimension(dimensionType(BuiltinDimensionTypes.NETHER), table, FAIL), "dimension"); + assertNoEntries(reader.generation(REGISTRIES.lookupOrThrow(Registries.NOISE_SETTINGS) + .getOrThrow(NoiseGeneratorSettings.OVERWORLD).value(), table), "generation"); + assertNoEntries(AttributeSlots.EMPTY, "empty"); + } + + @Test + void addonAttributeIsUnapplied() { + Attribute custom = HANDLE.attributeBuilder(AttributeKey.parse("test:custom"), HANDLE.types().floatType(), 0f) + .build(); + PackAttributeTable table = PackAttributeTable.of(registry(custom)); + assertEquals(List.of(custom), table.unapplied()); + assertEquals(51, table.environment().size()); + assertNull(READER.biome(Biomes.PLAINS, biome(Biomes.PLAINS), TABLE, FAIL).get(custom)); + } + + @Test + void vanillaMapsRoundTrip() { + int nonEmpty = 0; + for(Holder.Reference holder : biomes()) { + if(roundTrip(holder.key().identifier().toString(), holder.value().getAttributes(), true)) nonEmpty++; + } + for(Holder.Reference holder : dimensionTypes()) { + if(roundTrip(holder.key().identifier().toString(), holder.value().attributes(), false)) nonEmpty++; + } + assertTrue(nonEmpty > 10, "few vanilla maps had entries: " + nonEmpty); + } + + private static boolean roundTrip(String name, EnvironmentAttributeMap map, boolean positional) { + AttributeEntry[] into = new AttributeEntry[HANDLE.attributeCount()]; + MAPS.toTerra(map, TABLE, into, (attribute, reason) -> fail(name + ": " + attribute.getRegistryKey() + " unreadable: " + reason)); + Map, AttributeEntry> entries = new LinkedHashMap<>(); + for(Attribute attribute : ATTRIBUTES) { + if(into[attribute.index()] != null) entries.put(attribute, into[attribute.index()]); + } + assertEquals(map.keySet().size(), entries.size(), name); + EnvironmentAttributeMap back = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, entries, positional, + (attribute, reason) -> fail(name + ": " + attribute.getRegistryKey() + + " skipped: " + reason)); + assertEquals(map.keySet(), back.keySet(), name); + assertEquals(VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, map, OPS), + VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, back, OPS), name); + return !entries.isEmpty(); + } + + @Test + void oldParticleFormIsRejected() throws DecodeException { + Attribute particles = attribute(AMBIENT_PARTICLES); + Attribute fog = attribute(FOG_COLOR); + Object oldParticle = Map.of("type", "minecraft:falling_dust", "block_state", Map.of("Name", "minecraft:sand")); + Object newParticle = VanillaCodecs.encode(ParticleTypes.CODEC, + new BlockParticleOption(ParticleTypes.FALLING_DUST, Blocks.SAND.defaultBlockState()), + OPS); + + Map, AttributeEntry> entries = new LinkedHashMap<>(); + entries.put(particles, HANDLE.decodeEntry(particles, List.of(Map.of("particle", oldParticle, "probability", 0.01)), PLAIN)); + entries.put(fog, HANDLE.decodeEntry(fog, "#123456", PLAIN)); + List skipped = new ArrayList<>(); + EnvironmentAttributeMap rejected = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, entries, true, + (attribute, reason) -> { + assertEquals(particles, attribute); + skipped.add(reason); + }); + assertEquals(1, skipped.size()); + assertFalse(skipped.getFirst().isBlank()); + assertFalse(rejected.contains(EnvironmentAttributes.AMBIENT_PARTICLES)); + assertTrue(rejected.contains(vanilla(FOG_COLOR)), "the other entry still applies"); + + AttributeEntry accepted = HANDLE.decodeEntry(particles, List.of(Map.of("particle", newParticle, "probability", 0.01)), + PLAIN); + EnvironmentAttributeMap map = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(particles, accepted), true, FAIL); + List value = map.applyModifier(EnvironmentAttributes.AMBIENT_PARTICLES, + List.of()); + assertEquals(1, value.size()); + ParticleOptions particle = value.getFirst().particle(); + BlockParticleOption block = assertInstanceOf(BlockParticleOption.class, particle); + assertEquals(Blocks.SAND.defaultBlockState(), block.getState()); + } + + @Test + void nullOverrideKeepsBase() { + Attribute fog = attribute(FOG_COLOR); + EnvironmentAttributeMap base = biome(Biomes.PLAINS).getAttributes(); + EnvironmentAttributeMap result = MAPS.toVanilla(base, Map.of(fog, AttributeEntry.override(null)), true, FAIL); + assertEquals(base, result); + } + + @Test + void readsBiomeFields() { + Attribute temperature = attribute("terra:biome/temperature"); + Attribute precipitation = attribute("terra:biome/has_precipitation"); + Attribute villager = attribute("terra:biome/villager_type"); + + AttributeSlots plains = READER.biome(Biomes.PLAINS, biome(Biomes.PLAINS), TABLE, FAIL); + assertEquals(AttributeEntry.override(0.8f), plains.get(temperature)); + assertEquals(AttributeEntry.override(true), plains.get(precipitation)); + assertNull(plains.get(villager), "the test context has no villager types"); + + AttributeSlots desert = READER.biome(Biomes.DESERT, biome(Biomes.DESERT), TABLE, FAIL); + assertEquals(AttributeEntry.override(false), desert.get(precipitation)); + + assertEquals(AttributeEntry.override(Color.rgb(0x3f76e4)), plains.get(attribute("terra:biome/water_color"))); + assertNull(plains.get(attribute("terra:biome/grass_color"))); + + VanillaParentReader withVillagers = new VanillaParentReader(HANDLE, VanillaContext.of( + REGISTRIES, key -> key == Biomes.DESERT ? VillagerType.DESERT : null)); + assertEquals(AttributeEntry.override(RegistryKey.parse("minecraft:desert")), + withVillagers.biome(Biomes.DESERT, biome(Biomes.DESERT), TABLE, FAIL).get(villager)); + assertNull(withVillagers.biome(Biomes.PLAINS, biome(Biomes.PLAINS), TABLE, FAIL).get(villager)); + } + + @Test + void readsBiomeEnvironment() { + Biome plains = biome(Biomes.PLAINS); + AttributeSlots slots = READER.biome(Biomes.PLAINS, plains, TABLE, FAIL); + int present = 0; + for(PackAttributeTable.Bound b : TABLE.environment()) { + if(plains.getAttributes().contains(b.vanilla())) { + assertNotNull(slots.get(b.attribute()), b.attribute().getRegistryKey().toString()); + present++; + } else { + assertNull(slots.get(b.attribute()), b.attribute().getRegistryKey().toString()); + } + } + assertTrue(present > 0); + } + + @Test + void everyTerraPathIsVanillaField() { + Set dimensionKeys = new HashSet<>(); + List> types = dimensionTypes(); + assertEquals(4, types.size()); + for(Holder.Reference holder : types) { + dimensionKeys.addAll(encodeMap(DimensionType.DIRECT_CODEC, holder.value()).keySet()); + } + for(PackAttributeTable.Field field : TABLE.dimension()) { + assertTrue(dimensionKeys.contains(field.name()), field.name() + " is not a dimension type field: " + dimensionKeys); + } + + Set biomeKeys = new HashSet<>(); + for(Holder.Reference holder : biomes()) { + biomeKeys.addAll(climate(holder.value()).keySet()); + biomeKeys.addAll(effects(holder.value()).keySet()); + } + for(PackAttributeTable.Field field : TABLE.climate()) { + assertTrue(biomeKeys.contains(field.name()), field.name() + " is not a biome field: " + biomeKeys); + } + for(PackAttributeTable.Field field : TABLE.effects()) { + assertTrue(biomeKeys.contains(field.name()), field.name() + " is not a biome field: " + biomeKeys); + } + } + + @Test + void absentFieldsMatchTerraDefaults() { + List mismatches = new ArrayList<>(); + for(Holder.Reference holder : dimensionTypes()) { + absentFields(holder.key().identifier().toString(), DimensionType.DIRECT_CODEC, holder.value(), TABLE.dimension(), mismatches); + } + for(ResourceKey key : List.of(Biomes.PLAINS, Biomes.SWAMP, Biomes.PALE_GARDEN)) { + Biome biome = biome(key); + absentFields(key.identifier().toString(), Biome.ClimateSettings.CODEC.codec(), biome.climateSettings, TABLE.climate(), + mismatches); + absentFields(key.identifier().toString(), BiomeSpecialEffects.CODEC, biome.getSpecialEffects(), TABLE.effects(), mismatches); + } + assertEquals(List.of(), mismatches); + } + + private static void absentFields(String name, Codec codec, V original, List fields, + List mismatches) { + Map json = encodeMap(codec, original); + for(PackAttributeTable.Field field : fields) { + if(field.name().equals(DEFAULT_CLOCK) || json.containsKey(field.name())) continue; + Map withDefault = new LinkedHashMap<>(json); + Object terraDefault = encodedDefault(field.attribute()); + if(terraDefault != null) withDefault.put(field.name(), terraDefault); + try { + Map parsed = encodeMap(codec, VanillaCodecs.parse(codec, withDefault, OPS)); + if(!json.equals(parsed)) { + mismatches.add(name + " " + field.name() + ": Terra default " + terraDefault + " reads as " + parsed.get(field.name())); + } + } catch(DecodeException e) { + mismatches.add(name + " " + field.name() + ": vanilla rejects Terra default " + terraDefault + ": " + e.getMessage()); + } + } + } + + private static Object encodedDefault(Attribute attribute) { + T value = attribute.defaultValue(); + return value == null ? null : attribute.type().encode(value); + } + + @Test + void readsDimensionFields() { + AttributeSlots overworld = READER.dimension(dimensionType(BuiltinDimensionTypes.OVERWORLD), TABLE, FAIL); + assertEquals(AttributeEntry.override(-64), overworld.get(attribute("terra:dimension/min_y"))); + assertEquals(AttributeEntry.override(384), overworld.get(attribute("terra:dimension/height"))); + assertEquals(AttributeEntry.override(true), overworld.get(attribute("terra:dimension/has_skylight"))); + assertEquals(AttributeEntry.override(RegistryKey.parse("minecraft:overworld")), + overworld.get(attribute("terra:dimension/default_clock"))); + + AttributeSlots nether = READER.dimension(dimensionType(BuiltinDimensionTypes.NETHER), TABLE, FAIL); + assertEquals(AttributeEntry.override(null), nether.get(attribute("terra:dimension/default_clock"))); + assertEquals(AttributeEntry.override(true), nether.get(attribute("terra:dimension/has_ceiling"))); + assertEquals(AttributeEntry.override(4f), nether.get(attribute("minecraft:gameplay/sky_light_level"))); + } + + @Test + void readsGeneration() { + NoiseGeneratorSettings overworld = REGISTRIES.lookupOrThrow(Registries.NOISE_SETTINGS) + .getOrThrow(NoiseGeneratorSettings.OVERWORLD).value(); + AttributeSlots slots = READER.generation(overworld, TABLE); + assertEquals(AttributeEntry.override(63), slots.get(attribute("terra:world/sea_level"))); + assertEquals(AttributeEntry.override(true), slots.get(attribute("terra:world/mob_generation"))); + assertNull(slots.get(attribute("terra:world/spawn_height"))); + + NoiseGeneratorSettings nether = REGISTRIES.lookupOrThrow(Registries.NOISE_SETTINGS) + .getOrThrow(NoiseGeneratorSettings.NETHER).value(); + assertEquals(AttributeEntry.override(32), READER.generation(nether, TABLE).get(attribute("terra:world/sea_level"))); + } +} diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/LifecyclePlatform.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/LifecyclePlatform.java index 2270c60a2..74f9eb1cf 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/LifecyclePlatform.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/LifecyclePlatform.java @@ -25,6 +25,7 @@ import java.util.stream.Stream; import com.dfsek.terra.addon.EphemeralAddon; import com.dfsek.terra.api.addon.BaseAddon; import com.dfsek.terra.lifecycle.util.LifecycleBiomeUtil; +import com.dfsek.terra.lifecycle.util.LifecycleUtil; import com.dfsek.terra.mod.CommonPlatform; import com.dfsek.terra.mod.ModPlatform; import com.dfsek.terra.mod.generation.MinecraftChunkGeneratorWrapper; @@ -82,22 +83,32 @@ public abstract class LifecyclePlatform extends ModPlatform { @Override public boolean reload() { getTerraConfig().load(this); - boolean succeed = loadConfigPacks(); + // Old packs keep their parents until the reloaded packs are prepared and in the chunk generators. + attributeParents().beginPackReload(); + boolean succeed; + try { + succeed = loadConfigPacks(); - if(server != null) { - LifecycleBiomeUtil.registerBiomes(server.registryAccess().lookupOrThrow(Registries.BIOME)); - server.reloadResources(server.getPackRepository().getSelectedIds()).exceptionally(throwable -> { - LOGGER.warn("Failed to execute reload", throwable); - return null; - }).join(); - server.getAllLevels().forEach(world -> { - if(world.getChunkSource().getGenerator() instanceof MinecraftChunkGeneratorWrapper chunkGeneratorWrapper) { - getConfigRegistry().get(chunkGeneratorWrapper.getPack().getRegistryKey()).ifPresent(pack -> { - chunkGeneratorWrapper.setPack(pack); - LOGGER.info("Replaced pack in chunk generator for world {}", world); - }); - } - }); + if(server != null) { + LifecycleBiomeUtil.registerBiomes(server.registryAccess().lookupOrThrow(Registries.BIOME), + LifecycleUtil.biomeFactory(this)); + server.reloadResources(server.getPackRepository().getSelectedIds()).exceptionally(throwable -> { + LOGGER.warn("Failed to execute reload", throwable); + return null; + }).join(); + server.getAllLevels().forEach(world -> { + if(world.getChunkSource().getGenerator() instanceof MinecraftChunkGeneratorWrapper chunkGeneratorWrapper) { + getConfigRegistry().get(chunkGeneratorWrapper.getPack().getRegistryKey()).ifPresent(pack -> { + chunkGeneratorWrapper.setPack(pack); + LOGGER.info("Replaced pack in chunk generator for world {}", world); + }); + } + }); + LOGGER.info("Packs reloaded; dimension types, generation settings, timelines and existing biomes need a restart " + + "or new world."); + } + } finally { + attributeParents().endPackReload(); } return succeed; } diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RegistryLoadTaskMixin.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RegistryLoadTaskMixin.java new file mode 100644 index 000000000..33e7041e9 --- /dev/null +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RegistryLoadTaskMixin.java @@ -0,0 +1,28 @@ +package com.dfsek.terra.lifecycle.mixin; + +import net.minecraft.core.HolderLookup; +import net.minecraft.resources.RegistryLoadTask; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; + +import java.util.List; + +import com.dfsek.terra.lifecycle.util.LoadContextHolder; + + +@Mixin(RegistryLoadTask.class) +public abstract class RegistryLoadTaskMixin implements LoadContextHolder { + @Unique + private @Nullable List> terra$contextRegistries; + + @Override + public @Nullable List> terra_contextRegistries() { + return terra$contextRegistries; + } + + @Override + public void terra_setContextRegistries(List> contextRegistries) { + this.terra$contextRegistries = contextRegistries; + } +} diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/RegistryDataLoaderMixin.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/RegistryDataLoaderMixin.java index 539040591..a366f43a0 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/RegistryDataLoaderMixin.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/RegistryDataLoaderMixin.java @@ -1,11 +1,13 @@ package com.dfsek.terra.lifecycle.mixin.lifecycle; +import net.minecraft.core.HolderLookup; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; import net.minecraft.core.WritableRegistry; import net.minecraft.core.registries.Registries; import net.minecraft.resources.RegistryDataLoader; import net.minecraft.resources.RegistryLoadTask; +import net.minecraft.resources.RegistryOps; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceManagerRegistryLoadTask; import net.minecraft.world.item.enchantment.Enchantment; @@ -14,6 +16,7 @@ import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterList; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; import net.minecraft.world.level.levelgen.presets.WorldPreset; +import net.minecraft.world.timeline.Timeline; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; @@ -22,18 +25,29 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import com.dfsek.terra.lifecycle.LifecyclePlatform; import com.dfsek.terra.lifecycle.mixin.RegistryLoadTaskAccessor; import com.dfsek.terra.lifecycle.util.LifecycleUtil; +import com.dfsek.terra.lifecycle.util.LoadContextHolder; import com.dfsek.terra.lifecycle.util.RegistryHack; import com.dfsek.terra.mod.CommonPlatform; import com.dfsek.terra.mod.ModPlatform; +import com.dfsek.terra.mod.attribute.VanillaContext; +import com.dfsek.terra.mod.mixin.access.VillagerTypeAccessor; @Mixin(RegistryDataLoader.class) public class RegistryDataLoaderMixin { + // Until the load finishes, the static registries' tags are only in these lookups. + @Inject(method = "createContext", at = @At("HEAD")) + private static void captureContext(List> contextRegistries, List> loadTasks, + CallbackInfoReturnable cir) { + for(RegistryLoadTask task : loadTasks) ((LoadContextHolder) task).terra_setContextRegistries(contextRegistries); + } + // The thenApplyAsync callback in load(LoaderFactory, List, List, Executor): every registry populated, none frozen. @Inject( method = "lambda$load$2(Ljava/util/List;Ljava/util/Map;Ljava/lang/Void;)Lnet/minecraft/core/RegistryAccess$Frozen;", @@ -54,10 +68,18 @@ public class RegistryDataLoaderMixin { WritableRegistry multiNoiseBiomeSourceParameterLists = extractRegistry(loadTasks, Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST).orElseThrow(); WritableRegistry enchantments = extractRegistry(loadTasks, Registries.ENCHANTMENT).orElseThrow(); + // Binds the datapack's timelines before the freeze, for the time-marker check. + WritableRegistry timelines = extractRegistry(loadTasks, Registries.TIMELINE).orElseThrow(); LifecyclePlatform.setRegistries(biomes, dimensionTypes, chunkGeneratorSettings, multiNoiseBiomeSourceParameterLists, enchantments); - LifecycleUtil.initialize(biomes, worldPresets); + // After extractRegistry: its terra_bind gives the parents' holders their values before the freeze. + List> loaded = loadTasks.stream().map(RegistryDataLoaderMixin::getRegistry).toList(); + List> context = Objects.requireNonNull( + ((LoadContextHolder) loadTasks.getFirst()).terra_contextRegistries(), "the load built no context"); + platform.attributeParents().beginLoad( + VanillaContext.ofLoad(loaded, context, VillagerTypeAccessor.getBiomeTypeToIdMap()::get)); + LifecycleUtil.initialize(biomes, timelines, worldPresets); } } diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleBiomeUtil.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleBiomeUtil.java index 4e795f76e..bd102d54c 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleBiomeUtil.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleBiomeUtil.java @@ -4,23 +4,25 @@ import net.minecraft.core.Registry; import net.minecraft.core.registries.Registries; import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; -import net.minecraft.world.entity.npc.villager.VillagerType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; -import java.util.Map; -import java.util.Objects; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.world.biome.Biome; import com.dfsek.terra.mod.CommonPlatform; +import com.dfsek.terra.mod.ModPlatform; +import com.dfsek.terra.mod.attribute.AttributeReport; +import com.dfsek.terra.mod.attribute.MinecraftAttributeParents; +import com.dfsek.terra.mod.attribute.MinecraftBiomeFactory; +import com.dfsek.terra.mod.attribute.PackParents; import com.dfsek.terra.mod.config.PreLoadCompatibilityOptions; import com.dfsek.terra.mod.config.ProtoPlatformBiome; -import com.dfsek.terra.mod.config.VanillaBiomeProperties; import com.dfsek.terra.mod.mixin.access.VillagerTypeAccessor; import com.dfsek.terra.mod.util.BiomeUtil; import com.dfsek.terra.mod.util.MinecraftUtil; +import com.dfsek.terra.mod.util.TagUtil; public final class LifecycleBiomeUtil { @@ -30,78 +32,63 @@ public final class LifecycleBiomeUtil { } - public static void registerBiomes(Registry biomeRegistry) { + public static void registerBiomes(Registry biomeRegistry, MinecraftBiomeFactory factory) { logger.info("Registering biomes..."); - CommonPlatform.get().getConfigRegistry().forEach(pack -> { // Register all Terra biomes. + BiomeUtil.TERRA_BIOME_MAP.clear(); + BiomeUtil.TERRA_BIOME_PLATFORM_TAGS.clear(); + ModPlatform platform = CommonPlatform.get(); + MinecraftAttributeParents parents = platform.attributeParents(); + platform.getConfigRegistry().forEach(pack -> { // Register all Terra biomes. + PackParents packParents = parents.prepare(pack, platform.getAttributeHandle().pack(pack), + AttributeReport.logging(pack)); pack.getCheckedRegistry(Biome.class) - .forEach((id, biome) -> registerBiome(biome, pack, id, biomeRegistry)); + .forEach((id, biome) -> registerBiome(biome, pack, packParents, id, biomeRegistry, parents, factory)); }); logger.info("Terra biomes registered."); } /** - * Clones a Vanilla biome and injects Terra data to create a Terra-vanilla biome delegate. + * Builds a Terra biome's vanilla biome from its vanilla parent and its attribute entries, and registers it. * * @param biome The Terra BiomeBuilder. * @param pack The ConfigPack this biome belongs to. */ - private static void registerBiome(Biome biome, ConfigPack pack, + private static void registerBiome(Biome biome, ConfigPack pack, PackParents packParents, com.dfsek.terra.api.registry.key.RegistryKey id, - Registry registry) { - ResourceKey vanilla = ((ProtoPlatformBiome) biome.getPlatformBiome()).get(registry); - - if(vanilla == null) { + Registry registry, MinecraftAttributeParents parents, + MinecraftBiomeFactory factory) { + ProtoPlatformBiome proto = (ProtoPlatformBiome) biome.getPlatformBiome(); + ResourceKey vanilla = proto.get(registry); + net.minecraft.world.level.biome.Biome vanillaBiome = vanilla == null ? null : registry.getValue(vanilla); + if(vanillaBiome == null) { logger.error(""" - Failed to get Vanilla Biome Regiestry key! + Failed to get Vanilla Biome! Terra Biome ID: {} - Vanilla Biome: {}""", biome.getID(), biome.getPlatformBiome()); + Vanilla Biome: {}""", biome.getID(), vanilla == null ? biome.getPlatformBiome() : vanilla.identifier()); + return; } + proto.setParentEntries(parents.biomeEntries(packParents, vanilla, vanillaBiome)); + if(pack.getContext().get(PreLoadCompatibilityOptions.class).useVanillaBiomes()) { - ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(registry.wrapAsHolder(registry.getValue(vanilla))); - } else { - VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class); - - - net.minecraft.world.level.biome.Biome vanilaBiome = registry.getValue(vanilla); - if(vanilaBiome == null) { - String vanillaBiomeName; - if(vanilla != null) { - vanillaBiomeName = vanilla.identifier().toString(); - } else { - vanillaBiomeName = "NULL"; - } - logger.error(""" - Failed to get Vanilla Biome! - Terra Biome ID: {} - Vanilla Biome: {}""", biome.getID(), vanillaBiomeName); - return; - } - - net.minecraft.world.level.biome.Biome minecraftBiome = BiomeUtil.createBiome(Objects.requireNonNull(vanilaBiome), - vanillaBiomeProperties); - - Identifier identifier = Identifier.fromNamespaceAndPath("terra", BiomeUtil.createBiomeID(pack, id)); - - if(registry.containsKey(identifier)) { - ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(MinecraftUtil.getEntry(registry, identifier) - .orElseThrow()); - } else { - ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(Registry.registerForHolder(registry, - MinecraftUtil.registerBiomeKey(identifier) - .identifier(), - minecraftBiome)); - } - - Map, ResourceKey> villagerMap = - VillagerTypeAccessor.getBiomeTypeToIdMap(); - - villagerMap.put(ResourceKey.create(Registries.BIOME, identifier), - Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(), - villagerMap.getOrDefault(vanilla, VillagerType.PLAINS))); - - BiomeUtil.TERRA_BIOME_MAP.computeIfAbsent(vanilla.identifier(), i -> new ArrayList<>()).add(identifier); + proto.setDelegate(registry.wrapAsHolder(vanillaBiome)); + return; } - } + Identifier identifier = Identifier.fromNamespaceAndPath("terra", BiomeUtil.createBiomeID(pack, id)); + + if(registry.containsKey(identifier)) { + // Registered by an earlier load; edits wait for the next registry load. + proto.setDelegate(MinecraftUtil.getEntry(registry, identifier).orElseThrow()); + } else { + MinecraftBiomeFactory.Built built = factory.create(vanilla, vanillaBiome, biome, packParents, packParents.report()); + proto.setDelegate(Registry.registerForHolder(registry, MinecraftUtil.registerBiomeKey(identifier).identifier(), + built.biome())); + VillagerTypeAccessor.getBiomeTypeToIdMap().put(ResourceKey.create(Registries.BIOME, identifier), built.villagerType()); + } + + BiomeUtil.TERRA_BIOME_PLATFORM_TAGS.put(identifier, + new TagUtil.PlatformTagSource(packParents.report(), biome.getID(), biome.getPlatformTags())); + BiomeUtil.TERRA_BIOME_MAP.computeIfAbsent(vanilla.identifier(), i -> new ArrayList<>()).add(identifier); + } } diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleUtil.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleUtil.java index 86fda0d3a..ded62698d 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleUtil.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleUtil.java @@ -6,16 +6,52 @@ import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.levelgen.presets.WorldPreset; +import net.minecraft.world.timeline.Timeline; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent; import com.dfsek.terra.mod.CommonPlatform; +import com.dfsek.terra.mod.ModPlatform; +import com.dfsek.terra.mod.attribute.AttributeReport; +import com.dfsek.terra.mod.attribute.MinecraftAttributeParents; +import com.dfsek.terra.mod.attribute.MinecraftBiomeFactory; +import com.dfsek.terra.mod.attribute.MinecraftTimelines; +import com.dfsek.terra.mod.attribute.PackParents; +import com.dfsek.terra.mod.attribute.VanillaContext; public final class LifecycleUtil { - public static void initialize(WritableRegistry biomeMutableRegistry, WritableRegistry worldPresetMutableRegistry) { - CommonPlatform.get().getEventManager().callEvent(new PlatformInitializationEvent()); - LifecycleBiomeUtil.registerBiomes(biomeMutableRegistry); - CommonPlatform.get().registerWorldTypes( + private static final Logger LOGGER = LoggerFactory.getLogger(LifecycleUtil.class); + + /** + * Timelines go before world types: the dimension types name the packs' timeline tags. + */ + public static void initialize(WritableRegistry biomeMutableRegistry, WritableRegistry timelineMutableRegistry, + WritableRegistry worldPresetMutableRegistry) { + ModPlatform platform = CommonPlatform.get(); + platform.getEventManager().callEvent(new PlatformInitializationEvent()); + LifecycleBiomeUtil.registerBiomes(biomeMutableRegistry, biomeFactory(platform)); + registerTimelines(platform, timelineMutableRegistry); + platform.registerWorldTypes( (id, preset) -> Registry.register(worldPresetMutableRegistry, ResourceKey.create(Registries.WORLD_PRESET, id), preset)); + MinecraftTimelines.bindPendingTags(timelineMutableRegistry); + } + + private static void registerTimelines(ModPlatform platform, WritableRegistry timelines) { + MinecraftAttributeParents parents = platform.attributeParents(); + VanillaContext context = parents.context(); + if(context == null) throw new IllegalStateException("no registry load has begun"); + platform.getConfigRegistry().forEach(pack -> { + PackParents packParents = parents.prepare(pack, platform.getAttributeHandle().pack(pack), + AttributeReport.logging(pack)); + MinecraftTimelines.register(pack, packParents, timelines, platform.getAttributeHandle(), context); + }); + } + + public static MinecraftBiomeFactory biomeFactory(ModPlatform platform) { + VanillaContext context = platform.attributeParents().context(); + if(context == null) throw new IllegalStateException("no registry load has begun"); + return new MinecraftBiomeFactory(platform.getAttributeHandle(), context); } } diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LoadContextHolder.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LoadContextHolder.java new file mode 100644 index 000000000..f2233bba7 --- /dev/null +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LoadContextHolder.java @@ -0,0 +1,13 @@ +package com.dfsek.terra.lifecycle.util; + +import net.minecraft.core.HolderLookup; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + + +public interface LoadContextHolder { + @Nullable List> terra_contextRegistries(); + + void terra_setContextRegistries(List> contextRegistries); +} diff --git a/platforms/mixin-lifecycle/src/main/resources/terra.lifecycle.mixins.json b/platforms/mixin-lifecycle/src/main/resources/terra.lifecycle.mixins.json index 6350190b1..dc9ef9684 100644 --- a/platforms/mixin-lifecycle/src/main/resources/terra.lifecycle.mixins.json +++ b/platforms/mixin-lifecycle/src/main/resources/terra.lifecycle.mixins.json @@ -7,6 +7,7 @@ "RandomStateMixin", "HolderReferenceInvoker", "RegistryLoadTaskAccessor", + "RegistryLoadTaskMixin", "BuiltInRegistriesMixin", "MappedRegistryMixin", "lifecycle.MinecraftServerMixin",