From b04156bb45640c9c51bd758cf6e3b5679b224510 Mon Sep 17 00:00:00 2001 From: OakLoaf Date: Tue, 9 Dec 2025 21:32:28 +0000 Subject: [PATCH 01/44] Started migration to 1.21.11 --- buildSrc/src/main/kotlin/Versions.kt | 12 +-- .../terra/bukkit/nms/AwfulBukkitHacks.java | 16 ++-- .../terra/bukkit/nms/NMSBiomeInjector.java | 79 ++++++++++--------- .../dfsek/terra/bukkit/nms/NMSPlatform.java | 16 ++-- .../dfsek/terra/bukkit/nms/Reflection.java | 2 +- .../config/BiomeAdditionsSoundTemplate.java | 2 +- .../nms/config/BiomeMoodSoundTemplate.java | 2 +- .../config/BiomeParticleConfigTemplate.java | 8 +- .../bukkit/nms/config/EntityTypeTemplate.java | 4 +- .../bukkit/nms/config/SoundEventTemplate.java | 4 +- .../nms/config/VanillaBiomeProperties.java | 12 +-- .../nms/config/VillagerTypeTemplate.java | 6 +- platforms/fabric/build.gradle.kts | 2 +- platforms/mixin-common/build.gradle.kts | 4 +- platforms/mixin-lifecycle/build.gradle.kts | 4 +- 15 files changed, 89 insertions(+), 84 deletions(-) diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index 24a40a01a..22aeabb02 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -32,7 +32,7 @@ object Versions { } object Fabric { - const val fabricAPI = "0.134.1+${Mod.minecraft}" + const val fabricAPI = "0.139.4+${Mod.minecraft}" const val cloud = "2.0.0-beta.13" } // @@ -45,11 +45,11 @@ object Versions { const val mixin = "0.16.4+mixin.0.8.7" const val mixinExtras = "0.5.0" - const val minecraft = "1.21.10" + const val minecraft = "1.21.11" const val yarn = "$minecraft+build.1" - const val fabricLoader = "0.17.2" + const val fabricLoader = "0.18.2" - const val architecuryLoom = "1.11.451" + const val architecturyLoom = "1.13.467" const val architecturyPlugin = "3.4.162" } @@ -60,9 +60,9 @@ object Versions { // } object Bukkit { - const val minecraft = "1.21.10" + const val minecraft = "1.21.11-rc3" const val nms = "$minecraft-R0.1" - const val paperBuild = "$nms-20251012.013929-7" + const val paperBuild = "$nms-20251208.200020-2" const val paper = paperBuild const val paperLib = "1.0.8" const val reflectionRemapper = "0.1.3" diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java index beea1c536..310e4190f 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java @@ -7,10 +7,10 @@ import net.minecraft.core.HolderSet.Named; 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.ResourceKey; -import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; -import net.minecraft.world.entity.npc.VillagerType; +import net.minecraft.world.entity.npc.villager.VillagerType; import net.minecraft.world.level.biome.Biome; import org.bukkit.NamespacedKey; import org.slf4j.Logger; @@ -34,7 +34,7 @@ import com.dfsek.terra.registry.master.ConfigRegistry; public class AwfulBukkitHacks { private static final Logger LOGGER = LoggerFactory.getLogger(AwfulBukkitHacks.class); - private static final Map> terraBiomeMap = new HashMap<>(); + private static final Map> terraBiomeMap = new HashMap<>(); public static void registerBiomes(ConfigRegistry configRegistry) { try { @@ -50,7 +50,7 @@ public class AwfulBukkitHacks { BukkitPlatformBiome platformBiome = (BukkitPlatformBiome) biome.getPlatformBiome(); NamespacedKey vanillaBukkitKey = platformBiome.getHandle().getKey(); - ResourceLocation vanillaMinecraftKey = ResourceLocation.fromNamespaceAndPath(vanillaBukkitKey.getNamespace(), + Identifier vanillaMinecraftKey = Identifier.fromNamespaceAndPath(vanillaBukkitKey.getNamespace(), vanillaBukkitKey.getKey()); VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class); @@ -58,7 +58,7 @@ public class AwfulBukkitHacks { Biome platform = NMSBiomeInjector.createBiome(biomeRegistry.get(vanillaMinecraftKey).orElseThrow().value(), vanillaBiomeProperties); - ResourceLocation delegateMinecraftKey = ResourceLocation.fromNamespaceAndPath("terra", + Identifier delegateMinecraftKey = Identifier.fromNamespaceAndPath("terra", NMSBiomeInjector.createBiomeID(pack, key)); NamespacedKey delegateBukkitKey = NamespacedKey.fromString(delegateMinecraftKey.toString()); ResourceKey delegateKey = ResourceKey.create(Registries.BIOME, delegateMinecraftKey); @@ -75,7 +75,7 @@ public class AwfulBukkitHacks { Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(), villagerMap.getOrDefault(delegateKey, VillagerType.PLAINS))); - terraBiomeMap.computeIfAbsent(vanillaMinecraftKey, i -> new ArrayList<>()).add(delegateKey.location()); + terraBiomeMap.computeIfAbsent(vanillaMinecraftKey, i -> new ArrayList<>()).add(delegateKey.identifier()); LOGGER.debug("Registered biome: " + delegateKey); } catch(NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { @@ -100,8 +100,8 @@ public class AwfulBukkitHacks { tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb).ifPresentOrElse( terra -> { LOGGER.debug("{} (vanilla for {}): {}", - vanilla.unwrapKey().orElseThrow().location(), - terra.unwrapKey().orElseThrow().location(), + vanilla.unwrapKey().orElseThrow().identifier(), + terra.unwrapKey().orElseThrow().identifier(), vanilla.tags().toList()); vanilla.tags() .forEach(tag -> collect diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java index fea134c9e..5c3de7431 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java @@ -2,7 +2,8 @@ package com.dfsek.terra.bukkit.nms; import net.minecraft.core.Holder; import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; +import net.minecraft.world.attribute.EnvironmentAttributes; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.BiomeGenerationSettings; import net.minecraft.world.level.biome.BiomeSpecialEffects; @@ -17,7 +18,7 @@ import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties; public class NMSBiomeInjector { - public static Optional> getEntry(Registry registry, ResourceLocation identifier) { + public static Optional> getEntry(Registry registry, Identifier identifier) { return registry.getOptional(identifier) .flatMap(registry::getResourceKey) .flatMap(registry::get); @@ -29,55 +30,59 @@ public class NMSBiomeInjector { BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder(); - effects.fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor())) - .waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor())) - .waterFogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanilla.getWaterFogColor())) - .skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor())) + // TODO: Migrate to EnvironmentAttributes +// builder.setAttribute(EnvironmentAttributes.FOG_COLOR, Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getAttributes().get(EnvironmentAttributes.FOG_COLOR))) + +// effects.fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor())); + effects.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor())) +// .waterFogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanilla.getWaterFogColor())) +// .skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor())) .grassColorModifier(Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(), - vanilla.getSpecialEffects().getGrassColorModifier())) - .backgroundMusicVolume(Objects.requireNonNullElse(vanillaBiomeProperties.getMusicVolume(), vanilla.getBackgroundMusicVolume())); + vanilla.getSpecialEffects().grassColorModifier())); +// .backgroundMusicVolume(Objects.requireNonNullElse(vanillaBiomeProperties.getMusicVolume(), vanilla.getBackgroundMusicVolume())); if(vanillaBiomeProperties.getGrassColor() == null) { - vanilla.getSpecialEffects().getGrassColorOverride().ifPresent(effects::grassColorOverride); + vanilla.getSpecialEffects().grassColorOverride().ifPresent(effects::grassColorOverride); } else { effects.grassColorOverride(vanillaBiomeProperties.getGrassColor()); } if(vanillaBiomeProperties.getFoliageColor() == null) { - vanilla.getSpecialEffects().getFoliageColorOverride().ifPresent(effects::foliageColorOverride); + vanilla.getSpecialEffects().foliageColorOverride().ifPresent(effects::foliageColorOverride); } else { effects.foliageColorOverride(vanillaBiomeProperties.getFoliageColor()); } - if(vanillaBiomeProperties.getParticleConfig() == null) { - vanilla.getSpecialEffects().getAmbientParticleSettings().ifPresent(effects::ambientParticle); - } else { - effects.ambientParticle(vanillaBiomeProperties.getParticleConfig()); - } + // TODO +// if(vanillaBiomeProperties.getParticleConfig() == null) { +// vanilla.getSpecialEffects().getAmbientParticleSettings().ifPresent(effects::ambientParticle); +// } else { +// effects.ambientParticle(vanillaBiomeProperties.getParticleConfig()); +// } - if(vanillaBiomeProperties.getLoopSound() == null) { - vanilla.getSpecialEffects().getAmbientLoopSoundEvent().ifPresent(effects::ambientLoopSound); - } else { - RegistryFetcher.soundEventRegistry().get(vanillaBiomeProperties.getLoopSound().location()).ifPresent(effects::ambientLoopSound); - } +// if(vanillaBiomeProperties.getLoopSound() == null) { +// vanilla.getSpecialEffects().getAmbientLoopSoundEvent().ifPresent(effects::ambientLoopSound); +// } else { +// RegistryFetcher.soundEventRegistry().get(vanillaBiomeProperties.getLoopSound().location()).ifPresent(effects::ambientLoopSound); +// } - if(vanillaBiomeProperties.getMoodSound() == null) { - vanilla.getSpecialEffects().getAmbientMoodSettings().ifPresent(effects::ambientMoodSound); - } else { - effects.ambientMoodSound(vanillaBiomeProperties.getMoodSound()); - } - - if(vanillaBiomeProperties.getAdditionsSound() == null) { - vanilla.getSpecialEffects().getAmbientAdditionsSettings().ifPresent(effects::ambientAdditionsSound); - } else { - effects.ambientAdditionsSound(vanillaBiomeProperties.getAdditionsSound()); - } - - if(vanillaBiomeProperties.getMusic() == null) { - vanilla.getSpecialEffects().getBackgroundMusic().ifPresent(effects::backgroundMusic); - } else { - effects.backgroundMusic(vanillaBiomeProperties.getMusic()); - } +// if(vanillaBiomeProperties.getMoodSound() == null) { +// vanilla.getSpecialEffects().getAmbientMoodSettings().ifPresent(effects::ambientMoodSound); +// } else { +// effects.ambientMoodSound(vanillaBiomeProperties.getMoodSound()); +// } +// +// if(vanillaBiomeProperties.getAdditionsSound() == null) { +// vanilla.getSpecialEffects().getAmbientAdditionsSettings().ifPresent(effects::ambientAdditionsSound); +// } else { +// effects.ambientAdditionsSound(vanillaBiomeProperties.getAdditionsSound()); +// } +// +// if(vanillaBiomeProperties.getMusic() == null) { +// vanilla.getSpecialEffects().getBackgroundMusic().ifPresent(effects::backgroundMusic); +// } else { +// effects.backgroundMusic(vanillaBiomeProperties.getMusic()); +// } builder.hasPrecipitation(Objects.requireNonNullElse(vanillaBiomeProperties.getPrecipitation(), vanilla.hasPrecipitation())); diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java index efbdde212..c8b0c7036 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java @@ -2,15 +2,15 @@ package com.dfsek.terra.bukkit.nms; import com.dfsek.tectonic.api.TypeRegistry; import com.dfsek.tectonic.api.exception.LoadException; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.sounds.Music; import net.minecraft.sounds.SoundEvent; +import net.minecraft.world.attribute.AmbientParticle; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobCategory; -import net.minecraft.world.entity.npc.VillagerType; -import net.minecraft.world.level.biome.AmbientAdditionsSettings; -import net.minecraft.world.level.biome.AmbientMoodSettings; -import net.minecraft.world.level.biome.AmbientParticleSettings; +import net.minecraft.world.attribute.AmbientAdditionsSettings; +import net.minecraft.world.attribute.AmbientMoodSettings; +import net.minecraft.world.entity.npc.villager.VillagerType; import net.minecraft.world.level.biome.Biome.Precipitation; import net.minecraft.world.level.biome.Biome.TemperatureModifier; import net.minecraft.world.level.biome.BiomeSpecialEffects.GrassColorModifier; @@ -52,8 +52,8 @@ public class NMSPlatform extends PlatformImpl { public void register(TypeRegistry registry) { super.register(registry); registry.registerLoader(PlatformBiome.class, (type, o, loader, depthTracker) -> parseBiome((String) o, depthTracker)) - .registerLoader(ResourceLocation.class, (type, o, loader, depthTracker) -> { - ResourceLocation identifier = ResourceLocation.tryParse((String) o); + .registerLoader(Identifier.class, (type, o, loader, depthTracker) -> { + Identifier identifier = Identifier.tryParse((String) o); if(identifier == null) throw new LoadException("Invalid identifier: " + o, depthTracker); return identifier; @@ -67,7 +67,7 @@ public class NMSPlatform extends PlatformImpl { (type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase( Locale.ROOT))) .registerLoader(MobCategory.class, (type, o, loader, depthTracker) -> MobCategory.valueOf((String) o)) - .registerLoader(AmbientParticleSettings.class, BiomeParticleConfigTemplate::new) + .registerLoader(AmbientParticle.class, BiomeParticleConfigTemplate::new) .registerLoader(SoundEvent.class, SoundEventTemplate::new) .registerLoader(AmbientMoodSettings.class, BiomeMoodSoundTemplate::new) .registerLoader(AmbientAdditionsSettings.class, BiomeAdditionsSoundTemplate::new) diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java index 3c0e93e67..316c9ab8b 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java @@ -7,7 +7,7 @@ import net.minecraft.core.MappedRegistry; import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ChunkMap; import net.minecraft.tags.TagKey; -import net.minecraft.world.entity.npc.VillagerType; +import net.minecraft.world.entity.npc.villager.VillagerType; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.StructureManager; import net.minecraft.world.level.biome.Biome; diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java index 83ac758b2..3e3286098 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java @@ -5,7 +5,7 @@ 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.level.biome.AmbientAdditionsSettings; +import net.minecraft.world.attribute.AmbientAdditionsSettings; public class BiomeAdditionsSoundTemplate implements ObjectTemplate { diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeMoodSoundTemplate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeMoodSoundTemplate.java index 20f982920..b7b774ae3 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeMoodSoundTemplate.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeMoodSoundTemplate.java @@ -5,7 +5,7 @@ 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.level.biome.AmbientMoodSettings; +import net.minecraft.world.attribute.AmbientMoodSettings; public class BiomeMoodSoundTemplate implements ObjectTemplate { diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java index 99fe0cda3..7c31521f2 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java @@ -8,12 +8,12 @@ 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.level.biome.AmbientParticleSettings; +import net.minecraft.world.attribute.AmbientParticle; import java.util.stream.Stream; -public class BiomeParticleConfigTemplate implements ObjectTemplate { +public class BiomeParticleConfigTemplate implements ObjectTemplate { @Value("particle") @Default private String particle = null; @@ -23,13 +23,13 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate> { @Value("id") @Default - private ResourceLocation id = null; + private Identifier id = null; @Override public EntityType get() { diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java index 253582361..4d7b7bddd 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java @@ -3,14 +3,14 @@ package com.dfsek.terra.bukkit.nms.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.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.sounds.SoundEvent; public class SoundEventTemplate implements ObjectTemplate { @Value("id") @Default - private ResourceLocation id = null; + private Identifier id = null; @Value("distance-to-travel") @Default diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java index 3cd1e992b..c5637007d 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java @@ -6,10 +6,10 @@ 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.entity.npc.VillagerType; -import net.minecraft.world.level.biome.AmbientAdditionsSettings; -import net.minecraft.world.level.biome.AmbientMoodSettings; -import net.minecraft.world.level.biome.AmbientParticleSettings; +import net.minecraft.world.entity.npc.villager.VillagerType; +import net.minecraft.world.attribute.AmbientAdditionsSettings; +import net.minecraft.world.attribute.AmbientMoodSettings; +import net.minecraft.world.attribute.AmbientParticle; import net.minecraft.world.level.biome.Biome.TemperatureModifier; import net.minecraft.world.level.biome.BiomeSpecialEffects.GrassColorModifier; import net.minecraft.world.level.biome.MobSpawnSettings; @@ -52,7 +52,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties { @Value("particles") @Default - private AmbientParticleSettings particleConfig = null; + private AmbientParticle particleConfig = null; @Value("climate.precipitation") @Default @@ -130,7 +130,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties { return grassColorModifier; } - public AmbientParticleSettings getParticleConfig() { + public AmbientParticle getParticleConfig() { return particleConfig; } diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java index c254628b8..ab25b5011 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java @@ -5,14 +5,14 @@ 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.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.npc.VillagerType; +import net.minecraft.resources.Identifier; +import net.minecraft.world.entity.npc.villager.VillagerType; public class VillagerTypeTemplate implements ObjectTemplate> { @Value("id") @Default - private ResourceLocation id = null; + private Identifier id = null; @Override public ResourceKey get() { diff --git a/platforms/fabric/build.gradle.kts b/platforms/fabric/build.gradle.kts index 7e301083a..c1a427cb3 100644 --- a/platforms/fabric/build.gradle.kts +++ b/platforms/fabric/build.gradle.kts @@ -1,7 +1,7 @@ import java.util.* plugins { - id("dev.architectury.loom") version Versions.Mod.architecuryLoom + id("dev.architectury.loom") version Versions.Mod.architecturyLoom id("architectury-plugin") version Versions.Mod.architecturyPlugin } diff --git a/platforms/mixin-common/build.gradle.kts b/platforms/mixin-common/build.gradle.kts index 2fb92233c..97ed1768e 100644 --- a/platforms/mixin-common/build.gradle.kts +++ b/platforms/mixin-common/build.gradle.kts @@ -1,5 +1,5 @@ plugins { - id("dev.architectury.loom") version Versions.Mod.architecuryLoom + id("dev.architectury.loom") version Versions.Mod.architecturyLoom id("architectury-plugin") version Versions.Mod.architecturyPlugin } @@ -16,7 +16,7 @@ dependencies { compileOnly("net.fabricmc:sponge-mixin:${Versions.Mod.mixin}") annotationProcessor("net.fabricmc:sponge-mixin:${Versions.Mod.mixin}") - annotationProcessor("dev.architectury:architectury-loom:${Versions.Mod.architecuryLoom}") + annotationProcessor("dev.architectury:architectury-loom:${Versions.Mod.architecturyLoom}") minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") mappings("net.fabricmc:yarn:${Versions.Mod.yarn}:v2") diff --git a/platforms/mixin-lifecycle/build.gradle.kts b/platforms/mixin-lifecycle/build.gradle.kts index f93b86cbe..2663caf2f 100644 --- a/platforms/mixin-lifecycle/build.gradle.kts +++ b/platforms/mixin-lifecycle/build.gradle.kts @@ -1,5 +1,5 @@ plugins { - id("dev.architectury.loom") version Versions.Mod.architecuryLoom + id("dev.architectury.loom") version Versions.Mod.architecturyLoom id("architectury-plugin") version Versions.Mod.architecturyPlugin } @@ -9,7 +9,7 @@ dependencies { compileOnly("net.fabricmc:sponge-mixin:${Versions.Mod.mixin}") compileOnly("io.github.llamalad7:mixinextras-common:${Versions.Mod.mixinExtras}") annotationProcessor("net.fabricmc:sponge-mixin:${Versions.Mod.mixin}") - annotationProcessor("dev.architectury:architectury-loom:${Versions.Mod.architecuryLoom}") + annotationProcessor("dev.architectury:architectury-loom:${Versions.Mod.architecturyLoom}") implementation(project(path = ":platforms:mixin-common", configuration = "namedElements")) { isTransitive = false } From 349ce6654c9f32e686b987b924a908fddffbb3a0 Mon Sep 17 00:00:00 2001 From: OakLoaf Date: Tue, 9 Dec 2025 21:35:09 +0000 Subject: [PATCH 02/44] Adjusted list of supported versions --- .../src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java index 700bea610..019c79096 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java @@ -9,7 +9,7 @@ import java.util.List; public interface NMSInitializer { - List SUPPORTED_VERSIONS = List.of("v1.21.9", "v1.21.10"); + List SUPPORTED_VERSIONS = List.of("v1.21.11"); String MINECRAFT_VERSION = VersionUtil.getMinecraftVersionInfo().toString(); String TERRA_PACKAGE = NMSInitializer.class.getPackageName(); From d3429626b5361401414843c7c056e5c658115e03 Mon Sep 17 00:00:00 2001 From: Christian Bergschneider Date: Thu, 11 Dec 2025 02:59:19 +0100 Subject: [PATCH 03/44] chore: update gradle to version 9.2.1 to allow jvm25 --- buildSrc/src/main/kotlin/Utils.kt | 6 ++++-- gradle/wrapper/gradle-wrapper.jar | Bin 43764 -> 45633 bytes gradle/wrapper/gradle-wrapper.properties | 4 ++-- gradlew | 5 +---- gradlew.bat | 3 +-- 5 files changed, 8 insertions(+), 10 deletions(-) diff --git a/buildSrc/src/main/kotlin/Utils.kt b/buildSrc/src/main/kotlin/Utils.kt index 679786788..83606e51d 100644 --- a/buildSrc/src/main/kotlin/Utils.kt +++ b/buildSrc/src/main/kotlin/Utils.kt @@ -1,6 +1,8 @@ import java.io.ByteArrayOutputStream import org.gradle.api.Action import org.gradle.api.Project +import org.gradle.kotlin.dsl.support.serviceOf +import org.gradle.process.ExecOperations var isPrerelease = false @@ -8,7 +10,7 @@ var isPrerelease = false fun Project.getGitHash(): String { val stdout = ByteArrayOutputStream() - exec { + serviceOf().exec { commandLine = mutableListOf("git", "rev-parse", "--short", "HEAD") standardOutput = stdout } @@ -17,7 +19,7 @@ fun Project.getGitHash(): String { fun Project.gitClone(name: String) { val stdout = ByteArrayOutputStream() - exec { + serviceOf().exec { commandLine = mutableListOf("git", "clone", name) standardOutput = stdout } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 1b33c55baabb587c669f562ae36f953de2481846..f8e1ee3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VPcT7^u*RFe(sG| zX})O+)VX0_=JkbG7f(!~p>%RU2|@JqbZxU!it-DjCW)+#}uPX zt+{|G%#}Ammq##B+=!beac{@3ZV`)35?5;?AMRsusdrgd_#w{H-f8sRI^tV3K6o)L)dSNXaULi9-sPLXlUf>R zbiKP!{c{Q4=S}@LJnjwMI=JF8~SY2FRRY`wJD~5`(uy(r>q&9&K)4Y$gwzCJ{}tiq1oT~{Js4dpb|w%m zZ-Q_7Oi|@-GKkO#ycpCiqX>&_RTM^?1Hf(+D~(@e^;Rkc*XO|6pg@kiP_*>QPEZ*3 z3D=HR6j2d^%Bt#!>RL`B0H9Sn)r9cxaPB(13D}irKB&D4kCD<^S0)NASLuSnAU3#9 z&}~-ILBY1Va!Acc=oh?>V*u_b6I6Rxdcr^4(pOl4HzJ8mkVv&0rq%!{95ggURMuin zzTOoq<5d+=IL%2JTnjDu8Z6%lO;y`%M7;K)|J2A~Y^>lPRH1`48lcc#{9k)=-WsZ@ z@l+I=Tf@&GQH|JZ3zsWG#ZI%-NcA%6bl3@UZ?AXenaPkW7I%O2(pMz|dY2laS5}C1qkIRGb z7kzS1F%j@3TOa%~rdt`(0e~S&EhZm<95`m+>P;?ukNb6>aUlfyG78iO*I$;jQECdO ORzXA2f%7X@nSTIfr%7r6 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 9128c7d42..8a848873f 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,7 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionSha256Sum=845952a9d6afa783db70bb3b0effaae45ae5542ca2bb7929619e8af49cb634cf -distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.1-bin.zip +distributionSha256Sum=72f44c9f8ebcb1af43838f45ee5c4aa9c5444898b3468ab3f4af7b6076c5bc3f +distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew index 23d15a936..adff685a0 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright © 2015-2021 the original authors. +# Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -114,7 +114,6 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH="\\\"\\\"" # Determine the Java command to use to start the JVM. @@ -172,7 +171,6 @@ fi # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) @@ -212,7 +210,6 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" diff --git a/gradlew.bat b/gradlew.bat index db3a6ac20..c4bdd3ab8 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -70,11 +70,10 @@ goto fail :execute @rem Setup the command line -set CLASSPATH= @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell From 04554b886ade5827e599cd040f8d3665cb0cdbe2 Mon Sep 17 00:00:00 2001 From: Christian Bergschneider Date: Thu, 11 Dec 2025 03:01:29 +0100 Subject: [PATCH 04/44] chore: bump minestom to 1.21.10 --- buildSrc/src/main/kotlin/Versions.kt | 2 +- platforms/minestom/build.gradle.kts | 4 ++++ platforms/minestom/example/build.gradle.kts | 4 ++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index 9023eb5dc..5fed134c8 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -96,6 +96,6 @@ object Versions { } object Minestom { - const val minestom = "2025.10.04-1.21.8" + const val minestom = "2025.10.31-1.21.10" } } diff --git a/platforms/minestom/build.gradle.kts b/platforms/minestom/build.gradle.kts index 694cedbd5..c34763a7a 100644 --- a/platforms/minestom/build.gradle.kts +++ b/platforms/minestom/build.gradle.kts @@ -9,3 +9,7 @@ dependencies { tasks.named("jar") { finalizedBy("installAddonsIntoDefaultJar") } + +tasks.withType().configureEach { + options.release.set(25) +} \ No newline at end of file diff --git a/platforms/minestom/example/build.gradle.kts b/platforms/minestom/example/build.gradle.kts index 1cec6c60d..82fc81b00 100644 --- a/platforms/minestom/example/build.gradle.kts +++ b/platforms/minestom/example/build.gradle.kts @@ -20,6 +20,10 @@ tasks.withType { } } +tasks.withType().configureEach { + options.release.set(25) +} + application { mainClass.set(javaMainClass) } From 2e2b315ab7491ceba7ead9c6be2bdcb68fd3196d Mon Sep 17 00:00:00 2001 From: Christian Bergschneider Date: Thu, 11 Dec 2025 03:40:32 +0100 Subject: [PATCH 05/44] ci: bump java version to 25-tem --- .github/workflows/gradle-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/gradle-build.yml b/.github/workflows/gradle-build.yml index b289ca1aa..f4b8d9dff 100644 --- a/.github/workflows/gradle-build.yml +++ b/.github/workflows/gradle-build.yml @@ -21,7 +21,7 @@ jobs: - name: Set up JDK 21 uses: actions/setup-java@v4.7.1 with: - java-version: '21' + java-version: '25' distribution: 'temurin' server-id: github # Value of the distributionManagement/repository/id field of the pom.xml settings-path: ${{ github.workspace }} # location for the settings.xml file From e99ae48f1a60a5b18033b4cb898474a6d72d64b2 Mon Sep 17 00:00:00 2001 From: Christian Bergschneider Date: Thu, 11 Dec 2025 08:55:49 +0000 Subject: [PATCH 06/44] build: address review comments --- buildSrc/src/main/kotlin/Utils.kt | 12 +++--------- platforms/minestom/build.gradle.kts | 2 +- platforms/minestom/example/build.gradle.kts | 2 +- 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/buildSrc/src/main/kotlin/Utils.kt b/buildSrc/src/main/kotlin/Utils.kt index 83606e51d..4b761e1e2 100644 --- a/buildSrc/src/main/kotlin/Utils.kt +++ b/buildSrc/src/main/kotlin/Utils.kt @@ -2,26 +2,20 @@ import java.io.ByteArrayOutputStream import org.gradle.api.Action import org.gradle.api.Project import org.gradle.kotlin.dsl.support.serviceOf -import org.gradle.process.ExecOperations var isPrerelease = false fun Project.getGitHash(): String { - val stdout = ByteArrayOutputStream() - serviceOf().exec { + return providers.exec { commandLine = mutableListOf("git", "rev-parse", "--short", "HEAD") - standardOutput = stdout - } - return stdout.toString().trim() + }.standardOutput.asText.get().trim() } fun Project.gitClone(name: String) { - val stdout = ByteArrayOutputStream() - serviceOf().exec { + providers.exec { commandLine = mutableListOf("git", "clone", name) - standardOutput = stdout } } diff --git a/platforms/minestom/build.gradle.kts b/platforms/minestom/build.gradle.kts index c34763a7a..d3924c991 100644 --- a/platforms/minestom/build.gradle.kts +++ b/platforms/minestom/build.gradle.kts @@ -11,5 +11,5 @@ tasks.named("jar") { } tasks.withType().configureEach { - options.release.set(25) + options.release = 25 } \ No newline at end of file diff --git a/platforms/minestom/example/build.gradle.kts b/platforms/minestom/example/build.gradle.kts index 82fc81b00..8c465b7c9 100644 --- a/platforms/minestom/example/build.gradle.kts +++ b/platforms/minestom/example/build.gradle.kts @@ -21,7 +21,7 @@ tasks.withType { } tasks.withType().configureEach { - options.release.set(25) + options.release = 25 } application { From 2120dde0dbec15b9bf41fd63c51142c551357aea Mon Sep 17 00:00:00 2001 From: Zoe Gidiere Date: Fri, 19 Dec 2025 06:13:44 -0700 Subject: [PATCH 07/44] WIP on master --- buildSrc/src/main/kotlin/Versions.kt | 10 +++++----- .../src/main/java/com/dfsek/terra/mod/ModPlatform.java | 4 ++-- .../terra/mod/config/BiomeParticleConfigTemplate.java | 9 ++++----- .../dfsek/terra/mod/config/VanillaBiomeProperties.java | 6 +++--- .../compat/GenerationSettingsFloraFeaturesMixin.java | 4 +++- 5 files changed, 17 insertions(+), 16 deletions(-) diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index 962f32955..2f8a20b54 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -32,7 +32,7 @@ object Versions { } object Fabric { - const val fabricAPI = "0.139.4+${Mod.minecraft}" + const val fabricAPI = "0.140.0+${Mod.minecraft}" const val cloud = "2.0.0-beta.13" } // @@ -42,14 +42,14 @@ object Versions { // } object Mod { - const val mixin = "0.16.4+mixin.0.8.7" + const val mixin = "0.16.5+mixin.0.8.7" const val mixinExtras = "0.5.0" const val minecraft = "1.21.11" - const val yarn = "$minecraft+build.1" - const val fabricLoader = "0.18.2" + const val yarn = "$minecraft+build.3" + const val fabricLoader = "0.18.3" - const val architecturyLoom = "1.13.467" + const val architecturyLoom = "1.13.463" const val architecturyPlugin = "3.4.162" } 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 262fbf8fe..7dbc696b5 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 @@ -14,11 +14,11 @@ import net.minecraft.sound.MusicSound; import net.minecraft.sound.SoundEvent; import net.minecraft.util.Identifier; import net.minecraft.village.VillagerType; +import net.minecraft.world.attribute.AmbientParticle; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.Biome.Precipitation; import net.minecraft.world.biome.Biome.TemperatureModifier; import net.minecraft.world.biome.BiomeEffects.GrassColorModifier; -import net.minecraft.world.biome.BiomeParticleConfig; import net.minecraft.world.biome.SpawnSettings; import net.minecraft.world.biome.source.MultiNoiseBiomeSourceParameterList; import net.minecraft.world.dimension.DimensionType; @@ -87,7 +87,7 @@ public abstract class ModPlatform extends AbstractPlatform { .registerLoader(TemperatureModifier.class, (type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase())) .registerLoader(SpawnGroup.class, (type, o, loader, depthTracker) -> SpawnGroup.valueOf((String) o)) - .registerLoader(BiomeParticleConfig.class, BiomeParticleConfigTemplate::new) + .registerLoader(AmbientParticle.class, BiomeParticleConfigTemplate::new) .registerLoader(SoundEvent.class, SoundEventTemplate::new) .registerLoader(BiomeMoodSound.class, BiomeMoodSoundTemplate::new) .registerLoader(BiomeAdditionsSound.class, BiomeAdditionsSoundTemplate::new) 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 index ba2c4c1fb..83774831b 100644 --- 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 @@ -8,12 +8,11 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.minecraft.command.argument.ParticleEffectArgumentType; import net.minecraft.registry.Registries; import net.minecraft.registry.RegistryWrapper; -import net.minecraft.world.biome.BiomeParticleConfig; - +import net.minecraft.world.attribute.AmbientParticle; import java.util.stream.Stream; -public class BiomeParticleConfigTemplate implements ObjectTemplate { +public class BiomeParticleConfigTemplate implements ObjectTemplate { @Value("particle") @Default private String particle = null; @@ -23,13 +22,13 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate>> cir) { if(flora != null) { cir.setReturnValue(flora); From 96863722388af9c8f737822ba45712606b1966a6 Mon Sep 17 00:00:00 2001 From: Nico Weber Date: Sun, 21 Dec 2025 01:41:15 +0100 Subject: [PATCH 08/44] feat: update minestom to 1.21.11 --- buildSrc/src/main/kotlin/Versions.kt | 2 +- .../terra/minestom/TerraMinestomPlatform.java | 8 ++-- .../MinestomUserDefinedBiomeFactory.java | 39 +++++++++---------- .../config/BiomeAdditionsSoundTemplate.java | 7 ++-- .../config/BiomeMoodSoundTemplate.java | 7 ++-- .../config/BiomeParticleConfigTemplate.java | 11 +++--- .../config/VanillaBiomeProperties.java | 32 ++++++++------- 7 files changed, 56 insertions(+), 50 deletions(-) diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index 2f8a20b54..ae15639cf 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -96,6 +96,6 @@ object Versions { } object Minestom { - const val minestom = "2025.10.31-1.21.10" + const val minestom = "2025.12.20c-1.21.11" } } diff --git a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/TerraMinestomPlatform.java b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/TerraMinestomPlatform.java index 810426f83..ba5d6bb66 100644 --- a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/TerraMinestomPlatform.java +++ b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/TerraMinestomPlatform.java @@ -7,6 +7,8 @@ import net.kyori.adventure.util.RGBLike; import net.minestom.server.MinecraftServer; import net.minestom.server.instance.Instance; import net.minestom.server.sound.SoundEvent; +import net.minestom.server.world.attribute.AmbientParticle; +import net.minestom.server.world.attribute.AmbientSounds; import net.minestom.server.world.biome.BiomeEffects; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -82,9 +84,9 @@ public final class TerraMinestomPlatform extends AbstractPlatform { (TypeLoader) (annotatedType, o, configLoader, depthTracker) -> new MinestomEntityType((String) o)) .registerLoader(BlockState.class, (TypeLoader) (annotatedType, o, configLoader, depthTracker) -> worldHandle.createBlockState((String) o)) - .registerLoader(BiomeEffects.Particle.class, BiomeParticleConfigTemplate::new) - .registerLoader(BiomeEffects.MoodSound.class, BiomeMoodSoundTemplate::new) - .registerLoader(BiomeEffects.AdditionsSound.class, BiomeAdditionsSoundTemplate::new) + .registerLoader(AmbientParticle.class, BiomeParticleConfigTemplate::new) + .registerLoader(AmbientSounds.Mood.class, BiomeMoodSoundTemplate::new) + .registerLoader(AmbientSounds.Additions.class, BiomeAdditionsSoundTemplate::new) .registerLoader(SoundEvent.class, SoundEventTemplate::new); } diff --git a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/biome/MinestomUserDefinedBiomeFactory.java b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/biome/MinestomUserDefinedBiomeFactory.java index 644350d49..29ea5b117 100644 --- a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/biome/MinestomUserDefinedBiomeFactory.java +++ b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/biome/MinestomUserDefinedBiomeFactory.java @@ -5,6 +5,7 @@ import net.minestom.server.MinecraftServer; import net.minestom.server.color.Color; import net.minestom.server.registry.DynamicRegistry; import net.minestom.server.registry.RegistryKey; +import net.minestom.server.world.attribute.EnvironmentAttribute; import net.minestom.server.world.biome.Biome; import net.minestom.server.world.biome.BiomeEffects; import org.intellij.lang.annotations.Subst; @@ -27,6 +28,11 @@ public class MinestomUserDefinedBiomeFactory implements BiomeFactory { return first; } + private static void applyAttributeIfNotNull(Biome.Builder biomeBuilder, EnvironmentAttribute attribute, T value) { + if (value == null) return; + biomeBuilder.setAttribute(attribute, value); + } + @Subst("value") protected static String createBiomeID(ConfigPack pack, String biomeId) { return pack.getID().toLowerCase() + "/" + biomeId.toLowerCase(Locale.ROOT); @@ -41,32 +47,25 @@ public class MinestomUserDefinedBiomeFactory implements BiomeFactory { Key key = Key.key("terra", createBiomeID(pack, source.getID())); BiomeEffects.Builder effectsBuilder = BiomeEffects.builder() - .fogColor(mergeNullable(properties.getFogColor(), parentEffects.fogColor())) - .skyColor(mergeNullable(properties.getSkyColor(), parentEffects.skyColor())) .waterColor(mergeNullable(properties.getWaterColor(), parentEffects.waterColor())) - .waterFogColor(mergeNullable(properties.getWaterFogColor(), parentEffects.waterFogColor())) .foliageColor(mergeNullable(properties.getFoliageColor(), parentEffects.foliageColor())) .grassColor(mergeNullable(properties.getGrassColor(), parentEffects.grassColor())) - .grassColorModifier(mergeNullable(properties.getGrassColorModifier(), parentEffects.grassColorModifier())) - .biomeParticle(mergeNullable(properties.getParticleConfig(), parentEffects.biomeParticle())) - .ambientSound(mergeNullable(properties.getLoopSound(), parentEffects.ambientSound())) - .moodSound(mergeNullable(properties.getMoodSound(), parentEffects.moodSound())) - .additionsSound(mergeNullable(properties.getAdditionsSound(), parentEffects.additionsSound())) - // TODO music - .music(parentEffects.music()) - .musicVolume(parentEffects.musicVolume()); + .grassColorModifier(mergeNullable(properties.getGrassColorModifier(), parentEffects.grassColorModifier())); - if(effectsBuilder.build().equals(BiomeEffects.PLAINS_EFFECTS)) { - effectsBuilder.fogColor(new Color(0xC0D8FE)); // circumvent a minestom bug - } - - Biome target = Biome.builder() + Biome.Builder targetBuilder = Biome.builder() .downfall(mergeNullable(properties.getDownfall(), parent.downfall())) - .hasPrecipitation(mergeNullable(properties.getPrecipitation(), parent.hasPrecipitation())) + .precipitation(mergeNullable(properties.getPrecipitation(), parent.hasPrecipitation())) .temperature(mergeNullable(properties.getTemperature(), parent.temperature())) - .temperatureModifier(mergeNullable(properties.getTemperatureModifier(), parent.temperatureModifier())) - .effects(effectsBuilder.build()) - .build(); + .effects(effectsBuilder.build()); + + applyAttributeIfNotNull(targetBuilder, EnvironmentAttribute.FOG_COLOR, properties.getFogColor()); + applyAttributeIfNotNull(targetBuilder, EnvironmentAttribute.SKY_COLOR, properties.getSkyColor()); + applyAttributeIfNotNull(targetBuilder, EnvironmentAttribute.WATER_FOG_COLOR, properties.getWaterFogColor()); + applyAttributeIfNotNull(targetBuilder, EnvironmentAttribute.AMBIENT_PARTICLES, properties.getParticleConfig()); + applyAttributeIfNotNull(targetBuilder, EnvironmentAttribute.AMBIENT_SOUNDS, properties.getAmbientSoundConfig()); + // TODO music + + Biome target = targetBuilder.build(); RegistryKey registryKey = MinecraftServer.getBiomeRegistry().register(key, target); return new UserDefinedBiome(key, registryKey, source.getID(), target); diff --git a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeAdditionsSoundTemplate.java b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeAdditionsSoundTemplate.java index 85e4499fc..c5686688a 100644 --- a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeAdditionsSoundTemplate.java +++ b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeAdditionsSoundTemplate.java @@ -4,10 +4,11 @@ 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.minestom.server.sound.SoundEvent; +import net.minestom.server.world.attribute.AmbientSounds; import net.minestom.server.world.biome.BiomeEffects; -public class BiomeAdditionsSoundTemplate implements ObjectTemplate { +public class BiomeAdditionsSoundTemplate implements ObjectTemplate { @Value("sound") @Default private SoundEvent sound = null; @@ -17,8 +18,8 @@ public class BiomeAdditionsSoundTemplate implements ObjectTemplate { +public class BiomeMoodSoundTemplate implements ObjectTemplate { @Value("sound") @Default private SoundEvent sound = null; @@ -25,9 +26,9 @@ public class BiomeMoodSoundTemplate implements ObjectTemplate { +public class BiomeParticleConfigTemplate implements ObjectTemplate { @Value("particle") @Default private String particle = null; @@ -18,7 +19,7 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate getParticleConfig() { + if (particleConfig == null) return null; + return List.of(particleConfig); } public Boolean getPrecipitation() { @@ -125,15 +130,12 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties { return downfall; } - public SoundEvent getLoopSound() { - return loopSound; - } - - public BiomeEffects.MoodSound getMoodSound() { - return moodSound; - } - - public BiomeEffects.AdditionsSound getAdditionsSound() { - return additionsSound; + public AmbientSounds getAmbientSoundConfig() { + List additions = additionsSound == null ? List.of() : List.of(additionsSound); + return new AmbientSounds( + loopSound, + moodSound, + additions + ); } } From 7b44ea93ba01044674cbfb5704163fdca03693ee Mon Sep 17 00:00:00 2001 From: ArikSquad <75741608+ArikSquad@users.noreply.github.com> Date: Tue, 5 May 2026 17:42:55 +0300 Subject: [PATCH 09/44] feat: 26.1.2 --- .github/workflows/gradle-build.yml | 4 +- buildSrc/build.gradle.kts | 2 +- buildSrc/src/main/kotlin/Utils.kt | 11 +- buildSrc/src/main/kotlin/Versions.kt | 6 +- gradle/wrapper/gradle-wrapper.properties | 2 +- platforms/bukkit/build.gradle.kts | 4 + platforms/bukkit/common/build.gradle.kts | 3 + .../dfsek/terra/bukkit/NMSInitializer.java | 2 +- platforms/bukkit/nms/build.gradle.kts | 4 + .../terra/bukkit/nms/AwfulBukkitHacks.java | 16 +-- .../terra/bukkit/nms/NMSBiomeInjector.java | 134 ++++++++++++------ .../bukkit/nms/NMSChunkGeneratorDelegate.java | 4 +- .../dfsek/terra/bukkit/nms/NMSPlatform.java | 16 +-- .../dfsek/terra/bukkit/nms/Reflection.java | 3 +- .../config/BiomeAdditionsSoundTemplate.java | 2 +- .../nms/config/BiomeMoodSoundTemplate.java | 2 +- .../config/BiomeParticleConfigTemplate.java | 8 +- .../bukkit/nms/config/EntityTypeTemplate.java | 4 +- .../bukkit/nms/config/SoundEventTemplate.java | 4 +- .../nms/config/VanillaBiomeProperties.java | 12 +- .../nms/config/VillagerTypeTemplate.java | 6 +- 21 files changed, 153 insertions(+), 96 deletions(-) diff --git a/.github/workflows/gradle-build.yml b/.github/workflows/gradle-build.yml index b289ca1aa..959a6a81f 100644 --- a/.github/workflows/gradle-build.yml +++ b/.github/workflows/gradle-build.yml @@ -18,10 +18,10 @@ jobs: steps: - uses: actions/checkout@v4.2.2 - - name: Set up JDK 21 + - name: Set up JDK 25 uses: actions/setup-java@v4.7.1 with: - java-version: '21' + java-version: '25' distribution: 'temurin' server-id: github # Value of the distributionManagement/repository/id field of the pom.xml settings-path: ${{ github.workspace }} # location for the settings.xml file diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 5ca04d11a..c0a763e2d 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -24,7 +24,7 @@ dependencies { //TODO Allow pulling from Versions.kt implementation("com.gradleup.shadow", "shadow-gradle-plugin", "8.3.9") - implementation("io.papermc.paperweight.userdev", "io.papermc.paperweight.userdev.gradle.plugin", "2.0.0-beta.18") + implementation("io.papermc.paperweight.userdev", "io.papermc.paperweight.userdev.gradle.plugin", "2.0.0-beta.21") implementation("org.ow2.asm", "asm", "9.9") implementation("org.ow2.asm", "asm-tree", "9.9") implementation("com.dfsek.tectonic", "common", "4.3.1") diff --git a/buildSrc/src/main/kotlin/Utils.kt b/buildSrc/src/main/kotlin/Utils.kt index 679786788..b786d0645 100644 --- a/buildSrc/src/main/kotlin/Utils.kt +++ b/buildSrc/src/main/kotlin/Utils.kt @@ -7,19 +7,14 @@ var isPrerelease = false fun Project.getGitHash(): String { - val stdout = ByteArrayOutputStream() - exec { + return providers.exec { commandLine = mutableListOf("git", "rev-parse", "--short", "HEAD") - standardOutput = stdout - } - return stdout.toString().trim() + }.standardOutput.asText.get().trim() } fun Project.gitClone(name: String) { - val stdout = ByteArrayOutputStream() - exec { + providers.exec { commandLine = mutableListOf("git", "clone", name) - standardOutput = stdout } } diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index cb593331a..c12513ee0 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -60,15 +60,15 @@ object Versions { // } object Bukkit { - const val minecraft = "1.21.10" + const val minecraft = "26.1.2" const val nms = "$minecraft-R0.1" - const val paperBuild = "$nms-20251012.013929-7" + const val paperBuild = "26.1.2.build.60-stable" const val paper = paperBuild const val paperLib = "1.0.8" const val reflectionRemapper = "0.1.3" const val paperDevBundle = paperBuild const val runPaper = "2.3.1" - const val paperWeight = "2.0.0-beta.19" + const val paperWeight = "2.0.0-beta.21" const val cloud = "2.0.0-beta.12" const val multiverse = "5.3.0" } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 9128c7d42..3f8cf63e7 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,7 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionSha256Sum=845952a9d6afa783db70bb3b0effaae45ae5542ca2bb7929619e8af49cb634cf -distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/platforms/bukkit/build.gradle.kts b/platforms/bukkit/build.gradle.kts index b55db49b6..377eaaf95 100644 --- a/platforms/bukkit/build.gradle.kts +++ b/platforms/bukkit/build.gradle.kts @@ -12,6 +12,10 @@ dependencies { shaded("xyz.jpenilla", "reflection-remapper", Versions.Bukkit.reflectionRemapper) } +tasks.withType().configureEach { + options.release = 25 +} + tasks { shadowJar { relocate("io.papermc.lib", "com.dfsek.terra.lib.paperlib") diff --git a/platforms/bukkit/common/build.gradle.kts b/platforms/bukkit/common/build.gradle.kts index 57c7ba5a9..11673f8fc 100644 --- a/platforms/bukkit/common/build.gradle.kts +++ b/platforms/bukkit/common/build.gradle.kts @@ -1,6 +1,9 @@ repositories { } +tasks.withType().configureEach { + options.release = 25 +} dependencies { shadedApi(project(":common:implementation:base")) diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java index f15beea0a..bb89ec868 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java @@ -9,7 +9,7 @@ import com.dfsek.terra.bukkit.util.VersionUtil; public interface NMSInitializer { - List SUPPORTED_VERSIONS = List.of("v1.21.9", "v1.21.10"); + List SUPPORTED_VERSIONS = List.of("v26.1.2"); String MINECRAFT_VERSION = VersionUtil.getMinecraftVersionInfo().toString(); String TERRA_PACKAGE = NMSInitializer.class.getPackageName(); diff --git a/platforms/bukkit/nms/build.gradle.kts b/platforms/bukkit/nms/build.gradle.kts index b521d372a..032aa34d6 100644 --- a/platforms/bukkit/nms/build.gradle.kts +++ b/platforms/bukkit/nms/build.gradle.kts @@ -2,6 +2,10 @@ plugins { id("io.papermc.paperweight.userdev") } +tasks.withType().configureEach { + options.release = 25 +} + dependencies { api(project(":platforms:bukkit:common")) paperweight.paperDevBundle(Versions.Bukkit.paperDevBundle) diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java index beea1c536..310e4190f 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java @@ -7,10 +7,10 @@ import net.minecraft.core.HolderSet.Named; 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.ResourceKey; -import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; -import net.minecraft.world.entity.npc.VillagerType; +import net.minecraft.world.entity.npc.villager.VillagerType; import net.minecraft.world.level.biome.Biome; import org.bukkit.NamespacedKey; import org.slf4j.Logger; @@ -34,7 +34,7 @@ import com.dfsek.terra.registry.master.ConfigRegistry; public class AwfulBukkitHacks { private static final Logger LOGGER = LoggerFactory.getLogger(AwfulBukkitHacks.class); - private static final Map> terraBiomeMap = new HashMap<>(); + private static final Map> terraBiomeMap = new HashMap<>(); public static void registerBiomes(ConfigRegistry configRegistry) { try { @@ -50,7 +50,7 @@ public class AwfulBukkitHacks { BukkitPlatformBiome platformBiome = (BukkitPlatformBiome) biome.getPlatformBiome(); NamespacedKey vanillaBukkitKey = platformBiome.getHandle().getKey(); - ResourceLocation vanillaMinecraftKey = ResourceLocation.fromNamespaceAndPath(vanillaBukkitKey.getNamespace(), + Identifier vanillaMinecraftKey = Identifier.fromNamespaceAndPath(vanillaBukkitKey.getNamespace(), vanillaBukkitKey.getKey()); VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class); @@ -58,7 +58,7 @@ public class AwfulBukkitHacks { Biome platform = NMSBiomeInjector.createBiome(biomeRegistry.get(vanillaMinecraftKey).orElseThrow().value(), vanillaBiomeProperties); - ResourceLocation delegateMinecraftKey = ResourceLocation.fromNamespaceAndPath("terra", + Identifier delegateMinecraftKey = Identifier.fromNamespaceAndPath("terra", NMSBiomeInjector.createBiomeID(pack, key)); NamespacedKey delegateBukkitKey = NamespacedKey.fromString(delegateMinecraftKey.toString()); ResourceKey delegateKey = ResourceKey.create(Registries.BIOME, delegateMinecraftKey); @@ -75,7 +75,7 @@ public class AwfulBukkitHacks { Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(), villagerMap.getOrDefault(delegateKey, VillagerType.PLAINS))); - terraBiomeMap.computeIfAbsent(vanillaMinecraftKey, i -> new ArrayList<>()).add(delegateKey.location()); + terraBiomeMap.computeIfAbsent(vanillaMinecraftKey, i -> new ArrayList<>()).add(delegateKey.identifier()); LOGGER.debug("Registered biome: " + delegateKey); } catch(NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { @@ -100,8 +100,8 @@ public class AwfulBukkitHacks { tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb).ifPresentOrElse( terra -> { LOGGER.debug("{} (vanilla for {}): {}", - vanilla.unwrapKey().orElseThrow().location(), - terra.unwrapKey().orElseThrow().location(), + vanilla.unwrapKey().orElseThrow().identifier(), + terra.unwrapKey().orElseThrow().identifier(), vanilla.tags().toList()); vanilla.tags() .forEach(tag -> collect diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java index fea134c9e..25be1fc44 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java @@ -1,12 +1,26 @@ package com.dfsek.terra.bukkit.nms; +import com.dfsek.terra.api.registry.key.RegistryKey; + import net.minecraft.core.Holder; import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; +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.attribute.AmbientSounds; +import net.minecraft.world.attribute.BackgroundMusic; +import net.minecraft.world.attribute.EnvironmentAttributeMap; +import net.minecraft.world.attribute.EnvironmentAttributeMap.Entry; +import net.minecraft.world.attribute.EnvironmentAttributes; +import net.minecraft.world.attribute.modifier.AttributeModifier; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.BiomeGenerationSettings; import net.minecraft.world.level.biome.BiomeSpecialEffects; +import java.util.Collections; +import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; @@ -17,10 +31,8 @@ import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties; public class NMSBiomeInjector { - public static Optional> getEntry(Registry registry, ResourceLocation identifier) { - return registry.getOptional(identifier) - .flatMap(registry::getResourceKey) - .flatMap(registry::get); + public static Optional> getEntry(Registry registry, Identifier identifier) { + return registry.getOptional(identifier).flatMap(registry::getResourceKey).flatMap(registry::get); } public static Biome createBiome(Biome vanilla, VanillaBiomeProperties vanillaBiomeProperties) @@ -28,76 +40,116 @@ public class NMSBiomeInjector { Biome.BiomeBuilder builder = new Biome.BiomeBuilder(); BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder(); + EnvironmentAttributeMap attributes = vanilla.getAttributes(); - effects.fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor())) - .waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor())) - .waterFogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanilla.getWaterFogColor())) - .skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor())) - .grassColorModifier(Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(), - vanilla.getSpecialEffects().getGrassColorModifier())) - .backgroundMusicVolume(Objects.requireNonNullElse(vanillaBiomeProperties.getMusicVolume(), vanilla.getBackgroundMusicVolume())); + Integer vanillaFogColour = (Integer) Objects.requireNonNull(attributes.get(EnvironmentAttributes.FOG_COLOR)).argument(); + Integer vanillaWaterFogColour = (Integer) Objects.requireNonNull(attributes.get(EnvironmentAttributes.WATER_FOG_COLOR)).argument(); + Integer vanillaSkyColour = (Integer) Objects.requireNonNull(attributes.get(EnvironmentAttributes.SKY_COLOR)).argument(); + Float vanillaMusicVolume = (Float) Objects.requireNonNull(attributes.get(EnvironmentAttributes.MUSIC_VOLUME)).argument(); + + builder.modifyAttribute(EnvironmentAttributes.FOG_COLOR, AttributeModifier.override(), + Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanillaFogColour)); + builder.modifyAttribute(EnvironmentAttributes.WATER_FOG_COLOR, AttributeModifier.override(), + Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanillaWaterFogColour)); + builder.modifyAttribute(EnvironmentAttributes.SKY_COLOR, AttributeModifier.override(), + Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanillaSkyColour)); + builder.modifyAttribute(EnvironmentAttributes.MUSIC_VOLUME, AttributeModifier.override(), + Objects.requireNonNullElse(vanillaBiomeProperties.getMusicVolume(), vanillaMusicVolume)); + + effects.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor())); + effects.grassColorModifier( + Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(), vanilla.getSpecialEffects().grassColorModifier())); if(vanillaBiomeProperties.getGrassColor() == null) { - vanilla.getSpecialEffects().getGrassColorOverride().ifPresent(effects::grassColorOverride); + vanilla.getSpecialEffects().grassColorOverride().ifPresent(effects::grassColorOverride); } else { effects.grassColorOverride(vanillaBiomeProperties.getGrassColor()); } if(vanillaBiomeProperties.getFoliageColor() == null) { - vanilla.getSpecialEffects().getFoliageColorOverride().ifPresent(effects::foliageColorOverride); + vanilla.getSpecialEffects().foliageColorOverride().ifPresent(effects::foliageColorOverride); } else { effects.foliageColorOverride(vanillaBiomeProperties.getFoliageColor()); } if(vanillaBiomeProperties.getParticleConfig() == null) { - vanilla.getSpecialEffects().getAmbientParticleSettings().ifPresent(effects::ambientParticle); + Entry ambientEntry = attributes.get(EnvironmentAttributes.AMBIENT_PARTICLES); + if(ambientEntry != null) { + Object arg = ambientEntry.argument(); + + // this is not nice + if(arg instanceof List rawList) { + List ambientParticles = + rawList.stream() + .filter(AmbientParticle.class::isInstance) + .map(AmbientParticle.class::cast) + .toList(); + + builder.modifyAttribute( + EnvironmentAttributes.AMBIENT_PARTICLES, + AttributeModifier.override(), + ambientParticles + ); + } + } } else { - effects.ambientParticle(vanillaBiomeProperties.getParticleConfig()); + builder.modifyAttribute(EnvironmentAttributes.AMBIENT_PARTICLES, AttributeModifier.override(), + List.of(vanillaBiomeProperties.getParticleConfig())); } - if(vanillaBiomeProperties.getLoopSound() == null) { - vanilla.getSpecialEffects().getAmbientLoopSoundEvent().ifPresent(effects::ambientLoopSound); - } else { - RegistryFetcher.soundEventRegistry().get(vanillaBiomeProperties.getLoopSound().location()).ifPresent(effects::ambientLoopSound); + Optional> loop = Optional.empty(); + Optional mood = Optional.empty(); + List additions = Collections.emptyList(); + + if(attributes.contains(EnvironmentAttributes.AMBIENT_SOUNDS)) { + AmbientSounds sounds = + (AmbientSounds) Objects.requireNonNull(attributes.get(EnvironmentAttributes.AMBIENT_SOUNDS)).argument(); + + loop = sounds.loop(); + mood = sounds.mood(); + additions = sounds.additions(); } - if(vanillaBiomeProperties.getMoodSound() == null) { - vanilla.getSpecialEffects().getAmbientMoodSettings().ifPresent(effects::ambientMoodSound); - } else { - effects.ambientMoodSound(vanillaBiomeProperties.getMoodSound()); + if(vanillaBiomeProperties.getLoopSound() != null) { + loop = RegistryFetcher.soundEventRegistry() + .get(vanillaBiomeProperties.getLoopSound().location()) + .map(ref -> ref); } - if(vanillaBiomeProperties.getAdditionsSound() == null) { - vanilla.getSpecialEffects().getAmbientAdditionsSettings().ifPresent(effects::ambientAdditionsSound); - } else { - effects.ambientAdditionsSound(vanillaBiomeProperties.getAdditionsSound()); + if(vanillaBiomeProperties.getMoodSound() != null) { + mood = Optional.ofNullable(vanillaBiomeProperties.getMoodSound()); } + if(vanillaBiomeProperties.getAdditionsSound() != null) { + additions = Collections.singletonList(vanillaBiomeProperties.getAdditionsSound()); + } + + builder.modifyAttribute(EnvironmentAttributes.AMBIENT_SOUNDS, AttributeModifier.override(), + new AmbientSounds(loop, mood, additions)); + if(vanillaBiomeProperties.getMusic() == null) { - vanilla.getSpecialEffects().getBackgroundMusic().ifPresent(effects::backgroundMusic); + if(attributes.contains(EnvironmentAttributes.BACKGROUND_MUSIC)) { + BackgroundMusic music = (BackgroundMusic) Objects.requireNonNull(attributes.get(EnvironmentAttributes.BACKGROUND_MUSIC)) + .argument(); + builder.modifyAttribute(EnvironmentAttributes.BACKGROUND_MUSIC, AttributeModifier.override(), music); + } } else { - effects.backgroundMusic(vanillaBiomeProperties.getMusic()); + builder.modifyAttribute(EnvironmentAttributes.BACKGROUND_MUSIC, AttributeModifier.override(), + new BackgroundMusic(vanillaBiomeProperties.getMusic())); } builder.hasPrecipitation(Objects.requireNonNullElse(vanillaBiomeProperties.getPrecipitation(), vanilla.hasPrecipitation())); - builder.temperature(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperature(), vanilla.getBaseTemperature())); - builder.downfall(Objects.requireNonNullElse(vanillaBiomeProperties.getDownfall(), vanilla.climateSettings.downfall())); - builder.temperatureAdjustment( Objects.requireNonNullElse(vanillaBiomeProperties.getTemperatureModifier(), vanilla.climateSettings.temperatureModifier())); - builder.mobSpawnSettings(Objects.requireNonNullElse(vanillaBiomeProperties.getSpawnSettings(), vanilla.getMobSettings())); - return builder - .specialEffects(effects.build()) - .generationSettings(new BiomeGenerationSettings.PlainBuilder().build()) - .build(); + return builder.specialEffects(effects.build()).generationSettings(new BiomeGenerationSettings.PlainBuilder().build()).build(); } - public static String createBiomeID(ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey biomeID) { - return pack.getID() - .toLowerCase() + "/" + biomeID.getNamespace().toLowerCase(Locale.ROOT) + "/" + biomeID.getID().toLowerCase(Locale.ROOT); + public static String createBiomeID(ConfigPack pack, RegistryKey biomeID) { + return pack.getID().toLowerCase() + "/" + biomeID.getNamespace().toLowerCase(Locale.ROOT) + "/" + biomeID.getID().toLowerCase( + Locale.ROOT); } } diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java index 0b21b9d12..e22ff1e6b 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java @@ -106,8 +106,8 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator { Beardifier structureWeightSampler = Beardifier.forStructuresInChunk(structureAccessor, chunk.getPos()); double threshold = compatibilityOptions.getBeardThreshold(); double airThreshold = compatibilityOptions.getAirThreshold(); - int xi = chunk.getPos().x << 4; - int zi = chunk.getPos().z << 4; + int xi = chunk.getPos().x() << 4; + int zi = chunk.getPos().z() << 4; for(int x = 0; x < 16; x++) { for(int z = 0; z < 16; z++) { int depth = 0; diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java index efbdde212..e54b2fd04 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java @@ -2,15 +2,15 @@ package com.dfsek.terra.bukkit.nms; import com.dfsek.tectonic.api.TypeRegistry; import com.dfsek.tectonic.api.exception.LoadException; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; 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.VillagerType; -import net.minecraft.world.level.biome.AmbientAdditionsSettings; -import net.minecraft.world.level.biome.AmbientMoodSettings; -import net.minecraft.world.level.biome.AmbientParticleSettings; +import net.minecraft.world.entity.npc.villager.VillagerType; import net.minecraft.world.level.biome.Biome.Precipitation; import net.minecraft.world.level.biome.Biome.TemperatureModifier; import net.minecraft.world.level.biome.BiomeSpecialEffects.GrassColorModifier; @@ -52,8 +52,8 @@ public class NMSPlatform extends PlatformImpl { public void register(TypeRegistry registry) { super.register(registry); registry.registerLoader(PlatformBiome.class, (type, o, loader, depthTracker) -> parseBiome((String) o, depthTracker)) - .registerLoader(ResourceLocation.class, (type, o, loader, depthTracker) -> { - ResourceLocation identifier = ResourceLocation.tryParse((String) o); + .registerLoader(Identifier.class, (type, o, loader, depthTracker) -> { + Identifier identifier = Identifier.tryParse((String) o); if(identifier == null) throw new LoadException("Invalid identifier: " + o, depthTracker); return identifier; @@ -67,7 +67,7 @@ public class NMSPlatform extends PlatformImpl { (type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase( Locale.ROOT))) .registerLoader(MobCategory.class, (type, o, loader, depthTracker) -> MobCategory.valueOf((String) o)) - .registerLoader(AmbientParticleSettings.class, BiomeParticleConfigTemplate::new) + .registerLoader(AmbientParticle.class, BiomeParticleConfigTemplate::new) .registerLoader(SoundEvent.class, SoundEventTemplate::new) .registerLoader(AmbientMoodSettings.class, BiomeMoodSoundTemplate::new) .registerLoader(AmbientAdditionsSettings.class, BiomeAdditionsSoundTemplate::new) diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java index 3c0e93e67..32d6c9132 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java @@ -7,7 +7,7 @@ import net.minecraft.core.MappedRegistry; import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ChunkMap; import net.minecraft.tags.TagKey; -import net.minecraft.world.entity.npc.VillagerType; +import net.minecraft.world.entity.npc.villager.VillagerType; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.StructureManager; import net.minecraft.world.level.biome.Biome; @@ -24,7 +24,6 @@ import java.util.Collection; import java.util.List; import java.util.Map; - public class Reflection { public static final MappedRegistryProxy MAPPED_REGISTRY; public static final MappedRegistryTagSetProxy MAPPED_REGISTRY_TAG_SET; diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java index 83ac758b2..3e3286098 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java @@ -5,7 +5,7 @@ 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.level.biome.AmbientAdditionsSettings; +import net.minecraft.world.attribute.AmbientAdditionsSettings; public class BiomeAdditionsSoundTemplate implements ObjectTemplate { diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeMoodSoundTemplate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeMoodSoundTemplate.java index 20f982920..b7b774ae3 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeMoodSoundTemplate.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeMoodSoundTemplate.java @@ -5,7 +5,7 @@ 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.level.biome.AmbientMoodSettings; +import net.minecraft.world.attribute.AmbientMoodSettings; public class BiomeMoodSoundTemplate implements ObjectTemplate { diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java index 99fe0cda3..7c31521f2 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java @@ -8,12 +8,12 @@ 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.level.biome.AmbientParticleSettings; +import net.minecraft.world.attribute.AmbientParticle; import java.util.stream.Stream; -public class BiomeParticleConfigTemplate implements ObjectTemplate { +public class BiomeParticleConfigTemplate implements ObjectTemplate { @Value("particle") @Default private String particle = null; @@ -23,13 +23,13 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate> { @Value("id") @Default - private ResourceLocation id = null; + private Identifier id = null; @Override public EntityType get() { diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java index 253582361..4d7b7bddd 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java @@ -3,14 +3,14 @@ package com.dfsek.terra.bukkit.nms.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.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.sounds.SoundEvent; public class SoundEventTemplate implements ObjectTemplate { @Value("id") @Default - private ResourceLocation id = null; + private Identifier id = null; @Value("distance-to-travel") @Default diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java index 3cd1e992b..cb74f635d 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java @@ -6,10 +6,10 @@ 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.entity.npc.VillagerType; -import net.minecraft.world.level.biome.AmbientAdditionsSettings; -import net.minecraft.world.level.biome.AmbientMoodSettings; -import net.minecraft.world.level.biome.AmbientParticleSettings; +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; @@ -52,7 +52,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties { @Value("particles") @Default - private AmbientParticleSettings particleConfig = null; + private AmbientParticle particleConfig = null; @Value("climate.precipitation") @Default @@ -130,7 +130,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties { return grassColorModifier; } - public AmbientParticleSettings getParticleConfig() { + public AmbientParticle getParticleConfig() { return particleConfig; } diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java index c254628b8..209ce3da7 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java @@ -4,15 +4,15 @@ 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.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.npc.VillagerType; +import net.minecraft.world.entity.npc.villager.VillagerType; public class VillagerTypeTemplate implements ObjectTemplate> { @Value("id") @Default - private ResourceLocation id = null; + private Identifier id = null; @Override public ResourceKey get() { From 148b3cf6f02fb3a6f2d7361d94d561dad99ef149 Mon Sep 17 00:00:00 2001 From: ArikSquad <75741608+ArikSquad@users.noreply.github.com> Date: Tue, 5 May 2026 19:03:02 +0300 Subject: [PATCH 10/44] feat: hacks for 26.1.2 --- buildSrc/src/main/kotlin/Versions.kt | 4 +- .../bukkit/handles/BukkitWorldHandle.java | 20 ++++++- .../dfsek/terra/bukkit/util/BukkitUtils.java | 7 +++ .../terra/bukkit/nms/AwfulBukkitHacks.java | 26 ++++++++- .../terra/bukkit/nms/NMSBiomeInjector.java | 56 +++++++++++++++---- 5 files changed, 93 insertions(+), 20 deletions(-) diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index c12513ee0..3add39691 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -67,9 +67,9 @@ object Versions { const val paperLib = "1.0.8" const val reflectionRemapper = "0.1.3" const val paperDevBundle = paperBuild - const val runPaper = "2.3.1" + const val runPaper = "3.0.2" const val paperWeight = "2.0.0-beta.21" - const val cloud = "2.0.0-beta.12" + const val cloud = "2.0.0-beta.15" const val multiverse = "5.3.0" } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitWorldHandle.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitWorldHandle.java index 0136d4389..3ad138d83 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitWorldHandle.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitWorldHandle.java @@ -19,6 +19,7 @@ package com.dfsek.terra.bukkit.handles; import org.bukkit.Bukkit; import org.bukkit.Material; +import org.bukkit.block.data.BlockData; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,6 +30,9 @@ import com.dfsek.terra.api.handle.WorldHandle; import com.dfsek.terra.bukkit.util.BukkitUtils; import com.dfsek.terra.bukkit.world.block.data.BukkitBlockState; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + public class BukkitWorldHandle implements WorldHandle { private static final Logger logger = LoggerFactory.getLogger(BukkitWorldHandle.class); @@ -40,9 +44,19 @@ public class BukkitWorldHandle implements WorldHandle { @Override public synchronized @NotNull BlockState createBlockState(@NotNull String data) { - org.bukkit.block.data.BlockData bukkitData = Bukkit.createBlockData( - data); // somehow bukkit managed to make this not thread safe! :) - return BukkitBlockState.newInstance(bukkitData); + try { + org.bukkit.block.data.BlockData bukkitData = Bukkit.createBlockData(data); // somehow bukkit managed to make this not thread safe! :) + return BukkitBlockState.newInstance(bukkitData); + } catch (Exception ignored) { + try { + Class hacks = Class.forName("com.dfsek.terra.bukkit.nms.AwfulBukkitHacks"); + Method method = hacks.getMethod("createBlockState", String.class); + Object result = method.invoke(null, data); + return BukkitBlockState.newInstance((BlockData) result); + } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalArgumentException("Invalid block state data: " + data); + } + } } @Override diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitUtils.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitUtils.java index eb5d62270..d2c80f5ff 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitUtils.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitUtils.java @@ -23,6 +23,13 @@ public class BukkitUtils { if(!id.startsWith("minecraft:")) throw new IllegalArgumentException("Invalid entity identifier " + id); String entityID = id.toUpperCase(Locale.ROOT).substring(10); + // TODO: remove this + // the default end seems to use this, this should be removed otherwise + // or replaced by a proper entity & NBT loader + if (entityID.contains("END_CRYSTAL")) { + entityID = "END_CRYSTAL"; + } + return new BukkitEntityType(switch(entityID) { case "END_CRYSTAL" -> org.bukkit.entity.EntityType.END_CRYSTAL; case "ENDER_CRYSTAL" -> throw new IllegalArgumentException( diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java index 310e4190f..5b4bb1eaf 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java @@ -1,18 +1,29 @@ package com.dfsek.terra.bukkit.nms; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import net.minecraft.commands.arguments.blocks.BlockStateParser; +import net.minecraft.commands.arguments.blocks.BlockStateParser.BlockResult; import net.minecraft.core.Holder; import net.minecraft.core.Holder.Reference; -import net.minecraft.core.HolderSet; +import net.minecraft.core.HolderLookup; import net.minecraft.core.HolderSet.Named; 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.ResourceKey; +import net.minecraft.server.MinecraftServer; 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.block.Block; +import org.bukkit.Bukkit; import org.bukkit.NamespacedKey; +import org.bukkit.block.data.BlockData; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.block.data.CraftBlockData; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -120,7 +131,7 @@ public class AwfulBukkitHacks { } private static void bindTags(MappedRegistry registry, Map, List>> tagEntries) { - Map, List>> map = new IdentityHashMap<>(); + Map, List>> map = new IdentityHashMap<>(); Reflection.MAPPED_REGISTRY.getByKey(registry).values().forEach(entry -> map.put(entry, new ArrayList<>())); tagEntries.forEach((tag, entries) -> { for(Holder holder : entries) { @@ -145,7 +156,7 @@ public class AwfulBukkitHacks { // ); // } - Map, HolderSet.Named> map2 = new IdentityHashMap<>(registry.getTags().collect(Collectors.toMap( + Map, Named> map2 = new IdentityHashMap<>(registry.getTags().collect(Collectors.toMap( Named::key, (named) -> named ))); @@ -160,5 +171,14 @@ public class AwfulBukkitHacks { Reflection.MAPPED_REGISTRY.getByKey(registry).values().forEach( entry -> Reflection.HOLDER_REFERENCE.invokeBindTags(entry, Set.of())); } + + // used by BukkitWorldHandle + public static BlockData createBlockState(@NotNull String data) throws CommandSyntaxException { + MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer(); + HolderLookup.Provider lookup = server.registryAccess(); + final HolderLookup blocks = lookup.lookupOrThrow(Registries.BLOCK); + BlockResult result = BlockStateParser.parseForBlock(blocks, new StringReader(data), true); + return CraftBlockData.createData(result.blockState()); + } } diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java index 25be1fc44..4b2668814 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java @@ -11,11 +11,13 @@ import net.minecraft.world.attribute.AmbientMoodSettings; import net.minecraft.world.attribute.AmbientParticle; import net.minecraft.world.attribute.AmbientSounds; import net.minecraft.world.attribute.BackgroundMusic; +import net.minecraft.world.attribute.EnvironmentAttribute; import net.minecraft.world.attribute.EnvironmentAttributeMap; import net.minecraft.world.attribute.EnvironmentAttributeMap.Entry; import net.minecraft.world.attribute.EnvironmentAttributes; import net.minecraft.world.attribute.modifier.AttributeModifier; import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.Biome.BiomeBuilder; import net.minecraft.world.level.biome.BiomeGenerationSettings; import net.minecraft.world.level.biome.BiomeSpecialEffects; @@ -42,19 +44,22 @@ public class NMSBiomeInjector { BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder(); EnvironmentAttributeMap attributes = vanilla.getAttributes(); - Integer vanillaFogColour = (Integer) Objects.requireNonNull(attributes.get(EnvironmentAttributes.FOG_COLOR)).argument(); - Integer vanillaWaterFogColour = (Integer) Objects.requireNonNull(attributes.get(EnvironmentAttributes.WATER_FOG_COLOR)).argument(); - Integer vanillaSkyColour = (Integer) Objects.requireNonNull(attributes.get(EnvironmentAttributes.SKY_COLOR)).argument(); - Float vanillaMusicVolume = (Float) Objects.requireNonNull(attributes.get(EnvironmentAttributes.MUSIC_VOLUME)).argument(); + Integer vanillaFogColour = extractInt(attributes, EnvironmentAttributes.FOG_COLOR); + Integer vanillaWaterFogColour = extractInt(attributes, EnvironmentAttributes.WATER_FOG_COLOR); + Integer vanillaSkyColour = extractInt(attributes, EnvironmentAttributes.SKY_COLOR); + Float vanillaMusicVolume = extractFloat(attributes, EnvironmentAttributes.MUSIC_VOLUME); - builder.modifyAttribute(EnvironmentAttributes.FOG_COLOR, AttributeModifier.override(), - Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanillaFogColour)); - builder.modifyAttribute(EnvironmentAttributes.WATER_FOG_COLOR, AttributeModifier.override(), - Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanillaWaterFogColour)); - builder.modifyAttribute(EnvironmentAttributes.SKY_COLOR, AttributeModifier.override(), - Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanillaSkyColour)); - builder.modifyAttribute(EnvironmentAttributes.MUSIC_VOLUME, AttributeModifier.override(), - Objects.requireNonNullElse(vanillaBiomeProperties.getMusicVolume(), vanillaMusicVolume)); + applyIfPresent(builder, EnvironmentAttributes.FOG_COLOR, + vanillaBiomeProperties.getFogColor(), vanillaFogColour); + + applyIfPresent(builder, EnvironmentAttributes.WATER_FOG_COLOR, + vanillaBiomeProperties.getWaterFogColor(), vanillaWaterFogColour); + + applyIfPresent(builder, EnvironmentAttributes.SKY_COLOR, + vanillaBiomeProperties.getSkyColor(), vanillaSkyColour); + + applyIfPresent(builder, EnvironmentAttributes.MUSIC_VOLUME, + vanillaBiomeProperties.getMusicVolume(), vanillaMusicVolume); effects.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor())); effects.grassColorModifier( @@ -152,4 +157,31 @@ public class NMSBiomeInjector { return pack.getID().toLowerCase() + "/" + biomeID.getNamespace().toLowerCase(Locale.ROOT) + "/" + biomeID.getID().toLowerCase( Locale.ROOT); } + + private static Integer extractInt(EnvironmentAttributeMap attributes, + EnvironmentAttribute key) { + Entry attr = attributes.get(key); + return attr != null ? (Integer) attr.argument() : null; + } + + private static Float extractFloat(EnvironmentAttributeMap attributes, + EnvironmentAttribute key) { + Entry attr = attributes.get(key); + return attr != null ? (Float) attr.argument() : null; + } + + private static void applyIfPresent( + BiomeBuilder builder, + EnvironmentAttribute attr, + T overrideValue, + T fallbackValue + ) { + T value = overrideValue != null ? overrideValue : fallbackValue; + + if (value == null) { + return; + } + + builder.modifyAttribute(attr, AttributeModifier.override(), value); + } } From b49b38f240e36ab495686d388993e9b7fa28d88e Mon Sep 17 00:00:00 2001 From: Christian Bergschneider Date: Tue, 12 May 2026 10:04:19 +0200 Subject: [PATCH 11/44] feat: add extensible registry interface and integrate into config and meta-config registries --- .../terra/registry/CliExtensibleRegistry.java | 93 +++++++++++++++++++ .../terra/registry/master/ConfigRegistry.java | 16 +++- .../registry/master/MetaConfigRegistry.java | 18 +++- 3 files changed, 122 insertions(+), 5 deletions(-) create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/registry/CliExtensibleRegistry.java diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/CliExtensibleRegistry.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/CliExtensibleRegistry.java new file mode 100644 index 000000000..032e11a1a --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/CliExtensibleRegistry.java @@ -0,0 +1,93 @@ +package com.dfsek.terra.registry; + +import com.google.errorprone.annotations.MustBeClosed; +import org.intellij.lang.annotations.Pattern; +import org.jspecify.annotations.Nullable; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Objects; +import java.util.stream.Stream; + + +/** + * A file-discoverable registry that can be extended by system properties + *
+ * The main use-case for this is to allow for customized locations of file-system-based key entries, + * such as putting config packs into custom locations. + *
+ * Two system properties are used to define the search path: + *
+ * terra.registry.{searchPathName}.searchPath is a list of "parent folder" paths (like the pack directory) that + * will be searched for contained files. + *
+ * terra.registry.{searchPathName}.extraPath is a list of files that will be directly evaluated for membership and + * as such will be directly treated as members of the registry. + *
+ * These system properties are formatted like UNIX-style paths, with each path separated by a colon (':') character. + */ +public interface CliExtensibleRegistry { + /** + * Get a lowercase search path name for this registry that will get plugged into + *
+ * terra.registry.{searchPathName}.searchPath + *
+ * and + *
+ * terra.registry.{searchPathName}.extraPath + */ + @Pattern("^[a-z._]+$") + String getRegistryName(); + + /** + * Check if a path may be a member of this registry heuristically. + * + * @param path Path to check + * + * @return True if the path is a member of this registry. + */ + boolean validatePathIsMember(Path path); + + default @MustBeClosed Stream getMemberPaths(Path baseSearchPath) { + String basePropertyName = "terra.registry." + getRegistryName(); + + Stream searchPath = Stream.concat( + parseValidPaths(System.getProperty(basePropertyName + ".searchPath")), + Stream.of(baseSearchPath) + ); + + Stream extraPath = parseValidPaths(System.getProperty(basePropertyName + ".extraPath")); + + return Stream.concat( + searchPath + .filter(Files::isDirectory) + .flatMap(CliExtensibleRegistry::listDirectory), + extraPath + ) + .filter(this::validatePathIsMember); + } + + private static Stream parseValidPaths(@Nullable String paths) { + return Stream.ofNullable(paths) + .flatMap(p -> Arrays.stream(p.split(":"))) + .filter(v -> !v.isBlank()) + .map(v -> { + try { + return Path.of(v).toAbsolutePath().normalize(); + } catch (Exception e) { + return null; + } + }) + .filter(Objects::nonNull); + } + + private static Stream listDirectory(Path dir) { + try { + return Files.list(dir); + } catch(IOException e) { + return Stream.empty(); + } + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java index f4b4c9dd1..831188299 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java @@ -29,13 +29,14 @@ import com.dfsek.terra.api.Platform; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.util.reflection.TypeKey; import com.dfsek.terra.config.pack.ConfigPackImpl; +import com.dfsek.terra.registry.CliExtensibleRegistry; import com.dfsek.terra.registry.OpenRegistryImpl; /** * Class to hold config packs */ -public class ConfigRegistry extends OpenRegistryImpl { +public class ConfigRegistry extends OpenRegistryImpl implements CliExtensibleRegistry { public ConfigRegistry() { super(TypeKey.of(ConfigPack.class)); @@ -45,7 +46,7 @@ public class ConfigRegistry extends OpenRegistryImpl { Path packsDirectory = platform.getDataFolder().toPath().resolve("packs"); Files.createDirectories(packsDirectory); List failedLoads = new CopyOnWriteArrayList<>(); - try(Stream packs = Files.list(packsDirectory)) { + try(Stream packs = getMemberPaths(packsDirectory)) { packs.parallel().forEach(path -> { try { ConfigPack pack = new ConfigPackImpl(path, platform); @@ -60,6 +61,17 @@ public class ConfigRegistry extends OpenRegistryImpl { } } + @Override + public String getRegistryName() { + return "config"; + } + + @Override + public boolean validatePathIsMember(Path path) { + var file = path.toFile(); + return file.isDirectory() || file.getName().endsWith(".zip"); + } + public static class PackLoadFailuresException extends Exception { @Serial private static final long serialVersionUID = 538998844645186306L; diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java index 05539475e..9adeb0c71 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java @@ -28,6 +28,7 @@ import com.dfsek.terra.api.Platform; import com.dfsek.terra.api.config.MetaPack; import com.dfsek.terra.api.util.reflection.TypeKey; import com.dfsek.terra.config.pack.MetaPackImpl; +import com.dfsek.terra.registry.CliExtensibleRegistry; import com.dfsek.terra.registry.OpenRegistryImpl; import com.dfsek.terra.registry.master.ConfigRegistry.PackLoadFailuresException; @@ -35,7 +36,7 @@ import com.dfsek.terra.registry.master.ConfigRegistry.PackLoadFailuresException; /** * Class to hold config packs */ -public class MetaConfigRegistry extends OpenRegistryImpl { +public class MetaConfigRegistry extends OpenRegistryImpl implements CliExtensibleRegistry { public MetaConfigRegistry() { super(TypeKey.of(MetaPack.class)); @@ -45,8 +46,8 @@ public class MetaConfigRegistry extends OpenRegistryImpl { Path packsDirectory = platform.getDataFolder().toPath().resolve("metapacks"); Files.createDirectories(packsDirectory); List failedLoads = new ArrayList<>(); - try(Stream packs = Files.list(packsDirectory)) { - packs.forEach(path -> { + try(Stream paths = getMemberPaths(packsDirectory)) { + paths.forEach(path -> { try { MetaPack pack = new MetaPackImpl(path, platform, configRegistry); registerChecked(pack.getRegistryKey(), pack); @@ -59,4 +60,15 @@ public class MetaConfigRegistry extends OpenRegistryImpl { throw new PackLoadFailuresException(failedLoads); } } + + @Override + public String getRegistryName() { + return "metaconfig"; + } + + @Override + public boolean validatePathIsMember(Path path) { + var file = path.toFile(); + return file.isDirectory() || file.getName().endsWith(".zip"); + } } From fdf362acd296e2f6c52aaa42f910ff820dae1868 Mon Sep 17 00:00:00 2001 From: Sybsuper Date: Sat, 16 May 2026 01:58:49 +0200 Subject: [PATCH 12/44] feat: add additional data support for particles on Minestom platform --- .../config/BiomeParticleConfigTemplate.java | 36 ++++++++++++++++--- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeParticleConfigTemplate.java b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeParticleConfigTemplate.java index 24acb99e9..cf66e61a0 100644 --- a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeParticleConfigTemplate.java +++ b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeParticleConfigTemplate.java @@ -3,11 +3,15 @@ package com.dfsek.terra.minestom.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.kyori.adventure.nbt.CompoundBinaryTag; +import net.minestom.server.adventure.MinestomAdventure; +import net.minestom.server.codec.Transcoder; import net.minestom.server.particle.Particle; import net.minestom.server.world.attribute.AmbientParticle; -import net.minestom.server.world.biome.BiomeEffects; import org.slf4j.LoggerFactory; +import java.io.IOException; + public class BiomeParticleConfigTemplate implements ObjectTemplate { @Value("particle") @@ -25,11 +29,13 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate 1) { - LoggerFactory.getLogger(BiomeParticleConfigTemplate.class).warn("Particle {} has additional data, particle will be ignored.", - particle); - return null; + int start = particle.indexOf("{"); + String dataString = particle.substring(start); + parsedParticle = parseAdditionalParticleData(dataString, key); + if (parsedParticle == null) return null; } return new AmbientParticle( @@ -37,4 +43,24 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate Date: Fri, 22 May 2026 18:39:00 +0300 Subject: [PATCH 13/44] ci: update gradle-wrapper and hash --- gradle/wrapper/gradle-wrapper.jar | Bin 43764 -> 48462 bytes gradle/wrapper/gradle-wrapper.properties | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 1b33c55baabb587c669f562ae36f953de2481846..b1b8ef56b44f16b14dc800fa8103a6d89abb526f 100644 GIT binary patch delta 40183 zcmX6^Q(z?xv&_b}ZQHhOV`JMq;fc+SZQHhOCmU>RXYYRheVM0unyIepuC9Ju0iAsZ zt+zu2%*?=sFe8KS`x4(IV6D$TXXuryf~SfC>bBZ#h({AbpP#B)){IZGAbYN8%-hxE zJ)UJRf5$c1z{XMD<2;}au2@LPW|Mlv4U?Hbqw{oSM^i1YCMbbxv@P2^($E%wWhU;| zt0L$kNrltUu#AZy3W*1BiaVU->33zP5*o#k865!fOLQ)-|^umBO^%ynpPBo0ix)Cm1Ij zP=*B~91mn}_rYG359z6S!NB(BKK%oF03iK5m#khJb`}$8eONAGjK578vAXBXEnMxz z3)rwW=p_yXaM6Fr=tm(>P)ur2+wUKRG5`4B*Gk0jF0R6fuq-N&9=}Ki?0rjE!=o6} z6fR93rg%gc@=09c`sW)AQ-vH5N2=;SoN_Wl=6GxRM7C`bhZvq{RCh}wj4qyeCF#)V z^Onf08KzgbW;nXh*L@mmTVy!`k2F?V8PZFDqhc!6U|%0#?0Ma@?K$ z*1|aLJo6z4AY);^e)!f?OVqUi&{UAW5$$z08PhSN_A%Dr?5!)dn^h0t?nG6GwLu47 zUDgHcknB9Ob{H10--zC!{4~f=*;xcX_&(8kBbwk+Q4MFOe|=f>^6X82zkggo1?tc< zckgZa8U_^EyZB4313Bx?^>js+awOGsx6|Vc?6`sX?R4}50wP3!i*33;?gckqHNdhN zN9QRth#G55yl$No5d@ObQwy(O^$s05eJhRhuwL$l*|5Z|H1;I=)>-H~7`0OR=uAqp z@@dh)^_AV{Ko)Wv#i^AMGHVzh%NU1T=@f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)1{H|x*h{L_M`WGIy@#*9BM9G#v@II0)-rDkxmN^O48}NJ&I(6LP0W|Wec$MwI$Rm|bSzNB83-z|%5yC3RGX1+f)p<2*;W-{)B zv(Y?w=w8|o7J0|Ijni0l)!y}MiR+6ncUroSXY`*PoU{8EFYW%&-k$HjBN5kNF847# zS4nYl{Dh^8^yZ{MLY$L^wW#;eV08pmOCpM|K)u^q>Vd*_AB5AHCM(i2Lh(Bh+9`!hPk*iTu{*8U7jSoY@iof|hxj0@I+cWe9t6CWF!WM@gn`ZXoaaN@OeXKHf} zAvI1g^kn~qF5Xc1x}t#RGt#PISUemTW?iu8oNHw4vUO_Cfp&GZ_$TU>FIXFI6_gMQ znQlRegPE-G{_a^%=4k3Vy@;}A3HLSK(lymITW>Zn27B>k@cBE~n7*j?WB6C&jqByv zNeWs`^n?ApKF$r^#fdOC0wW`Rhk=5!j*9m2hutTc348TzG7_jnO4GrY>emk?xE;`7 z-NRZ5Uv*w5z4a}y)eg$MCw!3bOSgZ5L}_tQC4H@iDZigD>#CV9 z*S!&rReeb)k@zgW`L0ZTF*Me*wfE5cd-1ggJ+18cwZ6352KFJVZKct-iR|HpOrz9C z)BK*_9*3_w)zjebv135goc+`wXiai~;NIL=`G}B_eW^*996#1!Sx*+z1Vb*`J>!Pc z=Z+-(HaZkS&#AAc!W9cXqcDB1>< zLP_s$&7G{K$%k#DBckT)@?<= z5feQGTyY@zchB?807wQ7OY0GE#ZBPfVAXawmGo;BFx(MFRk) zD4>)ISBh0&m6q+0Oj;DwgHHFYD*}az72vEEN9dm-jFzZqhVC-(ZHqayqzkkx3xvUt zP++px-=H2OQN016zQnZjRUfJu!U_L{|#ibzNt~Omrws!@3P!k0O z Date: Thu, 28 May 2026 20:54:05 +0200 Subject: [PATCH 14/44] refactor: rename `CliExtensibleRegistry` to `ExtensibleRegistry` for clarity and consistency --- .../{CliExtensibleRegistry.java => ExtensibleRegistry.java} | 4 ++-- .../java/com/dfsek/terra/registry/master/ConfigRegistry.java | 4 ++-- .../com/dfsek/terra/registry/master/MetaConfigRegistry.java | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) rename common/implementation/base/src/main/java/com/dfsek/terra/registry/{CliExtensibleRegistry.java => ExtensibleRegistry.java} (96%) diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/CliExtensibleRegistry.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/ExtensibleRegistry.java similarity index 96% rename from common/implementation/base/src/main/java/com/dfsek/terra/registry/CliExtensibleRegistry.java rename to common/implementation/base/src/main/java/com/dfsek/terra/registry/ExtensibleRegistry.java index 032e11a1a..f1314c617 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/registry/CliExtensibleRegistry.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/ExtensibleRegistry.java @@ -28,7 +28,7 @@ import java.util.stream.Stream; *
* These system properties are formatted like UNIX-style paths, with each path separated by a colon (':') character. */ -public interface CliExtensibleRegistry { +public interface ExtensibleRegistry { /** * Get a lowercase search path name for this registry that will get plugged into *
@@ -63,7 +63,7 @@ public interface CliExtensibleRegistry { return Stream.concat( searchPath .filter(Files::isDirectory) - .flatMap(CliExtensibleRegistry::listDirectory), + .flatMap(ExtensibleRegistry::listDirectory), extraPath ) .filter(this::validatePathIsMember); diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java index 831188299..234c2f1b0 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java @@ -29,14 +29,14 @@ import com.dfsek.terra.api.Platform; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.util.reflection.TypeKey; import com.dfsek.terra.config.pack.ConfigPackImpl; -import com.dfsek.terra.registry.CliExtensibleRegistry; +import com.dfsek.terra.registry.ExtensibleRegistry; import com.dfsek.terra.registry.OpenRegistryImpl; /** * Class to hold config packs */ -public class ConfigRegistry extends OpenRegistryImpl implements CliExtensibleRegistry { +public class ConfigRegistry extends OpenRegistryImpl implements ExtensibleRegistry { public ConfigRegistry() { super(TypeKey.of(ConfigPack.class)); diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java index 9adeb0c71..f9e05cb42 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java @@ -28,7 +28,7 @@ import com.dfsek.terra.api.Platform; import com.dfsek.terra.api.config.MetaPack; import com.dfsek.terra.api.util.reflection.TypeKey; import com.dfsek.terra.config.pack.MetaPackImpl; -import com.dfsek.terra.registry.CliExtensibleRegistry; +import com.dfsek.terra.registry.ExtensibleRegistry; import com.dfsek.terra.registry.OpenRegistryImpl; import com.dfsek.terra.registry.master.ConfigRegistry.PackLoadFailuresException; @@ -36,7 +36,7 @@ import com.dfsek.terra.registry.master.ConfigRegistry.PackLoadFailuresException; /** * Class to hold config packs */ -public class MetaConfigRegistry extends OpenRegistryImpl implements CliExtensibleRegistry { +public class MetaConfigRegistry extends OpenRegistryImpl implements ExtensibleRegistry { public MetaConfigRegistry() { super(TypeKey.of(MetaPack.class)); From 8f1a53fc2ac2fc4c79391cf314f3d9da4cdf7957 Mon Sep 17 00:00:00 2001 From: Christian Bergschneider Date: Thu, 28 May 2026 20:57:17 +0200 Subject: [PATCH 15/44] refactor: move validatePathIsMember logic to NIO files API --- .../java/com/dfsek/terra/registry/master/ConfigRegistry.java | 3 +-- .../com/dfsek/terra/registry/master/MetaConfigRegistry.java | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java index 234c2f1b0..08343d59f 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java @@ -68,8 +68,7 @@ public class ConfigRegistry extends OpenRegistryImpl implements Exte @Override public boolean validatePathIsMember(Path path) { - var file = path.toFile(); - return file.isDirectory() || file.getName().endsWith(".zip"); + return Files.isDirectory(path)|| path.getFileName().endsWith(".zip"); } public static class PackLoadFailuresException extends Exception { diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java index f9e05cb42..65a416400 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java @@ -68,7 +68,6 @@ public class MetaConfigRegistry extends OpenRegistryImpl implements Ex @Override public boolean validatePathIsMember(Path path) { - var file = path.toFile(); - return file.isDirectory() || file.getName().endsWith(".zip"); + return Files.isDirectory(path) || path.getFileName().endsWith(".zip"); } } From 47b17b1e0f49783945564277ac5d26743397e2d5 Mon Sep 17 00:00:00 2001 From: Christian Bergschneider Date: Thu, 28 May 2026 20:57:51 +0200 Subject: [PATCH 16/44] refactor!: standardize property names to use kebab-case in ExtensibleRegistry --- .../java/com/dfsek/terra/registry/ExtensibleRegistry.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/ExtensibleRegistry.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/ExtensibleRegistry.java index f1314c617..0d6a8e3b8 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/registry/ExtensibleRegistry.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/ExtensibleRegistry.java @@ -54,11 +54,11 @@ public interface ExtensibleRegistry { String basePropertyName = "terra.registry." + getRegistryName(); Stream searchPath = Stream.concat( - parseValidPaths(System.getProperty(basePropertyName + ".searchPath")), + parseValidPaths(System.getProperty(basePropertyName + ".search-path")), Stream.of(baseSearchPath) ); - Stream extraPath = parseValidPaths(System.getProperty(basePropertyName + ".extraPath")); + Stream extraPath = parseValidPaths(System.getProperty(basePropertyName + ".extra-path")); return Stream.concat( searchPath From 5d1faf3c00338028ce84dfb3e67ac181dc2fbb87 Mon Sep 17 00:00:00 2001 From: IWareQ Date: Sat, 13 Jun 2026 20:14:42 +0400 Subject: [PATCH 17/44] feat: update mappings to 26.1 & adapt allay update --- buildSrc/src/main/kotlin/Versions.kt | 8 ++++---- platforms/allay/README.md | 2 +- .../java/com/dfsek/terra/allay/AllayPlatform.java | 2 +- .../main/java/com/dfsek/terra/allay/Mapping.java | 11 +++++------ .../com/dfsek/terra/allay/delegate/AllayChunk.java | 4 ++-- .../terra/allay/delegate/AllayProtoChunk.java | 6 +++--- .../terra/allay/delegate/AllayProtoWorld.java | 8 ++++---- .../terra/allay/delegate/AllayServerWorld.java | 8 ++++---- .../terra/allay/delegate/AllayWorldProperties.java | 12 ++++++------ .../allay/generator/AllayGeneratorWrapper.java | 14 +++++++------- 10 files changed, 37 insertions(+), 38 deletions(-) diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index cb593331a..33e26dfea 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -86,13 +86,13 @@ object Versions { } object Allay { - const val api = "0.20.0" + const val api = "0.28.0" const val gson = "2.13.2" - const val mappings = "366baa6" - const val mappingsGenerator = "e957088" + const val mappings = "0c2ac22" + const val mappingsGenerator = "3742321" - const val mcmeta = "c976eb3" + const val mcmeta = "805b8ac" } object Minestom { diff --git a/platforms/allay/README.md b/platforms/allay/README.md index 48ff78847..501ac9520 100644 --- a/platforms/allay/README.md +++ b/platforms/allay/README.md @@ -2,7 +2,7 @@ ## Resource files -Current mapping version: je 1.21.11 to be 1.21.111 +Current mapping version: JE 26.1.2 to BE 26.1 - `mapping/biomes.json` and `mapping/items.json` are obtained from [GeyserMC/mappings](https://github.com/GeyserMC/mappings). - `mapping/blocks.json` is obtained from [GeyserMC/mappings-generator](https://github.com/GeyserMC/mappings-generator) (path: `https://github.com/GeyserMC/mappings-generator/blob/master/generator_blocks.json`). diff --git a/platforms/allay/src/main/java/com/dfsek/terra/allay/AllayPlatform.java b/platforms/allay/src/main/java/com/dfsek/terra/allay/AllayPlatform.java index f9cb5831f..304d9d1d7 100644 --- a/platforms/allay/src/main/java/com/dfsek/terra/allay/AllayPlatform.java +++ b/platforms/allay/src/main/java/com/dfsek/terra/allay/AllayPlatform.java @@ -47,7 +47,7 @@ public class AllayPlatform extends AbstractPlatform { var dimension = wrapper.getAllayWorldGenerator().getDimension(); TerraAllayPlugin.instance.getPluginLogger().info( "Replaced pack in chunk generator for world {}", - dimension.getWorld().getWorldData().getDisplayName() + ":" + dimension.getDimensionInfo().dimensionId() + dimension.getWorld().getWorldData().getDisplayName() + ":" + dimension.getDimensionType().getIdentifier() ); }); }); diff --git a/platforms/allay/src/main/java/com/dfsek/terra/allay/Mapping.java b/platforms/allay/src/main/java/com/dfsek/terra/allay/Mapping.java index 5c17830c5..d389c1d04 100644 --- a/platforms/allay/src/main/java/com/dfsek/terra/allay/Mapping.java +++ b/platforms/allay/src/main/java/com/dfsek/terra/allay/Mapping.java @@ -82,12 +82,11 @@ public final class Mapping { } public static String dimensionIdBeToJe(String beDimensionId) { - return switch(beDimensionId) { - case "overworld" -> "minecraft:overworld"; - case "nether" -> "minecraft:the_nether"; - case "the_end" -> "minecraft:the_end"; - default -> beDimensionId; - }; + if(beDimensionId.equals("minecraft:nether")) { + return "minecraft:the_nether"; + } + + return beDimensionId; } public static Map getJeBlockDefaultProperties(String jeBlockIdentifier) { diff --git a/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayChunk.java b/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayChunk.java index 8fe456bac..a87bf6c3a 100644 --- a/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayChunk.java +++ b/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayChunk.java @@ -21,10 +21,10 @@ public record AllayChunk(ServerWorld world, Chunk allayChunk) implements com.dfs @Override public void setBlock(int x, int y, int z, BlockState data, boolean physics) { - var dimensionInfo = allayChunk.getDimensionInfo(); + var dimensionType = allayChunk.getDimensionType(); if(x < 0 || x > 15 || z < 0 || z > 15 || - y < dimensionInfo.minHeight() || y > dimensionInfo.maxHeight()) { + y < dimensionType.getMinHeight() || y > dimensionType.getMaxHeight()) { return; } diff --git a/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayProtoChunk.java b/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayProtoChunk.java index 164d316ff..62762ee5a 100644 --- a/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayProtoChunk.java +++ b/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayProtoChunk.java @@ -21,15 +21,15 @@ public record AllayProtoChunk(UnsafeChunk allayChunk) implements ProtoChunk { @Override public int getMaxHeight() { - return allayChunk.getDimensionInfo().maxHeight(); + return allayChunk.getDimensionType().getMaxHeight(); } @Override public void setBlock(int x, int y, int z, @NotNull BlockState blockState) { - var dimensionInfo = allayChunk.getDimensionInfo(); + var dimensionType = allayChunk.getDimensionType(); if(x < 0 || x > 15 || z < 0 || z > 15 || - y < dimensionInfo.minHeight() || y > dimensionInfo.maxHeight()) { + y < dimensionType.getMinHeight() || y > dimensionType.getMaxHeight()) { return; } diff --git a/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayProtoWorld.java b/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayProtoWorld.java index 01e38c31c..f47a30515 100644 --- a/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayProtoWorld.java +++ b/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayProtoWorld.java @@ -31,11 +31,11 @@ public record AllayProtoWorld(AllayServerWorld allayServerWorld, OtherChunkAcces var currentChunk = context.getCurrentChunk(); var currentChunkX = currentChunk.getX(); var currentChunkZ = currentChunk.getZ(); - var dimInfo = currentChunk.getDimensionInfo(); + var dimensionType = currentChunk.getDimensionType(); if(x >= currentChunkX * 16 && x < currentChunkX * 16 + 16 && z >= currentChunkZ * 16 && z < currentChunkZ * 16 + 16 && - y >= dimInfo.minHeight() && y <= dimInfo.maxHeight()) { + y >= dimensionType.getMinHeight() && y <= dimensionType.getMaxHeight()) { return currentChunk.getBlockEntity(x & 15, y, z & 15); } else { var chunk = context.getChunkSource().getChunk(x >> 4, z >> 4); @@ -60,8 +60,8 @@ public record AllayProtoWorld(AllayServerWorld allayServerWorld, OtherChunkAcces @Override public void setBlockState(int x, int y, int z, BlockState data, boolean physics) { - var dimensionInfo = allayServerWorld.allayDimension().getDimensionInfo(); - if(y < dimensionInfo.minHeight() || y > dimensionInfo.maxHeight()) { + var dimensionType = allayServerWorld.allayDimension().getDimensionType(); + if(y < dimensionType.getMinHeight() || y > dimensionType.getMaxHeight()) { return; } diff --git a/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayServerWorld.java b/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayServerWorld.java index 7239a2b70..9579ca332 100644 --- a/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayServerWorld.java +++ b/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayServerWorld.java @@ -27,8 +27,8 @@ public record AllayServerWorld(AllayGeneratorWrapper allayGeneratorWrapper, Dime @Override public void setBlockState(int x, int y, int z, BlockState data, boolean physics) { - var dimensionInfo = allayDimension.getDimensionInfo(); - if(y < dimensionInfo.minHeight() || y > dimensionInfo.maxHeight()) { + var dimensionType = allayDimension.getDimensionType(); + if(y < dimensionType.getMinHeight() || y > dimensionType.getMaxHeight()) { return; } @@ -74,12 +74,12 @@ public record AllayServerWorld(AllayGeneratorWrapper allayGeneratorWrapper, Dime @Override public int getMaxHeight() { - return allayDimension.getDimensionInfo().maxHeight(); + return allayDimension.getDimensionType().getMaxHeight(); } @Override public int getMinHeight() { - return allayDimension.getDimensionInfo().minHeight(); + return allayDimension.getDimensionType().getMinHeight(); } @Override diff --git a/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayWorldProperties.java b/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayWorldProperties.java index 221f6b67b..d57d4ac3a 100644 --- a/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayWorldProperties.java +++ b/platforms/allay/src/main/java/com/dfsek/terra/allay/delegate/AllayWorldProperties.java @@ -1,6 +1,6 @@ package com.dfsek.terra.allay.delegate; -import org.allaymc.api.world.data.DimensionInfo; +import org.allaymc.api.world.dimension.DimensionType; import com.dfsek.terra.api.world.info.WorldProperties; @@ -12,12 +12,12 @@ public class AllayWorldProperties implements WorldProperties { private final Object fakeHandle; private final long seed; - private final DimensionInfo dimensionInfo; + private final DimensionType dimensionType; - public AllayWorldProperties(long seed, DimensionInfo dimensionInfo) { + public AllayWorldProperties(long seed, DimensionType dimensionType) { this.fakeHandle = new Object(); this.seed = seed; - this.dimensionInfo = dimensionInfo; + this.dimensionType = dimensionType; } @Override @@ -27,12 +27,12 @@ public class AllayWorldProperties implements WorldProperties { @Override public int getMaxHeight() { - return dimensionInfo.maxHeight(); + return dimensionType.getMaxHeight(); } @Override public int getMinHeight() { - return dimensionInfo.minHeight(); + return dimensionType.getMinHeight(); } @Override diff --git a/platforms/allay/src/main/java/com/dfsek/terra/allay/generator/AllayGeneratorWrapper.java b/platforms/allay/src/main/java/com/dfsek/terra/allay/generator/AllayGeneratorWrapper.java index 9ffc029f7..750ab6354 100644 --- a/platforms/allay/src/main/java/com/dfsek/terra/allay/generator/AllayGeneratorWrapper.java +++ b/platforms/allay/src/main/java/com/dfsek/terra/allay/generator/AllayGeneratorWrapper.java @@ -4,7 +4,7 @@ import com.google.common.base.Preconditions; import org.allaymc.api.utils.AllayStringUtils; import org.allaymc.api.world.biome.BiomeType; import org.allaymc.api.world.chunk.UnsafeChunk; -import org.allaymc.api.world.data.DimensionInfo; +import org.allaymc.api.world.dimension.DimensionType; import org.allaymc.api.world.generator.WorldGenerator; import org.allaymc.api.world.generator.context.NoiseContext; import org.allaymc.api.world.generator.context.PopulateContext; @@ -55,11 +55,11 @@ public class AllayGeneratorWrapper implements GeneratorWrapper { .populators(new AllayPopulator()) .onDimensionSet(dimension -> { this.allayServerWorld = new AllayServerWorld(this, dimension); - this.worldProperties = new AllayWorldProperties(this.seed, dimension.getDimensionInfo()); + this.worldProperties = new AllayWorldProperties(this.seed, dimension.getDimensionType()); var metaPackName = options.get(OPTION_META_PACK_NAME); if(metaPackName != null) { - setConfigPack(getConfigPackByMeta(metaPackName, dimension.getDimensionInfo())); + setConfigPack(getConfigPackByMeta(metaPackName, dimension.getDimensionType())); return; } @@ -94,13 +94,13 @@ public class AllayGeneratorWrapper implements GeneratorWrapper { .orElseThrow(() -> new IllegalArgumentException("Cant find terra config pack named " + packId)); } - protected static ConfigPack getConfigPackByMeta(String metaPackId, DimensionInfo dimensionInfo) { + protected static ConfigPack getConfigPackByMeta(String metaPackId, DimensionType dimensionType) { return TerraAllayPlugin.platform .getMetaConfigRegistry() .getByID(metaPackId) .orElseThrow(() -> new IllegalArgumentException("Cant find terra meta pack named " + metaPackId)) .packs() - .get(Mapping.dimensionIdBeToJe(dimensionInfo.toString())); + .get(Mapping.dimensionIdBeToJe(dimensionType.getIdentifier().toString())); } protected static ChunkGenerator createGenerator(ConfigPack configPack) { @@ -148,8 +148,8 @@ public class AllayGeneratorWrapper implements GeneratorWrapper { worldProperties, biomeProvider, chunkX, chunkZ ); - int minHeight = context.getDimensionInfo().minHeight(); - int maxHeight = context.getDimensionInfo().maxHeight(); + int minHeight = context.getDimensionType().getMinHeight(); + int maxHeight = context.getDimensionType().getMaxHeight(); for(int x = 0; x < 16; x++) { for(int y = minHeight; y < maxHeight; y++) { for(int z = 0; z < 16; z++) { From c373be489639b1a8b65cbdaaadcb363d135bd095 Mon Sep 17 00:00:00 2001 From: ArikSquad <75741608+ArikSquad@users.noreply.github.com> Date: Tue, 23 Jun 2026 20:30:52 +0300 Subject: [PATCH 18/44] feat: 26.2 nothing changed for this project --- .../src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java index bb89ec868..e5e094bce 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java @@ -9,7 +9,7 @@ import com.dfsek.terra.bukkit.util.VersionUtil; public interface NMSInitializer { - List SUPPORTED_VERSIONS = List.of("v26.1.2"); + List SUPPORTED_VERSIONS = List.of("v26.1.2", "v26.2"); String MINECRAFT_VERSION = VersionUtil.getMinecraftVersionInfo().toString(); String TERRA_PACKAGE = NMSInitializer.class.getPackageName(); From 47d4307761a382eb37771fe6e0a6a3dfb07fa2e0 Mon Sep 17 00:00:00 2001 From: AriDev <75741608+ArikSquad@users.noreply.github.com> Date: Mon, 13 Jul 2026 23:44:31 +0300 Subject: [PATCH 19/44] chore: update cloud-minecraft to 2.0.0-beta.17 --- buildSrc/src/main/kotlin/Versions.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index 3add39691..489fd63dc 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -69,7 +69,7 @@ object Versions { const val paperDevBundle = paperBuild const val runPaper = "3.0.2" const val paperWeight = "2.0.0-beta.21" - const val cloud = "2.0.0-beta.15" + const val cloud = "2.0.0-beta.17" const val multiverse = "5.3.0" } From f4811235710743ae84630cbba972476fec721164 Mon Sep 17 00:00:00 2001 From: Sybsuper Date: Sat, 16 May 2026 01:58:49 +0200 Subject: [PATCH 20/44] feat: add additional data support for particles on Minestom platform (cherry picked from commit fdf362acd296e2f6c52aaa42f910ff820dae1868) --- .../config/BiomeParticleConfigTemplate.java | 36 ++++++++++++++++--- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeParticleConfigTemplate.java b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeParticleConfigTemplate.java index 24acb99e9..cf66e61a0 100644 --- a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeParticleConfigTemplate.java +++ b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeParticleConfigTemplate.java @@ -3,11 +3,15 @@ package com.dfsek.terra.minestom.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.kyori.adventure.nbt.CompoundBinaryTag; +import net.minestom.server.adventure.MinestomAdventure; +import net.minestom.server.codec.Transcoder; import net.minestom.server.particle.Particle; import net.minestom.server.world.attribute.AmbientParticle; -import net.minestom.server.world.biome.BiomeEffects; import org.slf4j.LoggerFactory; +import java.io.IOException; + public class BiomeParticleConfigTemplate implements ObjectTemplate { @Value("particle") @@ -25,11 +29,13 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate 1) { - LoggerFactory.getLogger(BiomeParticleConfigTemplate.class).warn("Particle {} has additional data, particle will be ignored.", - particle); - return null; + int start = particle.indexOf("{"); + String dataString = particle.substring(start); + parsedParticle = parseAdditionalParticleData(dataString, key); + if (parsedParticle == null) return null; } return new AmbientParticle( @@ -37,4 +43,24 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate Date: Mon, 28 Sep 2026 19:45:31 +0300 Subject: [PATCH 21/44] feat: 26.3 and entity snbt --- buildSrc/src/main/kotlin/Versions.kt | 5 +- platforms/bukkit/build.gradle.kts | 4 +- .../dfsek/terra/bukkit/NMSInitializer.java | 17 ++- .../terra/bukkit/util/BukkitNMSAccess.java | 16 +++ .../dfsek/terra/bukkit/util/BukkitUtils.java | 60 ++++++---- .../terra/bukkit/world/BukkitProtoWorld.java | 3 +- .../terra/bukkit/world/BukkitServerWorld.java | 5 +- .../world/block/state/BukkitMobSpawner.java | 8 +- .../bukkit/world/entity/BukkitEntityData.java | 16 +++ .../entity/BukkitEntityTypeExtended.java | 34 ++++++ platforms/bukkit/nms/26.1/build.gradle.kts | 13 +++ .../terra/bukkit/nms/v26_1/Bindings.java | 72 ++++++++++++ .../terra/bukkit/nms/v26_1/NMSPlatform.java | 11 ++ platforms/bukkit/nms/26.3/build.gradle.kts | 13 +++ .../terra/bukkit/nms/v26_3/Bindings.java | 80 +++++++++++++ .../terra/bukkit/nms/v26_3/NMSPlatform.java | 11 ++ platforms/bukkit/nms/build.gradle.kts | 14 ++- platforms/bukkit/nms/common/build.gradle.kts | 17 +++ .../terra/bukkit/nms/AwfulBukkitHacks.java | 107 +++++++++++++++++- .../com/dfsek/terra/bukkit/nms/NMSAddon.java | 0 .../dfsek/terra/bukkit/nms/NMSBiomeInfo.java | 0 .../terra/bukkit/nms/NMSBiomeInjector.java | 96 ++++------------ .../terra/bukkit/nms/NMSBiomeProvider.java | 0 .../bukkit/nms/NMSChunkGeneratorDelegate.java | 43 +------ .../terra/bukkit/nms/NMSInjectListener.java | 7 +- .../terra/bukkit/nms/NMSPlatformBase.java} | 31 ++++- .../bukkit/nms/NMSStructureBeardifier.java | 52 +++++++++ .../terra/bukkit/nms/NMSVersionBindings.java | 33 ++++++ .../terra/bukkit/nms/NMSWorldProperties.java | 0 .../dfsek/terra/bukkit/nms/Reflection.java | 0 .../terra/bukkit/nms/RegistryFetcher.java | 0 .../config/BiomeAdditionsSoundTemplate.java | 0 .../nms/config/BiomeMoodSoundTemplate.java | 0 .../config/BiomeParticleConfigTemplate.java | 71 ++++++++++++ .../bukkit/nms/config/EntityTypeTemplate.java | 0 .../bukkit/nms/config/MusicSoundTemplate.java | 0 .../bukkit/nms/config/SoundEventTemplate.java | 0 .../bukkit/nms/config/SpawnCostConfig.java | 0 .../bukkit/nms/config/SpawnEntryConfig.java | 13 ++- .../nms/config/SpawnSettingsTemplate.java | 23 ++-- .../bukkit/nms/config/SpawnTypeConfig.java | 0 .../nms/config/VanillaBiomeProperties.java | 0 .../nms/config/VillagerTypeTemplate.java | 0 .../config/BiomeParticleConfigTemplate.java | 38 ------- 44 files changed, 706 insertions(+), 207 deletions(-) create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitNMSAccess.java create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/entity/BukkitEntityData.java create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/entity/BukkitEntityTypeExtended.java create mode 100644 platforms/bukkit/nms/26.1/build.gradle.kts create mode 100644 platforms/bukkit/nms/26.1/src/main/java/com/dfsek/terra/bukkit/nms/v26_1/Bindings.java create mode 100644 platforms/bukkit/nms/26.1/src/main/java/com/dfsek/terra/bukkit/nms/v26_1/NMSPlatform.java create mode 100644 platforms/bukkit/nms/26.3/build.gradle.kts create mode 100644 platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/Bindings.java create mode 100644 platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/NMSPlatform.java create mode 100644 platforms/bukkit/nms/common/build.gradle.kts rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java (63%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/NMSAddon.java (100%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInfo.java (100%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java (58%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeProvider.java (100%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java (71%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/NMSInjectListener.java (92%) rename platforms/bukkit/nms/{src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java => common/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatformBase.java} (80%) create mode 100644 platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSStructureBeardifier.java create mode 100644 platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSVersionBindings.java rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/NMSWorldProperties.java (100%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java (100%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/RegistryFetcher.java (100%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java (100%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeMoodSoundTemplate.java (100%) create mode 100644 platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/config/EntityTypeTemplate.java (100%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/config/MusicSoundTemplate.java (100%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java (100%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnCostConfig.java (100%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnEntryConfig.java (79%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnSettingsTemplate.java (53%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnTypeConfig.java (100%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java (100%) rename platforms/bukkit/nms/{ => common}/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java (100%) delete mode 100644 platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index 489fd63dc..4f34358ed 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -12,7 +12,7 @@ object Versions { const val strata = "1.3.2" const val seismic = "2.5.7" - const val cloud = "2.0.0" + const val cloud = "2.1.0" const val caffeine = "3.2.2" @@ -67,9 +67,10 @@ object Versions { const val paperLib = "1.0.8" const val reflectionRemapper = "0.1.3" const val paperDevBundle = paperBuild + const val paperDevBundle26_3 = "26.3.build.49-alpha" const val runPaper = "3.0.2" const val paperWeight = "2.0.0-beta.21" - const val cloud = "2.0.0-beta.17" + const val cloud = "2.0.1" const val multiverse = "5.3.0" } diff --git a/platforms/bukkit/build.gradle.kts b/platforms/bukkit/build.gradle.kts index 377eaaf95..8de3d7228 100644 --- a/platforms/bukkit/build.gradle.kts +++ b/platforms/bukkit/build.gradle.kts @@ -8,7 +8,9 @@ dependencies { paperweight.paperDevBundle(Versions.Bukkit.paperDevBundle) shaded(project(":platforms:bukkit:common")) - shaded(project(":platforms:bukkit:nms")) + shaded(project(path = ":platforms:bukkit:nms:common", configuration = "runtimeElements")) + shaded(project(path = ":platforms:bukkit:nms:26.1", configuration = "runtimeElements")) + shaded(project(path = ":platforms:bukkit:nms:26.3", configuration = "runtimeElements")) shaded("xyz.jpenilla", "reflection-remapper", Versions.Bukkit.reflectionRemapper) } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java index e5e094bce..6bb64ca3a 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java @@ -6,10 +6,12 @@ import org.slf4j.LoggerFactory; import java.util.List; import com.dfsek.terra.bukkit.util.VersionUtil; +import com.dfsek.terra.bukkit.util.BukkitNMSAccess; +import com.dfsek.terra.bukkit.util.BukkitUtils; public interface NMSInitializer { - List SUPPORTED_VERSIONS = List.of("v26.1.2", "v26.2"); + List SUPPORTED_VERSIONS = List.of("v26.1.2", "v26.2", "v26.3"); String MINECRAFT_VERSION = VersionUtil.getMinecraftVersionInfo().toString(); String TERRA_PACKAGE = NMSInitializer.class.getPackageName(); @@ -44,10 +46,19 @@ public interface NMSInitializer { private static PlatformImpl constructPlatform(TerraBukkitPlugin plugin) { try { - Class platformClass = Class.forName(TERRA_PACKAGE + ".nms.NMSPlatform"); - return (PlatformImpl) platformClass + String bindingsVersion = switch(MINECRAFT_VERSION) { + case "v26.3" -> "v26_3"; + case "v26.1.2", "v26.2" -> "v26_1"; + default -> "v26_1"; + }; + Class platformClass = Class.forName(TERRA_PACKAGE + ".nms." + bindingsVersion + ".NMSPlatform"); + PlatformImpl platform = (PlatformImpl) platformClass .getConstructor(TerraBukkitPlugin.class) .newInstance(plugin); + if(platform instanceof BukkitNMSAccess nmsAccess) { + BukkitUtils.setNMSAccess(nmsAccess); + } + return platform; } catch(ReflectiveOperationException e) { throw new RuntimeException("Error initializing NMS bindings. Report this to Terra.", e); } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitNMSAccess.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitNMSAccess.java new file mode 100644 index 000000000..b9a88bf50 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitNMSAccess.java @@ -0,0 +1,16 @@ +package com.dfsek.terra.bukkit.util; + +import org.bukkit.Location; +import org.bukkit.block.CreatureSpawner; + +import com.dfsek.terra.api.entity.EntityType; +import com.dfsek.terra.api.entity.EntityTypeExtended; + + +public interface BukkitNMSAccess { + EntityType getEntityType(String data); + + org.bukkit.entity.Entity spawnEntity(Object target, Location location, EntityType type); + + void setSpawnerEntity(CreatureSpawner spawner, EntityTypeExtended type); +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitUtils.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitUtils.java index d2c80f5ff..1a450e74f 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitUtils.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitUtils.java @@ -1,40 +1,62 @@ package com.dfsek.terra.bukkit.util; import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.block.CreatureSpawner; import org.bukkit.block.data.BlockData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Locale; import com.dfsek.terra.api.entity.EntityType; +import com.dfsek.terra.api.entity.EntityTypeExtended; import com.dfsek.terra.bukkit.world.entity.BukkitEntityType; public class BukkitUtils { - private static final Logger logger = LoggerFactory.getLogger(BukkitUtils.class); + private static volatile BukkitNMSAccess nmsAccess; public static boolean isLiquid(BlockData blockState) { Material material = blockState.getMaterial(); return material == Material.WATER || material == Material.LAVA; } - public static EntityType getEntityType(String id) { - if(!id.startsWith("minecraft:")) throw new IllegalArgumentException("Invalid entity identifier " + id); - String entityID = id.toUpperCase(Locale.ROOT).substring(10); + public static void setNMSAccess(BukkitNMSAccess access) { + nmsAccess = access; + } - // TODO: remove this - // the default end seems to use this, this should be removed otherwise - // or replaced by a proper entity & NBT loader - if (entityID.contains("END_CRYSTAL")) { - entityID = "END_CRYSTAL"; + public static EntityType getEntityType(String id) { + BukkitNMSAccess access = nmsAccess; + return access == null ? getBukkitEntityType(id) : access.getEntityType(id); + } + + public static org.bukkit.entity.Entity spawnEntity(Object region, org.bukkit.Location location, EntityType entityType) { + if(entityType instanceof EntityTypeExtended) { + BukkitNMSAccess access = nmsAccess; + if(access == null) throw new IllegalStateException("Entity NBT loading requires Terra's NMS bindings"); + return access.spawnEntity(region, location, entityType); } - return new BukkitEntityType(switch(entityID) { - case "END_CRYSTAL" -> org.bukkit.entity.EntityType.END_CRYSTAL; - case "ENDER_CRYSTAL" -> throw new IllegalArgumentException( - "Invalid entity identifier " + id); // make sure this issue can't happen the other way around. - default -> org.bukkit.entity.EntityType.valueOf(entityID); - }); + org.bukkit.entity.EntityType bukkitType = ((BukkitEntityType) entityType).getHandle(); + if(region instanceof org.bukkit.generator.LimitedRegion limitedRegion) { + return limitedRegion.spawnEntity(location, bukkitType); + } + return ((org.bukkit.World) region).spawnEntity(location, bukkitType); + } + + public static void setSpawnerEntity(CreatureSpawner spawner, EntityTypeExtended type) { + BukkitNMSAccess access = nmsAccess; + if(access == null) throw new IllegalStateException("Entity NBT loading requires Terra's NMS bindings"); + access.setSpawnerEntity(spawner, type); + } + + private static EntityType getBukkitEntityType(String data) { + int nbtStart = data.indexOf('{'); + if(nbtStart >= 0) { + throw new IllegalArgumentException("Entity NBT loading requires Terra's NMS bindings: " + data); + } + + NamespacedKey key = NamespacedKey.fromString(data); + org.bukkit.entity.EntityType type = key == null ? null : Registry.ENTITY_TYPE.get(key); + if(type == null) throw new IllegalArgumentException("Invalid entity identifier " + data); + return new BukkitEntityType(type); } } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitProtoWorld.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitProtoWorld.java index 3de237bb3..67fbf1ee2 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitProtoWorld.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitProtoWorld.java @@ -24,7 +24,6 @@ import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper; import com.dfsek.terra.bukkit.util.BukkitUtils; import com.dfsek.terra.bukkit.world.block.data.BukkitBlockState; import com.dfsek.terra.bukkit.world.block.state.BukkitBlockEntity; -import com.dfsek.terra.bukkit.world.entity.BukkitEntityType; public class BukkitProtoWorld implements ProtoWorld { @@ -89,7 +88,7 @@ public class BukkitProtoWorld implements ProtoWorld { @Override public Entity spawnEntity(double x, double y, double z, EntityType entityType) { return access((int) x, (int) y, (int) z, () -> new BukkitEntity( - delegate.spawnEntity(new Location(delegate.getWorld(), x, y, z), ((BukkitEntityType) entityType).getHandle()))).orElse( + BukkitUtils.spawnEntity(delegate, new Location(delegate.getWorld(), x, y, z), entityType))).orElse( null); } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitServerWorld.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitServerWorld.java index 9ddf8ae87..cc3693734 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitServerWorld.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitServerWorld.java @@ -30,8 +30,8 @@ import com.dfsek.terra.api.world.chunk.Chunk; import com.dfsek.terra.api.world.chunk.generation.ChunkGenerator; import com.dfsek.terra.bukkit.BukkitEntity; import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper; +import com.dfsek.terra.bukkit.util.BukkitUtils; import com.dfsek.terra.bukkit.world.block.state.BukkitBlockEntity; -import com.dfsek.terra.bukkit.world.entity.BukkitEntityType; public class BukkitServerWorld implements ServerWorld { @@ -43,8 +43,7 @@ public class BukkitServerWorld implements ServerWorld { @Override public Entity spawnEntity(double x, double y, double z, EntityType entityType) { - return new BukkitEntity( - delegate.spawnEntity(new Location(delegate, x, y, z), ((BukkitEntityType) entityType).getHandle())); + return new BukkitEntity(BukkitUtils.spawnEntity(delegate, new Location(delegate, x, y, z), entityType)); } @Override diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/block/state/BukkitMobSpawner.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/block/state/BukkitMobSpawner.java index dc9d1ecb6..9302a6178 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/block/state/BukkitMobSpawner.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/block/state/BukkitMobSpawner.java @@ -23,6 +23,7 @@ import org.jetbrains.annotations.NotNull; import com.dfsek.terra.api.block.entity.MobSpawner; import com.dfsek.terra.api.block.entity.SerialState; import com.dfsek.terra.api.entity.EntityType; +import com.dfsek.terra.api.entity.EntityTypeExtended; import com.dfsek.terra.bukkit.util.BukkitUtils; import com.dfsek.terra.bukkit.world.entity.BukkitEntityType; @@ -39,7 +40,12 @@ public class BukkitMobSpawner extends BukkitBlockEntity implements MobSpawner { @Override public void setSpawnedType(@NotNull EntityType creatureType) { - ((CreatureSpawner) getHandle()).setSpawnedType(((BukkitEntityType) creatureType).getHandle()); + CreatureSpawner spawner = (CreatureSpawner) getHandle(); + if(creatureType instanceof EntityTypeExtended extended) { + BukkitUtils.setSpawnerEntity(spawner, extended); + } else { + spawner.setSpawnedType(((BukkitEntityType) creatureType).getHandle()); + } } @Override diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/entity/BukkitEntityData.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/entity/BukkitEntityData.java new file mode 100644 index 000000000..40de74825 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/entity/BukkitEntityData.java @@ -0,0 +1,16 @@ +package com.dfsek.terra.bukkit.world.entity; + +import com.dfsek.terra.api.data.ExtendedData; + + +public record BukkitEntityData(String snbt) implements ExtendedData { + @Override + public Object getHandle() { + return snbt; + } + + @Override + public String toString() { + return snbt; + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/entity/BukkitEntityTypeExtended.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/entity/BukkitEntityTypeExtended.java new file mode 100644 index 000000000..f1ba5a400 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/entity/BukkitEntityTypeExtended.java @@ -0,0 +1,34 @@ +package com.dfsek.terra.bukkit.world.entity; + +import com.dfsek.terra.api.data.ExtendedData; +import com.dfsek.terra.api.entity.EntityType; +import com.dfsek.terra.api.entity.EntityTypeExtended; + + +public final class BukkitEntityTypeExtended extends BukkitEntityType implements EntityTypeExtended { + private final BukkitEntityData data; + + public BukkitEntityTypeExtended(org.bukkit.entity.EntityType delegate, String snbt) { + super(delegate); + this.data = new BukkitEntityData(snbt); + } + + @Override + public ExtendedData getData() { + return data; + } + + @Override + public EntityTypeExtended setData(ExtendedData data) { + Object handle = data.getHandle(); + if(!(handle instanceof String snbt)) { + throw new IllegalArgumentException("Bukkit entity data must contain SNBT text"); + } + return new BukkitEntityTypeExtended(getHandle(), snbt); + } + + @Override + public EntityType getType() { + return new BukkitEntityType(getHandle()); + } +} diff --git a/platforms/bukkit/nms/26.1/build.gradle.kts b/platforms/bukkit/nms/26.1/build.gradle.kts new file mode 100644 index 000000000..d5aa24836 --- /dev/null +++ b/platforms/bukkit/nms/26.1/build.gradle.kts @@ -0,0 +1,13 @@ +plugins { + id("io.papermc.paperweight.userdev") +} + +tasks.withType().configureEach { + options.release = 25 +} + +dependencies { + compileOnly(project(":platforms:bukkit:common")) + compileOnly(project(":platforms:bukkit:nms:common")) + paperweight.paperDevBundle(Versions.Bukkit.paperDevBundle) +} diff --git a/platforms/bukkit/nms/26.1/src/main/java/com/dfsek/terra/bukkit/nms/v26_1/Bindings.java b/platforms/bukkit/nms/26.1/src/main/java/com/dfsek/terra/bukkit/nms/v26_1/Bindings.java new file mode 100644 index 000000000..bb0e5203d --- /dev/null +++ b/platforms/bukkit/nms/26.1/src/main/java/com/dfsek/terra/bukkit/nms/v26_1/Bindings.java @@ -0,0 +1,72 @@ +package com.dfsek.terra.bukkit.nms.v26_1; + +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.level.levelgen.Beardifier; +import net.minecraft.world.level.levelgen.DensityFunction.SinglePointContext; +import net.minecraft.world.level.StructureManager; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.MobSpawnSettings; +import net.minecraft.world.level.biome.MobSpawnSettings.SpawnerData; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.attribute.EnvironmentAttributes; +import net.minecraft.world.attribute.modifier.AttributeModifier; + +import com.dfsek.terra.api.world.biome.generation.BiomeProvider; +import com.dfsek.terra.api.world.chunk.generation.ChunkGenerator; +import com.dfsek.terra.api.world.info.WorldProperties; +import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions; +import com.dfsek.terra.bukkit.nms.NMSStructureBeardifier; +import com.dfsek.terra.bukkit.nms.NMSVersionBindings; +import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties; + + +public final class Bindings implements NMSVersionBindings { + @Override + public void addSpawn(MobSpawnSettings.Builder builder, MobCategory category, EntityType type, int weight, + int minCount, int maxCount) { + builder.addSpawn(category, weight, new SpawnerData(type, minCount, maxCount)); + } + + @Override + public void addSpawnCost(MobSpawnSettings.Builder builder, EntityType type, double mass, double gravity) { + builder.addMobCharge(type, mass, gravity); + } + + @Override + public boolean setCreatureGenerationProbability(MobSpawnSettings.Builder builder, float probability) { + builder.creatureGenerationProbability(probability); + return true; + } + + @Override + public void copyVanillaSpawnSettings(Biome.BiomeBuilder builder, Biome biome) { + builder.mobSpawnSettings(biome.getMobSettings()); + } + + @Override + public void setSpawnSettings(Biome.BiomeBuilder builder, MobSpawnSettings settings) { + builder.mobSpawnSettings(settings); + } + + @Override + public void applyBiomeColorOverrides(Biome.BiomeBuilder builder, VanillaBiomeProperties properties) { + if(properties.getFogColor() != null) { + builder.modifyAttribute(EnvironmentAttributes.FOG_COLOR, AttributeModifier.override(), properties.getFogColor()); + } + if(properties.getWaterFogColor() != null) { + builder.modifyAttribute(EnvironmentAttributes.WATER_FOG_COLOR, AttributeModifier.override(), properties.getWaterFogColor()); + } + if(properties.getSkyColor() != null) { + builder.modifyAttribute(EnvironmentAttributes.SKY_COLOR, AttributeModifier.override(), properties.getSkyColor()); + } + } + + @Override + public void applyStructureBeard(ChunkGenerator generator, StructureManager structures, ChunkAccess chunk, WorldProperties world, + BiomeProvider biomeProvider, PreLoadCompatibilityOptions options) { + Beardifier beardifier = Beardifier.forStructuresInChunk(structures, chunk.getPos()); + NMSStructureBeardifier.apply(generator, chunk, world, biomeProvider, options, + (x, y, z) -> beardifier.compute(new SinglePointContext(x, y, z))); + } +} diff --git a/platforms/bukkit/nms/26.1/src/main/java/com/dfsek/terra/bukkit/nms/v26_1/NMSPlatform.java b/platforms/bukkit/nms/26.1/src/main/java/com/dfsek/terra/bukkit/nms/v26_1/NMSPlatform.java new file mode 100644 index 000000000..753a6cda1 --- /dev/null +++ b/platforms/bukkit/nms/26.1/src/main/java/com/dfsek/terra/bukkit/nms/v26_1/NMSPlatform.java @@ -0,0 +1,11 @@ +package com.dfsek.terra.bukkit.nms.v26_1; + +import com.dfsek.terra.bukkit.TerraBukkitPlugin; +import com.dfsek.terra.bukkit.nms.NMSPlatformBase; + + +public final class NMSPlatform extends NMSPlatformBase { + public NMSPlatform(TerraBukkitPlugin plugin) { + super(plugin, new Bindings()); + } +} diff --git a/platforms/bukkit/nms/26.3/build.gradle.kts b/platforms/bukkit/nms/26.3/build.gradle.kts new file mode 100644 index 000000000..7f91b59a5 --- /dev/null +++ b/platforms/bukkit/nms/26.3/build.gradle.kts @@ -0,0 +1,13 @@ +plugins { + id("io.papermc.paperweight.userdev") +} + +tasks.withType().configureEach { + options.release = 25 +} + +dependencies { + compileOnly(project(":platforms:bukkit:common")) + compileOnly(project(":platforms:bukkit:nms:common")) + paperweight.paperDevBundle(Versions.Bukkit.paperDevBundle26_3) +} diff --git a/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/Bindings.java b/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/Bindings.java new file mode 100644 index 000000000..e1c9e9aa2 --- /dev/null +++ b/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/Bindings.java @@ -0,0 +1,80 @@ +package com.dfsek.terra.bukkit.nms.v26_3; + +import net.minecraft.util.valueproviders.UniformInt; +import net.minecraft.world.attribute.EnvironmentAttributes; +import net.minecraft.world.attribute.modifier.AttributeModifier; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.level.StructureManager; +import net.minecraft.world.level.levelgen.Beardifier; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.MobSpawnSettings; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.levelgen.densityfunction.SamplerContext; + +import com.dfsek.terra.api.world.biome.generation.BiomeProvider; +import com.dfsek.terra.api.world.chunk.generation.ChunkGenerator; +import com.dfsek.terra.api.world.info.WorldProperties; +import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions; +import com.dfsek.terra.bukkit.nms.NMSStructureBeardifier; +import com.dfsek.terra.bukkit.nms.NMSVersionBindings; +import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties; + + +public final class Bindings implements NMSVersionBindings { + @Override + public void addSpawn(MobSpawnSettings.Builder builder, MobCategory category, EntityType type, int weight, + int minCount, int maxCount) { + builder.addSpawn(type, category, weight, UniformInt.of(minCount, maxCount)); + } + + @Override + public void addSpawnCost(MobSpawnSettings.Builder builder, EntityType type, double mass, double gravity) { + builder.addMobSpawnCost(type, mass, gravity); + } + + @Override + public boolean setCreatureGenerationProbability(MobSpawnSettings.Builder builder, float probability) { + return false; + } + + @Override + public void copyVanillaSpawnSettings(Biome.BiomeBuilder builder, Biome biome) { + // 26.3 stores natural spawn settings in the biome's environment attributes, + // which NMSBiomeInjector already copies into its builder. + } + + @Override + public void setSpawnSettings(Biome.BiomeBuilder builder, MobSpawnSettings settings) { + builder.setAttribute(EnvironmentAttributes.NATURAL_MOB_SPAWNS, settings); + } + + @Override + public void applyBiomeColorOverrides(Biome.BiomeBuilder builder, VanillaBiomeProperties properties) { + if(properties.getFogColor() != null) { + builder.modifyAttribute(EnvironmentAttributes.FOG_COLOR, AttributeModifier.override(), color(properties.getFogColor())); + } + if(properties.getWaterFogColor() != null) { + builder.modifyAttribute(EnvironmentAttributes.WATER_FOG_COLOR, AttributeModifier.override(), color(properties.getWaterFogColor())); + } + if(properties.getSkyColor() != null) { + builder.modifyAttribute(EnvironmentAttributes.SKY_COLOR, AttributeModifier.override(), color(properties.getSkyColor())); + } + } + + private static org.joml.Vector3f color(int rgb) { + return new org.joml.Vector3f( + ((rgb >>> 16) & 0xFF) / 255.0f, + ((rgb >>> 8) & 0xFF) / 255.0f, + (rgb & 0xFF) / 255.0f + ); + } + + @Override + public void applyStructureBeard(ChunkGenerator generator, StructureManager structures, ChunkAccess chunk, WorldProperties world, + BiomeProvider biomeProvider, PreLoadCompatibilityOptions options) { + Beardifier beardifier = Beardifier.forStructuresInChunk(structures, chunk.getPos()); + NMSStructureBeardifier.apply(generator, chunk, world, biomeProvider, options, + (x, y, z) -> beardifier.sampleValue(SamplerContext.EMPTY_UNCACHED, x, y, z)); + } +} diff --git a/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/NMSPlatform.java b/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/NMSPlatform.java new file mode 100644 index 000000000..3da0e2911 --- /dev/null +++ b/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/NMSPlatform.java @@ -0,0 +1,11 @@ +package com.dfsek.terra.bukkit.nms.v26_3; + +import com.dfsek.terra.bukkit.TerraBukkitPlugin; +import com.dfsek.terra.bukkit.nms.NMSPlatformBase; + + +public final class NMSPlatform extends NMSPlatformBase { + public NMSPlatform(TerraBukkitPlugin plugin) { + super(plugin, new Bindings()); + } +} diff --git a/platforms/bukkit/nms/build.gradle.kts b/platforms/bukkit/nms/build.gradle.kts index 032aa34d6..22b4a74bb 100644 --- a/platforms/bukkit/nms/build.gradle.kts +++ b/platforms/bukkit/nms/build.gradle.kts @@ -1,5 +1,9 @@ plugins { - id("io.papermc.paperweight.userdev") + `java-library` +} + +subprojects { + group = "com.dfsek.terra.bukkit.nms" } tasks.withType().configureEach { @@ -7,7 +11,7 @@ tasks.withType().configureEach { } dependencies { - api(project(":platforms:bukkit:common")) - paperweight.paperDevBundle(Versions.Bukkit.paperDevBundle) - implementation("xyz.jpenilla", "reflection-remapper", Versions.Bukkit.reflectionRemapper) -} \ No newline at end of file + api(project(path = ":platforms:bukkit:nms:common", configuration = "runtimeElements")) + api(project(path = ":platforms:bukkit:nms:26.1", configuration = "runtimeElements")) + api(project(path = ":platforms:bukkit:nms:26.3", configuration = "runtimeElements")) +} diff --git a/platforms/bukkit/nms/common/build.gradle.kts b/platforms/bukkit/nms/common/build.gradle.kts new file mode 100644 index 000000000..d1816ef13 --- /dev/null +++ b/platforms/bukkit/nms/common/build.gradle.kts @@ -0,0 +1,17 @@ +plugins { + id("io.papermc.paperweight.userdev") +} + +tasks.withType().configureEach { + options.release = 25 +} + +dependencies { + compileOnly(project(":platforms:bukkit:common")) + compileOnly("xyz.jpenilla", "reflection-remapper", Versions.Bukkit.reflectionRemapper) + paperweight.paperDevBundle(Versions.Bukkit.paperDevBundle) +} + +tasks.withType().configureEach { + archiveBaseName.set("terra-bukkit-nms-common") +} diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java similarity index 63% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java index 5b4bb1eaf..973737d6b 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java @@ -10,19 +10,32 @@ import net.minecraft.core.HolderLookup; import net.minecraft.core.HolderSet.Named; import net.minecraft.core.MappedRegistry; import net.minecraft.core.RegistrationInfo; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.TagParser; import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; import net.minecraft.tags.TagKey; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.npc.villager.VillagerType; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Block; import org.bukkit.Bukkit; import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.World; +import org.bukkit.block.CreatureSpawner; import org.bukkit.block.data.BlockData; import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.CraftWorld; import org.bukkit.craftbukkit.block.data.CraftBlockData; +import org.bukkit.craftbukkit.entity.CraftEntitySnapshot; +import org.bukkit.craftbukkit.generator.CraftLimitedRegion; +import org.bukkit.event.entity.CreatureSpawnEvent; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,9 +49,12 @@ import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; -import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties; +import com.dfsek.terra.api.entity.EntityTypeExtended; import com.dfsek.terra.bukkit.world.BukkitBiomeInfo; import com.dfsek.terra.bukkit.world.BukkitPlatformBiome; +import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties; +import com.dfsek.terra.bukkit.world.entity.BukkitEntityType; +import com.dfsek.terra.bukkit.world.entity.BukkitEntityTypeExtended; import com.dfsek.terra.registry.master.ConfigRegistry; @@ -47,7 +63,7 @@ public class AwfulBukkitHacks { private static final Map> terraBiomeMap = new HashMap<>(); - public static void registerBiomes(ConfigRegistry configRegistry) { + public static void registerBiomes(ConfigRegistry configRegistry, NMSVersionBindings bindings) { try { LOGGER.info("Hacking biome registry..."); MappedRegistry biomeRegistry = (MappedRegistry) RegistryFetcher.biomeRegistry(); @@ -67,7 +83,7 @@ public class AwfulBukkitHacks { VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class); Biome platform = NMSBiomeInjector.createBiome(biomeRegistry.get(vanillaMinecraftKey).orElseThrow().value(), - vanillaBiomeProperties); + vanillaBiomeProperties, bindings); Identifier delegateMinecraftKey = Identifier.fromNamespaceAndPath("terra", NMSBiomeInjector.createBiomeID(pack, key)); @@ -180,5 +196,88 @@ public class AwfulBukkitHacks { BlockResult result = BlockStateParser.parseForBlock(blocks, new StringReader(data), true); return CraftBlockData.createData(result.blockState()); } -} + public static com.dfsek.terra.api.entity.EntityType getEntityType(@NotNull String data) { + StringReader reader = new StringReader(data); + Identifier identifier; + CompoundTag entityNbt = null; + try { + identifier = Identifier.read(reader); + if(reader.canRead()) { + if(reader.peek() != '{') throw new IllegalArgumentException("Unexpected data after entity identifier: " + data); + entityNbt = TagParser.parseCompoundAsArgument(reader); + if(reader.canRead()) throw new IllegalArgumentException("Unexpected data after entity NBT: " + data); + entityNbt.putString("id", identifier.toString()); + } + } catch(CommandSyntaxException e) { + throw new IllegalArgumentException("Invalid entity data: " + data, e); + } + + if(BuiltInRegistries.ENTITY_TYPE.getOptional(identifier).isEmpty()) { + throw new IllegalArgumentException("Unknown entity type: " + identifier); + } + + NamespacedKey key = NamespacedKey.fromString(identifier.toString()); + org.bukkit.entity.EntityType bukkitType = key == null ? null : Registry.ENTITY_TYPE.get(key); + if(bukkitType == null) throw new IllegalArgumentException("Bukkit has no entity type for " + identifier); + + if(entityNbt == null) return new BukkitEntityType(bukkitType); + return new BukkitEntityTypeExtended(bukkitType, entityNbt.toString()); + } + + public static org.bukkit.entity.Entity spawnEntity(Object target, org.bukkit.Location location, + com.dfsek.terra.api.entity.EntityType type) { + if(!(type instanceof BukkitEntityTypeExtended extended)) { + throw new IllegalArgumentException("Expected a Bukkit entity type with NBT data"); + } + CompoundTag nbt = parseEntityNbt(extended); + + CraftLimitedRegion limitedRegion = target instanceof CraftLimitedRegion region ? region : null; + World world = limitedRegion == null ? (World) target : limitedRegion.getWorld(); + if(!(world instanceof CraftWorld craftWorld)) throw new IllegalArgumentException("Unsupported Bukkit world: " + world); + ServerLevel level = craftWorld.getHandle(); + + String entityIDText = nbt.getString("id") + .orElseThrow(() -> new IllegalArgumentException("Missing entity identifier in NBT")); + Identifier entityID; + try { + entityID = Identifier.read(new StringReader(entityIDText)); + } catch(CommandSyntaxException e) { + throw new IllegalArgumentException("Invalid entity identifier in NBT: " + entityIDText, e); + } + EntityType entityType = BuiltInRegistries.ENTITY_TYPE.getOptional(entityID) + .orElseThrow(() -> new IllegalArgumentException("Unknown entity type in NBT: " + entityID)); + + net.minecraft.world.entity.Entity entity = EntityType.loadEntityRecursive(entityType, nbt, level, EntitySpawnReason.STRUCTURE, loaded -> { + loaded.snapTo(location.getX(), location.getY(), location.getZ(), loaded.getYRot(), loaded.getXRot()); + return loaded; + }); + if(entity == null) throw new IllegalArgumentException("Could not load entity from NBT: " + nbt); + + if(limitedRegion != null) { + limitedRegion.addEntityWithPassengers(entity, CreatureSpawnEvent.SpawnReason.CUSTOM); + } else if(!level.tryAddFreshEntityWithPassengers(entity, CreatureSpawnEvent.SpawnReason.CUSTOM)) { + throw new IllegalStateException("Could not add entity to world: " + nbt); + } + + return entity.getBukkitEntity(); + } + + public static void setSpawnerEntity(CreatureSpawner spawner, EntityTypeExtended type) { + if(!(type instanceof BukkitEntityTypeExtended extended)) { + throw new IllegalArgumentException("Expected a Bukkit entity type with NBT data"); + } + spawner.setSpawnedEntity(CraftEntitySnapshot.create(parseEntityNbt(extended), extended.getHandle())); + } + + private static CompoundTag parseEntityNbt(BukkitEntityTypeExtended extended) { + Object rawData = extended.getData().getHandle(); + if(!(rawData instanceof String snbt)) throw new IllegalArgumentException("Bukkit entity data must contain SNBT text"); + + try { + return TagParser.parseCompoundFully(snbt); + } catch(CommandSyntaxException e) { + throw new IllegalArgumentException("Invalid entity NBT: " + snbt, e); + } + } +} diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSAddon.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSAddon.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSAddon.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSAddon.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInfo.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInfo.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInfo.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInfo.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java similarity index 58% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java index 4b2668814..ccfba8cc0 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java @@ -8,7 +8,6 @@ import net.minecraft.resources.Identifier; 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.attribute.AmbientSounds; import net.minecraft.world.attribute.BackgroundMusic; import net.minecraft.world.attribute.EnvironmentAttribute; @@ -19,6 +18,7 @@ import net.minecraft.world.attribute.modifier.AttributeModifier; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome.BiomeBuilder; import net.minecraft.world.level.biome.BiomeGenerationSettings; +import net.minecraft.world.level.biome.MobSpawnSettings; import net.minecraft.world.level.biome.BiomeSpecialEffects; import java.util.Collections; @@ -37,29 +37,18 @@ public class NMSBiomeInjector { return registry.getOptional(identifier).flatMap(registry::getResourceKey).flatMap(registry::get); } - public static Biome createBiome(Biome vanilla, VanillaBiomeProperties vanillaBiomeProperties) + public static Biome createBiome(Biome vanilla, VanillaBiomeProperties vanillaBiomeProperties, NMSVersionBindings bindings) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Biome.BiomeBuilder builder = new Biome.BiomeBuilder(); BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder(); EnvironmentAttributeMap attributes = vanilla.getAttributes(); + builder.putAttributes(attributes); - Integer vanillaFogColour = extractInt(attributes, EnvironmentAttributes.FOG_COLOR); - Integer vanillaWaterFogColour = extractInt(attributes, EnvironmentAttributes.WATER_FOG_COLOR); - Integer vanillaSkyColour = extractInt(attributes, EnvironmentAttributes.SKY_COLOR); - Float vanillaMusicVolume = extractFloat(attributes, EnvironmentAttributes.MUSIC_VOLUME); - - applyIfPresent(builder, EnvironmentAttributes.FOG_COLOR, - vanillaBiomeProperties.getFogColor(), vanillaFogColour); - - applyIfPresent(builder, EnvironmentAttributes.WATER_FOG_COLOR, - vanillaBiomeProperties.getWaterFogColor(), vanillaWaterFogColour); - - applyIfPresent(builder, EnvironmentAttributes.SKY_COLOR, - vanillaBiomeProperties.getSkyColor(), vanillaSkyColour); - - applyIfPresent(builder, EnvironmentAttributes.MUSIC_VOLUME, - vanillaBiomeProperties.getMusicVolume(), vanillaMusicVolume); + bindings.applyBiomeColorOverrides(builder, vanillaBiomeProperties); + if(vanillaBiomeProperties.getMusicVolume() != null) { + builder.modifyAttribute(EnvironmentAttributes.MUSIC_VOLUME, AttributeModifier.override(), vanillaBiomeProperties.getMusicVolume()); + } effects.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor())); effects.grassColorModifier( @@ -77,27 +66,7 @@ public class NMSBiomeInjector { effects.foliageColorOverride(vanillaBiomeProperties.getFoliageColor()); } - if(vanillaBiomeProperties.getParticleConfig() == null) { - Entry ambientEntry = attributes.get(EnvironmentAttributes.AMBIENT_PARTICLES); - if(ambientEntry != null) { - Object arg = ambientEntry.argument(); - - // this is not nice - if(arg instanceof List rawList) { - List ambientParticles = - rawList.stream() - .filter(AmbientParticle.class::isInstance) - .map(AmbientParticle.class::cast) - .toList(); - - builder.modifyAttribute( - EnvironmentAttributes.AMBIENT_PARTICLES, - AttributeModifier.override(), - ambientParticles - ); - } - } - } else { + if(vanillaBiomeProperties.getParticleConfig() != null) { builder.modifyAttribute(EnvironmentAttributes.AMBIENT_PARTICLES, AttributeModifier.override(), List.of(vanillaBiomeProperties.getParticleConfig())); } @@ -106,10 +75,8 @@ public class NMSBiomeInjector { Optional mood = Optional.empty(); List additions = Collections.emptyList(); - if(attributes.contains(EnvironmentAttributes.AMBIENT_SOUNDS)) { - AmbientSounds sounds = - (AmbientSounds) Objects.requireNonNull(attributes.get(EnvironmentAttributes.AMBIENT_SOUNDS)).argument(); - + AmbientSounds sounds = getAttribute(attributes, EnvironmentAttributes.AMBIENT_SOUNDS); + if(sounds != null) { loop = sounds.loop(); mood = sounds.mood(); additions = sounds.additions(); @@ -132,13 +99,7 @@ public class NMSBiomeInjector { builder.modifyAttribute(EnvironmentAttributes.AMBIENT_SOUNDS, AttributeModifier.override(), new AmbientSounds(loop, mood, additions)); - if(vanillaBiomeProperties.getMusic() == null) { - if(attributes.contains(EnvironmentAttributes.BACKGROUND_MUSIC)) { - BackgroundMusic music = (BackgroundMusic) Objects.requireNonNull(attributes.get(EnvironmentAttributes.BACKGROUND_MUSIC)) - .argument(); - builder.modifyAttribute(EnvironmentAttributes.BACKGROUND_MUSIC, AttributeModifier.override(), music); - } - } else { + if(vanillaBiomeProperties.getMusic() != null) { builder.modifyAttribute(EnvironmentAttributes.BACKGROUND_MUSIC, AttributeModifier.override(), new BackgroundMusic(vanillaBiomeProperties.getMusic())); } @@ -148,7 +109,12 @@ public class NMSBiomeInjector { builder.downfall(Objects.requireNonNullElse(vanillaBiomeProperties.getDownfall(), vanilla.climateSettings.downfall())); builder.temperatureAdjustment( Objects.requireNonNullElse(vanillaBiomeProperties.getTemperatureModifier(), vanilla.climateSettings.temperatureModifier())); - builder.mobSpawnSettings(Objects.requireNonNullElse(vanillaBiomeProperties.getSpawnSettings(), vanilla.getMobSettings())); + MobSpawnSettings spawnSettings = vanillaBiomeProperties.getSpawnSettings(); + if(spawnSettings == null) { + bindings.copyVanillaSpawnSettings(builder, vanilla); + } else { + bindings.setSpawnSettings(builder, spawnSettings); + } return builder.specialEffects(effects.build()).generationSettings(new BiomeGenerationSettings.PlainBuilder().build()).build(); } @@ -158,30 +124,8 @@ public class NMSBiomeInjector { Locale.ROOT); } - private static Integer extractInt(EnvironmentAttributeMap attributes, - EnvironmentAttribute key) { - Entry attr = attributes.get(key); - return attr != null ? (Integer) attr.argument() : null; - } - - private static Float extractFloat(EnvironmentAttributeMap attributes, - EnvironmentAttribute key) { - Entry attr = attributes.get(key); - return attr != null ? (Float) attr.argument() : null; - } - - private static void applyIfPresent( - BiomeBuilder builder, - EnvironmentAttribute attr, - T overrideValue, - T fallbackValue - ) { - T value = overrideValue != null ? overrideValue : fallbackValue; - - if (value == null) { - return; - } - - builder.modifyAttribute(attr, AttributeModifier.override(), value); + private static T getAttribute(EnvironmentAttributeMap attributes, EnvironmentAttribute key) { + Entry entry = attributes.get(key); + return entry == null ? null : entry.applyModifier(key.defaultValue()); } } diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeProvider.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeProvider.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeProvider.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeProvider.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java similarity index 71% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java index e22ff1e6b..0766a99e0 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java @@ -9,19 +9,14 @@ import net.minecraft.world.level.NoiseColumn; import net.minecraft.world.level.StructureManager; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.biome.BiomeManager; -import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.levelgen.Beardifier; -import net.minecraft.world.level.levelgen.DensityFunction.SinglePointContext; import net.minecraft.world.level.levelgen.Heightmap.Types; import net.minecraft.world.level.levelgen.RandomState; import net.minecraft.world.level.levelgen.blending.Blender; import org.bukkit.craftbukkit.block.data.CraftBlockData; import org.jetbrains.annotations.NotNull; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -30,25 +25,25 @@ import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.world.biome.generation.BiomeProvider; import com.dfsek.terra.api.world.info.WorldProperties; import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions; -import com.dfsek.terra.bukkit.world.BukkitWorldProperties; -import com.dfsek.terra.bukkit.world.block.data.BukkitBlockState; public class NMSChunkGeneratorDelegate extends ChunkGenerator { - private static final Logger LOGGER = LoggerFactory.getLogger(NMSChunkGeneratorDelegate.class); private final com.dfsek.terra.api.world.chunk.generation.ChunkGenerator delegate; private final ChunkGenerator vanilla; private final ConfigPack pack; + private final NMSVersionBindings bindings; private final long seed; - public NMSChunkGeneratorDelegate(ChunkGenerator vanilla, ConfigPack pack, NMSBiomeProvider biomeProvider, long seed) { + public NMSChunkGeneratorDelegate(ChunkGenerator vanilla, ConfigPack pack, NMSBiomeProvider biomeProvider, long seed, + NMSVersionBindings bindings) { super(biomeProvider); this.delegate = pack.getGeneratorProvider().newInstance(pack); this.vanilla = vanilla; this.pack = pack; this.seed = seed; + this.bindings = bindings; } @Override @@ -94,40 +89,14 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator { BiomeProvider biomeProvider = pack.getBiomeProvider(); PreLoadCompatibilityOptions compatibilityOptions = pack.getContext().get(PreLoadCompatibilityOptions.class); if(compatibilityOptions.isBeard()) { - beard(structureAccessor, chunk, new BukkitWorldProperties(level.getMinecraftWorld().getWorld()), + bindings.applyStructureBeard(delegate, structureAccessor, chunk, + new com.dfsek.terra.bukkit.world.BukkitWorldProperties(level.getMinecraftWorld().getWorld()), biomeProvider, compatibilityOptions); } return c; }); } - private void beard(StructureManager structureAccessor, ChunkAccess chunk, WorldProperties world, BiomeProvider biomeProvider, - PreLoadCompatibilityOptions compatibilityOptions) { - Beardifier structureWeightSampler = Beardifier.forStructuresInChunk(structureAccessor, chunk.getPos()); - double threshold = compatibilityOptions.getBeardThreshold(); - double airThreshold = compatibilityOptions.getAirThreshold(); - int xi = chunk.getPos().x() << 4; - int zi = chunk.getPos().z() << 4; - for(int x = 0; x < 16; x++) { - for(int z = 0; z < 16; z++) { - int depth = 0; - for(int y = world.getMaxHeight(); y >= world.getMinHeight(); y--) { - double noise = structureWeightSampler.compute(new SinglePointContext(x + xi, y, z + zi)); - if(noise > threshold) { - chunk.setBlockState(new BlockPos(x, y, z), ((CraftBlockData) ((BukkitBlockState) delegate - .getPalette(x + xi, y, z + zi, world, biomeProvider) - .get(depth, x + xi, y, z + zi, world.getSeed())).getHandle()).getState(), 0); - depth++; - } else if(noise < airThreshold) { - chunk.setBlockState(new BlockPos(x, y, z), Blocks.AIR.defaultBlockState(), 0); - } else { - depth = 0; - } - } - } - } - } - @Override public int getSeaLevel() { return vanilla.getSeaLevel(); diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSInjectListener.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSInjectListener.java similarity index 92% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSInjectListener.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSInjectListener.java index 4a73dc77b..19597e22b 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSInjectListener.java +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSInjectListener.java @@ -24,6 +24,11 @@ public class NMSInjectListener implements Listener { private static final Logger LOGGER = LoggerFactory.getLogger(NMSInjectListener.class); private static final Set INJECTED = new HashSet<>(); private static final ReentrantLock INJECT_LOCK = new ReentrantLock(); + private final NMSVersionBindings bindings; + + public NMSInjectListener(NMSVersionBindings bindings) { + this.bindings = bindings; + } @EventHandler public void onWorldInit(WorldInitEvent event) { @@ -43,7 +48,7 @@ public class NMSInjectListener implements Listener { WorldGenContext worldGenContext = Reflection.CHUNKMAP.getWorldGenContext(chunkMap); Reflection.CHUNKMAP.setWorldGenContext(chunkMap, new WorldGenContext( worldGenContext.level(), - new NMSChunkGeneratorDelegate(vanilla, pack, provider, craftWorld.getSeed()), + new NMSChunkGeneratorDelegate(vanilla, pack, provider, craftWorld.getSeed(), bindings), worldGenContext.structureManager(), worldGenContext.lightEngine(), worldGenContext.mainThreadExecutor(), diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatformBase.java similarity index 80% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatformBase.java index e54b2fd04..150071f09 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatformBase.java @@ -16,17 +16,20 @@ import net.minecraft.world.level.biome.Biome.TemperatureModifier; import net.minecraft.world.level.biome.BiomeSpecialEffects.GrassColorModifier; import net.minecraft.world.level.biome.MobSpawnSettings; import org.bukkit.Bukkit; +import org.bukkit.block.CreatureSpawner; import java.util.List; import java.util.Locale; import com.dfsek.terra.addon.InternalAddon; import com.dfsek.terra.api.addon.BaseAddon; +import com.dfsek.terra.api.entity.EntityTypeExtended; import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent; import com.dfsek.terra.api.event.functional.FunctionalEventHandler; import com.dfsek.terra.api.world.biome.PlatformBiome; import com.dfsek.terra.bukkit.PlatformImpl; import com.dfsek.terra.bukkit.TerraBukkitPlugin; +import com.dfsek.terra.bukkit.util.BukkitNMSAccess; import com.dfsek.terra.bukkit.nms.config.BiomeAdditionsSoundTemplate; import com.dfsek.terra.bukkit.nms.config.BiomeMoodSoundTemplate; import com.dfsek.terra.bukkit.nms.config.BiomeParticleConfigTemplate; @@ -40,12 +43,30 @@ import com.dfsek.terra.bukkit.nms.config.SpawnTypeConfig; import com.dfsek.terra.bukkit.nms.config.VillagerTypeTemplate; -public class NMSPlatform extends PlatformImpl { +public class NMSPlatformBase extends PlatformImpl implements BukkitNMSAccess { + private final NMSVersionBindings bindings; - public NMSPlatform(TerraBukkitPlugin plugin) { + public NMSPlatformBase(TerraBukkitPlugin plugin, NMSVersionBindings bindings) { super(plugin); + this.bindings = bindings; - Bukkit.getPluginManager().registerEvents(new NMSInjectListener(), plugin); + Bukkit.getPluginManager().registerEvents(new NMSInjectListener(bindings), plugin); + } + + @Override + public com.dfsek.terra.api.entity.EntityType getEntityType(String data) { + return AwfulBukkitHacks.getEntityType(data); + } + + @Override + public org.bukkit.entity.Entity spawnEntity(Object target, org.bukkit.Location location, + com.dfsek.terra.api.entity.EntityType type) { + return AwfulBukkitHacks.spawnEntity(target, location, type); + } + + @Override + public void setSpawnerEntity(CreatureSpawner spawner, EntityTypeExtended type) { + AwfulBukkitHacks.setSpawnerEntity(spawner, type); } @Override @@ -76,7 +97,7 @@ public class NMSPlatform extends PlatformImpl { .registerLoader(SpawnCostConfig.class, SpawnCostConfig::new) .registerLoader(SpawnEntryConfig.class, SpawnEntryConfig::new) .registerLoader(SpawnTypeConfig.class, SpawnTypeConfig::new) - .registerLoader(MobSpawnSettings.class, SpawnSettingsTemplate::new) + .registerLoader(MobSpawnSettings.class, () -> new SpawnSettingsTemplate(bindings)) .registerLoader(VillagerType.class, VillagerTypeTemplate::new); } @@ -87,7 +108,7 @@ public class NMSPlatform extends PlatformImpl { this.getEventManager().getHandler(FunctionalEventHandler.class) .register(internalAddon, PlatformInitializationEvent.class) .priority(1) - .then(event -> AwfulBukkitHacks.registerBiomes(this.getRawConfigRegistry())) + .then(event -> AwfulBukkitHacks.registerBiomes(this.getRawConfigRegistry(), bindings)) .global(); return internalAddon; diff --git a/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSStructureBeardifier.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSStructureBeardifier.java new file mode 100644 index 000000000..7e0a584e4 --- /dev/null +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSStructureBeardifier.java @@ -0,0 +1,52 @@ +package com.dfsek.terra.bukkit.nms; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.chunk.ChunkAccess; +import org.bukkit.craftbukkit.block.data.CraftBlockData; + +import com.dfsek.terra.api.world.biome.generation.BiomeProvider; +import com.dfsek.terra.api.world.chunk.generation.ChunkGenerator; +import com.dfsek.terra.api.world.info.WorldProperties; +import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions; +import com.dfsek.terra.bukkit.world.block.data.BukkitBlockState; + + +public final class NMSStructureBeardifier { + private NMSStructureBeardifier() { } + + public static void apply(ChunkGenerator delegate, ChunkAccess chunk, WorldProperties world, + BiomeProvider biomeProvider, PreLoadCompatibilityOptions compatibilityOptions, + StructureDensitySampler sampler) { + double threshold = compatibilityOptions.getBeardThreshold(); + double airThreshold = compatibilityOptions.getAirThreshold(); + int chunkX = chunk.getPos().x() << 4; + int chunkZ = chunk.getPos().z() << 4; + + for(int x = 0; x < 16; x++) { + for(int z = 0; z < 16; z++) { + int depth = 0; + for(int y = world.getMaxHeight(); y >= world.getMinHeight(); y--) { + int worldX = x + chunkX; + int worldZ = z + chunkZ; + double density = sampler.sample(worldX, y, worldZ); + if(density > threshold) { + chunk.setBlockState(new BlockPos(x, y, z), ((CraftBlockData) ((BukkitBlockState) delegate + .getPalette(worldX, y, worldZ, world, biomeProvider) + .get(depth, worldX, y, worldZ, world.getSeed())).getHandle()).getState(), 0); + depth++; + } else if(density < airThreshold) { + chunk.setBlockState(new BlockPos(x, y, z), Blocks.AIR.defaultBlockState(), 0); + } else { + depth = 0; + } + } + } + } + } + + @FunctionalInterface + public interface StructureDensitySampler { + double sample(int x, int y, int z); + } +} diff --git a/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSVersionBindings.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSVersionBindings.java new file mode 100644 index 000000000..389a68ae7 --- /dev/null +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSVersionBindings.java @@ -0,0 +1,33 @@ +package com.dfsek.terra.bukkit.nms; + +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.level.StructureManager; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.Biome.BiomeBuilder; +import net.minecraft.world.level.biome.MobSpawnSettings; +import net.minecraft.world.level.chunk.ChunkAccess; + +import com.dfsek.terra.api.world.biome.generation.BiomeProvider; +import com.dfsek.terra.api.world.chunk.generation.ChunkGenerator; +import com.dfsek.terra.api.world.info.WorldProperties; +import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions; +import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties; + + +public interface NMSVersionBindings { + void addSpawn(MobSpawnSettings.Builder builder, MobCategory category, EntityType type, int weight, int minCount, int maxCount); + + void addSpawnCost(MobSpawnSettings.Builder builder, EntityType type, double mass, double gravity); + + boolean setCreatureGenerationProbability(MobSpawnSettings.Builder builder, float probability); + + void copyVanillaSpawnSettings(BiomeBuilder builder, Biome biome); + + void setSpawnSettings(BiomeBuilder builder, MobSpawnSettings settings); + + void applyBiomeColorOverrides(BiomeBuilder builder, VanillaBiomeProperties properties); + + void applyStructureBeard(ChunkGenerator generator, StructureManager structures, ChunkAccess chunk, WorldProperties world, + BiomeProvider biomeProvider, PreLoadCompatibilityOptions options); +} diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSWorldProperties.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSWorldProperties.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSWorldProperties.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSWorldProperties.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/RegistryFetcher.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/RegistryFetcher.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/RegistryFetcher.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/RegistryFetcher.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeMoodSoundTemplate.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeMoodSoundTemplate.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeMoodSoundTemplate.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeMoodSoundTemplate.java diff --git a/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java new file mode 100644 index 000000000..22a754055 --- /dev/null +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java @@ -0,0 +1,71 @@ +package com.dfsek.terra.bukkit.nms.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; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +public class BiomeParticleConfigTemplate implements ObjectTemplate { + private static final Pattern LEGACY_BLOCK_PARTICLE = Pattern.compile( + "^((?:[a-z0-9_.-]+:)?[a-z0-9_./-]+)\\{block_state:\\{Name:((?:[a-z0-9_.-]+:)?[a-z0-9_./-]+)\\}\\}$" + ); + + @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(parseParticle(particle), probability); + } catch(CommandSyntaxException e) { + String normalized = normalizeLegacyBlockParticle(particle); + if(normalized == null) { + throw new RuntimeException(e); + } + + try { + return new AmbientParticle(parseParticle(normalized), probability); + } catch(CommandSyntaxException fallbackException) { + fallbackException.addSuppressed(e); + throw new RuntimeException(fallbackException); + } + } + } + + private static net.minecraft.core.particles.ParticleOptions parseParticle(String value) throws CommandSyntaxException { + return ParticleArgument.readParticle(new StringReader(value), + HolderLookup.Provider.create(Stream.of(BuiltInRegistries.PARTICLE_TYPE))); + } + + private static String normalizeLegacyBlockParticle(String value) { + Matcher matcher = LEGACY_BLOCK_PARTICLE.matcher(value); + if(!matcher.matches()) { + return null; + } + + String block = matcher.group(2); + if(!block.contains(":")) { + block = "minecraft:" + block; + } + return matcher.group(1) + "{block_state:\"" + block + "\"}"; + } +} diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/EntityTypeTemplate.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/EntityTypeTemplate.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/EntityTypeTemplate.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/EntityTypeTemplate.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/MusicSoundTemplate.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/MusicSoundTemplate.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/MusicSoundTemplate.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/MusicSoundTemplate.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnCostConfig.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnCostConfig.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnCostConfig.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnCostConfig.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnEntryConfig.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnEntryConfig.java similarity index 79% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnEntryConfig.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnEntryConfig.java index 60a763769..e5dff2145 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnEntryConfig.java +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnEntryConfig.java @@ -4,7 +4,6 @@ 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; -import net.minecraft.world.level.biome.MobSpawnSettings.SpawnerData; import com.dfsek.terra.api.util.range.Range; @@ -26,8 +25,16 @@ public class SpawnEntryConfig implements ObjectTemplate { return weight; } - public SpawnerData getSpawnEntry() { - return new SpawnerData(type, groupSize.getMin(), groupSize.getMax()); + public EntityType getType() { + return type; + } + + public int getMinCount() { + return groupSize.getMin(); + } + + public int getMaxCount() { + return groupSize.getMax(); } @Override diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnSettingsTemplate.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnSettingsTemplate.java similarity index 53% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnSettingsTemplate.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnSettingsTemplate.java index 7950f3389..3d34bc828 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnSettingsTemplate.java +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnSettingsTemplate.java @@ -9,12 +9,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import com.dfsek.terra.bukkit.nms.NMSVersionBindings; public class SpawnSettingsTemplate implements ObjectTemplate { + private static final Logger LOGGER = LoggerFactory.getLogger(SpawnSettingsTemplate.class); + private static final AtomicBoolean PROBABILITY_WARNING_LOGGED = new AtomicBoolean(); - private static final Logger logger = LoggerFactory.getLogger(SpawnTypeConfig.class); - private static boolean used = false; + private final NMSVersionBindings bindings; @Value("spawns") @Default @@ -28,20 +32,25 @@ public class SpawnSettingsTemplate implements ObjectTemplate { @Default private Float probability = null; + public SpawnSettingsTemplate(NMSVersionBindings bindings) { + this.bindings = bindings; + } + @Override public MobSpawnSettings get() { MobSpawnSettings.Builder builder = new MobSpawnSettings.Builder(); for(SpawnTypeConfig spawn : spawns) { - MobCategory group = spawn.getGroup(); + MobCategory category = spawn.getGroup(); for(SpawnEntryConfig entry : spawn.getEntries()) { - builder.addSpawn(group, entry.getWeight(), entry.getSpawnEntry()); + bindings.addSpawn(builder, category, entry.getType(), entry.getWeight(), entry.getMinCount(), entry.getMaxCount()); } } for(SpawnCostConfig cost : costs) { - builder.addMobCharge(cost.getType(), cost.getMass(), cost.getGravity()); + bindings.addSpawnCost(builder, cost.getType(), cost.getMass(), cost.getGravity()); } - if(probability != null) { - builder.creatureGenerationProbability(probability); + if(probability != null && !bindings.setCreatureGenerationProbability(builder, probability) && + PROBABILITY_WARNING_LOGGED.compareAndSet(false, true)) { + LOGGER.warn("This server version ignores biome creature-generation probability values."); } return builder.build(); diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnTypeConfig.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnTypeConfig.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnTypeConfig.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnTypeConfig.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java similarity index 100% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java rename to platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java deleted file mode 100644 index 7c31521f2..000000000 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.dfsek.terra.bukkit.nms.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); - } - } -} From 65cd0c3e7cabb0d158badaba9ff864418b35dd4f Mon Sep 17 00:00:00 2001 From: Christian Bergschneider Date: Fri, 2 Oct 2026 22:54:19 +0200 Subject: [PATCH 22/44] docs: add full IDE meta to most terra addons --- .../src/main/kotlin/DistributionConfig.kt | 10 + .../resources/META-INF/api/config.terradoc | 215 + .../resources/META-INF/api/config.terradoc | 118 + .../resources/META-INF/api/config.terradoc | 420 ++ .../resources/META-INF/api/config.terradoc | 25 + .../resources/META-INF/api/config.terradoc | 388 ++ .../resources/META-INF/api/config.terradoc | 120 + .../resources/META-INF/api/config.terradoc | 206 + .../resources/META-INF/api/config.terradoc | 183 + .../resources/META-INF/api/config.terradoc | 207 + .../resources/META-INF/api/config.terradoc | 388 ++ .../resources/META-INF/api/config.terradoc | 6039 +++++++++++++++++ .../resources/META-INF/api/config.terradoc | 16 + .../resources/META-INF/api/config.terradoc | 253 + .../resources/META-INF/api/config.terradoc | 204 + .../resources/META-INF/api/config.terradoc | 99 + .../resources/META-INF/api/config.terradoc | 520 ++ .../resources/META-INF/api/config.terradoc | 26 + .../resources/META-INF/api/config.terradoc | 29 + .../resources/META-INF/api/config.terradoc | 110 + .../resources/META-INF/api/config.terradoc | 29 + .../resources/META-INF/api/config.terradoc | 11 + .../resources/META-INF/api/config.terradoc | 11 + .../main/resources/META-INF/api/core.terradoc | 265 + .../resources/META-INF/api/config.terradoc | 314 + 25 files changed, 10206 insertions(+) create mode 100644 common/addons/biome-provider-extrusion/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/biome-provider-image/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/biome-provider-pipeline/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/biome-provider-single/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/chunk-generator-noise-3d/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/config-biome/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/config-distributors/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/config-feature/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/config-flora/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/config-locators/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/config-noise-function/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/config-number-predicate/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/config-ore/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/config-palette/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/generation-stage-feature/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/library-image/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/locator-slant-noise-3d/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/palette-block-shortcut/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/pipeline-image/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/structure-block-shortcut/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/structure-sponge-loader/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/structure-terrascript-loader/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/implementation/base/src/main/resources/META-INF/api/core.terradoc create mode 100644 platforms/minestom/src/main/resources/META-INF/api/config.terradoc diff --git a/buildSrc/src/main/kotlin/DistributionConfig.kt b/buildSrc/src/main/kotlin/DistributionConfig.kt index 0ad6c4491..72c3f4d26 100644 --- a/buildSrc/src/main/kotlin/DistributionConfig.kt +++ b/buildSrc/src/main/kotlin/DistributionConfig.kt @@ -43,6 +43,16 @@ private fun Project.installAddonsInto(dest: Path) { fun Project.configureDistribution() { apply(plugin = "com.gradleup.shadow") + + listOf("jar", "shadowJar").forEach { taskName -> + tasks.named(taskName) { + manifest.attributes(mapOf( + "Implementation-Title" to "Terra", + "Implementation-Version" to project.version.toString(), + "Terra-Platform" to project.name + )) + } + } val downloadDefaultPacks = tasks.create("downloadDefaultPacks") { group = "terra" diff --git a/common/addons/biome-provider-extrusion/src/main/resources/META-INF/api/config.terradoc b/common/addons/biome-provider-extrusion/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..bfe0d20ea --- /dev/null +++ b/common/addons/biome-provider-extrusion/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,215 @@ +{ + "id": "biome-provider-extrusion", + "docVersion": 1, + "description": "EXTRUSION biome provider and SET/REPLACE vertical extrusion variants.", + "types": { + "terra:BiomeProvider": { + "kind": "union", + "discriminator": "type", + "values": { + "EXTRUSION": { + "kind": "object", + "fields": { + "provider": { + "schema": { + "kind": "type", + "target": "terra:BiomeProvider" + }, + "required": true + }, + "resolution": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 4 + }, + "extrusions": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "Extrusion" + } + }, + "required": true, + "summary": "Ordered extrusion steps." + } + } + } + } + }, + "Extrusion": { + "kind": "union", + "discriminator": "type", + "values": { + "SET": { + "kind": "object", + "fields": { + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "range": { + "schema": { + "kind": "type", + "target": "terra:Range" + }, + "required": true + }, + "to": { + "schema": { + "kind": "type", + "target": "WeightedBiomes" + }, + "required": true + } + }, + "description": "Selects a replacement biome within the height range." + }, + "REPLACE": { + "kind": "object", + "fields": { + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "range": { + "schema": { + "kind": "type", + "target": "terra:Range" + }, + "required": true + }, + "to": { + "schema": { + "kind": "type", + "target": "WeightedBiomes" + }, + "required": true + }, + "from": { + "schema": { + "kind": "type", + "target": "terra:Tag" + }, + "required": true, + "summary": "Biome tag required before replacing." + } + }, + "description": "Replaces biomes matching from within the height range." + } + } + }, + "ReplaceableBiome": { + "kind": "oneOf", + "options": [ + { + "kind": "ref", + "target": "terra:Biome" + }, + { + "kind": "literal", + "value": "SELF", + "description": "Keep the input biome at this extrusion step." + } + ], + "description": "Registered biome identifier or SELF. Unknown identifiers are rejected rather than becoming placeholders." + }, + "WeightedBiomes": { + "kind": "oneOf", + "description": "Replaceable biome, biome-to-weight map, or list of maps. Singleton weights are ignored; all other weights are raw integers.", + "options": [ + { + "kind": "type", + "target": "ReplaceableBiome" + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "ReplaceableBiome" + }, + "values": { + "kind": "any", + "name": "Ignored singleton weight" + }, + "maxEntries": 1 + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "ReplaceableBiome" + }, + "values": { + "kind": "integer" + }, + "minEntries": 2 + }, + { + "kind": "list", + "element": { + "kind": "oneOf", + "options": [ + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "ReplaceableBiome" + }, + "values": { + "kind": "any", + "name": "Ignored singleton weight" + }, + "maxEntries": 1 + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "ReplaceableBiome" + }, + "values": { + "kind": "integer" + }, + "minEntries": 2 + } + ] + }, + "maxItems": 1 + }, + { + "kind": "list", + "element": { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "ReplaceableBiome" + }, + "values": { + "kind": "integer" + } + }, + "minItems": 2 + } + ] + } + } +} diff --git a/common/addons/biome-provider-image/src/main/resources/META-INF/api/config.terradoc b/common/addons/biome-provider-image/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..35f2f2e1b --- /dev/null +++ b/common/addons/biome-provider-image/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,118 @@ +{ + "id": "biome-provider-image", + "docVersion": 1, + "description": "Image biome provider with registered Biome outputs.", + "types": { + "terra:BiomeProvider": { + "kind": "union", + "discriminator": "type", + "values": { + "IMAGE": { + "kind": "object", + "fields": { + "resolution": { + "schema": { + "kind": "integer", + "nullable": true + }, + "required": false, + "default": 1 + }, + "color-sampler": { + "schema": { + "kind": "type", + "target": "library-image:ColorSampler" + }, + "required": true + }, + "color-conversion": { + "schema": { + "kind": "type", + "target": "ColorConverter" + }, + "required": true + } + } + } + } + }, + "ColorConverter": { + "kind": "union", + "discriminator": "type", + "values": { + "EXACT": { + "kind": "object", + "fields": { + "match": { + "schema": { + "kind": "type", + "target": "ColorMapping" + }, + "required": true + }, + "else": { + "schema": { + "kind": "ref", + "target": "terra:Biome" + }, + "required": true, + "summary": "Required fallback for colors with no exact mapping." + }, + "ignore-alpha": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": true + } + }, + "description": "Exact color matching with a fallback; alpha is ignored by default." + }, + "CLOSEST": { + "kind": "object", + "fields": { + "match": { + "schema": { + "kind": "type", + "target": "ColorMapping" + }, + "required": true + } + }, + "description": "Closest color using summed absolute RGB differences; alpha is ignored. An empty map cannot produce a biome." + } + } + }, + "ColorMapping": { + "kind": "union", + "discriminator": "type", + "values": { + "USE_BIOME_COLORS": { + "kind": "object", + "fields": {}, + "description": "Build the mapping from registered Terra biome color values." + }, + "MAP": { + "kind": "object", + "fields": { + "map": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "library-image:Color" + }, + "values": { + "kind": "ref", + "target": "terra:Biome" + } + }, + "required": true + } + } + } + } + } + } +} diff --git a/common/addons/biome-provider-pipeline/src/main/resources/META-INF/api/config.terradoc b/common/addons/biome-provider-pipeline/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..c41b54fa8 --- /dev/null +++ b/common/addons/biome-provider-pipeline/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,420 @@ +{ + "id": "biome-provider-pipeline", + "docVersion": 1, + "description": "Pipeline biome provider, sampler source and six grid-processing stages. Pipeline stages are distinct from world generation stages.", + "types": { + "terra:BiomeProvider": { + "kind": "union", + "values": { + "PIPELINE": { + "kind": "object", + "fields": { + "resolution": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1, + "summary": "Biome sample spacing in blocks. Higher values reduce work and detail; there is no template range validator." + }, + "blend": { + "schema": { + "kind": "object", + "fields": { + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler", + "nullable": true + }, + "required": false, + "summary": "Coordinate-warping sampler; defaults to an internal zero sampler." + }, + "amplitude": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + } + }, + "nullable": true + }, + "required": false + }, + "pipeline": { + "schema": { + "kind": "object", + "fields": { + "source": { + "schema": { + "kind": "type", + "target": "Source" + }, + "required": true + }, + "stages": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "Stage" + } + }, + "required": true, + "summary": "Ordered stages; required even when the list is empty." + } + } + }, + "required": true + } + } + } + } + }, + "Source": { + "kind": "union", + "discriminator": "type", + "values": { + "SAMPLER": { + "kind": "object", + "fields": { + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "biomes": { + "schema": { + "kind": "type", + "target": "WeightedPipelineBiomes" + }, + "required": true + } + } + } + } + }, + "Stage": { + "kind": "union", + "discriminator": "type", + "values": { + "FRACTAL_EXPAND": { + "kind": "object", + "fields": { + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler used to choose among replacements or neighboring biomes." + } + }, + "description": "Expands the biome grid using fractal interpolation." + }, + "SMOOTH": { + "kind": "object", + "fields": { + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler used to choose among replacements or neighboring biomes." + } + }, + "description": "Smooths the biome grid using neighboring biomes." + }, + "REPLACE": { + "kind": "object", + "fields": { + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler used to choose among replacements or neighboring biomes." + }, + "from": { + "schema": { + "kind": "type", + "target": "terra:Tag" + }, + "required": true, + "summary": "Tag identifying biomes to replace." + }, + "to": { + "schema": { + "kind": "type", + "target": "WeightedPipelineBiomes" + }, + "required": true, + "summary": "Replacement biomes; SELF preserves the current biome." + } + } + }, + "REPLACE_LIST": { + "kind": "object", + "fields": { + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler used to choose among replacements or neighboring biomes." + }, + "default-from": { + "schema": { + "kind": "type", + "target": "terra:Tag" + }, + "required": true, + "summary": "Tag to match when the current biome is not a key in to." + }, + "default-to": { + "schema": { + "kind": "type", + "target": "WeightedPipelineBiomes" + }, + "required": true, + "summary": "Replacement distribution for default-from." + }, + "to": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "PipelineBiome" + }, + "values": { + "kind": "type", + "target": "WeightedPipelineBiomes" + } + }, + "required": true, + "summary": "Explicit per-biome replacements, checked before the default tag." + } + } + }, + "BORDER": { + "kind": "object", + "fields": { + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler used to choose among replacements or neighboring biomes." + }, + "from": { + "schema": { + "kind": "type", + "target": "terra:Tag" + }, + "required": true, + "summary": "Tag to look for among the eight neighboring cells." + }, + "replace": { + "schema": { + "kind": "type", + "target": "terra:Tag" + }, + "required": true, + "summary": "Tag that the center biome must have." + }, + "to": { + "schema": { + "kind": "type", + "target": "WeightedPipelineBiomes" + }, + "required": true, + "summary": "Replacement biomes when the center and a neighbor match." + } + } + }, + "BORDER_LIST": { + "kind": "object", + "fields": { + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler used to choose among replacements or neighboring biomes." + }, + "from": { + "schema": { + "kind": "type", + "target": "terra:Tag" + }, + "required": true, + "summary": "Tag to look for among the eight neighboring cells." + }, + "default-replace": { + "schema": { + "kind": "type", + "target": "terra:Tag" + }, + "required": true, + "summary": "Required tag for the center biome, including explicit map entries." + }, + "default-to": { + "schema": { + "kind": "type", + "target": "WeightedPipelineBiomes" + }, + "required": true, + "summary": "Replacement when the center has no entry in replace." + }, + "replace": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "PipelineBiome" + }, + "values": { + "kind": "type", + "target": "WeightedPipelineBiomes" + } + }, + "required": true, + "summary": "Explicit center-biome replacements after tag and neighbor checks." + } + } + } + } + }, + "PipelineBiome": { + "kind": "oneOf", + "description": "Pipeline biome loader input: a registered biome identifier, SELF, or an unregistered placeholder string. Placeholders must be removed before producing final biomes.", + "options": [ + { + "kind": "ref", + "target": "terra:Biome" + }, + { + "kind": "literal", + "value": "SELF", + "description": "Keep the current biome when used as a stage replacement." + }, + { + "kind": "string", + "description": "An identifier not found in the biome registry becomes a placeholder with tags ALL and its own identifier." + } + ], + "examples": [ + "PLAINS", + "SELF", + "PLACEHOLDER" + ] + }, + "WeightedPipelineBiomes": { + "kind": "oneOf", + "description": "A pipeline biome, a pipeline-biome-to-integer-weight map, or a list of such maps. Singleton weights are ignored. Other weights are raw integers.", + "options": [ + { + "kind": "type", + "target": "PipelineBiome" + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "PipelineBiome" + }, + "values": { + "kind": "any", + "name": "Ignored singleton weight" + }, + "maxEntries": 1 + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "PipelineBiome" + }, + "values": { + "kind": "integer" + }, + "minEntries": 2 + }, + { + "kind": "list", + "element": { + "kind": "oneOf", + "options": [ + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "PipelineBiome" + }, + "values": { + "kind": "any", + "name": "Ignored singleton weight" + }, + "maxEntries": 1 + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "PipelineBiome" + }, + "values": { + "kind": "integer" + }, + "minEntries": 2 + } + ] + }, + "maxItems": 1 + }, + { + "kind": "list", + "element": { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "PipelineBiome" + }, + "values": { + "kind": "integer" + } + }, + "minItems": 2 + } + ] + } + } +} diff --git a/common/addons/biome-provider-single/src/main/resources/META-INF/api/config.terradoc b/common/addons/biome-provider-single/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..e682c2579 --- /dev/null +++ b/common/addons/biome-provider-single/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,25 @@ +{ + "id": "biome-provider-single", + "docVersion": 1, + "description": "A biome provider that returns one registered biome everywhere.", + "types": { + "terra:BiomeProvider": { + "kind": "union", + "values": { + "SINGLE": { + "kind": "object", + "fields": { + "biome": { + "schema": { + "kind": "ref", + "target": "terra:Biome" + }, + "required": true, + "summary": "Registered Terra biome to use everywhere." + } + } + } + } + } + } +} diff --git a/common/addons/chunk-generator-noise-3d/src/main/resources/META-INF/api/config.terradoc b/common/addons/chunk-generator-noise-3d/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..96e3ec409 --- /dev/null +++ b/common/addons/chunk-generator-noise-3d/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,388 @@ +{ + "id": "chunk-generator-noise-3d", + "docVersion": 1, + "description": "Registers NOISE_3D and contributes pack options and biome terrain, carving and palette fields whenever this addon loads. Existing core metadata documents blend.terrain.elevation (default 4).", + "types": { + "terra:PaletteReference": { + "kind": "oneOf", + "options": [ + { + "kind": "ref", + "target": "terra:Palette" + } + ] + }, + "HeightPalettes": { + "kind": "list", + "element": { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:PaletteReference" + }, + "values": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + } + }, + "description": "Palette references mapped to inclusive upper Y boundaries, in a sequence of maps. Duplicate heights replace earlier entries. At least one entry is needed, and the highest boundary must cover the builder's range through Y=255. Boundary values may be numeric expressions.", + "minItems": 1 + }, + "SlantLayer": { + "kind": "object", + "fields": { + "threshold": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Slant threshold. Derivative uses the floor threshold; DotProduct uses the ceiling threshold. Multiple slant layers must use distinct thresholds." + }, + "palette": { + "schema": { + "kind": "type", + "target": "HeightPalettes" + }, + "required": true + } + } + }, + "terra:Biome": { + "kind": "object", + "fields": { + "terrain": { + "schema": { + "kind": "object", + "fields": { + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Required terrain-density sampler." + }, + "sampler-2d": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler", + "nullable": true + }, + "required": false, + "summary": "Elevation sampler; defaults to an internal zero sampler." + }, + "blend": { + "schema": { + "kind": "object", + "fields": { + "distance": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 3, + "summary": "Blend radius in sample steps." + }, + "weight": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + }, + "step": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 4, + "summary": "Distance between blend samples." + }, + "weight-2d": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + } + }, + "nullable": true + }, + "required": false + } + } + }, + "required": true + }, + "carving": { + "schema": { + "kind": "object", + "fields": { + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler", + "nullable": true + }, + "required": false, + "summary": "Carving sampler; defaults to an internal zero sampler." + }, + "update-palette": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false, + "summary": "Update palette depth when carving removes blocks." + } + }, + "nullable": true + }, + "required": false + }, + "palette": { + "schema": { + "kind": "type", + "target": "HeightPalettes" + }, + "required": true, + "summary": "Height-indexed terrain palettes." + }, + "slant": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "SlantLayer" + }, + "nullable": true + }, + "required": false, + "default": [], + "summary": "Optional palettes selected by terrain slant." + }, + "slant-depth": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2147483647, + "summary": "Maximum depth at which to apply a slant palette." + }, + "ocean": { + "schema": { + "kind": "object", + "fields": { + "level": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Sea level." + }, + "palette": { + "schema": { + "kind": "type", + "target": "terra:PaletteReference", + "nullable": true + }, + "required": false, + "summary": "Defaults to an internal palette returning platform air." + } + }, + "nullable": true + }, + "required": false + } + } + }, + "Noise3DGenerator": { + "kind": "literal", + "value": "NOISE_3D", + "description": "Registered chunk generator provider identifier. generator in pack.yml is a scalar identifier, not an inline object." + }, + "terra:ChunkGenerator": { + "kind": "string", + "description": "This addon registers the NOISE_3D chunk generator provider identifier.", + "examples": [ + "NOISE_3D" + ] + } + }, + "files": { + "pack.yml": { + "kind": "object", + "fields": { + "carving": { + "schema": { + "kind": "object", + "fields": { + "resolution": { + "schema": { + "kind": "object", + "fields": { + "horizontal": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 4 + }, + "vertical": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2 + } + }, + "nullable": true + }, + "required": false + } + }, + "nullable": true + }, + "required": false + }, + "slant": { + "schema": { + "kind": "object", + "fields": { + "calculation-method": { + "schema": { + "kind": "enum", + "values": [ + "DotProduct", + "Derivative" + ], + "nullable": true + }, + "required": false, + "default": "Derivative", + "summary": "Slant calculation method; spelling is case-sensitive." + }, + "disable-palettes": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false, + "summary": "Disable use of slant palettes; the biome slant fields are still loaded." + } + }, + "nullable": true + }, + "required": false + } + } + }, + "BIOME": { + "kind": "object", + "fields": {}, + "extends": [ + "terra:Biome" + ] + } + } +} diff --git a/common/addons/config-biome/src/main/resources/META-INF/api/config.terradoc b/common/addons/config-biome/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..3b31e93a4 --- /dev/null +++ b/common/addons/config-biome/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,120 @@ +{ + "id": "config-biome", + "docVersion": 1, + "description": "Registered biome configurations and a height-indexed palette-holder loader. Other addons contribute terrain, decoration and platform fields.", + "types": { + "terra:Biome": { + "kind": "object", + "fields": { + "id": { + "schema": { + "kind": "string", + "pattern": "^[a-zA-Z0-9_-]*$" + }, + "required": true, + "summary": "Registry identifier; must be present on this file even when inherited." + }, + "extends": { + "schema": { + "kind": "list", + "element": { + "kind": "string" + }, + "nullable": true + }, + "required": false, + "default": [], + "summary": "Parent configuration identifiers. This field is final and is read from the current file." + }, + "vanilla": { + "schema": { + "kind": "type", + "target": "terra:PlatformBiome" + }, + "required": true, + "summary": "Platform biome used for vanilla behavior." + }, + "color": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Biome mapping color; runtime forces the alpha byte to 0xff. Final: not inherited." + }, + "tags": { + "schema": { + "kind": "set", + "element": { + "kind": "type", + "target": "terra:Tag" + }, + "nullable": true + }, + "required": false, + "default": [], + "summary": "User tags; runtime also adds ALL and BIOME:." + } + } + }, + "PaletteHolder": { + "kind": "list", + "element": { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:PaletteReference" + }, + "values": { + "kind": "integer" + } + }, + "description": "Sequence of palette-reference to inclusive upper-Y maps. This loader reads raw integer map values, without numeric expression preprocessing. Heights select the first upper boundary at or above Y; duplicate heights replace earlier entries. Empty input cannot build a holder." + }, + "terra:PaletteReference": { + "kind": "oneOf", + "options": [ + { + "kind": "ref", + "target": "terra:Palette" + } + ] + } + }, + "files": { + "BIOME": { + "kind": "object", + "fields": { + "type": { + "schema": { + "kind": "literal", + "value": "BIOME" + }, + "required": true + }, + "abstract": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false, + "summary": "Abstract configurations are inherited rather than registered." + } + }, + "extends": [ + "terra:Biome" + ] + } + } +} diff --git a/common/addons/config-distributors/src/main/resources/META-INF/api/config.terradoc b/common/addons/config-distributors/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..186d30f49 --- /dev/null +++ b/common/addons/config-distributors/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,206 @@ +{ + "id": "config-distributors", + "docVersion": 1, + "description": "Eight registered distributor variants and explicit x/z point objects.", + "types": { + "terra:Distributor": { + "kind": "union", + "discriminator": "type", + "values": { + "AND": { + "kind": "object", + "fields": { + "distributors": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "terra:Distributor" + }, + "minItems": 1 + }, + "required": true + } + }, + "description": "Combines a nonempty list of distributor predicates using AND." + }, + "OR": { + "kind": "object", + "fields": { + "distributors": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "terra:Distributor" + }, + "minItems": 1 + }, + "required": true + } + }, + "description": "Combines a nonempty list of distributor predicates using OR." + }, + "XOR": { + "kind": "object", + "fields": { + "distributors": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "terra:Distributor" + }, + "minItems": 1 + }, + "required": true + } + }, + "description": "Combines a nonempty list of distributor predicates using XOR." + }, + "YES": { + "kind": "object", + "fields": {}, + "description": "Accepts every column." + }, + "NO": { + "kind": "object", + "fields": {}, + "description": "Rejects every column." + }, + "SAMPLER": { + "kind": "object", + "fields": { + "threshold": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Accepts a column when its 2D sampler value is strictly less than threshold." + }, + "POINTS": { + "kind": "object", + "fields": { + "points": { + "schema": { + "kind": "set", + "element": { + "kind": "type", + "target": "Point" + } + }, + "required": true + } + }, + "description": "Matches the configured x/z positions." + }, + "PADDED_GRID": { + "kind": "object", + "fields": { + "width": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "padding": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + } + }, + "description": "Chooses a seeded point inside each width-sized square separated by padding. No template numeric bounds are enforced; zero width or cell width can fail during sampling." + } + } + }, + "Point": { + "kind": "object", + "fields": { + "x": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "z": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + } + } + } + } +} diff --git a/common/addons/config-feature/src/main/resources/META-INF/api/config.terradoc b/common/addons/config-feature/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..74a66500d --- /dev/null +++ b/common/addons/config-feature/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,183 @@ +{ + "id": "config-feature", + "docVersion": 1, + "description": "FEATURE files register configured placement features, with inline distributor/locator definitions and weighted raw structure references.", + "types": { + "terra:Feature": { + "kind": "object", + "fields": { + "id": { + "schema": { + "kind": "string", + "pattern": "^[a-zA-Z0-9_-]*$" + }, + "required": true, + "summary": "Registry identifier; final and not inherited." + }, + "distributor": { + "schema": { + "kind": "type", + "target": "terra:Distributor" + }, + "required": true + }, + "locator": { + "schema": { + "kind": "type", + "target": "terra:Locator" + }, + "required": true + }, + "structures": { + "schema": { + "kind": "object", + "fields": { + "distribution": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler that chooses a structure from the weighted collection." + }, + "structures": { + "schema": { + "kind": "type", + "target": "WeightedStructures" + }, + "required": true + } + } + }, + "required": true + } + } + }, + "terra:StructureReference": { + "kind": "oneOf", + "options": [ + { + "kind": "ref", + "target": "terra:Structure" + } + ] + }, + "WeightedStructures": { + "kind": "oneOf", + "description": "A raw structure reference, reference-to-weight map, or list of maps. Singleton weights are ignored; all other weights are raw integers.", + "options": [ + { + "kind": "type", + "target": "terra:StructureReference" + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:StructureReference" + }, + "values": { + "kind": "any", + "name": "Ignored singleton weight" + }, + "maxEntries": 1 + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:StructureReference" + }, + "values": { + "kind": "integer" + }, + "minEntries": 2 + }, + { + "kind": "list", + "element": { + "kind": "oneOf", + "options": [ + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:StructureReference" + }, + "values": { + "kind": "any", + "name": "Ignored singleton weight" + }, + "maxEntries": 1 + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:StructureReference" + }, + "values": { + "kind": "integer" + }, + "minEntries": 2 + } + ] + }, + "maxItems": 1 + }, + { + "kind": "list", + "element": { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:StructureReference" + }, + "values": { + "kind": "integer" + } + }, + "minItems": 2 + } + ] + } + }, + "files": { + "FEATURE": { + "kind": "object", + "fields": { + "type": { + "schema": { + "kind": "literal", + "value": "FEATURE" + }, + "required": true + }, + "extends": { + "schema": { + "kind": "list", + "element": { + "kind": "string" + }, + "nullable": true + }, + "required": false, + "default": [], + "summary": "Parent configuration IDs; non-final fields may be inherited." + }, + "abstract": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false, + "summary": "Abstract configurations supply inherited values and are not registered." + } + }, + "extends": [ + "terra:Feature" + ] + } + } +} diff --git a/common/addons/config-flora/src/main/resources/META-INF/api/config.terradoc b/common/addons/config-flora/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..47470ef4f --- /dev/null +++ b/common/addons/config-flora/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,207 @@ +{ + "id": "config-flora", + "docVersion": 1, + "description": "FLORA configurations register layered block structures in the raw structure registry.", + "types": { + "Flora": { + "kind": "object", + "fields": { + "id": { + "schema": { + "kind": "string", + "pattern": "^[a-zA-Z0-9_-]*$" + }, + "required": true, + "summary": "Registry identifier; final and not inherited." + }, + "rotatable": { + "schema": { + "kind": "type", + "target": "terra:MaterialSet", + "nullable": true + }, + "required": false, + "default": [], + "summary": "Block types whose states may be rotated." + }, + "physics": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false + }, + "ceiling": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false + }, + "layers": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "BlockLayer" + } + }, + "required": true + }, + "layer-distribution": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + } + }, + "BlockLayer": { + "kind": "object", + "fields": { + "layers": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "materials": { + "schema": { + "kind": "type", + "target": "WeightedBlocks" + }, + "required": true + } + } + }, + "WeightedBlocks": { + "kind": "oneOf", + "description": "A block state, block-to-weight map, or list of maps. Singleton weights are ignored; all other weights are raw integers.", + "options": [ + { + "kind": "type", + "target": "terra:Block" + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:Block" + }, + "values": { + "kind": "any", + "name": "Ignored singleton weight" + }, + "maxEntries": 1 + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:Block" + }, + "values": { + "kind": "integer" + }, + "minEntries": 2 + }, + { + "kind": "list", + "element": { + "kind": "oneOf", + "options": [ + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:Block" + }, + "values": { + "kind": "any", + "name": "Ignored singleton weight" + }, + "maxEntries": 1 + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:Block" + }, + "values": { + "kind": "integer" + }, + "minEntries": 2 + } + ] + }, + "maxItems": 1 + }, + { + "kind": "list", + "element": { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:Block" + }, + "values": { + "kind": "integer" + } + }, + "minItems": 2 + } + ] + } + }, + "files": { + "FLORA": { + "kind": "object", + "fields": { + "type": { + "schema": { + "kind": "literal", + "value": "FLORA" + }, + "required": true + }, + "extends": { + "schema": { + "kind": "list", + "element": { + "kind": "string" + }, + "nullable": true + }, + "required": false, + "default": [], + "summary": "Parent configuration IDs; non-final fields may be inherited." + }, + "abstract": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false, + "summary": "Abstract configurations supply inherited values and are not registered." + } + }, + "extends": [ + "Flora" + ] + } + } +} diff --git a/common/addons/config-locators/src/main/resources/META-INF/api/config.terradoc b/common/addons/config-locators/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..9a0ce3690 --- /dev/null +++ b/common/addons/config-locators/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,388 @@ +{ + "id": "config-locators", + "docVersion": 1, + "description": "Eleven registered vertical locator variants and eight inline block-pattern variants.", + "types": { + "terra:Locator": { + "kind": "union", + "discriminator": "type", + "values": { + "SURFACE": { + "kind": "object", + "fields": { + "range": { + "schema": { + "kind": "type", + "target": "terra:Range" + }, + "required": true + } + }, + "description": "Finds air above a non-air block within the search range. May return multiple surfaces." + }, + "TOP": { + "kind": "object", + "fields": { + "range": { + "schema": { + "kind": "type", + "target": "terra:Range" + }, + "required": true + } + }, + "description": "Finds air above a non-air block within the search range. Returns only the top result; its implementation starts at range.max inclusively." + }, + "RANDOM": { + "kind": "object", + "fields": { + "height": { + "schema": { + "kind": "type", + "target": "terra:Range" + }, + "required": true + }, + "amount": { + "schema": { + "kind": "type", + "target": "terra:Range" + }, + "required": true + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + } + }, + "description": "Chooses seeded heights using a uniform distribution." + }, + "GAUSSIAN_RANDOM": { + "kind": "object", + "fields": { + "height": { + "schema": { + "kind": "type", + "target": "terra:Range" + }, + "required": true + }, + "amount": { + "schema": { + "kind": "type", + "target": "terra:Range" + }, + "required": true + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "standard-deviation": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + } + }, + "description": "Chooses seeded heights using a Gaussian distribution." + }, + "PATTERN": { + "kind": "object", + "fields": { + "range": { + "schema": { + "kind": "type", + "target": "terra:Range" + }, + "required": true + }, + "pattern": { + "schema": { + "kind": "type", + "target": "Pattern" + }, + "required": true + } + } + }, + "ADJACENT_PATTERN": { + "kind": "object", + "fields": { + "range": { + "schema": { + "kind": "type", + "target": "terra:Range" + }, + "required": true + }, + "pattern": { + "schema": { + "kind": "type", + "target": "Pattern" + }, + "required": true + }, + "match-all": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false, + "summary": "Require all four horizontal neighbors instead of at least one." + } + } + }, + "SAMPLER": { + "kind": "object", + "fields": { + "samplers": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "terra:NoiseSampler" + } + }, + "required": true + } + }, + "description": "Each 2D sampler output is floored to a height; results outside the column are discarded." + }, + "SAMPLER_3D": { + "kind": "object", + "fields": { + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Accepts each height where the 3D sampler returns a value greater than zero." + }, + "AND": { + "kind": "object", + "fields": { + "locators": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "terra:Locator" + }, + "minItems": 1 + }, + "required": true + } + }, + "description": "Combines a nonempty list of locator results using AND." + }, + "OR": { + "kind": "object", + "fields": { + "locators": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "terra:Locator" + }, + "minItems": 1 + }, + "required": true + } + }, + "description": "Combines a nonempty list of locator results using OR." + }, + "XOR": { + "kind": "object", + "fields": { + "locators": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "terra:Locator" + }, + "minItems": 1 + }, + "required": true + } + }, + "description": "Combines a nonempty list of locator results using XOR." + } + } + }, + "Pattern": { + "kind": "union", + "discriminator": "type", + "values": { + "MATCH_AIR": { + "kind": "object", + "fields": { + "offset": { + "schema": { + "kind": "type", + "target": "terra:Range" + }, + "required": true + } + }, + "description": "Checks air in the relative offset range." + }, + "MATCH_SOLID": { + "kind": "object", + "fields": { + "offset": { + "schema": { + "kind": "type", + "target": "terra:Range" + }, + "required": true + } + }, + "description": "Checks solid blocks in the relative offset range." + }, + "MATCH": { + "kind": "object", + "fields": { + "block": { + "schema": { + "kind": "type", + "target": "terra:Block" + }, + "required": true + }, + "offset": { + "schema": { + "kind": "type", + "target": "terra:Range" + }, + "required": true + } + } + }, + "MATCH_SET": { + "kind": "object", + "fields": { + "blocks": { + "schema": { + "kind": "type", + "target": "terra:MaterialSet" + }, + "required": true + }, + "offset": { + "schema": { + "kind": "type", + "target": "terra:Range" + }, + "required": true + } + } + }, + "AND": { + "kind": "object", + "fields": { + "patterns": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "Pattern" + }, + "minItems": 1 + }, + "required": true + } + }, + "description": "Combines a nonempty list of patterns using AND." + }, + "OR": { + "kind": "object", + "fields": { + "patterns": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "Pattern" + }, + "minItems": 1 + }, + "required": true + } + }, + "description": "Combines a nonempty list of patterns using OR." + }, + "XOR": { + "kind": "object", + "fields": { + "patterns": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "Pattern" + }, + "minItems": 1 + }, + "required": true + } + }, + "description": "Combines a nonempty list of patterns using XOR." + }, + "NOT": { + "kind": "object", + "fields": { + "pattern": { + "schema": { + "kind": "type", + "target": "Pattern" + }, + "required": true + } + } + } + } + } + } +} diff --git a/common/addons/config-noise-function/src/main/resources/META-INF/api/config.terradoc b/common/addons/config-noise-function/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..529e98041 --- /dev/null +++ b/common/addons/config-noise-function/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,6039 @@ +{ + "id": "config-noise-function", + "docVersion": 1, + "description": "Inline noise samplers and pack-level named samplers and expression functions.", + "types": { + "terra:NoiseSampler": { + "kind": "union", + "values": { + "LINEAR": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "min": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "max": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + } + }, + "description": "Transforms or clamps sampler output using min and max." + }, + "LINEAR_MAP": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "from": { + "schema": { + "kind": "object", + "fields": { + "a": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": -1 + }, + "b": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + } + }, + "nullable": true + }, + "required": false + }, + "to": { + "schema": { + "kind": "object", + "fields": { + "a": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "b": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + } + } + }, + "required": true + } + }, + "description": "Maps values from the source interval to the destination interval." + }, + "NORMAL": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "mean": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "standard-deviation": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "groups": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 16384 + } + }, + "description": "Normalizes sampler output using the specified distribution." + }, + "CLAMP": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "min": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "max": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + } + }, + "description": "Transforms or clamps sampler output using min and max." + }, + "PROBABILITY": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + } + }, + "description": "Converts sampler output to probability values." + }, + "SCALE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "amplitude": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + } + }, + "description": "Multiplies sampler output by an amplitude." + }, + "POSTERIZATION": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "steps": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + } + }, + "description": "Quantizes sampler output into steps." + }, + "CUBIC_SPLINE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "points": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "CubicSplinePoint" + } + }, + "required": true + } + }, + "description": "Maps sampler output through cubic spline control points." + }, + "DOMAIN_WARP": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "warp": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "amplitude": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + } + }, + "description": "Warps sample coordinates using another sampler." + }, + "FBM": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + }, + "octaves": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 3 + }, + "gain": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.5 + }, + "lacunarity": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2 + }, + "weighted-strength": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Fractal Brownian motion." + }, + "PING_PONG": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + }, + "octaves": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 3 + }, + "gain": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.5 + }, + "lacunarity": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2 + }, + "weighted-strength": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "ping-pong": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2 + } + }, + "description": "Ping-pong fractal noise." + }, + "RIDGED": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + }, + "octaves": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 3 + }, + "gain": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.5 + }, + "lacunarity": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2 + }, + "weighted-strength": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Ridged fractal noise." + }, + "OPEN_SIMPLEX_2": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "OpenSimplex2 noise." + }, + "OPEN_SIMPLEX_2S": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "OpenSimplex2S noise." + }, + "PERLIN": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "Perlin noise." + }, + "SIMPLEX": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "Simplex noise." + }, + "GABOR": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + }, + "rotation": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.25 + }, + "isotropic": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": true + }, + "deviation": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + }, + "impulses": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 64 + }, + "frequency_0": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.625 + }, + "a": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.1 + } + }, + "description": "Gabor noise." + }, + "PSEUDOEROSION": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + }, + "octaves": { + "schema": { + "kind": "integer", + "nullable": true + }, + "required": false, + "default": 4 + }, + "lacunarity": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 2 + }, + "gain": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 0.5 + }, + "slope-strength": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 1 + }, + "branch-strength": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 1 + }, + "strength": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 0.04 + }, + "erosion-frequency": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 0.02 + }, + "jitter": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 1 + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler", + "nullable": true + }, + "required": false, + "summary": "Must support derivatives. Defaults to internal OpenSimplex2 with frequency 0.02 and salt 0." + }, + "slope-mask": { + "schema": { + "kind": "object", + "fields": { + "enable": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": true + }, + "none": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": -0.5 + }, + "full": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 1 + } + }, + "nullable": true + }, + "required": false + }, + "average-impulses": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": true + } + }, + "description": "Pseudo erosion based on a differentiable height sampler. Derivative support is checked at runtime." + }, + "VALUE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "Value noise." + }, + "VALUE_CUBIC": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "Cubic value noise." + }, + "CELLULAR": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + }, + "distance": { + "schema": { + "kind": "type", + "target": "DistanceFunction", + "nullable": true + }, + "required": false, + "default": "EuclideanSq" + }, + "return": { + "schema": { + "kind": "enum", + "values": [ + "CellValue", + "Distance", + "Distance2", + "Distance2Add", + "Distance2Sub", + "Distance2Mul", + "Distance2Div", + "NoiseLookup", + "LocalNoiseLookup", + "Distance3", + "Distance3Add", + "Distance3Sub", + "Distance3Mul", + "Distance3Div", + "Angle" + ], + "nullable": true + }, + "required": false, + "default": "Distance" + }, + "jitter": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + }, + "lookup": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler", + "nullable": true + }, + "required": false, + "summary": "Defaults to an internal OpenSimplex2 sampler with frequency 0.02 and salt 0." + }, + "salt-lookup": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": true + } + }, + "description": "Cellular noise with selectable distance and return modes." + }, + "WHITE_NOISE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "White noise." + }, + "POSITIVE_WHITE_NOISE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "Positive white noise." + }, + "GAUSSIAN": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "Gaussian noise." + }, + "DISTANCE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + }, + "distance-function": { + "schema": { + "kind": "type", + "target": "DistanceFunction", + "nullable": true + }, + "required": false, + "default": "Euclidean" + }, + "point": { + "schema": { + "kind": "object", + "fields": { + "x": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "y": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "z": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + } + }, + "nullable": true + }, + "required": false + }, + "normalize": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false + }, + "radius": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 100 + } + }, + "description": "Distance from a configured point. The inherited frequency field is loaded but not passed to DistanceSampler." + }, + "CONSTANT": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "value": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + } + }, + "description": "Returns a constant value." + }, + "KERNEL": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "kernel": { + "schema": { + "kind": "list", + "element": { + "kind": "list", + "element": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "minItems": 1 + }, + "minItems": 1 + }, + "required": true, + "summary": "Nonempty rectangular matrix; all rows must have the same length." + }, + "factor": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + } + }, + "description": "Applies a rectangular sampling kernel." + }, + "LINEAR_HEIGHTMAP": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler", + "nullable": true + }, + "required": false, + "summary": "Defaults to an internal sampler returning zero." + }, + "base": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "scale": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + } + }, + "description": "Produces a linear heightmap using a base height and scaled sampler." + }, + "TRANSLATE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "x": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "y": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "z": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + } + }, + "description": "Translates sample coordinates." + }, + "ADD": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "left": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "right": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Adds the left and right sampler outputs." + }, + "SUB": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "left": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "right": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Subtracts the left and right sampler outputs." + }, + "MUL": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "left": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "right": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Multiplies the left and right sampler outputs." + }, + "DIV": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "left": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "right": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Divides the left and right sampler outputs." + }, + "MAX": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "left": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "right": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Takes the maximum of the left and right sampler outputs." + }, + "MIN": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "left": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "right": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Takes the minimum of the left and right sampler outputs." + }, + "CACHE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler", + "nullable": true + }, + "required": false, + "summary": "No fallback sampler is supplied. Omitting it leaves null and sampling will fail.", + "default": null + } + }, + "description": "Experimental sampler cache. Match sampling dimensionality to dimensions." + }, + "EXPRESSION": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "expression": { + "schema": { + "kind": "type", + "target": "terra:Expression" + }, + "required": true + }, + "variables": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "nullable": true + }, + "required": false, + "default": {} + }, + "samplers": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "type", + "target": "DimensionedSampler" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Local named samplers override pack samplers with the same name." + }, + "functions": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "type", + "target": "Function" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Local functions override pack functions with the same name." + } + }, + "description": "Paralithic coordinate expression with local variables, samplers and functions." + }, + "EXPRESSION_NORMALIZER": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "expression": { + "schema": { + "kind": "type", + "target": "terra:Expression" + }, + "required": true + }, + "variables": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "nullable": true + }, + "required": false, + "default": {} + }, + "samplers": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "type", + "target": "DimensionedSampler" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Local named samplers override pack samplers with the same name." + }, + "functions": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "type", + "target": "Function" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Local functions override pack functions with the same name." + } + }, + "description": "Paralithic expression transforming sampler output." + } + } + }, + "DimensionedSampler": { + "kind": "union", + "discriminator": "type", + "description": "A named sampler used as an expression function. dimensions is mandatory because DimensionApplicableSampler reads it without a default.", + "values": { + "LINEAR": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "min": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "max": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + } + }, + "description": "Transforms or clamps sampler output using min and max." + }, + "LINEAR_MAP": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "from": { + "schema": { + "kind": "object", + "fields": { + "a": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": -1 + }, + "b": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + } + }, + "nullable": true + }, + "required": false + }, + "to": { + "schema": { + "kind": "object", + "fields": { + "a": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "b": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + } + } + }, + "required": true + } + }, + "description": "Maps values from the source interval to the destination interval." + }, + "NORMAL": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "mean": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "standard-deviation": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "groups": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 16384 + } + }, + "description": "Normalizes sampler output using the specified distribution." + }, + "CLAMP": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "min": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "max": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + } + }, + "description": "Transforms or clamps sampler output using min and max." + }, + "PROBABILITY": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + } + }, + "description": "Converts sampler output to probability values." + }, + "SCALE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "amplitude": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + } + }, + "description": "Multiplies sampler output by an amplitude." + }, + "POSTERIZATION": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "steps": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + } + }, + "description": "Quantizes sampler output into steps." + }, + "CUBIC_SPLINE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "points": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "CubicSplinePoint" + } + }, + "required": true + } + }, + "description": "Maps sampler output through cubic spline control points." + }, + "DOMAIN_WARP": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "warp": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "amplitude": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + } + }, + "description": "Warps sample coordinates using another sampler." + }, + "FBM": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + }, + "octaves": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 3 + }, + "gain": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.5 + }, + "lacunarity": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2 + }, + "weighted-strength": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Fractal Brownian motion." + }, + "PING_PONG": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + }, + "octaves": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 3 + }, + "gain": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.5 + }, + "lacunarity": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2 + }, + "weighted-strength": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "ping-pong": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2 + } + }, + "description": "Ping-pong fractal noise." + }, + "RIDGED": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + }, + "octaves": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 3 + }, + "gain": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.5 + }, + "lacunarity": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 2 + }, + "weighted-strength": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Ridged fractal noise." + }, + "OPEN_SIMPLEX_2": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "OpenSimplex2 noise." + }, + "OPEN_SIMPLEX_2S": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "OpenSimplex2S noise." + }, + "PERLIN": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "Perlin noise." + }, + "SIMPLEX": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "Simplex noise." + }, + "GABOR": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + }, + "rotation": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.25 + }, + "isotropic": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": true + }, + "deviation": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + }, + "impulses": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 64 + }, + "frequency_0": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.625 + }, + "a": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.1 + } + }, + "description": "Gabor noise." + }, + "PSEUDOEROSION": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + }, + "octaves": { + "schema": { + "kind": "integer", + "nullable": true + }, + "required": false, + "default": 4 + }, + "lacunarity": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 2 + }, + "gain": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 0.5 + }, + "slope-strength": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 1 + }, + "branch-strength": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 1 + }, + "strength": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 0.04 + }, + "erosion-frequency": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 0.02 + }, + "jitter": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 1 + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler", + "nullable": true + }, + "required": false, + "summary": "Must support derivatives. Defaults to internal OpenSimplex2 with frequency 0.02 and salt 0." + }, + "slope-mask": { + "schema": { + "kind": "object", + "fields": { + "enable": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": true + }, + "none": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": -0.5 + }, + "full": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 1 + } + }, + "nullable": true + }, + "required": false + }, + "average-impulses": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": true + } + }, + "description": "Pseudo erosion based on a differentiable height sampler. Derivative support is checked at runtime." + }, + "VALUE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "Value noise." + }, + "VALUE_CUBIC": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "Cubic value noise." + }, + "CELLULAR": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + }, + "distance": { + "schema": { + "kind": "type", + "target": "DistanceFunction", + "nullable": true + }, + "required": false, + "default": "EuclideanSq" + }, + "return": { + "schema": { + "kind": "enum", + "values": [ + "CellValue", + "Distance", + "Distance2", + "Distance2Add", + "Distance2Sub", + "Distance2Mul", + "Distance2Div", + "NoiseLookup", + "LocalNoiseLookup", + "Distance3", + "Distance3Add", + "Distance3Sub", + "Distance3Mul", + "Distance3Div", + "Angle" + ], + "nullable": true + }, + "required": false, + "default": "Distance" + }, + "jitter": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + }, + "lookup": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler", + "nullable": true + }, + "required": false, + "summary": "Defaults to an internal OpenSimplex2 sampler with frequency 0.02 and salt 0." + }, + "salt-lookup": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": true + } + }, + "description": "Cellular noise with selectable distance and return modes." + }, + "WHITE_NOISE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "White noise." + }, + "POSITIVE_WHITE_NOISE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "Positive white noise." + }, + "GAUSSIAN": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + } + }, + "description": "Gaussian noise." + }, + "DISTANCE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0.02, + "summary": "Coordinate frequency before sampling." + }, + "salt": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Salt added to the seed." + }, + "distance-function": { + "schema": { + "kind": "type", + "target": "DistanceFunction", + "nullable": true + }, + "required": false, + "default": "Euclidean" + }, + "point": { + "schema": { + "kind": "object", + "fields": { + "x": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "y": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "z": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + } + }, + "nullable": true + }, + "required": false + }, + "normalize": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false + }, + "radius": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 100 + } + }, + "description": "Distance from a configured point. The inherited frequency field is loaded but not passed to DistanceSampler." + }, + "CONSTANT": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "value": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + } + }, + "description": "Returns a constant value." + }, + "KERNEL": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "kernel": { + "schema": { + "kind": "list", + "element": { + "kind": "list", + "element": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "minItems": 1 + }, + "minItems": 1 + }, + "required": true, + "summary": "Nonempty rectangular matrix; all rows must have the same length." + }, + "factor": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "frequency": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + } + }, + "description": "Applies a rectangular sampling kernel." + }, + "LINEAR_HEIGHTMAP": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler", + "nullable": true + }, + "required": false, + "summary": "Defaults to an internal sampler returning zero." + }, + "base": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "scale": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1 + } + }, + "description": "Produces a linear heightmap using a base height and scaled sampler." + }, + "TRANSLATE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "x": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "y": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + }, + "z": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 0 + } + }, + "description": "Translates sample coordinates." + }, + "ADD": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "left": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "right": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Adds the left and right sampler outputs." + }, + "SUB": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "left": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "right": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Subtracts the left and right sampler outputs." + }, + "MUL": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "left": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "right": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Multiplies the left and right sampler outputs." + }, + "DIV": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "left": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "right": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Divides the left and right sampler outputs." + }, + "MAX": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "left": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "right": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Takes the maximum of the left and right sampler outputs." + }, + "MIN": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "left": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + }, + "right": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true + } + }, + "description": "Takes the minimum of the left and right sampler outputs." + }, + "CACHE": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler", + "nullable": true + }, + "required": false, + "summary": "No fallback sampler is supplied. Omitting it leaves null and sampling will fail.", + "default": null + } + }, + "description": "Experimental sampler cache. Match sampling dimensionality to dimensions." + }, + "EXPRESSION": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "expression": { + "schema": { + "kind": "type", + "target": "terra:Expression" + }, + "required": true + }, + "variables": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "nullable": true + }, + "required": false, + "default": {} + }, + "samplers": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "type", + "target": "DimensionedSampler" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Local named samplers override pack samplers with the same name." + }, + "functions": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "type", + "target": "Function" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Local functions override pack functions with the same name." + } + }, + "description": "Paralithic coordinate expression with local variables, samplers and functions." + }, + "EXPRESSION_NORMALIZER": { + "kind": "object", + "fields": { + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "enum", + "values": [ + 2, + 3 + ] + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of dimensions; runtime accepts only 2 or 3." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler" + }, + "required": true, + "summary": "Sampler whose output is transformed." + }, + "expression": { + "schema": { + "kind": "type", + "target": "terra:Expression" + }, + "required": true + }, + "variables": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "nullable": true + }, + "required": false, + "default": {} + }, + "samplers": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "type", + "target": "DimensionedSampler" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Local named samplers override pack samplers with the same name." + }, + "functions": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "type", + "target": "Function" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Local functions override pack functions with the same name." + } + }, + "description": "Paralithic expression transforming sampler output." + } + } + }, + "DistanceFunction": { + "kind": "enum", + "values": [ + "Euclidean", + "EuclideanSq", + "Manhattan", + "Hybrid" + ] + }, + "CubicSplinePoint": { + "kind": "object", + "fields": { + "from": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "to": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + }, + "gradient": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true + } + } + }, + "Function": { + "kind": "object", + "fields": { + "arguments": { + "schema": { + "kind": "list", + "element": { + "kind": "string" + } + }, + "required": true, + "summary": "Ordered argument names for this function." + }, + "expression": { + "schema": { + "kind": "type", + "target": "terra:Expression" + }, + "required": true + }, + "functions": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "type", + "target": "Function" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Nested function definitions." + } + } + } + }, + "files": { + "pack.yml": { + "kind": "object", + "fields": { + "samplers": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "type", + "target": "DimensionedSampler" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Named samplers callable from expressions; each requires dimensions." + }, + "functions": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "type", + "target": "Function" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Pack-wide expression functions." + } + } + } + } +} diff --git a/common/addons/config-number-predicate/src/main/resources/META-INF/api/config.terradoc b/common/addons/config-number-predicate/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..ef1f15937 --- /dev/null +++ b/common/addons/config-number-predicate/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,16 @@ +{ + "id": "config-number-predicate", + "docVersion": 1, + "description": "Loads numeric predicates from Paralithic expression strings.", + "types": { + "NumberPredicate": { + "kind": "expr", + "name": "Paralithic", + "description": "String expression with invocation variable value. Evaluation is true when the numeric result is nonzero. YAML booleans and numeric values are rejected. Uses pack expression parse options, but this loader does not inject pack variables or noise functions.", + "examples": [ + "value > 3", + "value >= 0 && value < 1" + ] + } + } +} diff --git a/common/addons/config-ore/src/main/resources/META-INF/api/config.terradoc b/common/addons/config-ore/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..5ec19e503 --- /dev/null +++ b/common/addons/config-ore/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,253 @@ +{ + "id": "config-ore", + "docVersion": 1, + "description": "ORE and SCATTERED_ORE configurations register raw structures. Scattered size remains required despite its field initializer.", + "types": { + "Ore": { + "kind": "object", + "fields": { + "id": { + "schema": { + "kind": "string", + "pattern": "^[a-zA-Z0-9_-]*$" + }, + "required": true, + "summary": "Registry identifier; final and not inherited." + }, + "material": { + "schema": { + "kind": "type", + "target": "terra:Block" + }, + "required": true + }, + "material-overrides": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:Block" + }, + "values": { + "kind": "type", + "target": "terra:Block" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Override material by replaced block type. Key state properties are reduced to the block type." + }, + "replace": { + "schema": { + "kind": "type", + "target": "terra:MaterialSet" + }, + "required": true + }, + "physics": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false + }, + "size": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Ore vein size." + }, + "exposed": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1, + "summary": "Chance of accepting ore bordering air: 0 rejects, 1 accepts. Source does not enforce a 0\u20131 bound." + } + } + }, + "ScatteredOre": { + "kind": "object", + "fields": { + "id": { + "schema": { + "kind": "string", + "pattern": "^[a-zA-Z0-9_-]*$" + }, + "required": true, + "summary": "Registry identifier; final and not inherited." + }, + "material": { + "schema": { + "kind": "type", + "target": "terra:Block" + }, + "required": true + }, + "material-overrides": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:Block" + }, + "values": { + "kind": "type", + "target": "terra:Block" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Override material by replaced block type. Key state properties are reduced to the block type." + }, + "replace": { + "schema": { + "kind": "type", + "target": "terra:MaterialSet" + }, + "required": true + }, + "physics": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false + }, + "size": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Required size, loaded into both an integer spread and the inherited double vein size. The initializer 7 is not a default." + }, + "exposed": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "float" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ], + "nullable": true + }, + "required": false, + "default": 1, + "summary": "Chance of accepting ore bordering air: 0 rejects, 1 accepts. Source does not enforce a 0\u20131 bound." + } + } + } + }, + "files": { + "ORE": { + "kind": "object", + "fields": { + "type": { + "schema": { + "kind": "literal", + "value": "ORE" + }, + "required": true + }, + "extends": { + "schema": { + "kind": "list", + "element": { + "kind": "string" + }, + "nullable": true + }, + "required": false, + "default": [], + "summary": "Parent configuration IDs; non-final fields may be inherited." + }, + "abstract": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false, + "summary": "Abstract configurations supply inherited values and are not registered." + } + }, + "extends": [ + "Ore" + ] + }, + "SCATTERED_ORE": { + "kind": "object", + "fields": { + "type": { + "schema": { + "kind": "literal", + "value": "SCATTERED_ORE" + }, + "required": true + }, + "extends": { + "schema": { + "kind": "list", + "element": { + "kind": "string" + }, + "nullable": true + }, + "required": false, + "default": [], + "summary": "Parent configuration IDs; non-final fields may be inherited." + }, + "abstract": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false, + "summary": "Abstract configurations supply inherited values and are not registered." + } + }, + "extends": [ + "ScatteredOre" + ] + } + } +} diff --git a/common/addons/config-palette/src/main/resources/META-INF/api/config.terradoc b/common/addons/config-palette/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..6a94d61e2 --- /dev/null +++ b/common/addons/config-palette/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,204 @@ +{ + "id": "config-palette", + "docVersion": 1, + "description": "Registered palette configurations and their weighted block layers.", + "types": { + "terra:Palette": { + "kind": "object", + "fields": { + "id": { + "schema": { + "kind": "string", + "pattern": "^[a-zA-Z0-9_-]*$" + }, + "required": true, + "summary": "Registry identifier; must be present on this file even when inherited." + }, + "layers": { + "schema": { + "kind": "list", + "element": { + "kind": "type", + "target": "PaletteLayer" + } + }, + "required": true, + "summary": "Layers in order from the surface inward." + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler", + "nullable": true + }, + "required": false, + "summary": "Defaults to an internal sampler returning zero." + } + } + }, + "terra:PaletteReference": { + "kind": "oneOf", + "options": [ + { + "kind": "ref", + "target": "terra:Palette" + } + ] + }, + "PaletteLayer": { + "kind": "object", + "fields": { + "materials": { + "schema": { + "kind": "type", + "target": "WeightedBlocks" + }, + "required": true + }, + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler", + "nullable": true + }, + "required": false, + "summary": "When absent or YAML null, use the palette-level sampler.", + "default": null + }, + "layers": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Number of depth layers using these materials; the runtime does not enforce a positive minimum." + } + } + }, + "WeightedBlocks": { + "kind": "oneOf", + "description": "A block, a block-to-weight map, or a list of such maps. A singleton entry ignores its weight.", + "options": [ + { + "kind": "type", + "target": "terra:Block" + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:Block" + }, + "values": { + "kind": "any", + "name": "Ignored singleton weight" + }, + "maxEntries": 1 + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:Block" + }, + "values": { + "kind": "integer" + }, + "minEntries": 2 + }, + { + "kind": "list", + "element": { + "kind": "oneOf", + "options": [ + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:Block" + }, + "values": { + "kind": "any", + "name": "Ignored singleton weight" + }, + "maxEntries": 1 + }, + { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:Block" + }, + "values": { + "kind": "integer" + }, + "minEntries": 2 + } + ] + }, + "maxItems": 1 + }, + { + "kind": "list", + "element": { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "terra:Block" + }, + "values": { + "kind": "integer" + } + }, + "minItems": 2 + } + ] + } + }, + "files": { + "PALETTE": { + "kind": "object", + "fields": { + "type": { + "schema": { + "kind": "literal", + "value": "PALETTE" + }, + "required": true + }, + "extends": { + "schema": { + "kind": "list", + "element": { + "kind": "string" + }, + "nullable": true + }, + "required": false, + "default": [], + "summary": "Parent configuration identifiers; non-final fields can be inherited." + }, + "abstract": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false, + "summary": "Abstract configurations are available for inheritance and are not registered." + } + }, + "extends": [ + "terra:Palette" + ] + } + } +} diff --git a/common/addons/generation-stage-feature/src/main/resources/META-INF/api/config.terradoc b/common/addons/generation-stage-feature/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..c7d6b3618 --- /dev/null +++ b/common/addons/generation-stage-feature/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,99 @@ +{ + "id": "generation-stage-feature", + "docVersion": 1, + "description": "FEATURE generation stages and the per-stage feature lists contributed to biome configurations.", + "types": { + "terra:GenerationStage": { + "kind": "union", + "values": { + "FEATURE": { + "kind": "object", + "fields": { + "id": { + "schema": { + "kind": "string" + }, + "required": true, + "summary": "Stage identifier used to load biome features. lists. IDs containing dots are interpreted as nested YAML paths by the runtime." + }, + "resolution": { + "schema": { + "kind": "enum", + "values": [ + 1, + 2, + 4, + 8, + 16 + ], + "nullable": true + }, + "required": false, + "default": 4, + "summary": "Biome column sample resolution; must be one of these powers of two." + }, + "blend": { + "schema": { + "kind": "object", + "fields": { + "sampler": { + "schema": { + "kind": "type", + "target": "terra:NoiseSampler", + "nullable": true + }, + "required": false, + "summary": "Coordinate-warping sampler; defaults to an internal zero sampler." + }, + "amplitude": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": 0 + } + }, + "nullable": true + }, + "required": false + } + }, + "description": "Runs feature placement using biome lists indexed by this stage ID." + } + } + }, + "terra:Biome": { + "kind": "object", + "fields": { + "features": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "list", + "element": { + "kind": "ref", + "target": "terra:Feature" + } + }, + "nullable": true + }, + "required": false, + "summary": "Maps configured FEATURE stage IDs to ordered feature identifiers. Missing lists default to empty. Only IDs present in pack stages are loaded; v1 cannot derive or restrict these keys. Dotted stage IDs require nested maps and are not fully represented by this keyMap." + } + } + } + }, + "files": { + "BIOME": { + "kind": "object", + "fields": {}, + "extends": [ + "terra:Biome" + ] + } + } +} diff --git a/common/addons/library-image/src/main/resources/META-INF/api/config.terradoc b/common/addons/library-image/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..6c5e524e1 --- /dev/null +++ b/common/addons/library-image/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,520 @@ +{ + "id": "library-image", + "docVersion": 1, + "description": "Inline bitmap images, color samplers, two numeric image sampler variants and pack image-cache options.", + "types": { + "Image": { + "kind": "union", + "discriminator": "type", + "values": { + "BITMAP": { + "kind": "object", + "fields": { + "path": { + "schema": { + "kind": "string" + }, + "required": true, + "summary": "Path resolved against the pack root and read by ImageIO." + } + } + }, + "STITCHED_BITMAP": { + "kind": "object", + "fields": { + "path-format": { + "schema": { + "kind": "string", + "pattern": "^(?=[\\s\\S]*\\{row\\})(?=[\\s\\S]*\\{column\\})[\\s\\S]*$" + }, + "required": true, + "summary": "Must contain {row} and {column}; the first occurrence of each is substituted." + }, + "rows": { + "schema": { + "kind": "integer", + "minimum": 1 + }, + "required": true + }, + "columns": { + "schema": { + "kind": "integer", + "minimum": 1 + }, + "required": true + }, + "zero-indexed": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false, + "summary": "Use tile indices starting at 0 rather than 1." + } + } + } + } + }, + "ColorSampler": { + "kind": "union", + "discriminator": "type", + "values": { + "COLOR": { + "kind": "object", + "fields": { + "color": { + "schema": { + "kind": "type", + "target": "Color" + }, + "required": true + } + } + }, + "SINGLE_IMAGE": { + "kind": "object", + "fields": { + "image": { + "schema": { + "kind": "type", + "target": "Image" + }, + "required": true + }, + "align": { + "schema": { + "kind": "enum", + "values": [ + "NONE", + "CENTER" + ], + "nullable": true + }, + "required": false, + "default": "NONE" + }, + "outside-sampler": { + "schema": { + "kind": "type", + "target": "ColorSampler" + }, + "required": true, + "summary": "Required fallback sampler for positions outside the image." + } + } + }, + "TILED_IMAGE": { + "kind": "object", + "fields": { + "image": { + "schema": { + "kind": "type", + "target": "Image" + }, + "required": true + }, + "align": { + "schema": { + "kind": "enum", + "values": [ + "NONE", + "CENTER" + ], + "nullable": true + }, + "required": false, + "default": "NONE" + } + } + }, + "ROTATE": { + "kind": "object", + "fields": { + "color-sampler": { + "schema": { + "kind": "type", + "target": "ColorSampler" + }, + "required": true + }, + "angle": { + "schema": { + "kind": "float" + }, + "required": true, + "summary": "Rotation angle in degrees." + } + } + }, + "TRANSLATE": { + "kind": "object", + "fields": { + "color-sampler": { + "schema": { + "kind": "type", + "target": "ColorSampler" + }, + "required": true + }, + "x": { + "schema": { + "kind": "integer" + }, + "required": true + }, + "z": { + "schema": { + "kind": "integer" + }, + "required": true + } + } + } + } + }, + "Color": { + "kind": "string", + "minLength": 1, + "description": "Quoted color string: RRGGBB or AARRGGBB hex, optionally prefixed with #; or comma-separated red,green,blue / alpha,red,green,blue channels. Numeric channels use Integer.decode (decimal, hexadecimal or octal) and must be 0\u2013255.", + "examples": [ + "#ff0000", + "80ff0000", + "255,0,0", + "128,255,0,0" + ] + }, + "terra:NoiseSampler": { + "kind": "union", + "discriminator": "type", + "values": { + "CHANNEL": { + "kind": "object", + "fields": { + "color-sampler": { + "schema": { + "kind": "type", + "target": "ColorSampler" + }, + "required": true + }, + "channel": { + "schema": { + "kind": "enum", + "values": [ + "RED", + "GREEN", + "BLUE", + "GRAYSCALE", + "ALPHA" + ] + }, + "required": true + }, + "normalize": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": true, + "summary": "Normalize output into [-1, 1] instead of channel values." + }, + "premultiply": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false, + "summary": "Multiply RGB by alpha before reading the channel." + } + } + }, + "DISTANCE_TRANSFORM": { + "kind": "object", + "fields": { + "image": { + "schema": { + "kind": "type", + "target": "Image" + }, + "required": true + }, + "threshold": { + "schema": { + "kind": "integer", + "nullable": true + }, + "required": false, + "default": 127, + "summary": "Channel threshold used by binary cost functions." + }, + "clamp-to-max-edge": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false + }, + "channel": { + "schema": { + "kind": "enum", + "values": [ + "RED", + "GREEN", + "BLUE", + "GRAYSCALE", + "ALPHA" + ], + "nullable": true + }, + "required": false, + "default": "GRAYSCALE" + }, + "cost-function": { + "schema": { + "kind": "enum", + "values": [ + "Channel", + "Threshold", + "ThresholdEdge", + "ThresholdEdgeSigned" + ], + "nullable": true + }, + "required": false, + "default": "Channel" + }, + "invert-threshold": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false + }, + "normalization": { + "schema": { + "kind": "enum", + "values": [ + "None", + "Linear", + "SmoothPreserveZero" + ], + "nullable": true + }, + "required": false, + "default": "None" + } + } + } + } + }, + "config-noise-function:DimensionedSampler": { + "kind": "union", + "discriminator": "type", + "values": { + "CHANNEL": { + "kind": "object", + "fields": { + "color-sampler": { + "schema": { + "kind": "type", + "target": "ColorSampler" + }, + "required": true + }, + "channel": { + "schema": { + "kind": "enum", + "values": [ + "RED", + "GREEN", + "BLUE", + "GRAYSCALE", + "ALPHA" + ] + }, + "required": true + }, + "normalize": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": true, + "summary": "Normalize output into [-1, 1] instead of channel values." + }, + "premultiply": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false, + "summary": "Multiply RGB by alpha before reading the channel." + }, + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Required by the expression sampler wrapper; 2 selects 2D, other integers select 3D." + } + } + }, + "DISTANCE_TRANSFORM": { + "kind": "object", + "fields": { + "image": { + "schema": { + "kind": "type", + "target": "Image" + }, + "required": true + }, + "threshold": { + "schema": { + "kind": "integer", + "nullable": true + }, + "required": false, + "default": 127, + "summary": "Channel threshold used by binary cost functions." + }, + "clamp-to-max-edge": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false + }, + "channel": { + "schema": { + "kind": "enum", + "values": [ + "RED", + "GREEN", + "BLUE", + "GRAYSCALE", + "ALPHA" + ], + "nullable": true + }, + "required": false, + "default": "GRAYSCALE" + }, + "cost-function": { + "schema": { + "kind": "enum", + "values": [ + "Channel", + "Threshold", + "ThresholdEdge", + "ThresholdEdgeSigned" + ], + "nullable": true + }, + "required": false, + "default": "Channel" + }, + "invert-threshold": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false + }, + "normalization": { + "schema": { + "kind": "enum", + "values": [ + "None", + "Linear", + "SmoothPreserveZero" + ], + "nullable": true + }, + "required": false, + "default": "None" + }, + "dimensions": { + "schema": { + "kind": "oneOf", + "options": [ + { + "kind": "integer" + }, + { + "kind": "type", + "target": "terra:Expression" + } + ] + }, + "required": true, + "summary": "Required by the expression sampler wrapper; 2 selects 2D, other integers select 3D." + } + } + } + } + } + }, + "files": { + "pack.yml": { + "kind": "object", + "fields": { + "images": { + "schema": { + "kind": "object", + "fields": { + "cache": { + "schema": { + "kind": "object", + "fields": { + "load-on-use": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": false, + "summary": "Load images when first used rather than during pack loading." + }, + "timeout": { + "schema": { + "kind": "integer", + "nullable": true + }, + "required": false, + "default": 0, + "summary": "Seconds after last use before unloading; values <= 0 keep images cached." + } + }, + "nullable": true + }, + "required": false + } + }, + "nullable": true + }, + "required": false + } + } + } + } +} diff --git a/common/addons/locator-slant-noise-3d/src/main/resources/META-INF/api/config.terradoc b/common/addons/locator-slant-noise-3d/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..613589628 --- /dev/null +++ b/common/addons/locator-slant-noise-3d/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,26 @@ +{ + "id": "locator-slant-noise-3d", + "docVersion": 1, + "description": "SLANT locator tests the noise generator's slant value with a numeric predicate.", + "types": { + "terra:Locator": { + "kind": "union", + "discriminator": "type", + "values": { + "SLANT": { + "kind": "object", + "fields": { + "condition": { + "schema": { + "kind": "type", + "target": "config-number-predicate:NumberPredicate" + }, + "required": true + } + }, + "description": "Requires a numeric predicate loader and a world using NoiseChunkGenerator3D; sampling casts the world generator to that implementation." + } + } + } + } +} diff --git a/common/addons/palette-block-shortcut/src/main/resources/META-INF/api/config.terradoc b/common/addons/palette-block-shortcut/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..ab82d036a --- /dev/null +++ b/common/addons/palette-block-shortcut/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,29 @@ +{ + "id": "palette-block-shortcut", + "docVersion": 1, + "description": "BLOCK: creates a palette containing one block at every depth.", + "types": { + "PaletteBlockShortcut": { + "kind": "string", + "pattern": "^BLOCK:.+$", + "description": "BLOCK: followed by a platform block state; the prefix is case-sensitive.", + "examples": [ + "BLOCK:minecraft:stone", + "BLOCK:minecraft:oak_log[axis=y]" + ] + }, + "terra:PaletteReference": { + "kind": "oneOf", + "options": [ + { + "kind": "ref", + "target": "terra:Palette" + }, + { + "kind": "type", + "target": "PaletteBlockShortcut" + } + ] + } + } +} diff --git a/common/addons/pipeline-image/src/main/resources/META-INF/api/config.terradoc b/common/addons/pipeline-image/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..a4e32d84a --- /dev/null +++ b/common/addons/pipeline-image/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,110 @@ +{ + "id": "pipeline-image", + "docVersion": 1, + "description": "Image pipeline source with PipelineBiome outputs.", + "types": { + "biome-provider-pipeline:Source": { + "kind": "union", + "discriminator": "type", + "values": { + "IMAGE": { + "kind": "object", + "fields": { + "color-sampler": { + "schema": { + "kind": "type", + "target": "library-image:ColorSampler" + }, + "required": true + }, + "color-conversion": { + "schema": { + "kind": "type", + "target": "ColorConverter" + }, + "required": true + } + } + } + } + }, + "ColorConverter": { + "kind": "union", + "discriminator": "type", + "values": { + "EXACT": { + "kind": "object", + "fields": { + "match": { + "schema": { + "kind": "type", + "target": "ColorMapping" + }, + "required": true + }, + "else": { + "schema": { + "kind": "type", + "target": "biome-provider-pipeline:PipelineBiome" + }, + "required": true, + "summary": "Required fallback for colors with no exact mapping." + }, + "ignore-alpha": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": true + } + }, + "description": "Exact color matching with a fallback; alpha is ignored by default." + }, + "CLOSEST": { + "kind": "object", + "fields": { + "match": { + "schema": { + "kind": "type", + "target": "ColorMapping" + }, + "required": true + } + }, + "description": "Closest color using summed absolute RGB differences; alpha is ignored. An empty map cannot produce a biome." + } + } + }, + "ColorMapping": { + "kind": "union", + "discriminator": "type", + "values": { + "USE_BIOME_COLORS": { + "kind": "object", + "fields": {}, + "description": "Build the mapping from registered Terra biome color values." + }, + "MAP": { + "kind": "object", + "fields": { + "map": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "type", + "target": "library-image:Color" + }, + "values": { + "kind": "type", + "target": "biome-provider-pipeline:PipelineBiome" + } + }, + "required": true + } + } + } + } + } + } +} diff --git a/common/addons/structure-block-shortcut/src/main/resources/META-INF/api/config.terradoc b/common/addons/structure-block-shortcut/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..9afcd9b7a --- /dev/null +++ b/common/addons/structure-block-shortcut/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,29 @@ +{ + "id": "structure-block-shortcut", + "docVersion": 1, + "description": "BLOCK: creates a structure that places one block at its generation location.", + "types": { + "StructureBlockShortcut": { + "kind": "string", + "pattern": "^BLOCK:.+$", + "description": "Case-sensitive BLOCK: prefix followed by a platform block state. Rotation and random arguments do not change the placed block state.", + "examples": [ + "BLOCK:minecraft:stone", + "BLOCK:minecraft:oak_log[axis=y]" + ] + }, + "terra:StructureReference": { + "kind": "oneOf", + "options": [ + { + "kind": "ref", + "target": "terra:Structure" + }, + { + "kind": "type", + "target": "StructureBlockShortcut" + } + ] + } + } +} diff --git a/common/addons/structure-sponge-loader/src/main/resources/META-INF/api/config.terradoc b/common/addons/structure-sponge-loader/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..8cfbb0f18 --- /dev/null +++ b/common/addons/structure-sponge-loader/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,11 @@ +{ + "id": "structure-sponge-loader", + "docVersion": 1, + "description": "Recursively scans the pack root for case-sensitive .schem files during pack preload and registers raw Structure entries under structure-sponge-loader:. Directory names do not contribute to IDs, so equal basenames collide. Reads gzip or uncompressed NBT. The converter accepts Version 2 and 3 offset branches, but assumes root-level Palette and BlockData and reads one signed byte per block; this is not a claim of complete Sponge format compatibility. V2 uses a complete WEOffsetX/Y/Z metadata triplet or zero offset; V3 reads Offset. minecraft:structure_void states are skipped. V1 metadata cannot discover these IDs or validate binary schematic contents.", + "types": { + "terra:Structure": { + "kind": "string", + "description": "Recursively scans the pack root for case-sensitive .schem files during pack preload and registers raw Structure entries under structure-sponge-loader:. Directory names do not contribute to IDs, so equal basenames collide. Reads gzip or uncompressed NBT. The converter accepts Version 2 and 3 offset branches, but assumes root-level Palette and BlockData and reads one signed byte per block; this is not a claim of complete Sponge format compatibility. V2 uses a complete WEOffsetX/Y/Z metadata triplet or zero offset; V3 reads Offset. minecraft:structure_void states are skipped. V1 metadata cannot discover these IDs or validate binary schematic contents." + } + } +} diff --git a/common/addons/structure-terrascript-loader/src/main/resources/META-INF/api/config.terradoc b/common/addons/structure-terrascript-loader/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..fde8606a0 --- /dev/null +++ b/common/addons/structure-terrascript-loader/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,11 @@ +{ + "id": "structure-terrascript-loader", + "docVersion": 1, + "description": "Recursively scans the pack root for case-sensitive .tesf files during pack preload at priority 100 and registers raw Structure entries under structure-terrascript-loader:. Directory names do not contribute to IDs, so equal basenames collide. Files are parsed as TerraScript structures with access to pack Structure, LootTable and FunctionBuilder registries. Additional addons may supply script functions. V1 metadata cannot discover these IDs or describe TerraScript grammar and callable signatures.", + "types": { + "terra:Structure": { + "kind": "string", + "description": "Recursively scans the pack root for case-sensitive .tesf files during pack preload at priority 100 and registers raw Structure entries under structure-terrascript-loader:. Directory names do not contribute to IDs, so equal basenames collide. Files are parsed as TerraScript structures with access to pack Structure, LootTable and FunctionBuilder registries. Additional addons may supply script functions. V1 metadata cannot discover these IDs or describe TerraScript grammar and callable signatures." + } + } +} diff --git a/common/implementation/base/src/main/resources/META-INF/api/core.terradoc b/common/implementation/base/src/main/resources/META-INF/api/core.terradoc new file mode 100644 index 000000000..b2332f3a5 --- /dev/null +++ b/common/implementation/base/src/main/resources/META-INF/api/core.terradoc @@ -0,0 +1,265 @@ +{ + "id": "terra", + "docVersion": 1, + "description": "Terra core configuration types and pack manifest fields. Shared object shapes and union variants are contributed by the addons that register their implementations.", + "types": { + "Expression": { + "kind": "expr", + "name": "Paralithic", + "description": "A mathematical expression evaluated to a floating-point number. Available variables and functions depend on the consuming configuration; pack variables are configured under variables.", + "examples": ["3 + 2 / 8", "atan2(x, z)"] + }, + "Range": { + "kind": "oneOf", + "description": "An integer range with an inclusive minimum and exclusive maximum. A single integer n denotes [n, n + 1).", + "options": [ + { "kind": "integer" }, + { + "kind": "object", + "fields": { + "min": { "schema": { "kind": "integer" }, "required": true, "summary": "Inclusive minimum." }, + "max": { "schema": { "kind": "integer" }, "required": true, "summary": "Exclusive maximum." } + } + } + ], + "examples": [3, { "min": 2, "max": 5 }] + }, + "Version": { + "kind": "string", + "description": "A version string parsed by Strata. Quote versions in YAML so they remain strings.", + "examples": ["1.0.0"] + }, + "VersionRange": { + "kind": "string", + "description": "An addon dependency version range parsed by Strata. It must be a YAML string." + }, + "WeightedList": { + "kind": "oneOf", + "description": "The unparameterized ProbabilityCollection representation: an item identifier, an item-to-integer-weight mapping, or a sequence of such mappings. A singleton collection with one entry ignores its weight. Addons must specialize the item schema for their consuming type; v1 has no generic type parameters.", + "options": [ + { "kind": "string" }, + { + "kind": "keyMap", + "maxEntries": 1, + "keys": { "kind": "any", "name": "Collection item" }, + "values": { "kind": "any", "name": "Ignored singleton weight" } + }, + { + "kind": "keyMap", + "minEntries": 2, + "keys": { "kind": "string" }, + "values": { "kind": "integer" } + }, + { + "kind": "list", + "maxItems": 1, + "element": { + "kind": "oneOf", + "options": [ + { + "kind": "keyMap", + "maxEntries": 1, + "keys": { "kind": "any", "name": "Collection item" }, + "values": { "kind": "any", "name": "Ignored singleton weight" } + }, + { + "kind": "keyMap", + "minEntries": 2, + "keys": { "kind": "string" }, + "values": { "kind": "integer" } + } + ] + } + }, + { + "kind": "list", + "minItems": 2, + "element": { + "kind": "keyMap", + "keys": { "kind": "string" }, + "values": { "kind": "integer" } + } + } + ], + "examples": ["PLAINS", { "PLAINS": 3, "FOREST": 1 }, [{ "PLAINS": 3 }, { "FOREST": 1 }]] + }, + "NoiseSampler": { + "kind": "union", + "discriminator": "type", + "description": "An inline sampler that produces a numeric value from a position and seed. Sampler addons contribute variants selected by type." + }, + "BiomeProvider": { + "kind": "union", + "discriminator": "type", + "description": "An inline biome provider that chooses a Terra biome for a position. Biome provider addons contribute variants selected by type." + }, + "Distributor": { + "kind": "union", + "discriminator": "type", + "description": "An inline distributor that determines which columns allow feature placement. Distributor addons contribute variants selected by type." + }, + "Locator": { + "kind": "union", + "discriminator": "type", + "description": "An inline locator that determines eligible vertical positions for feature placement. Locator addons contribute variants selected by type." + }, + "GenerationStage": { + "kind": "union", + "discriminator": "type", + "description": "An inline generation stage. Stages run in the order listed in pack.yml after the initial chunk generator. Stage addons contribute variants selected by type." + }, + "ChunkGenerator": { + "kind": "string", + "description": "A registered chunk generator provider identifier, not an inline type-discriminated object. Generator addons register the available identifiers.", + "examples": ["NOISE_3D"] + }, + "Biome": { + "kind": "object", + "description": "Shared configuration target for registered Terra biomes. The config-biome addon contributes its configuration shape; consumers use ref targeting terra:Biome for biome identifiers." + }, + "Palette": { + "kind": "object", + "description": "Shared configuration target for registered palettes. The config-palette addon contributes its configuration shape; consumers use ref targeting terra:Palette for palette identifiers. Shortcut representations belong to their registering addons." + }, + "Feature": { + "kind": "object", + "description": "Shared configuration target for registered features. The config-feature addon contributes its configuration shape; consumers use ref targeting terra:Feature for feature identifiers." + }, + "Structure": { + "kind": "string", + "description": "A raw structure registry identifier, for example a TerraScript or schematic structure. This is distinct from a STRUCTURE configuration producing a ConfiguredStructure. Loader addons define the available identifiers and shortcuts." + }, + "Block": { + "kind": "string", + "description": "A platform-specific block state identifier. Minecraft platforms accept a block identifier with optional bracketed state properties.", + "examples": ["minecraft:grass_block", "minecraft:note_block[instrument=harp,note=9]"] + }, + "MaterialSet": { + "kind": "list", + "element": { "kind": "type", "target": "Block" }, + "description": "A sequence of platform block identifiers loaded into a MaterialSet. Repeated identifiers collapse into the same material." + }, + "Tag": { + "kind": "string", + "description": "A biome tag used to group biomes for distribution. Biomes also have the implicit ALL tag and their own identifier as a tag." + }, + "PlatformBiome": { + "kind": "string", + "description": "A platform-specific biome identifier. Minecraft platforms use identifiers such as minecraft:plains; available values depend on the platform and installed content.", + "examples": ["minecraft:plains"] + }, + "ExpressionOptions": { + "kind": "object", + "fields": { + "use-let-expressions": { + "schema": { "kind": "boolean" }, + "required": false, + "default": false, + "summary": "Enable Paralithic let expressions." + } + } + } + }, + "files": { + "pack.yml": { + "kind": "object", + "description": "The config pack manifest. Addons may contribute additional pack-wide fields directly to this root object.", + "fields": { + "id": { "schema": { "kind": "string" }, "required": true, "summary": "The config pack identifier used by the platform to select a world generator." }, + "author": { "schema": { "kind": "string" }, "required": false, "default": "Anon Y. Mous", "summary": "Who developed the config pack." }, + "version": { "schema": { "kind": "type", "target": "Version" }, "required": true, "summary": "The config pack version." }, + "addons": { + "schema": { + "kind": "keyMap", + "keys": { "kind": "string", "description": "An installed addon identifier." }, + "values": { "kind": "type", "target": "VersionRange" } + }, + "required": false, + "default": {}, + "summary": "Addon dependencies and their allowed version ranges." + }, + "variables": { + "schema": { "kind": "keyMap", "keys": { "kind": "string" }, "values": { "kind": "float" } }, + "required": false, + "default": {}, + "summary": "Pack-wide numeric expression variables." + }, + "generator": { "schema": { "kind": "type", "target": "ChunkGenerator" }, "required": true, "summary": "The generator used for initial chunk generation." }, + "biomes": { "schema": { "kind": "type", "target": "BiomeProvider" }, "required": true, "summary": "Determines which biomes generate at each position." }, + "stages": { "schema": { "kind": "list", "element": { "kind": "type", "target": "GenerationStage" } }, "required": false, "default": [], "summary": "Generation stages applied sequentially after initial chunk generation." }, + "expressions": { + "schema": { + "kind": "object", + "fields": { + "options": { "schema": { "kind": "type", "target": "ExpressionOptions" }, "required": false, "default": { "use-let-expressions": false } } + } + }, + "required": false + }, + "beta": { + "schema": { "kind": "object", "fields": { "carving": { "schema": { "kind": "boolean" }, "required": false, "default": false } } }, + "required": false + }, + "structures": { + "schema": { + "kind": "object", + "fields": { + "locatable": { "schema": { "kind": "keyMap", "keys": { "kind": "string" }, "values": { "kind": "string" } }, "required": false, "default": {} } + } + }, + "required": false + }, + "blend": { + "schema": { + "kind": "object", + "fields": { + "terrain": { + "schema": { "kind": "object", "fields": { "elevation": { "schema": { "kind": "integer" }, "required": false, "default": 4 } } }, + "required": false + } + } + }, + "required": false + }, + "vanilla": { + "schema": { + "kind": "object", + "fields": { + "mobs": { "schema": { "kind": "boolean" }, "required": false, "default": true }, + "caves": { "schema": { "kind": "boolean" }, "required": false, "default": false }, + "decorations": { "schema": { "kind": "boolean" }, "required": false, "default": false }, + "structures": { "schema": { "kind": "boolean" }, "required": false, "default": false } + } + }, + "required": false + }, + "disable": { + "schema": { + "kind": "object", + "fields": { + "sapling": { "schema": { "kind": "boolean" }, "required": false, "default": false }, + "carvers": { "schema": { "kind": "boolean" }, "required": false, "default": false }, + "structures": { "schema": { "kind": "boolean" }, "required": false, "default": false }, + "ores": { "schema": { "kind": "boolean" }, "required": false, "default": false }, + "trees": { "schema": { "kind": "boolean" }, "required": false, "default": false }, + "flora": { "schema": { "kind": "boolean" }, "required": false, "default": false } + } + }, + "required": false + }, + "cache": { + "schema": { + "kind": "object", + "fields": { + "biome": { + "schema": { "kind": "object", "fields": { "enable": { "schema": { "kind": "boolean" }, "required": false, "default": false } } }, + "required": false + } + } + }, + "required": false + } + } + } + } +} diff --git a/platforms/minestom/src/main/resources/META-INF/api/config.terradoc b/platforms/minestom/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..ff17f257d --- /dev/null +++ b/platforms/minestom/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,314 @@ +{ + "id": "terra-minestom", + "docVersion": 1, + "description": "Platform addon biome extensions registered directly by TerraMinestomPlatform. Covers active VanillaBiomeProperties fields and platform object loaders; commented-out music configuration is not registered.", + "types": { + "terra:Biome": { + "kind": "object", + "fields": { + "colors": { + "schema": { + "kind": "object", + "fields": { + "grass": { + "schema": { + "kind": "type", + "target": "RGBColor", + "nullable": true + }, + "required": false, + "default": null, + "summary": "Packed integer RGB; high bits are ignored by Minestom Color." + }, + "fog": { + "schema": { + "kind": "type", + "target": "RGBColor", + "nullable": true + }, + "required": false, + "default": null, + "summary": "Packed integer RGB; high bits are ignored by Minestom Color." + }, + "water": { + "schema": { + "kind": "type", + "target": "RGBColor", + "nullable": true + }, + "required": false, + "default": null, + "summary": "Packed integer RGB; high bits are ignored by Minestom Color." + }, + "water-fog": { + "schema": { + "kind": "type", + "target": "RGBColor", + "nullable": true + }, + "required": false, + "default": null, + "summary": "Packed integer RGB; high bits are ignored by Minestom Color." + }, + "foliage": { + "schema": { + "kind": "type", + "target": "RGBColor", + "nullable": true + }, + "required": false, + "default": null, + "summary": "Packed integer RGB; high bits are ignored by Minestom Color." + }, + "sky": { + "schema": { + "kind": "type", + "target": "RGBColor", + "nullable": true + }, + "required": false, + "default": null, + "summary": "Packed integer RGB; high bits are ignored by Minestom Color." + }, + "modifier": { + "schema": { + "kind": "enum", + "values": [ + "NONE", + "DARK_FOREST", + "SWAMP" + ], + "nullable": true + }, + "required": false, + "default": null + } + }, + "nullable": true + }, + "required": false + }, + "climate": { + "schema": { + "kind": "object", + "fields": { + "precipitation": { + "schema": { + "kind": "boolean", + "nullable": true + }, + "required": false, + "default": null + }, + "temperature": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": null + }, + "temperature-modifier": { + "schema": { + "kind": "enum", + "values": [ + "NONE", + "FROZEN" + ], + "nullable": true + }, + "required": false, + "default": null, + "summary": "Loaded into properties but not applied by the current default biome factory." + }, + "downfall": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": null + } + }, + "nullable": true + }, + "required": false + }, + "particles": { + "schema": { + "kind": "type", + "target": "Particle", + "nullable": true + }, + "required": false, + "default": null + }, + "sound": { + "schema": { + "kind": "object", + "fields": { + "loop-sound": { + "schema": { + "kind": "object", + "fields": { + "sound": { + "schema": { + "kind": "type", + "target": "SoundEvent", + "nullable": true + }, + "required": false, + "default": null + } + }, + "nullable": true + }, + "required": false + }, + "mood-sound": { + "schema": { + "kind": "type", + "target": "MoodSound", + "nullable": true + }, + "required": false, + "default": null + }, + "additions-sound": { + "schema": { + "kind": "type", + "target": "AdditionsSound", + "nullable": true + }, + "required": false, + "default": null + } + }, + "nullable": true + }, + "required": false + } + }, + "description": "Minestom biome fields loaded for every Terra biome. No numeric expression preprocessing. Water/foliage/grass/modifier and precipitation/temperature/downfall fall back to the platform biome (or plains if absent). Fog/sky/water-fog, particles and ambient sounds are applied separately as environment attributes; no parent fallback is supplied for these fields." + }, + "RGBColor": { + "kind": "integer", + "description": "RGBLikeLoader requires a Java Integer. Minestom Color extracts the low 24 bits as RGB; no 0\u20130xFFFFFF bound is enforced." + }, + "Key": { + "kind": "string", + "description": "Adventure key string: optional lowercase namespace followed by colon and value. Omitted or empty namespace defaults to minecraft. Key.key validates character sets.", + "pattern": "^(?:[a-z0-9_.-]*:)?[a-z0-9_./-]*$" + }, + "SoundEvent": { + "kind": "object", + "fields": { + "id": { + "schema": { + "kind": "type", + "target": "Key", + "nullable": true + }, + "required": false, + "default": null, + "summary": "Without an ID this template returns null." + }, + "distance-to-travel": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": null, + "summary": "Null is explicitly supported by SoundEvent.of." + } + }, + "description": "Inline sound event object, not a bare sound ID." + }, + "MoodSound": { + "kind": "object", + "fields": { + "sound": { + "schema": { + "kind": "type", + "target": "SoundEvent", + "nullable": true + }, + "required": false, + "default": null + }, + "cultivation-ticks": { + "schema": { + "kind": "integer", + "nullable": true + }, + "required": false, + "default": null + }, + "spawn-range": { + "schema": { + "kind": "integer", + "nullable": true + }, + "required": false, + "default": null + }, + "extra-distance": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": null + } + }, + "description": "Returns null without sound. With sound present, the remaining values are passed to primitive constructor parameters: omitted/null values can fail by unboxing. Template loading itself marks all fields optional." + }, + "AdditionsSound": { + "kind": "object", + "fields": { + "sound": { + "schema": { + "kind": "type", + "target": "SoundEvent", + "nullable": true + }, + "required": false, + "default": null + }, + "sound-chance": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": null + } + }, + "description": "Returns null without sound. With sound present, sound-chance is unboxed by the constructor and omission/null can fail. Template loading marks both fields optional." + }, + "Particle": { + "kind": "object", + "fields": { + "particle": { + "schema": { + "kind": "string", + "nullable": true + }, + "required": false, + "default": null, + "summary": "Particle key, optionally followed by an SNBT compound; data is decoded through Particle.CODEC." + }, + "probability": { + "schema": { + "kind": "float", + "nullable": true + }, + "required": false, + "default": null + } + }, + "description": "Returns null unless both particle and probability are supplied. Invalid additional SNBT data is logged and ignored. No template probability bounds are enforced." + } + } +} From 8b14615bf298e5ae4b2a6ab9f47d121d2100dfc8 Mon Sep 17 00:00:00 2001 From: Christian Bergschneider Date: Sat, 3 Oct 2026 14:50:57 +0200 Subject: [PATCH 23/44] feat: update to minestom 26_3 --- buildSrc/src/main/kotlin/DependencyConfig.kt | 6 ++++++ buildSrc/src/main/kotlin/Versions.kt | 2 +- .../dfsek/terra/registry/master/ConfigRegistry.java | 2 +- .../terra/registry/master/MetaConfigRegistry.java | 2 +- .../minestom/config/BiomeParticleConfigTemplate.java | 12 ++++++++++++ 5 files changed, 21 insertions(+), 3 deletions(-) diff --git a/buildSrc/src/main/kotlin/DependencyConfig.kt b/buildSrc/src/main/kotlin/DependencyConfig.kt index 47e3475a8..4a50298dc 100644 --- a/buildSrc/src/main/kotlin/DependencyConfig.kt +++ b/buildSrc/src/main/kotlin/DependencyConfig.kt @@ -60,6 +60,12 @@ fun Project.configureDependencies() { maven("https://repo.onarandombox.com/multiverse-releases") { name = "onarandombox" } + maven(url = "https://central.sonatype.com/repository/maven-snapshots/") { + content { + includeModule("net.minestom", "minestom") + includeModule("net.minestom", "testing") + } + } } dependencies { diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index ae15639cf..a1ea78852 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -96,6 +96,6 @@ object Versions { } object Minestom { - const val minestom = "2025.12.20c-1.21.11" + const val minestom = "26_3-SNAPSHOT" } } diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java index 08343d59f..2d39ead5d 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java @@ -68,7 +68,7 @@ public class ConfigRegistry extends OpenRegistryImpl implements Exte @Override public boolean validatePathIsMember(Path path) { - return Files.isDirectory(path)|| path.getFileName().endsWith(".zip"); + return Files.isDirectory(path)|| path.getFileName().toString().endsWith(".zip"); } public static class PackLoadFailuresException extends Exception { diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java index 65a416400..ed129b0ab 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java @@ -68,6 +68,6 @@ public class MetaConfigRegistry extends OpenRegistryImpl implements Ex @Override public boolean validatePathIsMember(Path path) { - return Files.isDirectory(path) || path.getFileName().endsWith(".zip"); + return Files.isDirectory(path) || path.getFileName().toString().endsWith(".zip"); } } diff --git a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeParticleConfigTemplate.java b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeParticleConfigTemplate.java index cf66e61a0..acc74b546 100644 --- a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeParticleConfigTemplate.java +++ b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/config/BiomeParticleConfigTemplate.java @@ -4,6 +4,7 @@ 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.kyori.adventure.nbt.CompoundBinaryTag; +import net.kyori.adventure.nbt.StringBinaryTag; import net.minestom.server.adventure.MinestomAdventure; import net.minestom.server.codec.Transcoder; import net.minestom.server.particle.Particle; @@ -51,6 +52,17 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate Date: Mon, 5 Oct 2026 18:46:17 +0300 Subject: [PATCH 24/44] feat: 26.3 nms update --- buildSrc/src/main/kotlin/Versions.kt | 2 +- .../terra/bukkit/nms/v26_3/Bindings.java | 15 ++++++ .../bukkit/nms/v26_3/BiomeProvider26_3.java | 20 ++++++++ .../bukkit/nms/v26_3/ChunkGenerator26_3.java | 48 +++++++++++++++++++ .../bukkit/nms/NMSChunkGeneratorDelegate.java | 26 +++++----- .../terra/bukkit/nms/NMSInjectListener.java | 41 ++++++++-------- .../bukkit/nms/NMSStructureBeardifier.java | 2 +- .../terra/bukkit/nms/NMSVersionBindings.java | 11 +++++ .../nms/config/SpawnSettingsTemplate.java | 4 +- 9 files changed, 135 insertions(+), 34 deletions(-) create mode 100644 platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/BiomeProvider26_3.java create mode 100644 platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/ChunkGenerator26_3.java diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index 4f34358ed..ee394083d 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -67,7 +67,7 @@ object Versions { const val paperLib = "1.0.8" const val reflectionRemapper = "0.1.3" const val paperDevBundle = paperBuild - const val paperDevBundle26_3 = "26.3.build.49-alpha" + const val paperDevBundle26_3 = "26.3.build.156-beta" const val runPaper = "3.0.2" const val paperWeight = "2.0.0-beta.21" const val cloud = "2.0.1" diff --git a/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/Bindings.java b/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/Bindings.java index e1c9e9aa2..55c8f552f 100644 --- a/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/Bindings.java +++ b/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/Bindings.java @@ -12,16 +12,31 @@ import net.minecraft.world.level.biome.MobSpawnSettings; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.levelgen.densityfunction.SamplerContext; +import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.world.biome.generation.BiomeProvider; import com.dfsek.terra.api.world.chunk.generation.ChunkGenerator; import com.dfsek.terra.api.world.info.WorldProperties; import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions; +import com.dfsek.terra.bukkit.nms.NMSBiomeProvider; +import com.dfsek.terra.bukkit.nms.NMSChunkGeneratorDelegate; import com.dfsek.terra.bukkit.nms.NMSStructureBeardifier; import com.dfsek.terra.bukkit.nms.NMSVersionBindings; import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties; public final class Bindings implements NMSVersionBindings { + @Override + public NMSBiomeProvider createBiomeProvider(BiomeProvider delegate, long seed) { + return new BiomeProvider26_3(delegate, seed); + } + + @Override + public NMSChunkGeneratorDelegate createChunkGenerator( + net.minecraft.world.level.chunk.ChunkGenerator vanilla, ConfigPack pack, + NMSBiomeProvider biomeProvider, long seed) { + return new ChunkGenerator26_3(vanilla, pack, biomeProvider, seed, this); + } + @Override public void addSpawn(MobSpawnSettings.Builder builder, MobCategory category, EntityType type, int weight, int minCount, int maxCount) { diff --git a/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/BiomeProvider26_3.java b/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/BiomeProvider26_3.java new file mode 100644 index 000000000..423725dd5 --- /dev/null +++ b/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/BiomeProvider26_3.java @@ -0,0 +1,20 @@ +package com.dfsek.terra.bukkit.nms.v26_3; + +import net.minecraft.world.level.biome.BiomeResolver; +import net.minecraft.world.level.biome.Climate.Sampler; +import org.jetbrains.annotations.NotNull; + +import com.dfsek.terra.api.world.biome.generation.BiomeProvider; +import com.dfsek.terra.bukkit.nms.NMSBiomeProvider; + + +public final class BiomeProvider26_3 extends NMSBiomeProvider { + public BiomeProvider26_3(BiomeProvider delegate, long seed) { + super(delegate, seed); + } + + @Override + public @NotNull BiomeResolver createResolver(@NotNull Sampler sampler) { + return (x, y, z) -> getNoiseBiome(x, y, z, sampler); + } +} diff --git a/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/ChunkGenerator26_3.java b/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/ChunkGenerator26_3.java new file mode 100644 index 000000000..004347932 --- /dev/null +++ b/platforms/bukkit/nms/26.3/src/main/java/com/dfsek/terra/bukkit/nms/v26_3/ChunkGenerator26_3.java @@ -0,0 +1,48 @@ +package com.dfsek.terra.bukkit.nms.v26_3; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.server.level.WorldGenRegion; +import net.minecraft.world.level.StructureManager; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeManager; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.levelgen.RandomState; +import net.minecraft.world.level.levelgen.blending.Blender; +import net.minecraft.world.level.levelgen.densityfunction.SamplerContext; + +import java.util.List; +import java.util.Set; +import java.util.concurrent.CompletableFuture; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.bukkit.nms.NMSBiomeProvider; +import com.dfsek.terra.bukkit.nms.NMSChunkGeneratorDelegate; +import com.dfsek.terra.bukkit.nms.NMSVersionBindings; + + +public final class ChunkGenerator26_3 extends NMSChunkGeneratorDelegate { + private final ChunkGenerator vanilla; + + public ChunkGenerator26_3(ChunkGenerator vanilla, ConfigPack pack, NMSBiomeProvider biomeProvider, long seed, + NMSVersionBindings bindings) { + super(vanilla, pack, biomeProvider, seed, bindings); + this.vanilla = vanilla; + } + + @Override + public CompletableFuture buildTerrain(ChunkAccess chunk, Blender blender, RandomState randomState, + StructureManager structures, BiomeManager biomeManager, + WorldGenRegion region, Set> biomes) { + return vanilla.buildTerrain(chunk, blender, randomState, structures, biomeManager, region, biomes) + .thenApply(result -> { + applyStructureBeard(structures, result); + return result; + }); + } + + @Override + public void addDebugScreenInfo(List text, RandomState randomState, BlockPos pos, SamplerContext context) { + } +} diff --git a/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java index 0766a99e0..82592a5d8 100644 --- a/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSChunkGeneratorDelegate.java @@ -85,18 +85,22 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator { @NotNull StructureManager structureAccessor, @NotNull ChunkAccess chunk) { return vanilla.fillFromNoise(blender, noiseConfig, structureAccessor, chunk) .thenApply(c -> { - LevelAccessor level = Reflection.STRUCTURE_MANAGER.getLevel(structureAccessor); - BiomeProvider biomeProvider = pack.getBiomeProvider(); - PreLoadCompatibilityOptions compatibilityOptions = pack.getContext().get(PreLoadCompatibilityOptions.class); - if(compatibilityOptions.isBeard()) { - bindings.applyStructureBeard(delegate, structureAccessor, chunk, - new com.dfsek.terra.bukkit.world.BukkitWorldProperties(level.getMinecraftWorld().getWorld()), - biomeProvider, compatibilityOptions); - } + applyStructureBeard(structureAccessor, chunk); return c; }); } + protected void applyStructureBeard(StructureManager structureAccessor, ChunkAccess chunk) { + LevelAccessor level = Reflection.STRUCTURE_MANAGER.getLevel(structureAccessor); + BiomeProvider biomeProvider = pack.getBiomeProvider(); + PreLoadCompatibilityOptions compatibilityOptions = pack.getContext().get(PreLoadCompatibilityOptions.class); + if(compatibilityOptions.isBeard()) { + bindings.applyStructureBeard(delegate, structureAccessor, chunk, + new com.dfsek.terra.bukkit.world.BukkitWorldProperties(level.getMinecraftWorld().getWorld()), + biomeProvider, compatibilityOptions); + } + } + @Override public int getSeaLevel() { return vanilla.getSeaLevel(); @@ -112,7 +116,7 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator { WorldProperties properties = new NMSWorldProperties(seed, world); int y = properties.getMaxHeight(); BiomeProvider biomeProvider = pack.getBiomeProvider(); - while(y >= getMinY() && !heightmap.isOpaque().test( + while(y > properties.getMinHeight() && !heightmap.isOpaque().test( ((CraftBlockData) delegate.getBlock(properties, x, y - 1, z, biomeProvider).getHandle()).getState())) { y--; } @@ -124,11 +128,11 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator { BlockState[] array = new BlockState[world.getHeight()]; WorldProperties properties = new NMSWorldProperties(seed, world); BiomeProvider biomeProvider = pack.getBiomeProvider(); - for(int y = properties.getMaxHeight(); y >= properties.getMinHeight(); y--) { + for(int y = properties.getMaxHeight() - 1; y >= properties.getMinHeight(); y--) { array[y - properties.getMinHeight()] = ((CraftBlockData) delegate.getBlock(properties, x, y, z, biomeProvider) .getHandle()).getState(); } - return new NoiseColumn(getMinY(), array); + return new NoiseColumn(properties.getMinHeight(), array); } @Override diff --git a/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSInjectListener.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSInjectListener.java index 19597e22b..e5dd57916 100644 --- a/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSInjectListener.java +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSInjectListener.java @@ -35,29 +35,32 @@ public class NMSInjectListener implements Listener { if(!INJECTED.contains(event.getWorld()) && event.getWorld().getGenerator() instanceof BukkitChunkGeneratorWrapper bukkitChunkGeneratorWrapper) { INJECT_LOCK.lock(); - INJECTED.add(event.getWorld()); - LOGGER.info("Preparing to take over the world: {}", event.getWorld().getName()); - CraftWorld craftWorld = (CraftWorld) event.getWorld(); - ServerLevel serverWorld = craftWorld.getHandle(); + try { + LOGGER.info("Preparing to take over the world: {}", event.getWorld().getName()); + CraftWorld craftWorld = (CraftWorld) event.getWorld(); + ServerLevel serverWorld = craftWorld.getHandle(); - ConfigPack pack = bukkitChunkGeneratorWrapper.getPack(); + ConfigPack pack = bukkitChunkGeneratorWrapper.getPack(); - ChunkGenerator vanilla = serverWorld.getChunkSource().getGenerator(); - NMSBiomeProvider provider = new NMSBiomeProvider(pack.getBiomeProvider(), craftWorld.getSeed()); - ChunkMap chunkMap = serverWorld.getChunkSource().chunkMap; - WorldGenContext worldGenContext = Reflection.CHUNKMAP.getWorldGenContext(chunkMap); - Reflection.CHUNKMAP.setWorldGenContext(chunkMap, new WorldGenContext( - worldGenContext.level(), - new NMSChunkGeneratorDelegate(vanilla, pack, provider, craftWorld.getSeed(), bindings), - worldGenContext.structureManager(), - worldGenContext.lightEngine(), - worldGenContext.mainThreadExecutor(), - worldGenContext.unsavedListener() - )); + ChunkGenerator vanilla = serverWorld.getChunkSource().getGenerator(); + NMSBiomeProvider provider = bindings.createBiomeProvider(pack.getBiomeProvider(), craftWorld.getSeed()); + ChunkMap chunkMap = serverWorld.getChunkSource().chunkMap; + WorldGenContext worldGenContext = Reflection.CHUNKMAP.getWorldGenContext(chunkMap); + Reflection.CHUNKMAP.setWorldGenContext(chunkMap, new WorldGenContext( + worldGenContext.level(), + bindings.createChunkGenerator(vanilla, pack, provider, craftWorld.getSeed()), + worldGenContext.structureManager(), + worldGenContext.lightEngine(), + worldGenContext.mainThreadExecutor(), + worldGenContext.unsavedListener() + )); - LOGGER.info("Successfully injected into world."); + INJECTED.add(event.getWorld()); + LOGGER.info("Successfully injected into world."); - INJECT_LOCK.unlock(); + } finally { + INJECT_LOCK.unlock(); + } } } } diff --git a/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSStructureBeardifier.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSStructureBeardifier.java index 7e0a584e4..a27b97337 100644 --- a/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSStructureBeardifier.java +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSStructureBeardifier.java @@ -26,7 +26,7 @@ public final class NMSStructureBeardifier { for(int x = 0; x < 16; x++) { for(int z = 0; z < 16; z++) { int depth = 0; - for(int y = world.getMaxHeight(); y >= world.getMinHeight(); y--) { + for(int y = world.getMaxHeight() - 1; y >= world.getMinHeight(); y--) { int worldX = x + chunkX; int worldZ = z + chunkZ; double density = sampler.sample(worldX, y, worldZ); diff --git a/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSVersionBindings.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSVersionBindings.java index 389a68ae7..6b590e70d 100644 --- a/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSVersionBindings.java +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/NMSVersionBindings.java @@ -8,6 +8,7 @@ import net.minecraft.world.level.biome.Biome.BiomeBuilder; import net.minecraft.world.level.biome.MobSpawnSettings; import net.minecraft.world.level.chunk.ChunkAccess; +import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.world.biome.generation.BiomeProvider; import com.dfsek.terra.api.world.chunk.generation.ChunkGenerator; import com.dfsek.terra.api.world.info.WorldProperties; @@ -16,6 +17,16 @@ import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties; public interface NMSVersionBindings { + default NMSBiomeProvider createBiomeProvider(BiomeProvider delegate, long seed) { + return new NMSBiomeProvider(delegate, seed); + } + + default NMSChunkGeneratorDelegate createChunkGenerator(net.minecraft.world.level.chunk.ChunkGenerator vanilla, + ConfigPack pack, + NMSBiomeProvider biomeProvider, long seed) { + return new NMSChunkGeneratorDelegate(vanilla, pack, biomeProvider, seed, this); + } + void addSpawn(MobSpawnSettings.Builder builder, MobCategory category, EntityType type, int weight, int minCount, int maxCount); void addSpawnCost(MobSpawnSettings.Builder builder, EntityType type, double mass, double gravity); diff --git a/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnSettingsTemplate.java b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnSettingsTemplate.java index 3d34bc828..2e35dad37 100644 --- a/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnSettingsTemplate.java +++ b/platforms/bukkit/nms/common/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnSettingsTemplate.java @@ -22,11 +22,11 @@ public class SpawnSettingsTemplate implements ObjectTemplate { @Value("spawns") @Default - private List spawns = null; + private List spawns = List.of(); @Value("costs") @Default - private List costs = null; + private List costs = List.of(); @Value("probability") @Default From c52d389c02b4ad8131c11db07760b3d6bd0e2f72 Mon Sep 17 00:00:00 2001 From: Oak Date: Sun, 1 Nov 2026 18:51:36 +0000 Subject: [PATCH 25/44] Updated dependencies --- build.gradle.kts | 2 +- buildSrc/build.gradle.kts | 4 ++-- .../src/main/kotlin/DistributionConfig.kt | 2 +- buildSrc/src/main/kotlin/Versions.kt | 11 ++++++----- gradle/wrapper/gradle-wrapper.jar | Bin 45633 -> 48749 bytes gradle/wrapper/gradle-wrapper.properties | 6 ++++-- 6 files changed, 14 insertions(+), 11 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 1d785b1a0..e4f00d7ce 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -15,7 +15,7 @@ allprojects { tasks.withType().configureEach { options.isFork = true options.isIncremental = true - options.release.set(21) + options.release.set(25) } tasks.withType().configureEach { diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 5ca04d11a..4503e4622 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -22,9 +22,9 @@ repositories { dependencies { //TODO Allow pulling from Versions.kt - implementation("com.gradleup.shadow", "shadow-gradle-plugin", "8.3.9") + implementation("com.gradleup.shadow", "shadow-gradle-plugin", "9.3.1") - implementation("io.papermc.paperweight.userdev", "io.papermc.paperweight.userdev.gradle.plugin", "2.0.0-beta.18") + implementation("io.papermc.paperweight.userdev", "io.papermc.paperweight.userdev.gradle.plugin", "2.0.0-beta.24") implementation("org.ow2.asm", "asm", "9.9") implementation("org.ow2.asm", "asm-tree", "9.9") implementation("com.dfsek.tectonic", "common", "4.3.1") diff --git a/buildSrc/src/main/kotlin/DistributionConfig.kt b/buildSrc/src/main/kotlin/DistributionConfig.kt index 0ad6c4491..b594d16b5 100644 --- a/buildSrc/src/main/kotlin/DistributionConfig.kt +++ b/buildSrc/src/main/kotlin/DistributionConfig.kt @@ -161,7 +161,7 @@ fun Project.configureDistribution() { tasks.named("shadowJar") { // Tell shadow to download the packs dependsOn(downloadDefaultPacks) - configurations = listOf(project.configurations["shaded"]) + configurations.set(listOf(project.configurations["shaded"])) archiveClassifier.set("shaded") version = project.version relocate("org.apache.commons", "com.dfsek.terra.lib.commons") diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index e7fe255eb..8b7585253 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -19,7 +19,7 @@ object Versions { const val slf4j = "2.0.17" object Internal { - const val shadow = "8.3.9" + const val shadow = "9.3.1" const val apacheText = "1.14.0" const val apacheIO = "2.20.0" const val guava = "33.5.0-jre" @@ -60,15 +60,16 @@ object Versions { // } object Bukkit { - const val minecraft = "1.21.11-rc3" - const val nms = "$minecraft-R0.1" - const val paperBuild = "$nms-20251208.200020-2" + const val minecraft = "26.3" +// const val nms = "$minecraft-R0.1" + const val paperBuild = "$minecraft.build.236-stable" const val paper = paperBuild const val paperLib = "1.0.8" const val reflectionRemapper = "0.1.3" const val paperDevBundle = paperBuild const val runPaper = "2.3.1" - const val paperWeight = "2.0.0-beta.19" + const val paperWeight = "2.0.0-beta.24" + const val wyck = "4.0.0-837d6ec" const val cloud = "2.0.0-beta.12" const val multiverse = "5.3.0" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index f8e1ee3125fe0768e9a76ee977ac089eb657005e..9fa7f288283f81eec4952784c271abd7e0938dee 100644 GIT binary patch delta 40542 zcmX6^Q(#?f(~Wsz+qP}nc4Oltje8o~YHZuKZM1QkG`9Wc{r;PMv-iz@o>{YI)~xB@ zhd6(OsIx}~dBln#46vd~JqB!$!MX%?oH6Srh#NpPcf=ew!7Ol6iq$&XVL`bH+Q-mjZwQMC)`bPI# z-$qNnubF zHQUkNz+8yd>$;7mSqXAQyoy|QUPFb+YukbP_|K-&8f7sl_M2P|6v_t}D47>r%6g~& z_1CE1k8TiHAM_cA*Keo8U5vP3!~B@%;K^W=wkgG$CR!~k|D<8r4vCloQTDWgs{{0d ziZaE1nus}QWUrhT>HVGx0T+ZNzF%h6`JU^N}ph&x)lS6vVtAuf@qlw*SvNL9=>qjjl6U=DbHzo)s2mC1p1NxxP zH}0T^=7x$cGZ%OE*C=NBQU@Q8m$@M3GoLx|I5B(q%K`8+)atPLLo6a`Gw2YsQy~YK>&yM?E-h_wf&{b2=yjF|aDppCPPL zXwz$!OlWXeo;%{;N>u!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^Erh;bb8OIn8!eD8A{D8h$&2%=H=Lh zz~%G@BxoY$F73&nY?Ce*cUh)+D-2)0Ma%vbrV+I-d}MoS6lPo%(JfUZ9E(jV4llQm zNv9v+S_?0yi+KeMtBaT9maX@wxZZfGeLIun)wt({IZq8=Egs*9CilTke!bbEUI15n z7!|X2Q>`kE6abWHK+hr*N(Wr0=?mytj0yn!Qgju*r+dzx8(K2DLLV^zNmv@?|4priAYg5-{lk)jLY18G<8)jAaGn5+xp4%JSCWF^b{vPI z#}7UM0Fr?1GX0082TiIt;eSU39tH&h05<_x;0A$ka2bn$A4jkKS#l?|c@IGp)k5&& zeOUnDB2Y?v2tg?Lznf@KM{*JXL@`Hos;TCMAMX?WdE=DE9zhnV@WTfFy9R`Qr@{nc z7vqjN*BWv7f9J@$&=^B_#oCjOpn;l;@Z&)U0Qd=%*k2t%Y`JGn>uQof8UTQR-gGno Jz@B;d?LWW7ENB1# diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 8a848873f..5907d39c3 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,8 +1,10 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionSha256Sum=72f44c9f8ebcb1af43838f45ee5c4aa9c5444898b3468ab3f4af7b6076c5bc3f -distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip +distributionSha256Sum=21bd5da2de49b642904077f38c0efdc7778e92b3ed0889392dca61b97e389607 +distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip networkTimeout=10000 +retries=0 +retryBackOffMs=500 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists From 31b5a0de2c194ac114083df5642a419d595981ff Mon Sep 17 00:00:00 2001 From: Oak Date: Sun, 1 Nov 2026 21:10:24 +0000 Subject: [PATCH 26/44] Initial work-in-progress commit --- buildSrc/src/main/kotlin/DependencyConfig.kt | 3 + platforms/bukkit/common/build.gradle.kts | 2 + .../com/dfsek/terra/bukkit/Bootstrapper.java | 94 ++++++++++ .../com/dfsek/terra/bukkit/BukkitAddon.java | 17 +- ...{PlatformImpl.java => BukkitPlatform.java} | 66 ++++++- .../dfsek/terra/bukkit/NMSInitializer.java | 6 +- .../dfsek/terra/bukkit/TerraBukkitPlugin.java | 4 +- .../config/BiomeAdditionsSoundTemplate.java | 12 +- .../config/BiomeMoodSoundTemplate.java | 15 +- .../config/BiomeParticleConfigTemplate.java | 32 ++++ .../bukkit/config/EntityTypeTemplate.java | 22 +++ .../bukkit}/config/MusicSoundTemplate.java | 14 +- .../bukkit}/config/SoundEventTemplate.java | 12 +- .../terra/bukkit}/config/SpawnCostConfig.java | 8 +- .../bukkit}/config/SpawnEntryConfig.java | 12 +- .../bukkit}/config/SpawnSettingsTemplate.java | 10 +- .../terra/bukkit}/config/SpawnTypeConfig.java | 4 +- .../config/VanillaBiomeProperties.java | 31 ++-- .../bukkit/config/VillagerTypeTemplate.java | 22 +++ .../bukkit/listeners/CommonListener.java | 5 +- .../terra/bukkit/world/BiomeHandler.java | 92 ++++++++++ .../terra/bukkit/world/BukkitBiomeInfo.java | 4 +- .../terra/bukkit/nms/AwfulBukkitHacks.java | 164 ------------------ .../com/dfsek/terra/bukkit/nms/NMSAddon.java | 31 ---- .../terra/bukkit/nms/NMSBiomeInjector.java | 108 ------------ .../dfsek/terra/bukkit/nms/NMSPlatform.java | 100 ----------- .../config/BiomeParticleConfigTemplate.java | 38 ---- .../bukkit/nms/config/EntityTypeTemplate.java | 20 --- .../nms/config/VillagerTypeTemplate.java | 21 --- 29 files changed, 418 insertions(+), 551 deletions(-) create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/Bootstrapper.java rename platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/{PlatformImpl.java => BukkitPlatform.java} (55%) rename platforms/bukkit/{nms/src/main/java/com/dfsek/terra/bukkit/nms => common/src/main/java/com/dfsek/terra/bukkit}/config/BiomeAdditionsSoundTemplate.java (66%) rename platforms/bukkit/{nms/src/main/java/com/dfsek/terra/bukkit/nms => common/src/main/java/com/dfsek/terra/bukkit}/config/BiomeMoodSoundTemplate.java (67%) create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeParticleConfigTemplate.java create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/EntityTypeTemplate.java rename platforms/bukkit/{nms/src/main/java/com/dfsek/terra/bukkit/nms => common/src/main/java/com/dfsek/terra/bukkit}/config/MusicSoundTemplate.java (69%) rename platforms/bukkit/{nms/src/main/java/com/dfsek/terra/bukkit/nms => common/src/main/java/com/dfsek/terra/bukkit}/config/SoundEventTemplate.java (65%) rename platforms/bukkit/{nms/src/main/java/com/dfsek/terra/bukkit/nms => common/src/main/java/com/dfsek/terra/bukkit}/config/SpawnCostConfig.java (80%) rename platforms/bukkit/{nms/src/main/java/com/dfsek/terra/bukkit/nms => common/src/main/java/com/dfsek/terra/bukkit}/config/SpawnEntryConfig.java (69%) rename platforms/bukkit/{nms/src/main/java/com/dfsek/terra/bukkit/nms => common/src/main/java/com/dfsek/terra/bukkit}/config/SpawnSettingsTemplate.java (80%) rename platforms/bukkit/{nms/src/main/java/com/dfsek/terra/bukkit/nms => common/src/main/java/com/dfsek/terra/bukkit}/config/SpawnTypeConfig.java (88%) rename platforms/bukkit/{nms/src/main/java/com/dfsek/terra/bukkit/nms => common/src/main/java/com/dfsek/terra/bukkit}/config/VanillaBiomeProperties.java (80%) create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VillagerTypeTemplate.java create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java delete mode 100644 platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java delete mode 100644 platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSAddon.java delete mode 100644 platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java delete mode 100644 platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java delete mode 100644 platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java delete mode 100644 platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/EntityTypeTemplate.java delete mode 100644 platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java diff --git a/buildSrc/src/main/kotlin/DependencyConfig.kt b/buildSrc/src/main/kotlin/DependencyConfig.kt index 47e3475a8..aabc80cf0 100644 --- a/buildSrc/src/main/kotlin/DependencyConfig.kt +++ b/buildSrc/src/main/kotlin/DependencyConfig.kt @@ -57,6 +57,9 @@ fun Project.configureDependencies() { maven("https://s01.oss.sonatype.org/content/repositories/snapshots/") { name = "Sonatype Snapshots" } + maven("https://repo.wyck.dev/snapshots") { + name = "Wyck Snapshots" + } maven("https://repo.onarandombox.com/multiverse-releases") { name = "onarandombox" } diff --git a/platforms/bukkit/common/build.gradle.kts b/platforms/bukkit/common/build.gradle.kts index 57c7ba5a9..d1b879abf 100644 --- a/platforms/bukkit/common/build.gradle.kts +++ b/platforms/bukkit/common/build.gradle.kts @@ -7,6 +7,8 @@ dependencies { compileOnly("io.papermc.paper", "paper-api", Versions.Bukkit.paper) + compileOnly("dev.wyck", "Wyck", Versions.Bukkit.wyck) + compileOnly("org.mvplugins.multiverse.core", "multiverse-core", Versions.Bukkit.multiverse) shadedApi("io.papermc", "paperlib", Versions.Bukkit.paperLib) diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/Bootstrapper.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/Bootstrapper.java new file mode 100644 index 000000000..dc2876eb1 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/Bootstrapper.java @@ -0,0 +1,94 @@ +package com.dfsek.terra.bukkit; + +import com.dfsek.terra.bukkit.config.VanillaBiomeProperties; +import com.dfsek.terra.bukkit.world.BukkitBiomeInfo; +import com.dfsek.terra.bukkit.world.BukkitPlatformBiome; +import com.dfsek.terra.bukkit.world.BiomeHandler; +import com.dfsek.terra.registry.master.ConfigRegistry; + +import dev.wyck.biome.Biome; +import dev.wyck.keys.ResourceKey; +import dev.wyck.registry.bootstrap.BootstrapBiomeRegistry; +import dev.wyck.registry.bootstrap.Composer; +import dev.wyck.tags.TagSet; +import io.papermc.paper.plugin.bootstrap.BootstrapContext; +import io.papermc.paper.plugin.bootstrap.PluginBootstrap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class Bootstrapper implements PluginBootstrap { + private static final Logger LOGGER = LoggerFactory.getLogger(Bootstrapper.class); + + private static final Map> terraBiomeMap = new HashMap<>(); + + @Override + public void bootstrap(BootstrapContext context) { + BootstrapBiomeRegistry registry = BootstrapBiomeRegistry.compose(context, Composer.DATAPACK); + + registry.deferring(() -> { + registerBiomes(context, ); // TODO: Get raw config registry instance here + }); + } + + public static void registerBiomes(BootstrapContext context, ConfigRegistry configRegistry) { + BootstrapBiomeRegistry biomeRegistry = BootstrapBiomeRegistry.compose(context, Composer.DATAPACK); + + // Register the terra biomes to the registry + configRegistry.forEach(pack -> pack.getRegistry(com.dfsek.terra.api.world.biome.Biome.class).forEach((key, biome) -> { + try { + BukkitPlatformBiome platformBiome = (BukkitPlatformBiome) biome.getPlatformBiome(); + ResourceKey vanillaMinecraftKey = ResourceKey.of(platformBiome.getHandle().getKey()); + VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class); + Biome wyckBiome = BiomeHandler.createBiome(vanillaMinecraftKey, vanillaBiomeProperties); + + ResourceKey delegateKey = ResourceKey.of("terra", BiomeHandler.createBiomeID(pack, key)); + + biomeRegistry.queue(wyckBiome); + + platformBiome.getContext().put(new BukkitBiomeInfo(delegateKey)); + + // TODO: Reimplement VillagerTypes - ideally this could be made into an EnvironmentAttribute in Wyck + // Map, ResourceKey> villagerMap = Reflection.VILLAGER_TYPE.getByBiome(); + // + // villagerMap.put(delegateKey, + // Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(), + // villagerMap.getOrDefault(delegateKey, VillagerType.PLAINS))); + + terraBiomeMap.computeIfAbsent(vanillaMinecraftKey, i -> new ArrayList<>()).add(delegateKey.identifier()); + + LOGGER.debug("Registered biome: " + delegateKey); + } catch(NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); + } + })); + + // Add each terra biome to the same tag sets as it's associated vanilla biome + terraBiomeMap.forEach((vb, terraBiomes) -> { + Biome vanilla = BiomeHandler.getBiome(vb); + if(vanilla != null) { + terraBiomes.forEach(tb -> { + Biome terra = BiomeHandler.getBiome(tb); + if(terra != null) { + LOGGER.debug("{} (vanilla for {}): {}", + vanilla.resourceKey().identifier(), + terra.resourceKey().identifier(), + vanilla.tags().toList()); + + vanilla.tags() // TODO: Waiting on implementation from Wyck + .forEach(tag -> TagSet.ofBiomes(tag.key(), terra).append()); + } else { + LOGGER.error("No such biome: {}", tb); + } + }); + } else { + LOGGER.error("No vanilla biome: {}", vb); + } + }); + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitAddon.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitAddon.java index 1fba7bda8..958096c87 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitAddon.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitAddon.java @@ -4,17 +4,20 @@ import ca.solostudios.strata.Versions; import ca.solostudios.strata.version.Version; 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.ConfigPackPreLoadEvent; import com.dfsek.terra.api.event.functional.FunctionalEventHandler; +import com.dfsek.terra.api.world.biome.Biome; import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions; +import com.dfsek.terra.bukkit.config.VanillaBiomeProperties; public class BukkitAddon implements BaseAddon { private static final Version VERSION = Versions.getVersion(1, 0, 0); - protected final PlatformImpl terraBukkitPlugin; + protected final BukkitPlatform terraBukkitPlugin; - public BukkitAddon(PlatformImpl terraBukkitPlugin) { + public BukkitAddon(BukkitPlatform terraBukkitPlugin) { this.terraBukkitPlugin = terraBukkitPlugin; } @@ -25,6 +28,16 @@ public class BukkitAddon implements BaseAddon { .register(this, ConfigPackPreLoadEvent.class) .then(event -> event.getPack().getContext().put(event.loadTemplate(new PreLoadCompatibilityOptions()))) .global(); + + terraBukkitPlugin.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/bukkit/common/src/main/java/com/dfsek/terra/bukkit/PlatformImpl.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java similarity index 55% rename from platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/PlatformImpl.java rename to platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java index 84efbc0cf..67ec084e2 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/PlatformImpl.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java @@ -20,16 +20,43 @@ package com.dfsek.terra.bukkit; import com.dfsek.tectonic.api.TypeRegistry; import com.dfsek.tectonic.api.depth.DepthTracker; import com.dfsek.tectonic.api.exception.LoadException; + +import com.dfsek.terra.api.addon.BaseAddon; +import com.dfsek.terra.bukkit.config.BiomeAdditionsSoundTemplate; +import com.dfsek.terra.bukkit.config.BiomeMoodSoundTemplate; +import com.dfsek.terra.bukkit.config.BiomeParticleConfigTemplate; +import com.dfsek.terra.bukkit.config.EntityTypeTemplate; +import com.dfsek.terra.bukkit.config.MusicSoundTemplate; +import com.dfsek.terra.bukkit.config.SoundEventTemplate; +import com.dfsek.terra.bukkit.config.SpawnCostConfig; +import com.dfsek.terra.bukkit.config.SpawnEntryConfig; +import com.dfsek.terra.bukkit.config.SpawnSettingsTemplate; +import com.dfsek.terra.bukkit.config.SpawnTypeConfig; +import com.dfsek.terra.bukkit.config.VillagerTypeTemplate; + +import dev.wyck.biome.TemperatureModifier; +import dev.wyck.biome.entity.MobCategory; +import dev.wyck.biome.entity.MobSpawnSettings; +import dev.wyck.environment.GrassColorModifier; +import dev.wyck.environment.particle.ParticleCatalog; +import dev.wyck.environment.sounds.AmbientAdditionsSettings; +import dev.wyck.environment.sounds.AmbientMoodSettings; +import dev.wyck.environment.sounds.Music; +import dev.wyck.environment.sounds.SoundEvent; +import dev.wyck.keys.ResourceKey; import io.papermc.paper.registry.RegistryAccess; import io.papermc.paper.registry.RegistryKey; import org.bukkit.Bukkit; import org.bukkit.NamespacedKey; import org.bukkit.entity.EntityType; +import org.bukkit.entity.Villager; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; +import java.util.List; +import java.util.Locale; import com.dfsek.terra.AbstractPlatform; import com.dfsek.terra.api.block.state.BlockState; @@ -42,8 +69,8 @@ import com.dfsek.terra.bukkit.handles.BukkitWorldHandle; import com.dfsek.terra.bukkit.world.BukkitPlatformBiome; -public class PlatformImpl extends AbstractPlatform { - private static final Logger LOGGER = LoggerFactory.getLogger(PlatformImpl.class); +public class BukkitPlatform extends AbstractPlatform { + private static final Logger LOGGER = LoggerFactory.getLogger(BukkitPlatform.class); private final ItemHandle itemHandle = new BukkitItemHandle(); @@ -53,7 +80,7 @@ public class PlatformImpl extends AbstractPlatform { private int generationThreads; - public PlatformImpl(TerraBukkitPlugin plugin) { + public BukkitPlatform(TerraBukkitPlugin plugin) { generationThreads = getMoonriseGenerationThreadsWithReflection(); if(generationThreads == 0) { generationThreads = 1; @@ -88,6 +115,11 @@ public class PlatformImpl extends AbstractPlatform { return "Bukkit"; } + @Override + protected Iterable platformAddon() { + return List.of(new BukkitAddon(this)); + } + @Override public void runPossiblyUnsafeTask(@NotNull Runnable runnable) { plugin.getGlobalRegionScheduler().run(plugin, task -> runnable.run()); @@ -118,8 +150,32 @@ public class PlatformImpl extends AbstractPlatform { super.register(registry); registry.registerLoader(BlockState.class, (type, o, loader, depthTracker) -> handle.createBlockState((String) o)) .registerLoader(PlatformBiome.class, (type, o, loader, depthTracker) -> parseBiome((String) o, depthTracker)) - .registerLoader(EntityType.class, (type, o, loader, depthTracker) -> EntityType.valueOf((String) o)); - + .registerLoader(EntityType.class, (type, o, loader, depthTracker) -> EntityType.valueOf((String) o)) + .registerLoader(PlatformBiome.class, (type, o, loader, depthTracker) -> parseBiome((String) o, depthTracker)) + .registerLoader(ResourceKey.class, (type, o, loader, depthTracker) -> { + String[] parts = ((String) o).split(":", 2); + if(parts.length == 0 || parts.length > 2) + throw new LoadException("Invalid identifier: " + o, depthTracker); + return ResourceKey.of(parts[0], parts[1]); + }) + .registerLoader(GrassColorModifier.class, + (type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase( + Locale.ROOT))) + .registerLoader(GrassColorModifier.class, + (type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase( + Locale.ROOT))) + .registerLoader(MobCategory.class, (type, o, loader, depthTracker) -> MobCategory.valueOf((String) o)) + .registerLoader(ParticleCatalog.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(Villager.Type.class, VillagerTypeTemplate::new); } protected BukkitPlatformBiome parseBiome(String id, DepthTracker depthTracker) throws LoadException { diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java index e1cee73ff..7c46e25d2 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java @@ -13,7 +13,7 @@ public interface NMSInitializer { String MINECRAFT_VERSION = VersionUtil.getMinecraftVersionInfo().toString(); String TERRA_PACKAGE = NMSInitializer.class.getPackageName(); - static PlatformImpl init(TerraBukkitPlugin plugin) { + static BukkitPlatform init(TerraBukkitPlugin plugin) { Logger logger = LoggerFactory.getLogger(NMSInitializer.class); if(!SUPPORTED_VERSIONS.contains(MINECRAFT_VERSION)) { @@ -42,10 +42,10 @@ public interface NMSInitializer { return constructPlatform(plugin); } - private static PlatformImpl constructPlatform(TerraBukkitPlugin plugin) { + private static BukkitPlatform constructPlatform(TerraBukkitPlugin plugin) { try { Class platformClass = Class.forName(TERRA_PACKAGE + ".nms.NMSPlatform"); - return (PlatformImpl) platformClass + return (BukkitPlatform) platformClass .getConstructor(TerraBukkitPlugin.class) .newInstance(plugin); } catch(ReflectiveOperationException e) { diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java index fe18d290d..06b3cc3cd 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java @@ -48,7 +48,7 @@ import com.dfsek.terra.bukkit.world.BukkitAdapter; public class TerraBukkitPlugin extends JavaPlugin { private static final Logger logger = LoggerFactory.getLogger(TerraBukkitPlugin.class); private final Map generatorMap = new HashMap<>(); - private PlatformImpl platform; + private BukkitPlatform platform; private AsyncScheduler asyncScheduler = this.getServer().getAsyncScheduler(); private GlobalRegionScheduler globalRegionScheduler = this.getServer().getGlobalRegionScheduler(); @@ -101,7 +101,7 @@ public class TerraBukkitPlugin extends JavaPlugin { return commandManager; } - public PlatformImpl getPlatform() { + public BukkitPlatform getPlatform() { return platform; } diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeAdditionsSoundTemplate.java similarity index 66% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java rename to platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeAdditionsSoundTemplate.java index 3e3286098..ae39c84ac 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeAdditionsSoundTemplate.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeAdditionsSoundTemplate.java @@ -1,11 +1,10 @@ -package com.dfsek.terra.bukkit.nms.config; +package com.dfsek.terra.bukkit.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; +import dev.wyck.environment.sounds.AmbientAdditionsSettings; +import dev.wyck.environment.sounds.SoundEvent; public class BiomeAdditionsSoundTemplate implements ObjectTemplate { @@ -22,7 +21,10 @@ public class BiomeAdditionsSoundTemplate implements ObjectTemplate { @@ -30,8 +29,12 @@ public class BiomeMoodSoundTemplate implements ObjectTemplate { + @Value("particle") + @Default + private String particle = null; + + @Value("probability") + @Default + private Float probability = 0.1f; + + @Override + public ParticleCatalog get() { + if(particle == null) { + return null; + } else { + ParticleOptions particleOptions = ParticleArgument.readParticle(new StringReader(particle)); + return ParticleCatalog.builder() + .particle(particleOptions) // TODO: Check that this supports custom particles + .probability(probability) + .build(); + } + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/EntityTypeTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/EntityTypeTemplate.java new file mode 100644 index 000000000..5472bad00 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/EntityTypeTemplate.java @@ -0,0 +1,22 @@ +package com.dfsek.terra.bukkit.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 dev.wyck.keys.ResourceKey; +import io.papermc.paper.registry.RegistryAccess; +import io.papermc.paper.registry.RegistryKey; +import org.bukkit.entity.EntityType; + + +public class EntityTypeTemplate implements ObjectTemplate { + @Value("id") + @Default + private ResourceKey id = null; + + @Override + public EntityType get() { + return RegistryAccess.registryAccess().getRegistry(RegistryKey.ENTITY_TYPE) + .getOrThrow(id); + } +} diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/MusicSoundTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/MusicSoundTemplate.java similarity index 69% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/MusicSoundTemplate.java rename to platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/MusicSoundTemplate.java index 890759a69..d5438675e 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/MusicSoundTemplate.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/MusicSoundTemplate.java @@ -1,11 +1,10 @@ -package com.dfsek.terra.bukkit.nms.config; +package com.dfsek.terra.bukkit.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 dev.wyck.environment.sounds.Music; +import dev.wyck.environment.sounds.SoundEvent; public class MusicSoundTemplate implements ObjectTemplate { @@ -30,7 +29,12 @@ public class MusicSoundTemplate implements ObjectTemplate { if(sound == null || minDelay == null || maxDelay == null || replaceCurrentMusic == null) { return null; } else { - return new Music(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(sound), minDelay, maxDelay, replaceCurrentMusic); + return Music.builder() + .sound(sound) + .minDelay(minDelay) + .maxDelay(maxDelay) + .replaceCurrentMusic(replaceCurrentMusic) + .build(); } } } diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SoundEventTemplate.java similarity index 65% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java rename to platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SoundEventTemplate.java index 4d7b7bddd..6af7bee60 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SoundEventTemplate.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SoundEventTemplate.java @@ -1,16 +1,16 @@ -package com.dfsek.terra.bukkit.nms.config; +package com.dfsek.terra.bukkit.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; +import dev.wyck.environment.sounds.SoundEvent; +import dev.wyck.keys.ResourceKey; public class SoundEventTemplate implements ObjectTemplate { @Value("id") @Default - private Identifier id = null; + private ResourceKey id = null; @Value("distance-to-travel") @Default @@ -21,9 +21,9 @@ public class SoundEventTemplate implements ObjectTemplate { if(id == null) { return null; } else if(distanceToTravel == null) { - return SoundEvent.createVariableRangeEvent(id); + return SoundEvent.variableRange(id); } else { - return SoundEvent.createFixedRangeEvent(id, distanceToTravel); + return SoundEvent.fixedRange(id, distanceToTravel); } } } diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnCostConfig.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnCostConfig.java similarity index 80% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnCostConfig.java rename to platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnCostConfig.java index f84c58491..eb5b522d5 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnCostConfig.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnCostConfig.java @@ -1,15 +1,15 @@ -package com.dfsek.terra.bukkit.nms.config; +package com.dfsek.terra.bukkit.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; +import org.bukkit.entity.EntityType; public class SpawnCostConfig implements ObjectTemplate { @Value("type") @Default - private EntityType type = null; + private EntityType type = null; @Value("mass") @Default @@ -19,7 +19,7 @@ public class SpawnCostConfig implements ObjectTemplate { @Default private Double gravity = null; - public EntityType getType() { + public EntityType getType() { return type; } diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnEntryConfig.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnEntryConfig.java similarity index 69% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnEntryConfig.java rename to platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnEntryConfig.java index 60a763769..97e6f69e6 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnEntryConfig.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnEntryConfig.java @@ -1,18 +1,20 @@ -package com.dfsek.terra.bukkit.nms.config; +package com.dfsek.terra.bukkit.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; -import net.minecraft.world.level.biome.MobSpawnSettings.SpawnerData; import com.dfsek.terra.api.util.range.Range; +import dev.wyck.biome.entity.SpawnerData; +import dev.wyck.worldgen.valueproviders.IntProvider; +import org.bukkit.entity.EntityType; + public class SpawnEntryConfig implements ObjectTemplate { @Value("type") @Default - private EntityType type = null; + private EntityType type = null; @Value("weight") @Default @@ -27,7 +29,7 @@ public class SpawnEntryConfig implements ObjectTemplate { } public SpawnerData getSpawnEntry() { - return new SpawnerData(type, groupSize.getMin(), groupSize.getMax()); + return SpawnerData.of(type, IntProvider.uniform(groupSize.getMin(), groupSize.getMax())); } @Override diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnSettingsTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnSettingsTemplate.java similarity index 80% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnSettingsTemplate.java rename to platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnSettingsTemplate.java index 7950f3389..2598dfd08 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnSettingsTemplate.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnSettingsTemplate.java @@ -1,10 +1,10 @@ -package com.dfsek.terra.bukkit.nms.config; +package com.dfsek.terra.bukkit.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 dev.wyck.biome.entity.MobCategory; +import dev.wyck.biome.entity.MobSpawnSettings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,7 +30,7 @@ public class SpawnSettingsTemplate implements ObjectTemplate { @Override public MobSpawnSettings get() { - MobSpawnSettings.Builder builder = new MobSpawnSettings.Builder(); + MobSpawnSettings.Builder builder = MobSpawnSettings.builder(); for(SpawnTypeConfig spawn : spawns) { MobCategory group = spawn.getGroup(); for(SpawnEntryConfig entry : spawn.getEntries()) { @@ -38,7 +38,7 @@ public class SpawnSettingsTemplate implements ObjectTemplate { } } for(SpawnCostConfig cost : costs) { - builder.addMobCharge(cost.getType(), cost.getMass(), cost.getGravity()); + builder.addMobSpawnCost(cost.getType(), cost.getMass(), cost.getGravity()); } if(probability != null) { builder.creatureGenerationProbability(probability); diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnTypeConfig.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnTypeConfig.java similarity index 88% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnTypeConfig.java rename to platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnTypeConfig.java index ee32f67d5..577857bc9 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/SpawnTypeConfig.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnTypeConfig.java @@ -1,9 +1,9 @@ -package com.dfsek.terra.bukkit.nms.config; +package com.dfsek.terra.bukkit.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 dev.wyck.biome.entity.MobCategory; import java.util.List; diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VanillaBiomeProperties.java similarity index 80% rename from platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java rename to platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VanillaBiomeProperties.java index c5637007d..c6c30bb0d 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VanillaBiomeProperties.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VanillaBiomeProperties.java @@ -1,21 +1,22 @@ -package com.dfsek.terra.bukkit.nms.config; +package com.dfsek.terra.bukkit.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.entity.npc.villager.VillagerType; -import net.minecraft.world.attribute.AmbientAdditionsSettings; -import net.minecraft.world.attribute.AmbientMoodSettings; -import net.minecraft.world.attribute.AmbientParticle; -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; +import dev.wyck.biome.TemperatureModifier; +import dev.wyck.biome.entity.MobSpawnSettings; +import dev.wyck.environment.GrassColorModifier; +import dev.wyck.environment.particle.AmbientParticle; +import dev.wyck.environment.particle.ParticleCatalog; +import dev.wyck.environment.sounds.AmbientAdditionsSettings; +import dev.wyck.environment.sounds.AmbientMoodSettings; +import dev.wyck.environment.sounds.Music; +import dev.wyck.environment.sounds.SoundEvent; +import org.bukkit.entity.Villager; + public class VanillaBiomeProperties implements ConfigTemplate, Properties { @Value("colors.grass") @@ -52,7 +53,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties { @Value("particles") @Default - private AmbientParticle particleConfig = null; + private ParticleCatalog particleConfig = null; @Value("climate.precipitation") @Default @@ -96,7 +97,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties { @Value("villager-type") @Default - private ResourceKey villagerType = null; + private Villager.Type villagerType = null; public Integer getFogColor() { return fogColor; @@ -130,7 +131,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties { return grassColorModifier; } - public AmbientParticle getParticleConfig() { + public ParticleCatalog getParticles() { return particleConfig; } @@ -174,7 +175,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties { return spawnSettings; } - public ResourceKey getVillagerType() { + public Villager.Type getVillagerType() { return villagerType; } } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VillagerTypeTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VillagerTypeTemplate.java new file mode 100644 index 000000000..ff3974d3e --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VillagerTypeTemplate.java @@ -0,0 +1,22 @@ +package com.dfsek.terra.bukkit.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 dev.wyck.keys.ResourceKey; +import io.papermc.paper.registry.RegistryAccess; +import io.papermc.paper.registry.RegistryKey; +import org.bukkit.entity.Villager; + + +public class VillagerTypeTemplate implements ObjectTemplate { + @Value("id") + @Default + private ResourceKey id = null; + + @Override + public Villager.Type get() { + return RegistryAccess.registryAccess().getRegistry(RegistryKey.VILLAGER_TYPE) + .getOrThrow(id); + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/CommonListener.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/CommonListener.java index 5cb6ab4e6..9a06dd3c9 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/CommonListener.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/CommonListener.java @@ -17,6 +17,7 @@ package com.dfsek.terra.bukkit.listeners; +import dev.wyck.keys.ResourceKey; import org.bukkit.NamespacedKey; import org.bukkit.World; import org.bukkit.entity.Entity; @@ -85,10 +86,10 @@ public class CommonListener implements Listener { return; } - NamespacedKey biomeKey = wolf.getWorld().getBiome(wolf.getLocation()).getKey(); + ResourceKey biomeKey = ResourceKey.of(wolf.getWorld().getBiome(wolf.getLocation()).getKey()); pack.getBiomeProvider().stream() .filter(biome -> { - NamespacedKey key = ((BukkitPlatformBiome) biome.getPlatformBiome()).getContext() + ResourceKey key = ((BukkitPlatformBiome) biome.getPlatformBiome()).getContext() .get(BukkitBiomeInfo.class) .biomeKey(); return key.equals(biomeKey); diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java new file mode 100644 index 000000000..2bf32e74d --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java @@ -0,0 +1,92 @@ +package com.dfsek.terra.bukkit.world; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.bukkit.config.VanillaBiomeProperties; + +import dev.wyck.biome.Biome; +import dev.wyck.biome.Biome.Builder; +import dev.wyck.biome.BiomeGenerationSettings; +import dev.wyck.biome.BiomeSpecialEffects; +import dev.wyck.biome.ClimateSettings; +import dev.wyck.environment.attribute.EnvironmentAttributeSupplier; +import dev.wyck.environment.attribute.EnvironmentAttributes; +import dev.wyck.environment.sounds.AmbientSounds; +import dev.wyck.environment.sounds.BackgroundMusic; +import dev.wyck.keys.KeyChains; +import dev.wyck.keys.ResourceKey; + +import java.util.Locale; +import java.util.Objects; + + +public class BiomeHandler { + + public static Biome getBiome(ResourceKey key) { + Biome biome = KeyChains.BIOMES.get(key); + return biome != null ? biome.wrap() : null; + } + + public static Biome getBiomeOrThrow(ResourceKey key) { + return KeyChains.BIOMES.getOrThrow(key); + } + + public static Biome createBiome(ResourceKey vanillaBiomeKey, VanillaBiomeProperties vanillaBiomeProperties) + throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { + Biome vanilla = getBiomeOrThrow(vanillaBiomeKey); + Builder builder = dev.wyck.biome.Biome.builder(); + + setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.FOG_COLOR, vanillaBiomeProperties.getFogColor()); + setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.WATER_FOG_COLOR, vanillaBiomeProperties.getWaterFogColor()); + setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.SKY_COLOR, vanillaBiomeProperties.getSkyColor()); + setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.AMBIENT_PARTICLES, vanillaBiomeProperties.getParticles()); + setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.AMBIENT_SOUNDS, AmbientSounds.builder() + .loop(vanillaBiomeProperties.getLoopSound()) + .mood(vanillaBiomeProperties.getMoodSound()) + .addition(vanillaBiomeProperties.getAdditionsSound()) + .build()); + setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.BACKGROUND_MUSIC, BackgroundMusic.builder() + .defaultMusic(vanillaBiomeProperties.getMusic()) + .build()); + setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.MUSIC_VOLUME, vanillaBiomeProperties.getMusicVolume()); + setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.NATURAL_MOB_SPAWNS, vanillaBiomeProperties.getSpawnSettings()); + + builder.climateSettings(ClimateSettings.builder() + .hasPrecipitation(Objects.requireNonNullElse(vanillaBiomeProperties.getPrecipitation(), vanilla.climateSettings().hasPrecipitation())) + .temperature(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperature(), vanilla.climateSettings().temperature())) + .temperatureModifier(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperatureModifier(), vanilla.climateSettings().temperatureModifier())) + .downfall(Objects.requireNonNullElse(vanillaBiomeProperties.getDownfall(), vanilla.climateSettings().downfall())) + .build()); + + BiomeSpecialEffects.Builder effects = BiomeSpecialEffects.builder(); + effects.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.specialEffects().waterColor())); + effects.grassColorModifier(Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(), vanilla.specialEffects().grassColorModifier())); + + if(vanillaBiomeProperties.getGrassColor() == null) { + vanilla.specialEffects().grassColorOverride().ifPresent(effects::grassColorOverride); + } else { + effects.grassColorOverride(vanillaBiomeProperties.getGrassColor()); + } + + if(vanillaBiomeProperties.getFoliageColor() == null) { + vanilla.specialEffects().foliageColorOverride().ifPresent(effects::foliageColorOverride); + } else { + effects.foliageColorOverride(vanillaBiomeProperties.getFoliageColor()); + } + + return builder + .specialEffects(effects.build()) + .generationSettings(BiomeGenerationSettings.builder() + .build()) + .build(); + } + + public static String createBiomeID(ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey biomeID) { + return pack.getID().toLowerCase(Locale.ROOT) + + "/" + biomeID.getNamespace().toLowerCase(Locale.ROOT) + + "/" + biomeID.getID().toLowerCase(Locale.ROOT); + } + + private static void setAttributeOrDefault(Biome.Builder builder, Biome def, EnvironmentAttributeSupplier attribute, T value) { + builder.attribute(attribute, Objects.requireNonNullElse(value, def.attributes().get(attribute))); + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java index 9079005e9..a2918aad7 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java @@ -1,9 +1,9 @@ package com.dfsek.terra.bukkit.world; -import org.bukkit.NamespacedKey; +import dev.wyck.keys.ResourceKey; import com.dfsek.terra.api.properties.Properties; -public record BukkitBiomeInfo(NamespacedKey biomeKey) implements Properties { +public record BukkitBiomeInfo(ResourceKey biomeKey) implements Properties { } diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java deleted file mode 100644 index 310e4190f..000000000 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/AwfulBukkitHacks.java +++ /dev/null @@ -1,164 +0,0 @@ -package com.dfsek.terra.bukkit.nms; - -import net.minecraft.core.Holder; -import net.minecraft.core.Holder.Reference; -import net.minecraft.core.HolderSet; -import net.minecraft.core.HolderSet.Named; -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.ResourceKey; -import net.minecraft.tags.TagKey; -import net.minecraft.world.entity.npc.villager.VillagerType; -import net.minecraft.world.level.biome.Biome; -import org.bukkit.NamespacedKey; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties; -import com.dfsek.terra.bukkit.world.BukkitBiomeInfo; -import com.dfsek.terra.bukkit.world.BukkitPlatformBiome; -import com.dfsek.terra.registry.master.ConfigRegistry; - - -public class AwfulBukkitHacks { - private static final Logger LOGGER = LoggerFactory.getLogger(AwfulBukkitHacks.class); - - private static final Map> terraBiomeMap = new HashMap<>(); - - public static void registerBiomes(ConfigRegistry configRegistry) { - try { - LOGGER.info("Hacking biome registry..."); - MappedRegistry biomeRegistry = (MappedRegistry) RegistryFetcher.biomeRegistry(); - - // Unfreeze the biome registry to allow modification - Reflection.MAPPED_REGISTRY.setFrozen(biomeRegistry, false); - - // Register the terra biomes to the registry - configRegistry.forEach(pack -> pack.getRegistry(com.dfsek.terra.api.world.biome.Biome.class).forEach((key, biome) -> { - try { - BukkitPlatformBiome platformBiome = (BukkitPlatformBiome) biome.getPlatformBiome(); - - NamespacedKey vanillaBukkitKey = platformBiome.getHandle().getKey(); - Identifier vanillaMinecraftKey = Identifier.fromNamespaceAndPath(vanillaBukkitKey.getNamespace(), - vanillaBukkitKey.getKey()); - - VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class); - - Biome platform = NMSBiomeInjector.createBiome(biomeRegistry.get(vanillaMinecraftKey).orElseThrow().value(), - vanillaBiomeProperties); - - Identifier delegateMinecraftKey = Identifier.fromNamespaceAndPath("terra", - NMSBiomeInjector.createBiomeID(pack, key)); - NamespacedKey delegateBukkitKey = NamespacedKey.fromString(delegateMinecraftKey.toString()); - ResourceKey delegateKey = ResourceKey.create(Registries.BIOME, delegateMinecraftKey); - - Reference holder = biomeRegistry.register(delegateKey, platform, RegistrationInfo.BUILT_IN); - Reflection.REFERENCE.invokeBindValue(holder, platform); // IMPORTANT: bind holder. - - platformBiome.getContext().put(new BukkitBiomeInfo(delegateBukkitKey)); - platformBiome.getContext().put(new NMSBiomeInfo(delegateKey)); - - Map, ResourceKey> villagerMap = Reflection.VILLAGER_TYPE.getByBiome(); - - villagerMap.put(delegateKey, - Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(), - villagerMap.getOrDefault(delegateKey, VillagerType.PLAINS))); - - terraBiomeMap.computeIfAbsent(vanillaMinecraftKey, i -> new ArrayList<>()).add(delegateKey.identifier()); - - LOGGER.debug("Registered biome: " + delegateKey); - } catch(NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } - })); - - Reflection.MAPPED_REGISTRY.setFrozen(biomeRegistry, true); // freeze registry again :) - - LOGGER.info("Doing tag garbage...."); - Map, List>> collect = biomeRegistry - .getTags() // streamKeysAndEntries - .collect(HashMap::new, - (map, pair) -> - map.put(pair.key(), new ArrayList<>(Reflection.HOLDER_SET.invokeContents(pair).stream().toList())), - HashMap::putAll); - - terraBiomeMap - .forEach((vb, terraBiomes) -> - NMSBiomeInjector.getEntry(biomeRegistry, vb).ifPresentOrElse( - vanilla -> terraBiomes.forEach( - tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb).ifPresentOrElse( - terra -> { - LOGGER.debug("{} (vanilla for {}): {}", - vanilla.unwrapKey().orElseThrow().identifier(), - 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))); - - resetTags(biomeRegistry); - bindTags(biomeRegistry, collect); - - } catch(SecurityException | IllegalArgumentException exception) { - throw new RuntimeException(exception); - } - } - - private static void bindTags(MappedRegistry registry, Map, List>> tagEntries) { - Map, List>> map = new IdentityHashMap<>(); - Reflection.MAPPED_REGISTRY.getByKey(registry).values().forEach(entry -> map.put(entry, new ArrayList<>())); - tagEntries.forEach((tag, entries) -> { - for(Holder holder : entries) { - // if (!holder.canSerializeIn(registry.asLookup())) { - // throw new IllegalStateException("Can't create named set " + tag + " containing value " + holder + " - // from outside registry " + this); - // } - - if(!(holder instanceof Holder.Reference reference)) { - throw new IllegalStateException("Found direct holder " + holder + " value in tag " + tag); - } - - map.get(reference).add(tag); - } - }); - // Set> set = Sets.difference(registry.tags.keySet(), tagEntries.keySet()); - // if (!set.isEmpty()) { - // LOGGER.warn( - // "Not all defined tags for registry {} are present in data pack: {}", - // registry.key(), - // set.stream().map(tag -> tag.location().toString()).sorted().collect(Collectors.joining(", ")) - // ); - // } - - Map, HolderSet.Named> map2 = new IdentityHashMap<>(registry.getTags().collect(Collectors.toMap( - Named::key, - (named) -> named - ))); - tagEntries.forEach((tag, entries) -> Reflection.HOLDER_SET.invokeBind( - map2.computeIfAbsent(tag, key -> Reflection.MAPPED_REGISTRY.invokeCreateTag(registry, key)), entries)); - map.forEach(Reflection.HOLDER_REFERENCE::invokeBindTags); - Reflection.MAPPED_REGISTRY.setAllTags(registry, Reflection.MAPPED_REGISTRY_TAG_SET.invokeFromMap(map2)); - } - - private static void resetTags(MappedRegistry registry) { - registry.getTags().forEach(entryList -> Reflection.HOLDER_SET.invokeBind(entryList, List.of())); - Reflection.MAPPED_REGISTRY.getByKey(registry).values().forEach( - entry -> Reflection.HOLDER_REFERENCE.invokeBindTags(entry, Set.of())); - } -} - diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSAddon.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSAddon.java deleted file mode 100644 index 4b3850018..000000000 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSAddon.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.dfsek.terra.bukkit.nms; - -import com.dfsek.terra.api.event.events.config.ConfigurationLoadEvent; -import com.dfsek.terra.api.event.functional.FunctionalEventHandler; -import com.dfsek.terra.api.world.biome.Biome; -import com.dfsek.terra.bukkit.BukkitAddon; -import com.dfsek.terra.bukkit.PlatformImpl; -import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties; - - -public class NMSAddon extends BukkitAddon { - - public NMSAddon(PlatformImpl platform) { - super(platform); - } - - @Override - public void initialize() { - super.initialize(); - - terraBukkitPlugin.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(); - } -} diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java deleted file mode 100644 index 5c3de7431..000000000 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInjector.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.dfsek.terra.bukkit.nms; - -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.resources.Identifier; -import net.minecraft.world.attribute.EnvironmentAttributes; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.BiomeGenerationSettings; -import net.minecraft.world.level.biome.BiomeSpecialEffects; - -import java.util.Locale; -import java.util.Objects; -import java.util.Optional; - -import com.dfsek.terra.api.config.ConfigPack; -import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties; - - -public class NMSBiomeInjector { - - public static Optional> getEntry(Registry registry, Identifier identifier) { - return registry.getOptional(identifier) - .flatMap(registry::getResourceKey) - .flatMap(registry::get); - } - - public static Biome createBiome(Biome vanilla, VanillaBiomeProperties vanillaBiomeProperties) - throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { - Biome.BiomeBuilder builder = new Biome.BiomeBuilder(); - - BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder(); - - // TODO: Migrate to EnvironmentAttributes -// builder.setAttribute(EnvironmentAttributes.FOG_COLOR, Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getAttributes().get(EnvironmentAttributes.FOG_COLOR))) - -// effects.fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor())); - effects.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor())) -// .waterFogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanilla.getWaterFogColor())) -// .skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor())) - .grassColorModifier(Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(), - vanilla.getSpecialEffects().grassColorModifier())); -// .backgroundMusicVolume(Objects.requireNonNullElse(vanillaBiomeProperties.getMusicVolume(), vanilla.getBackgroundMusicVolume())); - - if(vanillaBiomeProperties.getGrassColor() == null) { - vanilla.getSpecialEffects().grassColorOverride().ifPresent(effects::grassColorOverride); - } else { - effects.grassColorOverride(vanillaBiomeProperties.getGrassColor()); - } - - if(vanillaBiomeProperties.getFoliageColor() == null) { - vanilla.getSpecialEffects().foliageColorOverride().ifPresent(effects::foliageColorOverride); - } else { - effects.foliageColorOverride(vanillaBiomeProperties.getFoliageColor()); - } - - // TODO -// if(vanillaBiomeProperties.getParticleConfig() == null) { -// vanilla.getSpecialEffects().getAmbientParticleSettings().ifPresent(effects::ambientParticle); -// } else { -// effects.ambientParticle(vanillaBiomeProperties.getParticleConfig()); -// } - -// if(vanillaBiomeProperties.getLoopSound() == null) { -// vanilla.getSpecialEffects().getAmbientLoopSoundEvent().ifPresent(effects::ambientLoopSound); -// } else { -// RegistryFetcher.soundEventRegistry().get(vanillaBiomeProperties.getLoopSound().location()).ifPresent(effects::ambientLoopSound); -// } - -// if(vanillaBiomeProperties.getMoodSound() == null) { -// vanilla.getSpecialEffects().getAmbientMoodSettings().ifPresent(effects::ambientMoodSound); -// } else { -// effects.ambientMoodSound(vanillaBiomeProperties.getMoodSound()); -// } -// -// if(vanillaBiomeProperties.getAdditionsSound() == null) { -// vanilla.getSpecialEffects().getAmbientAdditionsSettings().ifPresent(effects::ambientAdditionsSound); -// } else { -// effects.ambientAdditionsSound(vanillaBiomeProperties.getAdditionsSound()); -// } -// -// if(vanillaBiomeProperties.getMusic() == null) { -// vanilla.getSpecialEffects().getBackgroundMusic().ifPresent(effects::backgroundMusic); -// } else { -// effects.backgroundMusic(vanillaBiomeProperties.getMusic()); -// } - - builder.hasPrecipitation(Objects.requireNonNullElse(vanillaBiomeProperties.getPrecipitation(), vanilla.hasPrecipitation())); - - builder.temperature(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperature(), vanilla.getBaseTemperature())); - - builder.downfall(Objects.requireNonNullElse(vanillaBiomeProperties.getDownfall(), vanilla.climateSettings.downfall())); - - builder.temperatureAdjustment( - Objects.requireNonNullElse(vanillaBiomeProperties.getTemperatureModifier(), vanilla.climateSettings.temperatureModifier())); - - builder.mobSpawnSettings(Objects.requireNonNullElse(vanillaBiomeProperties.getSpawnSettings(), vanilla.getMobSettings())); - - return builder - .specialEffects(effects.build()) - .generationSettings(new BiomeGenerationSettings.PlainBuilder().build()) - .build(); - } - - public static String createBiomeID(ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey biomeID) { - return pack.getID() - .toLowerCase() + "/" + biomeID.getNamespace().toLowerCase(Locale.ROOT) + "/" + biomeID.getID().toLowerCase(Locale.ROOT); - } -} diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java deleted file mode 100644 index c8b0c7036..000000000 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSPlatform.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.dfsek.terra.bukkit.nms; - -import com.dfsek.tectonic.api.TypeRegistry; -import com.dfsek.tectonic.api.exception.LoadException; -import net.minecraft.resources.Identifier; -import net.minecraft.sounds.Music; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.world.attribute.AmbientParticle; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.MobCategory; -import net.minecraft.world.attribute.AmbientAdditionsSettings; -import net.minecraft.world.attribute.AmbientMoodSettings; -import net.minecraft.world.entity.npc.villager.VillagerType; -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 org.bukkit.Bukkit; - -import java.util.List; -import java.util.Locale; - -import com.dfsek.terra.addon.InternalAddon; -import com.dfsek.terra.api.addon.BaseAddon; -import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent; -import com.dfsek.terra.api.event.functional.FunctionalEventHandler; -import com.dfsek.terra.api.world.biome.PlatformBiome; -import com.dfsek.terra.bukkit.PlatformImpl; -import com.dfsek.terra.bukkit.TerraBukkitPlugin; -import com.dfsek.terra.bukkit.nms.config.BiomeAdditionsSoundTemplate; -import com.dfsek.terra.bukkit.nms.config.BiomeMoodSoundTemplate; -import com.dfsek.terra.bukkit.nms.config.BiomeParticleConfigTemplate; -import com.dfsek.terra.bukkit.nms.config.EntityTypeTemplate; -import com.dfsek.terra.bukkit.nms.config.MusicSoundTemplate; -import com.dfsek.terra.bukkit.nms.config.SoundEventTemplate; -import com.dfsek.terra.bukkit.nms.config.SpawnCostConfig; -import com.dfsek.terra.bukkit.nms.config.SpawnEntryConfig; -import com.dfsek.terra.bukkit.nms.config.SpawnSettingsTemplate; -import com.dfsek.terra.bukkit.nms.config.SpawnTypeConfig; -import com.dfsek.terra.bukkit.nms.config.VillagerTypeTemplate; - - -public class NMSPlatform extends PlatformImpl { - - public NMSPlatform(TerraBukkitPlugin plugin) { - super(plugin); - - Bukkit.getPluginManager().registerEvents(new NMSInjectListener(), plugin); - } - - @Override - public void register(TypeRegistry registry) { - super.register(registry); - registry.registerLoader(PlatformBiome.class, (type, o, loader, depthTracker) -> parseBiome((String) o, depthTracker)) - .registerLoader(Identifier.class, (type, o, loader, depthTracker) -> { - Identifier identifier = Identifier.tryParse((String) o); - if(identifier == null) - throw new LoadException("Invalid identifier: " + o, depthTracker); - return identifier; - }) - .registerLoader(Precipitation.class, (type, o, loader, depthTracker) -> Precipitation.valueOf(((String) o).toUpperCase( - Locale.ROOT))) - .registerLoader(GrassColorModifier.class, - (type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase( - Locale.ROOT))) - .registerLoader(GrassColorModifier.class, - (type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase( - Locale.ROOT))) - .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); - } - - @Override - protected InternalAddon load() { - InternalAddon internalAddon = super.load(); - - this.getEventManager().getHandler(FunctionalEventHandler.class) - .register(internalAddon, PlatformInitializationEvent.class) - .priority(1) - .then(event -> AwfulBukkitHacks.registerBiomes(this.getRawConfigRegistry())) - .global(); - - return internalAddon; - } - - @Override - protected Iterable platformAddon() { - return List.of(new NMSAddon(this)); - } -} diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java deleted file mode 100644 index 7c31521f2..000000000 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/BiomeParticleConfigTemplate.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.dfsek.terra.bukkit.nms.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/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/EntityTypeTemplate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/EntityTypeTemplate.java deleted file mode 100644 index 2e171138d..000000000 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/EntityTypeTemplate.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.dfsek.terra.bukkit.nms.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/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java deleted file mode 100644 index ab25b5011..000000000 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/config/VillagerTypeTemplate.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.dfsek.terra.bukkit.nms.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.ResourceKey; -import net.minecraft.resources.Identifier; -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(BuiltInRegistries.VILLAGER_TYPE.key(), id); - } -} From c2a5df8e836a250e5fe61ac250afd92b4d2156fc Mon Sep 17 00:00:00 2001 From: Oak Date: Sun, 1 Nov 2026 21:13:38 +0000 Subject: [PATCH 27/44] Updated dev-server plugins --- platforms/bukkit/build.gradle.kts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/platforms/bukkit/build.gradle.kts b/platforms/bukkit/build.gradle.kts index b55db49b6..caae54a77 100644 --- a/platforms/bukkit/build.gradle.kts +++ b/platforms/bukkit/build.gradle.kts @@ -32,8 +32,9 @@ tasks { pluginJars(shadowJar.get().archiveFile) downloadPlugins { - modrinth("viaversion", "5.5.0") - modrinth("viabackwards", "5.5.0") + modrinth("viaversion", "5.12.2") + modrinth("viabackwards", "5.12.2") + modrinth("wyck", Versions.Bukkit.wyck) } } } From 8d1a43ece3311c83cd4a5f9bf242818ad550b3e3 Mon Sep 17 00:00:00 2001 From: Oak Date: Sun, 1 Nov 2026 21:13:48 +0000 Subject: [PATCH 28/44] Added Wyck as a hard-dependency and bumped api-version to 26.3 --- platforms/bukkit/common/src/main/resources/plugin.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/platforms/bukkit/common/src/main/resources/plugin.yml b/platforms/bukkit/common/src/main/resources/plugin.yml index 7bde40344..85f9e998a 100644 --- a/platforms/bukkit/common/src/main/resources/plugin.yml +++ b/platforms/bukkit/common/src/main/resources/plugin.yml @@ -4,6 +4,7 @@ version: "@VERSION@" load: "STARTUP" authors: [ "dfsek", "duplexsystem", "Astrash", "solonovamax", "Sancires", "Aureus", "RogueShade", "OakLoaf" ] website: "@WIKI@" -api-version: "1.21.1" +api-version: "26.3" description: "@DESCRIPTION@" folia-supported: true +depend: [ "Wyck" ] From 6b38537d639457a9b6edef8f0054b60fecc92856 Mon Sep 17 00:00:00 2001 From: Oak Date: Mon, 2 Nov 2026 23:04:41 +0000 Subject: [PATCH 29/44] Prepared BiomeProvider --- .../bukkit/world/BukkitBiomeProvider.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeProvider.java diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeProvider.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeProvider.java new file mode 100644 index 000000000..f18196560 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeProvider.java @@ -0,0 +1,40 @@ +package com.dfsek.terra.bukkit.world; + +import dev.wyck.biome.Biome; +import dev.wyck.worldgen.biome.custom.BiomeSourceContext; +import dev.wyck.worldgen.biome.custom.CustomBiomeSource; + +import java.util.Set; +import java.util.stream.Collectors; + +import com.dfsek.terra.api.world.biome.generation.BiomeProvider; + + +public class BukkitBiomeProvider extends CustomBiomeSource { + private final BiomeProvider delegate; + private final long seed; + + public BukkitBiomeProvider(BiomeProvider delegate, long seed) { + super(); + this.delegate = delegate; + this.seed = seed; + } + + @Override + public Biome biome(BiomeSourceContext context) { + return BiomeHandler.getBiomeOrThrow(((BukkitPlatformBiome) delegate.getBiome(context.blockX() << 2, context.blockY() << 2, context.blockZ() << 2, seed) + .getPlatformBiome()).getContext() + .get(BukkitBiomeInfo.class) + .biomeKey()); + } + + @Override + public Set possibleBiomes() { + return delegate.stream() + .map(biome -> BiomeHandler.getBiomeOrThrow(((BukkitPlatformBiome) biome.getPlatformBiome()) + .getContext() + .get(BukkitBiomeInfo.class) + .biomeKey())) + .collect(Collectors.toSet()); + } +} From bef99469a04020f76451804edc808cde468afc10 Mon Sep 17 00:00:00 2001 From: Oak Date: Tue, 3 Nov 2026 11:59:38 +0000 Subject: [PATCH 30/44] Removed already migrated code --- .../dfsek/terra/bukkit/nms/NMSBiomeInfo.java | 10 -- .../terra/bukkit/nms/NMSBiomeProvider.java | 53 ---------- .../dfsek/terra/bukkit/nms/Reflection.java | 96 ------------------- .../terra/bukkit/nms/RegistryFetcher.java | 25 ----- 4 files changed, 184 deletions(-) delete mode 100644 platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInfo.java delete mode 100644 platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeProvider.java delete mode 100644 platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/RegistryFetcher.java diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInfo.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInfo.java deleted file mode 100644 index 5c46273b2..000000000 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeInfo.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.dfsek.terra.bukkit.nms; - -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.biome.Biome; - -import com.dfsek.terra.api.properties.Properties; - - -public record NMSBiomeInfo(ResourceKey biomeKey) implements Properties { -} diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeProvider.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeProvider.java deleted file mode 100644 index 954c5187c..000000000 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/NMSBiomeProvider.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.dfsek.terra.bukkit.nms; - -import com.mojang.serialization.MapCodec; -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.BiomeSource; -import net.minecraft.world.level.biome.Climate.Sampler; -import org.jetbrains.annotations.NotNull; - -import java.util.stream.Stream; - -import com.dfsek.terra.api.world.biome.generation.BiomeProvider; -import com.dfsek.terra.bukkit.world.BukkitPlatformBiome; - - -public class NMSBiomeProvider extends BiomeSource { - private final BiomeProvider delegate; - private final long seed; - private final Registry biomeRegistry = RegistryFetcher.biomeRegistry(); - - public NMSBiomeProvider(BiomeProvider delegate, long seed) { - super(); - this.delegate = delegate; - this.seed = seed; - } - - @Override - protected Stream> collectPossibleBiomes() { - return delegate.stream() - .map(biome -> RegistryFetcher.biomeRegistry() - .getOrThrow(((BukkitPlatformBiome) biome.getPlatformBiome()).getContext() - .get(NMSBiomeInfo.class) - .biomeKey())); - } - - @Override - protected @NotNull MapCodec codec() { - return MapCodec.assumeMapUnsafe(BiomeSource.CODEC); - // return MapCodec.unit(null); - // BuiltInRegistries.BIOME_SOURCE.byNameCodec().dispatchMap(this::codec, Function.identity()); - // BuiltInRegistries.BIOME_SOURCE.byNameCodec().dispatchStable(BiomeSource::codec, Function.identity()); - // return BiomeSource.CODEC; - } - - @Override - public @NotNull Holder getNoiseBiome(int x, int y, int z, @NotNull Sampler sampler) { - return biomeRegistry.getOrThrow(((BukkitPlatformBiome) delegate.getBiome(x << 2, y << 2, z << 2, seed) - .getPlatformBiome()).getContext() - .get(NMSBiomeInfo.class) - .biomeKey()); - } -} diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java index 316c9ab8b..c5f53bde4 100644 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java +++ b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/Reflection.java @@ -1,82 +1,28 @@ package com.dfsek.terra.bukkit.nms; -import net.minecraft.core.Holder; -import net.minecraft.core.Holder.Reference; -import net.minecraft.core.HolderSet; -import net.minecraft.core.MappedRegistry; -import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ChunkMap; -import net.minecraft.tags.TagKey; -import net.minecraft.world.entity.npc.villager.VillagerType; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.StructureManager; -import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.chunk.status.WorldGenContext; import xyz.jpenilla.reflectionremapper.ReflectionRemapper; import xyz.jpenilla.reflectionremapper.proxy.ReflectionProxyFactory; import xyz.jpenilla.reflectionremapper.proxy.annotation.FieldGetter; import xyz.jpenilla.reflectionremapper.proxy.annotation.FieldSetter; -import xyz.jpenilla.reflectionremapper.proxy.annotation.MethodName; import xyz.jpenilla.reflectionremapper.proxy.annotation.Proxies; -import xyz.jpenilla.reflectionremapper.proxy.annotation.Static; - -import java.util.Collection; -import java.util.List; -import java.util.Map; public class Reflection { - public static final MappedRegistryProxy MAPPED_REGISTRY; - public static final MappedRegistryTagSetProxy MAPPED_REGISTRY_TAG_SET; public static final StructureManagerProxy STRUCTURE_MANAGER; - public static final ReferenceProxy REFERENCE; - - public static final ChunkMapProxy CHUNKMAP; - public static final HolderReferenceProxy HOLDER_REFERENCE; - public static final HolderSetNamedProxy HOLDER_SET; - public static final BiomeProxy BIOME; - public static final VillagerTypeProxy VILLAGER_TYPE; static { ReflectionRemapper reflectionRemapper = ReflectionRemapper.forReobfMappingsInPaperJar(); ReflectionProxyFactory reflectionProxyFactory = ReflectionProxyFactory.create(reflectionRemapper, Reflection.class.getClassLoader()); - MAPPED_REGISTRY = reflectionProxyFactory.reflectionProxy(MappedRegistryProxy.class); - MAPPED_REGISTRY_TAG_SET = reflectionProxyFactory.reflectionProxy(MappedRegistryTagSetProxy.class); STRUCTURE_MANAGER = reflectionProxyFactory.reflectionProxy(StructureManagerProxy.class); - REFERENCE = reflectionProxyFactory.reflectionProxy(ReferenceProxy.class); CHUNKMAP = reflectionProxyFactory.reflectionProxy(ChunkMapProxy.class); - HOLDER_REFERENCE = reflectionProxyFactory.reflectionProxy(HolderReferenceProxy.class); - HOLDER_SET = reflectionProxyFactory.reflectionProxy(HolderSetNamedProxy.class); - BIOME = reflectionProxyFactory.reflectionProxy(BiomeProxy.class); - VILLAGER_TYPE = reflectionProxyFactory.reflectionProxy(VillagerTypeProxy.class); - } - - - @Proxies(MappedRegistry.class) - public interface MappedRegistryProxy { - @FieldGetter("byKey") - Map, Reference> getByKey(MappedRegistry instance); - - @FieldSetter("allTags") - void setAllTags(MappedRegistry instance, Object obj); - - @FieldSetter("frozen") - void setFrozen(MappedRegistry instance, boolean frozen); - - @MethodName("createTag") - HolderSet.Named invokeCreateTag(MappedRegistry instance, TagKey tag); - } - - - @Proxies(className = "net.minecraft.core.MappedRegistry$TagSet") - public interface MappedRegistryTagSetProxy { - @MethodName("fromMap") - @Static - Object invokeFromMap(Map, HolderSet.Named> map); } @@ -87,16 +33,6 @@ public class Reflection { } - @Proxies(Holder.Reference.class) - public interface ReferenceProxy { - @MethodName("bindValue") - void invokeBindValue(Reference instance, T value); - - @MethodName("bindTags") - void invokeBindTags(Reference instance, Collection> tags); - } - - @Proxies(ChunkMap.class) public interface ChunkMapProxy { @FieldGetter("worldGenContext") @@ -105,36 +41,4 @@ public class Reflection { @FieldSetter("worldGenContext") void setWorldGenContext(ChunkMap instance, WorldGenContext worldGenContext); } - - - @Proxies(Holder.Reference.class) - public interface HolderReferenceProxy { - @MethodName("bindTags") - void invokeBindTags(Holder.Reference instance, Collection> tags); - } - - - @Proxies(HolderSet.Named.class) - public interface HolderSetNamedProxy { - @MethodName("bind") - void invokeBind(HolderSet.Named instance, List> entries); - - @MethodName("contents") - List> invokeContents(HolderSet.Named instance); - } - - - @Proxies(Biome.class) - public interface BiomeProxy { - @MethodName("getGrassColorFromTexture") - int invokeGrassColorFromTexture(Biome instance); - } - - - @Proxies(VillagerType.class) - public interface VillagerTypeProxy { - @Static - @FieldGetter("BY_BIOME") - Map, ResourceKey> getByBiome(); - } } diff --git a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/RegistryFetcher.java b/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/RegistryFetcher.java deleted file mode 100644 index 0863a2a42..000000000 --- a/platforms/bukkit/nms/src/main/java/com/dfsek/terra/bukkit/nms/RegistryFetcher.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.dfsek.terra.bukkit.nms; - -import net.minecraft.core.Registry; -import net.minecraft.core.registries.Registries; -import net.minecraft.resources.ResourceKey; -import net.minecraft.server.MinecraftServer; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.world.level.biome.Biome; - - -public class RegistryFetcher { - private static Registry getRegistry(ResourceKey> key) { - return MinecraftServer.getServer() - .registryAccess() - .lookupOrThrow(key); - } - - public static Registry biomeRegistry() { - return getRegistry(Registries.BIOME); - } - - public static Registry soundEventRegistry() { - return getRegistry(Registries.SOUND_EVENT); - } -} From b70e75c130fd504b8c2f29be88be7d51db76fdd9 Mon Sep 17 00:00:00 2001 From: Oak Date: Tue, 3 Nov 2026 12:21:12 +0000 Subject: [PATCH 31/44] Removed outdated nms code --- .../dfsek/terra/bukkit/NMSInitializer.java | 55 ------------------- .../dfsek/terra/bukkit/TerraBukkitPlugin.java | 7 +-- 2 files changed, 1 insertion(+), 61 deletions(-) delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java deleted file mode 100644 index 7c46e25d2..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/NMSInitializer.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.dfsek.terra.bukkit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; - -import com.dfsek.terra.bukkit.util.VersionUtil; - - -public interface NMSInitializer { - List SUPPORTED_VERSIONS = List.of("v1.21.11"); - String MINECRAFT_VERSION = VersionUtil.getMinecraftVersionInfo().toString(); - String TERRA_PACKAGE = NMSInitializer.class.getPackageName(); - - static BukkitPlatform init(TerraBukkitPlugin plugin) { - Logger logger = LoggerFactory.getLogger(NMSInitializer.class); - - if(!SUPPORTED_VERSIONS.contains(MINECRAFT_VERSION)) { - logger.error("You are running your server on Minecraft version {} which is not supported by this version of Terra.", - MINECRAFT_VERSION); - - String bypassKey = "IKnowThereAreNoNMSBindingsFor" + MINECRAFT_VERSION.replace(".", "_") + "ButIWillProceedAnyway"; - if(System.getProperty(bypassKey) == null) { - logger.error("Because of this **TERRA HAS BEEN DISABLED**."); - logger.error("Do not come ask us why it is not working."); - logger.error("If you wish to proceed anyways, you can add the JVM System Property \"{}\" to enable the plugin.", bypassKey); - return null; - } else { - logger.error(""); - logger.error(""); - for(int i = 0; i < 20; i++) { - logger.error("PROCEEDING WITH AN EXISTING TERRA WORLD WILL RESULT IN CORRUPTION!!!"); - } - logger.error(""); - logger.error(""); - logger.error("We will not give you any support for issues that may arise."); - logger.error("Since you enabled the \"{}\" flag, we won't disable Terra. But be warned.", bypassKey); - } - } - - return constructPlatform(plugin); - } - - private static BukkitPlatform constructPlatform(TerraBukkitPlugin plugin) { - try { - Class platformClass = Class.forName(TERRA_PACKAGE + ".nms.NMSPlatform"); - return (BukkitPlatform) platformClass - .getConstructor(TerraBukkitPlugin.class) - .newInstance(plugin); - } catch(ReflectiveOperationException e) { - throw new RuntimeException("Error initializing NMS bindings. Report this to Terra.", e); - } - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java index 06b3cc3cd..a0c877081 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java @@ -59,12 +59,7 @@ public class TerraBukkitPlugin extends JavaPlugin { return; } - platform = NMSInitializer.init(this); - if(platform == null) { - Bukkit.getPluginManager().disablePlugin(this); - return; - } - + platform = new BukkitPlatform(this); platform.getEventManager().callEvent(new PlatformInitializationEvent()); try { From a2d18cbfb1669807b7f40aa4ce05d633f71bd348 Mon Sep 17 00:00:00 2001 From: Oak Date: Tue, 3 Nov 2026 12:21:53 +0000 Subject: [PATCH 32/44] Corrected biome getter method --- .../main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java index 2bf32e74d..2f3c06209 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java @@ -27,7 +27,7 @@ public class BiomeHandler { } public static Biome getBiomeOrThrow(ResourceKey key) { - return KeyChains.BIOMES.getOrThrow(key); + return KeyChains.BIOMES.getOrThrow(key).wrap(); } public static Biome createBiome(ResourceKey vanillaBiomeKey, VanillaBiomeProperties vanillaBiomeProperties) From 4775000a57a00b5b0a4b7ada901ab220be8f7833 Mon Sep 17 00:00:00 2001 From: Oak Date: Tue, 3 Nov 2026 12:31:30 +0000 Subject: [PATCH 33/44] Migraed to paper-plugin.yml --- .../{Bootstrapper.java => TerraBootstrapper.java} | 4 ++-- .../main/resources/{plugin.yml => paper-plugin.yml} | 13 ++++++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) rename platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/{Bootstrapper.java => TerraBootstrapper.java} (98%) rename platforms/bukkit/common/src/main/resources/{plugin.yml => paper-plugin.yml} (55%) diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/Bootstrapper.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBootstrapper.java similarity index 98% rename from platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/Bootstrapper.java rename to platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBootstrapper.java index dc2876eb1..2a393d9ac 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/Bootstrapper.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBootstrapper.java @@ -22,8 +22,8 @@ import java.util.List; import java.util.Map; -public class Bootstrapper implements PluginBootstrap { - private static final Logger LOGGER = LoggerFactory.getLogger(Bootstrapper.class); +public class TerraBootstrapper implements PluginBootstrap { + private static final Logger LOGGER = LoggerFactory.getLogger(TerraBootstrapper.class); private static final Map> terraBiomeMap = new HashMap<>(); diff --git a/platforms/bukkit/common/src/main/resources/plugin.yml b/platforms/bukkit/common/src/main/resources/paper-plugin.yml similarity index 55% rename from platforms/bukkit/common/src/main/resources/plugin.yml rename to platforms/bukkit/common/src/main/resources/paper-plugin.yml index 85f9e998a..e36268af3 100644 --- a/platforms/bukkit/common/src/main/resources/plugin.yml +++ b/platforms/bukkit/common/src/main/resources/paper-plugin.yml @@ -5,6 +5,17 @@ load: "STARTUP" authors: [ "dfsek", "duplexsystem", "Astrash", "solonovamax", "Sancires", "Aureus", "RogueShade", "OakLoaf" ] website: "@WIKI@" api-version: "26.3" +bootstrapper: "com.dfsek.terra.bukkit.TerraBootstrapper" description: "@DESCRIPTION@" folia-supported: true -depend: [ "Wyck" ] +depend: + bootstrap: + Wyck: + load: BEFORE + required: true + join-classpath: true + server: + Wyck: + load: BEFORE + required: true + join-classpath: true From 3b37ad6eb4d76a2aa51a3913bae5e9f27330b9ee Mon Sep 17 00:00:00 2001 From: Oak Date: Sat, 7 Nov 2026 12:16:03 +0000 Subject: [PATCH 34/44] Refactored WyckBiomeProvider - could be worth looking at merging with BukkitBiomeProvider --- .../WyckBiomeProvider.java} | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) rename platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/{world/BukkitBiomeProvider.java => generator/WyckBiomeProvider.java} (77%) diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeProvider.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/WyckBiomeProvider.java similarity index 77% rename from platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeProvider.java rename to platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/WyckBiomeProvider.java index f18196560..e1c74363c 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeProvider.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/WyckBiomeProvider.java @@ -1,5 +1,8 @@ -package com.dfsek.terra.bukkit.world; +package com.dfsek.terra.bukkit.generator; +import com.dfsek.terra.bukkit.world.BiomeHandler; +import com.dfsek.terra.bukkit.world.BukkitBiomeInfo; +import com.dfsek.terra.bukkit.world.BukkitPlatformBiome; import dev.wyck.biome.Biome; import dev.wyck.worldgen.biome.custom.BiomeSourceContext; import dev.wyck.worldgen.biome.custom.CustomBiomeSource; @@ -10,11 +13,11 @@ import java.util.stream.Collectors; import com.dfsek.terra.api.world.biome.generation.BiomeProvider; -public class BukkitBiomeProvider extends CustomBiomeSource { +public class WyckBiomeProvider extends CustomBiomeSource { private final BiomeProvider delegate; private final long seed; - public BukkitBiomeProvider(BiomeProvider delegate, long seed) { + public WyckBiomeProvider(BiomeProvider delegate, long seed) { super(); this.delegate = delegate; this.seed = seed; From 4b3dd2b692f1afd05c4c89e1c750dd9a299a5f9a Mon Sep 17 00:00:00 2001 From: Zoe Gidiere Date: Sat, 7 Nov 2026 15:10:55 -0700 Subject: [PATCH 35/44] refactor: migrate mod platforms to Mojang mappings --- buildSrc/src/main/kotlin/Versions.kt | 1 - platforms/fabric/build.gradle.kts | 2 +- ...ConfigMixin.java => RandomStateMixin.java} | 2 +- .../main/resources/terra.forge.mixins.json | 2 +- platforms/mixin-common/build.gradle.kts | 2 +- .../java/com/dfsek/terra/mod/ModPlatform.java | 52 +++---- .../config/BiomeAdditionsSoundTemplate.java | 12 +- .../mod/config/BiomeMoodSoundTemplate.java | 12 +- .../config/BiomeParticleConfigTemplate.java | 11 +- .../terra/mod/config/EntityTypeTemplate.java | 8 +- .../terra/mod/config/MusicSoundTemplate.java | 12 +- .../terra/mod/config/ProtoPlatformBiome.java | 20 +-- .../terra/mod/config/SoundEventTemplate.java | 8 +- .../terra/mod/config/SpawnCostConfig.java | 2 +- .../terra/mod/config/SpawnEntryConfig.java | 8 +- .../mod/config/SpawnSettingsTemplate.java | 18 +-- .../terra/mod/config/SpawnTypeConfig.java | 6 +- .../mod/config/VanillaBiomeProperties.java | 38 ++--- .../mod/config/VanillaWorldProperties.java | 2 +- .../mod/config/VillagerTypeTemplate.java | 14 +- .../java/com/dfsek/terra/mod/data/Codecs.java | 4 +- .../MinecraftChunkGeneratorWrapper.java | 124 +++++++-------- .../mod/generation/TerraBiomeSource.java | 16 +- .../terra/mod/handle/MinecraftItemHandle.java | 30 ++-- .../mod/handle/MinecraftWorldHandle.java | 60 ++++---- .../MinecraftEntityTypeExtended.java | 6 +- .../mod/implmentation/TerraIntProvider.java | 12 +- ...Accessor.java => BaseSpawnerAccessor.java} | 12 +- .../terra/mod/mixin/access/BiomeAccessor.java | 6 +- .../mod/mixin/access/LevelChunkAccessor.java | 15 ++ ...Accessor.java => StateHolderAccessor.java} | 10 +- ...sor.java => StructureManagerAccessor.java} | 10 +- .../mixin/access/VillagerTypeAccessor.java | 10 +- .../mod/mixin/access/WorldChunkAccessor.java | 15 -- .../mixin/generalize/ServerLevelMixin.java | 44 ++++++ .../mixin/generalize/ServerWorldMixin.java | 44 ------ ...GenerationSettingsFloraFeaturesMixin.java} | 8 +- .../implementations/terra/BiomeMixin.java | 2 +- .../terra/HandleImplementationMixin.java | 44 +++--- .../terra/block/BlockMixin.java | 8 +- .../terra/block/entity/BlockEntityMixin.java | 18 +-- ...andomizableContainerBlockEntityMixin.java} | 6 +- .../block/entity/SignBlockEntityMixin.java | 10 +- ...ixin.java => SpawnerBlockEntityMixin.java} | 48 +++--- ...rgumentMixin.java => BlockInputMixin.java} | 42 +++--- ...ateMixin.java => BlockStateBaseMixin.java} | 34 ++--- .../terra/block/state/PropertyMixin.java | 10 +- ...ldChunkMixin.java => LevelChunkMixin.java} | 40 ++--- ...ionMixin.java => WorldGenRegionMixin.java} | 66 ++++---- .../terra/chunk/data/ProtoChunkMixin.java | 38 ++--- ...ixin.java => CommandSourceStackMixin.java} | 18 +-- .../terra/entity/EntityMixin.java | 16 +- .../terra/entity/EntityTypeMixin.java | 2 +- ...layerEntityMixin.java => PlayerMixin.java} | 5 +- ...ava => BaseContainerBlockEntityMixin.java} | 14 +- .../terra/inventory/item/ItemMixin.java | 8 +- .../terra/inventory/item/ItemStackMixin.java | 28 ++-- .../inventory/meta/EnchantmentMixin.java | 18 +-- .../meta/ItemStackDamageableMixin.java | 10 +- .../inventory/meta/ItemStackMetaMixin.java | 24 +-- ...mpoundMixin.java => CompoundTagMixin.java} | 8 +- ...rWorldMixin.java => ServerLevelMixin.java} | 92 ++++++------ ...ionMixin.java => WorldGenRegionMixin.java} | 91 ++++++----- .../terra/mod/mixin/invoke/BiomeInvoker.java | 4 +- .../mod/mixin/invoke/FluidBlockInvoker.java | 14 -- .../mod/mixin/invoke/LiquidBlockInvoker.java | 14 ++ .../lifecycle/DataPackContentsMixin.java | 57 ------- .../ReloadableServerResourcesMixin.java | 55 +++++++ .../mod/mixin_ifaces/FloraFeatureHolder.java | 2 +- .../com/dfsek/terra/mod/util/BiomeUtil.java | 54 +++---- .../dfsek/terra/mod/util/DimensionUtil.java | 10 +- .../terra/mod/util/MinecraftAdapter.java | 16 +- .../dfsek/terra/mod/util/MinecraftUtil.java | 106 ++++++------- .../com/dfsek/terra/mod/util/PresetUtil.java | 142 +++++++++--------- .../com/dfsek/terra/mod/util/SeedHack.java | 8 +- .../com/dfsek/terra/mod/util/TagUtil.java | 52 +++---- .../src/main/resources/terra.accesswidener | 14 +- .../main/resources/terra.common.mixins.json | 40 ++--- platforms/mixin-lifecycle/build.gradle.kts | 2 +- .../terra/lifecycle/LifecycleEntryPoint.java | 4 +- .../terra/lifecycle/LifecyclePlatform.java | 36 ++--- ...Mixin.java => BuiltInRegistriesMixin.java} | 6 +- ...voker.java => HolderReferenceInvoker.java} | 6 +- ...tryMixin.java => MappedRegistryMixin.java} | 14 +- .../lifecycle/mixin/NoiseConfigMixin.java | 34 ----- .../lifecycle/mixin/RandomStateMixin.java | 34 +++++ .../mixin/lifecycle/MinecraftServerMixin.java | 21 ++- .../lifecycle/RegistryDataLoaderMixin.java | 103 +++++++++++++ .../mixin/lifecycle/RegistryLoaderMixin.java | 104 ------------- .../mixin/lifecycle/SaveLoadingMixin.java | 33 ---- .../mixin/lifecycle/WorldLoaderMixin.java | 28 ++++ .../lifecycle/util/LifecycleBiomeUtil.java | 38 ++--- .../terra/lifecycle/util/LifecycleUtil.java | 16 +- .../terra/lifecycle/util/RegistryUtil.java | 10 +- .../resources/terra.lifecycle.mixins.json | 12 +- 95 files changed, 1217 insertions(+), 1230 deletions(-) rename platforms/forge/src/main/java/com/dfsek/terra/forge/mixin/lifecycle/{NoiseConfigMixin.java => RandomStateMixin.java} (97%) rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/{MobSpawnerLogicAccessor.java => BaseSpawnerAccessor.java} (76%) create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/LevelChunkAccessor.java rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/{StateAccessor.java => StateHolderAccessor.java} (80%) rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/{StructureAccessorAccessor.java => StructureManagerAccessor.java} (80%) delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/WorldChunkAccessor.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/generalize/ServerLevelMixin.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/generalize/ServerWorldMixin.java rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/compat/{GenerationSettingsFloraFeaturesMixin.java => BiomeGenerationSettingsFloraFeaturesMixin.java} (82%) rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/{LootableContainerBlockEntityMixin.java => RandomizableContainerBlockEntityMixin.java} (84%) rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/{MobSpawnerBlockEntityMixin.java => SpawnerBlockEntityMixin.java} (71%) rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/{BlockStateArgumentMixin.java => BlockInputMixin.java} (69%) rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/{BlockStateMixin.java => BlockStateBaseMixin.java} (53%) rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/{WorldChunkMixin.java => LevelChunkMixin.java} (64%) rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/{ChunkRegionMixin.java => WorldGenRegionMixin.java} (54%) rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/{ServerCommandSourceMixin.java => CommandSourceStackMixin.java} (77%) rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/{PlayerEntityMixin.java => PlayerMixin.java} (87%) rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/{LockableContainerBlockEntityMixin.java => BaseContainerBlockEntityMixin.java} (73%) rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/nbt/{NbtCompoundMixin.java => CompoundTagMixin.java} (73%) rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/{ServerWorldMixin.java => ServerLevelMixin.java} (57%) rename platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/{ChunkRegionMixin.java => WorldGenRegionMixin.java} (60%) delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/invoke/FluidBlockInvoker.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/invoke/LiquidBlockInvoker.java delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/lifecycle/DataPackContentsMixin.java create mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/lifecycle/ReloadableServerResourcesMixin.java rename platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/{RegistryMixin.java => BuiltInRegistriesMixin.java} (78%) rename platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/{RegistryEntryReferenceInvoker.java => HolderReferenceInvoker.java} (58%) rename platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/{SimpleRegistryMixin.java => MappedRegistryMixin.java} (50%) delete mode 100644 platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/NoiseConfigMixin.java create mode 100644 platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RandomStateMixin.java create mode 100644 platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/RegistryDataLoaderMixin.java delete mode 100644 platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/RegistryLoaderMixin.java delete mode 100644 platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/SaveLoadingMixin.java create mode 100644 platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/WorldLoaderMixin.java diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index c0388d26e..41de76619 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -46,7 +46,6 @@ object Versions { const val mixinExtras = "0.5.0" const val minecraft = "1.21.11" - const val yarn = "$minecraft+build.3" const val fabricLoader = "0.18.3" const val architecturyLoom = "1.13.463" diff --git a/platforms/fabric/build.gradle.kts b/platforms/fabric/build.gradle.kts index c1a427cb3..0797bae7f 100644 --- a/platforms/fabric/build.gradle.kts +++ b/platforms/fabric/build.gradle.kts @@ -22,7 +22,7 @@ dependencies { minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") - mappings("net.fabricmc:yarn:${Versions.Mod.yarn}:v2") + mappings(loom.officialMojangMappings()) modImplementation("net.fabricmc:fabric-loader:${Versions.Mod.fabricLoader}") diff --git a/platforms/forge/src/main/java/com/dfsek/terra/forge/mixin/lifecycle/NoiseConfigMixin.java b/platforms/forge/src/main/java/com/dfsek/terra/forge/mixin/lifecycle/RandomStateMixin.java similarity index 97% rename from platforms/forge/src/main/java/com/dfsek/terra/forge/mixin/lifecycle/NoiseConfigMixin.java rename to platforms/forge/src/main/java/com/dfsek/terra/forge/mixin/lifecycle/RandomStateMixin.java index c61ff8b24..894404f6d 100644 --- a/platforms/forge/src/main/java/com/dfsek/terra/forge/mixin/lifecycle/NoiseConfigMixin.java +++ b/platforms/forge/src/main/java/com/dfsek/terra/forge/mixin/lifecycle/RandomStateMixin.java @@ -19,7 +19,7 @@ import com.dfsek.terra.mod.util.SeedHack; * Hack to map noise sampler to seeds */ @Mixin(NoiseConfig.class) -public class NoiseConfigMixin { +public class RandomStateMixin { @Shadow @Final private MultiSampler multiSampler; diff --git a/platforms/forge/src/main/resources/terra.forge.mixins.json b/platforms/forge/src/main/resources/terra.forge.mixins.json index 095ea9234..3ab945d10 100644 --- a/platforms/forge/src/main/resources/terra.forge.mixins.json +++ b/platforms/forge/src/main/resources/terra.forge.mixins.json @@ -4,7 +4,7 @@ "package": "com.dfsek.terra.forge.mixin", "compatibilityLevel": "JAVA_21", "mixins": [ - "lifecycle.NoiseConfigMixin" + "lifecycle.RandomStateMixin" ], "client": [ ], diff --git a/platforms/mixin-common/build.gradle.kts b/platforms/mixin-common/build.gradle.kts index 97ed1768e..6ad243dcb 100644 --- a/platforms/mixin-common/build.gradle.kts +++ b/platforms/mixin-common/build.gradle.kts @@ -19,7 +19,7 @@ dependencies { annotationProcessor("dev.architectury:architectury-loom:${Versions.Mod.architecturyLoom}") minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") - mappings("net.fabricmc:yarn:${Versions.Mod.yarn}:v2") + mappings(loom.officialMojangMappings()) } architectury { 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 7dbc696b5..b2c815776 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 @@ -3,27 +3,27 @@ package com.dfsek.terra.mod; import com.dfsek.tectonic.api.TypeRegistry; import com.dfsek.tectonic.api.depth.DepthTracker; import com.dfsek.tectonic.api.exception.LoadException; -import net.minecraft.enchantment.Enchantment; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.SpawnGroup; -import net.minecraft.registry.Registry; +import net.minecraft.core.Registry; +import net.minecraft.resources.Identifier; import net.minecraft.server.MinecraftServer; -import net.minecraft.sound.BiomeAdditionsSound; -import net.minecraft.sound.BiomeMoodSound; -import net.minecraft.sound.MusicSound; -import net.minecraft.sound.SoundEvent; -import net.minecraft.util.Identifier; -import net.minecraft.village.VillagerType; +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.biome.Biome; -import net.minecraft.world.biome.Biome.Precipitation; -import net.minecraft.world.biome.Biome.TemperatureModifier; -import net.minecraft.world.biome.BiomeEffects.GrassColorModifier; -import net.minecraft.world.biome.SpawnSettings; -import net.minecraft.world.biome.source.MultiNoiseBiomeSourceParameterList; -import net.minecraft.world.dimension.DimensionType; -import net.minecraft.world.gen.WorldPreset; -import net.minecraft.world.gen.chunk.ChunkGeneratorSettings; +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; +import net.minecraft.world.level.levelgen.presets.WorldPreset; import org.jetbrains.annotations.NotNull; import java.util.HashSet; @@ -86,23 +86,23 @@ public abstract class ModPlatform extends AbstractPlatform { (type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase())) .registerLoader(TemperatureModifier.class, (type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase())) - .registerLoader(SpawnGroup.class, (type, o, loader, depthTracker) -> SpawnGroup.valueOf((String) o)) + .registerLoader(MobCategory.class, (type, o, loader, depthTracker) -> MobCategory.valueOf((String) o)) .registerLoader(AmbientParticle.class, BiomeParticleConfigTemplate::new) .registerLoader(SoundEvent.class, SoundEventTemplate::new) - .registerLoader(BiomeMoodSound.class, BiomeMoodSoundTemplate::new) - .registerLoader(BiomeAdditionsSound.class, BiomeAdditionsSoundTemplate::new) - .registerLoader(MusicSound.class, MusicSoundTemplate::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(SpawnSettings.class, SpawnSettingsTemplate::new) + .registerLoader(MobSpawnSettings.class, SpawnSettingsTemplate::new) .registerLoader(VillagerType.class, VillagerTypeTemplate::new); } private ProtoPlatformBiome parseBiome(String id, DepthTracker tracker) throws LoadException { Identifier identifier = Identifier.tryParse(id); - if(!biomeRegistry().containsId(identifier)) throw new LoadException("Invalid Biome ID: " + identifier, tracker); // failure. + if(!biomeRegistry().containsKey(identifier)) throw new LoadException("Invalid Biome ID: " + identifier, tracker); // failure. return new ProtoPlatformBiome(identifier); } @@ -117,7 +117,7 @@ public abstract class ModPlatform extends AbstractPlatform { public abstract Registry biomeRegistry(); - public abstract Registry chunkGeneratorSettingsRegistry(); + public abstract Registry chunkGeneratorSettingsRegistry(); public abstract Registry multiNoiseBiomeSourceParameterListRegistry(); 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 index 26896e959..6ff620d53 100644 --- 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 @@ -3,12 +3,12 @@ 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.registry.Registries; -import net.minecraft.sound.BiomeAdditionsSound; -import net.minecraft.sound.SoundEvent; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.world.attribute.AmbientAdditionsSettings; -public class BiomeAdditionsSoundTemplate implements ObjectTemplate { +public class BiomeAdditionsSoundTemplate implements ObjectTemplate { @Value("sound") @Default private SoundEvent sound = null; @@ -18,11 +18,11 @@ public class BiomeAdditionsSoundTemplate implements ObjectTemplate { +public class BiomeMoodSoundTemplate implements ObjectTemplate { @Value("sound") @Default private SoundEvent sound = null; @@ -26,11 +26,11 @@ public class BiomeMoodSoundTemplate implements ObjectTemplate { private Double soundExtraDistance = null; @Override - public BiomeMoodSound get() { + public AmbientMoodSettings get() { if(sound == null || soundCultivationTicks == null || soundSpawnRange == null || soundExtraDistance == null) { return null; } else { - return new BiomeMoodSound(Registries.SOUND_EVENT.getEntry(sound), soundCultivationTicks, soundSpawnRange, soundExtraDistance); + 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 index 83774831b..e1ace6607 100644 --- 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 @@ -5,10 +5,11 @@ 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.command.argument.ParticleEffectArgumentType; -import net.minecraft.registry.Registries; -import net.minecraft.registry.RegistryWrapper; +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; @@ -29,8 +30,8 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate> { @@ -15,6 +15,6 @@ public class EntityTypeTemplate implements ObjectTemplate> { @Override public EntityType get() { - return Registries.ENTITY_TYPE.getEntry(id).orElseThrow().value(); + return BuiltInRegistries.ENTITY_TYPE.get(id).orElseThrow().value(); } } 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 index c10f132b8..92c8f91da 100644 --- 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 @@ -3,14 +3,14 @@ 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.registry.Registries; -import net.minecraft.sound.MusicSound; -import net.minecraft.sound.SoundEvent; +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 { +public class MusicSoundTemplate implements ObjectTemplate { @Value("sound") @Default private SoundEvent sound = null; @@ -24,11 +24,11 @@ public class MusicSoundTemplate implements ObjectTemplate { private Boolean replaceCurrentMusic = null; @Override - public MusicSound get() { + public Music get() { if(sound == null || delay == null || replaceCurrentMusic == null) { return null; } else { - return new MusicSound(Registries.SOUND_EVENT.getEntry(sound), delay.getMin(), delay.getMax(), replaceCurrentMusic); + 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 b05ba8236..980257bfe 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 @@ -17,11 +17,11 @@ package com.dfsek.terra.mod.config; -import net.minecraft.registry.Registry; -import net.minecraft.registry.RegistryKey; -import net.minecraft.registry.entry.RegistryEntry; -import net.minecraft.util.Identifier; -import net.minecraft.world.biome.Biome; +import net.minecraft.core.Holder; +import net.minecraft.core.Registry; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.level.biome.Biome; import java.util.Objects; @@ -32,14 +32,14 @@ import com.dfsek.terra.mod.util.MinecraftUtil; public class ProtoPlatformBiome implements PlatformBiome { private final Identifier identifier; - private RegistryEntry delegate; + private Holder delegate; public ProtoPlatformBiome(Identifier identifier) { this.identifier = identifier; } - public RegistryKey get(Registry registry) { - return MinecraftUtil.getEntry(registry, identifier).orElseThrow().getKey().orElseThrow(); + public ResourceKey get(Registry registry) { + return MinecraftUtil.getEntry(registry, identifier).orElseThrow().unwrapKey().orElseThrow(); } @Override @@ -47,11 +47,11 @@ public class ProtoPlatformBiome implements PlatformBiome { return identifier; } - public RegistryEntry getDelegate() { + public Holder getDelegate() { return delegate; } - public void setDelegate(RegistryEntry delegate) { + public void setDelegate(Holder delegate) { this.delegate = Objects.requireNonNull(delegate); } } 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 index e794f99b0..d312c8b91 100644 --- 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 @@ -3,8 +3,8 @@ 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.sound.SoundEvent; -import net.minecraft.util.Identifier; +import net.minecraft.resources.Identifier; +import net.minecraft.sounds.SoundEvent; public class SoundEventTemplate implements ObjectTemplate { @@ -21,9 +21,9 @@ public class SoundEventTemplate implements ObjectTemplate { if(id == null) { return null; } else if(distanceToTravel == null) { - return SoundEvent.of(id); + return SoundEvent.createVariableRangeEvent(id); } else { - return SoundEvent.of(id, distanceToTravel); + 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 index 98c1ed71f..2f2339aed 100644 --- 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 @@ -3,7 +3,7 @@ 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.entity.EntityType; +import net.minecraft.world.entity.EntityType; public class SpawnCostConfig implements ObjectTemplate { 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 index 36cd0305d..2acad826e 100644 --- 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 @@ -3,8 +3,8 @@ 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.entity.EntityType; -import net.minecraft.world.biome.SpawnSettings.SpawnEntry; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.level.biome.MobSpawnSettings.SpawnerData; import com.dfsek.terra.api.util.range.Range; @@ -26,8 +26,8 @@ public class SpawnEntryConfig implements ObjectTemplate { return weight; } - public SpawnEntry getSpawnEntry() { - return new SpawnEntry(type, groupSize.getMin(), groupSize.getMax()); + public SpawnerData getSpawnEntry() { + return new SpawnerData(type, groupSize.getMin(), groupSize.getMax()); } @Override 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 index b4be04e03..3e2fefb6e 100644 --- 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 @@ -3,13 +3,13 @@ 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.entity.SpawnGroup; -import net.minecraft.world.biome.SpawnSettings; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.level.biome.MobSpawnSettings; import java.util.List; -public class SpawnSettingsTemplate implements ObjectTemplate { +public class SpawnSettingsTemplate implements ObjectTemplate { @Value("spawns") @Default private List spawns = null; @@ -23,19 +23,19 @@ public class SpawnSettingsTemplate implements ObjectTemplate { private Float probability = null; @Override - public SpawnSettings get() { - SpawnSettings.Builder builder = new SpawnSettings.Builder(); + public MobSpawnSettings get() { + MobSpawnSettings.Builder builder = new MobSpawnSettings.Builder(); for(SpawnTypeConfig spawn : spawns) { - SpawnGroup group = spawn.getGroup(); + MobCategory group = spawn.getGroup(); for(SpawnEntryConfig entry : spawn.getEntries()) { - builder.spawn(group, entry.getWeight(), entry.getSpawnEntry()); + builder.addSpawn(group, entry.getWeight(), entry.getSpawnEntry()); } } for(SpawnCostConfig cost : costs) { - builder.spawnCost(cost.getType(), cost.getMass(), cost.getGravity()); + builder.addMobCharge(cost.getType(), cost.getMass(), cost.getGravity()); } if(probability != null) { - builder.creatureSpawnProbability(probability); + builder.creatureGenerationProbability(probability); } 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 index 9d518c5c0..676fa2476 100644 --- 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 @@ -3,7 +3,7 @@ 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.entity.SpawnGroup; +import net.minecraft.world.entity.MobCategory; import java.util.List; @@ -11,13 +11,13 @@ import java.util.List; public class SpawnTypeConfig implements ObjectTemplate { @Value("group") @Default - private SpawnGroup group = null; + private MobCategory group = null; @Value("entries") @Default private List entries = null; - public SpawnGroup getGroup() { + public MobCategory getGroup() { return group; } 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 index 27076f5dd..910243a58 100644 --- 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 @@ -3,16 +3,16 @@ 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.registry.RegistryKey; -import net.minecraft.sound.BiomeAdditionsSound; -import net.minecraft.sound.BiomeMoodSound; -import net.minecraft.sound.MusicSound; -import net.minecraft.sound.SoundEvent; -import net.minecraft.village.VillagerType; +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.biome.Biome.TemperatureModifier; -import net.minecraft.world.biome.BiomeEffects.GrassColorModifier; -import net.minecraft.world.biome.SpawnSettings; +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; @@ -76,15 +76,15 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties { @Value("sound.mood-sound") @Default - private BiomeMoodSound moodSound = null; + private AmbientMoodSettings moodSound = null; @Value("sound.additions-sound") @Default - private BiomeAdditionsSound additionsSound = null; + private AmbientAdditionsSettings additionsSound = null; @Value("sound.music") @Default - private MusicSound music = null; + private Music music = null; @Value("sound.music-volume") @Default @@ -92,12 +92,12 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties { @Value("spawning") @Default - private SpawnSettings spawnSettings = null; + private MobSpawnSettings spawnSettings = null; @Value("villager-type") @Default private - RegistryKey villagerType = null; + ResourceKey villagerType = null; public Integer getGrassColor() { return grassColor; @@ -155,15 +155,15 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties { return loopSound; } - public BiomeMoodSound getMoodSound() { + public AmbientMoodSettings getMoodSound() { return moodSound; } - public BiomeAdditionsSound getAdditionsSound() { + public AmbientAdditionsSettings getAdditionsSound() { return additionsSound; } - public MusicSound getMusic() { + public Music getMusic() { return music; } @@ -171,11 +171,11 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties { return musicVolume; } - public SpawnSettings getSpawnSettings() { + public MobSpawnSettings getSpawnSettings() { return spawnSettings; } - public RegistryKey getVillagerType() { + 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 index 4534bc617..58a7c7cab 100644 --- 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 @@ -3,7 +3,7 @@ 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.util.Identifier; +import net.minecraft.resources.Identifier; import com.dfsek.terra.api.properties.Properties; import com.dfsek.terra.api.util.range.ConstantRange; 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 index da871ce26..f50d8963e 100644 --- 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 @@ -3,19 +3,19 @@ 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.registry.RegistryKey; -import net.minecraft.registry.RegistryKeys; -import net.minecraft.util.Identifier; -import net.minecraft.village.VillagerType; +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> { +public class VillagerTypeTemplate implements ObjectTemplate> { @Value("id") @Default private Identifier id = null; @Override - public RegistryKey get() { - return RegistryKey.of(RegistryKeys.VILLAGER_TYPE, id); + public ResourceKey get() { + return ResourceKey.create(Registries.VILLAGER_TYPE, id); } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/data/Codecs.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/data/Codecs.java index 8cdc42c6b..e60bdcdf3 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/data/Codecs.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/data/Codecs.java @@ -73,8 +73,8 @@ public final class Codecs { public static final MapCodec TERRA_CONSTANT_RANGE_INT_PROVIDER_TYPE = RecordCodecBuilder.mapCodec( range -> range.group( - Codec.INT.fieldOf("min").stable().forGetter(TerraIntProvider::getMin), - Codec.INT.fieldOf("max").stable().forGetter(TerraIntProvider::getMax)) + Codec.INT.fieldOf("min").stable().forGetter(TerraIntProvider::getMinValue), + Codec.INT.fieldOf("max").stable().forGetter(TerraIntProvider::getMaxValue)) .apply(range, range.stable((min, max) -> new TerraIntProvider(new ConstantRange( min, max))))); } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/MinecraftChunkGeneratorWrapper.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/MinecraftChunkGeneratorWrapper.java index 4a19a6c85..959e90816 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/MinecraftChunkGeneratorWrapper.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/MinecraftChunkGeneratorWrapper.java @@ -18,30 +18,30 @@ package com.dfsek.terra.mod.generation; import com.mojang.serialization.MapCodec; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.registry.entry.RegistryEntry; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.server.level.WorldGenRegion; import net.minecraft.util.Util; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.random.CheckedRandom; -import net.minecraft.util.math.random.ChunkRandom; -import net.minecraft.util.math.random.RandomSeed; -import net.minecraft.world.ChunkRegion; -import net.minecraft.world.HeightLimitView; -import net.minecraft.world.Heightmap.Type; -import net.minecraft.world.SpawnHelper; -import net.minecraft.world.StructureWorldAccess; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.biome.source.BiomeAccess; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.gen.StructureAccessor; -import net.minecraft.world.gen.StructureWeightSampler; -import net.minecraft.world.gen.chunk.Blender; -import net.minecraft.world.gen.chunk.VerticalBlockSample; -import net.minecraft.world.gen.densityfunction.DensityFunction.UnblendedNoisePos; -import net.minecraft.world.gen.noise.NoiseConfig; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.LevelHeightAccessor; +import net.minecraft.world.level.NaturalSpawner; +import net.minecraft.world.level.NoiseColumn; +import net.minecraft.world.level.StructureManager; +import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeManager; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.levelgen.Beardifier; +import net.minecraft.world.level.levelgen.DensityFunction.SinglePointContext; +import net.minecraft.world.level.levelgen.Heightmap.Types; +import net.minecraft.world.level.levelgen.LegacyRandomSource; +import net.minecraft.world.level.levelgen.RandomState; +import net.minecraft.world.level.levelgen.RandomSupport; +import net.minecraft.world.level.levelgen.WorldgenRandom; +import net.minecraft.world.level.levelgen.blending.Blender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,12 +59,12 @@ import com.dfsek.terra.api.world.chunk.generation.util.GeneratorWrapper; import com.dfsek.terra.api.world.info.WorldProperties; import com.dfsek.terra.mod.config.PreLoadCompatibilityOptions; import com.dfsek.terra.mod.data.Codecs; -import com.dfsek.terra.mod.mixin.access.StructureAccessorAccessor; +import com.dfsek.terra.mod.mixin.access.StructureManagerAccessor; import com.dfsek.terra.mod.util.MinecraftAdapter; import com.dfsek.terra.mod.util.SeedHack; -public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.gen.chunk.ChunkGenerator implements GeneratorWrapper { +public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.level.chunk.ChunkGenerator implements GeneratorWrapper { private static final Logger logger = LoggerFactory.getLogger(MinecraftChunkGeneratorWrapper.class); private final TerraBiomeSource biomeSource; @@ -85,31 +85,31 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.gen.chun } @Override - protected MapCodec getCodec() { + protected MapCodec codec() { return Codecs.MINECRAFT_CHUNK_GENERATOR_WRAPPER; } @Override - public void buildSurface(ChunkRegion region, StructureAccessor structures, NoiseConfig noiseConfig, Chunk chunk) { + public void buildSurface(WorldGenRegion region, StructureManager structures, RandomState noiseConfig, ChunkAccess chunk) { // no op } @Override - public void populateEntities(ChunkRegion region) { + public void spawnOriginalMobs(WorldGenRegion region) { if(this.settings.mobGeneration()) { - ChunkPos chunkPos = region.getCenterPos(); - RegistryEntry registryEntry = region.getBiome(chunkPos.getStartPos().withY(region.getTopYInclusive() - 1)); - ChunkRandom chunkRandom = new ChunkRandom(new CheckedRandom(RandomSeed.getSeed())); - chunkRandom.setPopulationSeed(region.getSeed(), chunkPos.getStartX(), chunkPos.getStartZ()); - SpawnHelper.populateEntities(region, registryEntry, chunkPos, chunkRandom); + ChunkPos chunkPos = region.getCenter(); + Holder registryEntry = region.getBiome(chunkPos.getWorldPosition().atY(region.getMaxY() - 1)); + WorldgenRandom chunkRandom = new WorldgenRandom(new LegacyRandomSource(RandomSupport.generateUniqueSeed())); + chunkRandom.setDecorationSeed(region.getSeed(), chunkPos.getMinBlockX(), chunkPos.getMinBlockZ()); + NaturalSpawner.spawnMobsForChunkGeneration(region, registryEntry, chunkPos, chunkRandom); } } @Override - public CompletableFuture populateNoise(Blender blender, NoiseConfig noiseConfig, StructureAccessor structureAccessor, - Chunk chunk) { + public CompletableFuture fillFromNoise(Blender blender, RandomState noiseConfig, StructureManager structureAccessor, + ChunkAccess chunk) { return CompletableFuture.supplyAsync(() -> { - ProtoWorld world = (ProtoWorld) ((StructureAccessorAccessor) structureAccessor).getWorld(); + ProtoWorld world = (ProtoWorld) ((StructureManagerAccessor) structureAccessor).getLevel(); BiomeProvider biomeProvider = pack.getBiomeProvider(); delegate.generateChunkData((ProtoChunk) chunk, world, biomeProvider, chunk.getPos().x, chunk.getPos().z); @@ -118,12 +118,12 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.gen.chun beard(structureAccessor, chunk, world, biomeProvider, compatibilityOptions); } return chunk; - }, Util.getMainWorkerExecutor()); + }, Util.backgroundExecutor()); } - private void beard(StructureAccessor structureAccessor, Chunk chunk, WorldProperties world, BiomeProvider biomeProvider, + private void beard(StructureManager structureAccessor, ChunkAccess chunk, WorldProperties world, BiomeProvider biomeProvider, PreLoadCompatibilityOptions compatibilityOptions) { - StructureWeightSampler structureWeightSampler = StructureWeightSampler.createStructureWeightSampler(structureAccessor, + Beardifier structureWeightSampler = Beardifier.forStructuresInChunk(structureAccessor, chunk.getPos()); double threshold = compatibilityOptions.getBeardThreshold(); double airThreshold = compatibilityOptions.getAirThreshold(); @@ -133,23 +133,23 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.gen.chun for(int z = 0; z < 16; z++) { int depth = 0; for(int y = world.getMaxHeight(); y >= world.getMinHeight(); y--) { - double noise = structureWeightSampler.sample(new UnblendedNoisePos(x + xi, y, z + zi)); + double noise = structureWeightSampler.compute(new SinglePointContext(x + xi, y, z + zi)); if(noise > threshold) { com.dfsek.terra.api.block.state.BlockState data = delegate.getPalette(x + xi, y, z + zi, world, biomeProvider).get( depth, x + xi, y, z + zi, world.getSeed()); BlockPos blockPos = new BlockPos(x, y, z); - boolean isExtended = data.isExtended() && data.getClass().equals(BlockStateArgument.class); + boolean isExtended = data.isExtended() && data.getClass().equals(BlockInput.class); if(isExtended) { BlockStateExtended blockStateExtended = (BlockStateExtended) data; - net.minecraft.block.BlockState blockState = (net.minecraft.block.BlockState) blockStateExtended.getState(); + net.minecraft.world.level.block.state.BlockState blockState = (net.minecraft.world.level.block.state.BlockState) blockStateExtended.getState(); chunk.setBlockState(blockPos, blockState, 0); } else { - chunk.setBlockState(blockPos, (net.minecraft.block.BlockState) data, 0); + chunk.setBlockState(blockPos, (net.minecraft.world.level.block.state.BlockState) data, 0); } depth++; } else if(noise < airThreshold) { - chunk.setBlockState(new BlockPos(x, y, z), Blocks.AIR.getDefaultState(), 0); + chunk.setBlockState(new BlockPos(x, y, z), Blocks.AIR.defaultBlockState(), 0); } else { depth = 0; } @@ -159,8 +159,8 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.gen.chun } @Override - public void generateFeatures(StructureWorldAccess world, Chunk chunk, StructureAccessor structureAccessor) { - super.generateFeatures(world, chunk, structureAccessor); + public void applyBiomeDecoration(WorldGenLevel world, ChunkAccess chunk, StructureManager structureAccessor) { + super.applyBiomeDecoration(world, chunk, structureAccessor); pack.getStages().forEach(populator -> { if(!(populator instanceof Chunkified)) { populator.populate((ProtoWorld) world); @@ -169,7 +169,7 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.gen.chun } @Override - public int getWorldHeight() { + public int getGenDepth() { return settings.height().getRange(); } @@ -179,47 +179,47 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.gen.chun } @Override - public int getMinimumY() { + public int getMinY() { return settings.height().getMin(); } @Override - public int getSpawnHeight(HeightLimitView world) { + public int getSpawnHeight(LevelHeightAccessor world) { return settings.spawnHeight(); } @Override - public int getHeight(int x, int z, Type heightmap, HeightLimitView height, NoiseConfig noiseConfig) { - WorldProperties properties = MinecraftAdapter.adapt(height, SeedHack.getSeed(noiseConfig.getMultiNoiseSampler())); + public int getBaseHeight(int x, int z, Types heightmap, LevelHeightAccessor height, RandomState noiseConfig) { + WorldProperties properties = MinecraftAdapter.adapt(height, SeedHack.getSeed(noiseConfig.sampler())); BiomeProvider biomeProvider = pack.getBiomeProvider(); - int min = height.getBottomY(); - for(int y = height.getTopYInclusive() - 1; y >= min; y--) { + int min = height.getMinY(); + for(int y = height.getMaxY() - 1; y >= min; y--) { com.dfsek.terra.api.block.state.BlockState terraBlockState = delegate.getBlock(properties, x, y, z, biomeProvider); BlockState blockState = (BlockState) (terraBlockState.isExtended() ? ((BlockStateExtended) terraBlockState).getState() : terraBlockState); if(heightmap - .getBlockPredicate() + .isOpaque() .test(blockState)) return y + 1; } return min; } @Override - public VerticalBlockSample getColumnSample(int x, int z, HeightLimitView height, NoiseConfig noiseConfig) { + public NoiseColumn getBaseColumn(int x, int z, LevelHeightAccessor height, RandomState noiseConfig) { BlockState[] array = new BlockState[height.getHeight()]; - WorldProperties properties = MinecraftAdapter.adapt(height, SeedHack.getSeed(noiseConfig.getMultiNoiseSampler())); + WorldProperties properties = MinecraftAdapter.adapt(height, SeedHack.getSeed(noiseConfig.sampler())); BiomeProvider biomeProvider = pack.getBiomeProvider(); - for(int y = height.getTopYInclusive() - 1; y >= height.getBottomY(); y--) { + for(int y = height.getMaxY() - 1; y >= height.getMinY(); y--) { com.dfsek.terra.api.block.state.BlockState terraBlockState = delegate.getBlock(properties, x, y, z, biomeProvider); BlockState blockState = (BlockState) (terraBlockState.isExtended() ? ((BlockStateExtended) terraBlockState).getState() : terraBlockState); - array[y - height.getBottomY()] = blockState; + array[y - height.getMinY()] = blockState; } - return new VerticalBlockSample(height.getBottomY(), array); + return new NoiseColumn(height.getMinY(), array); } @Override - public void appendDebugHudText(List text, NoiseConfig noiseConfig, BlockPos pos) { + public void addDebugScreenInfo(List text, RandomState noiseConfig, BlockPos pos) { // no op } @@ -237,8 +237,8 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.gen.chun @Override - public void carve(ChunkRegion chunkRegion, long seed, NoiseConfig noiseConfig, BiomeAccess biomeAccess, - StructureAccessor structureAccessor, Chunk chunk) { + public void applyCarvers(WorldGenRegion chunkRegion, long seed, RandomState noiseConfig, BiomeManager biomeAccess, + StructureManager structureAccessor, ChunkAccess chunk) { //no op } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/TerraBiomeSource.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/TerraBiomeSource.java index 1d5910082..49597b610 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/TerraBiomeSource.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/TerraBiomeSource.java @@ -18,10 +18,10 @@ package com.dfsek.terra.mod.generation; import com.mojang.serialization.MapCodec; -import net.minecraft.registry.entry.RegistryEntry; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.biome.source.BiomeSource; -import net.minecraft.world.biome.source.util.MultiNoiseUtil.MultiNoiseSampler; +import net.minecraft.core.Holder; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeSource; +import net.minecraft.world.level.biome.Climate.Sampler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,16 +43,16 @@ public class TerraBiomeSource extends BiomeSource { public TerraBiomeSource(ConfigPack pack) { this.pack = pack; - LOGGER.debug("Biomes: " + getBiomes()); + LOGGER.debug("Biomes: " + possibleBiomes()); } @Override - protected MapCodec getCodec() { + protected MapCodec codec() { return Codecs.TERRA_BIOME_SOURCE; } @Override - protected Stream> biomeStream() { + protected Stream> collectPossibleBiomes() { return StreamSupport .stream(pack.getBiomeProvider() .getBiomes() @@ -61,7 +61,7 @@ public class TerraBiomeSource extends BiomeSource { } @Override - public RegistryEntry getBiome(int biomeX, int biomeY, int biomeZ, MultiNoiseSampler Sampler) { + public Holder getNoiseBiome(int biomeX, int biomeY, int biomeZ, Sampler Sampler) { return ((ProtoPlatformBiome) pack .getBiomeProvider() .getBiome(biomeX << 2, biomeY << 2, biomeZ << 2, SeedHack.getSeed(Sampler)) diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/handle/MinecraftItemHandle.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/handle/MinecraftItemHandle.java index 5c34eb82c..25c5a776d 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/handle/MinecraftItemHandle.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/handle/MinecraftItemHandle.java @@ -19,13 +19,13 @@ package com.dfsek.terra.mod.handle; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.command.CommandRegistryAccess; -import net.minecraft.command.argument.ItemStackArgumentType; -import net.minecraft.registry.Registry; -import net.minecraft.registry.RegistryKey; -import net.minecraft.registry.RegistryWrapper.Impl; -import net.minecraft.resource.featuretoggle.FeatureSet; -import net.minecraft.util.Identifier; +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.commands.arguments.item.ItemArgument; +import net.minecraft.core.HolderLookup.RegistryLookup; +import net.minecraft.core.Registry; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.flag.FeatureFlagSet; import java.util.Optional; import java.util.Set; @@ -43,20 +43,20 @@ public class MinecraftItemHandle implements ItemHandle { @Override public Item createItem(String data) { try { - return (Item) new ItemStackArgumentType(new CommandRegistryAccess() { + return (Item) new ItemArgument(new CommandBuildContext() { @Override - public FeatureSet getEnabledFeatures() { - return FeatureSet.empty(); + public FeatureFlagSet enabledFeatures() { + return FeatureFlagSet.of(); } @Override - public Stream>> streamAllRegistryKeys() { - return CommonPlatform.get().getServer().getRegistryManager().streamAllRegistryKeys(); + public Stream>> listRegistryKeys() { + return CommonPlatform.get().getServer().registryAccess().listRegistryKeys(); } @Override - public Optional> getOptional(RegistryKey> registryRef) { - return Optional.of(CommonPlatform.get().getServer().getRegistryManager().getOrThrow(registryRef)); + public Optional> lookup(ResourceKey> registryRef) { + return Optional.of(CommonPlatform.get().getServer().registryAccess().lookupOrThrow(registryRef)); } }).parse(new StringReader(data)).getItem(); } catch(CommandSyntaxException e) { @@ -66,7 +66,7 @@ public class MinecraftItemHandle implements ItemHandle { @Override public Enchantment getEnchantment(String id) { - return (Enchantment) (Object) (CommonPlatform.get().enchantmentRegistry().getEntry(Identifier.tryParse(id))); + return (Enchantment) (Object) (CommonPlatform.get().enchantmentRegistry().get(Identifier.tryParse(id))); } @Override diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/handle/MinecraftWorldHandle.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/handle/MinecraftWorldHandle.java index b42b866e7..bfd508e51 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/handle/MinecraftWorldHandle.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/handle/MinecraftWorldHandle.java @@ -19,20 +19,20 @@ package com.dfsek.terra.mod.handle; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.block.BlockEntityProvider; -import net.minecraft.block.Blocks; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.command.argument.BlockArgumentParser; -import net.minecraft.command.argument.BlockArgumentParser.BlockResult; -import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.StringNbtReader; -import net.minecraft.registry.Registries; -import net.minecraft.registry.RegistryKey; -import net.minecraft.registry.RegistryKeys; -import net.minecraft.registry.entry.RegistryEntry.Reference; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.commands.arguments.blocks.BlockStateParser; +import net.minecraft.commands.arguments.blocks.BlockStateParser.BlockResult; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder.Reference; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.TagParser; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.entity.BlockEntity; import org.jetbrains.annotations.NotNull; import com.dfsek.terra.api.block.state.BlockState; @@ -41,33 +41,33 @@ import com.dfsek.terra.api.entity.EntityType; import com.dfsek.terra.api.handle.WorldHandle; import com.dfsek.terra.mod.implmentation.MinecraftEntityTypeExtended; -import static net.minecraft.command.argument.BlockArgumentParser.INVALID_BLOCK_ID_EXCEPTION; +import static net.minecraft.commands.arguments.blocks.BlockStateParser.ERROR_UNKNOWN_BLOCK; public class MinecraftWorldHandle implements WorldHandle { - private static final BlockState AIR = (BlockState) Blocks.AIR.getDefaultState(); + private static final BlockState AIR = (BlockState) Blocks.AIR.defaultBlockState(); @SuppressWarnings("DataFlowIssue") @Override public @NotNull BlockState createBlockState(@NotNull String data) { try { - BlockResult blockResult = BlockArgumentParser.block(Registries.BLOCK, data, true); + BlockResult blockResult = BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK, data, true); BlockState blockState; if(blockResult.nbt() != null) { - net.minecraft.block.BlockState state = blockResult.blockState(); - NbtCompound nbtCompound = blockResult.nbt(); + net.minecraft.world.level.block.state.BlockState state = blockResult.blockState(); + CompoundTag nbtCompound = blockResult.nbt(); if(state.hasBlockEntity()) { - BlockEntity blockEntity = ((BlockEntityProvider) state.getBlock()).createBlockEntity(new BlockPos(0, 0, 0), state); + BlockEntity blockEntity = ((EntityBlock) state.getBlock()).newBlockEntity(new BlockPos(0, 0, 0), state); nbtCompound.putInt("x", 0); nbtCompound.putInt("y", 0); nbtCompound.putInt("z", 0); - nbtCompound.put("id", BlockEntity.TYPE_CODEC, blockEntity.getType()); + nbtCompound.store("id", BlockEntity.TYPE_CODEC, blockEntity.getType()); - blockState = (BlockStateExtended) new BlockStateArgument(state, blockResult.properties().keySet(), nbtCompound); + blockState = (BlockStateExtended) new BlockInput(state, blockResult.properties().keySet(), nbtCompound); } else { blockState = (BlockState) state; } @@ -92,23 +92,23 @@ public class MinecraftWorldHandle implements WorldHandle { public @NotNull EntityType getEntity(@NotNull String data) { try { Identifier identifier; - NbtCompound nbtData = null; + CompoundTag nbtData = null; StringReader reader = new StringReader(data); int i = reader.getCursor(); - identifier = Identifier.fromCommandInput(reader); + identifier = Identifier.read(reader); - net.minecraft.entity.EntityType entity = - (net.minecraft.entity.EntityType) ((Reference) Registries.ENTITY_TYPE.getOptional( - RegistryKey.of(RegistryKeys.ENTITY_TYPE, identifier)).orElseThrow(() -> { + net.minecraft.world.entity.EntityType entity = + (net.minecraft.world.entity.EntityType) ((Reference) BuiltInRegistries.ENTITY_TYPE.get( + ResourceKey.create(Registries.ENTITY_TYPE, identifier)).orElseThrow(() -> { reader.setCursor(i); - return INVALID_BLOCK_ID_EXCEPTION.createWithContext(reader, identifier.toString()); + return ERROR_UNKNOWN_BLOCK.createWithContext(reader, identifier.toString()); })).value(); if(reader.canRead() && reader.peek() == '{') { - nbtData = StringNbtReader.readCompoundAsArgument(reader); - nbtData.putString("id", entity.getRegistryEntry().registryKey().getValue().toString()); + nbtData = TagParser.parseCompoundAsArgument(reader); + nbtData.putString("id", entity.builtInRegistryHolder().key().identifier().toString()); } EntityType entityType; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/implmentation/MinecraftEntityTypeExtended.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/implmentation/MinecraftEntityTypeExtended.java index 7d06b15b5..9663c49e7 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/implmentation/MinecraftEntityTypeExtended.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/implmentation/MinecraftEntityTypeExtended.java @@ -1,13 +1,13 @@ package com.dfsek.terra.mod.implmentation; -import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.CompoundTag; import com.dfsek.terra.api.data.ExtendedData; import com.dfsek.terra.api.entity.EntityType; import com.dfsek.terra.api.entity.EntityTypeExtended; -public record MinecraftEntityTypeExtended(net.minecraft.entity.EntityType entityType, NbtCompound nbtCompound) +public record MinecraftEntityTypeExtended(net.minecraft.world.entity.EntityType entityType, CompoundTag nbtCompound) implements EntityTypeExtended { @SuppressWarnings("DataFlowIssue") @Override @@ -19,7 +19,7 @@ public record MinecraftEntityTypeExtended(net.minecraft.entity.EntityType ent @Override public EntityTypeExtended setData(ExtendedData data) { return new MinecraftEntityTypeExtended(entityType, - data.getClass().equals(NbtCompound.class) ? ((NbtCompound) ((Object) data)) : null); + data.getClass().equals(CompoundTag.class) ? ((CompoundTag) ((Object) data)) : null); } @Override diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/implmentation/TerraIntProvider.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/implmentation/TerraIntProvider.java index afce31b90..1332c38ab 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/implmentation/TerraIntProvider.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/implmentation/TerraIntProvider.java @@ -1,8 +1,8 @@ package com.dfsek.terra.mod.implmentation; -import net.minecraft.util.math.intprovider.IntProvider; -import net.minecraft.util.math.intprovider.IntProviderType; -import net.minecraft.util.math.random.Random; +import net.minecraft.util.RandomSource; +import net.minecraft.util.valueproviders.IntProvider; +import net.minecraft.util.valueproviders.IntProviderType; import java.util.HashMap; import java.util.Map; @@ -21,17 +21,17 @@ public class TerraIntProvider extends IntProvider { } @Override - public int get(Random random) { + public int sample(RandomSource random) { return delegate.get(MinecraftAdapter.adapt(random)); } @Override - public int getMin() { + public int getMinValue() { return delegate.getMin(); } @Override - public int getMax() { + public int getMaxValue() { return delegate.getMax(); } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/MobSpawnerLogicAccessor.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/BaseSpawnerAccessor.java similarity index 76% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/MobSpawnerLogicAccessor.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/BaseSpawnerAccessor.java index 002b5c25b..7fd456e46 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/MobSpawnerLogicAccessor.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/BaseSpawnerAccessor.java @@ -17,14 +17,14 @@ package com.dfsek.terra.mod.mixin.access; -import net.minecraft.block.spawner.MobSpawnerEntry; -import net.minecraft.block.spawner.MobSpawnerLogic; +import net.minecraft.world.level.BaseSpawner; +import net.minecraft.world.level.SpawnData; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; -@Mixin(MobSpawnerLogic.class) -public interface MobSpawnerLogicAccessor { - @Accessor("spawnEntry") - MobSpawnerEntry getSpawnEntry(); +@Mixin(BaseSpawner.class) +public interface BaseSpawnerAccessor { + @Accessor("nextSpawnData") + SpawnData getSpawnEntry(); } 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 index c51029682..3af401b10 100644 --- 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 @@ -1,12 +1,12 @@ package com.dfsek.terra.mod.mixin.access; -import net.minecraft.world.biome.Biome; +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("weather") - Biome.Weather getWeather(); + @Accessor("climateSettings") + Biome.ClimateSettings getWeather(); } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/LevelChunkAccessor.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/LevelChunkAccessor.java new file mode 100644 index 000000000..f96541dc2 --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/LevelChunkAccessor.java @@ -0,0 +1,15 @@ +package com.dfsek.terra.mod.mixin.access; + +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.chunk.LevelChunk; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + + +@Mixin(LevelChunk.class) +public interface LevelChunkAccessor { + @Invoker("promotePendingBlockEntity") + public BlockEntity invokeLoadBlockEntity(BlockPos pos, CompoundTag nbt); +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StateAccessor.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StateHolderAccessor.java similarity index 80% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StateAccessor.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StateHolderAccessor.java index 0cee6cbaf..324066d5b 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StateAccessor.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StateHolderAccessor.java @@ -17,8 +17,8 @@ package com.dfsek.terra.mod.mixin.access; -import net.minecraft.state.State; -import net.minecraft.state.property.Property; +import net.minecraft.world.level.block.state.StateHolder; +import net.minecraft.world.level.block.state.properties.Property; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; @@ -26,9 +26,9 @@ import java.util.Map; import java.util.function.Function; -@Mixin(State.class) -public interface StateAccessor { - @Accessor("PROPERTY_MAP_PRINTER") +@Mixin(StateHolder.class) +public interface StateHolderAccessor { + @Accessor("PROPERTY_ENTRY_TO_STRING_FUNCTION") static Function, Comparable>, String> getPropertyMapPrinter() { throw new UnsupportedOperationException(); } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StructureAccessorAccessor.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StructureManagerAccessor.java similarity index 80% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StructureAccessorAccessor.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StructureManagerAccessor.java index b64b47faa..a8b65e1d9 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StructureAccessorAccessor.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StructureManagerAccessor.java @@ -17,14 +17,14 @@ package com.dfsek.terra.mod.mixin.access; -import net.minecraft.world.WorldAccess; -import net.minecraft.world.gen.StructureAccessor; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.StructureManager; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; -@Mixin(StructureAccessor.class) -public interface StructureAccessorAccessor { +@Mixin(StructureManager.class) +public interface StructureManagerAccessor { @Accessor - WorldAccess getWorld(); + LevelAccessor getLevel(); } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/VillagerTypeAccessor.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/VillagerTypeAccessor.java index 652512957..ea68f27cf 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/VillagerTypeAccessor.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/VillagerTypeAccessor.java @@ -1,8 +1,8 @@ package com.dfsek.terra.mod.mixin.access; -import net.minecraft.registry.RegistryKey; -import net.minecraft.village.VillagerType; -import net.minecraft.world.biome.Biome; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.entity.npc.villager.VillagerType; +import net.minecraft.world.level.biome.Biome; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; @@ -11,8 +11,8 @@ import java.util.Map; @Mixin(VillagerType.class) public interface VillagerTypeAccessor { - @Accessor("BIOME_TO_TYPE") - static Map, RegistryKey> getBiomeTypeToIdMap() { + @Accessor("BY_BIOME") + static Map, ResourceKey> getBiomeTypeToIdMap() { throw new AssertionError("Untransformed Accessor!"); } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/WorldChunkAccessor.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/WorldChunkAccessor.java deleted file mode 100644 index 72defb826..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/WorldChunkAccessor.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.dfsek.terra.mod.mixin.access; - -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.chunk.WorldChunk; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; - - -@Mixin(WorldChunk.class) -public interface WorldChunkAccessor { - @Invoker("loadBlockEntity") - public BlockEntity invokeLoadBlockEntity(BlockPos pos, NbtCompound nbt); -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/generalize/ServerLevelMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/generalize/ServerLevelMixin.java new file mode 100644 index 000000000..981f917d8 --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/generalize/ServerLevelMixin.java @@ -0,0 +1,44 @@ +package com.dfsek.terra.mod.mixin.generalize; + + +import net.minecraft.core.Holder; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.progress.LevelLoadListener; +import net.minecraft.world.RandomSequences; +import net.minecraft.world.level.CustomSpawner; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; +import net.minecraft.world.level.dimension.LevelStem; +import net.minecraft.world.level.storage.LevelStorageSource; +import net.minecraft.world.level.storage.ServerLevelData; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +import java.util.List; +import java.util.concurrent.Executor; + + +@Mixin(ServerLevel.class) +public abstract class ServerLevelMixin extends Level { + public ServerLevelMixin(MinecraftServer server, Executor workerExecutor, LevelStorageSource.LevelStorageAccess session, ServerLevelData properties, + ResourceKey worldKey, LevelStem dimensionOptions, + LevelLoadListener chunkLoadProgress, boolean debugWorld, long seed, + List spawners, boolean shouldTickTime, @Nullable RandomSequences randomSequencesState) { + super(properties, worldKey, server.registryAccess(), dimensionOptions.type(), false, debugWorld, seed, + server.getMaxChainedNeighborUpdates()); + } + + @Redirect(method = "", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/core/Holder;is(Lnet/minecraft/resources/ResourceKey;)Z")) + public boolean matchesKeyProxy(Holder instance, ResourceKey tRegistryKey) { + if(tRegistryKey == BuiltinDimensionTypes.END) { + return (this.dimension() == Level.END); + } + return instance.is(tRegistryKey); + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/generalize/ServerWorldMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/generalize/ServerWorldMixin.java deleted file mode 100644 index 470b0fa29..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/generalize/ServerWorldMixin.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.dfsek.terra.mod.mixin.generalize; - - -import net.minecraft.registry.RegistryKey; -import net.minecraft.registry.entry.RegistryEntry; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.random.RandomSequencesState; -import net.minecraft.world.World; -import net.minecraft.world.chunk.ChunkLoadProgress; -import net.minecraft.world.dimension.DimensionOptions; -import net.minecraft.world.dimension.DimensionTypes; -import net.minecraft.world.level.ServerWorldProperties; -import net.minecraft.world.level.storage.LevelStorage; -import net.minecraft.world.spawner.SpecialSpawner; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -import java.util.List; -import java.util.concurrent.Executor; - - -@Mixin(ServerWorld.class) -public abstract class ServerWorldMixin extends World { - public ServerWorldMixin(MinecraftServer server, Executor workerExecutor, LevelStorage.Session session, ServerWorldProperties properties, - RegistryKey worldKey, DimensionOptions dimensionOptions, - ChunkLoadProgress chunkLoadProgress, boolean debugWorld, long seed, - List spawners, boolean shouldTickTime, @Nullable RandomSequencesState randomSequencesState) { - super(properties, worldKey, server.getRegistryManager(), dimensionOptions.dimensionTypeEntry(), false, debugWorld, seed, - server.getMaxChainedNeighborUpdates()); - } - - @Redirect(method = "", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/registry/entry/RegistryEntry;matchesKey(Lnet/minecraft/registry/RegistryKey;)Z")) - public boolean matchesKeyProxy(RegistryEntry instance, RegistryKey tRegistryKey) { - if(tRegistryKey == DimensionTypes.THE_END) { - return (this.getRegistryKey() == World.END); - } - return instance.matchesKey(tRegistryKey); - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/compat/GenerationSettingsFloraFeaturesMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/compat/BiomeGenerationSettingsFloraFeaturesMixin.java similarity index 82% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/compat/GenerationSettingsFloraFeaturesMixin.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/compat/BiomeGenerationSettingsFloraFeaturesMixin.java index aafd577d0..689c4c179 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/compat/GenerationSettingsFloraFeaturesMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/compat/BiomeGenerationSettingsFloraFeaturesMixin.java @@ -1,7 +1,7 @@ package com.dfsek.terra.mod.mixin.implementations.compat; -import net.minecraft.world.biome.GenerationSettings; -import net.minecraft.world.gen.feature.ConfiguredFeature; +import net.minecraft.world.level.biome.BiomeGenerationSettings; +import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Intrinsic; @@ -16,9 +16,9 @@ import java.util.List; import com.dfsek.terra.mod.mixin_ifaces.FloraFeatureHolder; -@Mixin(GenerationSettings.class) +@Mixin(BiomeGenerationSettings.class) @Implements(@Interface(iface = FloraFeatureHolder.class, prefix = "terra$")) -public class GenerationSettingsFloraFeaturesMixin { +public class BiomeGenerationSettingsFloraFeaturesMixin { private List> flora; public void terra$setFloraFeatures(List> features) { diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/BiomeMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/BiomeMixin.java index 893921e8e..99e316944 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/BiomeMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/BiomeMixin.java @@ -17,7 +17,7 @@ package com.dfsek.terra.mod.mixin.implementations.terra; -import net.minecraft.world.biome.Biome; +import net.minecraft.world.level.biome.Biome; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Mixin; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/HandleImplementationMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/HandleImplementationMixin.java index e1a79782e..85d739164 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/HandleImplementationMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/HandleImplementationMixin.java @@ -1,21 +1,21 @@ package com.dfsek.terra.mod.mixin.implementations.terra; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.LockableContainerBlockEntity; -import net.minecraft.block.entity.LootableContainerBlockEntity; -import net.minecraft.enchantment.Enchantment; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.world.ChunkRegion; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.chunk.ProtoChunk; -import net.minecraft.world.chunk.WorldChunk; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.WorldGenRegion; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BaseContainerBlockEntity; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.RandomizableContainerBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.ProtoChunk; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Intrinsic; @@ -28,23 +28,23 @@ import com.dfsek.terra.api.Handle; * A ton of Minecraft classes must implement Handle identically, we can just take care of it here */ @Mixin({ - ServerWorld.class, - ChunkRegion.class, + ServerLevel.class, + WorldGenRegion.class, Block.class, BlockState.class, BlockEntity.class, - LootableContainerBlockEntity.class, - LockableContainerBlockEntity.class, + RandomizableContainerBlockEntity.class, + BaseContainerBlockEntity.class, ProtoChunk.class, - WorldChunk.class, + LevelChunk.class, Entity.class, EntityType.class, - ServerCommandSource.class, + CommandSourceStack.class, Item.class, ItemStack.class, diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/BlockMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/BlockMixin.java index 1665b2b8c..b00cc2876 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/BlockMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/BlockMixin.java @@ -17,8 +17,8 @@ package com.dfsek.terra.mod.mixin.implementations.terra.block; -import net.minecraft.block.Block; -import net.minecraft.block.Blocks; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Mixin; @@ -30,11 +30,11 @@ import com.dfsek.terra.api.block.BlockType; @Implements(@Interface(iface = BlockType.class, prefix = "terra$")) public abstract class BlockMixin { public com.dfsek.terra.api.block.state.BlockState terra$getDefaultState() { - return (com.dfsek.terra.api.block.state.BlockState) ((Block) (Object) this).getDefaultState(); + return (com.dfsek.terra.api.block.state.BlockState) ((Block) (Object) this).defaultBlockState(); } public boolean terra$isSolid() { - return ((Block) (Object) this).getDefaultState().isOpaque(); + return ((Block) (Object) this).defaultBlockState().canOcclude(); } @SuppressWarnings("ConstantConditions") diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/BlockEntityMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/BlockEntityMixin.java index fb00e9475..8917ed4d3 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/BlockEntityMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/BlockEntityMixin.java @@ -25,30 +25,30 @@ import com.dfsek.terra.api.block.entity.BlockEntity; import com.dfsek.terra.api.block.state.BlockState; -@Mixin(net.minecraft.block.entity.BlockEntity.class) +@Mixin(net.minecraft.world.level.block.entity.BlockEntity.class) @Implements(@Interface(iface = BlockEntity.class, prefix = "terra$")) public abstract class BlockEntityMixin { public boolean terra$update(boolean applyPhysics) { - if(((net.minecraft.block.entity.BlockEntity) (Object) this).hasWorld()) //noinspection ConstantConditions - ((net.minecraft.block.entity.BlockEntity) (Object) this).getWorld().getChunk( - ((net.minecraft.block.entity.BlockEntity) (Object) this).getPos()).setBlockEntity( - (net.minecraft.block.entity.BlockEntity) (Object) this); + if(((net.minecraft.world.level.block.entity.BlockEntity) (Object) this).hasLevel()) //noinspection ConstantConditions + ((net.minecraft.world.level.block.entity.BlockEntity) (Object) this).getLevel().getChunk( + ((net.minecraft.world.level.block.entity.BlockEntity) (Object) this).getBlockPos()).setBlockEntity( + (net.minecraft.world.level.block.entity.BlockEntity) (Object) this); return true; } public int terra$getX() { - return ((net.minecraft.block.entity.BlockEntity) (Object) this).getPos().getX(); + return ((net.minecraft.world.level.block.entity.BlockEntity) (Object) this).getBlockPos().getX(); } public int terra$getY() { - return ((net.minecraft.block.entity.BlockEntity) (Object) this).getPos().getY(); + return ((net.minecraft.world.level.block.entity.BlockEntity) (Object) this).getBlockPos().getY(); } public int terra$getZ() { - return ((net.minecraft.block.entity.BlockEntity) (Object) this).getPos().getZ(); + return ((net.minecraft.world.level.block.entity.BlockEntity) (Object) this).getBlockPos().getZ(); } public BlockState terra$getBlockState() { - return (BlockState) ((net.minecraft.block.entity.BlockEntity) (Object) this).getCachedState(); + return (BlockState) ((net.minecraft.world.level.block.entity.BlockEntity) (Object) this).getBlockState(); } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/LootableContainerBlockEntityMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/RandomizableContainerBlockEntityMixin.java similarity index 84% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/LootableContainerBlockEntityMixin.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/RandomizableContainerBlockEntityMixin.java index ad237b3b8..447f28371 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/LootableContainerBlockEntityMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/RandomizableContainerBlockEntityMixin.java @@ -17,7 +17,7 @@ package com.dfsek.terra.mod.mixin.implementations.terra.block.entity; -import net.minecraft.block.entity.LootableContainerBlockEntity; +import net.minecraft.world.level.block.entity.RandomizableContainerBlockEntity; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Mixin; @@ -26,9 +26,9 @@ import com.dfsek.terra.api.block.entity.Container; import com.dfsek.terra.api.inventory.Inventory; -@Mixin(LootableContainerBlockEntity.class) +@Mixin(RandomizableContainerBlockEntity.class) @Implements(@Interface(iface = Container.class, prefix = "terra$")) -public abstract class LootableContainerBlockEntityMixin extends BlockEntityMixin { +public abstract class RandomizableContainerBlockEntityMixin extends BlockEntityMixin { public Inventory terra$getInventory() { return (Inventory) this; } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/SignBlockEntityMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/SignBlockEntityMixin.java index 56536f9c0..45f4f22d7 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/SignBlockEntityMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/SignBlockEntityMixin.java @@ -17,9 +17,9 @@ package com.dfsek.terra.mod.mixin.implementations.terra.block.entity; -import net.minecraft.block.entity.SignBlockEntity; -import net.minecraft.block.entity.SignText; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; +import net.minecraft.world.level.block.entity.SignBlockEntity; +import net.minecraft.world.level.block.entity.SignText; import org.jetbrains.annotations.NotNull; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; @@ -40,11 +40,11 @@ public abstract class SignBlockEntityMixin { public abstract boolean setText(SignText text, boolean front); public void terra$setLine(int index, @NotNull String line) throws IndexOutOfBoundsException { - setText(frontText.withMessage(index, Text.literal(line)), true); + setText(frontText.setMessage(index, Component.literal(line)), true); } public @NotNull String[] terra$getLines() { - Text[] texts = frontText.getMessages(false); + Component[] texts = frontText.getMessages(false); String[] lines = new String[texts.length]; for(int i = 0; i < texts.length; i++) { lines[i] = texts[i].getString(); diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/MobSpawnerBlockEntityMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/SpawnerBlockEntityMixin.java similarity index 71% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/MobSpawnerBlockEntityMixin.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/SpawnerBlockEntityMixin.java index 4335f67ce..6a0e09849 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/MobSpawnerBlockEntityMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/SpawnerBlockEntityMixin.java @@ -17,15 +17,15 @@ package com.dfsek.terra.mod.mixin.implementations.terra.block.entity; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.block.entity.MobSpawnerBlockEntity; -import net.minecraft.block.spawner.MobSpawnerLogic; -import net.minecraft.registry.Registries; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.random.Random; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.BaseSpawner; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.entity.SpawnerBlockEntity; +import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.NotNull; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; @@ -37,40 +37,40 @@ import com.dfsek.terra.api.block.entity.SerialState; import com.dfsek.terra.api.entity.EntityType; import com.dfsek.terra.mod.CommonPlatform; import com.dfsek.terra.mod.implmentation.MinecraftEntityTypeExtended; -import com.dfsek.terra.mod.mixin.access.MobSpawnerLogicAccessor; +import com.dfsek.terra.mod.mixin.access.BaseSpawnerAccessor; -@Mixin(MobSpawnerBlockEntity.class) +@Mixin(SpawnerBlockEntity.class) @Implements(@Interface(iface = MobSpawner.class, prefix = "terra$")) -public abstract class MobSpawnerBlockEntityMixin extends BlockEntity { - private MobSpawnerBlockEntityMixin(BlockEntityType type, BlockPos pos, BlockState state) { +public abstract class SpawnerBlockEntityMixin extends BlockEntity { + private SpawnerBlockEntityMixin(BlockEntityType type, BlockPos pos, BlockState state) { super(type, pos, state); } @Shadow - public abstract MobSpawnerLogic getLogic(); + public abstract BaseSpawner getSpawner(); //method_46408 @Shadow - public abstract void setEntityType(net.minecraft.entity.EntityType entityType, Random random); + public abstract void setEntityId(net.minecraft.world.entity.EntityType entityType, RandomSource random); public EntityType terra$getSpawnedType() { - return (EntityType) Registries.ENTITY_TYPE.getEntry( - Identifier.tryParse(((MobSpawnerLogicAccessor) getLogic()).getSpawnEntry().getNbt().getString("id").orElseThrow())) + return (EntityType) BuiltInRegistries.ENTITY_TYPE.get( + Identifier.tryParse(((BaseSpawnerAccessor) getSpawner()).getSpawnEntry().getEntityToSpawn().getString("id").orElseThrow())) .orElseThrow(); } public void terra$setSpawnedType(@NotNull EntityType creatureType) { - Random rand; - if(hasWorld()) { - rand = world.getRandom(); + RandomSource rand; + if(hasLevel()) { + rand = level.getRandom(); } else { - rand = Random.create(); + rand = RandomSource.create(); } - net.minecraft.entity.EntityType entityType = - (((net.minecraft.entity.EntityType) (creatureType.isExtended() && creatureType.getClass().equals( + net.minecraft.world.entity.EntityType entityType = + (((net.minecraft.world.entity.EntityType) (creatureType.isExtended() && creatureType.getClass().equals( MinecraftEntityTypeExtended.class) ? ((MinecraftEntityTypeExtended) creatureType).getType() : creatureType))); - setEntityType(entityType, rand); + setEntityId(entityType, rand); } public int terra$getDelay() { diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockStateArgumentMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockInputMixin.java similarity index 69% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockStateArgumentMixin.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockInputMixin.java index 2798f0508..f00cf9934 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockStateArgumentMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockInputMixin.java @@ -1,9 +1,9 @@ package com.dfsek.terra.mod.mixin.implementations.terra.block.state; -import net.minecraft.block.BlockState; -import net.minecraft.block.pattern.CachedBlockPosition; -import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.nbt.NbtCompound; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.pattern.BlockInWorld; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Implements; @@ -21,74 +21,74 @@ import com.dfsek.terra.api.block.state.properties.Property; import com.dfsek.terra.api.data.ExtendedData; -@Mixin(BlockStateArgument.class) +@Mixin(BlockInput.class) @Implements(@Interface(iface = BlockStateExtended.class, prefix = "terra$")) -public abstract class BlockStateArgumentMixin implements Predicate { +public abstract class BlockInputMixin implements Predicate { @Shadow @Nullable @Final - private NbtCompound data; + private CompoundTag tag; @Shadow - public abstract BlockState getBlockState(); + public abstract BlockState getState(); @Shadow - public abstract Set> getProperties(); + public abstract Set> getDefinedProperties(); public boolean terra$matches(com.dfsek.terra.api.block.state.BlockState other) { - return ((com.dfsek.terra.api.block.state.BlockState) getBlockState()).matches(other); + return ((com.dfsek.terra.api.block.state.BlockState) getState()).matches(other); } @Intrinsic public > boolean terra$has(com.dfsek.terra.api.block.state.properties.Property property) { - return ((com.dfsek.terra.api.block.state.BlockState) getBlockState()).has(property); + return ((com.dfsek.terra.api.block.state.BlockState) getState()).has(property); } @Intrinsic public > T terra$get(com.dfsek.terra.api.block.state.properties.Property property) { - return ((com.dfsek.terra.api.block.state.BlockState) getBlockState()).get(property); + return ((com.dfsek.terra.api.block.state.BlockState) getState()).get(property); } @Intrinsic public > com.dfsek.terra.api.block.state.BlockState terra$set(Property property, T value) { - return ((com.dfsek.terra.api.block.state.BlockState) getBlockState()).set(property, value); + return ((com.dfsek.terra.api.block.state.BlockState) getState()).set(property, value); } @Intrinsic public BlockType terra$getBlockType() { - return ((com.dfsek.terra.api.block.state.BlockState) getBlockState()).getBlockType(); + return ((com.dfsek.terra.api.block.state.BlockState) getState()).getBlockType(); } @Intrinsic public String terra$getAsString(boolean properties) { - return ((com.dfsek.terra.api.block.state.BlockState) getBlockState()).getAsString(properties); + return ((com.dfsek.terra.api.block.state.BlockState) getState()).getAsString(properties); } @Intrinsic public boolean terra$isAir() { - return ((com.dfsek.terra.api.block.state.BlockState) getBlockState()).isAir(); + return ((com.dfsek.terra.api.block.state.BlockState) getState()).isAir(); } @SuppressWarnings({ "ConstantValue", "DataFlowIssue", "EqualsBetweenInconvertibleTypes" }) @Intrinsic public BlockStateExtended terra$setData(ExtendedData data) { - return (BlockStateExtended) new BlockStateArgument(getBlockState(), getProperties(), - data.getClass().equals(NbtCompound.class) ? ((NbtCompound) ((Object) data)) : null); + return (BlockStateExtended) new BlockInput(getState(), getDefinedProperties(), + data.getClass().equals(CompoundTag.class) ? ((CompoundTag) ((Object) data)) : null); } @SuppressWarnings("DataFlowIssue") @Intrinsic public ExtendedData terra$getData() { - return ((ExtendedData) ((Object) data)); + return ((ExtendedData) ((Object) tag)); } @Intrinsic public com.dfsek.terra.api.block.state.BlockState terra$getState() { - return (com.dfsek.terra.api.block.state.BlockState) getBlockState(); + return (com.dfsek.terra.api.block.state.BlockState) getState(); } public Object terra$getHandle() { - return getBlockState(); + return getState(); } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockStateMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockStateBaseMixin.java similarity index 53% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockStateMixin.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockStateBaseMixin.java index 4243bf942..3f22c2cf7 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockStateMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockStateBaseMixin.java @@ -3,10 +3,10 @@ package com.dfsek.terra.mod.mixin.implementations.terra.block.state; import com.mojang.serialization.MapCodec; import it.unimi.dsi.fastutil.objects.Reference2ObjectArrayMap; -import net.minecraft.block.AbstractBlock.AbstractBlockState; -import net.minecraft.block.Block; -import net.minecraft.registry.Registries; -import net.minecraft.state.State; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockBehaviour.BlockStateBase; +import net.minecraft.world.level.block.state.StateHolder; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Intrinsic; @@ -18,14 +18,14 @@ import java.util.stream.Collectors; import com.dfsek.terra.api.block.BlockType; import com.dfsek.terra.api.block.state.BlockState; import com.dfsek.terra.api.block.state.properties.Property; -import com.dfsek.terra.mod.mixin.access.StateAccessor; +import com.dfsek.terra.mod.mixin.access.StateHolderAccessor; -@Mixin(AbstractBlockState.class) +@Mixin(BlockStateBase.class) @Implements(@Interface(iface = BlockState.class, prefix = "terra$")) -public abstract class BlockStateMixin extends State { - private BlockStateMixin(Block owner, Reference2ObjectArrayMap, Comparable> entries, - MapCodec codec) { +public abstract class BlockStateBaseMixin extends StateHolder { + private BlockStateBaseMixin(Block owner, Reference2ObjectArrayMap, Comparable> entries, + MapCodec codec) { super(owner, entries, codec); } @@ -36,13 +36,13 @@ public abstract class BlockStateMixin extends State> boolean terra$has(Property property) { - if(property instanceof net.minecraft.state.property.Property minecraftProperty) { - return contains(minecraftProperty); + if(property instanceof net.minecraft.world.level.block.state.properties.Property minecraftProperty) { + return hasProperty(minecraftProperty); } return false; } @@ -50,13 +50,13 @@ public abstract class BlockStateMixin extends State> T terra$get(Property property) { - return get((net.minecraft.state.property.Property) property); + return getValue((net.minecraft.world.level.block.state.properties.Property) property); } @SuppressWarnings("unchecked") @Intrinsic public > BlockState terra$set(Property property, T value) { - return (BlockState) with((net.minecraft.state.property.Property) property, value); + return (BlockState) setValue((net.minecraft.world.level.block.state.properties.Property) property, value); } @Intrinsic @@ -66,11 +66,11 @@ public abstract class BlockStateMixin extends State { @Shadow @Final - private Class type; + private Class clazz; @Shadow @Final private String name; @Shadow - public abstract List getValues(); + public abstract List getPossibleValues(); @Intrinsic public Collection terra$values() { - return getValues(); + return getPossibleValues(); } @Intrinsic public Class terra$getType() { - return type; + return clazz; } @Intrinsic diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/WorldChunkMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/LevelChunkMixin.java similarity index 64% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/WorldChunkMixin.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/LevelChunkMixin.java index 1df0ba60e..b52d275c0 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/WorldChunkMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/LevelChunkMixin.java @@ -17,11 +17,11 @@ package com.dfsek.terra.mod.mixin.implementations.terra.chunk; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.chunk.WorldChunk; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.chunk.LevelChunk; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Final; @@ -38,42 +38,42 @@ import com.dfsek.terra.api.world.chunk.Chunk; import com.dfsek.terra.mod.util.MinecraftUtil; -@Mixin(WorldChunk.class) +@Mixin(LevelChunk.class) @Implements(@Interface(iface = Chunk.class, prefix = "terra$")) -public abstract class WorldChunkMixin { +public abstract class LevelChunkMixin { @Final @Shadow - net.minecraft.world.World world; + net.minecraft.world.level.Level level; @Shadow - public abstract net.minecraft.block.BlockState getBlockState(BlockPos pos); + public abstract net.minecraft.world.level.block.state.BlockState getBlockState(BlockPos pos); @Shadow @Nullable - public abstract net.minecraft.block.BlockState setBlockState(BlockPos pos, net.minecraft.block.BlockState state, int flags); + public abstract net.minecraft.world.level.block.state.BlockState setBlockState(BlockPos pos, net.minecraft.world.level.block.state.BlockState state, int flags); @Shadow - protected abstract BlockEntity loadBlockEntity(BlockPos pos, NbtCompound nbt); + protected abstract BlockEntity promotePendingBlockEntity(BlockPos pos, CompoundTag nbt); @SuppressWarnings("ConstantValue") public void terra$setBlock(int x, int y, int z, BlockState data, boolean physics) { BlockPos blockPos = new BlockPos(x, y, z); - net.minecraft.block.BlockState state; + net.minecraft.world.level.block.state.BlockState state; boolean isExtended = MinecraftUtil.isCompatibleBlockStateExtended(data); if(isExtended) { - BlockStateArgument arg = ((BlockStateArgument) data); - state = arg.getBlockState(); + BlockInput arg = ((BlockInput) data); + state = arg.getState(); setBlockState(blockPos, state, 0); - loadBlockEntity(blockPos, ((NbtCompound) (Object) ((BlockStateExtended) data).getData())); + promotePendingBlockEntity(blockPos, ((CompoundTag) (Object) ((BlockStateExtended) data).getData())); } else { - state = (net.minecraft.block.BlockState) data; + state = (net.minecraft.world.level.block.state.BlockState) data; setBlockState(blockPos, state, 0); } if(physics) { - MinecraftUtil.schedulePhysics(state, blockPos, world.getFluidTickScheduler(), world.getBlockTickScheduler()); + MinecraftUtil.schedulePhysics(state, blockPos, level.getFluidTicks(), level.getBlockTicks()); } } @@ -88,14 +88,14 @@ public abstract class WorldChunkMixin { } public int terra$getX() { - return ((net.minecraft.world.chunk.Chunk) (Object) this).getPos().x; + return ((net.minecraft.world.level.chunk.ChunkAccess) (Object) this).getPos().x; } public int terra$getZ() { - return ((net.minecraft.world.chunk.Chunk) (Object) this).getPos().z; + return ((net.minecraft.world.level.chunk.ChunkAccess) (Object) this).getPos().z; } public ServerWorld terra$getWorld() { - return (ServerWorld) world; + return (ServerWorld) level; } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/ChunkRegionMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/WorldGenRegionMixin.java similarity index 54% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/ChunkRegionMixin.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/WorldGenRegionMixin.java index c0d7f6f0e..a07ada6ac 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/ChunkRegionMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/WorldGenRegionMixin.java @@ -18,16 +18,16 @@ package com.dfsek.terra.mod.mixin.implementations.terra.chunk; import com.dfsek.seismic.math.coord.CoordFunctions; -import net.minecraft.block.Block; -import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.fluid.Fluid; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.ChunkRegion; -import net.minecraft.world.StructureWorldAccess; -import net.minecraft.world.tick.MultiTickScheduler; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.WorldGenRegion; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.ticks.WorldGenTickAccess; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Final; @@ -42,69 +42,69 @@ import com.dfsek.terra.api.world.chunk.Chunk; import com.dfsek.terra.mod.util.MinecraftUtil; -@Mixin(ChunkRegion.class) +@Mixin(WorldGenRegion.class) @Implements(@Interface(iface = Chunk.class, prefix = "terraChunk$")) -public abstract class ChunkRegionMixin implements StructureWorldAccess { +public abstract class WorldGenRegionMixin implements WorldGenLevel { @Shadow @Final - private net.minecraft.world.chunk.Chunk centerPos; + private net.minecraft.world.level.chunk.ChunkAccess center; @Shadow @Final - private ServerWorld world; + private ServerLevel level; @Shadow @Final - private MultiTickScheduler blockTickScheduler; + private WorldGenTickAccess blockTicks; @Shadow @Final - private MultiTickScheduler fluidTickScheduler; + private WorldGenTickAccess fluidTicks; @Shadow - public abstract net.minecraft.block.BlockState getBlockState(BlockPos pos); + public abstract net.minecraft.world.level.block.state.BlockState getBlockState(BlockPos pos); @Shadow @Nullable - public abstract boolean setBlockState(BlockPos pos, net.minecraft.block.BlockState state, int flags, int maxUpdateDepth); + public abstract boolean setBlock(BlockPos pos, net.minecraft.world.level.block.state.BlockState state, int flags, int maxUpdateDepth); public void terraChunk$setBlock(int x, int y, int z, @NotNull BlockState data, boolean physics) { - ChunkPos pos = centerPos.getPos(); + ChunkPos pos = center.getPos(); BlockPos blockPos = new BlockPos(CoordFunctions.chunkAndRelativeToAbsolute(pos.x, x), y, CoordFunctions.chunkAndRelativeToAbsolute(pos.z, z)); - net.minecraft.block.BlockState state; + net.minecraft.world.level.block.state.BlockState state; boolean isExtended = MinecraftUtil.isCompatibleBlockStateExtended(data); if(isExtended) { - BlockStateArgument arg = ((BlockStateArgument) data); - state = arg.getBlockState(); - setBlockState(blockPos, state, 0, 512); - net.minecraft.world.chunk.Chunk chunk = getChunk(blockPos); - NbtCompound nbt = ((NbtCompound) (Object) ((BlockStateExtended) data).getData()); - MinecraftUtil.loadBlockEntity(chunk, world, blockPos, state, nbt); + BlockInput arg = ((BlockInput) data); + state = arg.getState(); + setBlock(blockPos, state, 0, 512); + net.minecraft.world.level.chunk.ChunkAccess chunk = getChunk(blockPos); + CompoundTag nbt = ((CompoundTag) (Object) ((BlockStateExtended) data).getData()); + MinecraftUtil.loadBlockEntity(chunk, level, blockPos, state, nbt); } else { - state = (net.minecraft.block.BlockState) data; - setBlockState(blockPos, state, 0, 512); + state = (net.minecraft.world.level.block.state.BlockState) data; + setBlock(blockPos, state, 0, 512); } if(physics) { - MinecraftUtil.schedulePhysics(state, blockPos, getFluidTickScheduler(), getBlockTickScheduler()); + MinecraftUtil.schedulePhysics(state, blockPos, getFluidTicks(), getBlockTicks()); } } public @NotNull BlockState terraChunk$getBlock(int x, int y, int z) { - return (BlockState) ((ChunkRegion) (Object) this).getBlockState( - new BlockPos(x + (centerPos.getPos().x << 4), y, z + (centerPos.getPos().z << 4))); + return (BlockState) ((WorldGenRegion) (Object) this).getBlockState( + new BlockPos(x + (center.getPos().x << 4), y, z + (center.getPos().z << 4))); } public int terraChunk$getX() { - return centerPos.getPos().x; + return center.getPos().x; } public int terraChunk$getZ() { - return centerPos.getPos().z; + return center.getPos().z; } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/data/ProtoChunkMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/data/ProtoChunkMixin.java index d8dc40aaf..bdc5f4029 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/data/ProtoChunkMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/chunk/data/ProtoChunkMixin.java @@ -17,15 +17,15 @@ package com.dfsek.terra.mod.mixin.implementations.terra.chunk.data; -import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.HeightLimitView; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.ChunkSection; -import net.minecraft.world.chunk.PalettesFactory; -import net.minecraft.world.chunk.UpgradeData; -import net.minecraft.world.gen.chunk.BlendingData; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.LevelHeightAccessor; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.LevelChunkSection; +import net.minecraft.world.level.chunk.PalettedContainerFactory; +import net.minecraft.world.level.chunk.UpgradeData; +import net.minecraft.world.level.levelgen.blending.BlendingData; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Implements; @@ -38,30 +38,30 @@ import com.dfsek.terra.api.block.state.BlockStateExtended; import com.dfsek.terra.api.world.chunk.generation.ProtoChunk; -@Mixin(net.minecraft.world.chunk.ProtoChunk.class) +@Mixin(net.minecraft.world.level.chunk.ProtoChunk.class) @Implements(@Interface(iface = ProtoChunk.class, prefix = "terra$")) -public abstract class ProtoChunkMixin extends Chunk { - public ProtoChunkMixin(ChunkPos pos, UpgradeData upgradeData, HeightLimitView heightLimitView, PalettesFactory palettesFactory, - long inhabitedTime, @Nullable ChunkSection[] sectionArray, @Nullable BlendingData blendingData) { +public abstract class ProtoChunkMixin extends ChunkAccess { + public ProtoChunkMixin(ChunkPos pos, UpgradeData upgradeData, LevelHeightAccessor heightLimitView, PalettedContainerFactory palettesFactory, + long inhabitedTime, @Nullable LevelChunkSection[] sectionArray, @Nullable BlendingData blendingData) { super(pos, upgradeData, heightLimitView, palettesFactory, inhabitedTime, sectionArray, blendingData); } @Shadow - public abstract net.minecraft.block.BlockState getBlockState(BlockPos pos); + public abstract net.minecraft.world.level.block.state.BlockState getBlockState(BlockPos pos); @Shadow - public abstract HeightLimitView getHeightLimitView(); + public abstract LevelHeightAccessor getHeightAccessorForGeneration(); public void terra$setBlock(int x, int y, int z, @NotNull BlockState data) { BlockPos blockPos = new BlockPos(x, y, z); - boolean isExtended = data.isExtended() && data.getClass().equals(BlockStateArgument.class); + boolean isExtended = data.isExtended() && data.getClass().equals(BlockInput.class); if(isExtended) { BlockStateExtended blockStateExtended = (BlockStateExtended) data; - net.minecraft.block.BlockState blockState = (net.minecraft.block.BlockState) blockStateExtended.getState(); + net.minecraft.world.level.block.state.BlockState blockState = (net.minecraft.world.level.block.state.BlockState) blockStateExtended.getState(); this.setBlockState(blockPos, blockState, 0); } else { - this.setBlockState(blockPos, (net.minecraft.block.BlockState) data, 0); + this.setBlockState(blockPos, (net.minecraft.world.level.block.state.BlockState) data, 0); } } @@ -70,6 +70,6 @@ public abstract class ProtoChunkMixin extends Chunk { } public int terra$getMaxHeight() { - return getHeightLimitView().getTopYInclusive(); + return getHeightAccessorForGeneration().getMaxY(); } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/ServerCommandSourceMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/CommandSourceStackMixin.java similarity index 77% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/ServerCommandSourceMixin.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/CommandSourceStackMixin.java index 0afa29269..c30037f6c 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/ServerCommandSourceMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/CommandSourceStackMixin.java @@ -18,9 +18,9 @@ package com.dfsek.terra.mod.mixin.implementations.terra.entity; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.Text; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; @@ -34,21 +34,21 @@ import com.dfsek.terra.api.entity.Entity; import com.dfsek.terra.api.entity.Player; -@Mixin(ServerCommandSource.class) +@Mixin(CommandSourceStack.class) @Implements(@Interface(iface = CommandSender.class, prefix = "terra$")) -public abstract class ServerCommandSourceMixin { +public abstract class CommandSourceStackMixin { @Shadow - public abstract ServerPlayerEntity getPlayer() throws CommandSyntaxException; + public abstract ServerPlayer getPlayer() throws CommandSyntaxException; @Shadow @Nullable - public abstract net.minecraft.entity.@Nullable Entity getEntity(); + public abstract net.minecraft.world.entity.@Nullable Entity getEntity(); @Shadow - public abstract void sendMessage(Text message); + public abstract void sendSystemMessage(Component message); public void terra$sendMessage(String message) { - sendMessage(Text.literal(message)); + sendSystemMessage(Component.literal(message)); } @Nullable diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/EntityMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/EntityMixin.java index 7bc47dc62..60a860e90 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/EntityMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/EntityMixin.java @@ -18,8 +18,8 @@ package com.dfsek.terra.mod.mixin.implementations.terra.entity; import com.dfsek.seismic.type.vector.Vector3; -import net.minecraft.entity.Entity; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Entity; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Mixin; @@ -33,23 +33,23 @@ import com.dfsek.terra.mod.util.MinecraftAdapter; @Implements(@Interface(iface = com.dfsek.terra.api.entity.Entity.class, prefix = "terra$")) public abstract class EntityMixin { @Shadow - private net.minecraft.world.World world; + private net.minecraft.world.level.Level level; @Shadow - private BlockPos blockPos; + private BlockPos blockPosition; @Shadow - public abstract void updatePosition(double destX, double destY, double destZ); + public abstract void absSnapTo(double destX, double destY, double destZ); public Vector3 terra$position() { - return MinecraftAdapter.adapt(blockPos); + return MinecraftAdapter.adapt(blockPosition); } public void terra$position(Vector3 location) { - updatePosition(location.getX(), location.getY(), location.getZ()); + absSnapTo(location.getX(), location.getY(), location.getZ()); } public ServerWorld terra$world() { - return (ServerWorld) world; + return (ServerWorld) level; } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/EntityTypeMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/EntityTypeMixin.java index a79d4fb0d..fd94302ba 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/EntityTypeMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/EntityTypeMixin.java @@ -17,7 +17,7 @@ package com.dfsek.terra.mod.mixin.implementations.terra.entity; -import net.minecraft.entity.EntityType; +import net.minecraft.world.entity.EntityType; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Mixin; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/PlayerEntityMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/PlayerMixin.java similarity index 87% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/PlayerEntityMixin.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/PlayerMixin.java index ec60c9f69..b13797ec8 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/PlayerEntityMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/entity/PlayerMixin.java @@ -17,7 +17,6 @@ package com.dfsek.terra.mod.mixin.implementations.terra.entity; -import net.minecraft.entity.player.PlayerEntity; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Mixin; @@ -25,7 +24,7 @@ import org.spongepowered.asm.mixin.Mixin; import com.dfsek.terra.api.entity.Player; -@Mixin(PlayerEntity.class) +@Mixin(net.minecraft.world.entity.player.Player.class) @Implements(@Interface(iface = Player.class, prefix = "terra$")) -public abstract class PlayerEntityMixin extends EntityMixin { +public abstract class PlayerMixin extends EntityMixin { } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/LockableContainerBlockEntityMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/BaseContainerBlockEntityMixin.java similarity index 73% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/LockableContainerBlockEntityMixin.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/BaseContainerBlockEntityMixin.java index 41342d23f..0c1f2674e 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/LockableContainerBlockEntityMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/BaseContainerBlockEntityMixin.java @@ -17,8 +17,8 @@ package com.dfsek.terra.mod.mixin.implementations.terra.inventory; -import net.minecraft.block.entity.LockableContainerBlockEntity; -import net.minecraft.item.Items; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.entity.BaseContainerBlockEntity; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Mixin; @@ -27,21 +27,21 @@ import com.dfsek.terra.api.inventory.Inventory; import com.dfsek.terra.api.inventory.ItemStack; -@Mixin(LockableContainerBlockEntity.class) +@Mixin(BaseContainerBlockEntity.class) @Implements(@Interface(iface = Inventory.class, prefix = "terra$")) -public class LockableContainerBlockEntityMixin { +public class BaseContainerBlockEntityMixin { @SuppressWarnings("ConstantConditions") public void terra$setItem(int slot, ItemStack newStack) { - ((LockableContainerBlockEntity) (Object) this).setStack(slot, (net.minecraft.item.ItemStack) (Object) newStack); + ((BaseContainerBlockEntity) (Object) this).setItem(slot, (net.minecraft.world.item.ItemStack) (Object) newStack); } public int terra$getSize() { - return ((LockableContainerBlockEntity) (Object) this).size(); + return ((BaseContainerBlockEntity) (Object) this).getContainerSize(); } @SuppressWarnings("ConstantConditions") public ItemStack terra$getItem(int slot) { - net.minecraft.item.ItemStack itemStack = ((LockableContainerBlockEntity) (Object) this).getStack(slot); + net.minecraft.world.item.ItemStack itemStack = ((BaseContainerBlockEntity) (Object) this).getItem(slot); return itemStack.getItem() == Items.AIR ? null : (ItemStack) (Object) itemStack; } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/item/ItemMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/item/ItemMixin.java index e8832c214..1d8cdc73f 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/item/ItemMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/item/ItemMixin.java @@ -17,7 +17,7 @@ package com.dfsek.terra.mod.mixin.implementations.terra.inventory.item; -import net.minecraft.item.Item; +import net.minecraft.world.item.Item; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Mixin; @@ -30,15 +30,15 @@ import com.dfsek.terra.api.inventory.ItemStack; @Implements(@Interface(iface = com.dfsek.terra.api.inventory.Item.class, prefix = "terra$")) public abstract class ItemMixin { @Shadow - public abstract net.minecraft.item.ItemStack getDefaultStack(); + public abstract net.minecraft.world.item.ItemStack getDefaultInstance(); @SuppressWarnings("ConstantConditions") public ItemStack terra$newItemStack(int amount) { - return (ItemStack) (Object) new net.minecraft.item.ItemStack((Item) (Object) this, amount); + return (ItemStack) (Object) new net.minecraft.world.item.ItemStack((Item) (Object) this, amount); } public double terra$getMaxDurability() { //TODO verify this is correct - return getDefaultStack().getMaxDamage(); + return getDefaultInstance().getMaxDamage(); } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/item/ItemStackMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/item/ItemStackMixin.java index 7837c626a..59858c26d 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/item/ItemStackMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/item/ItemStackMixin.java @@ -17,10 +17,10 @@ package com.dfsek.terra.mod.mixin.implementations.terra.inventory.item; -import net.minecraft.component.ComponentChanges; -import net.minecraft.component.ComponentMap; -import net.minecraft.component.MergedComponentMap; -import net.minecraft.item.ItemStack; +import net.minecraft.core.component.DataComponentMap; +import net.minecraft.core.component.DataComponentPatch; +import net.minecraft.core.component.PatchedDataComponentMap; +import net.minecraft.world.item.ItemStack; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; @@ -37,7 +37,7 @@ import com.dfsek.terra.api.inventory.item.ItemMeta; public abstract class ItemStackMixin { @Shadow @Final - private MergedComponentMap components; + private PatchedDataComponentMap components; @Shadow public abstract int getCount(); @@ -46,13 +46,13 @@ public abstract class ItemStackMixin { public abstract void setCount(int count); @Shadow - public abstract net.minecraft.item.Item getItem(); + public abstract net.minecraft.world.item.Item getItem(); @Shadow - public abstract boolean isDamageable(); + public abstract boolean isDamageableItem(); @Shadow - public abstract ComponentMap getComponents(); + public abstract DataComponentMap getComponents(); public int terra$getAmount() { return getCount(); @@ -72,17 +72,17 @@ public abstract class ItemStackMixin { @SuppressWarnings("ConstantConditions") public void terra$setItemMeta(ItemMeta meta) { - ComponentChanges.Builder builder = ComponentChanges.builder(); - this.getComponents().getTypes().forEach(builder::remove); + DataComponentPatch.Builder builder = DataComponentPatch.builder(); + this.getComponents().keySet().forEach(builder::remove); - ComponentMap components = ((ItemStack) (Object) meta).getComponents(); - components.forEach(builder::add); + DataComponentMap components = ((ItemStack) (Object) meta).getComponents(); + components.forEach(builder::set); - this.components.applyChanges(builder.build()); + this.components.applyPatch(builder.build()); } @Intrinsic public boolean terra$isDamageable() { - return isDamageable(); + return isDamageableItem(); } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/meta/EnchantmentMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/meta/EnchantmentMixin.java index 8f58fb9d8..f1a30c8ba 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/meta/EnchantmentMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/meta/EnchantmentMixin.java @@ -17,9 +17,9 @@ package com.dfsek.terra.mod.mixin.implementations.terra.inventory.meta; -import net.minecraft.enchantment.Enchantment; -import net.minecraft.registry.entry.RegistryEntry; -import net.minecraft.registry.entry.RegistryEntryList; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderSet; +import net.minecraft.world.item.enchantment.Enchantment; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; @@ -31,7 +31,7 @@ import java.util.Objects; import com.dfsek.terra.api.inventory.ItemStack; import com.dfsek.terra.mod.CommonPlatform; -import static net.minecraft.enchantment.Enchantment.canBeCombined; +import static net.minecraft.world.item.enchantment.Enchantment.areCompatible; @Mixin(Enchantment.class) @@ -39,21 +39,21 @@ import static net.minecraft.enchantment.Enchantment.canBeCombined; public abstract class EnchantmentMixin { @Shadow @Final - private RegistryEntryList exclusiveSet; + private HolderSet exclusiveSet; @Shadow - public abstract boolean isAcceptableItem(net.minecraft.item.ItemStack stack); + public abstract boolean canEnchant(net.minecraft.world.item.ItemStack stack); @SuppressWarnings("ConstantConditions") public boolean terra$canEnchantItem(ItemStack itemStack) { - return isAcceptableItem((net.minecraft.item.ItemStack) (Object) itemStack); + return canEnchant((net.minecraft.world.item.ItemStack) (Object) itemStack); } public boolean terra$conflictsWith(com.dfsek.terra.api.inventory.item.Enchantment other) { - return canBeCombined(RegistryEntry.of((Enchantment) (Object) this), RegistryEntry.of((Enchantment) (Object) other)); + return areCompatible(Holder.direct((Enchantment) (Object) this), Holder.direct((Enchantment) (Object) other)); } public String terra$getID() { - return Objects.requireNonNull(CommonPlatform.get().enchantmentRegistry().getId((Enchantment) (Object) this)).toString(); + return Objects.requireNonNull(CommonPlatform.get().enchantmentRegistry().getKey((Enchantment) (Object) this)).toString(); } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/meta/ItemStackDamageableMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/meta/ItemStackDamageableMixin.java index 633df07d6..5d9dec693 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/meta/ItemStackDamageableMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/meta/ItemStackDamageableMixin.java @@ -17,7 +17,7 @@ package com.dfsek.terra.mod.mixin.implementations.terra.inventory.meta; -import net.minecraft.item.ItemStack; +import net.minecraft.world.item.ItemStack; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Intrinsic; @@ -34,19 +34,19 @@ public abstract class ItemStackDamageableMixin { public abstract boolean isDamaged(); @Shadow - public abstract int getDamage(); + public abstract int getDamageValue(); @Shadow - public abstract void setDamage(int damage); + public abstract void setDamageValue(int damage); @Intrinsic public int terra$getDamage() { - return getDamage(); + return getDamageValue(); } @Intrinsic public void terra$setDamage(int damage) { - setDamage(damage); + setDamageValue(damage); } public boolean terra$hasDamage() { diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/meta/ItemStackMetaMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/meta/ItemStackMetaMixin.java index 91a487d0b..6e06b7b3c 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/meta/ItemStackMetaMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/inventory/meta/ItemStackMetaMixin.java @@ -17,9 +17,9 @@ package com.dfsek.terra.mod.mixin.implementations.terra.inventory.meta; -import net.minecraft.component.type.ItemEnchantmentsComponent; -import net.minecraft.item.ItemStack; -import net.minecraft.registry.entry.RegistryEntry; +import net.minecraft.core.Holder; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.ItemEnchantments; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Intrinsic; @@ -38,28 +38,28 @@ import com.dfsek.terra.api.inventory.item.ItemMeta; @Implements(@Interface(iface = ItemMeta.class, prefix = "terra$")) public abstract class ItemStackMetaMixin { @Shadow - public abstract boolean hasEnchantments(); + public abstract boolean isEnchanted(); @Shadow - public abstract ItemEnchantmentsComponent getEnchantments(); + public abstract ItemEnchantments getEnchantments(); @Shadow - public abstract void addEnchantment(RegistryEntry enchantment, int level); + public abstract void enchant(Holder enchantment, int level); public void terra$addEnchantment(Enchantment enchantment, int level) { ; - addEnchantment(RegistryEntry.of((net.minecraft.enchantment.Enchantment) (Object) enchantment), level); + enchant(Holder.direct((net.minecraft.world.item.enchantment.Enchantment) (Object) enchantment), level); } @Intrinsic(displace = true) public Map terra$getEnchantments() { - if(!hasEnchantments()) return Collections.emptyMap(); + if(!isEnchanted()) return Collections.emptyMap(); Map map = new HashMap<>(); - ItemEnchantmentsComponent enchantments = getEnchantments(); - enchantments.getEnchantments().forEach(enchantment -> { - net.minecraft.enchantment.Enchantment enchantmentValue = enchantment.value(); - map.put((Enchantment) (Object) enchantmentValue, enchantments.getLevel(RegistryEntry.of(enchantmentValue))); + ItemEnchantments enchantments = getEnchantments(); + enchantments.keySet().forEach(enchantment -> { + net.minecraft.world.item.enchantment.Enchantment enchantmentValue = enchantment.value(); + map.put((Enchantment) (Object) enchantmentValue, enchantments.getLevel(Holder.direct(enchantmentValue))); }); return map; } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/nbt/NbtCompoundMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/nbt/CompoundTagMixin.java similarity index 73% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/nbt/NbtCompoundMixin.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/nbt/CompoundTagMixin.java index e81016e28..9eed7ce5b 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/nbt/NbtCompoundMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/nbt/CompoundTagMixin.java @@ -1,7 +1,7 @@ package com.dfsek.terra.mod.mixin.implementations.terra.nbt; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtElement; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.Tag; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Intrinsic; @@ -10,9 +10,9 @@ import org.spongepowered.asm.mixin.Mixin; import com.dfsek.terra.api.data.ExtendedData; -@Mixin(NbtCompound.class) +@Mixin(CompoundTag.class) @Implements(@Interface(iface = ExtendedData.class, prefix = "terra$")) -public abstract class NbtCompoundMixin implements NbtElement { +public abstract class CompoundTagMixin implements Tag { @Intrinsic public String terra$toString() { return this.toString(); diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/ServerWorldMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/ServerLevelMixin.java similarity index 57% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/ServerWorldMixin.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/ServerLevelMixin.java index fdba31a50..b5323166b 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/ServerWorldMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/ServerLevelMixin.java @@ -17,19 +17,19 @@ package com.dfsek.terra.mod.mixin.implementations.terra.world; -import net.minecraft.block.Block; -import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.entity.SpawnReason; -import net.minecraft.fluid.Fluid; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.registry.DynamicRegistryManager; -import net.minecraft.registry.RegistryKey; -import net.minecraft.registry.entry.RegistryEntry; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.MutableWorldProperties; -import net.minecraft.world.World; -import net.minecraft.world.dimension.DimensionType; -import net.minecraft.world.tick.WorldTickScheduler; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.core.RegistryAccess; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.level.storage.WritableLevelData; +import net.minecraft.world.ticks.LevelTicks; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Intrinsic; @@ -49,41 +49,41 @@ import com.dfsek.terra.api.world.chunk.generation.ChunkGenerator; import com.dfsek.terra.mod.generation.MinecraftChunkGeneratorWrapper; import com.dfsek.terra.mod.generation.TerraBiomeSource; import com.dfsek.terra.mod.implmentation.MinecraftEntityTypeExtended; -import com.dfsek.terra.mod.mixin.access.WorldChunkAccessor; +import com.dfsek.terra.mod.mixin.access.LevelChunkAccessor; import com.dfsek.terra.mod.util.MinecraftUtil; -@Mixin(net.minecraft.server.world.ServerWorld.class) +@Mixin(net.minecraft.server.level.ServerLevel.class) @Implements(@Interface(iface = ServerWorld.class, prefix = "terra$")) -public abstract class ServerWorldMixin extends World { - protected ServerWorldMixin(MutableWorldProperties properties, RegistryKey registryRef, DynamicRegistryManager registryManager, - RegistryEntry dimensionEntry, boolean isClient, boolean debugWorld, long seed, +public abstract class ServerLevelMixin extends Level { + protected ServerLevelMixin(WritableLevelData properties, ResourceKey registryRef, RegistryAccess registryManager, + Holder dimensionEntry, boolean isClient, boolean debugWorld, long seed, int maxChainedNeighborUpdates) { super(properties, registryRef, registryManager, dimensionEntry, isClient, debugWorld, seed, maxChainedNeighborUpdates); } @Shadow - public abstract WorldTickScheduler getBlockTickScheduler(); + public abstract LevelTicks getBlockTicks(); @Shadow - public abstract WorldTickScheduler getFluidTickScheduler(); + public abstract LevelTicks getFluidTicks(); public Entity terra$spawnEntity(double x, double y, double z, EntityType data) { boolean isExtended = MinecraftUtil.isCompatibleEntityTypeExtended(data); - net.minecraft.entity.Entity entity; + net.minecraft.world.entity.Entity entity; if(isExtended) { MinecraftEntityTypeExtended type = ((MinecraftEntityTypeExtended) data); - NbtCompound nbt = (NbtCompound) ((Object) type.getData()); - entity = net.minecraft.entity.EntityType.loadEntityWithPassengers(nbt, this, SpawnReason.CHUNK_GENERATION, (entityx) -> { - entityx.refreshPositionAndAngles(x, y, z, entityx.getYaw(), entityx.getPitch()); + CompoundTag nbt = (CompoundTag) ((Object) type.getData()); + entity = net.minecraft.world.entity.EntityType.loadEntityRecursive(nbt, this, EntitySpawnReason.CHUNK_GENERATION, (entityx) -> { + entityx.snapTo(x, y, z, entityx.getYRot(), entityx.getXRot()); return entityx; }); - spawnEntity(entity); + addFreshEntity(entity); } else { - entity = ((net.minecraft.entity.EntityType) data).create(this, SpawnReason.CHUNK_GENERATION); - entity.setPos(x, y, z); - spawnEntity(entity); + entity = ((net.minecraft.world.entity.EntityType) data).create(this, EntitySpawnReason.CHUNK_GENERATION); + entity.setPosRaw(x, y, z); + addFreshEntity(entity); } return (Entity) entity; @@ -91,35 +91,35 @@ public abstract class ServerWorldMixin extends World { public void terra$setBlockState(int x, int y, int z, BlockState data, boolean physics) { BlockPos blockPos = new BlockPos(x, y, z); - net.minecraft.block.BlockState state; + net.minecraft.world.level.block.state.BlockState state; int flags = physics ? 3 : 1042; boolean isExtended = MinecraftUtil.isCompatibleBlockStateExtended(data); if(isExtended) { - BlockStateArgument arg = ((BlockStateArgument) data); - state = arg.getBlockState(); - setBlockState(blockPos, state, flags); - net.minecraft.world.chunk.Chunk chunk = getWorldChunk(blockPos); - ((WorldChunkAccessor) chunk).invokeLoadBlockEntity(blockPos, ((NbtCompound) (Object) ((BlockStateExtended) data).getData())); + BlockInput arg = ((BlockInput) data); + state = arg.getState(); + setBlock(blockPos, state, flags); + net.minecraft.world.level.chunk.ChunkAccess chunk = getChunkAt(blockPos); + ((LevelChunkAccessor) chunk).invokeLoadBlockEntity(blockPos, ((CompoundTag) (Object) ((BlockStateExtended) data).getData())); } else { - state = (net.minecraft.block.BlockState) data; - setBlockState(blockPos, state, flags); + state = (net.minecraft.world.level.block.state.BlockState) data; + setBlock(blockPos, state, flags); } if(physics) { - MinecraftUtil.schedulePhysics(state, blockPos, this.getFluidTickScheduler(), this.getBlockTickScheduler()); + MinecraftUtil.schedulePhysics(state, blockPos, this.getFluidTicks(), this.getBlockTicks()); } } @Intrinsic public long terra$getSeed() { - return ((net.minecraft.server.world.ServerWorld) (Object) this).getSeed(); + return ((net.minecraft.server.level.ServerLevel) (Object) this).getSeed(); } public int terra$getMaxHeight() { - return ((this).getBottomY()) + + return ((this).getMinY()) + (this).getHeight(); } @@ -136,23 +136,23 @@ public abstract class ServerWorldMixin extends World { } public int terra$getMinHeight() { - return (this).getBottomY(); + return (this).getMinY(); } public ChunkGenerator terra$getGenerator() { - return ((MinecraftChunkGeneratorWrapper) ((net.minecraft.server.world.ServerWorld) (Object) this).getChunkManager() - .getChunkGenerator()).getHandle(); + return ((MinecraftChunkGeneratorWrapper) ((net.minecraft.server.level.ServerLevel) (Object) this).getChunkSource() + .getGenerator()).getHandle(); } public BiomeProvider terra$getBiomeProvider() { - return ((TerraBiomeSource) ((net.minecraft.server.world.ServerWorld) (Object) this).getChunkManager() - .getChunkGenerator() + return ((TerraBiomeSource) ((net.minecraft.server.level.ServerLevel) (Object) this).getChunkSource() + .getGenerator() .getBiomeSource()).getProvider(); } public ConfigPack terra$getPack() { - net.minecraft.world.gen.chunk.ChunkGenerator generator = - (((net.minecraft.server.world.ServerWorld) (Object) this).getChunkManager()).getChunkGenerator(); + net.minecraft.world.level.chunk.ChunkGenerator generator = + (((net.minecraft.server.level.ServerLevel) (Object) this).getChunkSource()).getGenerator(); if(generator instanceof MinecraftChunkGeneratorWrapper minecraftChunkGeneratorWrapper) { return minecraftChunkGeneratorWrapper.getPack(); } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/ChunkRegionMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/WorldGenRegionMixin.java similarity index 60% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/ChunkRegionMixin.java rename to platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/WorldGenRegionMixin.java index 1c34c6a4d..320d98af3 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/ChunkRegionMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/WorldGenRegionMixin.java @@ -17,18 +17,18 @@ package com.dfsek.terra.mod.mixin.implementations.terra.world; -import net.minecraft.block.Block; -import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.entity.SpawnReason; -import net.minecraft.fluid.Fluid; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.util.collection.BoundedRegionArray; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.ChunkRegion; -import net.minecraft.world.StructureWorldAccess; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.ChunkGenerationStep; -import net.minecraft.world.tick.MultiTickScheduler; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.server.level.WorldGenRegion; +import net.minecraft.util.StaticCache2D; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.status.ChunkStep; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.ticks.WorldGenTickAccess; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; @@ -54,37 +54,36 @@ import com.dfsek.terra.mod.implmentation.MinecraftEntityTypeExtended; import com.dfsek.terra.mod.util.MinecraftUtil; -@Mixin(ChunkRegion.class) +@Mixin(WorldGenRegion.class) @Implements(@Interface(iface = ProtoWorld.class, prefix = "terraWorld$")) -public abstract class ChunkRegionMixin implements StructureWorldAccess { +public abstract class WorldGenRegionMixin implements WorldGenLevel { private ConfigPack terra$config; @Shadow @Final - private net.minecraft.server.world.ServerWorld world; + private net.minecraft.server.level.ServerLevel level; @Shadow @Final private long seed; @Shadow @Final - private Chunk centerPos; + private ChunkAccess center; @Shadow @Final - private MultiTickScheduler fluidTickScheduler; + private WorldGenTickAccess fluidTicks; @Shadow @Final - private MultiTickScheduler blockTickScheduler; + private WorldGenTickAccess blockTicks; @Inject(at = @At("RETURN"), - method = "(Lnet/minecraft/server/world/ServerWorld;Lnet/minecraft/util/collection/BoundedRegionArray;" + - "Lnet/minecraft/world/chunk/ChunkGenerationStep;Lnet/minecraft/world/chunk/Chunk;)V") - public void injectConstructor(net.minecraft.server.world.ServerWorld world, BoundedRegionArray chunks, - ChunkGenerationStep generationStep, Chunk centerPos, CallbackInfo ci) { + method = "(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/util/StaticCache2D;Lnet/minecraft/world/level/chunk/status/ChunkStep;Lnet/minecraft/world/level/chunk/ChunkAccess;)V") + public void injectConstructor(net.minecraft.server.level.ServerLevel world, StaticCache2D chunks, + ChunkStep generationStep, ChunkAccess centerPos, CallbackInfo ci) { this.terra$config = ((ServerWorld) world).getPack(); } @@ -92,25 +91,25 @@ public abstract class ChunkRegionMixin implements StructureWorldAccess { @Intrinsic(displace = true) public void terraWorld$setBlockState(int x, int y, int z, BlockState data, boolean physics) { BlockPos blockPos = new BlockPos(x, y, z); - net.minecraft.block.BlockState state; + net.minecraft.world.level.block.state.BlockState state; int flags = physics ? 3 : 1042; boolean isExtended = MinecraftUtil.isCompatibleBlockStateExtended(data); if(isExtended) { - BlockStateArgument arg = ((BlockStateArgument) data); - state = arg.getBlockState(); - setBlockState(blockPos, state, flags); - net.minecraft.world.chunk.Chunk chunk = getChunk(blockPos); - NbtCompound nbt = ((NbtCompound) (Object) ((BlockStateExtended) data).getData()); - MinecraftUtil.loadBlockEntity(chunk, world, blockPos, state, nbt); + BlockInput arg = ((BlockInput) data); + state = arg.getState(); + setBlock(blockPos, state, flags); + net.minecraft.world.level.chunk.ChunkAccess chunk = getChunk(blockPos); + CompoundTag nbt = ((CompoundTag) (Object) ((BlockStateExtended) data).getData()); + MinecraftUtil.loadBlockEntity(chunk, level, blockPos, state, nbt); } else { - state = (net.minecraft.block.BlockState) data; - setBlockState(blockPos, state, flags); + state = (net.minecraft.world.level.block.state.BlockState) data; + setBlock(blockPos, state, flags); } if(physics) { - MinecraftUtil.schedulePhysics(state, blockPos, getFluidTickScheduler(), getBlockTickScheduler()); + MinecraftUtil.schedulePhysics(state, blockPos, getFluidTicks(), getBlockTicks()); } } @@ -120,7 +119,7 @@ public abstract class ChunkRegionMixin implements StructureWorldAccess { } public int terraWorld$getMaxHeight() { - return world.getTopYInclusive(); + return level.getMaxY(); } @Intrinsic(displace = true) @@ -134,11 +133,11 @@ public abstract class ChunkRegionMixin implements StructureWorldAccess { } public int terraWorld$getMinHeight() { - return world.getBottomY(); + return level.getMinY(); } public ChunkGenerator terraWorld$getGenerator() { - return ((MinecraftChunkGeneratorWrapper) world.getChunkManager().getChunkGenerator()).getHandle(); + return ((MinecraftChunkGeneratorWrapper) level.getChunkSource().getGenerator()).getHandle(); } public BiomeProvider terraWorld$getBiomeProvider() { @@ -148,34 +147,34 @@ public abstract class ChunkRegionMixin implements StructureWorldAccess { @SuppressWarnings("DataFlowIssue") public Entity terraWorld$spawnEntity(double x, double y, double z, EntityType data) { boolean isExtended = MinecraftUtil.isCompatibleEntityTypeExtended(data); - net.minecraft.entity.Entity entity; + net.minecraft.world.entity.Entity entity; if(isExtended) { MinecraftEntityTypeExtended type = ((MinecraftEntityTypeExtended) data); - NbtCompound nbt = (NbtCompound) ((Object) type.getData()); - entity = net.minecraft.entity.EntityType.loadEntityWithPassengers(nbt, world, SpawnReason.CHUNK_GENERATION, (entityx) -> { - entityx.refreshPositionAndAngles(x, y, z, entityx.getYaw(), entityx.getPitch()); + CompoundTag nbt = (CompoundTag) ((Object) type.getData()); + entity = net.minecraft.world.entity.EntityType.loadEntityRecursive(nbt, level, EntitySpawnReason.CHUNK_GENERATION, (entityx) -> { + entityx.snapTo(x, y, z, entityx.getYRot(), entityx.getXRot()); return entityx; }); - spawnEntity(entity); + addFreshEntity(entity); } else { - entity = ((net.minecraft.entity.EntityType) data).create(world, SpawnReason.CHUNK_GENERATION); - entity.setPos(x, y, z); - spawnEntity(entity); + entity = ((net.minecraft.world.entity.EntityType) data).create(level, EntitySpawnReason.CHUNK_GENERATION); + entity.setPosRaw(x, y, z); + addFreshEntity(entity); } return (Entity) entity; } public int terraWorld$centerChunkX() { - return centerPos.getPos().x; + return center.getPos().x; } public int terraWorld$centerChunkZ() { - return centerPos.getPos().z; + return center.getPos().z; } public ServerWorld terraWorld$getWorld() { - return (ServerWorld) world; + return (ServerWorld) level; } public ConfigPack terraWorld$getPack() { diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/invoke/BiomeInvoker.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/invoke/BiomeInvoker.java index b3aa4792b..9e0bc73c3 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/invoke/BiomeInvoker.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/invoke/BiomeInvoker.java @@ -1,12 +1,12 @@ package com.dfsek.terra.mod.mixin.invoke; -import net.minecraft.world.biome.Biome; +import net.minecraft.world.level.biome.Biome; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(Biome.class) public interface BiomeInvoker { - @Invoker("getDefaultGrassColor") + @Invoker("getGrassColorFromTexture") int invokeGetDefaultGrassColor(); } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/invoke/FluidBlockInvoker.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/invoke/FluidBlockInvoker.java deleted file mode 100644 index 620d03ec1..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/invoke/FluidBlockInvoker.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.dfsek.terra.mod.mixin.invoke; - -import net.minecraft.block.BlockState; -import net.minecraft.block.FluidBlock; -import net.minecraft.fluid.FluidState; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; - - -@Mixin(FluidBlock.class) -public interface FluidBlockInvoker { - @Invoker("getFluidState") - FluidState invokeGetFluidState(BlockState state); -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/invoke/LiquidBlockInvoker.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/invoke/LiquidBlockInvoker.java new file mode 100644 index 000000000..7c2d73d03 --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/invoke/LiquidBlockInvoker.java @@ -0,0 +1,14 @@ +package com.dfsek.terra.mod.mixin.invoke; + +import net.minecraft.world.level.block.LiquidBlock; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.FluidState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + + +@Mixin(LiquidBlock.class) +public interface LiquidBlockInvoker { + @Invoker("getFluidState") + FluidState invokeGetFluidState(BlockState state); +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/lifecycle/DataPackContentsMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/lifecycle/DataPackContentsMixin.java deleted file mode 100644 index ee7864d3b..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/lifecycle/DataPackContentsMixin.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.dfsek.terra.mod.mixin.lifecycle; - -import net.minecraft.registry.CombinedDynamicRegistries; -import net.minecraft.registry.DynamicRegistryManager; -import net.minecraft.registry.Registry; -import net.minecraft.registry.Registry.PendingTagLoad; -import net.minecraft.registry.RegistryKeys; -import net.minecraft.registry.ReloadableRegistries; -import net.minecraft.registry.ServerDynamicRegistryType; -import net.minecraft.resource.ResourceManager; -import net.minecraft.resource.featuretoggle.FeatureSet; -import net.minecraft.server.DataPackContents; -import net.minecraft.server.command.CommandManager; -import net.minecraft.world.biome.Biome; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; - -import com.dfsek.terra.mod.util.MinecraftUtil; -import com.dfsek.terra.mod.util.TagUtil; - - -@Mixin(DataPackContents.class) -public class DataPackContentsMixin { - @Shadow - @Final - private ReloadableRegistries.Lookup reloadableRegistries; - - /* - * #refresh populates all tags in the registries - */ - @Inject(method = "reload(Lnet/minecraft/resource/ResourceManager;Lnet/minecraft/registry/CombinedDynamicRegistries;Ljava/util/List;" + - "Lnet/minecraft/resource/featuretoggle/FeatureSet;" + - "Lnet/minecraft/server/command/CommandManager$RegistrationEnvironment;ILjava/util/concurrent/Executor;" + - "Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletableFuture;", - at = @At("RETURN")) - private static void injectReload(ResourceManager resourceManager, - CombinedDynamicRegistries dynamicRegistries, - List> pendingTagLoads, FeatureSet enabledFeatures, - CommandManager.RegistrationEnvironment environment, int functionPermissionLevel, - Executor prepareExecutor, - Executor applyExecutor, CallbackInfoReturnable> cir) { - DynamicRegistryManager.Immutable dynamicRegistryManager = dynamicRegistries.getCombinedRegistryManager(); - TagUtil.registerWorldPresetTags(dynamicRegistryManager.getOrThrow(RegistryKeys.WORLD_PRESET)); - - Registry biomeRegistry = dynamicRegistryManager.getOrThrow(RegistryKeys.BIOME); - TagUtil.registerBiomeTags(biomeRegistry); - MinecraftUtil.registerFlora(biomeRegistry); - } -} 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 new file mode 100644 index 000000000..f98731561 --- /dev/null +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/lifecycle/ReloadableServerResourcesMixin.java @@ -0,0 +1,55 @@ +package com.dfsek.terra.mod.mixin.lifecycle; + +import net.minecraft.commands.Commands; +import net.minecraft.core.LayeredRegistryAccess; +import net.minecraft.core.Registry; +import net.minecraft.core.Registry.PendingTags; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.registries.Registries; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.ReloadableServerRegistries; +import net.minecraft.server.ReloadableServerResources; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.server.permissions.PermissionSet; +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.level.biome.Biome; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; + +import com.dfsek.terra.mod.util.MinecraftUtil; +import com.dfsek.terra.mod.util.TagUtil; + + +@Mixin(ReloadableServerResources.class) +public class ReloadableServerResourcesMixin { + @Shadow + @Final + private ReloadableServerRegistries.Holder fullRegistryHolder; + + /* + * #refresh populates all tags in the registries + */ + @Inject(method = "loadResources(Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/core/LayeredRegistryAccess;Ljava/util/List;Lnet/minecraft/world/flag/FeatureFlagSet;Lnet/minecraft/commands/Commands$CommandSelection;Lnet/minecraft/server/permissions/PermissionSet;Ljava/util/concurrent/Executor;Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletableFuture;", + at = @At("RETURN")) + private static void injectReload(ResourceManager resourceManager, + LayeredRegistryAccess dynamicRegistries, + List> pendingTagLoads, FeatureFlagSet enabledFeatures, + Commands.CommandSelection environment, PermissionSet functionPermissions, + Executor prepareExecutor, + Executor applyExecutor, CallbackInfoReturnable> cir) { + RegistryAccess.Frozen dynamicRegistryManager = dynamicRegistries.compositeAccess(); + TagUtil.registerWorldPresetTags(dynamicRegistryManager.lookupOrThrow(Registries.WORLD_PRESET)); + + 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/mixin_ifaces/FloraFeatureHolder.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin_ifaces/FloraFeatureHolder.java index 4e7c38dec..de3d89e2d 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin_ifaces/FloraFeatureHolder.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin_ifaces/FloraFeatureHolder.java @@ -1,6 +1,6 @@ package com.dfsek.terra.mod.mixin_ifaces; -import net.minecraft.world.gen.feature.ConfiguredFeature; +import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import java.util.List; 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 fc8304d09..1713da9d3 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,11 +1,11 @@ package com.dfsek.terra.mod.util; -import net.minecraft.registry.Registries; -import net.minecraft.util.Identifier; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.biome.Biome.Builder; -import net.minecraft.world.biome.BiomeEffects; -import net.minecraft.world.biome.GenerationSettings; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.Biome.BiomeBuilder; +import net.minecraft.world.level.biome.BiomeGenerationSettings; +import net.minecraft.world.level.biome.BiomeSpecialEffects; import java.util.HashMap; import java.util.List; @@ -23,81 +23,81 @@ public class BiomeUtil { TERRA_BIOME_MAP = new HashMap<>(); public static Biome createBiome(Biome vanilla, VanillaBiomeProperties vanillaBiomeProperties) { - BiomeEffects.Builder effects = new BiomeEffects.Builder(); + BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder(); - net.minecraft.world.biome.Biome.Builder builder = new Builder(); + net.minecraft.world.level.biome.Biome.BiomeBuilder builder = new BiomeBuilder(); effects.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor())) .waterFogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanilla.getWaterFogColor())) .fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor())) .skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor())) .grassColorModifier( - Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(), vanilla.getEffects().getGrassColorModifier())) + Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(), vanilla.getSpecialEffects().getGrassColorModifier())) .musicVolume(Objects.requireNonNullElse(vanillaBiomeProperties.getMusicVolume(), vanilla.getMusicVolume())); if(vanillaBiomeProperties.getGrassColor() == null) { - vanilla.getEffects().getGrassColor().ifPresent(effects::grassColor); + vanilla.getSpecialEffects().getGrassColor().ifPresent(effects::grassColorOverride); } else { - effects.grassColor(vanillaBiomeProperties.getGrassColor()); + effects.grassColorOverride(vanillaBiomeProperties.getGrassColor()); } if(vanillaBiomeProperties.getFoliageColor() == null) { - vanilla.getEffects().getFoliageColor().ifPresent(effects::foliageColor); + vanilla.getSpecialEffects().getFoliageColor().ifPresent(effects::foliageColorOverride); } else { - effects.foliageColor(vanillaBiomeProperties.getFoliageColor()); + effects.foliageColorOverride(vanillaBiomeProperties.getFoliageColor()); } if(vanillaBiomeProperties.getDryFoliageColor() == null) { - vanilla.getEffects().getDryFoliageColor().ifPresent(effects::dryFoliageColor); + vanilla.getSpecialEffects().getDryFoliageColor().ifPresent(effects::dryFoliageColorOverride); } else { - effects.dryFoliageColor(vanillaBiomeProperties.getDryFoliageColor()); + effects.dryFoliageColorOverride(vanillaBiomeProperties.getDryFoliageColor()); } if(vanillaBiomeProperties.getParticleConfig() == null) { - vanilla.getEffects().getParticleConfig().ifPresent(effects::particleConfig); + vanilla.getSpecialEffects().getParticleConfig().ifPresent(effects::particleConfig); } else { effects.particleConfig(vanillaBiomeProperties.getParticleConfig()); } if(vanillaBiomeProperties.getLoopSound() == null) { - vanilla.getEffects().getLoopSound().ifPresent(effects::loopSound); + vanilla.getSpecialEffects().getLoopSound().ifPresent(effects::loopSound); } else { - effects.loopSound(Registries.SOUND_EVENT.getEntry(vanillaBiomeProperties.getLoopSound())); + effects.loopSound(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(vanillaBiomeProperties.getLoopSound())); } if(vanillaBiomeProperties.getMoodSound() == null) { - vanilla.getEffects().getMoodSound().ifPresent(effects::moodSound); + vanilla.getSpecialEffects().getMoodSound().ifPresent(effects::moodSound); } else { effects.moodSound(vanillaBiomeProperties.getMoodSound()); } if(vanillaBiomeProperties.getAdditionsSound() == null) { - vanilla.getEffects().getAdditionsSound().ifPresent(effects::additionsSound); + vanilla.getSpecialEffects().getAdditionsSound().ifPresent(effects::additionsSound); } else { effects.additionsSound(vanillaBiomeProperties.getAdditionsSound()); } if(vanillaBiomeProperties.getMusic() == null) { - vanilla.getEffects().getMusic().ifPresent(effects::music); + vanilla.getSpecialEffects().getMusic().ifPresent(effects::music); } else { effects.music(vanillaBiomeProperties.getMusic()); } - builder.precipitation(Objects.requireNonNullElse(vanillaBiomeProperties.getPrecipitation(), vanilla.hasPrecipitation())); + builder.hasPrecipitation(Objects.requireNonNullElse(vanillaBiomeProperties.getPrecipitation(), vanilla.hasPrecipitation())); - builder.temperature(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperature(), vanilla.getTemperature())); + builder.temperature(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperature(), vanilla.getBaseTemperature())); builder.downfall(Objects.requireNonNullElse(vanillaBiomeProperties.getDownfall(), ((BiomeAccessor) ((Object) vanilla)).getWeather().downfall())); - builder.temperatureModifier(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperatureModifier(), + builder.temperatureAdjustment(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperatureModifier(), ((BiomeAccessor) ((Object) vanilla)).getWeather().temperatureModifier())); - builder.spawnSettings(Objects.requireNonNullElse(vanillaBiomeProperties.getSpawnSettings(), vanilla.getSpawnSettings())); + builder.mobSpawnSettings(Objects.requireNonNullElse(vanillaBiomeProperties.getSpawnSettings(), vanilla.getMobSettings())); return builder - .effects(effects.build()) - .generationSettings(new GenerationSettings.Builder().build()) + .specialEffects(effects.build()) + .generationSettings(new BiomeGenerationSettings.PlainBuilder().build()) .build(); } 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 index 2704d5f59..6f3c65747 100644 --- 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 @@ -1,9 +1,9 @@ package com.dfsek.terra.mod.util; -import net.minecraft.registry.RegistryKeys; -import net.minecraft.registry.tag.TagKey; -import net.minecraft.world.dimension.DimensionType; -import net.minecraft.world.dimension.DimensionType.MonsterSettings; +import net.minecraft.core.registries.Registries; +import net.minecraft.tags.TagKey; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.dimension.DimensionType.MonsterSettings; import org.jetbrains.annotations.NotNull; import java.util.OptionalLong; @@ -48,7 +48,7 @@ public class DimensionUtil { : vanillaWorldProperties.getLogicalHeight(), vanillaWorldProperties.getInfiniburn() == null ? defaultDimension.infiniburn() - : TagKey.of(RegistryKeys.BLOCK, vanillaWorldProperties.getInfiniburn()), + : TagKey.create(Registries.BLOCK, vanillaWorldProperties.getInfiniburn()), vanillaWorldProperties.getEffects() == null ? defaultDimension.effects() : vanillaWorldProperties.getEffects(), vanillaWorldProperties.getAmbientLight() == null ? defaultDimension.ambientLight() : vanillaWorldProperties.getAmbientLight(), vanillaWorldProperties.getCloudHeight() == null diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/MinecraftAdapter.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/MinecraftAdapter.java index cb6f5c52c..0f027f747 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/MinecraftAdapter.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/MinecraftAdapter.java @@ -18,9 +18,9 @@ package com.dfsek.terra.mod.util; import com.dfsek.seismic.type.vector.Vector3; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.random.Random; -import net.minecraft.world.HeightLimitView; +import net.minecraft.core.BlockPos; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.LevelHeightAccessor; import java.util.random.RandomGenerator; @@ -33,7 +33,7 @@ public final class MinecraftAdapter { return Vector3.of(pos.getX(), pos.getY(), pos.getZ()); } - public static WorldProperties adapt(HeightLimitView height, long seed) { + public static WorldProperties adapt(LevelHeightAccessor height, long seed) { return new WorldProperties() { @Override public long getSeed() { @@ -42,12 +42,12 @@ public final class MinecraftAdapter { @Override public int getMaxHeight() { - return height.getTopYInclusive(); + return height.getMaxY(); } @Override public int getMinHeight() { - return height.getBottomY(); + return height.getMinY(); } @Override @@ -57,7 +57,7 @@ public final class MinecraftAdapter { }; } - public static RandomGenerator adapt(Random random) { + public static RandomGenerator adapt(RandomSource random) { return new RandomGenerator() { @Override public boolean nextBoolean() { @@ -96,7 +96,7 @@ public final class MinecraftAdapter { @Override public int nextInt(int origin, int bound) { - return random.nextBetween(origin, bound); + return random.nextIntBetweenInclusive(origin, bound); } }; } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/MinecraftUtil.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/MinecraftUtil.java index 076745ce8..b3578335e 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/MinecraftUtil.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/MinecraftUtil.java @@ -1,29 +1,29 @@ package com.dfsek.terra.mod.util; -import net.minecraft.block.Block; -import net.minecraft.block.BlockEntityProvider; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.LootableContainerBlockEntity; -import net.minecraft.block.entity.MobSpawnerBlockEntity; -import net.minecraft.block.entity.SignBlockEntity; -import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.fluid.Fluid; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.registry.Registry; -import net.minecraft.registry.RegistryKey; -import net.minecraft.registry.RegistryKeys; -import net.minecraft.registry.entry.RegistryEntry; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.intprovider.IntProviderType; -import net.minecraft.world.World; -import net.minecraft.world.WorldAccess; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.dimension.DimensionType; -import net.minecraft.world.gen.feature.ConfiguredFeature; -import net.minecraft.world.tick.OrderedTick; -import net.minecraft.world.tick.TickScheduler; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.util.valueproviders.IntProviderType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.entity.RandomizableContainerBlockEntity; +import net.minecraft.world.level.block.entity.SignBlockEntity; +import net.minecraft.world.level.block.entity.SpawnerBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.ticks.ScheduledTick; +import net.minecraft.world.ticks.TickAccess; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -53,51 +53,51 @@ public final class MinecraftUtil { } - public static Optional> getEntry(Registry registry, Identifier identifier) { - return registry.getOptionalValue(identifier) - .flatMap(id -> Optional.ofNullable(registry.getEntry(id))); + public static Optional> getEntry(Registry registry, Identifier identifier) { + return registry.getOptional(identifier) + .flatMap(id -> Optional.ofNullable(registry.wrapAsHolder(id))); } - public static BlockEntity createBlockEntity(WorldAccess worldAccess, BlockPos pos) { - net.minecraft.block.entity.BlockEntity entity = worldAccess.getBlockEntity(pos); + public static BlockEntity createBlockEntity(LevelAccessor worldAccess, BlockPos pos) { + net.minecraft.world.level.block.entity.BlockEntity entity = worldAccess.getBlockEntity(pos); if(entity instanceof SignBlockEntity) { return (Sign) entity; - } else if(entity instanceof MobSpawnerBlockEntity) { + } else if(entity instanceof SpawnerBlockEntity) { return (MobSpawner) entity; - } else if(entity instanceof LootableContainerBlockEntity) { + } else if(entity instanceof RandomizableContainerBlockEntity) { return (Container) entity; } return null; } - public static void schedulePhysics(BlockState blockState, BlockPos blockPos, TickScheduler fluidScheduler, - TickScheduler blockScheduler) { - if(blockState.isLiquid()) { - fluidScheduler.scheduleTick(OrderedTick.create(blockState.getFluidState().getFluid(), blockPos)); + public static void schedulePhysics(BlockState blockState, BlockPos blockPos, TickAccess fluidScheduler, + TickAccess blockScheduler) { + if(blockState.liquid()) { + fluidScheduler.schedule(ScheduledTick.probe(blockState.getFluidState().getType(), blockPos)); } else { - blockScheduler.scheduleTick(OrderedTick.create(blockState.getBlock(), blockPos)); + blockScheduler.schedule(ScheduledTick.probe(blockState.getBlock(), blockPos)); } } public static boolean isCompatibleBlockStateExtended(com.dfsek.terra.api.block.state.BlockState blockState) { - return blockState.isExtended() && BlockStateArgument.class.isAssignableFrom(blockState.getClass()); + return blockState.isExtended() && BlockInput.class.isAssignableFrom(blockState.getClass()); } //[Vanilla Copy] - public static void loadBlockEntity(Chunk chunk, World world, BlockPos blockPos, BlockState state, NbtCompound nbt) { - net.minecraft.block.entity.BlockEntity blockEntity; - if("DUMMY".equals(nbt.getString("id", ""))) { + public static void loadBlockEntity(ChunkAccess chunk, Level world, BlockPos blockPos, BlockState state, CompoundTag nbt) { + net.minecraft.world.level.block.entity.BlockEntity blockEntity; + if("DUMMY".equals(nbt.getStringOr("id", ""))) { if(state.hasBlockEntity()) { - blockEntity = ((BlockEntityProvider) state.getBlock()).createBlockEntity(blockPos, state); + blockEntity = ((EntityBlock) state.getBlock()).newBlockEntity(blockPos, state); } else { blockEntity = null; } } else { - blockEntity = net.minecraft.block.entity.BlockEntity.createFromNbt(blockPos, state, nbt, world.getRegistryManager()); + blockEntity = net.minecraft.world.level.block.entity.BlockEntity.loadStatic(blockPos, state, nbt, world.registryAccess()); } if(blockEntity != null) { - blockEntity.setWorld(world); + blockEntity.setLevel(world); chunk.setBlockEntity(blockEntity); } } @@ -113,7 +113,7 @@ public final class MinecraftUtil { TerraIntProvider.TERRA_RANGE_TYPE_TO_INT_PROVIDER_TYPE.put(ConstantRange.class, CONSTANT); } - public static void registerFlora(Registry biomeRegistry) { + public static void registerFlora(Registry biomeRegistry) { logger.info("Injecting flora into Terra biomes..."); CommonPlatform.get().getConfigRegistry().forEach(pack -> { // Register all Terra biomes. PreLoadCompatibilityOptions compatibilityOptions = pack.getContext().get(PreLoadCompatibilityOptions.class); @@ -128,12 +128,12 @@ public final class MinecraftUtil { private static void registerFlora(com.dfsek.terra.api.world.biome.Biome biome, ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey id, - Registry biomeRegistry) { - RegistryKey vanillaKey = ((ProtoPlatformBiome) biome.getPlatformBiome()).get(biomeRegistry); - biomeRegistry.getOptionalValue(vanillaKey) + Registry biomeRegistry) { + ResourceKey vanillaKey = ((ProtoPlatformBiome) biome.getPlatformBiome()).get(biomeRegistry); + biomeRegistry.getOptional(vanillaKey) .ifPresentOrElse(vanillaBiome -> { - Identifier terraBiomeIdentifier = Identifier.of("terra", BiomeUtil.createBiomeID(pack, id)); - biomeRegistry.getOptionalValue(terraBiomeIdentifier).ifPresentOrElse( + Identifier terraBiomeIdentifier = Identifier.fromNamespaceAndPath("terra", BiomeUtil.createBiomeID(pack, id)); + biomeRegistry.getOptional(terraBiomeIdentifier).ifPresentOrElse( terraBiome -> { List> flowerFeatures = List.copyOf( vanillaBiome.getGenerationSettings() @@ -152,11 +152,11 @@ public final class MinecraftUtil { () -> logger.error("No vanilla biome: {}", vanillaKey)); } - public static RegistryKey registerBiomeKey(Identifier identifier) { - return RegistryKey.of(RegistryKeys.BIOME, identifier); + public static ResourceKey registerBiomeKey(Identifier identifier) { + return ResourceKey.create(Registries.BIOME, identifier); } - public static RegistryKey registerDimensionTypeKey(Identifier identifier) { - return RegistryKey.of(RegistryKeys.DIMENSION_TYPE, identifier); + public static ResourceKey registerDimensionTypeKey(Identifier identifier) { + return ResourceKey.create(Registries.DIMENSION_TYPE, identifier); } } 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 1db7ade81..9f1c064fa 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 @@ -1,22 +1,22 @@ package com.dfsek.terra.mod.util; -import net.minecraft.registry.Registry; -import net.minecraft.registry.RegistryKey; -import net.minecraft.registry.RegistryKeys; -import net.minecraft.registry.entry.RegistryEntry; -import net.minecraft.util.Identifier; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.biome.source.MultiNoiseBiomeSource; -import net.minecraft.world.biome.source.MultiNoiseBiomeSourceParameterList; -import net.minecraft.world.biome.source.MultiNoiseBiomeSourceParameterLists; -import net.minecraft.world.biome.source.TheEndBiomeSource; -import net.minecraft.world.dimension.DimensionOptions; -import net.minecraft.world.dimension.DimensionType; -import net.minecraft.world.dimension.DimensionTypes; -import net.minecraft.world.gen.WorldPreset; -import net.minecraft.world.gen.chunk.ChunkGenerator; -import net.minecraft.world.gen.chunk.ChunkGeneratorSettings; -import net.minecraft.world.gen.chunk.NoiseChunkGenerator; +import net.minecraft.core.Holder; +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.MultiNoiseBiomeSource; +import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterList; +import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterLists; +import net.minecraft.world.level.biome.TheEndBiomeSource; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.dimension.LevelStem; +import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; +import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; +import net.minecraft.world.level.levelgen.presets.WorldPreset; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,7 +43,7 @@ public class PresetUtil { public static Pair createDefault(ConfigPack pack, ModPlatform platform, boolean extended, boolean packInMetapack) { Registry dimensionTypeRegistry = platform.dimensionTypeRegistry(); - Registry chunkGeneratorSettingsRegistry = platform.chunkGeneratorSettingsRegistry(); + Registry chunkGeneratorSettingsRegistry = platform.chunkGeneratorSettingsRegistry(); Registry multiNoiseBiomeSourceParameterLists = platform.multiNoiseBiomeSourceParameterListRegistry(); @@ -54,7 +54,7 @@ public class PresetUtil { PRESETS.add(Pair.of(generatorID, extended)); - HashMap, DimensionOptions> dimensionMap = new HashMap<>(); + HashMap, LevelStem> dimensionMap = new HashMap<>(); insertCustom(platform, "minecraft:overworld", pack, dimensionTypeRegistry, chunkGeneratorSettingsRegistry, dimensionMap, packInMetapack); @@ -69,17 +69,17 @@ public class PresetUtil { public static Pair createMetaPackPreset(MetaPack metaPack, ModPlatform platform, boolean extended) { Registry dimensionTypeRegistry = platform.dimensionTypeRegistry(); - Registry chunkGeneratorSettingsRegistry = platform.chunkGeneratorSettingsRegistry(); + Registry chunkGeneratorSettingsRegistry = platform.chunkGeneratorSettingsRegistry(); Registry multiNoiseBiomeSourceParameterLists = platform.multiNoiseBiomeSourceParameterListRegistry(); - Identifier generatorID = Identifier.of("terra", + Identifier generatorID = Identifier.fromNamespaceAndPath("terra", metaPack.getID().toLowerCase(Locale.ROOT) + "/" + metaPack.getNamespace().toLowerCase( Locale.ROOT)); PRESETS.add(Pair.of(generatorID, extended)); - HashMap, DimensionOptions> dimensionMap = new HashMap<>(); + HashMap, LevelStem> dimensionMap = new HashMap<>(); metaPack.packs().forEach((key, pack) -> { insertCustom(platform, key, pack, dimensionTypeRegistry, chunkGeneratorSettingsRegistry, dimensionMap, false); @@ -94,9 +94,9 @@ public class PresetUtil { } private static void insertCustom(ModPlatform platform, String key, ConfigPack pack, Registry dimensionTypeRegistry, - Registry chunkGeneratorSettingsRegistry, - HashMap, DimensionOptions> dimensionMap, boolean packInMetapack) { - Identifier demensionIdentifier = Identifier.of(key); + Registry chunkGeneratorSettingsRegistry, + HashMap, LevelStem> dimensionMap, boolean packInMetapack) { + Identifier demensionIdentifier = Identifier.parse(key); VanillaWorldProperties vanillaWorldProperties; @@ -106,98 +106,98 @@ public class PresetUtil { vanillaWorldProperties = new VanillaWorldProperties(); } - DimensionType defaultDimension = dimensionTypeRegistry.get(Identifier.of(vanillaWorldProperties.getVanillaDimension())); + DimensionType defaultDimension = dimensionTypeRegistry.getValue(Identifier.parse(vanillaWorldProperties.getVanillaDimension())); assert defaultDimension != null; - Identifier dimensionTypeID = Identifier.of("terra", pack.getID().toLowerCase(Locale.ROOT)); + Identifier dimensionTypeID = Identifier.fromNamespaceAndPath("terra", pack.getID().toLowerCase(Locale.ROOT)); DimensionType dimensionType; if(!packInMetapack) { dimensionType = DimensionUtil.createDimension(vanillaWorldProperties, defaultDimension, platform); - RegistryKey dimensionTypeRegistryKey = MinecraftUtil.registerDimensionTypeKey( + ResourceKey dimensionTypeRegistryKey = MinecraftUtil.registerDimensionTypeKey( dimensionTypeID); - Registry.registerReference(dimensionTypeRegistry, dimensionTypeRegistryKey, dimensionType); + Registry.registerForHolder(dimensionTypeRegistry, dimensionTypeRegistryKey, dimensionType); } else { - dimensionType = dimensionTypeRegistry.get(dimensionTypeID); + dimensionType = dimensionTypeRegistry.getValue(dimensionTypeID); } - RegistryEntry dimensionTypeRegistryEntry = dimensionTypeRegistry.getEntry(dimensionType); + Holder dimensionTypeRegistryEntry = dimensionTypeRegistry.wrapAsHolder(dimensionType); TerraBiomeSource biomeSource = new TerraBiomeSource(pack); - RegistryEntry defaultGeneratorSettings = chunkGeneratorSettingsRegistry.getEntry( - chunkGeneratorSettingsRegistry.get(Identifier.of(vanillaWorldProperties.getVanillaGeneration()))); + Holder defaultGeneratorSettings = chunkGeneratorSettingsRegistry.wrapAsHolder( + chunkGeneratorSettingsRegistry.getValue(Identifier.parse(vanillaWorldProperties.getVanillaGeneration()))); GenerationSettings generatorSettings = new GenerationSettings( vanillaWorldProperties.getHeight() == null ? new ConstantRange( - defaultGeneratorSettings.value().generationShapeConfig().minimumY(), - defaultGeneratorSettings.value().generationShapeConfig().height()) : vanillaWorldProperties.getHeight(), + defaultGeneratorSettings.value().noiseSettings().minY(), + defaultGeneratorSettings.value().noiseSettings().height()) : vanillaWorldProperties.getHeight(), vanillaWorldProperties.getSealevel() == null ? defaultGeneratorSettings.value().seaLevel() : vanillaWorldProperties.getSealevel(), vanillaWorldProperties.getMobGeneration() == null - ? !defaultGeneratorSettings.value().mobGenerationDisabled() + ? !defaultGeneratorSettings.value().disableMobGeneration() : vanillaWorldProperties.getMobGeneration(), vanillaWorldProperties.getSpawnHeight()); ChunkGenerator generator = new MinecraftChunkGeneratorWrapper(biomeSource, pack, generatorSettings); - DimensionOptions dimensionOptions = new DimensionOptions(dimensionTypeRegistryEntry, generator); - RegistryKey dimensionOptionsRegistryKey = RegistryKey.of(RegistryKeys.DIMENSION, demensionIdentifier); + LevelStem dimensionOptions = new LevelStem(dimensionTypeRegistryEntry, generator); + ResourceKey dimensionOptionsRegistryKey = ResourceKey.create(Registries.LEVEL_STEM, demensionIdentifier); dimensionMap.put(dimensionOptionsRegistryKey, dimensionOptions); } private static void insertDefaults(Registry dimensionTypeRegistry, - Registry chunkGeneratorSettingsRegistry, + Registry chunkGeneratorSettingsRegistry, Registry multiNoiseBiomeSourceParameterLists, - Registry biomeRegistry, HashMap, DimensionOptions> map) { - if(!map.containsKey(DimensionOptions.OVERWORLD)) { - RegistryEntry overworldDimensionType = dimensionTypeRegistry.getEntry( - dimensionTypeRegistry.get(DimensionTypes.OVERWORLD)); + Registry biomeRegistry, HashMap, LevelStem> map) { + if(!map.containsKey(LevelStem.OVERWORLD)) { + Holder overworldDimensionType = dimensionTypeRegistry.wrapAsHolder( + dimensionTypeRegistry.getValue(BuiltinDimensionTypes.OVERWORLD)); - RegistryEntry overworldChunkBiomeReference = - multiNoiseBiomeSourceParameterLists.getEntry(multiNoiseBiomeSourceParameterLists.get( + Holder overworldChunkBiomeReference = + multiNoiseBiomeSourceParameterLists.wrapAsHolder(multiNoiseBiomeSourceParameterLists.getValue( MultiNoiseBiomeSourceParameterLists.OVERWORLD)); - RegistryEntry overworldChunkGeneratorSettings = chunkGeneratorSettingsRegistry.getEntry( - chunkGeneratorSettingsRegistry.get( - ChunkGeneratorSettings.OVERWORLD)); + Holder overworldChunkGeneratorSettings = chunkGeneratorSettingsRegistry.wrapAsHolder( + chunkGeneratorSettingsRegistry.getValue( + NoiseGeneratorSettings.OVERWORLD)); - DimensionOptions overworldDimensionOptions = new DimensionOptions(overworldDimensionType, - (new NoiseChunkGenerator(MultiNoiseBiomeSource.create(overworldChunkBiomeReference), overworldChunkGeneratorSettings))); - map.put(DimensionOptions.OVERWORLD, overworldDimensionOptions); + LevelStem overworldDimensionOptions = new LevelStem(overworldDimensionType, + (new NoiseBasedChunkGenerator(MultiNoiseBiomeSource.createFromPreset(overworldChunkBiomeReference), overworldChunkGeneratorSettings))); + map.put(LevelStem.OVERWORLD, overworldDimensionOptions); } - if(!map.containsKey(DimensionOptions.NETHER)) { - RegistryEntry netherDimensionType = dimensionTypeRegistry.getEntry( - dimensionTypeRegistry.get(DimensionTypes.THE_NETHER)); + if(!map.containsKey(LevelStem.NETHER)) { + Holder netherDimensionType = dimensionTypeRegistry.wrapAsHolder( + dimensionTypeRegistry.getValue(BuiltinDimensionTypes.NETHER)); - RegistryEntry netherChunkBiomeReference = - multiNoiseBiomeSourceParameterLists.getEntry(multiNoiseBiomeSourceParameterLists.get( + Holder netherChunkBiomeReference = + multiNoiseBiomeSourceParameterLists.wrapAsHolder(multiNoiseBiomeSourceParameterLists.getValue( MultiNoiseBiomeSourceParameterLists.NETHER)); - RegistryEntry netherChunkGeneratorSettings = chunkGeneratorSettingsRegistry.getEntry( - chunkGeneratorSettingsRegistry.get( - ChunkGeneratorSettings.NETHER)); + Holder netherChunkGeneratorSettings = chunkGeneratorSettingsRegistry.wrapAsHolder( + chunkGeneratorSettingsRegistry.getValue( + NoiseGeneratorSettings.NETHER)); - DimensionOptions overworldDimensionOptions = new DimensionOptions(netherDimensionType, - (new NoiseChunkGenerator(MultiNoiseBiomeSource.create(netherChunkBiomeReference), netherChunkGeneratorSettings))); - map.put(DimensionOptions.NETHER, overworldDimensionOptions); + LevelStem overworldDimensionOptions = new LevelStem(netherDimensionType, + (new NoiseBasedChunkGenerator(MultiNoiseBiomeSource.createFromPreset(netherChunkBiomeReference), netherChunkGeneratorSettings))); + map.put(LevelStem.NETHER, overworldDimensionOptions); } - if(!map.containsKey(DimensionOptions.END)) { - RegistryEntry endDimensionType = dimensionTypeRegistry.getEntry( - dimensionTypeRegistry.get(DimensionTypes.THE_END)); + if(!map.containsKey(LevelStem.END)) { + Holder endDimensionType = dimensionTypeRegistry.wrapAsHolder( + dimensionTypeRegistry.getValue(BuiltinDimensionTypes.END)); - RegistryEntry endChunkGeneratorSettings = chunkGeneratorSettingsRegistry.getEntry( - chunkGeneratorSettingsRegistry.get( - ChunkGeneratorSettings.END)); + Holder endChunkGeneratorSettings = chunkGeneratorSettingsRegistry.wrapAsHolder( + chunkGeneratorSettingsRegistry.getValue( + NoiseGeneratorSettings.END)); - DimensionOptions overworldDimensionOptions = new DimensionOptions(endDimensionType, - (new NoiseChunkGenerator(TheEndBiomeSource.createVanilla(biomeRegistry), endChunkGeneratorSettings))); - map.put(DimensionOptions.END, overworldDimensionOptions); + LevelStem overworldDimensionOptions = new LevelStem(endDimensionType, + (new NoiseBasedChunkGenerator(TheEndBiomeSource.create(biomeRegistry), endChunkGeneratorSettings))); + map.put(LevelStem.END, overworldDimensionOptions); } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/SeedHack.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/SeedHack.java index 0979b346f..d2b92af44 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/SeedHack.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/SeedHack.java @@ -2,7 +2,7 @@ package com.dfsek.terra.mod.util; import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; -import net.minecraft.world.biome.source.util.MultiNoiseUtil.MultiNoiseSampler; +import net.minecraft.world.level.biome.Climate.Sampler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -13,16 +13,16 @@ import org.slf4j.LoggerFactory; public class SeedHack { private static final Logger LOGGER = LoggerFactory.getLogger(SeedHack.class); - private static final Object2LongMap seedMap = new Object2LongOpenHashMap<>(); + private static final Object2LongMap seedMap = new Object2LongOpenHashMap<>(); - public static long getSeed(MultiNoiseSampler sampler) { + public static long getSeed(Sampler sampler) { if(!seedMap.containsKey(sampler)) { throw new IllegalArgumentException("Sampler is not registered: " + sampler); } return seedMap.getLong(sampler); } - public static void register(MultiNoiseSampler sampler, long seed) { + public static void register(Sampler sampler, long seed) { LOGGER.info("Registered seed {} to sampler {}", seed, sampler.hashCode()); seedMap.put(sampler, seed); } 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 9e23a9662..0716d2b89 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 @@ -1,12 +1,12 @@ package com.dfsek.terra.mod.util; -import net.minecraft.registry.Registry; -import net.minecraft.registry.entry.RegistryEntry; -import net.minecraft.registry.tag.TagGroupLoader.RegistryTags; -import net.minecraft.registry.tag.TagKey; -import net.minecraft.registry.tag.WorldPresetTags; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.gen.WorldPreset; +import net.minecraft.core.Holder; +import net.minecraft.core.Registry; +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 org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -24,15 +24,15 @@ public final class TagUtil { } - private static Map, List>> tagsToMutableMap(Registry registry) { - return registry.streamTags().collect(HashMap::new, - (map, tag) -> map.put(tag.getTag(), tag.stream().collect(Collectors.toList())), + private static Map, List>> tagsToMutableMap(Registry registry) { + return registry.getTags().collect(HashMap::new, + (map, tag) -> map.put(tag.key(), tag.stream().collect(Collectors.toList())), HashMap::putAll); } public static void registerWorldPresetTags(Registry registry) { logger.info("Registering Preset Tags."); - Map, List>> collect = tagsToMutableMap(registry); + Map, List>> collect = tagsToMutableMap(registry); PresetUtil .getPresets() @@ -47,20 +47,20 @@ public final class TagUtil { }, () -> logger.error("Preset {} does not exist!", pair.getLeft()))); - registry.startTagReload(new RegistryTags<>(registry.getKey(), collect)).apply(); + registry.prepareTagReload(new LoadResult<>(registry.key(), collect)).apply(); if(logger.isDebugEnabled()) { - registry.streamEntries() - .map(e -> e.registryKey().getValue() + ": " + - e.streamTags().reduce("", (s, t) -> t.id() + ", " + s, String::concat)) + registry.listElements() + .map(e -> e.key().identifier() + ": " + + e.tags().reduce("", (s, t) -> t.location() + ", " + s, String::concat)) .forEach(logger::debug); } } public static void registerBiomeTags(Registry registry) { logger.info("Doing biome tag garbage...."); - Map, List>> collect = tagsToMutableMap(registry); + Map, List>> collect = tagsToMutableMap(registry); BiomeUtil .getTerraBiomeMap() @@ -74,18 +74,18 @@ public final class TagUtil { .ifPresentOrElse( terra -> { logger.debug( - vanilla.getKey() + vanilla.unwrapKey() .orElseThrow() - .getValue() + + .identifier() + " (vanilla for " + - terra.getKey() + terra.unwrapKey() .orElseThrow() - .getValue() + + .identifier() + ": " + - vanilla.streamTags() + vanilla.tags() .toList()); - vanilla.streamTags() + vanilla.tags() .forEach( tag -> collect .computeIfAbsent( @@ -98,12 +98,12 @@ public final class TagUtil { tb))), () -> logger.error("No vanilla biome: {}", vb))); - registry.startTagReload(new RegistryTags<>(registry.getKey(), collect)).apply(); + registry.prepareTagReload(new LoadResult<>(registry.key(), collect)).apply(); if(logger.isDebugEnabled()) { - registry.streamEntries() - .map(e -> e.registryKey().getValue() + ": " + - e.streamTags().reduce("", (s, t) -> t.id() + ", " + s, String::concat)) + registry.listElements() + .map(e -> e.key().identifier() + ": " + + e.tags().reduce("", (s, t) -> t.location() + ", " + s, String::concat)) .forEach(logger::debug); } } diff --git a/platforms/mixin-common/src/main/resources/terra.accesswidener b/platforms/mixin-common/src/main/resources/terra.accesswidener index 1d7159070..2bb5b5b48 100644 --- a/platforms/mixin-common/src/main/resources/terra.accesswidener +++ b/platforms/mixin-common/src/main/resources/terra.accesswidener @@ -1,7 +1,7 @@ -accessWidener v1 named -accessible class net/minecraft/world/biome/Biome$Weather -accessible class net/minecraft/world/gen/WorldPresets$Registrar -accessible field net/minecraft/world/dimension/DimensionOptionsRegistryHolder VANILLA_KEYS Ljava/util/Set; -accessible class net/minecraft/registry/RegistryLoader$Loader -extendable class net/minecraft/nbt/NbtElement -accessible field net/minecraft/block/entity/BlockEntity TYPE_CODEC Lcom/mojang/serialization/Codec; \ No newline at end of file +accessWidener v1 named +accessible class net/minecraft/world/level/biome/Biome$ClimateSettings +accessible class net/minecraft/world/level/levelgen/presets/WorldPresets$Bootstrap +accessible field net/minecraft/world/level/levelgen/WorldDimensions BUILTIN_ORDER Ljava/util/Set; +accessible class net/minecraft/resources/RegistryDataLoader$Loader +extendable class net/minecraft/nbt/Tag +accessible field net/minecraft/world/level/block/entity/BlockEntity TYPE_CODEC Lcom/mojang/serialization/Codec; 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 f1d2c5a3f..29ae1d827 100644 --- a/platforms/mixin-common/src/main/resources/terra.common.mixins.json +++ b/platforms/mixin-common/src/main/resources/terra.common.mixins.json @@ -5,42 +5,42 @@ "compatibilityLevel": "JAVA_21", "mixins": [ "access.BiomeAccessor", - "access.MobSpawnerLogicAccessor", - "access.StateAccessor", - "access.StructureAccessorAccessor", + "access.BaseSpawnerAccessor", + "access.StateHolderAccessor", + "access.StructureManagerAccessor", "access.VillagerTypeAccessor", - "access.WorldChunkAccessor", - "generalize.ServerWorldMixin", - "implementations.compat.GenerationSettingsFloraFeaturesMixin", + "access.LevelChunkAccessor", + "generalize.ServerLevelMixin", + "implementations.compat.BiomeGenerationSettingsFloraFeaturesMixin", "implementations.terra.BiomeMixin", "implementations.terra.HandleImplementationMixin", "implementations.terra.block.BlockMixin", "implementations.terra.block.entity.BlockEntityMixin", - "implementations.terra.block.entity.LootableContainerBlockEntityMixin", - "implementations.terra.block.entity.MobSpawnerBlockEntityMixin", + "implementations.terra.block.entity.RandomizableContainerBlockEntityMixin", + "implementations.terra.block.entity.SpawnerBlockEntityMixin", "implementations.terra.block.entity.SignBlockEntityMixin", - "implementations.terra.block.state.BlockStateArgumentMixin", - "implementations.terra.block.state.BlockStateMixin", + "implementations.terra.block.state.BlockInputMixin", + "implementations.terra.block.state.BlockStateBaseMixin", "implementations.terra.block.state.PropertyMixin", - "implementations.terra.chunk.ChunkRegionMixin", - "implementations.terra.chunk.WorldChunkMixin", + "implementations.terra.chunk.WorldGenRegionMixin", + "implementations.terra.chunk.LevelChunkMixin", "implementations.terra.chunk.data.ProtoChunkMixin", "implementations.terra.entity.EntityMixin", "implementations.terra.entity.EntityTypeMixin", - "implementations.terra.entity.PlayerEntityMixin", - "implementations.terra.entity.ServerCommandSourceMixin", - "implementations.terra.inventory.LockableContainerBlockEntityMixin", + "implementations.terra.entity.PlayerMixin", + "implementations.terra.entity.CommandSourceStackMixin", + "implementations.terra.inventory.BaseContainerBlockEntityMixin", "implementations.terra.inventory.item.ItemMixin", "implementations.terra.inventory.item.ItemStackMixin", "implementations.terra.inventory.meta.EnchantmentMixin", "implementations.terra.inventory.meta.ItemStackDamageableMixin", "implementations.terra.inventory.meta.ItemStackMetaMixin", - "implementations.terra.nbt.NbtCompoundMixin", - "implementations.terra.world.ChunkRegionMixin", - "implementations.terra.world.ServerWorldMixin", + "implementations.terra.nbt.CompoundTagMixin", + "implementations.terra.world.WorldGenRegionMixin", + "implementations.terra.world.ServerLevelMixin", "invoke.BiomeInvoker", - "invoke.FluidBlockInvoker", - "lifecycle.DataPackContentsMixin" + "invoke.LiquidBlockInvoker", + "lifecycle.ReloadableServerResourcesMixin" ], "client": [ ], diff --git a/platforms/mixin-lifecycle/build.gradle.kts b/platforms/mixin-lifecycle/build.gradle.kts index 2663caf2f..39dc6367b 100644 --- a/platforms/mixin-lifecycle/build.gradle.kts +++ b/platforms/mixin-lifecycle/build.gradle.kts @@ -14,7 +14,7 @@ dependencies { implementation(project(path = ":platforms:mixin-common", configuration = "namedElements")) { isTransitive = false } minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") - mappings("net.fabricmc:yarn:${Versions.Mod.yarn}:v2") + mappings(loom.officialMojangMappings()) modImplementation("org.incendo", "cloud-fabric", Versions.Fabric.cloud) { exclude("net.fabricmc") diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/LifecycleEntryPoint.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/LifecycleEntryPoint.java index ed6bc7db8..669d9c652 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/LifecycleEntryPoint.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/LifecycleEntryPoint.java @@ -1,6 +1,6 @@ package com.dfsek.terra.lifecycle; -import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.commands.CommandSourceStack; import org.incendo.cloud.SenderMapper; import org.incendo.cloud.execution.ExecutionCoordinator; import org.incendo.cloud.fabric.FabricServerCommandManager; @@ -21,7 +21,7 @@ public final class LifecycleEntryPoint { ExecutionCoordinator.asyncCoordinator(), SenderMapper.create( serverCommandSource -> (CommandSender) serverCommandSource, - commandSender -> (ServerCommandSource) commandSender) + commandSender -> (CommandSourceStack) commandSender) ); 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 5f9d6a651..2270c60a2 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 @@ -4,15 +4,15 @@ import ca.solostudios.strata.Versions; import ca.solostudios.strata.parser.tokenizer.ParseException; import ca.solostudios.strata.version.Version; import net.minecraft.SharedConstants; -import net.minecraft.enchantment.Enchantment; -import net.minecraft.registry.DynamicRegistryManager; -import net.minecraft.registry.Registry; -import net.minecraft.registry.RegistryKeys; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.registries.Registries; import net.minecraft.server.MinecraftServer; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.biome.source.MultiNoiseBiomeSourceParameterList; -import net.minecraft.world.dimension.DimensionType; -import net.minecraft.world.gen.chunk.ChunkGeneratorSettings; +import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterList; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,10 +34,10 @@ public abstract class LifecyclePlatform extends ModPlatform { private static final Logger LOGGER = LoggerFactory.getLogger(LifecyclePlatform.class); private static final AtomicReference> BIOMES = new AtomicReference<>(); private static final AtomicReference> DIMENSIONS = new AtomicReference<>(); - private static final AtomicReference> SETTINGS = new AtomicReference<>(); + private static final AtomicReference> SETTINGS = new AtomicReference<>(); private static final AtomicReference> NOISE = new AtomicReference<>(); private static final AtomicReference> ENCHANTMENT = new AtomicReference<>(); - private static final AtomicReference DYNAMIC_REGISTRY_MANAGER = new AtomicReference<>(); + private static final AtomicReference DYNAMIC_REGISTRY_MANAGER = new AtomicReference<>(); private static MinecraftServer server; private int generationThreads; @@ -56,7 +56,7 @@ public abstract class LifecyclePlatform extends ModPlatform { public static void setRegistries(Registry biomeRegistry, Registry dimensionTypeRegistry, - Registry chunkGeneratorSettingsRegistry, + Registry chunkGeneratorSettingsRegistry, Registry multiNoiseBiomeSourceParameterListRegistry, Registry enchantmentRegistry) { BIOMES.set(biomeRegistry); @@ -66,7 +66,7 @@ public abstract class LifecyclePlatform extends ModPlatform { ENCHANTMENT.set(enchantmentRegistry); } - public static void setDynamicRegistryManager(DynamicRegistryManager.Immutable dynamicRegistryManager) { + public static void setDynamicRegistryManager(RegistryAccess.Frozen dynamicRegistryManager) { DYNAMIC_REGISTRY_MANAGER.set(dynamicRegistryManager); } @@ -85,13 +85,13 @@ public abstract class LifecyclePlatform extends ModPlatform { boolean succeed = loadConfigPacks(); if(server != null) { - LifecycleBiomeUtil.registerBiomes(server.getRegistryManager().getOrThrow(RegistryKeys.BIOME)); - server.reloadResources(server.getDataPackManager().getEnabledIds()).exceptionally(throwable -> { + 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.getWorlds().forEach(world -> { - if(world.getChunkManager().getChunkGenerator() instanceof MinecraftChunkGeneratorWrapper chunkGeneratorWrapper) { + 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); @@ -108,7 +108,7 @@ public abstract class LifecyclePlatform extends ModPlatform { super.platformAddon().forEach(addons::add); - String mcVersion = SharedConstants.getGameVersion().name(); + String mcVersion = SharedConstants.getCurrentVersion().name(); try { addons.add(new EphemeralAddon(Versions.parseVersion(mcVersion), "minecraft")); } catch(ParseException e) { @@ -149,7 +149,7 @@ public abstract class LifecyclePlatform extends ModPlatform { } @Override - public Registry chunkGeneratorSettingsRegistry() { + public Registry chunkGeneratorSettingsRegistry() { return SETTINGS.get(); } diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RegistryMixin.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/BuiltInRegistriesMixin.java similarity index 78% rename from platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RegistryMixin.java rename to platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/BuiltInRegistriesMixin.java index ce4e4bfe0..30944f8d7 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RegistryMixin.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/BuiltInRegistriesMixin.java @@ -1,6 +1,6 @@ package com.dfsek.terra.lifecycle.mixin; -import net.minecraft.registry.Registries; +import net.minecraft.core.registries.BuiltInRegistries; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -9,8 +9,8 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import com.dfsek.terra.lifecycle.util.RegistryUtil; -@Mixin(Registries.class) -public class RegistryMixin { +@Mixin(BuiltInRegistries.class) +public class BuiltInRegistriesMixin { @Inject(method = "", at = @At("RETURN")) private static void registerTerraGenerators(CallbackInfo ci) { RegistryUtil.register(); diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RegistryEntryReferenceInvoker.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/HolderReferenceInvoker.java similarity index 58% rename from platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RegistryEntryReferenceInvoker.java rename to platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/HolderReferenceInvoker.java index d84b643cb..990cb73f5 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RegistryEntryReferenceInvoker.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/HolderReferenceInvoker.java @@ -1,13 +1,13 @@ package com.dfsek.terra.lifecycle.mixin; -import net.minecraft.registry.entry.RegistryEntry.Reference; +import net.minecraft.core.Holder.Reference; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(Reference.class) -public interface RegistryEntryReferenceInvoker { - @Invoker("setValue") +public interface HolderReferenceInvoker { + @Invoker("bindValue") void invokeSetValue(T value); } diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/SimpleRegistryMixin.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/MappedRegistryMixin.java similarity index 50% rename from platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/SimpleRegistryMixin.java rename to platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/MappedRegistryMixin.java index 27f28700c..c44c2efa0 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/SimpleRegistryMixin.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/MappedRegistryMixin.java @@ -1,7 +1,7 @@ package com.dfsek.terra.lifecycle.mixin; -import net.minecraft.registry.SimpleRegistry; -import net.minecraft.registry.entry.RegistryEntry.Reference; +import net.minecraft.core.Holder.Reference; +import net.minecraft.core.MappedRegistry; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -11,17 +11,17 @@ import java.util.Map; import com.dfsek.terra.lifecycle.util.RegistryHack; -@Mixin(SimpleRegistry.class) -public class SimpleRegistryMixin implements RegistryHack { +@Mixin(MappedRegistry.class) +public class MappedRegistryMixin implements RegistryHack { @Shadow @Final - private Map> valueToEntry; + private Map> byValue; @Override public void terra_bind() { - valueToEntry.forEach((value, entry) -> { + byValue.forEach((value, entry) -> { //noinspection unchecked - ((RegistryEntryReferenceInvoker) entry).invokeSetValue(value); + ((HolderReferenceInvoker) entry).invokeSetValue(value); }); } } diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/NoiseConfigMixin.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/NoiseConfigMixin.java deleted file mode 100644 index 47fe9a9ca..000000000 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/NoiseConfigMixin.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.dfsek.terra.lifecycle.mixin; - -import net.minecraft.registry.RegistryEntryLookup; -import net.minecraft.util.math.noise.DoublePerlinNoiseSampler; -import net.minecraft.world.biome.source.util.MultiNoiseUtil.MultiNoiseSampler; -import net.minecraft.world.gen.chunk.ChunkGeneratorSettings; -import net.minecraft.world.gen.noise.NoiseConfig; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import com.dfsek.terra.mod.util.SeedHack; - - -/** - * Hack to map noise sampler to seeds - */ -@Mixin(NoiseConfig.class) -public class NoiseConfigMixin { - @Shadow - @Final - private MultiNoiseSampler multiNoiseSampler; - - @Inject(method = "(Lnet/minecraft/world/gen/chunk/ChunkGeneratorSettings;Lnet/minecraft/registry/RegistryEntryLookup;J)V", - at = @At("TAIL")) - private void mapMultiNoise(ChunkGeneratorSettings chunkGeneratorSettings, - RegistryEntryLookup noiseParametersLookup, long seed, - CallbackInfo ci) { - SeedHack.register(multiNoiseSampler, seed); - } -} diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RandomStateMixin.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RandomStateMixin.java new file mode 100644 index 000000000..a7c5668ff --- /dev/null +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RandomStateMixin.java @@ -0,0 +1,34 @@ +package com.dfsek.terra.lifecycle.mixin; + +import net.minecraft.core.HolderGetter; +import net.minecraft.world.level.biome.Climate.Sampler; +import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; +import net.minecraft.world.level.levelgen.RandomState; +import net.minecraft.world.level.levelgen.synth.NormalNoise; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.dfsek.terra.mod.util.SeedHack; + + +/** + * Hack to map noise sampler to seeds + */ +@Mixin(RandomState.class) +public class RandomStateMixin { + @Shadow + @Final + private Sampler sampler; + + @Inject(method = "(Lnet/minecraft/world/level/levelgen/NoiseGeneratorSettings;Lnet/minecraft/core/HolderGetter;J)V", + at = @At("TAIL")) + private void mapMultiNoise(NoiseGeneratorSettings chunkGeneratorSettings, + HolderGetter noiseParametersLookup, long seed, + CallbackInfo ci) { + SeedHack.register(sampler, seed); + } +} diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/MinecraftServerMixin.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/MinecraftServerMixin.java index 9cde600c3..c6c07bdbc 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/MinecraftServerMixin.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/MinecraftServerMixin.java @@ -1,12 +1,12 @@ package com.dfsek.terra.lifecycle.mixin.lifecycle; import com.mojang.datafixers.DataFixer; -import net.minecraft.resource.ResourcePackManager; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.SaveLoader; -import net.minecraft.util.ApiServices; -import net.minecraft.world.chunk.ChunkLoadProgress; -import net.minecraft.world.level.storage.LevelStorage; +import net.minecraft.server.Services; +import net.minecraft.server.WorldStem; +import net.minecraft.server.level.progress.LevelLoadListener; +import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.world.level.storage.LevelStorageSource; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -19,14 +19,11 @@ import com.dfsek.terra.lifecycle.LifecyclePlatform; @Mixin(MinecraftServer.class) public class MinecraftServerMixin { - @Inject(method = "(Ljava/lang/Thread;Lnet/minecraft/world/level/storage/LevelStorage$Session;" + - "Lnet/minecraft/resource/ResourcePackManager;Lnet/minecraft/server/SaveLoader;Ljava/net/Proxy;" + - "Lcom/mojang/datafixers/DataFixer;Lnet/minecraft/util/ApiServices;" + - "Lnet/minecraft/world/chunk/ChunkLoadProgress;)V", + @Inject(method = "(Ljava/lang/Thread;Lnet/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess;Lnet/minecraft/server/packs/repository/PackRepository;Lnet/minecraft/server/WorldStem;Ljava/net/Proxy;Lcom/mojang/datafixers/DataFixer;Lnet/minecraft/server/Services;Lnet/minecraft/server/level/progress/LevelLoadListener;)V", at = @At("RETURN")) - private void injectConstructor(Thread serverThread, LevelStorage.Session session, ResourcePackManager dataPackManager, - SaveLoader saveLoader, Proxy proxy, DataFixer dataFixer, ApiServices apiServices, - ChunkLoadProgress chunkLoadProgress, CallbackInfo ci) { + private void injectConstructor(Thread serverThread, LevelStorageSource.LevelStorageAccess session, PackRepository dataPackManager, + WorldStem saveLoader, Proxy proxy, DataFixer dataFixer, Services apiServices, + LevelLoadListener chunkLoadProgress, CallbackInfo ci) { LifecyclePlatform.setServer((MinecraftServer) (Object) this); } } 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 new file mode 100644 index 000000000..625aa2c76 --- /dev/null +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/RegistryDataLoaderMixin.java @@ -0,0 +1,103 @@ +package com.dfsek.terra.lifecycle.mixin.lifecycle; + +import com.llamalad7.mixinextras.sugar.Local; +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.ResourceKey; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.level.biome.Biome; +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 org.slf4j.Logger; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Coerce; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; + +import com.dfsek.terra.lifecycle.LifecyclePlatform; +import com.dfsek.terra.lifecycle.util.LifecycleUtil; +import com.dfsek.terra.lifecycle.util.RegistryHack; +import com.dfsek.terra.mod.CommonPlatform; +import com.dfsek.terra.mod.ModPlatform; + + +@Mixin(RegistryDataLoader.class) +public class RegistryDataLoaderMixin { + + @Unique + private static final AtomicBoolean LOADING_DYNAMIC_REGISTRIES = new AtomicBoolean(false); + @Shadow + @Final + private static Logger LOGGER; + + @Inject(method = "load(Lnet/minecraft/server/packs/resources/ResourceManager;Ljava/util/List;Ljava/util/List;)Lnet/minecraft/core/RegistryAccess$Frozen;", + at = @At("HEAD")) + private static void loadFromResources(ResourceManager resourceManager, List> registries, + List> entries, + CallbackInfoReturnable cir) { + LOADING_DYNAMIC_REGISTRIES.set(entries.stream().anyMatch(entry -> entry.key() == Registries.BIOME)); + } + + @Inject( + method = "load(Lnet/minecraft/resources/RegistryDataLoader$LoadingFunction;Ljava/util/List;Ljava/util/List;)" + + "Lnet/minecraft/core/RegistryAccess$Frozen;", + at = @At( + value = "INVOKE", + target = "Ljava/util/List;forEach(Ljava/util/function/Consumer;)V", + ordinal = 1 + ) + ) + private static void beforeFreeze(@Coerce Object loadable, List> wrappers, List> entries, + CallbackInfoReturnable cir, + @Local(ordinal = 2) List> registriesList) { + if(LOADING_DYNAMIC_REGISTRIES.getAndSet(false)) { + ModPlatform platform = CommonPlatform.get(); + platform.getRawConfigRegistry().clear(); + WritableRegistry biomes = extractRegistry(registriesList, Registries.BIOME).orElseThrow(); + WritableRegistry dimensionTypes = extractRegistry(registriesList, Registries.DIMENSION_TYPE).orElseThrow(); + WritableRegistry worldPresets = extractRegistry(registriesList, Registries.WORLD_PRESET).orElseThrow(); + WritableRegistry chunkGeneratorSettings = extractRegistry(registriesList, + Registries.NOISE_SETTINGS).orElseThrow(); + WritableRegistry multiNoiseBiomeSourceParameterLists = extractRegistry(registriesList, + Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST).orElseThrow(); + WritableRegistry enchantments = extractRegistry(registriesList, Registries.ENCHANTMENT).orElseThrow(); + + LifecyclePlatform.setRegistries(biomes, dimensionTypes, chunkGeneratorSettings, multiNoiseBiomeSourceParameterLists, + enchantments); + LifecycleUtil.initialize(biomes, worldPresets); + } + } + + @Unique + @SuppressWarnings("unchecked") + private static Optional> extractRegistry(List> instance, + ResourceKey> key) { + List> matches = instance + .stream().map(RegistryDataLoader.Loader::registry) + .filter(r -> r.key().equals(key)) + .toList(); + if(matches.size() > 1) { + throw new IllegalStateException("Illegal number of registries returned: " + matches); + } else if(matches.isEmpty()) { + return Optional.empty(); + } + WritableRegistry registry = (WritableRegistry) matches.getFirst(); + ((RegistryHack) registry).terra_bind(); + return Optional.of(registry); + } +} diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/RegistryLoaderMixin.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/RegistryLoaderMixin.java deleted file mode 100644 index d0a50afea..000000000 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/RegistryLoaderMixin.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.dfsek.terra.lifecycle.mixin.lifecycle; - -import com.llamalad7.mixinextras.sugar.Local; -import net.minecraft.enchantment.Enchantment; -import net.minecraft.registry.DynamicRegistryManager; -import net.minecraft.registry.MutableRegistry; -import net.minecraft.registry.Registry; -import net.minecraft.registry.RegistryKey; -import net.minecraft.registry.RegistryKeys; -import net.minecraft.registry.RegistryLoader; -import net.minecraft.registry.RegistryWrapper; -import net.minecraft.resource.ResourceManager; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.biome.source.MultiNoiseBiomeSourceParameterList; -import net.minecraft.world.dimension.DimensionType; -import net.minecraft.world.gen.WorldPreset; -import net.minecraft.world.gen.chunk.ChunkGeneratorSettings; -import org.slf4j.Logger; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Coerce; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.List; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; - -import com.dfsek.terra.lifecycle.LifecyclePlatform; -import com.dfsek.terra.lifecycle.util.LifecycleUtil; -import com.dfsek.terra.lifecycle.util.RegistryHack; -import com.dfsek.terra.mod.CommonPlatform; -import com.dfsek.terra.mod.ModPlatform; - - -@Mixin(RegistryLoader.class) -public class RegistryLoaderMixin { - - @Unique - private static final AtomicBoolean LOADING_DYNAMIC_REGISTRIES = new AtomicBoolean(false); - @Shadow - @Final - private static Logger LOGGER; - - @Inject(method = "loadFromResource(Lnet/minecraft/resource/ResourceManager;Ljava/util/List;Ljava/util/List;)" + - "Lnet/minecraft/registry/DynamicRegistryManager$Immutable;", - at = @At("HEAD")) - private static void loadFromResources(ResourceManager resourceManager, List> registries, - List> entries, - CallbackInfoReturnable cir) { - LOADING_DYNAMIC_REGISTRIES.set(entries.stream().anyMatch(entry -> entry.key() == RegistryKeys.BIOME)); - } - - @Inject( - method = "load(Lnet/minecraft/registry/RegistryLoader$RegistryLoadable;Ljava/util/List;Ljava/util/List;)" + - "Lnet/minecraft/registry/DynamicRegistryManager$Immutable;", - at = @At( - value = "INVOKE", - target = "Ljava/util/List;forEach(Ljava/util/function/Consumer;)V", - ordinal = 1 - ) - ) - private static void beforeFreeze(@Coerce Object loadable, List> wrappers, List> entries, - CallbackInfoReturnable cir, - @Local(ordinal = 2) List> registriesList) { - if(LOADING_DYNAMIC_REGISTRIES.getAndSet(false)) { - ModPlatform platform = CommonPlatform.get(); - platform.getRawConfigRegistry().clear(); - MutableRegistry biomes = extractRegistry(registriesList, RegistryKeys.BIOME).orElseThrow(); - MutableRegistry dimensionTypes = extractRegistry(registriesList, RegistryKeys.DIMENSION_TYPE).orElseThrow(); - MutableRegistry worldPresets = extractRegistry(registriesList, RegistryKeys.WORLD_PRESET).orElseThrow(); - MutableRegistry chunkGeneratorSettings = extractRegistry(registriesList, - RegistryKeys.CHUNK_GENERATOR_SETTINGS).orElseThrow(); - MutableRegistry multiNoiseBiomeSourceParameterLists = extractRegistry(registriesList, - RegistryKeys.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST).orElseThrow(); - MutableRegistry enchantments = extractRegistry(registriesList, RegistryKeys.ENCHANTMENT).orElseThrow(); - - LifecyclePlatform.setRegistries(biomes, dimensionTypes, chunkGeneratorSettings, multiNoiseBiomeSourceParameterLists, - enchantments); - LifecycleUtil.initialize(biomes, worldPresets); - } - } - - @Unique - @SuppressWarnings("unchecked") - private static Optional> extractRegistry(List> instance, - RegistryKey> key) { - List> matches = instance - .stream().map(RegistryLoader.Loader::registry) - .filter(r -> r.getKey().equals(key)) - .toList(); - if(matches.size() > 1) { - throw new IllegalStateException("Illegal number of registries returned: " + matches); - } else if(matches.isEmpty()) { - return Optional.empty(); - } - MutableRegistry registry = (MutableRegistry) matches.getFirst(); - ((RegistryHack) registry).terra_bind(); - return Optional.of(registry); - } -} diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/SaveLoadingMixin.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/SaveLoadingMixin.java deleted file mode 100644 index a7bf93453..000000000 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/SaveLoadingMixin.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.dfsek.terra.lifecycle.mixin.lifecycle; - -import net.minecraft.registry.CombinedDynamicRegistries; -import net.minecraft.registry.RegistryKeys; -import net.minecraft.registry.ServerDynamicRegistryType; -import net.minecraft.server.SaveLoading; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyArg; - -import com.dfsek.terra.mod.util.MinecraftUtil; - - -@Mixin(SaveLoading.class) -public class SaveLoadingMixin { - @ModifyArg( - method = "load(Lnet/minecraft/server/SaveLoading$ServerConfig;Lnet/minecraft/server/SaveLoading$LoadContextSupplier;" + - "Lnet/minecraft/server/SaveLoading$SaveApplierFactory;Ljava/util/concurrent/Executor;Ljava/util/concurrent/Executor;)" + - "Ljava/util/concurrent/CompletableFuture;", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/server/DataPackContents;reload(Lnet/minecraft/resource/ResourceManager;" + - "Lnet/minecraft/registry/CombinedDynamicRegistries;Ljava/util/List;Lnet/minecraft/resource/featuretoggle/FeatureSet;" + - "Lnet/minecraft/server/command/CommandManager$RegistrationEnvironment;ILjava/util/concurrent/Executor;" + - "Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletableFuture;"), - index = 1 - ) - private static CombinedDynamicRegistries grabManager( - CombinedDynamicRegistries dynamicRegistries) { - MinecraftUtil.registerFlora(dynamicRegistries.getCombinedRegistryManager().getOrThrow(RegistryKeys.BIOME)); - return dynamicRegistries; - } -} diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/WorldLoaderMixin.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/WorldLoaderMixin.java new file mode 100644 index 000000000..2db9e067d --- /dev/null +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/WorldLoaderMixin.java @@ -0,0 +1,28 @@ +package com.dfsek.terra.lifecycle.mixin.lifecycle; + +import net.minecraft.core.LayeredRegistryAccess; +import net.minecraft.core.registries.Registries; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.WorldLoader; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; + +import com.dfsek.terra.mod.util.MinecraftUtil; + + +@Mixin(WorldLoader.class) +public class WorldLoaderMixin { + @ModifyArg( + method = "load(Lnet/minecraft/server/WorldLoader$InitConfig;Lnet/minecraft/server/WorldLoader$WorldDataSupplier;Lnet/minecraft/server/WorldLoader$ResultFactory;Ljava/util/concurrent/Executor;Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletableFuture;", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/server/ReloadableServerResources;loadResources(Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/core/LayeredRegistryAccess;Ljava/util/List;Lnet/minecraft/world/flag/FeatureFlagSet;Lnet/minecraft/commands/Commands$CommandSelection;Lnet/minecraft/server/permissions/PermissionSet;Ljava/util/concurrent/Executor;Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletableFuture;"), + index = 1 + ) + private static LayeredRegistryAccess grabManager( + LayeredRegistryAccess dynamicRegistries) { + MinecraftUtil.registerFlora(dynamicRegistries.compositeAccess().lookupOrThrow(Registries.BIOME)); + return dynamicRegistries; + } +} 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 f9fcd0f72..4e795f76e 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 @@ -1,10 +1,10 @@ package com.dfsek.terra.lifecycle.util; -import net.minecraft.registry.Registry; -import net.minecraft.registry.RegistryKey; -import net.minecraft.registry.RegistryKeys; -import net.minecraft.util.Identifier; -import net.minecraft.village.VillagerType; +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; @@ -30,7 +30,7 @@ public final class LifecycleBiomeUtil { } - public static void registerBiomes(Registry biomeRegistry) { + public static void registerBiomes(Registry biomeRegistry) { logger.info("Registering biomes..."); CommonPlatform.get().getConfigRegistry().forEach(pack -> { // Register all Terra biomes. pack.getCheckedRegistry(Biome.class) @@ -47,8 +47,8 @@ public final class LifecycleBiomeUtil { */ private static void registerBiome(Biome biome, ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey id, - Registry registry) { - RegistryKey vanilla = ((ProtoPlatformBiome) biome.getPlatformBiome()).get(registry); + Registry registry) { + ResourceKey vanilla = ((ProtoPlatformBiome) biome.getPlatformBiome()).get(registry); if(vanilla == null) { logger.error(""" @@ -58,16 +58,16 @@ public final class LifecycleBiomeUtil { } if(pack.getContext().get(PreLoadCompatibilityOptions.class).useVanillaBiomes()) { - ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(registry.getEntry(registry.get(vanilla))); + ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(registry.wrapAsHolder(registry.getValue(vanilla))); } else { VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class); - net.minecraft.world.biome.Biome vanilaBiome = registry.get(vanilla); + net.minecraft.world.level.biome.Biome vanilaBiome = registry.getValue(vanilla); if(vanilaBiome == null) { String vanillaBiomeName; if(vanilla != null) { - vanillaBiomeName = vanilla.getValue().toString(); + vanillaBiomeName = vanilla.identifier().toString(); } else { vanillaBiomeName = "NULL"; } @@ -78,29 +78,29 @@ public final class LifecycleBiomeUtil { return; } - net.minecraft.world.biome.Biome minecraftBiome = BiomeUtil.createBiome(Objects.requireNonNull(vanilaBiome), + net.minecraft.world.level.biome.Biome minecraftBiome = BiomeUtil.createBiome(Objects.requireNonNull(vanilaBiome), vanillaBiomeProperties); - Identifier identifier = Identifier.of("terra", BiomeUtil.createBiomeID(pack, id)); + Identifier identifier = Identifier.fromNamespaceAndPath("terra", BiomeUtil.createBiomeID(pack, id)); - if(registry.containsId(identifier)) { + if(registry.containsKey(identifier)) { ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(MinecraftUtil.getEntry(registry, identifier) .orElseThrow()); } else { - ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(Registry.registerReference(registry, + ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(Registry.registerForHolder(registry, MinecraftUtil.registerBiomeKey(identifier) - .getValue(), + .identifier(), minecraftBiome)); } - Map, RegistryKey> villagerMap = + Map, ResourceKey> villagerMap = VillagerTypeAccessor.getBiomeTypeToIdMap(); - villagerMap.put(RegistryKey.of(RegistryKeys.BIOME, identifier), + villagerMap.put(ResourceKey.create(Registries.BIOME, identifier), Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(), villagerMap.getOrDefault(vanilla, VillagerType.PLAINS))); - BiomeUtil.TERRA_BIOME_MAP.computeIfAbsent(vanilla.getValue(), i -> new ArrayList<>()).add(identifier); + 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 3d896c4ab..86fda0d3a 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 @@ -1,21 +1,21 @@ package com.dfsek.terra.lifecycle.util; -import net.minecraft.registry.MutableRegistry; -import net.minecraft.registry.Registry; -import net.minecraft.registry.RegistryKey; -import net.minecraft.registry.RegistryKeys; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.gen.WorldPreset; +import net.minecraft.core.Registry; +import net.minecraft.core.WritableRegistry; +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 com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent; import com.dfsek.terra.mod.CommonPlatform; public final class LifecycleUtil { - public static void initialize(MutableRegistry biomeMutableRegistry, MutableRegistry worldPresetMutableRegistry) { + public static void initialize(WritableRegistry biomeMutableRegistry, WritableRegistry worldPresetMutableRegistry) { CommonPlatform.get().getEventManager().callEvent(new PlatformInitializationEvent()); LifecycleBiomeUtil.registerBiomes(biomeMutableRegistry); CommonPlatform.get().registerWorldTypes( - (id, preset) -> Registry.register(worldPresetMutableRegistry, RegistryKey.of(RegistryKeys.WORLD_PRESET, id), preset)); + (id, preset) -> Registry.register(worldPresetMutableRegistry, ResourceKey.create(Registries.WORLD_PRESET, id), preset)); } } diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/RegistryUtil.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/RegistryUtil.java index 7c9232d7e..3e4ac2cfb 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/RegistryUtil.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/RegistryUtil.java @@ -1,8 +1,8 @@ package com.dfsek.terra.lifecycle.util; -import net.minecraft.registry.Registries; -import net.minecraft.registry.Registry; -import net.minecraft.util.Identifier; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; import com.dfsek.terra.mod.data.Codecs; import com.dfsek.terra.mod.util.MinecraftUtil; @@ -15,7 +15,7 @@ public final class RegistryUtil { public static void register() { MinecraftUtil.registerIntProviderTypes(); - Registry.register(Registries.CHUNK_GENERATOR, Identifier.of("terra:terra"), Codecs.MINECRAFT_CHUNK_GENERATOR_WRAPPER); - Registry.register(Registries.BIOME_SOURCE, Identifier.of("terra:terra"), Codecs.TERRA_BIOME_SOURCE); + Registry.register(BuiltInRegistries.CHUNK_GENERATOR, Identifier.parse("terra:terra"), Codecs.MINECRAFT_CHUNK_GENERATOR_WRAPPER); + Registry.register(BuiltInRegistries.BIOME_SOURCE, Identifier.parse("terra:terra"), Codecs.TERRA_BIOME_SOURCE); } } 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 29f4f61a6..a37090d7f 100644 --- a/platforms/mixin-lifecycle/src/main/resources/terra.lifecycle.mixins.json +++ b/platforms/mixin-lifecycle/src/main/resources/terra.lifecycle.mixins.json @@ -4,13 +4,13 @@ "package": "com.dfsek.terra.lifecycle.mixin", "compatibilityLevel": "JAVA_21", "mixins": [ - "NoiseConfigMixin", - "RegistryEntryReferenceInvoker", - "RegistryMixin", - "SimpleRegistryMixin", + "RandomStateMixin", + "HolderReferenceInvoker", + "BuiltInRegistriesMixin", + "MappedRegistryMixin", "lifecycle.MinecraftServerMixin", - "lifecycle.RegistryLoaderMixin", - "lifecycle.SaveLoadingMixin" + "lifecycle.RegistryDataLoaderMixin", + "lifecycle.WorldLoaderMixin" ], "server": [ ], From b8d8807ae8e76362e93a71606b71fad738f822c6 Mon Sep 17 00:00:00 2001 From: Zoe Gidiere Date: Sat, 7 Nov 2026 15:10:55 -0700 Subject: [PATCH 36/44] feat: update mod platforms to Minecraft 26.3 --- buildSrc/src/main/kotlin/Versions.kt | 16 ++-- platforms/fabric/build.gradle.kts | 38 +++++---- .../fabric/src/main/resources/fabric.mod.json | 8 +- .../main/resources/terra.fabric.mixins.json | 2 +- platforms/merged/build.gradle.kts | 2 +- platforms/mixin-common/build.gradle.kts | 12 +-- .../terra/mod/config/SpawnEntryConfig.java | 3 +- .../mod/config/SpawnSettingsTemplate.java | 10 +-- .../java/com/dfsek/terra/mod/data/Codecs.java | 4 +- .../MinecraftChunkGeneratorWrapper.java | 39 ++++----- .../mod/generation/TerraBiomeSource.java | 10 ++- .../terra/mod/handle/MinecraftItemHandle.java | 2 +- .../mod/implmentation/TerraIntProvider.java | 12 +-- .../mod/mixin/access/StateHolderAccessor.java | 35 -------- .../mixin/generalize/ServerLevelMixin.java | 12 +-- ...eGenerationSettingsFloraFeaturesMixin.java | 10 +-- .../block/entity/SignBlockEntityMixin.java | 17 ++-- .../block/state/BlockStateBaseMixin.java | 13 ++- .../terra/chunk/LevelChunkMixin.java | 4 +- .../terra/chunk/WorldGenRegionMixin.java | 10 +-- .../terra/world/ServerLevelMixin.java | 3 +- .../terra/world/WorldGenRegionMixin.java | 7 +- .../mod/mixin_ifaces/FloraFeatureHolder.java | 4 +- .../com/dfsek/terra/mod/util/BiomeUtil.java | 83 +------------------ .../dfsek/terra/mod/util/DimensionUtil.java | 57 +------------ .../dfsek/terra/mod/util/MinecraftUtil.java | 11 +-- .../com/dfsek/terra/mod/util/SeedHack.java | 21 +++-- .../data/minecraft/wolf_variant/ashen.json | 5 ++ .../data/minecraft/wolf_variant/black.json | 5 ++ .../data/minecraft/wolf_variant/chestnut.json | 5 ++ .../data/minecraft/wolf_variant/pale.json | 5 ++ .../data/minecraft/wolf_variant/rusty.json | 5 ++ .../data/minecraft/wolf_variant/snowy.json | 5 ++ .../data/minecraft/wolf_variant/spotted.json | 5 ++ .../data/minecraft/wolf_variant/striped.json | 5 ++ .../data/minecraft/wolf_variant/woods.json | 5 ++ .../src/main/resources/terra.accesswidener | 3 +- .../main/resources/terra.common.mixins.json | 6 +- platforms/mixin-lifecycle/build.gradle.kts | 25 ++---- .../lifecycle/mixin/RandomStateMixin.java | 18 ++-- .../mixin/RegistryLoadTaskAccessor.java | 13 +++ .../mixin/lifecycle/MinecraftServerMixin.java | 17 ++-- .../lifecycle/RegistryDataLoaderMixin.java | 67 ++++++--------- .../mixin/lifecycle/WorldLoaderMixin.java | 7 +- .../resources/terra.lifecycle.mixins.json | 6 +- 45 files changed, 250 insertions(+), 402 deletions(-) delete mode 100644 platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StateHolderAccessor.java create mode 100644 platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RegistryLoadTaskAccessor.java diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index 41de76619..eb09f4ead 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -32,8 +32,8 @@ object Versions { } object Fabric { - const val fabricAPI = "0.140.0+${Mod.minecraft}" - const val cloud = "2.0.0-beta.13" + const val fabricAPI = "0.165.2+${Mod.minecraft}" + const val cloud = "2.1.0" } // // object Quilt { @@ -42,14 +42,14 @@ object Versions { // } object Mod { - const val mixin = "0.16.5+mixin.0.8.7" - const val mixinExtras = "0.5.0" + const val mixin = "0.17.5+mixin.0.8.7" + const val mixinExtras = "0.5.5" - const val minecraft = "1.21.11" - const val fabricLoader = "0.18.3" + const val minecraft = "26.3" + const val fabricLoader = "0.20.1" - const val architecturyLoom = "1.13.463" - const val architecturyPlugin = "3.4.162" + const val architecturyLoom = "1.17.493" + const val architecturyPlugin = "3.5.170" } // diff --git a/platforms/fabric/build.gradle.kts b/platforms/fabric/build.gradle.kts index 0797bae7f..02a3458bf 100644 --- a/platforms/fabric/build.gradle.kts +++ b/platforms/fabric/build.gradle.kts @@ -1,7 +1,7 @@ import java.util.* plugins { - id("dev.architectury.loom") version Versions.Mod.architecturyLoom + id("dev.architectury.loom-no-remap") version Versions.Mod.architecturyLoom id("architectury-plugin") version Versions.Mod.architecturyPlugin } @@ -13,45 +13,49 @@ architectury { dependencies { shadedApi(project(":common:implementation:base")) - implementation(project(path = ":platforms:mixin-common", configuration = "namedElements")) { isTransitive = false } - "developmentFabric"(project(path = ":platforms:mixin-common", configuration = "namedElements")) { isTransitive = false } + implementation(project(":platforms:mixin-common")) { isTransitive = false } + "developmentFabric"(project(":platforms:mixin-common")) { isTransitive = false } shaded(project(path = ":platforms:mixin-common", configuration = "transformProductionFabric")) { isTransitive = false } - implementation(project(path = ":platforms:mixin-lifecycle", configuration = "namedElements")) { isTransitive = false } - "developmentFabric"(project(path = ":platforms:mixin-lifecycle", configuration = "namedElements")) { isTransitive = false } + implementation(project(":platforms:mixin-lifecycle")) { isTransitive = false } + "developmentFabric"(project(":platforms:mixin-lifecycle")) { isTransitive = false } shaded(project(path = ":platforms:mixin-lifecycle", configuration = "transformProductionFabric")) { isTransitive = false } minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") - mappings(loom.officialMojangMappings()) - modImplementation("net.fabricmc:fabric-loader:${Versions.Mod.fabricLoader}") + implementation("net.fabricmc:fabric-loader:${Versions.Mod.fabricLoader}") - modImplementation("org.incendo", "cloud-fabric", Versions.Fabric.cloud) { + implementation("org.incendo", "cloud-fabric", Versions.Fabric.cloud) { exclude("me.lucko", "fabric-permissions-api") } include("org.incendo", "cloud-fabric", Versions.Fabric.cloud) - modRuntimeOnly("net.fabricmc.fabric-api", "fabric-api", Versions.Fabric.fabricAPI) + runtimeOnly("net.fabricmc.fabric-api", "fabric-api", Versions.Fabric.fabricAPI) } loom { accessWidenerPath.set(project(":platforms:mixin-common").file("src/main/resources/terra.accesswidener")) - mixin { - defaultRefmapName.set("terra.fabric.refmap.json") - } - + // Minecraft 26.x is unobfuscated: no remapJar, the shaded jar is the release jar. + nestJars(tasks.shadowJar, configurations.include) + injectAccessWidener(tasks.shadowJar) } addonDir(project.file("./run/config/Terra/addons"), tasks.named("configureLaunch").get()) tasks { - remapJar { - dependsOn("installAddons") + jar { + archiveClassifier.set("dev") + } - injectAccessWidener.set(true) - inputFile.set(shadowJar.get().archiveFile) + shadowJar { + archiveClassifier.set("") archiveFileName.set("${rootProject.name.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }}-fabric-${project.version}.jar") + manifest.attributes("Fabric-Mapping-Namespace" to "official") + } + + withType().configureEach { + options.release = 25 } } diff --git a/platforms/fabric/src/main/resources/fabric.mod.json b/platforms/fabric/src/main/resources/fabric.mod.json index c4575aca7..b7c2191fc 100644 --- a/platforms/fabric/src/main/resources/fabric.mod.json +++ b/platforms/fabric/src/main/resources/fabric.mod.json @@ -33,9 +33,9 @@ "terra.common.mixins.json" ], "depends": { - "fabricloader": ">=0.16.10", - "java": ">=21", - "minecraft": "1.21.10", - "fabric": "*" + "fabricloader": ">=0.20.1", + "java": ">=25", + "minecraft": "~26.3", + "fabric-api": "*" } } \ No newline at end of file diff --git a/platforms/fabric/src/main/resources/terra.fabric.mixins.json b/platforms/fabric/src/main/resources/terra.fabric.mixins.json index 4778acf1b..5dae5a2f6 100644 --- a/platforms/fabric/src/main/resources/terra.fabric.mixins.json +++ b/platforms/fabric/src/main/resources/terra.fabric.mixins.json @@ -2,7 +2,7 @@ "required": true, "minVersion": "0.8", "package": "com.dfsek.terra.fabric.mixin", - "compatibilityLevel": "JAVA_21", + "compatibilityLevel": "JAVA_25", "mixins": [ ], "client": [ diff --git a/platforms/merged/build.gradle.kts b/platforms/merged/build.gradle.kts index aab37e093..b82335b8a 100644 --- a/platforms/merged/build.gradle.kts +++ b/platforms/merged/build.gradle.kts @@ -1,5 +1,5 @@ val platformOverrides = mapOf( - "fabric" to "remapJar" + "fabric" to "shadowJar" ) dependencies { diff --git a/platforms/mixin-common/build.gradle.kts b/platforms/mixin-common/build.gradle.kts index 6ad243dcb..0f8b4c399 100644 --- a/platforms/mixin-common/build.gradle.kts +++ b/platforms/mixin-common/build.gradle.kts @@ -1,25 +1,18 @@ plugins { - id("dev.architectury.loom") version Versions.Mod.architecturyLoom + id("dev.architectury.loom-no-remap") version Versions.Mod.architecturyLoom id("architectury-plugin") version Versions.Mod.architecturyPlugin } loom { accessWidenerPath.set(file("src/main/resources/terra.accesswidener")) - - mixin { - defaultRefmapName.set("terra.common.refmap.json") - } } dependencies { shadedApi(project(":common:implementation:base")) compileOnly("net.fabricmc:sponge-mixin:${Versions.Mod.mixin}") - annotationProcessor("net.fabricmc:sponge-mixin:${Versions.Mod.mixin}") - annotationProcessor("dev.architectury:architectury-loom:${Versions.Mod.architecturyLoom}") minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") - mappings(loom.officialMojangMappings()) } architectury { @@ -27,3 +20,6 @@ architectury { minecraft = Versions.Mod.minecraft } +tasks.withType().configureEach { + options.release = 25 +} 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 index 2acad826e..e1cae45d5 100644 --- 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 @@ -3,6 +3,7 @@ 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; @@ -27,7 +28,7 @@ public class SpawnEntryConfig implements ObjectTemplate { } public SpawnerData getSpawnEntry() { - return new SpawnerData(type, groupSize.getMin(), groupSize.getMax()); + return new SpawnerData(type, UniformInt.of(groupSize.getMin(), groupSize.getMax())); } @Override 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 index 3e2fefb6e..bd3bbbb7f 100644 --- 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 @@ -28,15 +28,15 @@ public class SpawnSettingsTemplate implements ObjectTemplate { for(SpawnTypeConfig spawn : spawns) { MobCategory group = spawn.getGroup(); for(SpawnEntryConfig entry : spawn.getEntries()) { - builder.addSpawn(group, entry.getWeight(), entry.getSpawnEntry()); + MobSpawnSettings.SpawnerData spawnEntry = entry.getSpawnEntry(); + builder.addSpawn(spawnEntry.type(), group, entry.getWeight(), spawnEntry.count()); } } for(SpawnCostConfig cost : costs) { - builder.addMobCharge(cost.getType(), cost.getMass(), cost.getGravity()); - } - if(probability != null) { - builder.creatureGenerationProbability(probability); + 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/data/Codecs.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/data/Codecs.java index e60bdcdf3..62e426d66 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/data/Codecs.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/data/Codecs.java @@ -73,8 +73,8 @@ public final class Codecs { public static final MapCodec TERRA_CONSTANT_RANGE_INT_PROVIDER_TYPE = RecordCodecBuilder.mapCodec( range -> range.group( - Codec.INT.fieldOf("min").stable().forGetter(TerraIntProvider::getMinValue), - Codec.INT.fieldOf("max").stable().forGetter(TerraIntProvider::getMaxValue)) + Codec.INT.fieldOf("min").stable().forGetter(TerraIntProvider::minInclusive), + Codec.INT.fieldOf("max").stable().forGetter(TerraIntProvider::maxInclusive)) .apply(range, range.stable((min, max) -> new TerraIntProvider(new ConstantRange( min, max))))); } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/MinecraftChunkGeneratorWrapper.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/MinecraftChunkGeneratorWrapper.java index 959e90816..704ff1349 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/MinecraftChunkGeneratorWrapper.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/MinecraftChunkGeneratorWrapper.java @@ -35,17 +35,18 @@ import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.levelgen.Beardifier; -import net.minecraft.world.level.levelgen.DensityFunction.SinglePointContext; import net.minecraft.world.level.levelgen.Heightmap.Types; import net.minecraft.world.level.levelgen.LegacyRandomSource; import net.minecraft.world.level.levelgen.RandomState; import net.minecraft.world.level.levelgen.RandomSupport; import net.minecraft.world.level.levelgen.WorldgenRandom; import net.minecraft.world.level.levelgen.blending.Blender; +import net.minecraft.world.level.levelgen.densityfunction.SamplerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; +import java.util.Set; import java.util.concurrent.CompletableFuture; import com.dfsek.terra.api.block.state.BlockStateExtended; @@ -61,7 +62,6 @@ import com.dfsek.terra.mod.config.PreLoadCompatibilityOptions; import com.dfsek.terra.mod.data.Codecs; import com.dfsek.terra.mod.mixin.access.StructureManagerAccessor; import com.dfsek.terra.mod.util.MinecraftAdapter; -import com.dfsek.terra.mod.util.SeedHack; public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.level.chunk.ChunkGenerator implements GeneratorWrapper { @@ -89,29 +89,25 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.level.ch return Codecs.MINECRAFT_CHUNK_GENERATOR_WRAPPER; } - @Override - public void buildSurface(WorldGenRegion region, StructureManager structures, RandomState noiseConfig, ChunkAccess chunk) { - // no op - } - @Override public void spawnOriginalMobs(WorldGenRegion region) { if(this.settings.mobGeneration()) { ChunkPos chunkPos = region.getCenter(); - Holder registryEntry = region.getBiome(chunkPos.getWorldPosition().atY(region.getMaxY() - 1)); + BlockPos sourcePos = chunkPos.getWorldPosition().atY(region.getMaxY() - 1); WorldgenRandom chunkRandom = new WorldgenRandom(new LegacyRandomSource(RandomSupport.generateUniqueSeed())); chunkRandom.setDecorationSeed(region.getSeed(), chunkPos.getMinBlockX(), chunkPos.getMinBlockZ()); - NaturalSpawner.spawnMobsForChunkGeneration(region, registryEntry, chunkPos, chunkRandom); + NaturalSpawner.spawnMobsForChunkGeneration(region, sourcePos, chunkPos, chunkRandom); } } @Override - public CompletableFuture fillFromNoise(Blender blender, RandomState noiseConfig, StructureManager structureAccessor, - ChunkAccess chunk) { + public CompletableFuture buildTerrain(ChunkAccess chunk, Blender blender, RandomState noiseConfig, + StructureManager structureAccessor, BiomeManager biomeAccess, + WorldGenRegion carverBiomeRegion, Set> possibleBiomes) { return CompletableFuture.supplyAsync(() -> { ProtoWorld world = (ProtoWorld) ((StructureManagerAccessor) structureAccessor).getLevel(); BiomeProvider biomeProvider = pack.getBiomeProvider(); - delegate.generateChunkData((ProtoChunk) chunk, world, biomeProvider, chunk.getPos().x, chunk.getPos().z); + delegate.generateChunkData((ProtoChunk) chunk, world, biomeProvider, chunk.getPos().x(), chunk.getPos().z()); PreLoadCompatibilityOptions compatibilityOptions = pack.getContext().get(PreLoadCompatibilityOptions.class); if(compatibilityOptions.isBeard()) { @@ -127,13 +123,13 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.level.ch chunk.getPos()); double threshold = compatibilityOptions.getBeardThreshold(); double airThreshold = compatibilityOptions.getAirThreshold(); - int xi = chunk.getPos().x << 4; - int zi = chunk.getPos().z << 4; + int xi = chunk.getPos().x() << 4; + int zi = chunk.getPos().z() << 4; for(int x = 0; x < 16; x++) { for(int z = 0; z < 16; z++) { int depth = 0; for(int y = world.getMaxHeight(); y >= world.getMinHeight(); y--) { - double noise = structureWeightSampler.compute(new SinglePointContext(x + xi, y, z + zi)); + double noise = structureWeightSampler.sampleValue(SamplerContext.EMPTY_UNCACHED, x + xi, y, z + zi); if(noise > threshold) { com.dfsek.terra.api.block.state.BlockState data = delegate.getPalette(x + xi, y, z + zi, world, biomeProvider).get( depth, x + xi, y, z + zi, world.getSeed()); @@ -190,7 +186,7 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.level.ch @Override public int getBaseHeight(int x, int z, Types heightmap, LevelHeightAccessor height, RandomState noiseConfig) { - WorldProperties properties = MinecraftAdapter.adapt(height, SeedHack.getSeed(noiseConfig.sampler())); + WorldProperties properties = MinecraftAdapter.adapt(height, noiseConfig.seed()); BiomeProvider biomeProvider = pack.getBiomeProvider(); int min = height.getMinY(); for(int y = height.getMaxY() - 1; y >= min; y--) { @@ -207,7 +203,7 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.level.ch @Override public NoiseColumn getBaseColumn(int x, int z, LevelHeightAccessor height, RandomState noiseConfig) { BlockState[] array = new BlockState[height.getHeight()]; - WorldProperties properties = MinecraftAdapter.adapt(height, SeedHack.getSeed(noiseConfig.sampler())); + WorldProperties properties = MinecraftAdapter.adapt(height, noiseConfig.seed()); BiomeProvider biomeProvider = pack.getBiomeProvider(); for(int y = height.getMaxY() - 1; y >= height.getMinY(); y--) { com.dfsek.terra.api.block.state.BlockState terraBlockState = delegate.getBlock(properties, x, y, z, biomeProvider); @@ -219,7 +215,7 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.level.ch } @Override - public void addDebugScreenInfo(List text, RandomState noiseConfig, BlockPos pos) { + public void addDebugScreenInfo(List text, RandomState noiseConfig, BlockPos pos, SamplerContext samplerContext) { // no op } @@ -235,13 +231,6 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.level.ch logger.debug("Loading world with config pack {}", pack.getID()); } - - @Override - public void applyCarvers(WorldGenRegion chunkRegion, long seed, RandomState noiseConfig, BiomeManager biomeAccess, - StructureManager structureAccessor, ChunkAccess chunk) { - //no op - } - @Override public ChunkGenerator getHandle() { return delegate; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/TerraBiomeSource.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/TerraBiomeSource.java index 49597b610..ad905f5bf 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/TerraBiomeSource.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/generation/TerraBiomeSource.java @@ -20,6 +20,7 @@ package com.dfsek.terra.mod.generation; import com.mojang.serialization.MapCodec; import net.minecraft.core.Holder; import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeResolver; import net.minecraft.world.level.biome.BiomeSource; import net.minecraft.world.level.biome.Climate.Sampler; import org.slf4j.Logger; @@ -61,10 +62,15 @@ public class TerraBiomeSource extends BiomeSource { } @Override - public Holder getNoiseBiome(int biomeX, int biomeY, int biomeZ, Sampler Sampler) { + public BiomeResolver createResolver(Sampler sampler) { + long seed = SeedHack.getSeed(sampler); + return (biomeX, biomeY, biomeZ) -> getNoiseBiome(biomeX, biomeY, biomeZ, seed); + } + + public Holder getNoiseBiome(int biomeX, int biomeY, int biomeZ, long seed) { return ((ProtoPlatformBiome) pack .getBiomeProvider() - .getBiome(biomeX << 2, biomeY << 2, biomeZ << 2, SeedHack.getSeed(Sampler)) + .getBiome(biomeX << 2, biomeY << 2, biomeZ << 2, seed) .getPlatformBiome()).getDelegate(); } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/handle/MinecraftItemHandle.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/handle/MinecraftItemHandle.java index 25c5a776d..5690f6bb5 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/handle/MinecraftItemHandle.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/handle/MinecraftItemHandle.java @@ -58,7 +58,7 @@ public class MinecraftItemHandle implements ItemHandle { public Optional> lookup(ResourceKey> registryRef) { return Optional.of(CommonPlatform.get().getServer().registryAccess().lookupOrThrow(registryRef)); } - }).parse(new StringReader(data)).getItem(); + }).parse(new StringReader(data)).item().value(); } catch(CommandSyntaxException e) { throw new IllegalArgumentException("Invalid item data \"" + data + "\"", e); } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/implmentation/TerraIntProvider.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/implmentation/TerraIntProvider.java index 1332c38ab..bf93fea26 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/implmentation/TerraIntProvider.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/implmentation/TerraIntProvider.java @@ -1,8 +1,8 @@ package com.dfsek.terra.mod.implmentation; +import com.mojang.serialization.MapCodec; import net.minecraft.util.RandomSource; import net.minecraft.util.valueproviders.IntProvider; -import net.minecraft.util.valueproviders.IntProviderType; import java.util.HashMap; import java.util.Map; @@ -11,8 +11,8 @@ import com.dfsek.terra.api.util.range.Range; import com.dfsek.terra.mod.util.MinecraftAdapter; -public class TerraIntProvider extends IntProvider { - public static final Map TERRA_RANGE_TYPE_TO_INT_PROVIDER_TYPE = new HashMap<>(); +public class TerraIntProvider implements IntProvider { + public static final Map> TERRA_RANGE_TYPE_TO_INT_PROVIDER_TYPE = new HashMap<>(); public Range delegate; @@ -26,17 +26,17 @@ public class TerraIntProvider extends IntProvider { } @Override - public int getMinValue() { + public int minInclusive() { return delegate.getMin(); } @Override - public int getMaxValue() { + public int maxInclusive() { return delegate.getMax(); } @Override - public IntProviderType getType() { + public MapCodec codec() { return TERRA_RANGE_TYPE_TO_INT_PROVIDER_TYPE.get(delegate.getClass()); } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StateHolderAccessor.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StateHolderAccessor.java deleted file mode 100644 index 324066d5b..000000000 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/StateHolderAccessor.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * This file is part of Terra. - * - * Terra is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Terra is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Terra. If not, see . - */ - -package com.dfsek.terra.mod.mixin.access; - -import net.minecraft.world.level.block.state.StateHolder; -import net.minecraft.world.level.block.state.properties.Property; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -import java.util.Map; -import java.util.function.Function; - - -@Mixin(StateHolder.class) -public interface StateHolderAccessor { - @Accessor("PROPERTY_ENTRY_TO_STRING_FUNCTION") - static Function, Comparable>, String> getPropertyMapPrinter() { - throw new UnsupportedOperationException(); - } -} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/generalize/ServerLevelMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/generalize/ServerLevelMixin.java index 981f917d8..ebadae981 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/generalize/ServerLevelMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/generalize/ServerLevelMixin.java @@ -1,7 +1,6 @@ package com.dfsek.terra.mod.mixin.generalize; -import net.minecraft.core.Holder; import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; @@ -9,7 +8,7 @@ import net.minecraft.server.level.progress.LevelLoadListener; import net.minecraft.world.RandomSequences; import net.minecraft.world.level.CustomSpawner; import net.minecraft.world.level.Level; -import net.minecraft.world.level.dimension.BuiltinDimensionTypes; +import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.dimension.LevelStem; import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.ServerLevelData; @@ -34,11 +33,8 @@ public abstract class ServerLevelMixin extends Level { @Redirect(method = "", at = @At(value = "INVOKE", - target = "Lnet/minecraft/core/Holder;is(Lnet/minecraft/resources/ResourceKey;)Z")) - public boolean matchesKeyProxy(Holder instance, ResourceKey tRegistryKey) { - if(tRegistryKey == BuiltinDimensionTypes.END) { - return (this.dimension() == Level.END); - } - return instance.is(tRegistryKey); + target = "Lnet/minecraft/world/level/dimension/DimensionType;hasEnderDragonFight()Z")) + public boolean hasEnderDragonFightProxy(DimensionType instance) { + return this.dimension() == Level.END; } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/compat/BiomeGenerationSettingsFloraFeaturesMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/compat/BiomeGenerationSettingsFloraFeaturesMixin.java index 689c4c179..387b89f82 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/compat/BiomeGenerationSettingsFloraFeaturesMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/compat/BiomeGenerationSettingsFloraFeaturesMixin.java @@ -1,7 +1,7 @@ package com.dfsek.terra.mod.mixin.implementations.compat; import net.minecraft.world.level.biome.BiomeGenerationSettings; -import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; +import net.minecraft.world.level.levelgen.feature.Feature; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Intrinsic; @@ -19,14 +19,14 @@ import com.dfsek.terra.mod.mixin_ifaces.FloraFeatureHolder; @Mixin(BiomeGenerationSettings.class) @Implements(@Interface(iface = FloraFeatureHolder.class, prefix = "terra$")) public class BiomeGenerationSettingsFloraFeaturesMixin { - private List> flora; + private List flora; - public void terra$setFloraFeatures(List> features) { + public void terra$setFloraFeatures(List features) { this.flora = features; } - @Inject(method = "getFlowerFeatures()Ljava/util/List;", cancellable = true, at = @At("HEAD")) - public void inject(CallbackInfoReturnable>> cir) { + @Inject(method = "getBoneMealFeatures()Ljava/util/List;", cancellable = true, at = @At("HEAD")) + public void inject(CallbackInfoReturnable> cir) { if(flora != null) { cir.setReturnValue(flora); } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/SignBlockEntityMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/SignBlockEntityMixin.java index 45f4f22d7..2c146a031 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/SignBlockEntityMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/entity/SignBlockEntityMixin.java @@ -20,12 +20,15 @@ package com.dfsek.terra.mod.mixin.implementations.terra.block.entity; import net.minecraft.network.chat.Component; import net.minecraft.world.level.block.entity.SignBlockEntity; import net.minecraft.world.level.block.entity.SignText; +import net.minecraft.world.level.block.entity.SignTextSlot; import org.jetbrains.annotations.NotNull; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import java.util.List; + import com.dfsek.terra.api.block.entity.SerialState; import com.dfsek.terra.api.block.entity.Sign; @@ -37,23 +40,23 @@ public abstract class SignBlockEntityMixin { private SignText frontText; @Shadow - public abstract boolean setText(SignText text, boolean front); + public abstract void setText(SignText text, SignTextSlot slot); public void terra$setLine(int index, @NotNull String line) throws IndexOutOfBoundsException { - setText(frontText.setMessage(index, Component.literal(line)), true); + setText(frontText.asMutable().setLine(index, Component.literal(line)).asImmutable(), SignTextSlot.FRONT); } public @NotNull String[] terra$getLines() { - Component[] texts = frontText.getMessages(false); - String[] lines = new String[texts.length]; - for(int i = 0; i < texts.length; i++) { - lines[i] = texts[i].getString(); + List texts = frontText.getMessages(false); + String[] lines = new String[texts.size()]; + for(int i = 0; i < texts.size(); i++) { + lines[i] = texts.get(i).getString(); } return lines; } public @NotNull String terra$getLine(int index) throws IndexOutOfBoundsException { - return frontText.getMessage(index, false).getString(); + return frontText.getMessages(false).get(index).getString(); } public void terra$applyState(String state) { diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockStateBaseMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockStateBaseMixin.java index 3f22c2cf7..40a81ff9f 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockStateBaseMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/block/state/BlockStateBaseMixin.java @@ -1,8 +1,6 @@ package com.dfsek.terra.mod.mixin.implementations.terra.block.state; -import com.mojang.serialization.MapCodec; -import it.unimi.dsi.fastutil.objects.Reference2ObjectArrayMap; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockBehaviour.BlockStateBase; @@ -18,15 +16,14 @@ import java.util.stream.Collectors; import com.dfsek.terra.api.block.BlockType; import com.dfsek.terra.api.block.state.BlockState; import com.dfsek.terra.api.block.state.properties.Property; -import com.dfsek.terra.mod.mixin.access.StateHolderAccessor; @Mixin(BlockStateBase.class) @Implements(@Interface(iface = BlockState.class, prefix = "terra$")) public abstract class BlockStateBaseMixin extends StateHolder { - private BlockStateBaseMixin(Block owner, Reference2ObjectArrayMap, Comparable> entries, - MapCodec codec) { - super(owner, entries, codec); + private BlockStateBaseMixin(Block owner, net.minecraft.world.level.block.state.properties.Property[] propertyKeys, + Comparable[] propertyValues) { + super(owner, propertyKeys, propertyValues); } @Shadow @@ -67,10 +64,10 @@ public abstract class BlockStateBaseMixin extends StateHolder { + entity = net.minecraft.world.entity.EntityType.loadEntityRecursive(nbt, this, new EntitySpawnRequest(EntitySpawnReason.CHUNK_GENERATION, false), (entityx) -> { entityx.snapTo(x, y, z, entityx.getYRot(), entityx.getXRot()); return entityx; }); diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/WorldGenRegionMixin.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/WorldGenRegionMixin.java index 320d98af3..50dad70dc 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/WorldGenRegionMixin.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/implementations/terra/world/WorldGenRegionMixin.java @@ -23,6 +23,7 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.server.level.WorldGenRegion; import net.minecraft.util.StaticCache2D; import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntitySpawnRequest; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.chunk.ChunkAccess; @@ -151,7 +152,7 @@ public abstract class WorldGenRegionMixin implements WorldGenLevel { if(isExtended) { MinecraftEntityTypeExtended type = ((MinecraftEntityTypeExtended) data); CompoundTag nbt = (CompoundTag) ((Object) type.getData()); - entity = net.minecraft.world.entity.EntityType.loadEntityRecursive(nbt, level, EntitySpawnReason.CHUNK_GENERATION, (entityx) -> { + entity = net.minecraft.world.entity.EntityType.loadEntityRecursive(nbt, level, new EntitySpawnRequest(EntitySpawnReason.CHUNK_GENERATION, false), (entityx) -> { entityx.snapTo(x, y, z, entityx.getYRot(), entityx.getXRot()); return entityx; }); @@ -166,11 +167,11 @@ public abstract class WorldGenRegionMixin implements WorldGenLevel { } public int terraWorld$centerChunkX() { - return center.getPos().x; + return center.getPos().x(); } public int terraWorld$centerChunkZ() { - return center.getPos().z; + return center.getPos().z(); } public ServerWorld terraWorld$getWorld() { diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin_ifaces/FloraFeatureHolder.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin_ifaces/FloraFeatureHolder.java index de3d89e2d..d7e7c06db 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin_ifaces/FloraFeatureHolder.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin_ifaces/FloraFeatureHolder.java @@ -1,10 +1,10 @@ package com.dfsek.terra.mod.mixin_ifaces; -import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; +import net.minecraft.world.level.levelgen.feature.Feature; import java.util.List; public interface FloraFeatureHolder { - void setFloraFeatures(List> features); + void setFloraFeatures(List features); } 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 1713da9d3..c035e45f9 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,21 +1,15 @@ package com.dfsek.terra.mod.util; -import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.Identifier; import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.Biome.BiomeBuilder; -import net.minecraft.world.level.biome.BiomeGenerationSettings; -import net.minecraft.world.level.biome.BiomeSpecialEffects; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.Objects; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.mod.config.VanillaBiomeProperties; -import com.dfsek.terra.mod.mixin.access.BiomeAccessor; public class BiomeUtil { @@ -23,82 +17,7 @@ public class BiomeUtil { TERRA_BIOME_MAP = new HashMap<>(); public static Biome createBiome(Biome vanilla, VanillaBiomeProperties vanillaBiomeProperties) { - BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder(); - - net.minecraft.world.level.biome.Biome.BiomeBuilder builder = new BiomeBuilder(); - - effects.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor())) - .waterFogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanilla.getWaterFogColor())) - .fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor())) - .skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor())) - .grassColorModifier( - Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(), vanilla.getSpecialEffects().getGrassColorModifier())) - .musicVolume(Objects.requireNonNullElse(vanillaBiomeProperties.getMusicVolume(), vanilla.getMusicVolume())); - - if(vanillaBiomeProperties.getGrassColor() == null) { - vanilla.getSpecialEffects().getGrassColor().ifPresent(effects::grassColorOverride); - } else { - effects.grassColorOverride(vanillaBiomeProperties.getGrassColor()); - } - - if(vanillaBiomeProperties.getFoliageColor() == null) { - vanilla.getSpecialEffects().getFoliageColor().ifPresent(effects::foliageColorOverride); - } else { - effects.foliageColorOverride(vanillaBiomeProperties.getFoliageColor()); - } - - if(vanillaBiomeProperties.getDryFoliageColor() == null) { - vanilla.getSpecialEffects().getDryFoliageColor().ifPresent(effects::dryFoliageColorOverride); - } else { - effects.dryFoliageColorOverride(vanillaBiomeProperties.getDryFoliageColor()); - } - - if(vanillaBiomeProperties.getParticleConfig() == null) { - vanilla.getSpecialEffects().getParticleConfig().ifPresent(effects::particleConfig); - } else { - effects.particleConfig(vanillaBiomeProperties.getParticleConfig()); - } - - if(vanillaBiomeProperties.getLoopSound() == null) { - vanilla.getSpecialEffects().getLoopSound().ifPresent(effects::loopSound); - } else { - effects.loopSound(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(vanillaBiomeProperties.getLoopSound())); - } - - if(vanillaBiomeProperties.getMoodSound() == null) { - vanilla.getSpecialEffects().getMoodSound().ifPresent(effects::moodSound); - } else { - effects.moodSound(vanillaBiomeProperties.getMoodSound()); - } - - if(vanillaBiomeProperties.getAdditionsSound() == null) { - vanilla.getSpecialEffects().getAdditionsSound().ifPresent(effects::additionsSound); - } else { - effects.additionsSound(vanillaBiomeProperties.getAdditionsSound()); - } - - if(vanillaBiomeProperties.getMusic() == null) { - vanilla.getSpecialEffects().getMusic().ifPresent(effects::music); - } else { - effects.music(vanillaBiomeProperties.getMusic()); - } - - builder.hasPrecipitation(Objects.requireNonNullElse(vanillaBiomeProperties.getPrecipitation(), vanilla.hasPrecipitation())); - - builder.temperature(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperature(), vanilla.getBaseTemperature())); - - builder.downfall(Objects.requireNonNullElse(vanillaBiomeProperties.getDownfall(), - ((BiomeAccessor) ((Object) vanilla)).getWeather().downfall())); - - builder.temperatureAdjustment(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperatureModifier(), - ((BiomeAccessor) ((Object) vanilla)).getWeather().temperatureModifier())); - - builder.mobSpawnSettings(Objects.requireNonNullElse(vanillaBiomeProperties.getSpawnSettings(), vanilla.getMobSettings())); - - return builder - .specialEffects(effects.build()) - .generationSettings(new BiomeGenerationSettings.PlainBuilder().build()) - .build(); + throw new UnsupportedOperationException("TODO: environment attributes"); } public static String createBiomeID(ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey biomeID) { 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 index 6f3c65747..3f1f93bde 100644 --- 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 @@ -1,75 +1,22 @@ package com.dfsek.terra.mod.util; -import net.minecraft.core.registries.Registries; -import net.minecraft.tags.TagKey; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.dimension.DimensionType.MonsterSettings; import org.jetbrains.annotations.NotNull; -import java.util.OptionalLong; - import com.dfsek.terra.mod.ModPlatform; import com.dfsek.terra.mod.config.MonsterSettingsConfig; import com.dfsek.terra.mod.config.VanillaWorldProperties; -import com.dfsek.terra.mod.implmentation.TerraIntProvider; public class DimensionUtil { public static DimensionType createDimension(VanillaWorldProperties vanillaWorldProperties, DimensionType defaultDimension, ModPlatform platform) { - - MonsterSettingsConfig monsterSettingsConfig; - if(vanillaWorldProperties.getMonsterSettings() != null) { - monsterSettingsConfig = vanillaWorldProperties.getMonsterSettings(); - } else { - monsterSettingsConfig = new MonsterSettingsConfig(); - } - - MonsterSettings monsterSettings = getMonsterSettings(defaultDimension, monsterSettingsConfig); - - return new DimensionType( - vanillaWorldProperties.getFixedTime() == null ? defaultDimension.fixedTime() : OptionalLong.of( - vanillaWorldProperties.getFixedTime()), - vanillaWorldProperties.getHasSkyLight() == null ? defaultDimension.hasSkyLight() : vanillaWorldProperties.getHasSkyLight(), - vanillaWorldProperties.getHasCeiling() == null ? defaultDimension.hasCeiling() : vanillaWorldProperties.getHasCeiling(), - vanillaWorldProperties.getUltraWarm() == null ? defaultDimension.ultrawarm() : vanillaWorldProperties.getUltraWarm(), - vanillaWorldProperties.getNatural() == null ? defaultDimension.natural() : vanillaWorldProperties.getNatural(), - vanillaWorldProperties.getCoordinateScale() == null - ? defaultDimension.coordinateScale() - : vanillaWorldProperties.getCoordinateScale(), - vanillaWorldProperties.getBedWorks() == null ? defaultDimension.bedWorks() : vanillaWorldProperties.getBedWorks(), - vanillaWorldProperties.getRespawnAnchorWorks() == null - ? defaultDimension.respawnAnchorWorks() - : vanillaWorldProperties.getRespawnAnchorWorks(), - vanillaWorldProperties.getHeight() == null ? defaultDimension.minY() : vanillaWorldProperties.getHeight().getMin(), - vanillaWorldProperties.getHeight() == null ? defaultDimension.height() : vanillaWorldProperties.getHeight().getRange(), - vanillaWorldProperties.getLogicalHeight() == null - ? defaultDimension.logicalHeight() - : vanillaWorldProperties.getLogicalHeight(), - vanillaWorldProperties.getInfiniburn() == null - ? defaultDimension.infiniburn() - : TagKey.create(Registries.BLOCK, vanillaWorldProperties.getInfiniburn()), - vanillaWorldProperties.getEffects() == null ? defaultDimension.effects() : vanillaWorldProperties.getEffects(), - vanillaWorldProperties.getAmbientLight() == null ? defaultDimension.ambientLight() : vanillaWorldProperties.getAmbientLight(), - vanillaWorldProperties.getCloudHeight() == null - ? defaultDimension.cloudHeight() - : vanillaWorldProperties.getCloudHeight().describeConstable(), - monsterSettings - ); + throw new UnsupportedOperationException("TODO: environment attributes"); } @NotNull private static MonsterSettings getMonsterSettings(DimensionType defaultDimension, MonsterSettingsConfig monsterSettingsConfig) { - MonsterSettings defaultMonsterSettings = defaultDimension.monsterSettings(); - - return new MonsterSettings( - monsterSettingsConfig.getPiglinSafe() == null ? defaultMonsterSettings.piglinSafe() : monsterSettingsConfig.getPiglinSafe(), - monsterSettingsConfig.getHasRaids() == null ? defaultMonsterSettings.hasRaids() : monsterSettingsConfig.getHasRaids(), - monsterSettingsConfig.getMonsterSpawnLight() == null ? defaultMonsterSettings.monsterSpawnLightTest() : new TerraIntProvider( - monsterSettingsConfig.getMonsterSpawnLight()), - monsterSettingsConfig.getMonsterSpawnBlockLightLimit() == null - ? defaultMonsterSettings.monsterSpawnBlockLightLimit() - : monsterSettingsConfig.getMonsterSpawnBlockLightLimit() - ); + throw new UnsupportedOperationException("TODO: environment attributes"); } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/MinecraftUtil.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/MinecraftUtil.java index b3578335e..44ba7c28e 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/MinecraftUtil.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/MinecraftUtil.java @@ -1,14 +1,15 @@ package com.dfsek.terra.mod.util; +import com.mojang.serialization.MapCodec; import net.minecraft.commands.arguments.blocks.BlockInput; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.core.Registry; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; -import net.minecraft.util.valueproviders.IntProviderType; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.biome.Biome; @@ -20,7 +21,7 @@ import net.minecraft.world.level.block.entity.SpawnerBlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.dimension.DimensionType; -import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; +import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.ticks.ScheduledTick; import net.minecraft.world.ticks.TickAccess; @@ -107,7 +108,7 @@ public final class MinecraftUtil { } public static void registerIntProviderTypes() { - IntProviderType CONSTANT = IntProviderType.register("terra:constant_range", + MapCodec CONSTANT = Registry.register(BuiltInRegistries.INT_PROVIDER_TYPE, "terra:constant_range", Codecs.TERRA_CONSTANT_RANGE_INT_PROVIDER_TYPE); TerraIntProvider.TERRA_RANGE_TYPE_TO_INT_PROVIDER_TYPE.put(ConstantRange.class, CONSTANT); @@ -135,9 +136,9 @@ public final class MinecraftUtil { Identifier terraBiomeIdentifier = Identifier.fromNamespaceAndPath("terra", BiomeUtil.createBiomeID(pack, id)); biomeRegistry.getOptional(terraBiomeIdentifier).ifPresentOrElse( terraBiome -> { - List> flowerFeatures = List.copyOf( + List flowerFeatures = List.copyOf( vanillaBiome.getGenerationSettings() - .getFlowerFeatures()); + .getBoneMealFeatures()); logger.debug("Injecting flora into biome" + " {} : {}", terraBiomeIdentifier, flowerFeatures); diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/SeedHack.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/SeedHack.java index d2b92af44..64f1faefb 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/SeedHack.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/SeedHack.java @@ -1,29 +1,28 @@ package com.dfsek.terra.mod.util; -import it.unimi.dsi.fastutil.objects.Object2LongMap; -import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; +import com.google.common.collect.MapMaker; import net.minecraft.world.level.biome.Climate.Sampler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import java.util.concurrent.ConcurrentMap; /** - * Holder for hacky biome source seed workaround + * Maps climate samplers to world seeds. + *

+ * {@link net.minecraft.world.level.levelgen.RandomState} creates a new {@link Sampler} for every sampling context. */ public class SeedHack { - private static final Logger LOGGER = LoggerFactory.getLogger(SeedHack.class); - - private static final Object2LongMap seedMap = new Object2LongOpenHashMap<>(); + private static final ConcurrentMap seedMap = new MapMaker().weakKeys().makeMap(); public static long getSeed(Sampler sampler) { - if(!seedMap.containsKey(sampler)) { + Long seed = seedMap.get(sampler); + if(seed == null) { throw new IllegalArgumentException("Sampler is not registered: " + sampler); } - return seedMap.getLong(sampler); + return seed; } public static void register(Sampler sampler, long seed) { - LOGGER.info("Registered seed {} to sampler {}", seed, sampler.hashCode()); seedMap.put(sampler, seed); } } diff --git a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/ashen.json b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/ashen.json index 204c648df..25135d042 100644 --- a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/ashen.json +++ b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/ashen.json @@ -4,6 +4,11 @@ "tame": "minecraft:entity/wolf/wolf_ashen_tame", "wild": "minecraft:entity/wolf/wolf_ashen" }, + "baby_assets": { + "angry": "minecraft:entity/wolf/wolf_ashen_angry_baby", + "tame": "minecraft:entity/wolf/wolf_ashen_tame_baby", + "wild": "minecraft:entity/wolf/wolf_ashen_baby" + }, "spawn_conditions": [ { "condition": { diff --git a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/black.json b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/black.json index dd97f8c86..d521c6d4a 100644 --- a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/black.json +++ b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/black.json @@ -4,6 +4,11 @@ "tame": "minecraft:entity/wolf/wolf_black_tame", "wild": "minecraft:entity/wolf/wolf_black" }, + "baby_assets": { + "angry": "minecraft:entity/wolf/wolf_black_angry_baby", + "tame": "minecraft:entity/wolf/wolf_black_tame_baby", + "wild": "minecraft:entity/wolf/wolf_black_baby" + }, "spawn_conditions": [ { "condition": { diff --git a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/chestnut.json b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/chestnut.json index 747ae204e..0f08e83e3 100644 --- a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/chestnut.json +++ b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/chestnut.json @@ -4,6 +4,11 @@ "tame": "minecraft:entity/wolf/wolf_chestnut_tame", "wild": "minecraft:entity/wolf/wolf_chestnut" }, + "baby_assets": { + "angry": "minecraft:entity/wolf/wolf_chestnut_angry_baby", + "tame": "minecraft:entity/wolf/wolf_chestnut_tame_baby", + "wild": "minecraft:entity/wolf/wolf_chestnut_baby" + }, "spawn_conditions": [ { "condition": { diff --git a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/pale.json b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/pale.json index 72f13b0bc..dfab1402f 100644 --- a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/pale.json +++ b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/pale.json @@ -4,6 +4,11 @@ "tame": "minecraft:entity/wolf/wolf_tame", "wild": "minecraft:entity/wolf/wolf" }, + "baby_assets": { + "angry": "minecraft:entity/wolf/wolf_angry_baby", + "tame": "minecraft:entity/wolf/wolf_tame_baby", + "wild": "minecraft:entity/wolf/wolf_baby" + }, "spawn_conditions": [ { "condition": { diff --git a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/rusty.json b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/rusty.json index 596e8ac7a..b93d9a657 100644 --- a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/rusty.json +++ b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/rusty.json @@ -4,6 +4,11 @@ "tame": "minecraft:entity/wolf/wolf_rusty_tame", "wild": "minecraft:entity/wolf/wolf_rusty" }, + "baby_assets": { + "angry": "minecraft:entity/wolf/wolf_rusty_angry_baby", + "tame": "minecraft:entity/wolf/wolf_rusty_tame_baby", + "wild": "minecraft:entity/wolf/wolf_rusty_baby" + }, "spawn_conditions": [ { "condition": { diff --git a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/snowy.json b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/snowy.json index f4dd77019..5e12740af 100644 --- a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/snowy.json +++ b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/snowy.json @@ -4,6 +4,11 @@ "tame": "minecraft:entity/wolf/wolf_snowy_tame", "wild": "minecraft:entity/wolf/wolf_snowy" }, + "baby_assets": { + "angry": "minecraft:entity/wolf/wolf_snowy_angry_baby", + "tame": "minecraft:entity/wolf/wolf_snowy_tame_baby", + "wild": "minecraft:entity/wolf/wolf_snowy_baby" + }, "spawn_conditions": [ { "condition": { diff --git a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/spotted.json b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/spotted.json index 1ad0f5770..e80efb733 100644 --- a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/spotted.json +++ b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/spotted.json @@ -4,6 +4,11 @@ "tame": "minecraft:entity/wolf/wolf_spotted_tame", "wild": "minecraft:entity/wolf/wolf_spotted" }, + "baby_assets": { + "angry": "minecraft:entity/wolf/wolf_spotted_angry_baby", + "tame": "minecraft:entity/wolf/wolf_spotted_tame_baby", + "wild": "minecraft:entity/wolf/wolf_spotted_baby" + }, "spawn_conditions": [ { "condition": { diff --git a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/striped.json b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/striped.json index e413164b0..9246e1742 100644 --- a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/striped.json +++ b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/striped.json @@ -4,6 +4,11 @@ "tame": "minecraft:entity/wolf/wolf_striped_tame", "wild": "minecraft:entity/wolf/wolf_striped" }, + "baby_assets": { + "angry": "minecraft:entity/wolf/wolf_striped_angry_baby", + "tame": "minecraft:entity/wolf/wolf_striped_tame_baby", + "wild": "minecraft:entity/wolf/wolf_striped_baby" + }, "spawn_conditions": [ { "condition": { diff --git a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/woods.json b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/woods.json index 384d155f0..f304a12f8 100644 --- a/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/woods.json +++ b/platforms/mixin-common/src/main/resources/data/minecraft/wolf_variant/woods.json @@ -4,6 +4,11 @@ "tame": "minecraft:entity/wolf/wolf_woods_tame", "wild": "minecraft:entity/wolf/wolf_woods" }, + "baby_assets": { + "angry": "minecraft:entity/wolf/wolf_woods_angry_baby", + "tame": "minecraft:entity/wolf/wolf_woods_tame_baby", + "wild": "minecraft:entity/wolf/wolf_woods_baby" + }, "spawn_conditions": [ { "condition": { diff --git a/platforms/mixin-common/src/main/resources/terra.accesswidener b/platforms/mixin-common/src/main/resources/terra.accesswidener index 2bb5b5b48..49ee5c2e9 100644 --- a/platforms/mixin-common/src/main/resources/terra.accesswidener +++ b/platforms/mixin-common/src/main/resources/terra.accesswidener @@ -1,7 +1,6 @@ -accessWidener v1 named +accessWidener v2 official accessible class net/minecraft/world/level/biome/Biome$ClimateSettings accessible class net/minecraft/world/level/levelgen/presets/WorldPresets$Bootstrap accessible field net/minecraft/world/level/levelgen/WorldDimensions BUILTIN_ORDER Ljava/util/Set; -accessible class net/minecraft/resources/RegistryDataLoader$Loader extendable class net/minecraft/nbt/Tag accessible field net/minecraft/world/level/block/entity/BlockEntity TYPE_CODEC Lcom/mojang/serialization/Codec; 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 29ae1d827..c5f1fcdb6 100644 --- a/platforms/mixin-common/src/main/resources/terra.common.mixins.json +++ b/platforms/mixin-common/src/main/resources/terra.common.mixins.json @@ -2,11 +2,10 @@ "required": true, "minVersion": "0.8", "package": "com.dfsek.terra.mod.mixin", - "compatibilityLevel": "JAVA_21", + "compatibilityLevel": "JAVA_25", "mixins": [ "access.BiomeAccessor", "access.BaseSpawnerAccessor", - "access.StateHolderAccessor", "access.StructureManagerAccessor", "access.VillagerTypeAccessor", "access.LevelChunkAccessor", @@ -48,6 +47,5 @@ ], "injectors": { "defaultRequire": 1 - }, - "refmap": "terra.common.refmap.json" + } } \ No newline at end of file diff --git a/platforms/mixin-lifecycle/build.gradle.kts b/platforms/mixin-lifecycle/build.gradle.kts index 39dc6367b..cca5e654a 100644 --- a/platforms/mixin-lifecycle/build.gradle.kts +++ b/platforms/mixin-lifecycle/build.gradle.kts @@ -1,5 +1,5 @@ plugins { - id("dev.architectury.loom") version Versions.Mod.architecturyLoom + id("dev.architectury.loom-no-remap") version Versions.Mod.architecturyLoom id("architectury-plugin") version Versions.Mod.architecturyPlugin } @@ -8,15 +8,12 @@ dependencies { compileOnly("net.fabricmc:sponge-mixin:${Versions.Mod.mixin}") compileOnly("io.github.llamalad7:mixinextras-common:${Versions.Mod.mixinExtras}") - annotationProcessor("net.fabricmc:sponge-mixin:${Versions.Mod.mixin}") - annotationProcessor("dev.architectury:architectury-loom:${Versions.Mod.architecturyLoom}") - implementation(project(path = ":platforms:mixin-common", configuration = "namedElements")) { isTransitive = false } + implementation(project(":platforms:mixin-common")) { isTransitive = false } minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") - mappings(loom.officialMojangMappings()) - modImplementation("org.incendo", "cloud-fabric", Versions.Fabric.cloud) { + implementation("org.incendo", "cloud-fabric", Versions.Fabric.cloud) { exclude("net.fabricmc") exclude("net.fabricmc.fabric-api") exclude("me.lucko", "fabric-permissions-api") @@ -25,19 +22,13 @@ dependencies { loom { accessWidenerPath.set(project(":platforms:mixin-common").file("src/main/resources/terra.accesswidener")) - - mixin { - defaultRefmapName.set("terra.lifecycle.refmap.json") - } -} - -tasks { - remapJar { - inputFile.set(shadowJar.get().archiveFile) - } } architectury { common("fabric") minecraft = Versions.Mod.minecraft -} \ No newline at end of file +} + +tasks.withType().configureEach { + options.release = 25 +} diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RandomStateMixin.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RandomStateMixin.java index a7c5668ff..427ec31fe 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RandomStateMixin.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RandomStateMixin.java @@ -1,16 +1,14 @@ package com.dfsek.terra.lifecycle.mixin; -import net.minecraft.core.HolderGetter; import net.minecraft.world.level.biome.Climate.Sampler; -import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; import net.minecraft.world.level.levelgen.RandomState; -import net.minecraft.world.level.levelgen.synth.NormalNoise; +import net.minecraft.world.level.levelgen.densityfunction.SamplerContext; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import com.dfsek.terra.mod.util.SeedHack; @@ -22,13 +20,11 @@ import com.dfsek.terra.mod.util.SeedHack; public class RandomStateMixin { @Shadow @Final - private Sampler sampler; + private long seed; - @Inject(method = "(Lnet/minecraft/world/level/levelgen/NoiseGeneratorSettings;Lnet/minecraft/core/HolderGetter;J)V", - at = @At("TAIL")) - private void mapMultiNoise(NoiseGeneratorSettings chunkGeneratorSettings, - HolderGetter noiseParametersLookup, long seed, - CallbackInfo ci) { - SeedHack.register(sampler, seed); + @Inject(method = "createClimateSampler(Lnet/minecraft/world/level/levelgen/densityfunction/SamplerContext;)Lnet/minecraft/world/level/biome/Climate$Sampler;", + at = @At("RETURN")) + private void mapMultiNoise(SamplerContext context, CallbackInfoReturnable cir) { + SeedHack.register(cir.getReturnValue(), seed); } } diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RegistryLoadTaskAccessor.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RegistryLoadTaskAccessor.java new file mode 100644 index 000000000..259956212 --- /dev/null +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/RegistryLoadTaskAccessor.java @@ -0,0 +1,13 @@ +package com.dfsek.terra.lifecycle.mixin; + +import net.minecraft.core.WritableRegistry; +import net.minecraft.resources.RegistryLoadTask; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + + +@Mixin(RegistryLoadTask.class) +public interface RegistryLoadTaskAccessor { + @Accessor("registry") + WritableRegistry getRegistry(); +} diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/MinecraftServerMixin.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/MinecraftServerMixin.java index c6c07bdbc..281482a66 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/MinecraftServerMixin.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/MinecraftServerMixin.java @@ -1,29 +1,22 @@ package com.dfsek.terra.lifecycle.mixin.lifecycle; -import com.mojang.datafixers.DataFixer; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.Services; -import net.minecraft.server.WorldStem; -import net.minecraft.server.level.progress.LevelLoadListener; -import net.minecraft.server.packs.repository.PackRepository; -import net.minecraft.world.level.storage.LevelStorageSource; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import java.net.Proxy; - import com.dfsek.terra.lifecycle.LifecyclePlatform; @Mixin(MinecraftServer.class) public class MinecraftServerMixin { - @Inject(method = "(Ljava/lang/Thread;Lnet/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess;Lnet/minecraft/server/packs/repository/PackRepository;Lnet/minecraft/server/WorldStem;Ljava/net/Proxy;Lcom/mojang/datafixers/DataFixer;Lnet/minecraft/server/Services;Lnet/minecraft/server/level/progress/LevelLoadListener;)V", + @Inject(method = "(Ljava/lang/Thread;Lnet/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess;" + + "Lnet/minecraft/server/packs/repository/PackRepository;Lnet/minecraft/server/WorldStem;Ljava/util/Optional;" + + "Ljava/net/Proxy;Lcom/mojang/datafixers/DataFixer;Lnet/minecraft/server/Services;" + + "Lnet/minecraft/server/level/progress/LevelLoadListener;ZLnet/minecraft/server/notifications/NotificationManager;)V", at = @At("RETURN")) - private void injectConstructor(Thread serverThread, LevelStorageSource.LevelStorageAccess session, PackRepository dataPackManager, - WorldStem saveLoader, Proxy proxy, DataFixer dataFixer, Services apiServices, - LevelLoadListener chunkLoadProgress, CallbackInfo ci) { + private void injectConstructor(CallbackInfo ci) { LifecyclePlatform.setServer((MinecraftServer) (Object) this); } } 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 625aa2c76..539040591 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,35 +1,31 @@ package com.dfsek.terra.lifecycle.mixin.lifecycle; -import com.llamalad7.mixinextras.sugar.Local; -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.ResourceKey; -import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.resources.ResourceManagerRegistryLoadTask; import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.level.biome.Biome; 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 org.slf4j.Logger; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Coerce; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.List; +import java.util.Map; import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; 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.RegistryHack; import com.dfsek.terra.mod.CommonPlatform; @@ -38,44 +34,26 @@ import com.dfsek.terra.mod.ModPlatform; @Mixin(RegistryDataLoader.class) public class RegistryDataLoaderMixin { - - @Unique - private static final AtomicBoolean LOADING_DYNAMIC_REGISTRIES = new AtomicBoolean(false); - @Shadow - @Final - private static Logger LOGGER; - - @Inject(method = "load(Lnet/minecraft/server/packs/resources/ResourceManager;Ljava/util/List;Ljava/util/List;)Lnet/minecraft/core/RegistryAccess$Frozen;", - at = @At("HEAD")) - private static void loadFromResources(ResourceManager resourceManager, List> registries, - List> entries, - CallbackInfoReturnable cir) { - LOADING_DYNAMIC_REGISTRIES.set(entries.stream().anyMatch(entry -> entry.key() == Registries.BIOME)); - } - + // The thenApplyAsync callback in load(LoaderFactory, List, List, Executor): every registry populated, none frozen. @Inject( - method = "load(Lnet/minecraft/resources/RegistryDataLoader$LoadingFunction;Ljava/util/List;Ljava/util/List;)" + - "Lnet/minecraft/core/RegistryAccess$Frozen;", - at = @At( - value = "INVOKE", - target = "Ljava/util/List;forEach(Ljava/util/function/Consumer;)V", - ordinal = 1 - ) + method = "lambda$load$2(Ljava/util/List;Ljava/util/Map;Ljava/lang/Void;)Lnet/minecraft/core/RegistryAccess$Frozen;", + at = @At("HEAD") ) - private static void beforeFreeze(@Coerce Object loadable, List> wrappers, List> entries, - CallbackInfoReturnable cir, - @Local(ordinal = 2) List> registriesList) { - if(LOADING_DYNAMIC_REGISTRIES.getAndSet(false)) { + private static void beforeFreeze(List> loadTasks, Map, Exception> loadingErrors, Void ignored, + CallbackInfoReturnable cir) { + boolean loadingDynamicRegistries = loadTasks.stream().anyMatch( + task -> task instanceof ResourceManagerRegistryLoadTask && getRegistry(task).key() == Registries.BIOME); + if(loadingDynamicRegistries) { ModPlatform platform = CommonPlatform.get(); platform.getRawConfigRegistry().clear(); - WritableRegistry biomes = extractRegistry(registriesList, Registries.BIOME).orElseThrow(); - WritableRegistry dimensionTypes = extractRegistry(registriesList, Registries.DIMENSION_TYPE).orElseThrow(); - WritableRegistry worldPresets = extractRegistry(registriesList, Registries.WORLD_PRESET).orElseThrow(); - WritableRegistry chunkGeneratorSettings = extractRegistry(registriesList, + WritableRegistry biomes = extractRegistry(loadTasks, Registries.BIOME).orElseThrow(); + WritableRegistry dimensionTypes = extractRegistry(loadTasks, Registries.DIMENSION_TYPE).orElseThrow(); + WritableRegistry worldPresets = extractRegistry(loadTasks, Registries.WORLD_PRESET).orElseThrow(); + WritableRegistry chunkGeneratorSettings = extractRegistry(loadTasks, Registries.NOISE_SETTINGS).orElseThrow(); - WritableRegistry multiNoiseBiomeSourceParameterLists = extractRegistry(registriesList, + WritableRegistry multiNoiseBiomeSourceParameterLists = extractRegistry(loadTasks, Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST).orElseThrow(); - WritableRegistry enchantments = extractRegistry(registriesList, Registries.ENCHANTMENT).orElseThrow(); + WritableRegistry enchantments = extractRegistry(loadTasks, Registries.ENCHANTMENT).orElseThrow(); LifecyclePlatform.setRegistries(biomes, dimensionTypes, chunkGeneratorSettings, multiNoiseBiomeSourceParameterLists, enchantments); @@ -83,12 +61,17 @@ public class RegistryDataLoaderMixin { } } + @Unique + private static WritableRegistry getRegistry(RegistryLoadTask task) { + return ((RegistryLoadTaskAccessor) task).getRegistry(); + } + @Unique @SuppressWarnings("unchecked") - private static Optional> extractRegistry(List> instance, + private static Optional> extractRegistry(List> instance, ResourceKey> key) { List> matches = instance - .stream().map(RegistryDataLoader.Loader::registry) + .stream().map(RegistryDataLoaderMixin::getRegistry) .filter(r -> r.key().equals(key)) .toList(); if(matches.size() > 1) { diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/WorldLoaderMixin.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/WorldLoaderMixin.java index 2db9e067d..31c2c09de 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/WorldLoaderMixin.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/WorldLoaderMixin.java @@ -14,7 +14,12 @@ import com.dfsek.terra.mod.util.MinecraftUtil; @Mixin(WorldLoader.class) public class WorldLoaderMixin { @ModifyArg( - method = "load(Lnet/minecraft/server/WorldLoader$InitConfig;Lnet/minecraft/server/WorldLoader$WorldDataSupplier;Lnet/minecraft/server/WorldLoader$ResultFactory;Ljava/util/concurrent/Executor;Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletableFuture;", + // The innermost thenComposeAsync callback of WorldLoader.load, which builds the server resources. + method = "lambda$load$2(Lcom/mojang/datafixers/util/Pair;Ljava/util/List;Lnet/minecraft/server/WorldLoader$WorldDataSupplier;" + + "Lnet/minecraft/server/packs/resources/CloseableResourceManager;Lnet/minecraft/core/LayeredRegistryAccess;" + + "Lnet/minecraft/core/RegistryAccess$Frozen;Ljava/util/List;Lnet/minecraft/server/WorldLoader$InitConfig;" + + "Ljava/util/concurrent/Executor;Ljava/util/concurrent/Executor;Lnet/minecraft/server/WorldLoader$ResultFactory;" + + "Lnet/minecraft/core/RegistryAccess$Frozen;)Ljava/util/concurrent/CompletionStage;", at = @At( value = "INVOKE", target = "Lnet/minecraft/server/ReloadableServerResources;loadResources(Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/core/LayeredRegistryAccess;Ljava/util/List;Lnet/minecraft/world/flag/FeatureFlagSet;Lnet/minecraft/commands/Commands$CommandSelection;Lnet/minecraft/server/permissions/PermissionSet;Ljava/util/concurrent/Executor;Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletableFuture;"), 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 a37090d7f..6350190b1 100644 --- a/platforms/mixin-lifecycle/src/main/resources/terra.lifecycle.mixins.json +++ b/platforms/mixin-lifecycle/src/main/resources/terra.lifecycle.mixins.json @@ -2,10 +2,11 @@ "required": true, "minVersion": "0.8", "package": "com.dfsek.terra.lifecycle.mixin", - "compatibilityLevel": "JAVA_21", + "compatibilityLevel": "JAVA_25", "mixins": [ "RandomStateMixin", "HolderReferenceInvoker", + "RegistryLoadTaskAccessor", "BuiltInRegistriesMixin", "MappedRegistryMixin", "lifecycle.MinecraftServerMixin", @@ -16,6 +17,5 @@ ], "injectors": { "defaultRequire": 1 - }, - "refmap": "terra.lifecycle.refmap.json" + } } \ No newline at end of file From ad1d4870327d981a87ac006f455f9216d07e8b4f Mon Sep 17 00:00:00 2001 From: Zoe Gidiere Date: Sat, 7 Nov 2026 15:10:55 -0700 Subject: [PATCH 37/44] feat: finish Wyck port for Paper 26.3 --- buildSrc/src/main/kotlin/Versions.kt | 1 - .../com/dfsek/terra/AbstractPlatform.java | 7 + .../terra/registry/master/ConfigRegistry.java | 2 +- .../registry/master/MetaConfigRegistry.java | 2 +- platforms/bukkit/build.gradle.kts | 1 - platforms/bukkit/common/build.gradle.kts | 2 - .../com/dfsek/terra/bukkit/BukkitEntity.java | 5 +- .../dfsek/terra/bukkit/BukkitPlatform.java | 18 +- .../com/dfsek/terra/bukkit/BukkitPlayer.java | 5 +- .../terra/bukkit/CloudCommandSender.java | 10 +- .../dfsek/terra/bukkit/TerraBootstrapper.java | 94 --------- .../dfsek/terra/bukkit/TerraBukkitPlugin.java | 101 ++-------- .../config/BiomeParticleConfigTemplate.java | 26 ++- .../terra/bukkit/config/SpawnEntryConfig.java | 9 +- .../bukkit/config/SpawnSettingsTemplate.java | 25 ++- .../bukkit/generator/BukkitBiomeProvider.java | 14 +- .../BukkitChunkGeneratorWrapper.java | 52 +++-- .../bukkit/handles/BukkitItemHandle.java | 15 +- .../bukkit/handles/BukkitWorldHandle.java | 20 +- .../terra/bukkit/listeners/BiomeListener.java | 73 +++++++ .../bukkit/listeners/SpigotListener.java | 104 ---------- .../terra/bukkit/util/BukkitNMSAccess.java | 16 -- .../dfsek/terra/bukkit/util/BukkitUtils.java | 86 +++++--- .../terra/bukkit/util/MinecraftUtils.java | 25 --- .../dfsek/terra/bukkit/util/PaperUtil.java | 37 ---- .../terra/bukkit/util/VanillaParticles.java | 86 ++++++++ .../dfsek/terra/bukkit/util/VersionUtil.java | 134 ------------ .../terra/bukkit/world/BiomeHandler.java | 190 ++++++++++++------ .../terra/bukkit/world/BukkitBiomeInfo.java | 2 +- .../bukkit/world/BukkitBiomeProvider.java | 40 ---- .../bukkit/world/block/state/BukkitSign.java | 16 +- .../src/main/resources/paper-plugin.yml | 8 +- 32 files changed, 504 insertions(+), 722 deletions(-) delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBootstrapper.java create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/BiomeListener.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/SpigotListener.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitNMSAccess.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/MinecraftUtils.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/PaperUtil.java create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VanillaParticles.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VersionUtil.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeProvider.java diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index 601f09c6f..2a8fa889a 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -62,7 +62,6 @@ object Versions { const val minecraft = "26.3" const val paperBuild = "$minecraft.build.244-stable" const val paper = paperBuild - const val paperLib = "1.0.8" const val runPaper = "3.0.2" const val wyck = "4.0.0-837d6ec" const val cloud = "2.0.1" diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java b/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java index aae1bc3ad..9a4097108 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java @@ -89,6 +89,11 @@ public abstract class AbstractPlatform implements Platform { private static final MutableBoolean LOADED = new MutableBoolean(false); private static final String moonrise = "Moonrise"; + private static final String PACK_LOAD_FAILURE_QUOTE = """ + > I felt a great disturbance in the JVM, as if millions of plugins suddenly cried out in stack traces and were suddenly silenced. + > I fear something terrible has happened. + > - Astrash + """.strip(); private final EventManager eventManager = new EventManagerImpl(); private final ConfigRegistry configRegistry = new ConfigRegistry(); private final MetaConfigRegistry metaConfigRegistry = new MetaConfigRegistry(); @@ -215,6 +220,7 @@ public abstract class AbstractPlatform implements Platform { return false; } catch(PackLoadFailuresException e) { e.getExceptions().forEach(ex -> logger.error("Failed to load config pack", ex)); + logger.error(PACK_LOAD_FAILURE_QUOTE); return false; } return true; @@ -231,6 +237,7 @@ public abstract class AbstractPlatform implements Platform { return false; } catch(PackLoadFailuresException e) { e.getExceptions().forEach(ex -> logger.error("Failed to meta load config pack", ex)); + logger.error(PACK_LOAD_FAILURE_QUOTE); return false; } return true; diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java index 08343d59f..2d39ead5d 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/ConfigRegistry.java @@ -68,7 +68,7 @@ public class ConfigRegistry extends OpenRegistryImpl implements Exte @Override public boolean validatePathIsMember(Path path) { - return Files.isDirectory(path)|| path.getFileName().endsWith(".zip"); + return Files.isDirectory(path)|| path.getFileName().toString().endsWith(".zip"); } public static class PackLoadFailuresException extends Exception { diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java index 65a416400..ed129b0ab 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/master/MetaConfigRegistry.java @@ -68,6 +68,6 @@ public class MetaConfigRegistry extends OpenRegistryImpl implements Ex @Override public boolean validatePathIsMember(Path path) { - return Files.isDirectory(path) || path.getFileName().endsWith(".zip"); + return Files.isDirectory(path) || path.getFileName().toString().endsWith(".zip"); } } diff --git a/platforms/bukkit/build.gradle.kts b/platforms/bukkit/build.gradle.kts index c4f32a13b..19e82e6ae 100644 --- a/platforms/bukkit/build.gradle.kts +++ b/platforms/bukkit/build.gradle.kts @@ -12,7 +12,6 @@ tasks.withType().configureEach { tasks { shadowJar { - relocate("io.papermc.lib", "com.dfsek.terra.lib.paperlib") relocate("com.google.common", "com.dfsek.terra.lib.google.common") relocate("org.apache.logging.slf4j", "com.dfsek.terra.lib.slf4j-over-log4j") exclude("org/slf4j/**") diff --git a/platforms/bukkit/common/build.gradle.kts b/platforms/bukkit/common/build.gradle.kts index 3a5a1b10d..3a3d3805a 100644 --- a/platforms/bukkit/common/build.gradle.kts +++ b/platforms/bukkit/common/build.gradle.kts @@ -14,8 +14,6 @@ dependencies { compileOnly("org.mvplugins.multiverse.core", "multiverse-core", Versions.Bukkit.multiverse) - shadedApi("io.papermc", "paperlib", Versions.Bukkit.paperLib) - shadedApi("com.google.guava", "guava", Versions.Libraries.Internal.guava) shadedApi("org.incendo", "cloud-paper", Versions.Bukkit.cloud) diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitEntity.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitEntity.java index 7303e09fc..6bbdab9af 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitEntity.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitEntity.java @@ -18,7 +18,6 @@ package com.dfsek.terra.bukkit; import com.dfsek.seismic.type.vector.Vector3; -import io.papermc.lib.PaperLib; import org.bukkit.Location; import com.dfsek.terra.api.entity.Entity; @@ -45,14 +44,14 @@ public class BukkitEntity implements Entity { @Override public void position(Vector3 location) { - PaperLib.teleportAsync(entity, BukkitAdapter.adapt(location).toLocation(entity.getWorld())); + entity.teleportAsync(BukkitAdapter.adapt(location).toLocation(entity.getWorld())); } @Override public void world(ServerWorld world) { Location newLoc = entity.getLocation().clone(); newLoc.setWorld(BukkitAdapter.adapt(world)); - PaperLib.teleportAsync(entity, newLoc); + entity.teleportAsync(newLoc); } @Override diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java index 67ec084e2..b3491ef77 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java @@ -66,6 +66,7 @@ import com.dfsek.terra.api.world.biome.PlatformBiome; import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper; import com.dfsek.terra.bukkit.handles.BukkitItemHandle; import com.dfsek.terra.bukkit.handles.BukkitWorldHandle; +import com.dfsek.terra.bukkit.world.BiomeHandler; import com.dfsek.terra.bukkit.world.BukkitPlatformBiome; @@ -97,6 +98,8 @@ public class BukkitPlatform extends AbstractPlatform { public boolean reload() { getTerraConfig().load(this); boolean succeed = loadConfigPacks(); + BiomeHandler.registerBiomes(getRawConfigRegistry()); + BiomeHandler.addToVanillaTags(getRawConfigRegistry()); Bukkit.getWorlds().forEach(world -> { if(world.getGenerator() instanceof BukkitChunkGeneratorWrapper wrapper) { @@ -149,19 +152,16 @@ public class BukkitPlatform extends AbstractPlatform { public void register(TypeRegistry registry) { super.register(registry); registry.registerLoader(BlockState.class, (type, o, loader, depthTracker) -> handle.createBlockState((String) o)) - .registerLoader(PlatformBiome.class, (type, o, loader, depthTracker) -> parseBiome((String) o, depthTracker)) - .registerLoader(EntityType.class, (type, o, loader, depthTracker) -> EntityType.valueOf((String) o)) .registerLoader(PlatformBiome.class, (type, o, loader, depthTracker) -> parseBiome((String) o, depthTracker)) .registerLoader(ResourceKey.class, (type, o, loader, depthTracker) -> { - String[] parts = ((String) o).split(":", 2); - if(parts.length == 0 || parts.length > 2) - throw new LoadException("Invalid identifier: " + o, depthTracker); - return ResourceKey.of(parts[0], parts[1]); + NamespacedKey key = NamespacedKey.fromString(((String) o).toLowerCase(Locale.ROOT)); + if(key == null) throw new LoadException("Invalid identifier: " + o, depthTracker); + return ResourceKey.of(key); }) .registerLoader(GrassColorModifier.class, (type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase( Locale.ROOT))) - .registerLoader(GrassColorModifier.class, + .registerLoader(TemperatureModifier.class, (type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase( Locale.ROOT))) .registerLoader(MobCategory.class, (type, o, loader, depthTracker) -> MobCategory.valueOf((String) o)) @@ -181,6 +181,8 @@ public class BukkitPlatform extends AbstractPlatform { protected BukkitPlatformBiome parseBiome(String id, DepthTracker depthTracker) throws LoadException { NamespacedKey key = NamespacedKey.fromString(id); if(key == null || !key.namespace().equals("minecraft")) throw new LoadException("Invalid biome identifier " + id, depthTracker); - return new BukkitPlatformBiome(RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME).getOrThrow(key)); + org.bukkit.block.Biome biome = RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME).get(key); + if(biome == null) throw new LoadException("No such biome " + id, depthTracker); + return new BukkitPlatformBiome(biome); } } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlayer.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlayer.java index cdcd1efd7..28a35ba8a 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlayer.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlayer.java @@ -18,7 +18,6 @@ package com.dfsek.terra.bukkit; import com.dfsek.seismic.type.vector.Vector3; -import io.papermc.lib.PaperLib; import org.bukkit.Location; import com.dfsek.terra.api.entity.Player; @@ -46,14 +45,14 @@ public class BukkitPlayer implements Player { @Override public void position(Vector3 location) { - PaperLib.teleportAsync(delegate, BukkitAdapter.adapt(location).toLocation(delegate.getWorld())); + delegate.teleportAsync(BukkitAdapter.adapt(location).toLocation(delegate.getWorld())); } @Override public void world(ServerWorld world) { Location newLoc = delegate.getLocation().clone(); newLoc.setWorld(BukkitAdapter.adapt(world)); - PaperLib.teleportAsync(delegate, newLoc); + delegate.teleportAsync(newLoc); } @Override diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/CloudCommandSender.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/CloudCommandSender.java index 9a08402b4..5e51897fa 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/CloudCommandSender.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/CloudCommandSender.java @@ -1,7 +1,7 @@ package com.dfsek.terra.bukkit; import io.papermc.paper.command.brigadier.CommandSourceStack; -import org.bukkit.ChatColor; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import java.util.Optional; @@ -12,6 +12,12 @@ import com.dfsek.terra.bukkit.world.BukkitAdapter; public class CloudCommandSender implements CommandSender { + private static final LegacyComponentSerializer LEGACY_AMPERSAND = LegacyComponentSerializer.builder() + .character(LegacyComponentSerializer.AMPERSAND_CHAR) + .hexColors() + .useUnusualXRepeatedCharacterHexFormat() + .build(); + private final CommandSourceStack delegate; public CloudCommandSender(CommandSourceStack delegate) { @@ -20,7 +26,7 @@ public class CloudCommandSender implements CommandSender { @Override public void sendMessage(String message) { - delegate.getSender().sendMessage(ChatColor.translateAlternateColorCodes('&', message)); + delegate.getSender().sendMessage(LEGACY_AMPERSAND.deserialize(message)); } @Override diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBootstrapper.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBootstrapper.java deleted file mode 100644 index 2a393d9ac..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBootstrapper.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.dfsek.terra.bukkit; - -import com.dfsek.terra.bukkit.config.VanillaBiomeProperties; -import com.dfsek.terra.bukkit.world.BukkitBiomeInfo; -import com.dfsek.terra.bukkit.world.BukkitPlatformBiome; -import com.dfsek.terra.bukkit.world.BiomeHandler; -import com.dfsek.terra.registry.master.ConfigRegistry; - -import dev.wyck.biome.Biome; -import dev.wyck.keys.ResourceKey; -import dev.wyck.registry.bootstrap.BootstrapBiomeRegistry; -import dev.wyck.registry.bootstrap.Composer; -import dev.wyck.tags.TagSet; -import io.papermc.paper.plugin.bootstrap.BootstrapContext; -import io.papermc.paper.plugin.bootstrap.PluginBootstrap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class TerraBootstrapper implements PluginBootstrap { - private static final Logger LOGGER = LoggerFactory.getLogger(TerraBootstrapper.class); - - private static final Map> terraBiomeMap = new HashMap<>(); - - @Override - public void bootstrap(BootstrapContext context) { - BootstrapBiomeRegistry registry = BootstrapBiomeRegistry.compose(context, Composer.DATAPACK); - - registry.deferring(() -> { - registerBiomes(context, ); // TODO: Get raw config registry instance here - }); - } - - public static void registerBiomes(BootstrapContext context, ConfigRegistry configRegistry) { - BootstrapBiomeRegistry biomeRegistry = BootstrapBiomeRegistry.compose(context, Composer.DATAPACK); - - // Register the terra biomes to the registry - configRegistry.forEach(pack -> pack.getRegistry(com.dfsek.terra.api.world.biome.Biome.class).forEach((key, biome) -> { - try { - BukkitPlatformBiome platformBiome = (BukkitPlatformBiome) biome.getPlatformBiome(); - ResourceKey vanillaMinecraftKey = ResourceKey.of(platformBiome.getHandle().getKey()); - VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class); - Biome wyckBiome = BiomeHandler.createBiome(vanillaMinecraftKey, vanillaBiomeProperties); - - ResourceKey delegateKey = ResourceKey.of("terra", BiomeHandler.createBiomeID(pack, key)); - - biomeRegistry.queue(wyckBiome); - - platformBiome.getContext().put(new BukkitBiomeInfo(delegateKey)); - - // TODO: Reimplement VillagerTypes - ideally this could be made into an EnvironmentAttribute in Wyck - // Map, ResourceKey> villagerMap = Reflection.VILLAGER_TYPE.getByBiome(); - // - // villagerMap.put(delegateKey, - // Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(), - // villagerMap.getOrDefault(delegateKey, VillagerType.PLAINS))); - - terraBiomeMap.computeIfAbsent(vanillaMinecraftKey, i -> new ArrayList<>()).add(delegateKey.identifier()); - - LOGGER.debug("Registered biome: " + delegateKey); - } catch(NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } - })); - - // Add each terra biome to the same tag sets as it's associated vanilla biome - terraBiomeMap.forEach((vb, terraBiomes) -> { - Biome vanilla = BiomeHandler.getBiome(vb); - if(vanilla != null) { - terraBiomes.forEach(tb -> { - Biome terra = BiomeHandler.getBiome(tb); - if(terra != null) { - LOGGER.debug("{} (vanilla for {}): {}", - vanilla.resourceKey().identifier(), - terra.resourceKey().identifier(), - vanilla.tags().toList()); - - vanilla.tags() // TODO: Waiting on implementation from Wyck - .forEach(tag -> TagSet.ofBiomes(tag.key(), terra).append()); - } else { - LOGGER.error("No such biome: {}", tb); - } - }); - } else { - LOGGER.error("No vanilla biome: {}", vb); - } - }); - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java index a0c877081..5caa27e39 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java @@ -17,7 +17,8 @@ package com.dfsek.terra.bukkit; -import io.papermc.paper.threadedregions.scheduler.AsyncScheduler; +import io.papermc.paper.ServerBuildInfo; +import io.papermc.paper.ServerBuildInfo.StringRepresentation; import io.papermc.paper.threadedregions.scheduler.GlobalRegionScheduler; import org.bukkit.Bukkit; import org.bukkit.generator.ChunkGenerator; @@ -32,16 +33,15 @@ import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; -import java.util.concurrent.TimeUnit; import com.dfsek.terra.api.command.CommandSender; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.event.events.platform.CommandRegistrationEvent; import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent; import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper; +import com.dfsek.terra.bukkit.listeners.BiomeListener; import com.dfsek.terra.bukkit.listeners.CommonListener; -import com.dfsek.terra.bukkit.util.PaperUtil; -import com.dfsek.terra.bukkit.util.VersionUtil; +import com.dfsek.terra.bukkit.world.BiomeHandler; import com.dfsek.terra.bukkit.world.BukkitAdapter; @@ -49,18 +49,15 @@ public class TerraBukkitPlugin extends JavaPlugin { private static final Logger logger = LoggerFactory.getLogger(TerraBukkitPlugin.class); private final Map generatorMap = new HashMap<>(); private BukkitPlatform platform; - private AsyncScheduler asyncScheduler = this.getServer().getAsyncScheduler(); - - private GlobalRegionScheduler globalRegionScheduler = this.getServer().getGlobalRegionScheduler(); @Override public void onEnable() { - if(!doVersionCheck()) { - return; - } + logServerVersion(); platform = new BukkitPlatform(this); - platform.getEventManager().callEvent(new PlatformInitializationEvent()); + platform.getEventManager().callEvent(new PlatformInitializationEvent()); // Loads config packs + BiomeHandler.registerBiomes(platform.getRawConfigRegistry()); + BiomeHandler.addToVanillaTags(platform.getRawConfigRegistry()); try { PaperCommandManager commandManager = getCommandSenderPaperCommandManager(); @@ -79,7 +76,7 @@ public class TerraBukkitPlugin extends JavaPlugin { } Bukkit.getPluginManager().registerEvents(new CommonListener(platform), this); // Register master event listener - PaperUtil.checkPaper(this); + Bukkit.getPluginManager().registerEvents(new BiomeListener(platform), this); } @NotNull @@ -100,76 +97,10 @@ public class TerraBukkitPlugin extends JavaPlugin { return platform; } - @SuppressWarnings({ "deprecation", "AccessOfSystemProperties" }) - private boolean doVersionCheck() { - logger.info("Running on Minecraft version {} with server implementation {}.", VersionUtil.getMinecraftVersionInfo(), - Bukkit.getServer().getName()); - - if(!VersionUtil.getSpigotVersionInfo().isSpigot()) - logger.error("YOU ARE RUNNING A CRAFTBUKKIT OR BUKKIT SERVER. PLEASE UPGRADE TO PAPER."); - - if(!VersionUtil.getSpigotVersionInfo().isPaper()) - logger.error("YOU ARE RUNNING A SPIGOT SERVER. PLEASE UPGRADE TO PAPER."); - - if(VersionUtil.getSpigotVersionInfo().isMohist()) { - if(System.getProperty("IKnowMohistCausesLotsOfIssuesButIWillUseItAnyways") == null) { - Runnable runnable = () -> { // scary big block of text - logger.error(""" - .----------------------------------------------------------------------------------. - | | - | âš  !! Warning !! âš  | - | | - | You are currently using Mohist. | - | | - | Do not use Mohist. | - | | - | The concept of combining the rigid Bukkit platform, which assumes a 100% | - | Vanilla server, with the flexible Forge platform, which allows changing | - | core components of the game, simply does not work. These platforms are | - | incompatible at a conceptual level, the only way to combine them would | - | be to make incompatible changes to both. As a result, Mohist's Bukkit | - | API implementation is not compliant. This will cause many plugins to | - | break. Rather than fix their platform, Mohist has chosen to distribute | - | unofficial builds of plugins they deem to be "fixed". These builds are not | - | "fixed", they are simply hacked together to work with Mohist's half-baked | - | Bukkit implementation. To distribute these as "fixed" versions implies that: | - | - These builds are endorsed by the original developers. (They are not) | - | - The issue is on the plugin's end, not Mohist's. (It is not. The issue | - | is that Mohist chooses to not create a compliant Bukkit implementation) | - | Please, do not use Mohist. It causes issues with most plugins, and rather | - | than fixing their platform, Mohist has chosen to distribute unofficial | - | hacked-together builds of plugins, calling them "fixed". If you want | - | to use a server API with Forge mods, look at the Sponge project, an | - | API that is designed to be implementation-agnostic, with first-party | - | support for the Forge mod loader. You are bound to encounter issues if | - | you use Terra with Mohist. We will provide NO SUPPORT for servers running | - | Mohist. If you wish to proceed anyways, you can add the JVM System Property | - | "IKnowMohistCausesLotsOfIssuesButIWillUseItAnyways" to enable the plugin. No | - | support will be provided for servers running Mohist. | - | | - | Because of this **TERRA HAS BEEN DISABLED**. | - | Do not come ask us why it is not working. | - | | - |----------------------------------------------------------------------------------| - """.strip()); - }; - runnable.run(); - asyncScheduler.runDelayed(this, task -> runnable.run(), 200L, TimeUnit.SECONDS); - // Bukkit.shutdown(); // we're not *that* evil - Bukkit.getPluginManager().disablePlugin(this); - return false; - } else { - logger.warn(""" - You are using Mohist, so we will not give you any support for issues that may arise. - Since you enabled the "IKnowMohistCausesLotsOfIssuesButIWillUseItAnyways" flag, we won't disable Terra. But be warned. - - > I felt a great disturbance in the JVM, as if millions of plugins suddenly cried out in stack traces and were suddenly silenced. - > I fear something terrible has happened. - > - Astrash - """.strip()); - } - } - return true; + private void logServerVersion() { + ServerBuildInfo buildInfo = ServerBuildInfo.buildInfo(); + logger.info("Running on Minecraft version {} with server implementation {} {}.", buildInfo.minecraftVersionName(), + buildInfo.brandName(), buildInfo.asString(StringRepresentation.VERSION_SIMPLE)); } @Override @@ -183,11 +114,7 @@ public class TerraBukkitPlugin extends JavaPlugin { }), platform.getRawConfigRegistry().getByID(id).orElseThrow(), platform.getWorldHandle().air()); } - public AsyncScheduler getAsyncScheduler() { - return asyncScheduler; - } - public GlobalRegionScheduler getGlobalRegionScheduler() { - return globalRegionScheduler; + return getServer().getGlobalRegionScheduler(); } } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeParticleConfigTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeParticleConfigTemplate.java index a0227b356..bf567032c 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeParticleConfigTemplate.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeParticleConfigTemplate.java @@ -3,12 +3,20 @@ package com.dfsek.terra.bukkit.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 dev.wyck.environment.particle.AmbientParticle; import dev.wyck.environment.particle.ParticleCatalog; -import dev.wyck.environment.particle.ParticleOptions; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import com.dfsek.terra.bukkit.util.VanillaParticles; public class BiomeParticleConfigTemplate implements ObjectTemplate { + private static final Logger LOGGER = LoggerFactory.getLogger(BiomeParticleConfigTemplate.class); + @Value("particle") @Default private String particle = null; @@ -21,12 +29,14 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate { return weight; } - public SpawnerData getSpawnEntry() { - return SpawnerData.of(type, IntProvider.uniform(groupSize.getMin(), groupSize.getMax())); + public EntityType getType() { + return type; + } + + public IntProvider getCount() { + return IntProvider.uniform(groupSize.getMin(), groupSize.getMax()); } @Override diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnSettingsTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnSettingsTemplate.java index 2598dfd08..686524c28 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnSettingsTemplate.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnSettingsTemplate.java @@ -9,12 +9,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; public class SpawnSettingsTemplate implements ObjectTemplate { - private static final Logger logger = LoggerFactory.getLogger(SpawnTypeConfig.class); - private static boolean used = false; + private static final Logger LOGGER = LoggerFactory.getLogger(SpawnSettingsTemplate.class); + private static final AtomicBoolean PROBABILITY_WARNING_LOGGED = new AtomicBoolean(false); @Value("spawns") @Default @@ -31,17 +32,21 @@ public class SpawnSettingsTemplate implements ObjectTemplate { @Override public MobSpawnSettings get() { MobSpawnSettings.Builder builder = MobSpawnSettings.builder(); - for(SpawnTypeConfig spawn : spawns) { - MobCategory group = spawn.getGroup(); - for(SpawnEntryConfig entry : spawn.getEntries()) { - builder.addSpawn(group, entry.getWeight(), entry.getSpawnEntry()); + if(spawns != null) { + for(SpawnTypeConfig spawn : spawns) { + MobCategory group = spawn.getGroup(); + for(SpawnEntryConfig entry : spawn.getEntries()) { + builder.addSpawn(entry.getType(), group, entry.getWeight(), entry.getCount()); + } } } - for(SpawnCostConfig cost : costs) { - builder.addMobSpawnCost(cost.getType(), cost.getMass(), cost.getGravity()); + if(costs != null) { + for(SpawnCostConfig cost : costs) { + builder.addMobSpawnCost(cost.getType(), cost.getMass(), cost.getGravity()); + } } - if(probability != null) { - builder.creatureGenerationProbability(probability); + if(probability != null && PROBABILITY_WARNING_LOGGED.compareAndSet(false, true)) { + LOGGER.warn("Biome spawning.probability is ignored on this server version."); } return builder.build(); diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBiomeProvider.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBiomeProvider.java index cb59ca8d5..04c8f3be9 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBiomeProvider.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBiomeProvider.java @@ -10,6 +10,8 @@ import java.util.stream.StreamSupport; import com.dfsek.terra.api.Handle; import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.bukkit.world.BukkitBiomeInfo; +import com.dfsek.terra.bukkit.world.BukkitPlatformBiome; public class BukkitBiomeProvider extends BiomeProvider implements Handle { @@ -19,17 +21,23 @@ public class BukkitBiomeProvider extends BiomeProvider implements Handle { @Override public @NotNull org.bukkit.block.Biome getBiome(@NotNull WorldInfo worldInfo, int x, int y, int z) { - Biome biome = delegate.getBiome(x, y, z, worldInfo.getSeed()); - return (org.bukkit.block.Biome) biome.getPlatformBiome().getHandle(); + return toBukkit(delegate.getBiome(x, y, z, worldInfo.getSeed())); } @Override public @NotNull List getBiomes(@NotNull WorldInfo worldInfo) { return StreamSupport.stream(delegate.getBiomes().spliterator(), false) - .map(terraBiome -> (org.bukkit.block.Biome) terraBiome.getPlatformBiome().getHandle()) + .map(BukkitBiomeProvider::toBukkit) .collect(Collectors.toList()); } + private static org.bukkit.block.Biome toBukkit(Biome biome) { + BukkitPlatformBiome platformBiome = (BukkitPlatformBiome) biome.getPlatformBiome(); + return platformBiome.getContext().has(BukkitBiomeInfo.class) + ? platformBiome.getContext().get(BukkitBiomeInfo.class).bukkitBiome() + : platformBiome.getHandle(); + } + @Override public Object getHandle() { return delegate; diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitChunkGeneratorWrapper.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitChunkGeneratorWrapper.java index bd6796bad..7f60527aa 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitChunkGeneratorWrapper.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitChunkGeneratorWrapper.java @@ -17,7 +17,12 @@ package com.dfsek.terra.bukkit.generator; +import org.bukkit.HeightMap; +import org.bukkit.Material; +import org.bukkit.Tag; import org.bukkit.World; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.Waterlogged; import org.bukkit.generator.BiomeProvider; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.WorldInfo; @@ -33,8 +38,9 @@ import com.dfsek.terra.api.block.state.BlockState; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.world.chunk.generation.ChunkGenerator; import com.dfsek.terra.api.world.chunk.generation.util.GeneratorWrapper; -import com.dfsek.terra.api.world.info.WorldProperties; +import com.dfsek.terra.bukkit.util.BukkitUtils; import com.dfsek.terra.bukkit.world.BukkitWorldProperties; +import com.dfsek.terra.bukkit.world.block.data.BukkitBlockState; public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGenerator implements GeneratorWrapper { @@ -67,6 +73,32 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener delegate.generateChunkData(new BukkitProtoChunk(chunkData), properties, pack.getBiomeProvider(), x, z); } + @Override + public int getBaseHeight(@NotNull WorldInfo worldInfo, @NotNull Random random, int x, int z, @NotNull HeightMap heightMap) { + BukkitWorldProperties properties = new BukkitWorldProperties(worldInfo); + com.dfsek.terra.api.world.biome.generation.BiomeProvider biomeProvider = pack.getBiomeProvider(); + int y = properties.getMaxHeight(); + while(y > properties.getMinHeight() && + !isHeightmapBlock(heightMap, ((BukkitBlockState) delegate.getBlock(properties, x, y - 1, z, biomeProvider)).getHandle())) { + y--; + } + return y; + } + + private static boolean isHeightmapBlock(HeightMap heightMap, BlockData data) { + Material material = data.getMaterial(); + return switch(heightMap) { + case WORLD_SURFACE, WORLD_SURFACE_WG -> !material.isAir(); + case OCEAN_FLOOR, OCEAN_FLOOR_WG -> material.isSolid(); + case MOTION_BLOCKING -> material.isSolid() || hasFluid(data); + case MOTION_BLOCKING_NO_LEAVES -> (material.isSolid() || hasFluid(data)) && !Tag.LEAVES.isTagged(material); + }; + } + + private static boolean hasFluid(BlockData data) { + return BukkitUtils.isLiquid(data) || (data instanceof Waterlogged waterlogged && waterlogged.isWaterlogged()); + } + @Override public @NotNull List getDefaultPopulators(@NotNull World world) { return List.of(blockPopulator); @@ -106,22 +138,4 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener public ChunkGenerator getHandle() { return delegate; } - - - private record SeededVector(int x, int z, WorldProperties worldProperties) { - @Override - public boolean equals(Object obj) { - if(obj instanceof SeededVector that) { - return this.z == that.z && this.x == that.x && this.worldProperties.equals(that.worldProperties); - } - return false; - } - - @Override - public int hashCode() { - int code = x; - code = 31 * code + z; - return 31 * code + worldProperties.hashCode(); - } - } } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitItemHandle.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitItemHandle.java index 35b99a0fc..92b4c61df 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitItemHandle.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitItemHandle.java @@ -17,17 +17,18 @@ package com.dfsek.terra.bukkit.handles; +import io.papermc.paper.registry.RegistryAccess; +import io.papermc.paper.registry.RegistryKey; import org.bukkit.Material; import org.bukkit.NamespacedKey; +import org.bukkit.Registry; -import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; import com.dfsek.terra.api.handle.ItemHandle; import com.dfsek.terra.api.inventory.Item; import com.dfsek.terra.api.inventory.item.Enchantment; -import com.dfsek.terra.bukkit.util.MinecraftUtils; import com.dfsek.terra.bukkit.world.BukkitAdapter; @@ -40,12 +41,16 @@ public class BukkitItemHandle implements ItemHandle { @Override public Enchantment getEnchantment(String id) { - return BukkitAdapter.adapt( - org.bukkit.enchantments.Enchantment.getByKey(NamespacedKey.minecraft(MinecraftUtils.stripMinecraftNamespace(id)))); + NamespacedKey key = NamespacedKey.fromString(id); + return BukkitAdapter.adapt(key == null ? null : enchantments().get(key)); } @Override public Set getEnchantments() { - return Arrays.stream(org.bukkit.enchantments.Enchantment.values()).map(BukkitAdapter::adapt).collect(Collectors.toSet()); + return enchantments().stream().map(BukkitAdapter::adapt).collect(Collectors.toSet()); + } + + private static Registry enchantments() { + return RegistryAccess.registryAccess().getRegistry(RegistryKey.ENCHANTMENT); } } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitWorldHandle.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitWorldHandle.java index 3ad138d83..5fee3d9d7 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitWorldHandle.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitWorldHandle.java @@ -19,7 +19,6 @@ package com.dfsek.terra.bukkit.handles; import org.bukkit.Bukkit; import org.bukkit.Material; -import org.bukkit.block.data.BlockData; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,8 +29,6 @@ import com.dfsek.terra.api.handle.WorldHandle; import com.dfsek.terra.bukkit.util.BukkitUtils; import com.dfsek.terra.bukkit.world.block.data.BukkitBlockState; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; public class BukkitWorldHandle implements WorldHandle { @@ -44,18 +41,13 @@ public class BukkitWorldHandle implements WorldHandle { @Override public synchronized @NotNull BlockState createBlockState(@NotNull String data) { + // BlockData can't hold block entity NBT. + int nbtStart = data.indexOf('{'); + String state = nbtStart >= 0 ? data.substring(0, nbtStart) : data; try { - org.bukkit.block.data.BlockData bukkitData = Bukkit.createBlockData(data); // somehow bukkit managed to make this not thread safe! :) - return BukkitBlockState.newInstance(bukkitData); - } catch (Exception ignored) { - try { - Class hacks = Class.forName("com.dfsek.terra.bukkit.nms.AwfulBukkitHacks"); - Method method = hacks.getMethod("createBlockState", String.class); - Object result = method.invoke(null, data); - return BukkitBlockState.newInstance((BlockData) result); - } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - throw new IllegalArgumentException("Invalid block state data: " + data); - } + return BukkitBlockState.newInstance(Bukkit.createBlockData(state)); // somehow bukkit managed to make this not thread safe! :) + } catch(IllegalArgumentException e) { + throw new IllegalArgumentException("Invalid block state data: " + data, e); } } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/BiomeListener.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/BiomeListener.java new file mode 100644 index 000000000..7e7321f7b --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/BiomeListener.java @@ -0,0 +1,73 @@ +package com.dfsek.terra.bukkit.listeners; + +import io.papermc.paper.event.server.ServerResourcesReloadedEvent; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Villager; +import org.bukkit.entity.ZombieVillager; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; +import org.bukkit.event.entity.EntityBreedEvent; + +import java.util.Set; + +import com.dfsek.terra.bukkit.BukkitPlatform; +import com.dfsek.terra.bukkit.world.BiomeHandler; + + +public class BiomeListener implements Listener { + private static final Set BIOME_TYPED_VILLAGER_REASONS = Set.of( + SpawnReason.SPAWNER_EGG, SpawnReason.DISPENSE_EGG, SpawnReason.SPAWNER, SpawnReason.COMMAND); + + private final BukkitPlatform platform; + + public BiomeListener(BukkitPlatform platform) { + this.platform = platform; + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onResourcesReloaded(ServerResourcesReloadedEvent event) { + BiomeHandler.addToVanillaTags(platform.getRawConfigRegistry()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onCreatureSpawn(CreatureSpawnEvent event) { + SpawnReason reason = event.getSpawnReason(); + if(event.getEntity() instanceof Villager villager && BIOME_TYPED_VILLAGER_REASONS.contains(reason)) { + applyBiomeType(villager); + } else if(event.getEntity() instanceof ZombieVillager zombieVillager && reason != SpawnReason.INFECTION) { + Villager.Type type = biomeType(zombieVillager); + if(type != null && zombieVillager.getVillagerType() == Villager.Type.PLAINS) { + zombieVillager.setVillagerType(type); + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBreed(EntityBreedEvent event) { + if(event.getEntity() instanceof Villager child && isNotPlains(event.getMother()) && isNotPlains(event.getFather())) { + applyBiomeType(child); + } + } + + private static void applyBiomeType(Villager villager) { + Villager.Type type = biomeType(villager); + if(type != null && villager.getVillagerType() == Villager.Type.PLAINS) { + villager.setVillagerType(type); + } + } + + private static Villager.Type biomeType(Entity entity) { + Location location = entity.getLocation(); + if(!entity.getWorld().isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) return null; + return BiomeHandler.getVillagerType(entity.getWorld().getBiome(location)); + } + + private static boolean isNotPlains(LivingEntity parent) { + return parent instanceof Villager villager && villager.getVillagerType() != Villager.Type.PLAINS; + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/SpigotListener.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/SpigotListener.java deleted file mode 100644 index a72379959..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/SpigotListener.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * This file is part of Terra. - * - * Terra is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Terra is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Terra. If not, see . - */ - -package com.dfsek.terra.bukkit.listeners; - -import org.bukkit.entity.Villager; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntitySpawnEvent; -import org.bukkit.event.entity.VillagerAcquireTradeEvent; -import org.bukkit.event.entity.VillagerCareerChangeEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.dfsek.terra.api.Platform; - - -/** - * Listener to load on Spigot servers, contains Villager crash prevention and hacky ender eye redirection. - *

- * (This is currently loaded on all servers; once Paper accepts the StructureLocateEvent PR this will only be loaded on servers without - * StructureLocateEvent). - */ -public class SpigotListener implements Listener { - private static final Logger logger = LoggerFactory.getLogger(SpigotListener.class); - private final Platform platform; - - public SpigotListener(Platform platform) { - this.platform = platform; - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onEnderEye(EntitySpawnEvent e) { -/* - Entity entity = e.getEntity(); - if(e.getEntityType() == EntityType.ENDER_SIGNAL) { - logger.info("Detected Ender Signal..."); - World w = BukkitAdapter.adapt(e.getEntity().getWorld()); - EnderSignal signal = (EnderSignal) entity; - ConfiguredStructure config = tw.getConfig().getRegistry(TerraStructure.class).get(w.getConfig().getLocatable().get - ("STRONGHOLD")); - if(config != null) { - logger.info("Overriding Ender Signal..."); - AsyncStructureFinder finder = new AsyncStructureFinder(tw.getBiomeProvider(), config, BukkitAdapter.adapt(e.getLocation() - .toVector()), tw.getWorld(), 0, 500, location -> { - if(location != null) - signal.setTargetLocation(BukkitAdapter.adapt(location).toLocation(e.getLocation().getWorld())); - logger.info("Location: {}", location); - }, main); - finder.run(); // Do this synchronously so eye doesn't change direction several ticks after spawning. - } else - logger.warn("No overrides are defined for Strongholds. Ender Signals will not work correctly."); - } -*/ - } - - @EventHandler - public void onCartographerChange(VillagerAcquireTradeEvent e) { - if(!(e.getEntity() instanceof Villager)) - return; - if(((Villager) e.getEntity()).getProfession() == Villager.Profession.CARTOGRAPHER) { - logger.error(""" - .------------------------------------------------------------------------. - | Prevented server crash by stopping Cartographer villager from | - | spawning. Please upgrade to Paper, which has a StructureLocateEvent | - | that fixes this issue at the source, and doesn't require us to do | - | stupid band-aids. | - |------------------------------------------------------------------------| - """.strip()); - e.setCancelled(true); // Cancel leveling if the villager is a Cartographer, to prevent crashing server. - } - } - - @EventHandler - public void onCartographerLevel(VillagerCareerChangeEvent e) { - if(e.getProfession() == Villager.Profession.CARTOGRAPHER) { - logger.error(""" - .------------------------------------------------------------------------. - | Prevented server crash by stopping Cartographer villager from leveling | - | up. Please upgrade to Paper, which has a StructureLocateEvent that | - | fixes this issue at the source, and doesn't require us to do stupid | - | band-aids. | - |------------------------------------------------------------------------| - """.strip()); - e.getEntity().setProfession(Villager.Profession.NITWIT); // Give villager new profession to prevent server crash. - e.setCancelled(true); - } - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitNMSAccess.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitNMSAccess.java deleted file mode 100644 index b9a88bf50..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitNMSAccess.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.dfsek.terra.bukkit.util; - -import org.bukkit.Location; -import org.bukkit.block.CreatureSpawner; - -import com.dfsek.terra.api.entity.EntityType; -import com.dfsek.terra.api.entity.EntityTypeExtended; - - -public interface BukkitNMSAccess { - EntityType getEntityType(String data); - - org.bukkit.entity.Entity spawnEntity(Object target, Location location, EntityType type); - - void setSpawnerEntity(CreatureSpawner spawner, EntityTypeExtended type); -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitUtils.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitUtils.java index 1a450e74f..1f5827068 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitUtils.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/BukkitUtils.java @@ -1,62 +1,82 @@ package com.dfsek.terra.bukkit.util; +import io.papermc.paper.registry.RegistryAccess; +import io.papermc.paper.registry.RegistryKey; +import org.bukkit.Bukkit; +import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.NamespacedKey; -import org.bukkit.Registry; +import org.bukkit.RegionAccessor; +import org.bukkit.World; import org.bukkit.block.CreatureSpawner; import org.bukkit.block.data.BlockData; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntitySnapshot; +import org.bukkit.generator.LimitedRegion; + +import java.math.BigDecimal; +import java.util.Locale; import com.dfsek.terra.api.entity.EntityType; import com.dfsek.terra.api.entity.EntityTypeExtended; import com.dfsek.terra.bukkit.world.entity.BukkitEntityType; +import com.dfsek.terra.bukkit.world.entity.BukkitEntityTypeExtended; public class BukkitUtils { - private static volatile BukkitNMSAccess nmsAccess; - public static boolean isLiquid(BlockData blockState) { Material material = blockState.getMaterial(); return material == Material.WATER || material == Material.LAVA; } - public static void setNMSAccess(BukkitNMSAccess access) { - nmsAccess = access; + public static EntityType getEntityType(String data) { + int nbtStart = data.indexOf('{'); + String id = nbtStart >= 0 ? data.substring(0, nbtStart) : data; + + NamespacedKey key = NamespacedKey.fromString(id.toLowerCase(Locale.ROOT)); + org.bukkit.entity.EntityType type = key == null ? null : RegistryAccess.registryAccess().getRegistry(RegistryKey.ENTITY_TYPE).get(key); + if(type == null) throw new IllegalArgumentException("Invalid entity identifier " + data); + if(nbtStart < 0) return new BukkitEntityType(type); + + String snbt = data.substring(nbtStart); + createSnapshot(type, snbt, null); // fail on invalid SNBT while the pack loads + return new BukkitEntityTypeExtended(type, snbt); } - public static EntityType getEntityType(String id) { - BukkitNMSAccess access = nmsAccess; - return access == null ? getBukkitEntityType(id) : access.getEntityType(id); - } - - public static org.bukkit.entity.Entity spawnEntity(Object region, org.bukkit.Location location, EntityType entityType) { - if(entityType instanceof EntityTypeExtended) { - BukkitNMSAccess access = nmsAccess; - if(access == null) throw new IllegalStateException("Entity NBT loading requires Terra's NMS bindings"); - return access.spawnEntity(region, location, entityType); + public static Entity spawnEntity(RegionAccessor region, Location location, EntityType entityType) { + if(entityType instanceof BukkitEntityTypeExtended extended) { + World world = region instanceof LimitedRegion limitedRegion ? limitedRegion.getWorld() : (World) region; + // LimitedRegion only accepts entities already inside it. + Entity entity = createSnapshot(extended.getHandle(), (String) extended.getData().getHandle(), location).createEntity(world); + return region.addEntity(entity); } - - org.bukkit.entity.EntityType bukkitType = ((BukkitEntityType) entityType).getHandle(); - if(region instanceof org.bukkit.generator.LimitedRegion limitedRegion) { - return limitedRegion.spawnEntity(location, bukkitType); - } - return ((org.bukkit.World) region).spawnEntity(location, bukkitType); + return region.spawnEntity(location, ((BukkitEntityType) entityType).getHandle()); } public static void setSpawnerEntity(CreatureSpawner spawner, EntityTypeExtended type) { - BukkitNMSAccess access = nmsAccess; - if(access == null) throw new IllegalStateException("Entity NBT loading requires Terra's NMS bindings"); - access.setSpawnerEntity(spawner, type); + if(!(type instanceof BukkitEntityTypeExtended extended)) { + throw new IllegalArgumentException("Expected a Bukkit entity type with NBT data"); + } + spawner.setSpawnedEntity(createSnapshot(extended.getHandle(), (String) extended.getData().getHandle(), null)); } - private static EntityType getBukkitEntityType(String data) { - int nbtStart = data.indexOf('{'); - if(nbtStart >= 0) { - throw new IllegalArgumentException("Entity NBT loading requires Terra's NMS bindings: " + data); - } + private static EntitySnapshot createSnapshot(org.bukkit.entity.EntityType type, String snbt, Location position) { + String body = snbt.strip(); + if(!body.startsWith("{") || !body.endsWith("}")) throw new IllegalArgumentException("Invalid entity NBT: " + snbt); + body = body.substring(1, body.length() - 1).strip(); - NamespacedKey key = NamespacedKey.fromString(data); - org.bukkit.entity.EntityType type = key == null ? null : Registry.ENTITY_TYPE.get(key); - if(type == null) throw new IllegalArgumentException("Invalid entity identifier " + data); - return new BukkitEntityType(type); + StringBuilder compound = new StringBuilder("{id:\"").append(type.getKey()).append('"'); + if(position != null) { + compound.append(",Pos:[").append(snbtDouble(position.getX())).append(',').append(snbtDouble(position.getY())) + .append(',').append(snbtDouble(position.getZ())).append(']'); + } + if(!body.isEmpty()) compound.append(',').append(body); + compound.append('}'); + + return Bukkit.getEntityFactory().createEntitySnapshot(compound.toString()); + } + + private static String snbtDouble(double value) { + return BigDecimal.valueOf(value).toPlainString() + "d"; } } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/MinecraftUtils.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/MinecraftUtils.java deleted file mode 100644 index 98da508b2..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/MinecraftUtils.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * This file is part of Terra. - * - * Terra is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Terra is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Terra. If not, see . - */ - -package com.dfsek.terra.bukkit.util; - -public final class MinecraftUtils { - public static String stripMinecraftNamespace(String in) { - if(in.startsWith("minecraft:")) return in.substring("minecraft:".length()); - return in; - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/PaperUtil.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/PaperUtil.java deleted file mode 100644 index c687fb000..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/PaperUtil.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of Terra. - * - * Terra is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Terra is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Terra. If not, see . - */ - -package com.dfsek.terra.bukkit.util; - -import io.papermc.lib.PaperLib; - -import java.util.concurrent.TimeUnit; - -import com.dfsek.terra.bukkit.TerraBukkitPlugin; - -import static io.papermc.lib.PaperLib.suggestPaper; - - -public final class PaperUtil { - public static void checkPaper(TerraBukkitPlugin plugin) { - plugin.getAsyncScheduler().runDelayed(plugin, task -> { - if(!PaperLib.isPaper()) { - suggestPaper(plugin); - } - }, 100L, TimeUnit.SECONDS); - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VanillaParticles.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VanillaParticles.java new file mode 100644 index 000000000..5f22c6868 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VanillaParticles.java @@ -0,0 +1,86 @@ +package com.dfsek.terra.bukkit.util; + +import com.mojang.brigadier.LiteralMessage; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; +import dev.wyck.environment.particle.AmbientParticle; +import org.bukkit.Bukkit; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; + + +public final class VanillaParticles { + private static final Logger LOGGER = LoggerFactory.getLogger(VanillaParticles.class); + private static final SimpleCommandExceptionType TRAILING_DATA = new SimpleCommandExceptionType( + new LiteralMessage("Unexpected text after the particle")); + + private VanillaParticles() { + } + + public static @Nullable AmbientParticle parse(String particle, float probability) throws CommandSyntaxException { + Handles handles = Holder.HANDLES; + if(handles == null) return null; + + StringReader reader = new StringReader(particle.strip()); + Object options; + Object ambient; + try { + options = handles.readParticle.invokeExact(reader, handles.registries); + ambient = handles.ambientParticle.invokeExact(options, probability); + } catch(CommandSyntaxException | RuntimeException | Error e) { + throw e; + } catch(Throwable e) { + throw new IllegalStateException(e); + } + if(reader.canRead()) throw TRAILING_DATA.createWithContext(reader); + return AmbientParticle.decode(ambient); + } + + private static @Nullable Handles resolve() { + String step = "net.minecraft.server.MinecraftServer"; + try { + ClassLoader loader = Bukkit.getServer().getClass().getClassLoader(); + MethodHandles.Lookup lookup = MethodHandles.publicLookup(); + + Class server = Class.forName(step, false, loader); + step = "MinecraftServer.getServer()"; + Object instance = lookup.findStatic(server, "getServer", MethodType.methodType(server)).invoke(); + if(instance == null) throw new IllegalStateException("the server has not started"); + step = "MinecraftServer.registryAccess()"; + Object registries = lookup.findVirtual(server, "registryAccess", + MethodType.methodType(Class.forName("net.minecraft.core.RegistryAccess$Frozen", false, loader))).invoke(instance); + + step = "ParticleArgument.readParticle(StringReader, HolderLookup.Provider)"; + Class provider = Class.forName("net.minecraft.core.HolderLookup$Provider", false, loader); + Class options = Class.forName("net.minecraft.core.particles.ParticleOptions", false, loader); + MethodHandle readParticle = lookup.findStatic(Class.forName("net.minecraft.commands.arguments.ParticleArgument", false, loader), + "readParticle", MethodType.methodType(options, StringReader.class, provider)) + .asType(MethodType.methodType(Object.class, StringReader.class, Object.class)); + + step = "AmbientParticle(ParticleOptions, float)"; + MethodHandle ambientParticle = lookup.findConstructor(Class.forName("net.minecraft.world.attribute.AmbientParticle", false, loader), + MethodType.methodType(void.class, options, float.class)) + .asType(MethodType.methodType(Object.class, Object.class, float.class)); + + return new Handles(readParticle, registries, ambientParticle); + } catch(Throwable e) { + LOGGER.warn("Biome particles are disabled: could not find vanilla's {} ({}). " + + "This Minecraft version is probably not supported yet.", step, e.toString()); + return null; + } + } + + private record Handles(MethodHandle readParticle, Object registries, MethodHandle ambientParticle) { + } + + + private static final class Holder { + private static final @Nullable Handles HANDLES = resolve(); + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VersionUtil.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VersionUtil.java deleted file mode 100644 index 3f32b6be2..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VersionUtil.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.dfsek.terra.bukkit.util; - -import io.papermc.lib.PaperLib; -import org.bukkit.Bukkit; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - -public final class VersionUtil { - public static final SpigotVersionInfo SPIGOT_VERSION_INFO; - public static final MinecraftVersionInfo MINECRAFT_VERSION_INFO; - - private static final Logger logger = LoggerFactory.getLogger(VersionUtil.class); - - static { - SPIGOT_VERSION_INFO = new SpigotVersionInfo(); - - MinecraftVersionInfo mcVersionInfo; - try { - mcVersionInfo = new MinecraftVersionInfo(); - } catch(Throwable t) { - logger.error("Error while parsing minecraft version info. Continuing launch, but setting all versions to -1."); - mcVersionInfo = new MinecraftVersionInfo(-1, -1, -1); - } - MINECRAFT_VERSION_INFO = mcVersionInfo; - } - - public static MinecraftVersionInfo getMinecraftVersionInfo() { - return MINECRAFT_VERSION_INFO; - } - - public static SpigotVersionInfo getSpigotVersionInfo() { - return SPIGOT_VERSION_INFO; - } - - public static final class SpigotVersionInfo { - private final boolean spigot; - private final boolean paper; - private final boolean mohist; - - - public SpigotVersionInfo() { - logger.debug("Parsing spigot version info..."); - - paper = PaperLib.isPaper(); - spigot = PaperLib.isSpigot(); - - - boolean isMohist = false; - try { - Class.forName("com.mohistmc.MohistMC"); - // it's mohist - isMohist = true; - } catch(ClassNotFoundException ignore) { } - this.mohist = isMohist; - - logger.debug("Spigot version info parsed successfully."); - } - - public boolean isPaper() { - return paper; - } - - public boolean isMohist() { - return mohist; - } - - public boolean isSpigot() { - return spigot; - } - } - - - public static final class MinecraftVersionInfo { - private static final Logger logger = LoggerFactory.getLogger(MinecraftVersionInfo.class); - - private static final Pattern VERSION_PATTERN = Pattern.compile("(\\d+)\\.(\\d+)(?:\\.(\\d+))?"); - private final int major; - private final int minor; - private final int patch; - - private MinecraftVersionInfo() { - this(Bukkit.getServer().getBukkitVersion().split("-")[0]); - } - - private MinecraftVersionInfo(int major, int minor, int patch) { - this.major = major; - this.minor = minor; - this.patch = patch; - } - - private MinecraftVersionInfo(String versionString) { - Matcher versionMatcher = VERSION_PATTERN.matcher(versionString); - if(versionMatcher.find()) { - major = Integer.parseInt(versionMatcher.group(1)); - minor = Integer.parseInt(versionMatcher.group(2)); - patch = versionMatcher.group(3) != null ? Integer.parseInt(versionMatcher.group(3)) : -1; - } else { - logger.warn("Error while parsing minecraft version info. Continuing launch, but setting all versions to -1."); - - major = -1; - minor = -1; - patch = -1; - } - } - - @Override - public String toString() { - if(major == -1 && minor == -1 && patch == -1) - return "Unknown"; - - if(patch >= 0) { - return String.format("v%d.%d.%d", major, minor, patch); - } else { - return String.format("v%d.%d", major, minor); - } - } - - public int getMajor() { - return major; - } - - public int getMinor() { - return minor; - } - - public int getPatch() { - return patch; - } - } -} \ No newline at end of file diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java index 2f3c06209..e89517d1f 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java @@ -1,81 +1,154 @@ package com.dfsek.terra.bukkit.world; -import com.dfsek.terra.api.config.ConfigPack; -import com.dfsek.terra.bukkit.config.VanillaBiomeProperties; - import dev.wyck.biome.Biome; -import dev.wyck.biome.Biome.Builder; -import dev.wyck.biome.BiomeGenerationSettings; import dev.wyck.biome.BiomeSpecialEffects; import dev.wyck.biome.ClimateSettings; +import dev.wyck.environment.attribute.EnvironmentAttributeMap; import dev.wyck.environment.attribute.EnvironmentAttributeSupplier; import dev.wyck.environment.attribute.EnvironmentAttributes; import dev.wyck.environment.sounds.AmbientSounds; import dev.wyck.environment.sounds.BackgroundMusic; -import dev.wyck.keys.KeyChains; import dev.wyck.keys.ResourceKey; +import dev.wyck.registry.BiomeRegistry; +import dev.wyck.tags.TagSet; +import io.papermc.paper.registry.RegistryAccess; +import io.papermc.paper.registry.RegistryKey; +import io.papermc.paper.registry.TypedKey; +import io.papermc.paper.registry.tag.Tag; +import org.bukkit.NamespacedKey; +import org.bukkit.entity.Villager; +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.List; import java.util.Locale; +import java.util.Map; import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.bukkit.config.VanillaBiomeProperties; +import com.dfsek.terra.registry.master.ConfigRegistry; -public class BiomeHandler { +public final class BiomeHandler { + private static final Logger LOGGER = LoggerFactory.getLogger(BiomeHandler.class); + private static final Map VILLAGER_TYPES = new ConcurrentHashMap<>(); - public static Biome getBiome(ResourceKey key) { - Biome biome = KeyChains.BIOMES.get(key); - return biome != null ? biome.wrap() : null; + private BiomeHandler() { } + + public static void registerBiomes(ConfigRegistry configRegistry) { + org.bukkit.Registry bukkitRegistry = RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME); + List toRegister = new ArrayList<>(); + List afterRegistration = new ArrayList<>(); + + configRegistry.forEach(pack -> pack.getRegistry(com.dfsek.terra.api.world.biome.Biome.class).forEach((key, biome) -> { + BukkitPlatformBiome platformBiome = (BukkitPlatformBiome) biome.getPlatformBiome(); + ResourceKey vanillaKey = ResourceKey.of(platformBiome.getHandle().getKey()); + ResourceKey terraKey = ResourceKey.of("terra", createBiomeID(pack, key)); + + NamespacedKey bukkitKey = new NamespacedKey(terraKey.namespace(), terraKey.path()); + VanillaBiomeProperties properties = biome.getContext().has(VanillaBiomeProperties.class) + ? biome.getContext().get(VanillaBiomeProperties.class) + : new VanillaBiomeProperties(); + + if(bukkitRegistry.get(bukkitKey) == null) { + toRegister.add(createBiome(terraKey, getBiomeOrThrow(vanillaKey), properties)); + } + + afterRegistration.add(() -> { + org.bukkit.block.Biome bukkitBiome = bukkitRegistry.getOrThrow(bukkitKey); + platformBiome.getContext().put(new BukkitBiomeInfo(terraKey, vanillaKey, bukkitBiome)); + if(properties.getVillagerType() != null) { + VILLAGER_TYPES.put(bukkitKey, properties.getVillagerType()); + } + }); + })); + + LOGGER.info("Registering {} custom biomes through Wyck...", toRegister.size()); + BiomeRegistry.registry().register(toRegister); + afterRegistration.forEach(Runnable::run); + } + + public static void addToVanillaTags(ConfigRegistry configRegistry) { + Map, Set> terraBiomesByVanilla = new HashMap<>(); + configRegistry.forEach(pack -> pack.getRegistry(com.dfsek.terra.api.world.biome.Biome.class).forEach(biome -> { + Context context = ((BukkitPlatformBiome) biome.getPlatformBiome()).getContext(); + if(context.has(BukkitBiomeInfo.class)) { + BukkitBiomeInfo info = context.get(BukkitBiomeInfo.class); + TypedKey vanillaKey = TypedKey.create(RegistryKey.BIOME, info.vanillaKey().key()); + terraBiomesByVanilla.computeIfAbsent(vanillaKey, k -> new HashSet<>()).add(Biome.reference(info.biomeKey())); + } + })); + + org.bukkit.Registry bukkitRegistry = RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME); + int count = 0; + for(Tag tag : bukkitRegistry.getTags()) { + Set members = new HashSet<>(); + terraBiomesByVanilla.forEach((vanillaKey, terraBiomes) -> { + if(tag.contains(vanillaKey)) { + members.addAll(terraBiomes); + } + }); + if(!members.isEmpty()) { + TagSet.ofBiomes(ResourceKey.of(tag.tagKey().key()), members).append(); + count++; + } + } + LOGGER.info("Added Terra biomes to {} vanilla biome tags.", count); + } + + public static @Nullable Villager.Type getVillagerType(org.bukkit.block.Biome biome) { + return VILLAGER_TYPES.get(biome.getKey()); } public static Biome getBiomeOrThrow(ResourceKey key) { - return KeyChains.BIOMES.getOrThrow(key).wrap(); + return Biome.reference(key).wrap(); } - public static Biome createBiome(ResourceKey vanillaBiomeKey, VanillaBiomeProperties vanillaBiomeProperties) - throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { - Biome vanilla = getBiomeOrThrow(vanillaBiomeKey); - Builder builder = dev.wyck.biome.Biome.builder(); - - setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.FOG_COLOR, vanillaBiomeProperties.getFogColor()); - setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.WATER_FOG_COLOR, vanillaBiomeProperties.getWaterFogColor()); - setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.SKY_COLOR, vanillaBiomeProperties.getSkyColor()); - setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.AMBIENT_PARTICLES, vanillaBiomeProperties.getParticles()); - setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.AMBIENT_SOUNDS, AmbientSounds.builder() - .loop(vanillaBiomeProperties.getLoopSound()) - .mood(vanillaBiomeProperties.getMoodSound()) - .addition(vanillaBiomeProperties.getAdditionsSound()) - .build()); - setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.BACKGROUND_MUSIC, BackgroundMusic.builder() - .defaultMusic(vanillaBiomeProperties.getMusic()) - .build()); - setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.MUSIC_VOLUME, vanillaBiomeProperties.getMusicVolume()); - setAttributeOrDefault(builder, vanilla, EnvironmentAttributes.NATURAL_MOB_SPAWNS, vanillaBiomeProperties.getSpawnSettings()); - - builder.climateSettings(ClimateSettings.builder() - .hasPrecipitation(Objects.requireNonNullElse(vanillaBiomeProperties.getPrecipitation(), vanilla.climateSettings().hasPrecipitation())) - .temperature(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperature(), vanilla.climateSettings().temperature())) - .temperatureModifier(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperatureModifier(), vanilla.climateSettings().temperatureModifier())) - .downfall(Objects.requireNonNullElse(vanillaBiomeProperties.getDownfall(), vanilla.climateSettings().downfall())) - .build()); - - BiomeSpecialEffects.Builder effects = BiomeSpecialEffects.builder(); - effects.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.specialEffects().waterColor())); - effects.grassColorModifier(Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(), vanilla.specialEffects().grassColorModifier())); - - if(vanillaBiomeProperties.getGrassColor() == null) { - vanilla.specialEffects().grassColorOverride().ifPresent(effects::grassColorOverride); - } else { - effects.grassColorOverride(vanillaBiomeProperties.getGrassColor()); + public static Biome createBiome(ResourceKey key, Biome vanilla, VanillaBiomeProperties properties) { + EnvironmentAttributeMap attributes = vanilla.attributes(); + attributes = override(attributes, EnvironmentAttributes.FOG_COLOR, properties.getFogColor()); + attributes = override(attributes, EnvironmentAttributes.WATER_FOG_COLOR, properties.getWaterFogColor()); + attributes = override(attributes, EnvironmentAttributes.SKY_COLOR, properties.getSkyColor()); + attributes = override(attributes, EnvironmentAttributes.AMBIENT_PARTICLES, properties.getParticles()); + attributes = override(attributes, EnvironmentAttributes.MUSIC_VOLUME, properties.getMusicVolume()); + attributes = override(attributes, EnvironmentAttributes.NATURAL_MOB_SPAWNS, properties.getSpawnSettings()); + if(properties.getMusic() != null) { + attributes = attributes.with(EnvironmentAttributes.BACKGROUND_MUSIC, + BackgroundMusic.builder().defaultMusic(properties.getMusic()).build()); + } + if(properties.getLoopSound() != null || properties.getMoodSound() != null || properties.getAdditionsSound() != null) { + AmbientSounds sounds = Objects.requireNonNullElse(attributes.get(EnvironmentAttributes.AMBIENT_SOUNDS), AmbientSounds.EMPTY); + attributes = attributes.with(EnvironmentAttributes.AMBIENT_SOUNDS, AmbientSounds.of( + properties.getLoopSound() != null ? properties.getLoopSound() : sounds.loop().orElse(null), + properties.getMoodSound() != null ? properties.getMoodSound() : sounds.mood().orElse(null), + properties.getAdditionsSound() != null ? List.of(properties.getAdditionsSound()) : sounds.additions())); } - if(vanillaBiomeProperties.getFoliageColor() == null) { - vanilla.specialEffects().foliageColorOverride().ifPresent(effects::foliageColorOverride); - } else { - effects.foliageColorOverride(vanillaBiomeProperties.getFoliageColor()); - } + ClimateSettings climate = vanilla.climateSettings(); + BiomeSpecialEffects effects = vanilla.specialEffects(); - return builder - .specialEffects(effects.build()) - .generationSettings(BiomeGenerationSettings.builder() + return Biome.builder(key) + .attributes(attributes) + .climateSettings(ClimateSettings.builder() + .hasPrecipitation(Objects.requireNonNullElse(properties.getPrecipitation(), climate.hasPrecipitation())) + .temperature(Objects.requireNonNullElse(properties.getTemperature(), climate.temperature())) + .temperatureModifier(Objects.requireNonNullElse(properties.getTemperatureModifier(), climate.temperatureModifier())) + .downfall(Objects.requireNonNullElse(properties.getDownfall(), climate.downfall())) + .build()) + .specialEffects(BiomeSpecialEffects.builder() + .waterColor(Objects.requireNonNullElse(properties.getWaterColor(), effects.waterColor())) + .grassColorModifier(Objects.requireNonNullElse(properties.getGrassColorModifier(), effects.grassColorModifier())) + .grassColorOverride(orElse(properties.getGrassColor(), effects.grassColorOverride().orElse(null))) + .foliageColorOverride(orElse(properties.getFoliageColor(), effects.foliageColorOverride().orElse(null))) + .dryFoliageColorOverride(orElse(properties.getDryFoliageColor(), effects.dryFoliageColorOverride().orElse(null))) .build()) .build(); } @@ -86,7 +159,12 @@ public class BiomeHandler { + "/" + biomeID.getID().toLowerCase(Locale.ROOT); } - private static void setAttributeOrDefault(Biome.Builder builder, Biome def, EnvironmentAttributeSupplier attribute, T value) { - builder.attribute(attribute, Objects.requireNonNullElse(value, def.attributes().get(attribute))); + private static EnvironmentAttributeMap override(EnvironmentAttributeMap map, EnvironmentAttributeSupplier attribute, + @Nullable T value) { + return value == null ? map : map.with(attribute, value); + } + + private static @Nullable Integer orElse(@Nullable Integer value, @Nullable Integer fallback) { + return value != null ? value : fallback; } } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java index a2918aad7..5be1be7d8 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java @@ -5,5 +5,5 @@ import dev.wyck.keys.ResourceKey; import com.dfsek.terra.api.properties.Properties; -public record BukkitBiomeInfo(ResourceKey biomeKey) implements Properties { +public record BukkitBiomeInfo(ResourceKey biomeKey, ResourceKey vanillaKey, org.bukkit.block.Biome bukkitBiome) implements Properties { } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeProvider.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeProvider.java deleted file mode 100644 index f18196560..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeProvider.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.dfsek.terra.bukkit.world; - -import dev.wyck.biome.Biome; -import dev.wyck.worldgen.biome.custom.BiomeSourceContext; -import dev.wyck.worldgen.biome.custom.CustomBiomeSource; - -import java.util.Set; -import java.util.stream.Collectors; - -import com.dfsek.terra.api.world.biome.generation.BiomeProvider; - - -public class BukkitBiomeProvider extends CustomBiomeSource { - private final BiomeProvider delegate; - private final long seed; - - public BukkitBiomeProvider(BiomeProvider delegate, long seed) { - super(); - this.delegate = delegate; - this.seed = seed; - } - - @Override - public Biome biome(BiomeSourceContext context) { - return BiomeHandler.getBiomeOrThrow(((BukkitPlatformBiome) delegate.getBiome(context.blockX() << 2, context.blockY() << 2, context.blockZ() << 2, seed) - .getPlatformBiome()).getContext() - .get(BukkitBiomeInfo.class) - .biomeKey()); - } - - @Override - public Set possibleBiomes() { - return delegate.stream() - .map(biome -> BiomeHandler.getBiomeOrThrow(((BukkitPlatformBiome) biome.getPlatformBiome()) - .getContext() - .get(BukkitBiomeInfo.class) - .biomeKey())) - .collect(Collectors.toSet()); - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/block/state/BukkitSign.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/block/state/BukkitSign.java index 2ed7ea8e0..a2f780cc9 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/block/state/BukkitSign.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/block/state/BukkitSign.java @@ -17,31 +17,39 @@ package com.dfsek.terra.bukkit.world.block.state; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.bukkit.block.sign.Side; +import org.bukkit.block.sign.SignSide; import org.jetbrains.annotations.NotNull; import com.dfsek.terra.api.block.entity.SerialState; import com.dfsek.terra.api.block.entity.Sign; -@SuppressWarnings("deprecation") public class BukkitSign extends BukkitBlockEntity implements Sign { + private static final LegacyComponentSerializer LEGACY = LegacyComponentSerializer.legacySection(); + protected BukkitSign(org.bukkit.block.Sign block) { super(block); } @Override public void setLine(int index, @NotNull String line) throws IndexOutOfBoundsException { - ((org.bukkit.block.Sign) getHandle()).setLine(index, line); + front().line(index, LEGACY.deserialize(line)); } @Override public @NotNull String[] getLines() { - return ((org.bukkit.block.Sign) getHandle()).getLines(); + return front().lines().stream().map(LEGACY::serialize).toArray(String[]::new); } @Override public @NotNull String getLine(int index) throws IndexOutOfBoundsException { - return ((org.bukkit.block.Sign) getHandle()).getLine(index); + return LEGACY.serialize(front().line(index)); + } + + private SignSide front() { + return ((org.bukkit.block.Sign) getHandle()).getSide(Side.FRONT); } @Override diff --git a/platforms/bukkit/common/src/main/resources/paper-plugin.yml b/platforms/bukkit/common/src/main/resources/paper-plugin.yml index e36268af3..2a1b472a5 100644 --- a/platforms/bukkit/common/src/main/resources/paper-plugin.yml +++ b/platforms/bukkit/common/src/main/resources/paper-plugin.yml @@ -5,15 +5,9 @@ load: "STARTUP" authors: [ "dfsek", "duplexsystem", "Astrash", "solonovamax", "Sancires", "Aureus", "RogueShade", "OakLoaf" ] website: "@WIKI@" api-version: "26.3" -bootstrapper: "com.dfsek.terra.bukkit.TerraBootstrapper" description: "@DESCRIPTION@" folia-supported: true -depend: - bootstrap: - Wyck: - load: BEFORE - required: true - join-classpath: true +dependencies: server: Wyck: load: BEFORE From 6ddf039e4967ba73f39c4df2260663d19e7d4e36 Mon Sep 17 00:00:00 2001 From: Zoe Gidiere Date: Fri, 6 Nov 2026 22:11:06 -0700 Subject: [PATCH 38/44] fix: adapt minestom platform to 26_3 snapshot renames --- .../com/dfsek/terra/minestom/biome/MinestomBiomeLoader.java | 2 +- .../com/dfsek/terra/minestom/block/MinestomBlockState.java | 2 +- .../com/dfsek/terra/minestom/block/MinestomBlockType.java | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/biome/MinestomBiomeLoader.java b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/biome/MinestomBiomeLoader.java index 21e4645b4..3d30bafe7 100644 --- a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/biome/MinestomBiomeLoader.java +++ b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/biome/MinestomBiomeLoader.java @@ -21,6 +21,6 @@ public class MinestomBiomeLoader implements TypeLoader { @Subst("name:value") String id = (String) o; Key key = Key.key(id); - return new MinestomBiome(RegistryKey.unsafeOf(key)); + return new MinestomBiome(RegistryKey.of(key)); } } \ No newline at end of file diff --git a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/block/MinestomBlockState.java b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/block/MinestomBlockState.java index 6725e947f..3130f3386 100644 --- a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/block/MinestomBlockState.java +++ b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/block/MinestomBlockState.java @@ -133,7 +133,7 @@ public record MinestomBlockState(Block block) implements BlockState { @Override public boolean isAir() { - return block.isAir(); + return block.air(); } @Override diff --git a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/block/MinestomBlockType.java b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/block/MinestomBlockType.java index e8602306f..03541ceb0 100644 --- a/platforms/minestom/src/main/java/com/dfsek/terra/minestom/block/MinestomBlockType.java +++ b/platforms/minestom/src/main/java/com/dfsek/terra/minestom/block/MinestomBlockType.java @@ -20,12 +20,12 @@ public class MinestomBlockType implements BlockType { @Override public boolean isSolid() { - return block.isSolid(); + return block.solid(); } @Override public boolean isWater() { - return block.isLiquid(); + return block.liquid(); } @Override From 8a940f7e1f90702e10a4740228772be7af2f7989 Mon Sep 17 00:00:00 2001 From: Zoe Gidiere Date: Sat, 7 Nov 2026 18:02:53 -0700 Subject: [PATCH 39/44] perf: replace biome tag checks with bitset columns --- .../biome-provider-extrusion/build.gradle.kts | 3 +- .../extrusions/ReplaceExtrusionTemplate.java | 5 +- .../extrusions/ReplaceExtrusion.java | 28 +-- .../src/main/resources/terra.addon.yml | 2 - .../java/extrusion/ReplaceExtrusionTest.java | 101 ++++++++++ .../biome-provider-pipeline/build.gradle.kts | 2 +- .../biome/pipeline/BiomePipelineAddon.java | 2 +- .../api/biome/DelegatedPipelineBiome.java | 3 +- .../pipeline/api/biome/PipelineBiome.java | 49 ++++- .../api/biome/PlaceholderPipelineBiome.java | 17 +- .../pipeline/api/biome/SelfPipelineBiome.java | 4 +- .../pipeline/config/PipelineBiomeLoader.java | 10 +- .../mutator/BorderListStageTemplate.java | 5 +- .../stage/mutator/BorderStageTemplate.java | 5 +- .../mutator/ReplaceListStageTemplate.java | 3 +- .../stage/mutator/ReplaceStageTemplate.java | 3 +- .../stage/mutators/BorderListStage.java | 21 +- .../pipeline/stage/mutators/BorderStage.java | 11 +- .../stage/mutators/ReplaceListStage.java | 18 +- .../pipeline/stage/mutators/ReplaceStage.java | 9 +- .../pipeline/stage/mutators/ReplaceTable.java | 27 +++ .../java/pipeline/PipelineBiomeTagTest.java | 190 ++++++++++++++++++ common/addons/biome-query-api/README.md | 4 - .../addons/biome-query-api/build.gradle.kts | 5 - .../biome/query/BiomeQueryAPIAddon.java | 46 ----- .../addons/biome/query/api/BiomeQueries.java | 17 -- .../biome/query/impl/BiomeTagFlattener.java | 20 -- .../biome/query/impl/BiomeTagHolder.java | 26 --- .../biome/query/impl/SingleTagQuery.java | 31 --- .../src/main/resources/terra.addon.yml | 12 -- common/addons/config-biome/build.gradle.kts | 2 + .../terra/addons/biome/BiomeTemplate.java | 24 ++- .../terra/addons/biome/UserDefinedBiome.java | 19 +- .../src/test/java/biome/PlatformTagsTest.java | 68 +++++++ .../src/main/resources/terra.addon.yml | 2 +- .../dfsek/terra/api/config/ConfigPack.java | 6 + .../api/util/collection/TriStateIntCache.java | 67 ------ .../dfsek/terra/api/world/biome/Biome.java | 16 +- .../terra/api/world/biome/tag/BiomeTag.java | 79 ++++++++ .../api/world/biome/tag/BiomeTagIndex.java | 74 +++++++ .../world/biome/tag/BiomeTagIndexTest.java | 120 +++++++++++ .../terra/config/loaders/BiomeTagLoader.java | 34 ++++ .../terra/config/pack/ConfigPackImpl.java | 14 ++ .../config/loaders/BiomeTagLoaderTest.java | 41 ++++ platforms/cli/build.gradle.kts | 7 + 45 files changed, 938 insertions(+), 314 deletions(-) create mode 100644 common/addons/biome-provider-extrusion/src/test/java/extrusion/ReplaceExtrusionTest.java create mode 100644 common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceTable.java create mode 100644 common/addons/biome-provider-pipeline/src/test/java/pipeline/PipelineBiomeTagTest.java delete mode 100644 common/addons/biome-query-api/README.md delete mode 100644 common/addons/biome-query-api/build.gradle.kts delete mode 100644 common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/BiomeQueryAPIAddon.java delete mode 100644 common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/api/BiomeQueries.java delete mode 100644 common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagFlattener.java delete mode 100644 common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagHolder.java delete mode 100644 common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/SingleTagQuery.java delete mode 100644 common/addons/biome-query-api/src/main/resources/terra.addon.yml create mode 100644 common/addons/config-biome/src/test/java/biome/PlatformTagsTest.java delete mode 100644 common/api/src/main/java/com/dfsek/terra/api/util/collection/TriStateIntCache.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTag.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndex.java create mode 100644 common/api/src/test/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndexTest.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/config/loaders/BiomeTagLoader.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/config/loaders/BiomeTagLoaderTest.java diff --git a/common/addons/biome-provider-extrusion/build.gradle.kts b/common/addons/biome-provider-extrusion/build.gradle.kts index 7615a16d0..7b116d3a2 100644 --- a/common/addons/biome-provider-extrusion/build.gradle.kts +++ b/common/addons/biome-provider-extrusion/build.gradle.kts @@ -1,6 +1,5 @@ -version = version("1.0.0") +version = version("2.0.0") dependencies { compileOnlyApi(project(":common:addons:manifest-addon-loader")) - compileOnlyApi(project(":common:addons:biome-query-api")) } diff --git a/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/config/extrusions/ReplaceExtrusionTemplate.java b/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/config/extrusions/ReplaceExtrusionTemplate.java index dd29b282a..e821f22dd 100644 --- a/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/config/extrusions/ReplaceExtrusionTemplate.java +++ b/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/config/extrusions/ReplaceExtrusionTemplate.java @@ -7,6 +7,7 @@ import com.dfsek.terra.addons.biome.extrusion.api.ReplaceableBiome; import com.dfsek.terra.addons.biome.extrusion.extrusions.ReplaceExtrusion; import com.dfsek.terra.api.config.meta.Meta; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; public class ReplaceExtrusionTemplate extends SamplerExtrusionTemplate { @@ -14,10 +15,10 @@ public class ReplaceExtrusionTemplate extends SamplerExtrusionTemplate { private @Meta ProbabilityCollection<@Meta ReplaceableBiome> biomes; @Value("from") - private @Meta String fromTag; + private @Meta BiomeTag from; @Override public Extrusion get() { - return new ReplaceExtrusion(sampler, range, biomes, fromTag); + return new ReplaceExtrusion(sampler, range, biomes, from); } } diff --git a/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/extrusions/ReplaceExtrusion.java b/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/extrusions/ReplaceExtrusion.java index 4985a2f90..e880933ae 100644 --- a/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/extrusions/ReplaceExtrusion.java +++ b/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/extrusions/ReplaceExtrusion.java @@ -8,11 +8,10 @@ import java.util.stream.Collectors; import com.dfsek.terra.addons.biome.extrusion.api.Extrusion; import com.dfsek.terra.addons.biome.extrusion.api.ReplaceableBiome; -import com.dfsek.terra.addons.biome.query.api.BiomeQueries; import com.dfsek.terra.api.util.collection.ProbabilityCollection; -import com.dfsek.terra.api.util.collection.TriStateIntCache; import com.dfsek.terra.api.util.range.Range; import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; /** @@ -22,34 +21,19 @@ public class ReplaceExtrusion implements Extrusion { private final Sampler sampler; private final Range range; private final ProbabilityCollection biomes; - private final Predicate hasTag; - private final TriStateIntCache cache; + // Concrete final type keeps has() monomorphic for inlining. + private final BiomeTag from; - public ReplaceExtrusion(Sampler sampler, Range range, ProbabilityCollection biomes, String tag) { + public ReplaceExtrusion(Sampler sampler, Range range, ProbabilityCollection biomes, BiomeTag from) { this.sampler = sampler; this.range = range; this.biomes = biomes; - this.hasTag = BiomeQueries.has(tag); - this.cache = new TriStateIntCache(Biome.INT_ID_COUNTER.get()); + this.from = from; } @Override public Biome extrude(Biome original, int x, int y, int z, long seed) { - int id = original.getIntID(); - - long state = cache.get(id); - boolean passes; - - if(state == TriStateIntCache.STATE_UNSET) { - // Only run the test if unset in cache - passes = hasTag.test(original); - cache.set(id, passes); - } else { - // Read the primitive long directly - passes = (state == TriStateIntCache.STATE_TRUE); - } - - if(passes) { + if(from.has(original.getIntID())) { if(range.isInRange(y)) { return biomes.get(sampler, x, y, z, seed).get(original); } diff --git a/common/addons/biome-provider-extrusion/src/main/resources/terra.addon.yml b/common/addons/biome-provider-extrusion/src/main/resources/terra.addon.yml index 21992a6d1..b491cc3ae 100644 --- a/common/addons/biome-provider-extrusion/src/main/resources/terra.addon.yml +++ b/common/addons/biome-provider-extrusion/src/main/resources/terra.addon.yml @@ -10,5 +10,3 @@ website: source: https://github.com/PolyhedralDev/Terra docs: https://terra.polydev.org license: MIT License -depends: - biome-query-api: "1.+" \ No newline at end of file diff --git a/common/addons/biome-provider-extrusion/src/test/java/extrusion/ReplaceExtrusionTest.java b/common/addons/biome-provider-extrusion/src/test/java/extrusion/ReplaceExtrusionTest.java new file mode 100644 index 000000000..6af5575ea --- /dev/null +++ b/common/addons/biome-provider-extrusion/src/test/java/extrusion/ReplaceExtrusionTest.java @@ -0,0 +1,101 @@ +package extrusion; + +import com.dfsek.seismic.type.sampler.Sampler; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.util.Map; +import java.util.Set; + +import com.dfsek.terra.addons.biome.extrusion.api.ReplaceableBiome; +import com.dfsek.terra.addons.biome.extrusion.extrusions.ReplaceExtrusion; +import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.util.range.ConstantRange; +import com.dfsek.terra.api.util.range.Range; +import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.biome.PlatformBiome; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; + +import static org.junit.jupiter.api.Assertions.*; + + +class ReplaceExtrusionTest { + private static final Sampler SAMPLER = new Sampler() { + @Override + public double getSample(long seed, double x, double y) { + return 0; + } + + @Override + public double getSample(long seed, double x, double y, double z) { + return 0; + } + }; + + private static final class StubBiome implements Biome { + private final String id; + private final Set tags; + private final int intId; + + StubBiome(BiomeTagIndex index, String id, Set tags) { + this.id = id; + this.tags = tags; + this.intId = index.register(tags); + } + + @Override + public PlatformBiome getPlatformBiome() { + return null; + } + + @Override + public int getColor() { + return 0; + } + + @Override + public Set getTags() { + return tags; + } + + @Override + public int getIntID() { + return intId; + } + + @Override + public Context getContext() { + return null; + } + + @Override + public String getID() { + return id; + } + } + + private final BiomeTagIndex index = new BiomeTagIndex(); + private final Map biomes = Map.of( + "tagged", new StubBiome(index, "tagged", Set.of("X")), + "untagged", new StubBiome(index, "untagged", Set.of("Y")), + "replacement", new StubBiome(index, "replacement", Set.of())); + + @ParameterizedTest(name = "{0}: {1} at y {2} -> {3}") + @CsvSource({ + "X, tagged, 10, replacement", + "X, untagged, 10, untagged", + "X, tagged, 100, tagged", + "TYPO, tagged, 10, tagged", + "TYPO, untagged, 10, untagged", + "TYPO, replacement, 10, replacement", + }) + void replacesTaggedBiomesInRange(String tag, String biome, int y, String expected) { + ProbabilityCollection to = new ProbabilityCollection() + .add(ReplaceableBiome.of(biomes.get("replacement")), 1); + Range range = new ConstantRange(0, 64); + ReplaceExtrusion extrusion = new ReplaceExtrusion(SAMPLER, range, to, index.tag(tag)); + index.seal(); + assertSame(biomes.get(expected), extrusion.extrude(biomes.get(biome), 0, y, 0, 0)); + } +} diff --git a/common/addons/biome-provider-pipeline/build.gradle.kts b/common/addons/biome-provider-pipeline/build.gradle.kts index 2bbce32db..7b64535ef 100644 --- a/common/addons/biome-provider-pipeline/build.gradle.kts +++ b/common/addons/biome-provider-pipeline/build.gradle.kts @@ -1,4 +1,4 @@ -version = version("2.0.0") +version = version("3.0.0") dependencies { compileOnlyApi(project(":common:addons:manifest-addon-loader")) diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/BiomePipelineAddon.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/BiomePipelineAddon.java index 432fd4dec..17ff8bd73 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/BiomePipelineAddon.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/BiomePipelineAddon.java @@ -83,7 +83,7 @@ public class BiomePipelineAddon implements AddonInitializer { .register(addon, ConfigPackPostLoadEvent.class) .then(event -> { Registry biomeRegistry = event.getPack().getRegistry(Biome.class); - event.getPack().applyLoader(PipelineBiome.class, new PipelineBiomeLoader(biomeRegistry)); + event.getPack().applyLoader(PipelineBiome.class, new PipelineBiomeLoader(biomeRegistry, event.getPack().getBiomeTagIndex())); }); } } diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/DelegatedPipelineBiome.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/DelegatedPipelineBiome.java index a915e32f2..b33d8d01f 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/DelegatedPipelineBiome.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/DelegatedPipelineBiome.java @@ -5,10 +5,11 @@ import java.util.Set; import com.dfsek.terra.api.world.biome.Biome; -public final class DelegatedPipelineBiome implements PipelineBiome { +public final class DelegatedPipelineBiome extends PipelineBiome { private final Biome biome; public DelegatedPipelineBiome(Biome biome) { + super(biome.getIntID()); this.biome = biome; } diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PipelineBiome.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PipelineBiome.java index fdcc77cc7..dd9f18a47 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PipelineBiome.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PipelineBiome.java @@ -4,30 +4,61 @@ import java.util.Set; import com.dfsek.terra.api.registry.key.StringIdentifiable; import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; -public interface PipelineBiome extends StringIdentifiable { - static PipelineBiome placeholder(String id) { - return new PlaceholderPipelineBiome(id); +public abstract sealed class PipelineBiome implements StringIdentifiable + permits DelegatedPipelineBiome, PlaceholderPipelineBiome, SelfPipelineBiome { + private final int intId; + + PipelineBiome(int intId) { + this.intId = intId; } - static PipelineBiome from(Biome biome) { + /** + * Registers a new ID per call; call before {@code index} is sealed. + */ + @ApiStatus.Internal + public static PipelineBiome placeholder(String id, BiomeTagIndex index) { + return new PlaceholderPipelineBiome(id, index); + } + + /** + * {@code biome} must come from the same pack as the index it is tested against. + */ + public static PipelineBiome from(Biome biome) { return new DelegatedPipelineBiome(biome); } - static PipelineBiome self() { + public static PipelineBiome self() { return SelfPipelineBiome.INSTANCE; } - Biome getBiome(); + /** + * Dense per pack, not stable across loads. + */ + @Contract(pure = true) + public final int getIntID() { + return intId; + } - Set getTags(); + @NotNull + public abstract Biome getBiome(); - default boolean isPlaceholder() { + @NotNull + public abstract Set getTags(); + + @Contract(pure = true) + public boolean isPlaceholder() { return false; } - default boolean isSelf() { + @Contract(pure = true) + public boolean isSelf() { return false; } diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PlaceholderPipelineBiome.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PlaceholderPipelineBiome.java index 5a458676e..4bec743a7 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PlaceholderPipelineBiome.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PlaceholderPipelineBiome.java @@ -4,17 +4,28 @@ import java.util.HashSet; import java.util.Set; import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; -final class PlaceholderPipelineBiome implements PipelineBiome { +final class PlaceholderPipelineBiome extends PipelineBiome { private final Set tags; private final String id; - public PlaceholderPipelineBiome(String id) { + public PlaceholderPipelineBiome(String id, BiomeTagIndex index) { + this(id, tagsOf(id), index); + } + + private PlaceholderPipelineBiome(String id, Set tags, BiomeTagIndex index) { + super(index.register(tags)); this.id = id; - tags = new HashSet<>(); + this.tags = tags; + } + + private static Set tagsOf(String id) { + Set tags = new HashSet<>(); tags.add(id); tags.add("ALL"); + return Set.copyOf(tags); } @Override diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/SelfPipelineBiome.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/SelfPipelineBiome.java index 7a00ef5fd..0ee712dc2 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/SelfPipelineBiome.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/SelfPipelineBiome.java @@ -6,11 +6,11 @@ import java.util.Set; import com.dfsek.terra.api.world.biome.Biome; -final class SelfPipelineBiome implements PipelineBiome { +final class SelfPipelineBiome extends PipelineBiome { public static final SelfPipelineBiome INSTANCE = new SelfPipelineBiome(); private SelfPipelineBiome() { - + super(0); // reserved in every pack's index, untagged } @Override diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/PipelineBiomeLoader.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/PipelineBiomeLoader.java index afd249c25..53a7e0a45 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/PipelineBiomeLoader.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/PipelineBiomeLoader.java @@ -7,17 +7,23 @@ import com.dfsek.tectonic.api.loader.type.TypeLoader; import org.jetbrains.annotations.NotNull; import java.lang.reflect.AnnotatedType; +import java.util.concurrent.ConcurrentHashMap; import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome; import com.dfsek.terra.api.registry.Registry; import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; public class PipelineBiomeLoader implements TypeLoader { private final Registry biomeRegistry; - public PipelineBiomeLoader(Registry biomeRegistry) { + private final BiomeTagIndex tagIndex; + private final ConcurrentHashMap placeholders = new ConcurrentHashMap<>(); + + public PipelineBiomeLoader(Registry biomeRegistry, BiomeTagIndex tagIndex) { this.biomeRegistry = biomeRegistry; + this.tagIndex = tagIndex; } @Override @@ -27,6 +33,6 @@ public class PipelineBiomeLoader implements TypeLoader { return biomeRegistry .getByID((String) c) .map(PipelineBiome::from) - .orElseGet(() -> PipelineBiome.placeholder((String) c)); + .orElseGet(() -> placeholders.computeIfAbsent((String) c, id -> PipelineBiome.placeholder(id, tagIndex))); } } diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderListStageTemplate.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderListStageTemplate.java index 4d767ef26..e5a70fe95 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderListStageTemplate.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderListStageTemplate.java @@ -17,15 +17,16 @@ import com.dfsek.terra.addons.biome.pipeline.config.stage.StageTemplate; import com.dfsek.terra.addons.biome.pipeline.stage.mutators.BorderListStage; import com.dfsek.terra.api.config.meta.Meta; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; @SuppressWarnings("unused") public class BorderListStageTemplate extends StageTemplate { @Value("from") - private @Meta String from; + private @Meta BiomeTag from; @Value("default-replace") - private @Meta String defaultReplace; + private @Meta BiomeTag defaultReplace; @Value("default-to") private @Meta ProbabilityCollection<@Meta PipelineBiome> defaultTo; diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderStageTemplate.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderStageTemplate.java index 4aa3e83ed..b8694e471 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderStageTemplate.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderStageTemplate.java @@ -15,15 +15,16 @@ import com.dfsek.terra.addons.biome.pipeline.config.stage.StageTemplate; import com.dfsek.terra.addons.biome.pipeline.stage.mutators.BorderStage; import com.dfsek.terra.api.config.meta.Meta; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; @SuppressWarnings("unused") public class BorderStageTemplate extends StageTemplate { @Value("from") - private @Meta String from; + private @Meta BiomeTag from; @Value("replace") - private @Meta String replace; + private @Meta BiomeTag replace; @Value("to") private @Meta ProbabilityCollection<@Meta PipelineBiome> to; diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceListStageTemplate.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceListStageTemplate.java index e1cfcb4cb..42b237c80 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceListStageTemplate.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceListStageTemplate.java @@ -17,12 +17,13 @@ import com.dfsek.terra.addons.biome.pipeline.config.stage.StageTemplate; import com.dfsek.terra.addons.biome.pipeline.stage.mutators.ReplaceListStage; import com.dfsek.terra.api.config.meta.Meta; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; @SuppressWarnings("unused") public class ReplaceListStageTemplate extends StageTemplate { @Value("default-from") - private @Meta String defaultFrom; + private @Meta BiomeTag defaultFrom; @Value("default-to") private @Meta ProbabilityCollection<@Meta PipelineBiome> defaultTo; diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceStageTemplate.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceStageTemplate.java index 4c2d33266..92a33d5e1 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceStageTemplate.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceStageTemplate.java @@ -15,12 +15,13 @@ import com.dfsek.terra.addons.biome.pipeline.config.stage.StageTemplate; import com.dfsek.terra.addons.biome.pipeline.stage.mutators.ReplaceStage; import com.dfsek.terra.api.config.meta.Meta; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; @SuppressWarnings("unused") public class ReplaceStageTemplate extends StageTemplate { @Value("from") - private @Meta String from; + private @Meta BiomeTag from; @Value("to") private @Meta ProbabilityCollection<@Meta PipelineBiome> to; diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderListStage.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderListStage.java index dd4e64e5d..01b96aa21 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderListStage.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderListStage.java @@ -21,24 +21,29 @@ import com.dfsek.terra.addons.biome.pipeline.api.Stage; import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome; import com.dfsek.terra.addons.biome.pipeline.pipeline.BiomeChunkImpl; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; public class BorderListStage implements Stage { - private final String border; + private final BiomeTag border; private final Sampler Sampler; private final ProbabilityCollection replaceDefault; - private final String defaultReplace; + private final BiomeTag defaultReplace; private final Map> replace; + // By PipelineBiome#getIntID(); relies on one ID per biome name. + private final ProbabilityCollection[] replaceById; private final Vector2Int[] borderPoints; - public BorderListStage(Map> replace, String border, String defaultReplace, + public BorderListStage(Map> replace, BiomeTag border, + BiomeTag defaultReplace, Sampler Sampler, ProbabilityCollection replaceDefault) { this.border = border; this.Sampler = Sampler; this.replaceDefault = replaceDefault; this.defaultReplace = defaultReplace; this.replace = replace; + this.replaceById = ReplaceTable.byId(replace); List points = new ArrayList<>(); for(int x = -1; x <= 1; x++) { @@ -63,12 +68,14 @@ public class BorderListStage implements Stage { @Override public PipelineBiome apply(BiomeChunkImpl.ViewPoint viewPoint) { PipelineBiome center = viewPoint.getBiome(); - if(center.getTags().contains(defaultReplace)) { + int centerId = center.getIntID(); + if(defaultReplace.has(centerId)) { for(Vector2Int point : borderPoints) { PipelineBiome current = viewPoint.getRelativeBiome(point.getX(), point.getZ()); - if(current != null && current.getTags().contains(border)) { - if(replace.containsKey(center)) { - PipelineBiome replacement = replace.get(center).get(Sampler, viewPoint.worldX(), viewPoint.worldZ(), + if(current != null && border.has(current.getIntID())) { + ProbabilityCollection collection = centerId < replaceById.length ? replaceById[centerId] : null; + if(collection != null) { + PipelineBiome replacement = collection.get(Sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed()); return replacement.isSelf() ? center : replacement; } diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderStage.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderStage.java index 339fdb366..78a14cadb 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderStage.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderStage.java @@ -20,16 +20,17 @@ import com.dfsek.terra.addons.biome.pipeline.api.Stage; import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome; import com.dfsek.terra.addons.biome.pipeline.pipeline.BiomeChunkImpl; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; public class BorderStage implements Stage { - private final String border; + private final BiomeTag border; private final Sampler Sampler; private final ProbabilityCollection replace; - private final String replaceTag; + private final BiomeTag replaceTag; private final Vector2Int[] borderPoints; - public BorderStage(String border, String replaceTag, Sampler Sampler, ProbabilityCollection replace) { + public BorderStage(BiomeTag border, BiomeTag replaceTag, Sampler Sampler, ProbabilityCollection replace) { this.border = border; this.Sampler = Sampler; this.replace = replace; @@ -47,10 +48,10 @@ public class BorderStage implements Stage { @Override public PipelineBiome apply(BiomeChunkImpl.ViewPoint viewPoint) { PipelineBiome center = viewPoint.getBiome(); - if(center.getTags().contains(replaceTag)) { + if(replaceTag.has(center.getIntID())) { for(Vector2Int point : borderPoints) { PipelineBiome current = viewPoint.getRelativeBiome(point.getX(), point.getZ()); - if(current != null && current.getTags().contains(border)) { + if(current != null && border.has(current.getIntID())) { PipelineBiome replacement = replace.get(Sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed()); return replacement.isSelf() ? center : replacement; } diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceListStage.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceListStage.java index ca4f0db09..c14843ca7 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceListStage.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceListStage.java @@ -18,17 +18,21 @@ import com.dfsek.terra.addons.biome.pipeline.api.Stage; import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome; import com.dfsek.terra.addons.biome.pipeline.pipeline.BiomeChunkImpl; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; public class ReplaceListStage implements Stage { private final Map> replace; + // By PipelineBiome#getIntID(); relies on one ID per biome name. + private final ProbabilityCollection[] replaceById; private final Sampler sampler; private final ProbabilityCollection replaceDefault; - private final String defaultTag; + private final BiomeTag defaultTag; - public ReplaceListStage(Map> replace, String defaultTag, + public ReplaceListStage(Map> replace, BiomeTag defaultTag, ProbabilityCollection replaceDefault, Sampler sampler) { this.replace = replace; + this.replaceById = ReplaceTable.byId(replace); this.sampler = sampler; this.defaultTag = defaultTag; this.replaceDefault = replaceDefault; @@ -37,11 +41,13 @@ public class ReplaceListStage implements Stage { @Override public PipelineBiome apply(BiomeChunkImpl.ViewPoint viewPoint) { PipelineBiome center = viewPoint.getBiome(); - if(replace.containsKey(center)) { - PipelineBiome biome = replace.get(center).get(sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed()); + int id = center.getIntID(); + ProbabilityCollection collection = id < replaceById.length ? replaceById[id] : null; + if(collection != null) { + PipelineBiome biome = collection.get(sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed()); return biome.isSelf() ? viewPoint.getBiome() : biome; } - if(viewPoint.getBiome().getTags().contains(defaultTag)) { + if(defaultTag.has(id)) { PipelineBiome biome = replaceDefault.get(sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed()); return biome.isSelf() ? viewPoint.getBiome() : biome; } @@ -60,7 +66,7 @@ public class ReplaceListStage implements Stage { Set reject = new HashSet<>(); biomes.forEach(biome -> { - if(!biome.getTags().contains(defaultTag) && !replace.containsKey(biome)) { + if(!biome.getTags().contains(defaultTag.name()) && !replace.containsKey(biome)) { biomeSet.add(biome); } else { reject.add(biome); diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceStage.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceStage.java index 2c7ab9bf9..23c3be4ef 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceStage.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceStage.java @@ -17,14 +17,15 @@ import com.dfsek.terra.addons.biome.pipeline.api.Stage; import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome; import com.dfsek.terra.addons.biome.pipeline.pipeline.BiomeChunkImpl; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; public class ReplaceStage implements Stage { - private final String replaceableTag; + private final BiomeTag replaceableTag; private final ProbabilityCollection replace; private final Sampler sampler; - public ReplaceStage(String replaceable, ProbabilityCollection replace, Sampler sampler) { + public ReplaceStage(BiomeTag replaceable, ProbabilityCollection replace, Sampler sampler) { this.replaceableTag = replaceable; this.replace = replace; this.sampler = sampler; @@ -32,7 +33,7 @@ public class ReplaceStage implements Stage { @Override public PipelineBiome apply(BiomeChunkImpl.ViewPoint viewPoint) { - if(viewPoint.getBiome().getTags().contains(replaceableTag)) { + if(replaceableTag.has(viewPoint.getBiome().getIntID())) { PipelineBiome biome = replace.get(sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed()); return biome.isSelf() ? viewPoint.getBiome() : biome; } @@ -49,7 +50,7 @@ public class ReplaceStage implements Stage { Set biomeSet = new HashSet<>(); Set reject = new HashSet<>(); biomes.forEach(biome -> { - if(!biome.getTags().contains(replaceableTag)) { + if(!biome.getTags().contains(replaceableTag.name())) { biomeSet.add(biome); } else { reject.add(biome); diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceTable.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceTable.java new file mode 100644 index 000000000..d0e285898 --- /dev/null +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceTable.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2020-2025 Polyhedral Development + * + * The Terra Core Addons are licensed under the terms of the MIT License. For more details, + * reference the LICENSE file in this module's root directory. + */ + +package com.dfsek.terra.addons.biome.pipeline.stage.mutators; + +import java.util.Map; + +import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome; +import com.dfsek.terra.api.util.collection.ProbabilityCollection; + + +final class ReplaceTable { + private ReplaceTable() { } + + @SuppressWarnings("unchecked") + static ProbabilityCollection[] byId(Map> replace) { + int max = -1; + for(PipelineBiome key : replace.keySet()) max = Math.max(max, key.getIntID()); + ProbabilityCollection[] table = new ProbabilityCollection[max + 1]; + replace.forEach((key, value) -> table[key.getIntID()] = value); + return table; + } +} diff --git a/common/addons/biome-provider-pipeline/src/test/java/pipeline/PipelineBiomeTagTest.java b/common/addons/biome-provider-pipeline/src/test/java/pipeline/PipelineBiomeTagTest.java new file mode 100644 index 000000000..ffe9f5373 --- /dev/null +++ b/common/addons/biome-provider-pipeline/src/test/java/pipeline/PipelineBiomeTagTest.java @@ -0,0 +1,190 @@ +package pipeline; + +import com.dfsek.seismic.type.sampler.Sampler; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.lang.reflect.AnnotatedType; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import com.dfsek.terra.addons.biome.pipeline.api.Source; +import com.dfsek.terra.addons.biome.pipeline.api.Stage; +import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome; +import com.dfsek.terra.addons.biome.pipeline.config.PipelineBiomeLoader; +import com.dfsek.terra.addons.biome.pipeline.pipeline.PipelineImpl; +import com.dfsek.terra.addons.biome.pipeline.stage.mutators.BorderListStage; +import com.dfsek.terra.addons.biome.pipeline.stage.mutators.ReplaceListStage; +import com.dfsek.terra.addons.biome.pipeline.stage.mutators.ReplaceStage; +import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.registry.Registry; +import com.dfsek.terra.api.util.cache.SeededVector2Key; +import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.biome.PlatformBiome; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; + +import static org.junit.jupiter.api.Assertions.*; + + +class PipelineBiomeTagTest { + private static final Sampler SAMPLER = new Sampler() { + @Override + public double getSample(long seed, double x, double y) { + return 0; + } + + @Override + public double getSample(long seed, double x, double y, double z) { + return 0; + } + }; + + private static final class StubBiome implements Biome { + private final String id; + private final Set tags; + private final int intId; + + StubBiome(BiomeTagIndex index, String id, Set tags) { + this.id = id; + this.tags = tags; + this.intId = index.register(tags); + } + + @Override + public PlatformBiome getPlatformBiome() { + return null; + } + + @Override + public int getColor() { + return 0; + } + + @Override + public Set getTags() { + return tags; + } + + @Override + public int getIntID() { + return intId; + } + + @Override + public Context getContext() { + return null; + } + + @Override + public String getID() { + return id; + } + } + + @SuppressWarnings("unchecked") + private static Registry emptyRegistry() { + return (Registry) Proxy.newProxyInstance(Registry.class.getClassLoader(), new Class[]{ Registry.class }, + (proxy, method, args) -> { + if(method.getName().equals("getByID")) return Optional.empty(); + throw new UnsupportedOperationException(method.getName()); + }); + } + + private final BiomeTagIndex index = new BiomeTagIndex(); + private final Map biomes = new LinkedHashMap<>(); + + { + biome("border", "border"); + biome("c", "R", "D"); + biome("a", "R"); + biome("b", "R"); + biome("x"); + biome("y"); + biome("e"); + biome("f", "R", "D"); + } + + private void biome(String id, String... tags) { + biomes.put(id, PipelineBiome.from(new StubBiome(index, id, Set.of(tags)))); + } + + private static ProbabilityCollection only(PipelineBiome biome) { + return new ProbabilityCollection().add(biome, 1); + } + + private Map> replaceTable() { + Map> replace = new HashMap<>(); + replace.put(biomes.get("a"), only(biomes.get("x"))); + replace.put(biomes.get("b"), only(PipelineBiome.self())); + return replace; + } + + private String run(Stage stage, String centre) { + index.seal(); + PipelineBiome centreBiome = biomes.get(centre); + PipelineBiome border = biomes.get("border"); + Source source = new Source() { + @Override + public PipelineBiome get(long seed, int x, int z) { + return x == 0 && z == 0 ? centreBiome : border; + } + + @Override + public Iterable getBiomes() { + return List.of(centreBiome, border); + } + }; + return new PipelineImpl(source, List.of(stage), 1, 3).generateChunk(new SeededVector2Key(0, 0, 0)).get(0, 0).getID(); + } + + @ParameterizedTest(name = "{0} -> {1}") + @CsvSource({ "a, x", "b, b", "c, y", "e, e", "f, y" }) + void borderListStage(String centre, String expected) { + assertEquals(expected, run(new BorderListStage(replaceTable(), index.tag("border"), index.tag("R"), SAMPLER, + only(biomes.get("y"))), centre)); + } + + @ParameterizedTest(name = "{0} -> {1}") + @CsvSource({ "a, x", "b, b", "c, y", "e, e", "f, y" }) + void replaceListStage(String centre, String expected) { + assertEquals(expected, run(new ReplaceListStage(replaceTable(), index.tag("D"), only(biomes.get("y")), SAMPLER), centre)); + } + + @ParameterizedTest(name = "{0}: {1} -> {2}") + @CsvSource({ "D, c, y", "D, e, e", "TYPO, c, c", "TYPO, e, e" }) + void replaceStage(String tag, String centre, String expected) { + assertEquals(expected, run(new ReplaceStage(index.tag(tag), only(biomes.get("y")), SAMPLER), centre)); + } + + @Test + void placeholderRegistration() { + PipelineBiomeLoader loader = new PipelineBiomeLoader(emptyRegistry(), index); + int before = index.size(); + PipelineBiome first = load(loader, "OCEAN"); + assertSame(first, load(loader, "OCEAN")); + assertEquals(before + 1, index.size()); + assertDoesNotThrow(() -> load(loader, "ALL")); + index.seal(); + assertTrue(index.tag("OCEAN").has(first.getIntID())); + assertTrue(index.tag("ALL").has(first.getIntID())); + assertFalse(index.tag("OTHER").has(first.getIntID())); + } + + @Test + void selfHasNoTags() { + assertEquals(0, PipelineBiome.self().getIntID()); + index.seal(); + assertFalse(index.tag("ALL").has(PipelineBiome.self().getIntID())); + } + + private static PipelineBiome load(PipelineBiomeLoader loader, String id) { + return loader.load((AnnotatedType) null, id, null, null); + } +} diff --git a/common/addons/biome-query-api/README.md b/common/addons/biome-query-api/README.md deleted file mode 100644 index e8e2a800c..000000000 --- a/common/addons/biome-query-api/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# Biome Query API - -This addon contains an API to allow other addons to quickly query -Biome data, by baking queries and using Contexts on biomes. \ No newline at end of file diff --git a/common/addons/biome-query-api/build.gradle.kts b/common/addons/biome-query-api/build.gradle.kts deleted file mode 100644 index 9d0aac37f..000000000 --- a/common/addons/biome-query-api/build.gradle.kts +++ /dev/null @@ -1,5 +0,0 @@ -version = version("1.0.0") - -dependencies { - compileOnlyApi(project(":common:addons:manifest-addon-loader")) -} diff --git a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/BiomeQueryAPIAddon.java b/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/BiomeQueryAPIAddon.java deleted file mode 100644 index 40afa4130..000000000 --- a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/BiomeQueryAPIAddon.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.dfsek.terra.addons.biome.query; - -import java.util.Collection; - -import com.dfsek.terra.addons.biome.query.impl.BiomeTagFlattener; -import com.dfsek.terra.addons.biome.query.impl.BiomeTagHolder; -import com.dfsek.terra.addons.manifest.api.AddonInitializer; -import com.dfsek.terra.api.Platform; -import com.dfsek.terra.api.addon.BaseAddon; -import com.dfsek.terra.api.event.events.config.pack.ConfigPackPostLoadEvent; -import com.dfsek.terra.api.event.functional.FunctionalEventHandler; -import com.dfsek.terra.api.inject.annotations.Inject; -import com.dfsek.terra.api.properties.Context; -import com.dfsek.terra.api.properties.PropertyKey; -import com.dfsek.terra.api.world.biome.Biome; - - -public class BiomeQueryAPIAddon implements AddonInitializer { - public static PropertyKey BIOME_TAG_KEY = Context.create(BiomeTagHolder.class); - @Inject - private Platform platform; - @Inject - private BaseAddon addon; - - @Override - public void initialize() { - - platform.getEventManager() - .getHandler(FunctionalEventHandler.class) - .register(addon, ConfigPackPostLoadEvent.class) - .then(event -> { - Collection biomes = event - .getPack() - .getRegistry(Biome.class) - .entries(); - - BiomeTagFlattener flattener = new BiomeTagFlattener(biomes - .stream() - .flatMap(biome -> biome.getTags().stream()) - .toList()); - - biomes.forEach(biome -> biome.getContext().put(BIOME_TAG_KEY, new BiomeTagHolder(biome, flattener))); - }) - .global(); - } -} diff --git a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/api/BiomeQueries.java b/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/api/BiomeQueries.java deleted file mode 100644 index 4066e048e..000000000 --- a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/api/BiomeQueries.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.dfsek.terra.addons.biome.query.api; - -import java.util.function.Predicate; - -import com.dfsek.terra.addons.biome.query.impl.SingleTagQuery; -import com.dfsek.terra.api.world.biome.Biome; - - -public final class BiomeQueries { - private BiomeQueries() { - - } - - public static Predicate has(String tag) { - return new SingleTagQuery(tag); - } -} diff --git a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagFlattener.java b/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagFlattener.java deleted file mode 100644 index c52851598..000000000 --- a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagFlattener.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.dfsek.terra.addons.biome.query.impl; - -import java.util.List; - - -public class BiomeTagFlattener { - private final List tags; - - public BiomeTagFlattener(List tags) { - this.tags = tags; - } - - public int index(String tag) { - return tags.indexOf(tag); - } - - public int size() { - return tags.size(); - } -} diff --git a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagHolder.java b/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagHolder.java deleted file mode 100644 index 4d4f34fea..000000000 --- a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagHolder.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.dfsek.terra.addons.biome.query.impl; - -import com.dfsek.terra.api.properties.Properties; -import com.dfsek.terra.api.world.biome.Biome; - - -public class BiomeTagHolder implements Properties { - private final boolean[] tags; - private final BiomeTagFlattener flattener; - - public BiomeTagHolder(Biome biome, BiomeTagFlattener flattener) { - this.tags = new boolean[flattener.size()]; - this.flattener = flattener; - for(String tag : biome.getTags()) { - tags[flattener.index(tag)] = true; - } - } - - boolean get(int index) { - return tags[index]; - } - - public BiomeTagFlattener getFlattener() { - return flattener; - } -} diff --git a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/SingleTagQuery.java b/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/SingleTagQuery.java deleted file mode 100644 index 1e39408c2..000000000 --- a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/SingleTagQuery.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.dfsek.terra.addons.biome.query.impl; - -import java.util.function.Predicate; - -import com.dfsek.terra.addons.biome.query.BiomeQueryAPIAddon; -import com.dfsek.terra.api.world.biome.Biome; - - -public class SingleTagQuery implements Predicate { - private final String tag; - private int tagIndex = -1; - - public SingleTagQuery(String tag) { - this.tag = tag; - } - - @Override - public boolean test(Biome biome) { - if(tagIndex < 0) { - tagIndex = biome - .getContext() - .get(BiomeQueryAPIAddon.BIOME_TAG_KEY) - .getFlattener() - .index(tag); - } - return biome - .getContext() - .get(BiomeQueryAPIAddon.BIOME_TAG_KEY) - .get(tagIndex); - } -} diff --git a/common/addons/biome-query-api/src/main/resources/terra.addon.yml b/common/addons/biome-query-api/src/main/resources/terra.addon.yml deleted file mode 100644 index 8a55ce2dc..000000000 --- a/common/addons/biome-query-api/src/main/resources/terra.addon.yml +++ /dev/null @@ -1,12 +0,0 @@ -schema-version: 1 -contributors: - - Terra contributors -id: biome-query-api -version: @VERSION@ -entrypoints: - - "com.dfsek.terra.addons.biome.query.BiomeQueryAPIAddon" -website: - issues: https://github.com/PolyhedralDev/Terra/issues - source: https://github.com/PolyhedralDev/Terra - docs: https://terra.polydev.org -license: MIT License \ No newline at end of file diff --git a/common/addons/config-biome/build.gradle.kts b/common/addons/config-biome/build.gradle.kts index 9d0aac37f..57b95fdb4 100644 --- a/common/addons/config-biome/build.gradle.kts +++ b/common/addons/config-biome/build.gradle.kts @@ -2,4 +2,6 @@ version = version("1.0.0") dependencies { compileOnlyApi(project(":common:addons:manifest-addon-loader")) + + testImplementation("com.dfsek.tectonic", "common", Versions.Libraries.tectonic) } diff --git a/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/BiomeTemplate.java b/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/BiomeTemplate.java index 102a70ef5..2c371f6f6 100644 --- a/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/BiomeTemplate.java +++ b/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/BiomeTemplate.java @@ -11,6 +11,7 @@ import com.dfsek.tectonic.api.config.template.ValidatedConfigTemplate; import com.dfsek.tectonic.api.config.template.annotations.Default; import com.dfsek.tectonic.api.config.template.annotations.Final; import com.dfsek.tectonic.api.config.template.annotations.Value; +import com.dfsek.tectonic.api.exception.ValidationException; import java.util.Collections; import java.util.HashSet; @@ -21,6 +22,7 @@ import com.dfsek.terra.api.Platform; import com.dfsek.terra.api.config.AbstractableTemplate; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.config.meta.Meta; +import com.dfsek.terra.api.registry.key.RegistryKey; import com.dfsek.terra.api.world.biome.PlatformBiome; @@ -48,13 +50,29 @@ public class BiomeTemplate implements AbstractableTemplate, ValidatedConfigTempl @Default private @Meta Set<@Meta String> tags = new HashSet<>(); + private Set platformTags = Set.of(); + public BiomeTemplate(ConfigPack pack, Platform platform) { this.pack = pack; } @Override - public boolean validate() { + public boolean validate() throws ValidationException { color |= 0xff000000; // Alpha adjustment + Set parsed = new HashSet<>(); + for(String tag : tags) { + int colon = tag.indexOf(':'); + if(colon < 0) continue; + // RegistryKey.parse accepts an empty namespace or ID. + if(colon == 0) throw new ValidationException("Invalid namespaced biome tag \"" + tag + "\": the namespace is empty"); + if(colon == tag.length() - 1) throw new ValidationException("Invalid namespaced biome tag \"" + tag + "\": the ID is empty"); + try { + parsed.add(RegistryKey.parse(tag)); + } catch(IllegalArgumentException e) { + throw new ValidationException("Invalid namespaced biome tag \"" + tag + "\": " + e.getMessage()); + } + } + platformTags = Set.copyOf(parsed); return true; } @@ -66,6 +84,10 @@ public class BiomeTemplate implements AbstractableTemplate, ValidatedConfigTempl return tags; } + public Set getPlatformTags() { + return platformTags; + } + public int getColor() { return color; } diff --git a/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/UserDefinedBiome.java b/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/UserDefinedBiome.java index 4729f60df..443871b11 100644 --- a/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/UserDefinedBiome.java +++ b/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/UserDefinedBiome.java @@ -7,10 +7,11 @@ package com.dfsek.terra.addons.biome; +import java.util.HashSet; import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.registry.key.RegistryKey; import com.dfsek.terra.api.world.biome.Biome; import com.dfsek.terra.api.world.biome.PlatformBiome; @@ -24,6 +25,7 @@ public class UserDefinedBiome implements Biome { private final BiomeTemplate config; private final int color; private final Set tags; + private final Set platformTags; private final Context context = new Context(); private final int intID; @@ -33,10 +35,12 @@ public class UserDefinedBiome implements Biome { this.id = config.getID(); this.config = config; this.color = config.getColor(); - this.tags = config.getTags(); - this.intID = INT_ID_COUNTER.getAndIncrement(); - tags.add("BIOME:" + id); - tags.add("ALL"); + Set allTags = new HashSet<>(config.getTags()); + allTags.add("BIOME:" + id); + allTags.add("ALL"); + this.tags = Set.copyOf(allTags); + this.platformTags = Set.copyOf(config.getPlatformTags()); + this.intID = config.getPack().getBiomeTagIndex().register(tags); } @Override @@ -64,6 +68,11 @@ public class UserDefinedBiome implements Biome { return tags; } + @Override + public Set getPlatformTags() { + return platformTags; + } + @Override public int getIntID() { return intID; diff --git a/common/addons/config-biome/src/test/java/biome/PlatformTagsTest.java b/common/addons/config-biome/src/test/java/biome/PlatformTagsTest.java new file mode 100644 index 000000000..6ab3113b7 --- /dev/null +++ b/common/addons/config-biome/src/test/java/biome/PlatformTagsTest.java @@ -0,0 +1,68 @@ +package biome; + +import com.dfsek.tectonic.api.exception.ValidationException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.lang.reflect.Field; +import java.lang.reflect.Proxy; +import java.util.HashSet; +import java.util.Set; + +import com.dfsek.terra.addons.biome.BiomeTemplate; +import com.dfsek.terra.addons.biome.UserDefinedBiome; +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class PlatformTagsTest { + private static BiomeTemplate template(String... tags) throws ReflectiveOperationException { + BiomeTagIndex index = new BiomeTagIndex(); + ConfigPack pack = (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class[]{ ConfigPack.class }, + (proxy, method, args) -> { + if(method.getName().equals("getBiomeTagIndex")) return index; + throw new UnsupportedOperationException(method.getName()); + }); + BiomeTemplate template = new BiomeTemplate(pack, null); + set(template, "id", "TEST"); + set(template, "tags", new HashSet<>(Set.of(tags))); + return template; + } + + private static void set(BiomeTemplate template, String field, Object value) throws ReflectiveOperationException { + Field f = BiomeTemplate.class.getDeclaredField(field); + f.setAccessible(true); + f.set(template, value); + } + + @Test + void platformTags() throws Exception { + BiomeTemplate template = template("USE_RIVER", "minecraft:is_forest", "c:hot"); + template.validate(); + UserDefinedBiome biome = new UserDefinedBiome(null, template); + + assertEquals(Set.of(RegistryKey.parse("minecraft:is_forest"), RegistryKey.parse("c:hot")), biome.getPlatformTags()); + assertEquals(Set.of("USE_RIVER", "minecraft:is_forest", "c:hot", "BIOME:TEST", "ALL"), biome.getTags()); + assertThrows(UnsupportedOperationException.class, () -> biome.getTags().add("X")); + assertFalse(template.getTags().contains("BIOME:TEST")); + } + + @ParameterizedTest(name = "{0}") + @CsvSource(delimiter = '|', value = { + "minecraft:Bad Tag | minecraft:Bad Tag", + ":is_forest | empty", + "minecraft: | empty", + }) + void invalidNamespacedTag(String tag, String reasonPart) throws Exception { + ValidationException e = assertThrows(ValidationException.class, template(tag)::validate); + assertTrue(e.getMessage().contains("\"" + tag + "\""), e.getMessage()); + assertTrue(e.getMessage().contains(reasonPart), e.getMessage()); + } +} diff --git a/common/addons/pipeline-image/src/main/resources/terra.addon.yml b/common/addons/pipeline-image/src/main/resources/terra.addon.yml index 750434fba..4be0186ed 100644 --- a/common/addons/pipeline-image/src/main/resources/terra.addon.yml +++ b/common/addons/pipeline-image/src/main/resources/terra.addon.yml @@ -12,4 +12,4 @@ website: license: MIT License depends: library-image: "1.+" - biome-provider-pipeline: "2.+" + biome-provider-pipeline: "3.+" diff --git a/common/api/src/main/java/com/dfsek/terra/api/config/ConfigPack.java b/common/api/src/main/java/com/dfsek/terra/api/config/ConfigPack.java index a9fd6982b..ebc621471 100644 --- a/common/api/src/main/java/com/dfsek/terra/api/config/ConfigPack.java +++ b/common/api/src/main/java/com/dfsek/terra/api/config/ConfigPack.java @@ -26,6 +26,7 @@ import com.dfsek.terra.api.tectonic.LoaderRegistrar; import com.dfsek.terra.api.tectonic.ShortcutLoader; import com.dfsek.terra.api.util.reflection.TypeKey; import com.dfsek.terra.api.world.biome.generation.BiomeProvider; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; import com.dfsek.terra.api.world.chunk.generation.stage.GenerationStage; import com.dfsek.terra.api.world.chunk.generation.util.provider.ChunkGeneratorProvider; @@ -43,6 +44,11 @@ public interface ConfigPack extends LoaderRegistrar, BiomeProvider getBiomeProvider(); + /** + * @return this pack's biome tag index; sealed once the pack has finished loading + */ + BiomeTagIndex getBiomeTagIndex(); + List getStages(); Path getRootPath(); diff --git a/common/api/src/main/java/com/dfsek/terra/api/util/collection/TriStateIntCache.java b/common/api/src/main/java/com/dfsek/terra/api/util/collection/TriStateIntCache.java deleted file mode 100644 index 6b2ac54e9..000000000 --- a/common/api/src/main/java/com/dfsek/terra/api/util/collection/TriStateIntCache.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.dfsek.terra.api.util.collection; - -import java.lang.invoke.MethodHandles; -import java.lang.invoke.VarHandle; - -import com.dfsek.seismic.util.UnsafeUtils; - - -public class TriStateIntCache { - public static final long STATE_UNSET = 0L; - public static final long STATE_FALSE = 1L; - public static final long STATE_TRUE = 2L; - - private static final long BIT_MASK = 3L; - private final long[] data; - - private static final VarHandle ARRAY_HANDLE = MethodHandles.arrayElementVarHandle(long[].class); - - private static int getOptimalMaxKeys(int requestedKeys) { - // 192 keys fill the first cache line exactly (along with the 16-byte header) - if (requestedKeys <= 192) { - return 192; - } - - // For every additional line, we fit 256 keys (64 bytes * 4 keys/byte) - // We calculate the overflow beyond 192, round up to the nearest 256, and add it back. - int overflow = requestedKeys - 192; - int chunks = (overflow + 255) >>> 8; // Fast ceil division by 256 - - return 192 + (chunks << 8); // chunks * 256 - } - - public TriStateIntCache(int maxKeySize) { - this.data = new long[(getOptimalMaxKeys(maxKeySize) + 31) >>> 5]; - } - - /** - * Checks the cache state without any allocation. - * - * @return STATE_UNSET (0), STATE_FALSE (1), or STATE_TRUE (2) - */ - public long get(int key) { - long offset = UnsafeUtils.LONG_ARRAY_BASE + ((long)(key >>> 5) << UnsafeUtils.LONG_ARRAY_SHIFT); - long currentWord = UnsafeUtils.UNSAFE.getLong(data, offset); - return (currentWord >>> ((key << 1) & 63)) & BIT_MASK; - } - - /** - * Sets the value safely. Handles race conditions internally. - */ - public void set(int key, boolean value) { - int index = key >>> 5; - int shift = (key << 1) & 63; - - long targetWord = (value ? STATE_TRUE : STATE_FALSE) << shift; - - long current; - do { - current = (long) ARRAY_HANDLE.getVolatile(data, index); - - if (((current >>> shift) & BIT_MASK) != STATE_UNSET) { - return; - } - - } while (!ARRAY_HANDLE.compareAndSet(data, index, current, current | targetWord)); - } -} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/biome/Biome.java b/common/api/src/main/java/com/dfsek/terra/api/world/biome/Biome.java index e43a4d2ff..aedf2c4eb 100644 --- a/common/api/src/main/java/com/dfsek/terra/api/world/biome/Biome.java +++ b/common/api/src/main/java/com/dfsek/terra/api/world/biome/Biome.java @@ -8,10 +8,12 @@ package com.dfsek.terra.api.world.biome; +import org.jetbrains.annotations.NotNull; + import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; import com.dfsek.terra.api.properties.PropertyHolder; +import com.dfsek.terra.api.registry.key.RegistryKey; import com.dfsek.terra.api.registry.key.StringIdentifiable; @@ -19,8 +21,6 @@ import com.dfsek.terra.api.registry.key.StringIdentifiable; * Represents a Terra biome */ public interface Biome extends PropertyHolder, StringIdentifiable { - AtomicInteger INT_ID_COUNTER = new AtomicInteger(0); - /** * Gets the platform biome this custom biome delegates to. * @@ -42,9 +42,17 @@ public interface Biome extends PropertyHolder, StringIdentifiable { */ Set getTags(); + /** + * Get the namespaced entries of this biome's config {@code tags:}, as written. + */ + default @NotNull Set getPlatformTags() { + return Set.of(); + } + /** - * Get the numeric ID of this biome, generated at registration time + * Get the numeric ID of this biome: dense per pack, from 1, issued by {@code getBiomeTagIndex().register(...)} during pack + * load. * * @return The numeric ID. */ diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTag.java b/common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTag.java new file mode 100644 index 000000000..90c3be619 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTag.java @@ -0,0 +1,79 @@ +package com.dfsek.terra.api.world.biome.tag; + +import com.dfsek.seismic.util.UnsafeUtils; + +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; + +import com.dfsek.terra.api.world.biome.Biome; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + + +/** + * Biome IDs are not stable across loads; never persist one. + */ +public final class BiomeTag implements Predicate { + // Lets has() on an unsealed tag return false for IDs below 512. + private static final long[] UNSEALED = new long[8]; + + private final String name; + private final BiomeTagIndex index; + + // Not volatile: published by the index's volatile sealed flag, or by the index lock for tags created after seal. + private long[] bits = UNSEALED; + + BiomeTag(String name, BiomeTagIndex index) { + this.name = name; + this.index = index; + } + + @NotNull + @Contract(pure = true) + public String name() { + return name; + } + + /** + * No bounds checks. Only call after the owning {@link BiomeTagIndex} is sealed, with IDs from that index. + */ + public boolean has(int biomeId) { + long word = UnsafeUtils.UNSAFE.getLong(bits, + UnsafeUtils.LONG_ARRAY_BASE + ((long) (biomeId >>> 6) << UnsafeUtils.LONG_ARRAY_SHIFT)); + return ((word >>> biomeId) & 1L) != 0L; + } + + /** + * Doesn't detect a biome from another pack whose ID is in range. + * + * @throws IllegalArgumentException if sealed and the biome's ID is outside this tag's bitset + */ + @Override + public boolean test(Biome biome) { + if(!index.isSealed()) { // volatile read: also publishes bits built by seal + return biome.getTags().contains(name); + } + int id = biome.getIntID(); + if(id < 0 || id >= (bits.length << 6)) { + throw new IllegalArgumentException("biome id " + id + " is not from this tag's pack"); + } + return has(id); + } + + long[] bits() { + return bits; + } + + void build(int size, List> tagSets) { + // Whole 64-byte lines: every ID below size is in bounds. + long[] built = new long[((size + 511) >>> 9) << 3]; + for(int id = 1; id < size; id++) { + if(tagSets.get(id).contains(name)) { + built[id >>> 6] |= 1L << id; + } + } + this.bits = built; + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndex.java b/common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndex.java new file mode 100644 index 000000000..dbee73498 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndex.java @@ -0,0 +1,74 @@ +package com.dfsek.terra.api.world.biome.tag; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + + +/** + * ID 0 is reserved. Biomes register during pack load; the platform seals the index once the pack is built. + */ +public final class BiomeTagIndex { + private final ConcurrentHashMap tags = new ConcurrentHashMap<>(); + private final List> tagSets = new ArrayList<>(); // guarded by this + private volatile boolean sealed = false; + + public BiomeTagIndex() { + tagSets.add(Set.of()); + } + + /** + * @return a dense ID, at least 1 + * + * @throws IllegalStateException if sealed + */ + public synchronized int register(Set biomeTags) { + if(sealed) throw new IllegalStateException("BiomeTagIndex is sealed"); + tagSets.add(Set.copyOf(biomeTags)); + return tagSets.size() - 1; + } + + /** + * Never released: resolve each tag once at pack load, not per sample. + */ + @NotNull + public BiomeTag tag(String name) { + BiomeTag existing = tags.get(name); + // The volatile read of sealed publishes the bits; before seal, the lock does. + if(existing != null && sealed) return existing; + synchronized(this) { + BiomeTag tag = tags.get(name); + if(tag == null) { + tag = new BiomeTag(name, this); + if(sealed) tag.build(tagSets.size(), tagSets); + tags.put(name, tag); + } + return tag; + } + } + + @ApiStatus.Internal + public synchronized void seal() { + if(sealed) return; + int size = tagSets.size(); + for(BiomeTag tag : tags.values()) tag.build(size, tagSets); + sealed = true; + } + + @Contract(pure = true) + public boolean isSealed() { + return sealed; + } + + /** + * @return number of IDs including the reserved 0 + */ + public synchronized int size() { + return tagSets.size(); + } +} diff --git a/common/api/src/test/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndexTest.java b/common/api/src/test/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndexTest.java new file mode 100644 index 000000000..975974b3e --- /dev/null +++ b/common/api/src/test/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndexTest.java @@ -0,0 +1,120 @@ +package com.dfsek.terra.api.world.biome.tag; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Proxy; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import com.dfsek.terra.api.world.biome.Biome; + +import static org.junit.jupiter.api.Assertions.*; + + +public class BiomeTagIndexTest { + @Test + public void denseIds() { + BiomeTagIndex index = new BiomeTagIndex(); + assertEquals(1, index.register(Set.of("A"))); + assertEquals(2, index.register(Set.of("B"))); + assertEquals(3, index.register(Set.of())); + assertEquals(4, index.size()); + } + + @Test + public void membershipAndInterning() { + BiomeTagIndex index = new BiomeTagIndex(); + int a = index.register(Set.of("X", "Z")); + int b = index.register(Set.of("X")); + int c = index.register(Set.of("Y")); + BiomeTag x = index.tag("X"); + index.seal(); + assertSame(x, index.tag("X")); + BiomeTag z = index.tag("Z"); + assertSame(z, index.tag("Z")); + assertEquals("Z", z.name()); + BiomeTag y = index.tag("Y"); + BiomeTag unknown = index.tag("NOPE"); + for(int id = 0; id < index.size(); id++) { + assertEquals(id == a || id == b, x.has(id), "X has " + id); + assertEquals(id == c, y.has(id), "Y has " + id); + assertEquals(id == a, z.has(id), "Z has " + id); + assertFalse(unknown.has(id), "unknown tag has " + id); + } + } + + @Test + public void sealing() { + BiomeTagIndex index = new BiomeTagIndex(); + int a = index.register(Set.of("X")); + index.seal(); + index.seal(); + assertTrue(index.isSealed()); + assertTrue(index.tag("X").has(a)); + assertThrows(IllegalStateException.class, () -> index.register(Set.of("X"))); + } + + @Test + public void parallelRegister() { + BiomeTagIndex index = new BiomeTagIndex(); + Set ids = IntStream.range(0, 10_000).parallel() + .mapToObj(i -> index.register(Set.of("T" + (i % 7)))) + .collect(Collectors.toSet()); + assertEquals(10_000, ids.size()); + assertEquals(1, ids.stream().mapToInt(Integer::intValue).min().getAsInt()); + assertEquals(10_000, ids.stream().mapToInt(Integer::intValue).max().getAsInt()); + assertEquals(10_001, index.size()); + index.seal(); + for(int id : ids) { + int matches = 0; + for(int t = 0; t < 7; t++) { + if(index.tag("T" + t).has(id)) matches++; + } + assertEquals(1, matches); + } + } + + @Test + public void bitsetSize() { + BiomeTagIndex index = new BiomeTagIndex(); + for(int i = 0; i < 600; i++) index.register(Set.of("X")); + BiomeTag x = index.tag("X"); + index.seal(); + assertEquals(0, x.bits().length % 8); + assertTrue(x.bits().length * 64L >= index.size()); + assertTrue(x.has(600)); + BiomeTag late = index.tag("LATE"); + assertEquals(0, late.bits().length % 8); + assertTrue(late.bits().length * 64L >= index.size()); + } + + private static Biome biome(int id, Set tags) { + return (Biome) Proxy.newProxyInstance(Biome.class.getClassLoader(), new Class[]{ Biome.class }, (proxy, method, args) -> + switch(method.getName()) { + case "getIntID" -> id; + case "getTags" -> tags; + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + + @Test + public void testBeforeAndAfterSeal() { + BiomeTagIndex index = new BiomeTagIndex(); + Set tagsA = Set.of("X"); + Set tagsB = Set.of("Y"); + Biome a = biome(index.register(tagsA), tagsA); + Biome b = biome(index.register(tagsB), tagsB); + BiomeTag x = index.tag("X"); + assertTrue(x.test(a)); + assertFalse(x.test(b)); + for(int i = 0; i < 512; i++) assertFalse(x.has(i)); + index.seal(); + assertTrue(x.has(a.getIntID())); + assertTrue(x.test(a)); + assertFalse(x.test(b)); + assertThrows(IllegalArgumentException.class, () -> x.test(biome(512, Set.of()))); + assertThrows(IllegalArgumentException.class, () -> x.test(biome(100_000, Set.of()))); + assertThrows(IllegalArgumentException.class, () -> x.test(biome(-1, Set.of()))); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/config/loaders/BiomeTagLoader.java b/common/implementation/base/src/main/java/com/dfsek/terra/config/loaders/BiomeTagLoader.java new file mode 100644 index 000000000..3b49d141e --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/config/loaders/BiomeTagLoader.java @@ -0,0 +1,34 @@ +package com.dfsek.terra.config.loaders; + +import com.dfsek.tectonic.api.depth.DepthTracker; +import com.dfsek.tectonic.api.exception.LoadException; +import com.dfsek.tectonic.api.loader.ConfigLoader; +import com.dfsek.tectonic.api.loader.type.TypeLoader; +import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.AnnotatedType; + +import com.dfsek.terra.api.world.biome.tag.BiomeTag; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; + + +public class BiomeTagLoader implements TypeLoader { + private final BiomeTagIndex index; + + public BiomeTagLoader(BiomeTagIndex index) { + this.index = index; + } + + @Override + public BiomeTag load(@NotNull AnnotatedType t, @NotNull Object c, @NotNull ConfigLoader loader, DepthTracker depthTracker) + throws LoadException { + if(!(c instanceof String name)) { + throw new LoadException("expected a tag name, got " + describe(c), depthTracker); + } + return index.tag(name); + } + + private static String describe(Object value) { + return value == null ? "null" : "type " + value.getClass().getCanonicalName(); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java index 42530b81f..6bb0ce13d 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java @@ -73,8 +73,11 @@ import com.dfsek.terra.api.util.generic.pair.Pair; import com.dfsek.terra.api.util.reflection.ReflectionUtil; import com.dfsek.terra.api.util.reflection.TypeKey; import com.dfsek.terra.api.world.biome.generation.BiomeProvider; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; import com.dfsek.terra.api.world.chunk.generation.stage.GenerationStage; import com.dfsek.terra.api.world.chunk.generation.util.provider.ChunkGeneratorProvider; +import com.dfsek.terra.config.loaders.BiomeTagLoader; import com.dfsek.terra.config.loaders.GenericTemplateSupplierLoader; import com.dfsek.terra.config.preprocessor.MetaListLikePreprocessor; import com.dfsek.terra.config.preprocessor.MetaMapPreprocessor; @@ -106,6 +109,8 @@ public class ConfigPackImpl implements ConfigPack { private final BiomeProvider seededBiomeProvider; + private final BiomeTagIndex biomeTagIndex = new BiomeTagIndex(); + private final Map> registryMap = new HashMap<>(); private final Map> shortcuts = new HashMap<>(); @@ -148,6 +153,8 @@ public class ConfigPackImpl implements ConfigPack { register(abstractConfigLoader); platform.register(abstractConfigLoader); + applyLoader(BiomeTag.class, new BiomeTagLoader(biomeTagIndex)); + ConfigPackAddonsTemplate addonsTemplate = new ConfigPackAddonsTemplate(); selfLoader.load(addonsTemplate, packManifest); this.addons = addonsTemplate.getAddons(); @@ -222,6 +229,8 @@ public class ConfigPackImpl implements ConfigPack { selfLoader.load(packPostTemplate, packManifest); seededBiomeProvider = template.getBiomeCache() ? packPostTemplate.getProviderBuilder().caching(platform) : packPostTemplate.getProviderBuilder(); + // Must stay inside the constructor: generation threads read tag bitsets without volatile reads. + biomeTagIndex.seal(); checkDeadEntries(); } @@ -297,6 +306,11 @@ public class ConfigPackImpl implements ConfigPack { return seededBiomeProvider; } + @Override + public BiomeTagIndex getBiomeTagIndex() { + return biomeTagIndex; + } + @Override public CheckedRegistry getOrCreateRegistry(TypeKey typeKey) { return (CheckedRegistry) registryMap.computeIfAbsent(typeKey.getType(), c -> { diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/config/loaders/BiomeTagLoaderTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/config/loaders/BiomeTagLoaderTest.java new file mode 100644 index 000000000..f62a7656a --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/config/loaders/BiomeTagLoaderTest.java @@ -0,0 +1,41 @@ +package com.dfsek.terra.config.loaders; + +import com.dfsek.tectonic.impl.MapConfiguration; +import com.dfsek.tectonic.api.depth.DepthTracker; +import com.dfsek.tectonic.api.exception.LoadException; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.AnnotatedType; +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class BiomeTagLoaderTest { + private final BiomeTagIndex index = new BiomeTagIndex(); + private final BiomeTagLoader loader = new BiomeTagLoader(index); + + private static DepthTracker tracker() { + return new DepthTracker(List.of(), new MapConfiguration(Map.of(), "biome.yml")); + } + + @Test + void nonString() { + LoadException e = assertThrows(LoadException.class, () -> loader.load((AnnotatedType) null, 42, null, tracker())); + assertTrue(e.getMessage().contains("expected a tag name"), e.getMessage()); + assertTrue(e.getMessage().contains("type java.lang.Integer"), e.getMessage()); + } + + @Test + void stringInterns() throws LoadException { + Object first = loader.load((AnnotatedType) null, "FOO", null, tracker()); + assertSame(first, loader.load((AnnotatedType) null, "FOO", null, tracker())); + assertSame(index.tag("FOO"), first); + } +} diff --git a/platforms/cli/build.gradle.kts b/platforms/cli/build.gradle.kts index 1d5cb6f73..c28c25f17 100644 --- a/platforms/cli/build.gradle.kts +++ b/platforms/cli/build.gradle.kts @@ -41,4 +41,11 @@ application { tasks.getByName("run").setProperty("workingDir", file("./run")) +// CLIPlatform uses "./" as its data folder. +tasks.withType { + workingDir = file("./run").also { it.mkdirs() } +} + +tasks.withType { dependsOn("moveAddonsrun") } + addonDir(project.file("./run/addons"), tasks.named("run").get()) From 4e37c361ea043ab83f44b055f30971dea25062fc Mon Sep 17 00:00:00 2001 From: Zoe Gidiere Date: Sun, 8 Nov 2026 03:51:22 -0700 Subject: [PATCH 40/44] feat: add environment attribute system --- buildSrc/build.gradle.kts | 8 +- buildSrc/src/main/kotlin/Versions.kt | 2 +- common/addons/config-attributes/LICENSE | 21 + .../addons/config-attributes/build.gradle.kts | 10 + .../addons/attribute/AttributeAddon.java | 194 ++++++++ .../addons/attribute/AttributeReader.java | 86 ++++ .../attribute/BiomeAttributeEntries.java | 13 + .../attribute/BiomeAttributesTemplate.java | 23 + .../addons/attribute/ConfigDecodeContext.java | 135 ++++++ .../addons/attribute/LazyConfigValue.java | 19 + .../addons/attribute/PackAttributesImpl.java | 133 ++++++ .../attribute/PackAttributesTemplate.java | 60 +++ .../attribute/RegistryAttributeLookup.java | 60 +++ .../terra/addons/attribute/ScheduleIds.java | 30 ++ .../resources/META-INF/api/config.terradoc | 122 +++++ .../src/main/resources/terra.addon.yml | 14 + .../java/attribute/AttributeReaderTest.java | 193 ++++++++ .../attribute/PackAttributesImplTest.java | 160 +++++++ .../attribute/ConfigDecodeContextTest.java | 186 ++++++++ .../addons/attribute/ScheduleIdsTest.java | 40 ++ common/addons/minecraft-attributes/LICENSE | 21 + .../minecraft-attributes/build.gradle.kts | 8 + .../attribute/minecraft/AmbientParticle.java | 6 + .../attribute/minecraft/AmbientSounds.java | 18 + .../attribute/minecraft/BackgroundMusic.java | 8 + .../addons/attribute/minecraft/BedRule.java | 26 + .../attribute/minecraft/CardinalLight.java | 20 + .../minecraft/GrassColorModifier.java | 21 + .../attribute/minecraft/IntProviderValue.java | 15 + .../minecraft/MinecraftAttributeTable.java | 159 +++++++ .../minecraft/MinecraftAttributeTypes.java | 109 +++++ .../minecraft/MinecraftAttributes.java | 128 +++++ .../minecraft/MinecraftAttributesAddon.java | 35 ++ .../attribute/minecraft/MinecraftCodecs.java | 349 ++++++++++++++ .../attribute/minecraft/MinecraftIds.java | 29 ++ .../attribute/minecraft/MobSpawnSettings.java | 25 + .../addons/attribute/minecraft/MoonPhase.java | 26 + .../addons/attribute/minecraft/Music.java | 3 + .../addons/attribute/minecraft/Skybox.java | 21 + .../addons/attribute/minecraft/SoundRef.java | 8 + .../minecraft/TemperatureModifier.java | 20 + .../src/main/resources/terra.addon.yml | 12 + .../MinecraftAttributeTypesTest.java | 450 ++++++++++++++++++ .../MinecraftAttributesAddonTest.java | 99 ++++ .../minecraft/MinecraftAttributesTest.java | 194 ++++++++ .../MinecraftCodecRoundTripTest.java | 177 +++++++ .../java/com/dfsek/terra/api/Platform.java | 15 + .../dfsek/terra/api/properties/Context.java | 8 + .../terra/api/registry/key/RegistryKey.java | 48 +- .../dfsek/terra/api/registry/key/TagKey.java | 63 +++ .../terra/api/world/attribute/Attribute.java | 63 +++ .../api/world/attribute/AttributeCodec.java | 14 + .../api/world/attribute/AttributeCodecs.java | 127 +++++ .../api/world/attribute/AttributeEntry.java | 43 ++ .../api/world/attribute/AttributeHandle.java | 110 +++++ .../api/world/attribute/AttributeKey.java | 71 +++ .../api/world/attribute/AttributeLookup.java | 9 + .../api/world/attribute/AttributeMap.java | 103 ++++ .../world/attribute/AttributeModifier.java | 6 + .../api/world/attribute/AttributeParents.java | 33 ++ .../api/world/attribute/AttributeScope.java | 6 + .../api/world/attribute/AttributeType.java | 61 +++ .../api/world/attribute/AttributeTypes.java | 68 +++ .../api/world/attribute/DecodeContext.java | 17 + .../api/world/attribute/DecodeException.java | 14 + .../terra/api/world/attribute/Operation.java | 44 ++ .../api/world/attribute/PackAttributes.java | 64 +++ .../terra/api/world/attribute/RawValue.java | 34 ++ .../attribute/schedule/AttributeSchedule.java | 21 + .../api/world/attribute/schedule/Easing.java | 29 ++ .../world/attribute/schedule/Keyframe.java | 6 + .../schedule/ScheduleDecodeResult.java | 20 + .../attribute/schedule/ScheduleTrack.java | 12 + .../world/attribute/schedule/TimeMarker.java | 3 + .../world/attribute/value/BlendToGray.java | 6 + .../api/world/attribute/value/Color.java | 97 ++++ .../world/attribute/value/FloatWithAlpha.java | 6 + .../api/world/attribute/value/TriState.java | 21 + .../api/registry/key/RegistryKeyTest.java | 113 +++++ .../api/world/attribute/AttributeMapTest.java | 72 +++ .../api/world/attribute/ValueTypesTest.java | 132 +++++ .../com/dfsek/terra/AbstractPlatform.java | 9 + .../MetaListLikePreprocessor.java | 3 +- .../preprocessor/MetaMapPreprocessor.java | 2 +- .../config/preprocessor/MetaPreprocessor.java | 19 +- .../preprocessor/MetaStringPreprocessor.java | 4 +- .../world/attribute/AttributeCodecsImpl.java | 107 +++++ .../world/attribute/AttributeHandleImpl.java | 137 ++++++ .../terra/world/attribute/AttributeImpl.java | 159 +++++++ .../world/attribute/AttributeLayers.java | 60 +++ .../world/attribute/AttributeTypeImpl.java | 155 ++++++ .../world/attribute/AttributeTypesImpl.java | 186 ++++++++ .../world/attribute/PlainDecodeContext.java | 63 +++ .../terra/world/attribute/ValueDecoders.java | 412 ++++++++++++++++ .../world/attribute/format/EntryFormat.java | 73 +++ .../attribute/format/ScheduleFormat.java | 299 ++++++++++++ .../AttributeCodecRoundTripTest.java | 163 +++++++ .../world/attribute/AttributeCodecsTest.java | 119 +++++ .../world/attribute/AttributeComposeTest.java | 151 ++++++ .../world/attribute/AttributeIndexTest.java | 51 ++ .../world/attribute/AttributeLayersTest.java | 88 ++++ .../world/attribute/AttributeTypesTest.java | 382 +++++++++++++++ .../world/attribute/EntryFormatTest.java | 79 +++ .../attribute/FixedArityResolveTest.java | 67 +++ .../world/attribute/ScheduleFormatTest.java | 416 ++++++++++++++++ platforms/cli/build.gradle.kts | 4 +- .../dfsek/terra/cli/AttributePackTest.java | 410 ++++++++++++++++ .../dfsek/terra/cli/FeatureStagePackTest.java | 56 +++ .../packs/attribute-test/biomes/bad.yml | 7 + .../packs/attribute-test/biomes/base.yml | 9 + .../packs/attribute-test/biomes/chain.yml | 11 + .../packs/attribute-test/biomes/child.yml | 6 + .../packs/attribute-test/biomes/expr.yml | 31 ++ .../packs/attribute-test/biomes/expr_bad.yml | 11 + .../packs/attribute-test/biomes/foggy.yml | 8 + .../packs/attribute-test/biomes/ground.yml | 14 + .../attribute-test/biomes/meta_child.yml | 8 + .../attribute-test/biomes/meta_include.yml | 8 + .../packs/attribute-test/biomes/nulled.yml | 6 + .../packs/attribute-test/biomes/plain.yml | 3 + .../resources/packs/attribute-test/meta.yml | 22 + .../resources/packs/attribute-test/pack.yml | 43 ++ .../packs/feature-stage-test/biomes/plain.yml | 19 + .../feature-stage-test/features/rock.yml | 15 + .../packs/feature-stage-test/pack.yml | 30 ++ .../packs/schedule-test/biomes/plain.yml | 12 + .../resources/packs/schedule-test/pack.yml | 49 ++ 127 files changed, 9022 insertions(+), 19 deletions(-) create mode 100644 common/addons/config-attributes/LICENSE create mode 100644 common/addons/config-attributes/build.gradle.kts create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeAddon.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeReader.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributeEntries.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributesTemplate.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ConfigDecodeContext.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/LazyConfigValue.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesImpl.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesTemplate.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/RegistryAttributeLookup.java create mode 100644 common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ScheduleIds.java create mode 100644 common/addons/config-attributes/src/main/resources/META-INF/api/config.terradoc create mode 100644 common/addons/config-attributes/src/main/resources/terra.addon.yml create mode 100644 common/addons/config-attributes/src/test/java/attribute/AttributeReaderTest.java create mode 100644 common/addons/config-attributes/src/test/java/attribute/PackAttributesImplTest.java create mode 100644 common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ConfigDecodeContextTest.java create mode 100644 common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ScheduleIdsTest.java create mode 100644 common/addons/minecraft-attributes/LICENSE create mode 100644 common/addons/minecraft-attributes/build.gradle.kts create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientParticle.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientSounds.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BackgroundMusic.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BedRule.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/CardinalLight.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/GrassColorModifier.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/IntProviderValue.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTable.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTypes.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributes.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributesAddon.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftCodecs.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftIds.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MobSpawnSettings.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MoonPhase.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Music.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Skybox.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/SoundRef.java create mode 100644 common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/TemperatureModifier.java create mode 100644 common/addons/minecraft-attributes/src/main/resources/terra.addon.yml create mode 100644 common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributeTypesTest.java create mode 100644 common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesAddonTest.java create mode 100644 common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesTest.java create mode 100644 common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftCodecRoundTripTest.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/registry/key/TagKey.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/Attribute.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodec.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodecs.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeEntry.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeHandle.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeKey.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeLookup.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeMap.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeModifier.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeParents.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeScope.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeType.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeTypes.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeContext.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeException.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/Operation.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/PackAttributes.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/RawValue.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/AttributeSchedule.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Easing.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Keyframe.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleDecodeResult.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleTrack.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/TimeMarker.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/BlendToGray.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/Color.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/FloatWithAlpha.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/TriState.java create mode 100644 common/api/src/test/java/com/dfsek/terra/api/registry/key/RegistryKeyTest.java create mode 100644 common/api/src/test/java/com/dfsek/terra/api/world/attribute/AttributeMapTest.java create mode 100644 common/api/src/test/java/com/dfsek/terra/api/world/attribute/ValueTypesTest.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeCodecsImpl.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeHandleImpl.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeImpl.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeLayers.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypeImpl.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypesImpl.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/PlainDecodeContext.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/ValueDecoders.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/EntryFormat.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/ScheduleFormat.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecRoundTripTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecsTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeComposeTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeIndexTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeLayersTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeTypesTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/EntryFormatTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/FixedArityResolveTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/ScheduleFormatTest.java create mode 100644 platforms/cli/src/test/java/com/dfsek/terra/cli/AttributePackTest.java create mode 100644 platforms/cli/src/test/java/com/dfsek/terra/cli/FeatureStagePackTest.java create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/bad.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/base.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/chain.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/child.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/expr.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/expr_bad.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/foggy.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/ground.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_child.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_include.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/nulled.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/biomes/plain.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/meta.yml create mode 100644 platforms/cli/src/test/resources/packs/attribute-test/pack.yml create mode 100644 platforms/cli/src/test/resources/packs/feature-stage-test/biomes/plain.yml create mode 100644 platforms/cli/src/test/resources/packs/feature-stage-test/features/rock.yml create mode 100644 platforms/cli/src/test/resources/packs/feature-stage-test/pack.yml create mode 100644 platforms/cli/src/test/resources/packs/schedule-test/biomes/plain.yml create mode 100644 platforms/cli/src/test/resources/packs/schedule-test/pack.yml diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 34721c9fd..594f03e1b 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -4,6 +4,12 @@ plugins { } repositories { + // TODO: remove once Tectonic 4.4.0 is published + mavenLocal { + content { + includeGroup("com.dfsek.tectonic") + } + } mavenCentral() gradlePluginPortal() maven("https://maven.solo-studios.ca/releases") { @@ -26,6 +32,6 @@ dependencies { implementation("org.ow2.asm", "asm", "9.9") implementation("org.ow2.asm", "asm-tree", "9.9") - implementation("com.dfsek.tectonic", "common", "4.3.1") + implementation("com.dfsek.tectonic", "common", "4.4.0") implementation("org.yaml", "snakeyaml", "2.5") } \ No newline at end of file diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index eb75413fa..bdfec58ce 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -7,7 +7,7 @@ object Versions { } object Libraries { - const val tectonic = "4.3.1" + const val tectonic = "4.4.0" const val paralithic = "2.0.1" const val strata = "1.3.2" const val seismic = "2.5.7" diff --git a/common/addons/config-attributes/LICENSE b/common/addons/config-attributes/LICENSE new file mode 100644 index 000000000..da43ecc81 --- /dev/null +++ b/common/addons/config-attributes/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020-2025 Polyhedral Development + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/common/addons/config-attributes/build.gradle.kts b/common/addons/config-attributes/build.gradle.kts new file mode 100644 index 000000000..172601515 --- /dev/null +++ b/common/addons/config-attributes/build.gradle.kts @@ -0,0 +1,10 @@ +version = version("1.0.0") + +dependencies { + compileOnlyApi(project(":common:addons:manifest-addon-loader")) + + testImplementation(project(":common:implementation:base")) + testImplementation(project(":common:addons:minecraft-attributes")) + testImplementation(project(":common:addons:manifest-addon-loader")) + testImplementation("com.dfsek", "paralithic", Versions.Libraries.paralithic) +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeAddon.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeAddon.java new file mode 100644 index 000000000..7288e69c8 --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeAddon.java @@ -0,0 +1,194 @@ +package com.dfsek.terra.addons.attribute; + +import org.slf4j.Logger; +import org.slf4j.helpers.MessageFormatter; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import com.dfsek.terra.addons.attribute.AttributeReader.Problem; +import com.dfsek.terra.addons.attribute.AttributeReader.Result; +import com.dfsek.terra.addons.attribute.AttributeReader.Scope; +import com.dfsek.terra.addons.manifest.api.AddonInitializer; +import com.dfsek.terra.api.Platform; +import com.dfsek.terra.api.addon.BaseAddon; +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.event.events.config.ConfigurationLoadEvent; +import com.dfsek.terra.api.event.events.config.pack.ConfigPackPostLoadEvent; +import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent; +import com.dfsek.terra.api.event.functional.FunctionalEventHandler; +import com.dfsek.terra.api.inject.annotations.Inject; +import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.properties.PropertyKey; +import com.dfsek.terra.api.registry.Registry; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeMap; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.PackAttributes; +import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult; +import com.dfsek.terra.api.world.biome.Biome; + + +/** + * Biome configs load in parallel: the biome handler may only read shared immutable state and write to its own biome. + */ +public class AttributeAddon implements AddonInitializer { + private static final String ATTRIBUTE_WARNING = "Pack \"{}\", config \"{}\": attribute \"{}\" skipped: {}"; + private static final String SCHEDULE_SKIPPED = "Pack \"{}\": schedule \"{}\" skipped: {}"; + private static final String TRACK_DROPPED = "Pack \"{}\": schedule \"{}\" track \"{}\" dropped: {}"; + private static final String PARENT_WARNING = "Pack \"{}\", config \"{}\": \"{}\" ignored: {}"; + private static final String PACK_CONFIG = "pack.yml"; + private static final String VANILLA = "vanilla"; + private static final String VANILLA_GENERATION = "vanilla-generation"; + + @Inject + private Platform platform; + + @Inject + private BaseAddon addon; + + @Inject + private Logger logger; + + @Override + public void initialize() { + AttributeHandle handle = platform.getAttributeHandle(); + // Before any parallel load: Context.create is not thread safe. + PropertyKey biomeKey = Context.create(BiomeAttributeEntries.class); + PropertyKey packKey = Context.create(PackAttributes.class); + + platform.getEventManager() + .getHandler(FunctionalEventHandler.class) + .register(addon, ConfigPackPreLoadEvent.class) + .then(event -> { + for(Class type : ConfigDecodeContext.CAPTURED_TYPES) event.getPack().applyLoader(type, LazyConfigValue.LOADER); + }) + .failThrough(); + + platform.getEventManager() + .getHandler(FunctionalEventHandler.class) + .register(addon, ConfigurationLoadEvent.class) + .then(event -> { + if(!event.is(Biome.class)) return; + Map raw = event.load(new BiomeAttributesTemplate()).getAttributes(); + AttributeReader reader = new AttributeReader(event.getPack().getRegistry(Attribute.REGISTRY_TYPE), handle); + Result result = reader.readConfig(raw, Scope.BIOME); + List warnings = new ArrayList<>(); + for(Problem problem : result.problems()) { + warnings.add(warn(ATTRIBUTE_WARNING, event.getPack(), event.getConfiguration().getID(), problem.key(), + problem.reason())); + } + event.getLoadedObject(Biome.class).getContext().put(biomeKey, new BiomeAttributeEntries(result.map(), warnings)); + }) + .failThrough(); + + platform.getEventManager() + .getHandler(FunctionalEventHandler.class) + .register(addon, ConfigPackPostLoadEvent.class) + .then(event -> { + ConfigPack pack = event.getPack(); + Registry> attributes = pack.getRegistry(Attribute.REGISTRY_TYPE); + PackAttributesTemplate template = event.loadTemplate(new PackAttributesTemplate()); + List warnings = new ArrayList<>(); + + Result result = new AttributeReader(attributes, handle).readConfig(template.getAttributes(), Scope.PACK); + for(Problem problem : result.problems()) { + warnings.add(warn(ATTRIBUTE_WARNING, pack, PACK_CONFIG, problem.key(), problem.reason())); + } + + Map parents = new LinkedHashMap<>(); + parent(parents, VANILLA, template.getVanilla(), pack, warnings); + parent(parents, VANILLA_GENERATION, template.getVanillaGeneration(), pack, warnings); + + List> schedules = new ArrayList<>(); + for(String schedule : template.getSchedules()) { + try { + schedules.add(ScheduleIds.reference(schedule)); + } catch(IllegalArgumentException e) { + warnings.add(warn(SCHEDULE_SKIPPED, pack, schedule, e.getMessage())); + } + } + + Map definitions = new LinkedHashMap<>(); + Set claimed = new HashSet<>(); + RegistryAttributeLookup lookup = new RegistryAttributeLookup(attributes); + template.getScheduleDefinitions().forEach((idString, lazy) -> { + RegistryKey id; + try { + id = ScheduleIds.claim(idString, claimed); + } catch(IllegalArgumentException e) { + warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, e.getMessage())); + return; + } + DecodeContext context; + Object value; + try { + context = lazy == null ? handle.plainContext() : lazy.context(handle.plainContext()); + value = lazy == null ? null : context.resolve(lazy.raw()); + } catch(DecodeException e) { + warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, e.getMessage())); + return; + } + if(!(value instanceof Map map) || !map.keySet().stream().allMatch(String.class::isInstance)) { + warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, "a schedule must be a map")); + return; + } + @SuppressWarnings("unchecked") + Map raw = (Map) map; + ScheduleDecodeResult schedule = handle.decodeSchedule(id, raw, lookup, context); + for(ScheduleDecodeResult.Problem problem : schedule.droppedTracks()) { + warnings.add(warn(TRACK_DROPPED, pack, idString, problem.key(), problem.reason())); + } + schedule.skipped().ifPresent(problem -> warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, problem.reason()))); + schedule.schedule().ifPresent(definition -> definitions.put(id, definition)); + }); + + pack.getContext().put(packKey, new PackAttributesImpl(handle, platform.getAttributeParents(), attributes, + result.map(), + parents, + schedules, + definitions, + biomeEntries(pack, biomeKey), + warnings)); + }) + .failThrough(); + } + + private static AttributeMap[] biomeEntries(ConfigPack pack, PropertyKey biomeKey) { + Registry biomes = pack.getRegistry(Biome.class); + if(biomes == null) return new AttributeMap[0]; + AttributeMap[] entries = new AttributeMap[pack.getBiomeTagIndex().size()]; + biomes.forEach(biome -> { + if(biome.getContext().has(biomeKey)) entries[biome.getIntID()] = biome.getContext().get(biomeKey).entries(); + }); + return entries; + } + + private void parent(Map parents, String key, Optional value, ConfigPack pack, List warnings) { + if(value.isEmpty()) return; + try { + parents.put(key, RegistryKey.parseNamespaced(value.get())); + } catch(IllegalArgumentException e) { + warnings.add(warn(PARENT_WARNING, pack, PACK_CONFIG, key, e.getMessage())); + } + } + + private String warn(String format, ConfigPack pack, Object... args) { + Object[] all = new Object[args.length + 1]; + all[0] = pack.getID(); + System.arraycopy(args, 0, all, 1, args.length); + logger.warn(format, all); + return MessageFormatter.arrayFormat(format, all).getMessage(); + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeReader.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeReader.java new file mode 100644 index 000000000..68d74bce0 --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/AttributeReader.java @@ -0,0 +1,86 @@ +package com.dfsek.terra.addons.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.registry.Registry; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeMap; +import com.dfsek.terra.api.world.attribute.AttributeScope; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; + + +public final class AttributeReader { + private final RegistryAttributeLookup lookup; + private final AttributeHandle handle; + + public AttributeReader(@Nullable Registry> registry, AttributeHandle handle) { + this.lookup = new RegistryAttributeLookup(registry); + this.handle = handle; + } + + public enum Scope { BIOME, PACK } + + + public record Result(AttributeMap map, List problems) { } + + + public record Problem(String key, String reason) { } + + + private record Value(Object raw, DecodeContext context) { } + + public Result read(Map raw, Scope scope) { + DecodeContext plain = handle.plainContext(); + Map values = new LinkedHashMap<>(); + raw.forEach((key, value) -> values.put(key, new Value(value, plain))); + return readValues(values, scope); + } + + Result readConfig(Map config, Scope scope) { + DecodeContext plain = handle.plainContext(); + Map values = new LinkedHashMap<>(); + config.forEach((key, value) -> values.put(key, value == null + ? new Value(null, plain) + : new Value(value.raw(), value.context(plain)))); + return readValues(values, scope); + } + + private Result readValues(Map raw, Scope scope) { + AttributeMap.Builder builder = AttributeMap.builder(); + List problems = new ArrayList<>(); + for(Map.Entry entry : raw.entrySet()) { + String keyString = entry.getKey(); + Attribute attribute; + try { + attribute = lookup.find(keyString); + } catch(DecodeException e) { + problems.add(new Problem(keyString, e.getMessage())); + continue; + } + if(scope == Scope.BIOME && attribute.scope() == AttributeScope.PACK_ONLY) { + problems.add(new Problem(keyString, "not allowed in a biome")); + continue; + } + // Explicit null un-sets an inherited value. + if(entry.getValue().raw() == null) continue; + try { + put(builder, attribute, entry.getValue().raw(), entry.getValue().context()); + } catch(DecodeException | RuntimeException e) { + problems.add(new Problem(keyString, e.getMessage() == null ? "unexpected error" : e.getMessage())); + } + } + return new Result(builder.build(), problems); + } + + private void put(AttributeMap.Builder builder, Attribute attribute, Object value, DecodeContext context) + throws DecodeException { + builder.put(attribute.key(), handle.decodeEntry(attribute, value, context)); + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributeEntries.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributeEntries.java new file mode 100644 index 000000000..ed1840534 --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributeEntries.java @@ -0,0 +1,13 @@ +package com.dfsek.terra.addons.attribute; + +import java.util.List; + +import com.dfsek.terra.api.properties.Properties; +import com.dfsek.terra.api.world.attribute.AttributeMap; + + +record BiomeAttributeEntries(AttributeMap entries, List warnings) implements Properties { + BiomeAttributeEntries { + warnings = List.copyOf(warnings); + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributesTemplate.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributesTemplate.java new file mode 100644 index 000000000..981b828dc --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/BiomeAttributesTemplate.java @@ -0,0 +1,23 @@ +package com.dfsek.terra.addons.attribute; + +import com.dfsek.tectonic.api.config.template.ConfigTemplate; +import com.dfsek.tectonic.api.config.template.annotations.Default; +import com.dfsek.tectonic.api.config.template.annotations.Merge; +import com.dfsek.tectonic.api.config.template.annotations.Value; + +import java.util.Collections; +import java.util.Map; + +import com.dfsek.terra.api.config.meta.Meta; + + +public class BiomeAttributesTemplate implements ConfigTemplate { + @Value("attributes") + @Merge + @Default + private @Meta Map<@Meta String, LazyConfigValue> attributes = Map.of(); + + Map getAttributes() { + return Collections.unmodifiableMap(attributes); + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ConfigDecodeContext.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ConfigDecodeContext.java new file mode 100644 index 000000000..78ece4d03 --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ConfigDecodeContext.java @@ -0,0 +1,135 @@ +package com.dfsek.terra.addons.attribute; + +import com.dfsek.tectonic.api.depth.DepthTracker; +import com.dfsek.tectonic.api.exception.ConfigException; +import com.dfsek.tectonic.api.exception.LoadException; +import com.dfsek.tectonic.api.loader.ConfigLoader; + +import java.lang.reflect.AnnotatedType; +import java.lang.reflect.Type; +import java.util.AbstractList; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.dfsek.terra.api.config.meta.Meta; +import com.dfsek.terra.api.util.reflection.TypeKey; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; + + +/** + * Tectonic picks preprocessors by declared type. + *

+ * Not thread safe: include preprocessors mutate the {@link DepthTracker}. + */ +final class ConfigDecodeContext implements DecodeContext { + static final List> CAPTURED_TYPES = List.of(LazyConfigValue.class, MapShape.class, ListShape.class); + + private static final AnnotatedType WHOLE_VALUE = new TypeKey<@Meta LazyConfigValue>() { }.getAnnotatedType(); + private static final AnnotatedType MAP = new TypeKey<@Meta MapShape>() { }.getAnnotatedType(); + private static final AnnotatedType LIST = new TypeKey<@Meta ListShape>() { }.getAnnotatedType(); + private static final AnnotatedType STRING = new TypeKey<@Meta String>() { }.getAnnotatedType(); + private static final AnnotatedType NUMBER = new TypeKey<@Meta Double>() { }.getAnnotatedType(); + + private final ConfigLoader loader; + private final DepthTracker tracker; + private final DecodeContext plain; + private final Set resolved = Collections.newSetFromMap(new IdentityHashMap<>()); + + ConfigDecodeContext(ConfigLoader loader, DepthTracker tracker, DecodeContext plain) { + this.loader = loader; + this.tracker = tracker; + this.plain = plain; + } + + private static boolean numeric(Type type) { + return type instanceof Class c && Number.class.isAssignableFrom(c); + } + + private static DecodeException failure(RuntimeException e) { + String message = e instanceof ConfigException && e.getMessage() != null ? e.getMessage().strip() : "config preprocessing failed"; + // Tectonic leaves some details only in the cause. + Throwable cause = e.getCause(); + boolean readable = cause instanceof ConfigException + || cause != null && !(cause instanceof RuntimeException || cause instanceof Error); + if(readable && cause.getMessage() != null && !message.contains(cause.getMessage().strip())) { + message += "\n\tCaused by: " + cause.getMessage().strip(); + } + return new DecodeException(message, e); + } + + @Override + public V load(Type type, Object raw) throws DecodeException { + Object value = resolve(raw); + if(value instanceof String expression && numeric(type)) { + try { + value = loadType(NUMBER, expression, tracker); + } catch(RuntimeException e) { + throw failure(e); + } + } + return plain.load(type, value); + } + + @Override + public Object resolve(Object raw) throws DecodeException { + try { + return resolve(raw, tracker); + } catch(RuntimeException e) { + throw failure(e); + } + } + + private Object resolve(Object raw, DepthTracker at) { + if(raw == null || raw instanceof Number || raw instanceof Boolean || resolved.contains(raw)) return raw; + LazyConfigValue whole = capture(WHOLE_VALUE, raw, at); + Object value = whole.raw(); + Object out; + if(value instanceof String) { + out = loadType(STRING, raw, at); + } else if(value instanceof Map) { + LazyConfigValue included = capture(MAP, value, whole.tracker()); + Map map = new LinkedHashMap<>(); + for(Map.Entry entry : ((Map) included.raw()).entrySet()) { + map.put(entry.getKey(), resolve(entry.getValue(), included.tracker().entry(String.valueOf(entry.getKey())))); + } + out = Collections.unmodifiableMap(map); + } else if(value instanceof List) { + LazyConfigValue included = capture(LIST, value, whole.tracker()); + List elements = (List) included.raw(); + List list = new ArrayList<>(elements.size()); + for(int i = 0; i < elements.size(); i++) list.add(resolve(elements.get(i), included.tracker().index(i))); + out = Collections.unmodifiableList(list); + } else { + out = value; + } + if(out != null) resolved.add(out); + return out; + } + + private LazyConfigValue capture(AnnotatedType type, Object raw, DepthTracker at) { + return (LazyConfigValue) loadType(type, raw, at); + } + + private Object loadType(AnnotatedType type, Object raw, DepthTracker at) { + try { + return loader.loadType(type, raw, at); + } catch(ConfigException e) { + throw e; + } catch(RuntimeException e) { + throw new LoadException("config preprocessing failed", e, at); + } + } + + + private abstract static class MapShape extends AbstractMap { } + + + private abstract static class ListShape extends AbstractList { } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/LazyConfigValue.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/LazyConfigValue.java new file mode 100644 index 000000000..25fbe9542 --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/LazyConfigValue.java @@ -0,0 +1,19 @@ +package com.dfsek.terra.addons.attribute; + +import com.dfsek.tectonic.api.depth.DepthTracker; +import com.dfsek.tectonic.api.loader.ConfigLoader; +import com.dfsek.tectonic.api.loader.type.TypeLoader; + +import com.dfsek.terra.api.world.attribute.DecodeContext; + + +/** + * Use only on the thread that loaded it: the {@link DepthTracker} is mutable. + */ +record LazyConfigValue(Object raw, ConfigLoader loader, DepthTracker tracker) { + static final TypeLoader LOADER = (type, o, loader, depthTracker) -> new LazyConfigValue(o, loader, depthTracker); + + DecodeContext context(DecodeContext plain) { + return new ConfigDecodeContext(loader, tracker, plain); + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesImpl.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesImpl.java new file mode 100644 index 000000000..0f4a45511 --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesImpl.java @@ -0,0 +1,133 @@ +package com.dfsek.terra.addons.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.registry.Registry; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeMap; +import com.dfsek.terra.api.world.attribute.AttributeParents; +import com.dfsek.terra.api.world.attribute.PackAttributes; +import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule; +import com.dfsek.terra.api.world.biome.Biome; + + +/** + * {@link #biomeEntryOrNull}, {@link #resolve} and {@link #resolvePack} must not allocate. + */ +public final class PackAttributesImpl implements PackAttributes { + private final AttributeHandle handle; + private final AttributeParents attributeParents; + private final AttributeMap entries; + private final AttributeEntry[] packEntries; + private final AttributeEntry[][] columns; + private final AttributeMap[] biomeEntries; + private final Map parents; + private final List> scheduleRefs; + private final Map scheduleDefinitions; + private final List warnings; + + public PackAttributesImpl(AttributeHandle handle, AttributeParents attributeParents, @Nullable Registry> attributes, + AttributeMap entries, Map parents, + List> scheduleRefs, Map scheduleDefinitions, + AttributeMap[] biomeEntries, List warnings) { + this.handle = handle; + this.attributeParents = attributeParents; + this.entries = entries; + this.packEntries = new AttributeEntry[handle.attributeCount()]; + for(AttributeKey key : entries.keys()) { + packEntries[attribute(attributes, key).index()] = entries.get(key).orElseThrow(); + } + this.columns = new AttributeEntry[handle.attributeCount()][]; + for(int id = 0; id < biomeEntries.length; id++) { + AttributeMap declared = biomeEntries[id]; + if(declared == null) continue; + for(AttributeKey key : declared.keys()) { + int index = attribute(attributes, key).index(); + if(columns[index] == null) columns[index] = new AttributeEntry[biomeEntries.length]; + columns[index][id] = declared.get(key).orElseThrow(); + } + } + this.biomeEntries = biomeEntries; + this.parents = Collections.unmodifiableMap(new LinkedHashMap<>(parents)); + this.scheduleRefs = List.copyOf(scheduleRefs); + this.scheduleDefinitions = Collections.unmodifiableMap(new LinkedHashMap<>(scheduleDefinitions)); + this.warnings = List.copyOf(warnings); + } + + private static Attribute attribute(@Nullable Registry> attributes, AttributeKey key) { + if(attributes == null) throw new IllegalArgumentException("entry " + key + " given for a pack without attributes"); + return attributes.get(key.getRegistryKey()) + .orElseThrow(() -> new IllegalArgumentException("entry " + key + " names no attribute of the pack")); + } + + @Override + public AttributeMap entries() { + return entries; + } + + @Override + public Map parents() { + return parents; + } + + @Override + public List> scheduleRefs() { + return scheduleRefs; + } + + @Override + public Map scheduleDefinitions() { + return scheduleDefinitions; + } + + @Override + @SuppressWarnings("unchecked") + public @Nullable AttributeEntry biomeEntryOrNull(Attribute attribute, Biome biome) { + int index = attribute.index(); + if(index >= columns.length) return null; + AttributeEntry[] column = columns[index]; + if(column == null) return null; + int id = biome.getIntID(); + if(id < 0 || id >= column.length) return null; + return (AttributeEntry) column[id]; + } + + @Override + public AttributeMap biomeEntries(Biome biome) { + int id = biome.getIntID(); + if(id < 0 || id >= biomeEntries.length || biomeEntries[id] == null) return AttributeMap.empty(); + return biomeEntries[id]; + } + + @SuppressWarnings("unchecked") + private @Nullable AttributeEntry packEntryOrNull(Attribute attribute) { + int index = attribute.index(); + return index < packEntries.length ? (AttributeEntry) packEntries[index] : null; + } + + @Override + public @Nullable T resolve(Attribute attribute, Biome biome) { + return handle.resolve(attribute, attributeParents.packOrNull(this, attribute), packEntryOrNull(attribute), + attributeParents.biomeOrNull(biome, attribute), biomeEntryOrNull(attribute, biome)); + } + + @Override + public @Nullable T resolvePack(Attribute attribute) { + return handle.resolve(attribute, attributeParents.packOrNull(this, attribute), packEntryOrNull(attribute), null); + } + + public List warnings() { + return warnings; + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesTemplate.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesTemplate.java new file mode 100644 index 000000000..7909d75db --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/PackAttributesTemplate.java @@ -0,0 +1,60 @@ +package com.dfsek.terra.addons.attribute; + +import com.dfsek.tectonic.api.config.template.ConfigTemplate; +import com.dfsek.tectonic.api.config.template.annotations.Default; +import com.dfsek.tectonic.api.config.template.annotations.Value; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import com.dfsek.terra.api.config.meta.Meta; + + +public class PackAttributesTemplate implements ConfigTemplate { + @Value("attributes") + @Default + private @Meta Map<@Meta String, LazyConfigValue> attributes = Map.of(); + + @Value("schedules") + @Default + private @Meta List<@Meta String> schedules = List.of(); + + @Value("schedule-definitions") + @Default + private @Meta Map<@Meta String, LazyConfigValue> scheduleDefinitions = Map.of(); + + // May be a map (vanilla.mobs); only a string names a parent. + @Value("vanilla") + @Default + private @Meta LazyConfigValue vanilla = null; + + @Value("vanilla-generation") + @Default + private @Meta LazyConfigValue vanillaGeneration = null; + + Map getAttributes() { + return Collections.unmodifiableMap(attributes); + } + + public List getSchedules() { + return schedules; + } + + Map getScheduleDefinitions() { + return Collections.unmodifiableMap(scheduleDefinitions); + } + + public Optional getVanilla() { + return string(vanilla); + } + + public Optional getVanillaGeneration() { + return string(vanillaGeneration); + } + + private static Optional string(LazyConfigValue value) { + return value != null && value.raw() instanceof String s ? Optional.of(s) : Optional.empty(); + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/RegistryAttributeLookup.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/RegistryAttributeLookup.java new file mode 100644 index 000000000..c6e8a089e --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/RegistryAttributeLookup.java @@ -0,0 +1,60 @@ +package com.dfsek.terra.addons.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.Map; + +import com.dfsek.terra.api.registry.Registry; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeLookup; +import com.dfsek.terra.api.world.attribute.DecodeException; + + +/** + * Keys must be fully namespaced: inheritance merges config maps by raw key text. + */ +public final class RegistryAttributeLookup implements AttributeLookup { + private static final String NAMESPACE_REQUIRED = "attribute keys must include a namespace, e.g. \"minecraft:visual/fog_color\""; + private static final String UNKNOWN = "unknown attribute"; + private static final Map NAMESPACE_ADDONS = Map.of( + "minecraft", "minecraft-attributes", + "terra", "minecraft-attributes"); + + private final @Nullable Registry> registry; + + public RegistryAttributeLookup(@Nullable Registry> registry) { + this.registry = registry; + } + + @Override + public Attribute find(String key) throws DecodeException { + AttributeKey parsed; + try { + parsed = AttributeKey.parse(key); + } catch(IllegalArgumentException e) { + if(key.indexOf(':') < 0) throw new DecodeException(NAMESPACE_REQUIRED, e); + throw new DecodeException(invalidKey(e), e); + } + Attribute attribute = registry == null ? null : registry.get(parsed.getRegistryKey()).orElse(null); + if(attribute == null) throw new DecodeException(unknownAttribute(parsed.getRegistryKey())); + return attribute; + } + + private static String invalidKey(IllegalArgumentException e) { + Throwable cause = e.getCause() == null ? e : e.getCause(); + String message = cause.getMessage(); + return message == null ? "invalid attribute key" : "invalid attribute key: " + message; + } + + private String unknownAttribute(RegistryKey key) { + String namespace = key.getNamespace(); + String addon = NAMESPACE_ADDONS.get(namespace); + if(addon == null) return UNKNOWN; + if(registry != null && registry.keys().stream().anyMatch(registered -> registered.getNamespace().equals(namespace))) { + return UNKNOWN; + } + return UNKNOWN + ": no \"" + namespace + "\" attributes are registered; add the \"" + addon + "\" addon to the pack's addons"; + } +} diff --git a/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ScheduleIds.java b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ScheduleIds.java new file mode 100644 index 000000000..8a12ef604 --- /dev/null +++ b/common/addons/config-attributes/src/main/java/com/dfsek/terra/addons/attribute/ScheduleIds.java @@ -0,0 +1,30 @@ +package com.dfsek.terra.addons.attribute; + +import java.util.Set; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; + + +final class ScheduleIds { + private ScheduleIds() { } + + static RegistryKey claim(String id, Set claimed) { + if(id.startsWith("#")) throw new IllegalArgumentException("schedule IDs must not be tags"); + RegistryKey key; + try { + key = RegistryKey.parseNamespaced(id); + } catch(IllegalArgumentException e) { + if(id.indexOf(':') < 0) throw new IllegalArgumentException("schedule IDs must include a namespace, e.g. \"mypack:seasons\"", e); + throw e; + } + if(!claimed.add(key)) throw new IllegalArgumentException("duplicate schedule ID"); + return key; + } + + static Either reference(String value) { + if(value.startsWith("#")) return Either.right(TagKey.parse(value)); + return Either.left(RegistryKey.parseNamespaced(value)); + } +} diff --git a/common/addons/config-attributes/src/main/resources/META-INF/api/config.terradoc b/common/addons/config-attributes/src/main/resources/META-INF/api/config.terradoc new file mode 100644 index 000000000..f9e0ade98 --- /dev/null +++ b/common/addons/config-attributes/src/main/resources/META-INF/api/config.terradoc @@ -0,0 +1,122 @@ +{ + "id": "config-attributes", + "docVersion": 1, + "description": "Environment attributes for biomes and packs. Contributes the attributes key to biome configurations, and attributes, schedules, schedule-definitions and vanilla-generation to pack.yml, and reads pack.yml's vanilla key when it is a string. The pack must list this addon under addons: in pack.yml, along with the addon that registers the attributes it uses (minecraft-attributes for the minecraft: and terra: ones); an unknown key's warning names that addon when none of its attributes are registered. Attribute keys must be fully namespaced (minecraft:visual/fog_color); a bad entry logs a warning and is skipped without affecting the rest of the pack.", + "types": { + "terra:AttributeEntry": { + "kind": "oneOf", + "options": [ + { + "kind": "object", + "fields": { + "modifier": { + "schema": { + "kind": "string" + }, + "required": true, + "summary": "Modifier name. The modifier form is exactly the two keys modifier and argument. Examples: override, add, subtract, multiply, minimum, maximum, overlay, alpha_blend or blend_to_gray. Which modifiers are valid depends on the attribute's value type." + }, + "argument": { + "schema": { + "kind": "any" + }, + "required": true, + "summary": "Modifier argument, in the attribute's value format or the modifier's own argument format. Range validation applies to plain values and override arguments; other modifier arguments are clamped when the value is resolved." + } + }, + "description": "Modifier form. Any map containing a modifier key is read as this form, never as a plain value." + }, + { + "kind": "any" + } + ], + "description": "A plain value in the attribute's vanilla format (for example \"#c0d8ff\", 0.5, true, or a list or map for complex types), or a modifier object. Particle options and text components are kept as opaque raw values for platforms to decode, with meta resolved." + }, + "terra:Biome": { + "kind": "object", + "fields": { + "attributes": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "type", + "target": "terra:AttributeEntry" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Maps namespaced attribute IDs (for example minecraft:visual/fog_color) to a value or a {modifier, argument} object. Merged per key through extends, nearest config winning, and << meta includes work at every layer. A key without a namespace, an unknown key, a value that does not decode, or a non-biome attribute logs a warning and is skipped. Attributes not set here are inherited, not defaulted. An explicit null value for a known attribute that is allowed in biomes clears the inherited entry without a warning, so the attribute falls back to the lower layers (the platform's biome parent, the pack, the platform's pack parent, the default). Setting attributes: null on a child does not clear what it inherits, because inheritance merges per key and skips a null layer; clear entries one key at a time instead. Meta features work inside values at any depth: $file:key references, ${file:key} interpolation, << includes in maps and lists, and number expressions wherever a number is expected. A meta error inside a value logs a warning and skips that entry." + } + } + } + }, + "files": { + "BIOME": { + "kind": "object", + "fields": {}, + "extends": [ + "terra:Biome" + ] + }, + "pack.yml": { + "kind": "object", + "fields": { + "attributes": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "type", + "target": "terra:AttributeEntry" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Pack-level (dimension) attribute values, keyed by namespaced attribute ID. They layer over the platform's pack parent, which it may take from the IDs in vanilla: and vanilla-generation:, and biome values layer on top of them. Bad entries warn and are skipped. An explicit null value for a known attribute sets no entry, without a warning." + }, + "schedules": { + "schema": { + "kind": "list", + "element": { + "kind": "string" + }, + "nullable": true + }, + "required": false, + "default": [], + "summary": "Schedule IDs or #tags to attach to the pack's dimension, each with a namespace (mypack:seasons, #mypack:in_overworld); an entry without one logs a warning and is skipped. Entries are resolved by the platform; they may also name schedules declared in schedule-definitions. A single string is accepted as a one-entry list. Platforms map schedules to Minecraft timelines." + }, + "schedule-definitions": { + "schema": { + "kind": "keyMap", + "keys": { + "kind": "string" + }, + "values": { + "kind": "any" + }, + "nullable": true + }, + "required": false, + "default": {}, + "summary": "Maps schedule IDs to schedule objects in vanilla's format (clock, period_ticks, time_markers, tracks of keyframes). IDs must include a namespace (mypack:seasons), must not be tags, and must be unique; the first definition with an ID wins. Clock and time-marker IDs must include a namespace too; one without skips the whole definition. A shape error skips the whole definition; an unknown attribute, a modifier invalid for the attribute's type, or a bad keyframe value drops only that track. An unknown modifier name skips the whole definition." + }, + "vanilla-generation": { + "schema": { + "kind": "string", + "nullable": true + }, + "required": false, + "summary": "Parent ID for the platform's generation settings (for example minecraft:overworld). Like pack.yml's vanilla: key, which this addon reads only when it is a string ID (a map there is for other settings and is ignored here), it must include a namespace. An ID without one, or an invalid ID, in either key logs a warning and is ignored. The platform decides what each parent supplies and to which attributes; without platform support these layers are empty." + } + } + } + } +} diff --git a/common/addons/config-attributes/src/main/resources/terra.addon.yml b/common/addons/config-attributes/src/main/resources/terra.addon.yml new file mode 100644 index 000000000..3859bc59e --- /dev/null +++ b/common/addons/config-attributes/src/main/resources/terra.addon.yml @@ -0,0 +1,14 @@ +schema-version: 1 +contributors: + - Terra contributors +id: config-attributes +version: @VERSION@ +entrypoints: + - "com.dfsek.terra.addons.attribute.AttributeAddon" +website: + issues: https://github.com/PolyhedralDev/Terra/issues + source: https://github.com/PolyhedralDev/Terra + docs: https://terra.polydev.org +license: MIT License +depends: + config-biome: "1.+" diff --git a/common/addons/config-attributes/src/test/java/attribute/AttributeReaderTest.java b/common/addons/config-attributes/src/test/java/attribute/AttributeReaderTest.java new file mode 100644 index 000000000..a0a97b393 --- /dev/null +++ b/common/addons/config-attributes/src/test/java/attribute/AttributeReaderTest.java @@ -0,0 +1,193 @@ +package attribute; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalInt; +import java.util.stream.Stream; + +import com.dfsek.terra.addons.attribute.AttributeReader; +import com.dfsek.terra.addons.attribute.AttributeReader.Problem; +import com.dfsek.terra.addons.attribute.AttributeReader.Result; +import com.dfsek.terra.addons.attribute.AttributeReader.Scope; +import com.dfsek.terra.addons.attribute.RegistryAttributeLookup; +import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue; +import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTable; +import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes; +import com.dfsek.terra.api.registry.Registry; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult; +import com.dfsek.terra.registry.OpenRegistryImpl; +import com.dfsek.terra.world.attribute.AttributeHandleImpl; + +import static org.junit.jupiter.api.Assertions.*; + + +class AttributeReaderTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final Registry> REGISTRY = registry(); + private static final AttributeReader READER = new AttributeReader(REGISTRY, HANDLE); + private static final String LIGHT = "terra:dimension/monster_spawn_light_level"; + private static final String NAMESPACE_REQUIRED = "attribute keys must include a namespace, e.g. \"minecraft:visual/fog_color\""; + + private static Registry> registry() { + OpenRegistryImpl> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE); + for(Attribute attribute : MinecraftAttributeTable.create(HANDLE)) registry.register(attribute.getRegistryKey(), attribute); + return registry; + } + + private static Map map(Object... kv) { + Map m = new LinkedHashMap<>(); + for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]); + return m; + } + + private static void assertExactProblem(Result result, String key, String reason) { + assertEquals(List.of(new Problem(key, reason)), result.problems()); + } + + static Stream accepted() { + return Stream.of( + Arguments.of(Scope.BIOME, "minecraft:visual/fog_color", "#c0d8ff", Operation.OVERRIDE), + Arguments.of(Scope.BIOME, "minecraft:visual/water_fog_end_distance", map("modifier", "multiply", "argument", 0.85), + Operation.MULTIPLY), + Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "multiply", "argument", 5), Operation.MULTIPLY), + Arguments.of(Scope.BIOME, "minecraft:visual/ambient_particles", map("modifier", "append", + "argument", List.of(map("particle", map("type", "minecraft:crimson_spore"), "probability", 0.025))), Operation.APPEND), + Arguments.of(Scope.BIOME, "minecraft:gameplay/natural_mob_spawns", map("modifier", "overlay", "argument", map( + "spawn_costs", map("minecraft:enderman", map("energy_budget", 0.7, "charge", 0.15)), + "spawns_by_category", map("creature", List.of( + map("type", "minecraft:sheep", "count", 4, "weight", 12), + map("type", "minecraft:horse", "weight", 5, + "count", map("type", "minecraft:uniform", "max_inclusive", 6, "min_inclusive", 2)))))), Operation.OVERLAY), + Arguments.of(Scope.PACK, "minecraft:gameplay/fast_lava", true, Operation.OVERRIDE), + Arguments.of(Scope.PACK, LIGHT, map("type", "minecraft:uniform", "min_inclusive", 0, "max_inclusive", 7), Operation.OVERRIDE)); + } + + @ParameterizedTest(name = "{1}") + @MethodSource("accepted") + void accepts(Scope scope, String key, Object value, Operation operation) { + Result r = READER.read(Map.of(key, value), scope); + assertTrue(r.problems().isEmpty(), r.problems().toString()); + assertEquals(operation, r.map().get(AttributeKey.parse(key)).orElseThrow().operation()); + } + + @Test + void intProviderModifierForm() { + Result r = READER.read(Map.of(LIGHT, Map.of("modifier", "override", "argument", 7)), Scope.PACK); + assertTrue(r.problems().isEmpty(), r.problems().toString()); + AttributeEntry e = r.map().get(MinecraftAttributes.DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL).orElseThrow(); + assertEquals(Operation.OVERRIDE, e.operation()); + assertEquals(new IntProviderValue(OptionalInt.of(7), Optional.empty()), e.argument()); + } + + static Stream problems() { + return Stream.of( + Arguments.of(Scope.BIOME, "minecraft:nope", 1, "unknown attribute"), + Arguments.of(Scope.BIOME, "minecraft:Visual/Sky_Color", "#123456", "unknown attribute"), + Arguments.of(Scope.BIOME, "visual/sky_color", "#123456", NAMESPACE_REQUIRED), + Arguments.of(Scope.BIOME, "minecraft:Bad Key!", 1, "invalid attribute key..."), + Arguments.of(Scope.BIOME, "minecraft:visual/sky_color", true, "expected..."), + Arguments.of(Scope.BIOME, "minecraft:audio/ambient_sounds", map("loop", "minecraft:Music.Game"), + "\"loop\" of ambient sounds: expected an identifier like \"minecraft:id\", got \"minecraft:Music.Game\""), + Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", 2, "value 2.0 is outside [0, 1]"), + Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "override", "argument", 2), + "value 2.0 is outside [0, 1]"), + Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "and", "argument", true), + "modifier and is not valid for minecraft:visual/star_brightness"), + Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "frobnicate", "argument", 1), + "unknown modifier \"frobnicate\""), + Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "add", "argument", null), + "expected a number, got nothing"), + Arguments.of(Scope.PACK, LIGHT, map("modifier", "frobnicate", "argument", 7), "unknown modifier \"frobnicate\""), + Arguments.of(Scope.PACK, LIGHT, map("min_inclusive", 0, "max_inclusive", 7), "int provider object is missing \"type\""), + Arguments.of(Scope.PACK, "terra:dimension/height", 100, "value 100 is not a multiple of 16"), + Arguments.of(Scope.BIOME, "minecraft:gameplay/fast_lava", true, "not allowed in a biome"), + Arguments.of(Scope.BIOME, "minecraft:visual/ambient_particles", Arrays.asList((Object) null), + "element 0: expected an object for ambient particle, got nothing"), + Arguments.of(Scope.BIOME, "minecraft:visual/ambient_particles", List.of(map("particle", null, "probability", 0.1)), + "element 0: \"particle\" of ambient particle: expected a particle object with a \"type\" key, got nothing")); + } + + @ParameterizedTest(name = "{1}: {3}") + @MethodSource("problems") + void badEntryIsolated(Scope scope, String key, Object value, String reason) { + Result r = READER.read(map(key, value, "minecraft:visual/fog_color", "#c0d8ff"), scope); + assertEquals(1, r.problems().size(), r.problems().toString()); + assertEquals(key, r.problems().get(0).key()); + if(reason.endsWith("...")) { + String prefix = reason.substring(0, reason.length() - 3); + assertTrue(r.problems().get(0).reason().startsWith(prefix), r.problems().get(0).reason()); + } else { + assertEquals(reason, r.problems().get(0).reason()); + } + assertTrue(r.map().get(MinecraftAttributes.VISUAL_FOG_COLOR).isPresent()); + assertEquals(1, r.map().keys().size()); + } + + @Test + void nullUnsetsKnownKeys() { + for(Scope scope : Scope.values()) { + Result r = READER.read(map("minecraft:visual/fog_color", null, "minecraft:visual/sky_color", "#405060"), scope); + assertTrue(r.problems().isEmpty(), r.problems().toString()); + assertTrue(r.map().get(MinecraftAttributes.VISUAL_FOG_COLOR).isEmpty()); + assertEquals(1, r.map().keys().size()); + } + Map raw = map("minecraft:nope", null, "minecraft:Bad Key!", null, "visual/sky_color", null, + "terra:world/sea_level", null, "minecraft:visual/fog_color", null); + Result r = READER.read(raw, Scope.BIOME); + assertEquals(List.of( + new Problem("minecraft:nope", "unknown attribute"), + new Problem("minecraft:Bad Key!", "invalid attribute key: ID must only contain alphanumeric characters, hyphens, underscores, periods, and slashes. \"Bad Key!\" is not a valid ID."), + new Problem("visual/sky_color", NAMESPACE_REQUIRED), + new Problem("terra:world/sea_level", "not allowed in a biome")), + r.problems()); + assertTrue(r.map().isEmpty()); + assertTrue(READER.read(map("terra:world/sea_level", null), Scope.PACK).problems().isEmpty()); + } + + @Test + void unknownKeyHint() { + AttributeReader empty = new AttributeReader(new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE), HANDLE); + for(String key : List.of("minecraft:visual/fog_color", "terra:biome/temperature")) { + String namespace = key.substring(0, key.indexOf(':')); + assertExactProblem(empty.read(Map.of(key, "#ffffff"), Scope.BIOME), key, + "unknown attribute: no \"" + namespace + "\" attributes are registered; add the \"minecraft-attributes\" addon " + + "to the pack's addons"); + } + Result none = new AttributeReader(null, HANDLE).read(Map.of("minecraft:visual/fog_color", "#ffffff"), Scope.PACK); + assertExactProblem(none, "minecraft:visual/fog_color", "unknown attribute: no \"minecraft\" attributes are registered; add the " + + "\"minecraft-attributes\" addon to the pack's addons"); + assertExactProblem(empty.read(Map.of("mypack:thing", 1), Scope.BIOME), "mypack:thing", "unknown attribute"); + assertExactProblem(READER.read(Map.of("minecraft:visual/fog_colour", "#ffffff"), Scope.BIOME), "minecraft:visual/fog_colour", + "unknown attribute"); + } + + @Test + void scheduleTrackKeys() { + Map track = Map.of("keyframes", List.of(Map.of("ticks", 0, "value", 10.0))); + Map raw = map("clock", "minecraft:overworld", "tracks", map( + "visual/sun_angle", track, + "minecraft:visual/sun angle", track, + "minecraft:visual/moon_angle", track)); + ScheduleDecodeResult r = HANDLE.decodeSchedule(RegistryKey.parse("terra:test"), raw, new RegistryAttributeLookup(REGISTRY), + HANDLE.plainContext()); + assertEquals(List.of( + new ScheduleDecodeResult.Problem("visual/sun_angle", NAMESPACE_REQUIRED), + new ScheduleDecodeResult.Problem("minecraft:visual/sun angle", "invalid attribute key: ID must only contain alphanumeric characters, hyphens, underscores, periods, and slashes. \"visual/sun angle\" is not a valid ID.")), + r.droppedTracks()); + assertEquals(1, r.schedule().orElseThrow().tracks().size()); + } +} diff --git a/common/addons/config-attributes/src/test/java/attribute/PackAttributesImplTest.java b/common/addons/config-attributes/src/test/java/attribute/PackAttributesImplTest.java new file mode 100644 index 000000000..da454001a --- /dev/null +++ b/common/addons/config-attributes/src/test/java/attribute/PackAttributesImplTest.java @@ -0,0 +1,160 @@ +package attribute; + +import org.jetbrains.annotations.Nullable; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Proxy; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.OptionalInt; + +import com.dfsek.terra.addons.attribute.PackAttributesImpl; +import com.dfsek.terra.api.registry.Registry; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeMap; +import com.dfsek.terra.api.world.attribute.AttributeParents; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.PackAttributes; +import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule; +import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.registry.OpenRegistryImpl; +import com.dfsek.terra.world.attribute.AttributeHandleImpl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + + +class PackAttributesImplTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final Attribute COUNT = HANDLE.attributeBuilder(AttributeKey.parse("test:count"), HANDLE.types().integer(), + 10).build(); + private static final Attribute OTHER = HANDLE.attributeBuilder(AttributeKey.parse("test:other"), HANDLE.types().integer(), + 0).build(); + private static final Registry> REGISTRY = registry(COUNT, OTHER); + + private static Registry> registry(Attribute... attributes) { + OpenRegistryImpl> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE); + for(Attribute attribute : attributes) registry.register(attribute.getRegistryKey(), attribute); + return registry; + } + + private static Biome withId(int id) { + return (Biome) Proxy.newProxyInstance(Biome.class.getClassLoader(), new Class[]{ Biome.class }, (proxy, method, args) -> + switch(method.getName()) { + case "getIntID" -> id; + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + + private static PackAttributesImpl pack(AttributeParents parents, AttributeMap entries, AttributeMap... biomeEntries) { + return new PackAttributesImpl(HANDLE, parents, REGISTRY, entries, Map.of(), List.of(), Map.of(), biomeEntries, List.of()); + } + + private static AttributeMap map(Attribute attribute, AttributeEntry entry) { + return AttributeMap.builder().put(attribute.key(), entry).build(); + } + + @Test + void resolveUsesParents() { + AttributeParents parents = new AttributeParents() { + @Override + @SuppressWarnings("unchecked") + public @Nullable AttributeEntry biomeOrNull(Biome biome, Attribute attribute) { + return attribute == COUNT ? (AttributeEntry) AttributeEntry.override(5) : null; + } + + @Override + @SuppressWarnings("unchecked") + public @Nullable AttributeEntry packOrNull(PackAttributes pack, Attribute attribute) { + return attribute == COUNT ? (AttributeEntry) AttributeEntry.of(Operation.ADD, 1) : null; + } + }; + PackAttributesImpl pack = pack(parents, map(COUNT, AttributeEntry.of(Operation.ADD, 2)), new AttributeMap[2]); + + assertEquals(5, pack.resolve(COUNT, withId(1))); + assertEquals(COUNT.defaultValue() + 3, pack.resolvePack(COUNT)); + PackAttributesImpl withBiome = pack(parents, map(COUNT, AttributeEntry.of(Operation.ADD, 2)), null, + map(COUNT, AttributeEntry.of(Operation.ADD, 100))); + assertEquals(105, withBiome.resolve(COUNT, withId(1))); + assertEquals(0, pack.resolve(OTHER, withId(1))); + assertEquals(0, pack.resolvePack(OTHER)); + } + + @Test + void parentsNone() { + PackAttributesImpl pack = pack(AttributeParents.NONE, map(COUNT, AttributeEntry.of(Operation.ADD, 2)), null, + map(COUNT, AttributeEntry.of(Operation.MULTIPLY, 3))); + assertEquals(36, pack.resolve(COUNT, withId(1))); + assertEquals(12, pack.resolve(COUNT, withId(0))); + assertEquals(12, pack.resolvePack(COUNT)); + } + + @Test + void twoPacksIndependentColumns() { + AttributeEntry small1 = AttributeEntry.override(1); + AttributeEntry large1 = AttributeEntry.override(2); + AttributeEntry large2 = AttributeEntry.override(3); + PackAttributesImpl small = pack(AttributeParents.NONE, AttributeMap.empty(), null, map(COUNT, small1)); + PackAttributesImpl large = pack(AttributeParents.NONE, AttributeMap.empty(), null, map(COUNT, large1), map(COUNT, large2)); + + assertSame(small1, small.biomeEntryOrNull(COUNT, withId(1))); + assertSame(large1, large.biomeEntryOrNull(COUNT, withId(1))); + assertSame(large2, large.biomeEntryOrNull(COUNT, withId(2))); + assertNull(small.biomeEntryOrNull(COUNT, withId(2))); + assertEquals(10, small.resolve(COUNT, withId(2))); + assertEquals(3, large.resolve(COUNT, withId(2))); + } + + @Test + void storedBiomeEntry() { + AttributeEntry stored = AttributeEntry.override(7); + PackAttributesImpl pack = pack(AttributeParents.NONE, AttributeMap.empty(), null, map(COUNT, stored), null); + + assertSame(stored, pack.biomeEntryOrNull(COUNT, withId(1))); + assertNull(pack.biomeEntryOrNull(COUNT, withId(0))); + assertNull(pack.biomeEntryOrNull(COUNT, withId(-1))); + assertNull(pack.biomeEntryOrNull(COUNT, withId(3))); + assertNull(pack.biomeEntryOrNull(OTHER, withId(1))); + Attribute later = HANDLE.attributeBuilder(AttributeKey.parse("test:later"), HANDLE.types().integer(), 4).build(); + assertNull(pack.biomeEntryOrNull(later, withId(1))); + assertEquals(4, pack.resolve(later, withId(1))); + assertEquals(4, pack.resolvePack(later)); + } + + @Test + void biomeEntriesCold() { + AttributeMap declared = AttributeMap.builder() + .put(COUNT.key(), AttributeEntry.override(1)) + .put(OTHER.key(), AttributeEntry.of(Operation.ADD, 2)) + .build(); + PackAttributesImpl pack = pack(AttributeParents.NONE, AttributeMap.empty(), null, declared); + + assertSame(declared, pack.biomeEntries(withId(1))); + assertSame(AttributeMap.empty(), pack.biomeEntries(withId(0))); + assertSame(AttributeMap.empty(), pack.biomeEntries(withId(2))); + assertSame(AttributeMap.empty(), pack.biomeEntries(withId(-1))); + } + + @Test + void configOrder() { + Map parents = new LinkedHashMap<>(); + parents.put("vanilla-generation", RegistryKey.parse("test:generation")); + parents.put("vanilla", RegistryKey.parse("test:dimension")); + List ids = List.of("terra:z", "terra:a", "terra:m", "terra:b", "terra:y", "terra:c", "terra:x", "terra:d"); + Map definitions = new LinkedHashMap<>(); + for(String id : ids) { + definitions.put(RegistryKey.parse(id), new AttributeSchedule(RegistryKey.parse("test:clock"), OptionalInt.empty(), + Map.of(), Map.of())); + } + PackAttributesImpl pack = new PackAttributesImpl(HANDLE, AttributeParents.NONE, REGISTRY, AttributeMap.empty(), parents, + List.of(), definitions, new AttributeMap[0], List.of()); + assertEquals(List.of("vanilla-generation", "vanilla"), List.copyOf(pack.parents().keySet())); + assertEquals(ids, pack.scheduleDefinitions().keySet().stream().map(RegistryKey::toString).toList()); + } +} diff --git a/common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ConfigDecodeContextTest.java b/common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ConfigDecodeContextTest.java new file mode 100644 index 000000000..cc2f06fa0 --- /dev/null +++ b/common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ConfigDecodeContextTest.java @@ -0,0 +1,186 @@ +package com.dfsek.terra.addons.attribute; + +import com.dfsek.paralithic.eval.parser.Parser.ParseOptions; +import com.dfsek.tectonic.api.config.Configuration; +import com.dfsek.tectonic.api.depth.DepthTracker; +import com.dfsek.tectonic.api.loader.ConfigLoader; +import com.dfsek.tectonic.api.preprocessor.Result; +import com.dfsek.tectonic.api.preprocessor.ValuePreprocessor; +import com.dfsek.tectonic.impl.MapConfiguration; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.AnnotatedType; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.config.meta.Meta; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.config.preprocessor.MetaListLikePreprocessor; +import com.dfsek.terra.config.preprocessor.MetaMapPreprocessor; +import com.dfsek.terra.config.preprocessor.MetaNumberPreprocessor; +import com.dfsek.terra.config.preprocessor.MetaStringPreprocessor; +import com.dfsek.terra.config.preprocessor.MetaValuePreprocessor; +import com.dfsek.terra.world.attribute.AttributeHandleImpl; + +import static org.junit.jupiter.api.Assertions.*; + + +class ConfigDecodeContextTest { + private static final Map META = map( + "n", 3, + "s", "two", + "chain", "$meta.yml:s", + "obj", map("x", 1, "y", "$meta.yml:s"), + "list", List.of("a", "b")); + + private static Map map(Object... kv) { + Map m = new LinkedHashMap<>(); + for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]); + return m; + } + + private static DecodeContext context() { + return context(Map.of("meta.yml", new MapConfiguration(META, "meta.yml"))); + } + + private static DecodeContext context(Map configs) { + ConfigLoader loader = new ConfigLoader(); + loader.registerPreprocessor(Meta.class, new MetaStringPreprocessor(configs)); + loader.registerPreprocessor(Meta.class, new MetaListLikePreprocessor(configs)); + loader.registerPreprocessor(Meta.class, new MetaMapPreprocessor(configs)); + loader.registerPreprocessor(Meta.class, new MetaValuePreprocessor(configs)); + loader.registerPreprocessor(Meta.class, new MetaNumberPreprocessor(configs, new ParseOptions())); + return context(loader); + } + + private static DecodeContext context(ConfigLoader loader) { + for(Class type : ConfigDecodeContext.CAPTURED_TYPES) loader.registerLoader(type, LazyConfigValue.LOADER); + DepthTracker tracker = new DepthTracker(List.of(), new MapConfiguration(Map.of(), "biome.yml")); + return new LazyConfigValue(null, loader, tracker).context(new AttributeHandleImpl().plainContext()); + } + + @Test + void numberExpressions() throws DecodeException { + DecodeContext context = context(); + assertEquals("2 * 6000", context.resolve("2 * 6000")); + assertEquals(12000, context.load(Integer.class, "2 * 6000")); + assertEquals(1.5f, context.load(Float.class, "${meta.yml:n} / 2")); + assertEquals(3.0, context.load(Double.class, "$meta.yml:n")); + assertEquals(0.5f, context.load(Float.class, 0.5)); + } + + @Test + void plainConversion() { + DecodeContext context = context(); + assertTrue(assertThrows(DecodeException.class, () -> context.load(Integer.class, "5 / 2")).getMessage() + .startsWith("expected an integer")); + assertEquals("expected a string, got 3", + assertThrows(DecodeException.class, () -> context.load(String.class, "$meta.yml:n")).getMessage()); + assertEquals("expected a boolean (true or false), got \"two\"", + assertThrows(DecodeException.class, () -> context.load(Boolean.class, "$meta.yml:s")).getMessage()); + } + + @Test + void nestedResolve() throws DecodeException { + Map raw = map( + "null", null, + "ref", "$meta.yml:obj", + "list", List.of("<< meta.yml:list", "c", "${meta.yml:s}"), + "include", map("<<", List.of("meta.yml:obj"), "x", 2), + "string", "one-${meta.yml:s}", + "deep", map("a", List.of(map("b", "$meta.yml:n")))); + Map resolved = (Map) context().resolve(raw); + assertEquals(map( + "null", null, + "ref", map("x", 1, "y", "two"), + "list", List.of("a", "b", "c", "two"), + "include", map("x", 2, "y", "two"), + "string", "one-two", + "deep", map("a", List.of(map("b", 3)))), resolved); + assertEquals(List.copyOf(raw.keySet()), List.copyOf(resolved.keySet())); + } + + @Test + void resolveTwice() throws DecodeException { + DecodeContext context = context(); + Object once = context.resolve(map("a", "$meta.yml:chain")); + assertEquals(map("a", "$meta.yml:s"), once); + assertSame(once, context.resolve(once)); + Object chained = ((Map) once).get("a"); + assertSame(chained, context.resolve(chained)); + assertEquals("$meta.yml:s", context.load(String.class, chained)); + } + + @Test + void preprocessingErrors() { + DecodeContext context = context(); + String missing = assertThrows(DecodeException.class, () -> context.resolve(map("a", "${meta.yml:missing}"))).getMessage(); + assertTrue(missing.contains("No such key missing"), missing); + assertTrue(missing.contains("Path: a"), missing); + + String malformed = assertThrows(DecodeException.class, () -> context.resolve(List.of("${2 * 6000}"))).getMessage(); + assertTrue(malformed.contains("meta reference \"2 * 6000\" must have the form file:key"), malformed); + assertTrue(malformed.contains("Path: [0]"), malformed); + assertReadable(malformed); + + String escape = assertThrows(DecodeException.class, () -> context.resolve(map("a", "$meta.yml:bad\\q"))).getMessage(); + assertTrue(escape.contains("meta reference \"meta.yml:bad\\q\" has an invalid key path"), escape); + assertReadable(escape); + + String expression = assertThrows(DecodeException.class, () -> context.load(Float.class, "1 +")).getMessage(); + assertTrue(expression.contains("Invalid expression"), expression); + + String include = assertThrows(DecodeException.class, () -> context.resolve(map("<<", List.of("meta.yml:list")))).getMessage(); + assertTrue(include.contains("MetaMap injection candidate must be map, is type java.util."), include); + } + + @Test + void nullMetaTargets() { + Configuration nulls = new Configuration() { + @Override + public Object get(@NotNull String key) { + return null; + } + + @Override + public boolean contains(@NotNull String key) { + return true; + } + + @Override + public String getName() { + return "null.yml"; + } + }; + DecodeContext context = context(Map.of("null.yml", nulls)); + String string = assertThrows(DecodeException.class, () -> context.resolve("${null.yml:x}")).getMessage(); + assertTrue(string.contains("must be string or primitive, is null"), string); + String list = assertThrows(DecodeException.class, () -> context.resolve(List.of("<< null.yml:x"))).getMessage(); + assertTrue(list.contains("'null.yml:x' points to null"), list); + String include = assertThrows(DecodeException.class, () -> context.resolve(map("<<", List.of("null.yml:x")))).getMessage(); + assertTrue(include.contains("must be map, is null"), include); + } + + @Test + void preprocessorRuntimeExceptions() { + ConfigLoader loader = new ConfigLoader(); + loader.registerPreprocessor(Meta.class, new ValuePreprocessor() { + @Override + public @NotNull Result process(AnnotatedType t, T c, ConfigLoader l, Meta annotation, DepthTracker depthTracker) { + throw new IllegalStateException("java.lang.Boom"); + } + }); + DecodeContext context = context(loader); + String message = assertThrows(DecodeException.class, () -> context.resolve("x")).getMessage(); + assertTrue(message.contains("config preprocessing failed"), message); + assertReadable(message); + } + + private static void assertReadable(String message) { + assertFalse(message.contains("java."), message); + assertFalse(message.contains("Exception"), message); + } +} diff --git a/common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ScheduleIdsTest.java b/common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ScheduleIdsTest.java new file mode 100644 index 000000000..f01a31451 --- /dev/null +++ b/common/addons/config-attributes/src/test/java/com/dfsek/terra/addons/attribute/ScheduleIdsTest.java @@ -0,0 +1,40 @@ +package com.dfsek.terra.addons.attribute; + +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.Set; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + + +class ScheduleIdsTest { + @Test + void referenceNamespace() { + assertEquals(Either.left(RegistryKey.parse("mypack:seasons")), ScheduleIds.reference("mypack:seasons")); + assertEquals(Either.right(TagKey.parse("#mypack:in_overworld")), ScheduleIds.reference("#mypack:in_overworld")); + assertEquals("a namespace is required, as in \"namespace:seasons\"", + assertThrows(IllegalArgumentException.class, () -> ScheduleIds.reference("seasons")).getMessage()); + assertEquals("invalid tag \"#in_overworld\": a namespace is required, as in \"#namespace:in_overworld\"", + assertThrows(IllegalArgumentException.class, () -> ScheduleIds.reference("#in_overworld")).getMessage()); + } + + @Test + void claim() { + Set claimed = new HashSet<>(); + assertEquals(RegistryKey.parse("mypack:seasons"), ScheduleIds.claim("mypack:seasons", claimed)); + assertEquals("duplicate schedule ID", + assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("mypack:seasons", claimed)).getMessage()); + assertEquals(RegistryKey.parse("MyPack:Seasons"), ScheduleIds.claim("MyPack:Seasons", claimed)); + assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("mypack:", claimed)); + assertEquals("schedule IDs must include a namespace, e.g. \"mypack:seasons\"", + assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("seasons", claimed)).getMessage()); + assertEquals("schedule IDs must not be tags", + assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("#mypack:seasons", claimed)).getMessage()); + } +} diff --git a/common/addons/minecraft-attributes/LICENSE b/common/addons/minecraft-attributes/LICENSE new file mode 100644 index 000000000..da43ecc81 --- /dev/null +++ b/common/addons/minecraft-attributes/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020-2025 Polyhedral Development + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/common/addons/minecraft-attributes/build.gradle.kts b/common/addons/minecraft-attributes/build.gradle.kts new file mode 100644 index 000000000..c98a1c4b2 --- /dev/null +++ b/common/addons/minecraft-attributes/build.gradle.kts @@ -0,0 +1,8 @@ +version = version("1.0.0") + +dependencies { + compileOnlyApi(project(":common:addons:manifest-addon-loader")) + + testImplementation(project(":common:implementation:base")) + testImplementation(project(":common:addons:manifest-addon-loader")) +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientParticle.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientParticle.java new file mode 100644 index 000000000..1f3827b61 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientParticle.java @@ -0,0 +1,6 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import com.dfsek.terra.api.world.attribute.RawValue; + + +public record AmbientParticle(RawValue particle, float probability) { } diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientSounds.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientSounds.java new file mode 100644 index 000000000..e5d4463fc --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/AmbientSounds.java @@ -0,0 +1,18 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import java.util.List; +import java.util.Optional; + + +public record AmbientSounds(Optional loop, Optional mood, List additions) { + public static final AmbientSounds EMPTY = new AmbientSounds(Optional.empty(), Optional.empty(), List.of()); + + public AmbientSounds { + additions = List.copyOf(additions); + } + + public record Mood(SoundRef sound, int tickDelay, int blockSearchExtent, double offset) { } + + + public record Additions(SoundRef sound, double tickChance) { } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BackgroundMusic.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BackgroundMusic.java new file mode 100644 index 000000000..576cd0f06 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BackgroundMusic.java @@ -0,0 +1,8 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import java.util.Optional; + + +public record BackgroundMusic(Optional defaultMusic, Optional creative, Optional underwater) { + public static final BackgroundMusic EMPTY = new BackgroundMusic(Optional.empty(), Optional.empty(), Optional.empty()); +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BedRule.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BedRule.java new file mode 100644 index 000000000..d52a464ad --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/BedRule.java @@ -0,0 +1,26 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import java.util.Optional; + +import com.dfsek.terra.api.registry.key.StringIdentifiable; +import com.dfsek.terra.api.world.attribute.RawValue; + + +public record BedRule(Rule canSleep, Rule canSetSpawn, boolean destroyOnUse, boolean destroyOnLeave, Optional errorMessage) { + public enum Rule implements StringIdentifiable { + ALWAYS("always"), + WHEN_DARK("when_dark"), + NEVER("never"); + + private final String id; + + Rule(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/CardinalLight.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/CardinalLight.java new file mode 100644 index 000000000..440552eec --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/CardinalLight.java @@ -0,0 +1,20 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import com.dfsek.terra.api.registry.key.StringIdentifiable; + + +public enum CardinalLight implements StringIdentifiable { + DEFAULT("default"), + NETHER("nether"); + + private final String id; + + CardinalLight(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/GrassColorModifier.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/GrassColorModifier.java new file mode 100644 index 000000000..d7fe13f89 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/GrassColorModifier.java @@ -0,0 +1,21 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import com.dfsek.terra.api.registry.key.StringIdentifiable; + + +public enum GrassColorModifier implements StringIdentifiable { + NONE("none"), + DARK_FOREST("dark_forest"), + SWAMP("swamp"); + + private final String id; + + GrassColorModifier(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/IntProviderValue.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/IntProviderValue.java new file mode 100644 index 000000000..c6144ef94 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/IntProviderValue.java @@ -0,0 +1,15 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import java.util.Optional; +import java.util.OptionalInt; + +import com.dfsek.terra.api.world.attribute.RawValue; + + +public record IntProviderValue(OptionalInt constant, Optional provider) { + public IntProviderValue { + if(constant.isPresent() == provider.isPresent()) { + throw new IllegalArgumentException("an int provider value needs exactly one of a constant and a provider"); + } + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTable.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTable.java new file mode 100644 index 000000000..f1221dcd8 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTable.java @@ -0,0 +1,159 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalInt; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.AttributeTypes; +import com.dfsek.terra.api.world.attribute.RawValue; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.api.world.attribute.value.TriState; + + +public final class MinecraftAttributeTable { + private static final RawValue NO_SLEEP_MESSAGE = new RawValue(Map.of("translate", "block.minecraft.bed.no_sleep")); + + private static final BedRule CAN_SLEEP_WHEN_DARK = new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.ALWAYS, false, false, + Optional.of(NO_SLEEP_MESSAGE)); + + private static final BedRule DESTROY_ON_LEAVE = new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.NEVER, false, true, + Optional.of(NO_SLEEP_MESSAGE)); + + private static final IntProviderValue MONSTER_SPAWN_LIGHT_LEVEL = new IntProviderValue(OptionalInt.empty(), Optional.of( + new RawValue(Map.of("type", "minecraft:uniform", "min_inclusive", 0, "max_inclusive", 7)))); + + private MinecraftAttributeTable() { } + + public static List> create(AttributeHandle handle) { + AttributeTypes t = handle.types(); + MinecraftAttributeTypes m = new MinecraftAttributeTypes(handle); + AttributeType temperatureModifier = t.enumType("temperature_modifier", TemperatureModifier.class); + AttributeType grassColorModifier = t.enumType("grass_color_modifier", GrassColorModifier.class); + AttributeType skybox = t.enumType("skybox", Skybox.class); + AttributeType cardinalLight = t.enumType("cardinal_light", CardinalLight.class); + Table table = new Table(handle); + + table.row(MinecraftAttributes.VISUAL_FOG_COLOR, t.rgbColor(), Color.rgb(0x000000)); + table.row(MinecraftAttributes.VISUAL_FOG_START_DISTANCE, t.floatType(), 0f); + table.row(MinecraftAttributes.VISUAL_FOG_END_DISTANCE, t.floatType(), 1024f).range(0, Double.POSITIVE_INFINITY); + table.row(MinecraftAttributes.VISUAL_SKY_FOG_END_DISTANCE, t.floatType(), 512f).range(0, Double.POSITIVE_INFINITY); + table.row(MinecraftAttributes.VISUAL_CLOUD_FOG_END_DISTANCE, t.floatType(), 2048f).range(0, Double.POSITIVE_INFINITY); + table.row(MinecraftAttributes.VISUAL_WATER_FOG_COLOR, t.rgbColor(), Color.rgb(0x050533)); + table.row(MinecraftAttributes.VISUAL_WATER_FOG_START_DISTANCE, t.floatType(), -8f); + table.row(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE, t.floatType(), 96f).range(0, Double.POSITIVE_INFINITY); + table.row(MinecraftAttributes.VISUAL_SKY_COLOR, t.rgbColor(), Color.rgb(0x000000)); + table.row(MinecraftAttributes.VISUAL_SUNRISE_SUNSET_COLOR, t.argbColor(), Color.argb(0)); + table.row(MinecraftAttributes.VISUAL_CLOUD_COLOR, t.argbColor(), Color.argb(0)); + table.row(MinecraftAttributes.VISUAL_CLOUD_HEIGHT, t.floatType(), 192.33f); + table.row(MinecraftAttributes.VISUAL_SUN_ANGLE, t.angleDegrees(), 0f); + table.row(MinecraftAttributes.VISUAL_MOON_ANGLE, t.angleDegrees(), 0f); + table.row(MinecraftAttributes.VISUAL_STAR_ANGLE, t.angleDegrees(), 0f); + table.row(MinecraftAttributes.VISUAL_MOON_PHASE, m.moonPhase(), MoonPhase.FULL_MOON); + table.row(MinecraftAttributes.VISUAL_STAR_BRIGHTNESS, t.floatType(), 0f).range(0, 1); + table.row(MinecraftAttributes.VISUAL_BLOCK_LIGHT_TINT, t.rgbColor(), Color.rgb(0xffd88c)); + table.row(MinecraftAttributes.VISUAL_SKY_LIGHT_COLOR, t.rgbColor(), Color.rgb(0xffffff)); + table.row(MinecraftAttributes.VISUAL_SKY_LIGHT_FACTOR, t.floatType(), 1f).range(0, 1); + table.row(MinecraftAttributes.VISUAL_NIGHT_VISION_COLOR, t.rgbColor(), Color.rgb(0x999999)); + table.row(MinecraftAttributes.VISUAL_AMBIENT_LIGHT_COLOR, t.rgbColor(), Color.rgb(0x000000)); + table.row(MinecraftAttributes.VISUAL_DEFAULT_DRIPSTONE_PARTICLE, m.particle(), + new RawValue(Map.of("type", "minecraft:dripping_dripstone_water"))); + table.row(MinecraftAttributes.VISUAL_AMBIENT_PARTICLES, m.ambientParticles(), List.of()); + table.row(MinecraftAttributes.AUDIO_BACKGROUND_MUSIC, m.backgroundMusic(), BackgroundMusic.EMPTY); + table.row(MinecraftAttributes.AUDIO_MUSIC_VOLUME, t.floatType(), 1f).range(0, 1); + table.row(MinecraftAttributes.AUDIO_AMBIENT_SOUNDS, m.ambientSounds(), AmbientSounds.EMPTY); + table.row(MinecraftAttributes.AUDIO_FIREFLY_BUSH_SOUNDS, t.booleanType(), false); + table.row(MinecraftAttributes.GAMEPLAY_SKY_LIGHT_LEVEL, t.floatType(), 15f).range(0, 15).packOnly(); + table.row(MinecraftAttributes.GAMEPLAY_CAN_START_RAID, t.booleanType(), true); + table.row(MinecraftAttributes.GAMEPLAY_WATER_EVAPORATES, t.booleanType(), false); + table.row(MinecraftAttributes.GAMEPLAY_BED_RULE, m.bedRule(), CAN_SLEEP_WHEN_DARK); + table.row(MinecraftAttributes.GAMEPLAY_STRAW_BED_RULE, m.bedRule(), DESTROY_ON_LEAVE); + table.row(MinecraftAttributes.GAMEPLAY_RESPAWN_ANCHOR_WORKS, t.booleanType(), false); + table.row(MinecraftAttributes.GAMEPLAY_NETHER_PORTAL_SPAWNS_PIGLIN, t.booleanType(), false); + table.row(MinecraftAttributes.GAMEPLAY_FAST_LAVA, t.booleanType(), false).packOnly(); + table.row(MinecraftAttributes.GAMEPLAY_INCREASED_FIRE_BURNOUT, t.booleanType(), false); + table.row(MinecraftAttributes.GAMEPLAY_EYEBLOSSOM_OPEN, t.triState(), TriState.DEFAULT); + table.row(MinecraftAttributes.GAMEPLAY_TURTLE_EGG_HATCH_CHANCE, t.floatType(), 0.002f).range(0, 1); + table.row(MinecraftAttributes.GAMEPLAY_PIGLINS_ZOMBIFY, t.booleanType(), true); + table.row(MinecraftAttributes.GAMEPLAY_SNOW_GOLEM_MELTS, t.booleanType(), false); + table.row(MinecraftAttributes.GAMEPLAY_CREAKING_ACTIVE, t.booleanType(), false); + table.row(MinecraftAttributes.GAMEPLAY_SURFACE_SLIME_SPAWN_CHANCE, t.floatType(), 0f).range(0, 1); + table.row(MinecraftAttributes.GAMEPLAY_CAT_WAKING_UP_GIFT_CHANCE, t.floatType(), 0f).range(0, 1); + table.row(MinecraftAttributes.GAMEPLAY_BEES_STAY_IN_HIVE, t.booleanType(), false); + table.row(MinecraftAttributes.GAMEPLAY_MONSTERS_BURN, t.booleanType(), false); + table.row(MinecraftAttributes.GAMEPLAY_CAN_PILLAGER_PATROL_SPAWN, t.booleanType(), true); + table.row(MinecraftAttributes.GAMEPLAY_NATURAL_MOB_SPAWNS, m.mobSpawnSettings(), MobSpawnSettings.EMPTY); + table.row(MinecraftAttributes.GAMEPLAY_CREATURE_WORLD_GEN_SPAWN_PROBABILITY, t.floatType(), 0.1f).range(0, 0.9999999); + table.row(MinecraftAttributes.GAMEPLAY_VILLAGER_ACTIVITY, m.identifier(), RegistryKey.parse("minecraft:idle")); + table.row(MinecraftAttributes.GAMEPLAY_BABY_VILLAGER_ACTIVITY, m.identifier(), RegistryKey.parse("minecraft:idle")); + + table.row(MinecraftAttributes.BIOME_HAS_PRECIPITATION, t.booleanType(), true); + table.row(MinecraftAttributes.BIOME_TEMPERATURE, t.floatType(), 0.5f); + table.row(MinecraftAttributes.BIOME_TEMPERATURE_MODIFIER, temperatureModifier, TemperatureModifier.NONE); + table.row(MinecraftAttributes.BIOME_DOWNFALL, t.floatType(), 0.5f); + table.row(MinecraftAttributes.BIOME_WATER_COLOR, t.rgbColor(), Color.rgb(0x3f76e4)); + table.row(MinecraftAttributes.BIOME_FOLIAGE_COLOR, t.rgbColor(), null); + table.row(MinecraftAttributes.BIOME_DRY_FOLIAGE_COLOR, t.rgbColor(), null); + table.row(MinecraftAttributes.BIOME_GRASS_COLOR, t.rgbColor(), null); + table.row(MinecraftAttributes.BIOME_GRASS_COLOR_MODIFIER, grassColorModifier, GrassColorModifier.NONE); + table.row(MinecraftAttributes.BIOME_VILLAGER_TYPE, m.identifier(), RegistryKey.parse("minecraft:plains")); + table.row(MinecraftAttributes.DIMENSION_HAS_FIXED_TIME, t.booleanType(), false).packOnly(); + table.row(MinecraftAttributes.DIMENSION_HAS_SKYLIGHT, t.booleanType(), true).packOnly(); + table.row(MinecraftAttributes.DIMENSION_HAS_CEILING, t.booleanType(), false).packOnly(); + table.row(MinecraftAttributes.DIMENSION_HAS_ENDER_DRAGON_FIGHT, t.booleanType(), false).packOnly(); + table.row(MinecraftAttributes.DIMENSION_COORDINATE_SCALE, t.floatType(), 1f).packOnly().range(1e-5, 3e7); + table.row(MinecraftAttributes.DIMENSION_MIN_Y, t.integerOverrideOnly(), -64).packOnly().range(-2032, 2031).multipleOf(16); + table.row(MinecraftAttributes.DIMENSION_HEIGHT, t.integerOverrideOnly(), 384).packOnly().range(16, 4064).multipleOf(16); + table.row(MinecraftAttributes.DIMENSION_LOGICAL_HEIGHT, t.integerOverrideOnly(), 384).packOnly().range(0, 4064); + table.row(MinecraftAttributes.DIMENSION_INFINIBURN, m.identifierOrTag(), + Either.right(TagKey.parse("#minecraft:infiniburn_overworld"))).packOnly(); + table.row(MinecraftAttributes.DIMENSION_AMBIENT_LIGHT, t.floatType(), 0f).packOnly(); + table.row(MinecraftAttributes.DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL, m.intProvider(), MONSTER_SPAWN_LIGHT_LEVEL).packOnly(); + table.row(MinecraftAttributes.DIMENSION_MONSTER_SPAWN_BLOCK_LIGHT_LIMIT, t.integer(), 0).packOnly().range(0, 15); + table.row(MinecraftAttributes.DIMENSION_SKYBOX, skybox, Skybox.OVERWORLD).packOnly(); + table.row(MinecraftAttributes.DIMENSION_CARDINAL_LIGHT, cardinalLight, CardinalLight.DEFAULT).packOnly(); + table.row(MinecraftAttributes.DIMENSION_DEFAULT_CLOCK, m.identifier(), RegistryKey.parse("minecraft:overworld")).packOnly(); + table.row(MinecraftAttributes.WORLD_SEA_LEVEL, t.integer(), 63).packOnly(); + table.row(MinecraftAttributes.WORLD_SPAWN_HEIGHT, t.integer(), 64).packOnly(); + table.row(MinecraftAttributes.WORLD_MOB_GENERATION, t.booleanType(), true).packOnly(); + + List> attributes = table.build(); + if(!attributes.stream().map(Attribute::key).toList().equals(MinecraftAttributes.all())) { + throw new IllegalStateException("the Minecraft attribute table does not match MinecraftAttributes.all()"); + } + return attributes; + } + + + private static final class Table { + private final AttributeHandle handle; + private final List> rows = new ArrayList<>(); + + private Table(AttributeHandle handle) { + this.handle = handle; + } + + private Attribute.Builder row(AttributeKey key, AttributeType type, @Nullable T defaultValue) { + MinecraftIds.requireLowerCase(key.getRegistryKey()); + Attribute.Builder builder = handle.attributeBuilder(key, type, defaultValue); + rows.add(builder); + return builder; + } + + private List> build() { + List> built = new ArrayList<>(rows.size()); + for(Attribute.Builder row : rows) built.add(row.build()); + return List.copyOf(built); + } + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTypes.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTypes.java new file mode 100644 index 000000000..405931447 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributeTypes.java @@ -0,0 +1,109 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.RawValue; + + +public final class MinecraftAttributeTypes { + private final AttributeType moonPhase; + private final AttributeType bedRule; + private final AttributeType particle; + private final AttributeType> ambientParticles; + private final AttributeType backgroundMusic; + private final AttributeType ambientSounds; + private final AttributeType mobSpawnSettings; + private final AttributeType identifier; + private final AttributeType> identifierOrTag; + private final AttributeType intProvider; + + public MinecraftAttributeTypes(AttributeHandle handle) { + MinecraftCodecs codecs = new MinecraftCodecs(handle); + this.moonPhase = handle.typeBuilder("moon_phase", codecs.moonPhase()).build(); + this.bedRule = handle.typeBuilder("bed_rule", codecs.bedRule()).build(); + this.particle = handle.typeBuilder("particle", codecs.particle()).build(); + this.ambientParticles = handle.typeBuilder("ambient_particles", codecs.ambientParticles()) + .op(Operation.APPEND, codecs.ambientParticles(), MinecraftAttributeTypes::append) + .build(); + this.backgroundMusic = handle.typeBuilder("background_music", codecs.backgroundMusic()).build(); + this.ambientSounds = handle.typeBuilder("ambient_sounds", codecs.ambientSounds()).build(); + this.mobSpawnSettings = handle.typeBuilder("mob_spawn_settings", codecs.mobSpawnSettings()) + .op(Operation.OVERLAY, codecs.mobSpawnSettings(), MinecraftAttributeTypes::overlay) + .build(); + this.identifier = handle.typeBuilder("identifier", codecs.identifier()).build(); + this.identifierOrTag = handle.typeBuilder("identifier_or_tag", codecs.identifierOrTag()).build(); + this.intProvider = handle.typeBuilder("int_provider", codecs.intProvider()).build(); + } + + public AttributeType moonPhase() { + return moonPhase; + } + + public AttributeType bedRule() { + return bedRule; + } + + public AttributeType particle() { + return particle; + } + + public AttributeType> ambientParticles() { + return ambientParticles; + } + + public AttributeType backgroundMusic() { + return backgroundMusic; + } + + public AttributeType ambientSounds() { + return ambientSounds; + } + + public AttributeType mobSpawnSettings() { + return mobSpawnSettings; + } + + public AttributeType identifier() { + return identifier; + } + + public AttributeType> identifierOrTag() { + return identifierOrTag; + } + + public AttributeType intProvider() { + return intProvider; + } + + private static List append(List s, List a) { + if(a.isEmpty()) return s; + if(s.isEmpty()) return a; + List out = new ArrayList<>(s.size() + a.size()); + out.addAll(s); + out.addAll(a); + return List.copyOf(out); + } + + private static MobSpawnSettings overlay(MobSpawnSettings first, MobSpawnSettings second) { + if(first.spawnsByCategory().isEmpty() && first.spawnCosts().isEmpty()) return second; + if(second.spawnsByCategory().isEmpty() && second.spawnCosts().isEmpty()) return first; + if(second.spawnsByCategory().keySet().containsAll(first.spawnsByCategory().keySet()) + && second.spawnCosts().keySet().containsAll(first.spawnCosts().keySet())) { + return second; + } + Map> categories = new LinkedHashMap<>(first.spawnsByCategory()); + categories.putAll(second.spawnsByCategory()); + Map costs = new LinkedHashMap<>(first.spawnCosts()); + costs.putAll(second.spawnCosts()); + return new MobSpawnSettings(categories, costs); + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributes.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributes.java new file mode 100644 index 000000000..3a3138ee4 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributes.java @@ -0,0 +1,128 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import java.util.ArrayList; +import java.util.List; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.RawValue; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.api.world.attribute.value.TriState; + + +public final class MinecraftAttributes { + private static List> building = new ArrayList<>(); + + public static final AttributeKey VISUAL_FOG_COLOR = vanilla("visual/fog_color"); + public static final AttributeKey VISUAL_FOG_START_DISTANCE = vanilla("visual/fog_start_distance"); + public static final AttributeKey VISUAL_FOG_END_DISTANCE = vanilla("visual/fog_end_distance"); + public static final AttributeKey VISUAL_SKY_FOG_END_DISTANCE = vanilla("visual/sky_fog_end_distance"); + public static final AttributeKey VISUAL_CLOUD_FOG_END_DISTANCE = vanilla("visual/cloud_fog_end_distance"); + public static final AttributeKey VISUAL_WATER_FOG_COLOR = vanilla("visual/water_fog_color"); + public static final AttributeKey VISUAL_WATER_FOG_START_DISTANCE = vanilla("visual/water_fog_start_distance"); + public static final AttributeKey VISUAL_WATER_FOG_END_DISTANCE = vanilla("visual/water_fog_end_distance"); + public static final AttributeKey VISUAL_SKY_COLOR = vanilla("visual/sky_color"); + public static final AttributeKey VISUAL_SUNRISE_SUNSET_COLOR = vanilla("visual/sunrise_sunset_color"); + public static final AttributeKey VISUAL_CLOUD_COLOR = vanilla("visual/cloud_color"); + public static final AttributeKey VISUAL_CLOUD_HEIGHT = vanilla("visual/cloud_height"); + public static final AttributeKey VISUAL_SUN_ANGLE = vanilla("visual/sun_angle"); + public static final AttributeKey VISUAL_MOON_ANGLE = vanilla("visual/moon_angle"); + public static final AttributeKey VISUAL_STAR_ANGLE = vanilla("visual/star_angle"); + public static final AttributeKey VISUAL_MOON_PHASE = vanilla("visual/moon_phase"); + public static final AttributeKey VISUAL_STAR_BRIGHTNESS = vanilla("visual/star_brightness"); + public static final AttributeKey VISUAL_BLOCK_LIGHT_TINT = vanilla("visual/block_light_tint"); + public static final AttributeKey VISUAL_SKY_LIGHT_COLOR = vanilla("visual/sky_light_color"); + public static final AttributeKey VISUAL_SKY_LIGHT_FACTOR = vanilla("visual/sky_light_factor"); + public static final AttributeKey VISUAL_NIGHT_VISION_COLOR = vanilla("visual/night_vision_color"); + public static final AttributeKey VISUAL_AMBIENT_LIGHT_COLOR = vanilla("visual/ambient_light_color"); + public static final AttributeKey VISUAL_DEFAULT_DRIPSTONE_PARTICLE = vanilla("visual/default_dripstone_particle"); + public static final AttributeKey> VISUAL_AMBIENT_PARTICLES = vanilla("visual/ambient_particles"); + public static final AttributeKey AUDIO_BACKGROUND_MUSIC = vanilla("audio/background_music"); + public static final AttributeKey AUDIO_MUSIC_VOLUME = vanilla("audio/music_volume"); + public static final AttributeKey AUDIO_AMBIENT_SOUNDS = vanilla("audio/ambient_sounds"); + public static final AttributeKey AUDIO_FIREFLY_BUSH_SOUNDS = vanilla("audio/firefly_bush_sounds"); + public static final AttributeKey GAMEPLAY_SKY_LIGHT_LEVEL = vanilla("gameplay/sky_light_level"); + public static final AttributeKey GAMEPLAY_CAN_START_RAID = vanilla("gameplay/can_start_raid"); + public static final AttributeKey GAMEPLAY_WATER_EVAPORATES = vanilla("gameplay/water_evaporates"); + public static final AttributeKey GAMEPLAY_BED_RULE = vanilla("gameplay/bed_rule"); + public static final AttributeKey GAMEPLAY_STRAW_BED_RULE = vanilla("gameplay/straw_bed_rule"); + public static final AttributeKey GAMEPLAY_RESPAWN_ANCHOR_WORKS = vanilla("gameplay/respawn_anchor_works"); + public static final AttributeKey GAMEPLAY_NETHER_PORTAL_SPAWNS_PIGLIN = vanilla("gameplay/nether_portal_spawns_piglin"); + public static final AttributeKey GAMEPLAY_FAST_LAVA = vanilla("gameplay/fast_lava"); + public static final AttributeKey GAMEPLAY_INCREASED_FIRE_BURNOUT = vanilla("gameplay/increased_fire_burnout"); + public static final AttributeKey GAMEPLAY_EYEBLOSSOM_OPEN = vanilla("gameplay/eyeblossom_open"); + public static final AttributeKey GAMEPLAY_TURTLE_EGG_HATCH_CHANCE = vanilla("gameplay/turtle_egg_hatch_chance"); + public static final AttributeKey GAMEPLAY_PIGLINS_ZOMBIFY = vanilla("gameplay/piglins_zombify"); + public static final AttributeKey GAMEPLAY_SNOW_GOLEM_MELTS = vanilla("gameplay/snow_golem_melts"); + public static final AttributeKey GAMEPLAY_CREAKING_ACTIVE = vanilla("gameplay/creaking_active"); + public static final AttributeKey GAMEPLAY_SURFACE_SLIME_SPAWN_CHANCE = vanilla("gameplay/surface_slime_spawn_chance"); + public static final AttributeKey GAMEPLAY_CAT_WAKING_UP_GIFT_CHANCE = vanilla("gameplay/cat_waking_up_gift_chance"); + public static final AttributeKey GAMEPLAY_BEES_STAY_IN_HIVE = vanilla("gameplay/bees_stay_in_hive"); + public static final AttributeKey GAMEPLAY_MONSTERS_BURN = vanilla("gameplay/monsters_burn"); + public static final AttributeKey GAMEPLAY_CAN_PILLAGER_PATROL_SPAWN = vanilla("gameplay/can_pillager_patrol_spawn"); + public static final AttributeKey GAMEPLAY_NATURAL_MOB_SPAWNS = vanilla("gameplay/natural_mob_spawns"); + public static final AttributeKey GAMEPLAY_CREATURE_WORLD_GEN_SPAWN_PROBABILITY = + vanilla("gameplay/creature_world_gen_spawn_probability"); + public static final AttributeKey GAMEPLAY_VILLAGER_ACTIVITY = vanilla("gameplay/villager_activity"); + public static final AttributeKey GAMEPLAY_BABY_VILLAGER_ACTIVITY = vanilla("gameplay/baby_villager_activity"); + + public static final AttributeKey BIOME_HAS_PRECIPITATION = terra("biome/has_precipitation"); + public static final AttributeKey BIOME_TEMPERATURE = terra("biome/temperature"); + public static final AttributeKey BIOME_TEMPERATURE_MODIFIER = terra("biome/temperature_modifier"); + public static final AttributeKey BIOME_DOWNFALL = terra("biome/downfall"); + public static final AttributeKey BIOME_WATER_COLOR = terra("biome/water_color"); + public static final AttributeKey BIOME_FOLIAGE_COLOR = terra("biome/foliage_color"); + public static final AttributeKey BIOME_DRY_FOLIAGE_COLOR = terra("biome/dry_foliage_color"); + public static final AttributeKey BIOME_GRASS_COLOR = terra("biome/grass_color"); + public static final AttributeKey BIOME_GRASS_COLOR_MODIFIER = terra("biome/grass_color_modifier"); + public static final AttributeKey BIOME_VILLAGER_TYPE = terra("biome/villager_type"); + public static final AttributeKey DIMENSION_HAS_FIXED_TIME = terra("dimension/has_fixed_time"); + public static final AttributeKey DIMENSION_HAS_SKYLIGHT = terra("dimension/has_skylight"); + public static final AttributeKey DIMENSION_HAS_CEILING = terra("dimension/has_ceiling"); + public static final AttributeKey DIMENSION_HAS_ENDER_DRAGON_FIGHT = terra("dimension/has_ender_dragon_fight"); + public static final AttributeKey DIMENSION_COORDINATE_SCALE = terra("dimension/coordinate_scale"); + public static final AttributeKey DIMENSION_MIN_Y = terra("dimension/min_y"); + public static final AttributeKey DIMENSION_HEIGHT = terra("dimension/height"); + public static final AttributeKey DIMENSION_LOGICAL_HEIGHT = terra("dimension/logical_height"); + public static final AttributeKey> DIMENSION_INFINIBURN = terra("dimension/infiniburn"); + public static final AttributeKey DIMENSION_AMBIENT_LIGHT = terra("dimension/ambient_light"); + public static final AttributeKey DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL = terra("dimension/monster_spawn_light_level"); + public static final AttributeKey DIMENSION_MONSTER_SPAWN_BLOCK_LIGHT_LIMIT = + terra("dimension/monster_spawn_block_light_limit"); + public static final AttributeKey DIMENSION_SKYBOX = terra("dimension/skybox"); + public static final AttributeKey DIMENSION_CARDINAL_LIGHT = terra("dimension/cardinal_light"); + public static final AttributeKey DIMENSION_DEFAULT_CLOCK = terra("dimension/default_clock"); + public static final AttributeKey WORLD_SEA_LEVEL = terra("world/sea_level"); + public static final AttributeKey WORLD_SPAWN_HEIGHT = terra("world/spawn_height"); + public static final AttributeKey WORLD_MOB_GENERATION = terra("world/mob_generation"); + + private static final List> VIEW = seal(); + + private MinecraftAttributes() { } + + public static List> all() { + return VIEW; + } + + private static List> seal() { + List> view = List.copyOf(building); + building = null; + return view; + } + + private static AttributeKey vanilla(String path) { + return add(RegistryKey.of("minecraft", path)); + } + + private static AttributeKey terra(String path) { + return add(RegistryKey.of("terra", path)); + } + + private static AttributeKey add(RegistryKey key) { + AttributeKey attributeKey = AttributeKey.of(key); + building.add(attributeKey); + return attributeKey; + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributesAddon.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributesAddon.java new file mode 100644 index 000000000..846afd075 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftAttributesAddon.java @@ -0,0 +1,35 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import java.util.List; + +import com.dfsek.terra.addons.manifest.api.AddonInitializer; +import com.dfsek.terra.api.Platform; +import com.dfsek.terra.api.addon.BaseAddon; +import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent; +import com.dfsek.terra.api.event.functional.FunctionalEventHandler; +import com.dfsek.terra.api.inject.annotations.Inject; +import com.dfsek.terra.api.registry.CheckedRegistry; +import com.dfsek.terra.api.world.attribute.Attribute; + + +public class MinecraftAttributesAddon implements AddonInitializer { + @Inject + private Platform platform; + + @Inject + private BaseAddon addon; + + @Override + public void initialize() { + List> attributes = MinecraftAttributeTable.create(platform.getAttributeHandle()); + + platform.getEventManager() + .getHandler(FunctionalEventHandler.class) + .register(addon, ConfigPackPreLoadEvent.class) + .then(event -> { + CheckedRegistry> registry = event.getPack().getOrCreateRegistry(Attribute.REGISTRY_TYPE); + for(Attribute attribute : attributes) registry.register(attribute.getRegistryKey(), attribute); + }) + .failThrough(); + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftCodecs.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftCodecs.java new file mode 100644 index 000000000..8919d3158 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftCodecs.java @@ -0,0 +1,349 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalDouble; +import java.util.OptionalInt; +import java.util.Set; +import java.util.TreeSet; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.AttributeCodec; +import com.dfsek.terra.api.world.attribute.AttributeCodecs; +import com.dfsek.terra.api.world.attribute.AttributeCodecs.ObjectReader; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.RawValue; + + +public final class MinecraftCodecs { + public static final String NAMESPACE = "minecraft"; + + // Same wording as the core identifier codec. + private static final String EXPECTED_IDENTIFIER = "expected an identifier like \"" + NAMESPACE + ":id\""; + + private static final Set MOB_CATEGORIES = Set.of("monster", "creature", "ambient", "axolotls", "underground_water_creature", + "water_creature", "water_ambient", "misc"); + + private final AttributeCodecs codecs; + private final DecodeContext plain; + private final AttributeCodec idString; + private final AttributeCodec identifier; + private final AttributeCodec> identifierOrTag; + private final AttributeCodec moonPhase; + private final AttributeCodec particle; + private final AttributeCodec ambientParticle; + private final AttributeCodec> ambientParticles; + private final AttributeCodec intProvider; + private final AttributeCodec soundRef; + private final AttributeCodec music; + private final AttributeCodec backgroundMusic; + private final AttributeCodec mood; + private final AttributeCodec> additions; + private final AttributeCodec ambientSounds; + private final AttributeCodec bedRuleRule; + private final AttributeCodec bedRule; + private final AttributeCodec> spawners; + private final AttributeCodec spawnCost; + private final AttributeCodec>> spawnsByCategory; + private final AttributeCodec> spawnCosts; + private final AttributeCodec mobSpawnSettings; + + public MinecraftCodecs(AttributeHandle handle) { + AttributeCodecs c = handle.codecs(); + this.codecs = c; + this.plain = handle.plainContext(); + this.idString = c.string(EXPECTED_IDENTIFIER); + + AttributeCodec coreIdentifier = c.identifier(NAMESPACE); + this.identifier = c.of((raw, context) -> { + String s = idString.decode(raw, context); + return lowerCase(coreIdentifier.decode(s, plain), s); + }, coreIdentifier::encode); + + AttributeCodec> coreIdentifierOrTag = c.identifierOrTag(NAMESPACE); + this.identifierOrTag = c.of((raw, context) -> { + String s = idString.decode(raw, context); + Either id = coreIdentifierOrTag.decode(s, plain); + lowerCase(id.hasLeft() ? id.getLeft().orElseThrow() : id.getRight().orElseThrow().key(), s); + return id; + }, coreIdentifierOrTag::encode); + + this.moonPhase = c.enumCodec("moon phase", MoonPhase.class); + + this.particle = c.of((raw, context) -> { + Object value = context.resolve(raw); + if(!(value instanceof Map map) || !map.containsKey("type")) { + throw new DecodeException("expected a particle object with a \"type\" key, got " + c.describe(value)); + } + if(map.get("type") instanceof String type) { + try { + identifier.decode(type, plain); + } catch(DecodeException e) { + throw new DecodeException("\"type\" of particle: " + e.getMessage(), e); + } + } + return c.raw().decode(value, context); + }, RawValue::value); + + this.ambientParticle = c.of((raw, context) -> { + ObjectReader f = c.reader("ambient particle", raw, context); + RawValue value = f.required("particle", this.particle); + float probability = f.required("probability", c.unitFloat()); + f.finish(); + return new AmbientParticle(value, probability); + }, value -> c.writer() + .put("particle", particle, value.particle()) + .put("probability", c.unitFloat(), value.probability()) + .map()); + + this.ambientParticles = c.list(ambientParticle); + + this.intProvider = c.of((raw, context) -> { + String expected = "expected an integer or an int provider object"; + Object value = context.resolve(raw); + if(value instanceof Map map) { + if(!map.containsKey("type")) throw new DecodeException("int provider object is missing \"type\""); + return new IntProviderValue(OptionalInt.empty(), Optional.of(c.raw().decode(value, context))); + } + if(value instanceof Number) return new IntProviderValue(OptionalInt.of(c.intCodec().decode(value, context)), Optional.empty()); + if(value instanceof String) { + try { + return new IntProviderValue(OptionalInt.of(c.intCodec().decode(value, context)), Optional.empty()); + } catch(DecodeException e) { + throw new DecodeException(expected + ", got " + c.describe(value), e); + } + } + throw new DecodeException(expected + ", got " + c.describe(value)); + }, value -> value.constant().isPresent() ? (Object) value.constant().getAsInt() : value.provider().orElseThrow().value()); + + this.soundRef = c.of((raw, context) -> { + Object value = context.resolve(raw); + if(value instanceof String) return new SoundRef(identifier.decode(value, context), OptionalDouble.empty()); + if(value instanceof Map) { + ObjectReader f = c.reader("sound", value, context); + RegistryKey id = f.required("sound_id", identifier); + Optional range = f.optional("range", c.doubleCodec()); + f.finish(); + return new SoundRef(id, range.map(OptionalDouble::of).orElse(OptionalDouble.empty())); + } + throw new DecodeException("expected a sound ID or a {sound_id, range} object, got " + c.describe(value)); + }, value -> { + if(value.range().isEmpty()) return identifier.encode(value.id()); + return c.writer() + .put("sound_id", identifier, value.id()) + .put("range", c.doubleCodec(), value.range().getAsDouble()) + .map(); + }); + + this.music = c.of((raw, context) -> { + ObjectReader f = c.reader("music", raw, context); + SoundRef sound = f.required("sound", soundRef); + int min = f.required("min_delay", c.nonNegativeInt()); + int max = f.required("max_delay", c.nonNegativeInt()); + boolean replace = f.orDefault("replace_current_music", c.booleanCodec(), false); + f.finish(); + return new Music(sound, min, max, replace); + }, value -> c.writer() + .put("sound", soundRef, value.sound()) + .put("min_delay", c.nonNegativeInt(), value.minDelay()) + .put("max_delay", c.nonNegativeInt(), value.maxDelay()) + .put("replace_current_music", c.booleanCodec(), value.replaceCurrentMusic()) + .map()); + + this.backgroundMusic = c.of((raw, context) -> { + ObjectReader f = c.reader("background music", raw, context); + Optional def = f.optional("default", music); + Optional creative = f.optional("creative", music); + Optional underwater = f.optional("underwater", music); + f.finish(); + return new BackgroundMusic(def, creative, underwater); + }, value -> c.writer() + .optional("default", music, value.defaultMusic()) + .optional("creative", music, value.creative()) + .optional("underwater", music, value.underwater()) + .map()); + + this.mood = c.of((raw, context) -> { + ObjectReader f = c.reader("ambient mood", raw, context); + SoundRef sound = f.required("sound", soundRef); + int tickDelay = f.required("tick_delay", c.intCodec()); + int extent = f.required("block_search_extent", c.intCodec()); + double offset = f.required("offset", c.doubleCodec()); + f.finish(); + return new AmbientSounds.Mood(sound, tickDelay, extent, offset); + }, value -> c.writer() + .put("sound", soundRef, value.sound()) + .put("tick_delay", c.intCodec(), value.tickDelay()) + .put("block_search_extent", c.intCodec(), value.blockSearchExtent()) + .put("offset", c.doubleCodec(), value.offset()) + .map()); + + this.additions = c.compactList(c.of((raw, context) -> { + ObjectReader f = c.reader("ambient additions", raw, context); + SoundRef sound = f.required("sound", soundRef); + double chance = f.required("tick_chance", c.doubleCodec()); + f.finish(); + return new AmbientSounds.Additions(sound, chance); + }, value -> c.writer() + .put("sound", soundRef, value.sound()) + .put("tick_chance", c.doubleCodec(), value.tickChance()) + .map())); + + this.ambientSounds = c.of((raw, context) -> { + ObjectReader f = c.reader("ambient sounds", raw, context); + Optional loop = f.optional("loop", soundRef); + Optional moodValue = f.optional("mood", mood); + List additionsValue = f.orDefault("additions", additions, List.of()); + f.finish(); + return new AmbientSounds(loop, moodValue, additionsValue); + }, value -> c.writer() + .optional("loop", soundRef, value.loop()) + .optional("mood", mood, value.mood()) + .put("additions", additions, value.additions()) + .map()); + + this.bedRuleRule = c.enumCodec("bed rule", BedRule.Rule.class); + + this.bedRule = c.of((raw, context) -> { + ObjectReader f = c.reader("bed rule", raw, context); + BedRule.Rule canSleep = f.required("can_sleep", bedRuleRule); + BedRule.Rule canSetSpawn = f.required("can_set_spawn", bedRuleRule); + boolean onUse = f.orDefault("destroy_on_use", c.booleanCodec(), false); + boolean onLeave = f.orDefault("destroy_on_leave", c.booleanCodec(), false); + Optional message = f.optional("error_message", c.raw()); + f.finish(); + return new BedRule(canSleep, canSetSpawn, onUse, onLeave, message); + }, value -> c.writer() + .put("can_sleep", bedRuleRule, value.canSleep()) + .put("can_set_spawn", bedRuleRule, value.canSetSpawn()) + .put("destroy_on_use", c.booleanCodec(), value.destroyOnUse()) + .put("destroy_on_leave", c.booleanCodec(), value.destroyOnLeave()) + .optional("error_message", c.raw(), value.errorMessage()) + .map()); + + this.spawners = c.list(c.of((raw, context) -> { + ObjectReader f = c.reader("mob spawner", raw, context); + RegistryKey type = f.required("type", identifier); + int weight = f.required("weight", c.nonNegativeInt()); + IntProviderValue count = f.required("count", intProvider); + f.finish(); + return new MobSpawnSettings.Spawner(type, weight, count); + }, value -> c.writer() + .put("type", identifier, value.type()) + .put("weight", c.nonNegativeInt(), value.weight()) + .put("count", intProvider, value.count()) + .map())); + + this.spawnCost = c.of((raw, context) -> { + ObjectReader f = c.reader("spawn cost", raw, context); + double budget = f.required("energy_budget", c.doubleCodec()); + double charge = f.required("charge", c.doubleCodec()); + f.finish(); + return new MobSpawnSettings.Cost(budget, charge); + }, value -> c.writer() + .put("energy_budget", c.doubleCodec(), value.energyBudget()) + .put("charge", c.doubleCodec(), value.charge()) + .map()); + + this.spawnsByCategory = c.of((raw, context) -> { + ObjectReader categories = c.reader("spawns_by_category", raw, context); + Map> out = new LinkedHashMap<>(); + for(String key : categories.keys()) { + if(!MOB_CATEGORIES.contains(key)) { + throw new DecodeException("unknown mob category \"" + key + "\", expected one of " + new TreeSet<>(MOB_CATEGORIES)); + } + out.put(key, categories.required(key, spawners)); + } + categories.finish(); + return out; + }, value -> { + Map out = new LinkedHashMap<>(); + value.forEach((category, list) -> out.put(category, spawners.encode(list))); + return out; + }); + + // Map keys are never preprocessed. + this.spawnCosts = c.of((raw, context) -> { + ObjectReader costs = c.reader("spawn_costs", raw, context); + Map out = new LinkedHashMap<>(); + for(String key : costs.keys()) { + out.put(identifier.decode(key, plain), costs.required(key, spawnCost)); + } + costs.finish(); + return out; + }, value -> { + Map out = new LinkedHashMap<>(); + value.forEach((entity, cost) -> out.put((String) identifier.encode(entity), spawnCost.encode(cost))); + return out; + }); + + this.mobSpawnSettings = c.of((raw, context) -> { + ObjectReader f = c.reader("mob spawn settings", raw, context); + Map> byCategory = f.required("spawns_by_category", spawnsByCategory); + Map costs = f.required("spawn_costs", spawnCosts); + f.finish(); + return new MobSpawnSettings(byCategory, costs); + }, value -> c.writer() + .put("spawns_by_category", spawnsByCategory, value.spawnsByCategory()) + .put("spawn_costs", spawnCosts, value.spawnCosts()) + .map()); + } + + private RegistryKey lowerCase(RegistryKey key, String written) throws DecodeException { + try { + return MinecraftIds.requireLowerCase(key, written); + } catch(IllegalArgumentException e) { + throw new DecodeException(EXPECTED_IDENTIFIER + ", got " + codecs.describe(written), e); + } + } + + public AttributeCodec identifier() { + return identifier; + } + + public AttributeCodec> identifierOrTag() { + return identifierOrTag; + } + + public AttributeCodec moonPhase() { + return moonPhase; + } + + public AttributeCodec particle() { + return particle; + } + + public AttributeCodec> ambientParticles() { + return ambientParticles; + } + + public AttributeCodec intProvider() { + return intProvider; + } + + public AttributeCodec soundRef() { + return soundRef; + } + + public AttributeCodec backgroundMusic() { + return backgroundMusic; + } + + public AttributeCodec ambientSounds() { + return ambientSounds; + } + + public AttributeCodec bedRule() { + return bedRule; + } + + public AttributeCodec mobSpawnSettings() { + return mobSpawnSettings; + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftIds.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftIds.java new file mode 100644 index 000000000..44739214f --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MinecraftIds.java @@ -0,0 +1,29 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import java.util.regex.Pattern; + +import com.dfsek.terra.api.registry.key.RegistryKey; + + +public final class MinecraftIds { + private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9_.-]+"); + private static final Pattern PATH = Pattern.compile("[a-z0-9_./-]+"); + + private MinecraftIds() { } + + public static RegistryKey requireLowerCase(RegistryKey key) { + return requireLowerCase(key, key.toString()); + } + + public static RegistryKey requireLowerCase(RegistryKey key, String written) { + if(!NAMESPACE.matcher(key.getNamespace()).matches()) { + throw new IllegalArgumentException( + "invalid ID \"" + written + "\": the namespace must be non-empty and use only a-z, 0-9, _, . and -"); + } + if(!PATH.matcher(key.getID()).matches()) { + throw new IllegalArgumentException( + "invalid ID \"" + written + "\": the path must be non-empty and use only a-z, 0-9, _, ., / and -"); + } + return key; + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MobSpawnSettings.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MobSpawnSettings.java new file mode 100644 index 000000000..4bc8a1822 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MobSpawnSettings.java @@ -0,0 +1,25 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.registry.key.RegistryKey; + + +public record MobSpawnSettings(Map> spawnsByCategory, Map spawnCosts) { + public static final MobSpawnSettings EMPTY = new MobSpawnSettings(Map.of(), Map.of()); + + public MobSpawnSettings { + Map> copy = new LinkedHashMap<>(); + spawnsByCategory.forEach((k, v) -> copy.put(k, List.copyOf(v))); + spawnsByCategory = Collections.unmodifiableMap(copy); + spawnCosts = Collections.unmodifiableMap(new LinkedHashMap<>(spawnCosts)); + } + + public record Spawner(RegistryKey type, int weight, IntProviderValue count) { } + + + public record Cost(double energyBudget, double charge) { } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MoonPhase.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MoonPhase.java new file mode 100644 index 000000000..95087c733 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/MoonPhase.java @@ -0,0 +1,26 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import com.dfsek.terra.api.registry.key.StringIdentifiable; + + +public enum MoonPhase implements StringIdentifiable { + FULL_MOON("full_moon"), + WANING_GIBBOUS("waning_gibbous"), + THIRD_QUARTER("third_quarter"), + WANING_CRESCENT("waning_crescent"), + NEW_MOON("new_moon"), + WAXING_CRESCENT("waxing_crescent"), + FIRST_QUARTER("first_quarter"), + WAXING_GIBBOUS("waxing_gibbous"); + + private final String id; + + MoonPhase(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Music.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Music.java new file mode 100644 index 000000000..27e1c0895 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Music.java @@ -0,0 +1,3 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +public record Music(SoundRef sound, int minDelay, int maxDelay, boolean replaceCurrentMusic) { } diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Skybox.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Skybox.java new file mode 100644 index 000000000..7ec311ffd --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/Skybox.java @@ -0,0 +1,21 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import com.dfsek.terra.api.registry.key.StringIdentifiable; + + +public enum Skybox implements StringIdentifiable { + NONE("none"), + OVERWORLD("overworld"), + END("end"); + + private final String id; + + Skybox(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } +} diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/SoundRef.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/SoundRef.java new file mode 100644 index 000000000..014ff5da0 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/SoundRef.java @@ -0,0 +1,8 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import java.util.OptionalDouble; + +import com.dfsek.terra.api.registry.key.RegistryKey; + + +public record SoundRef(RegistryKey id, OptionalDouble range) { } diff --git a/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/TemperatureModifier.java b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/TemperatureModifier.java new file mode 100644 index 000000000..77937199c --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/java/com/dfsek/terra/addons/attribute/minecraft/TemperatureModifier.java @@ -0,0 +1,20 @@ +package com.dfsek.terra.addons.attribute.minecraft; + +import com.dfsek.terra.api.registry.key.StringIdentifiable; + + +public enum TemperatureModifier implements StringIdentifiable { + NONE("none"), + FROZEN("frozen"); + + private final String id; + + TemperatureModifier(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } +} diff --git a/common/addons/minecraft-attributes/src/main/resources/terra.addon.yml b/common/addons/minecraft-attributes/src/main/resources/terra.addon.yml new file mode 100644 index 000000000..c58b7b5e8 --- /dev/null +++ b/common/addons/minecraft-attributes/src/main/resources/terra.addon.yml @@ -0,0 +1,12 @@ +schema-version: 1 +contributors: + - Terra contributors +id: minecraft-attributes +version: @VERSION@ +entrypoints: + - "com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributesAddon" +website: + issues: https://github.com/PolyhedralDev/Terra/issues + source: https://github.com/PolyhedralDev/Terra + docs: https://terra.polydev.org +license: MIT License diff --git a/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributeTypesTest.java b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributeTypesTest.java new file mode 100644 index 000000000..de2997da7 --- /dev/null +++ b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributeTypesTest.java @@ -0,0 +1,450 @@ +package attribute.minecraft; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.dfsek.terra.addons.attribute.minecraft.AmbientParticle; +import com.dfsek.terra.addons.attribute.minecraft.AmbientSounds; +import com.dfsek.terra.addons.attribute.minecraft.BackgroundMusic; +import com.dfsek.terra.addons.attribute.minecraft.BedRule; +import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue; +import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTypes; +import com.dfsek.terra.addons.attribute.minecraft.MinecraftCodecs; +import com.dfsek.terra.addons.attribute.minecraft.MinecraftIds; +import com.dfsek.terra.addons.attribute.minecraft.MobSpawnSettings; +import com.dfsek.terra.addons.attribute.minecraft.MoonPhase; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.RawValue; +import com.dfsek.terra.world.attribute.AttributeHandleImpl; + +import static org.junit.jupiter.api.Assertions.*; + + +class MinecraftAttributeTypesTest { + private static final float EPS = 1e-6f; + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final MinecraftAttributeTypes TYPES = new MinecraftAttributeTypes(HANDLE); + private static final DecodeContext PLAIN = HANDLE.plainContext(); + private static final MinecraftCodecs CODECS = new MinecraftCodecs(HANDLE); + + private static T mod(AttributeType type, Operation op, T subject, Object rawArg) throws DecodeException { + return type.apply(op, subject, type.decodeArgument(op, rawArg, PLAIN)); + } + + private static Map map(Object... kv) { + Map m = new LinkedHashMap<>(); + for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]); + return m; + } + + @Test + void everyTypeSupportsOverride() { + List> all = List.of(TYPES.moonPhase(), TYPES.bedRule(), TYPES.particle(), TYPES.ambientParticles(), + TYPES.backgroundMusic(), TYPES.ambientSounds(), TYPES.mobSpawnSettings(), TYPES.identifier(), TYPES.identifierOrTag(), + TYPES.intProvider()); + for(AttributeType t : all) assertTrue(t.operations().contains(Operation.OVERRIDE), t.id()); + } + + @Test + void operationSets() { + assertEquals(EnumSet.of(Operation.OVERRIDE), TYPES.identifier().operations()); + assertEquals(EnumSet.of(Operation.OVERRIDE), TYPES.identifierOrTag().operations()); + assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.APPEND), TYPES.ambientParticles().operations()); + assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.OVERLAY), TYPES.mobSpawnSettings().operations()); + } + + @Test + void idsAreVanillaTypeIds() { + assertEquals("moon_phase", TYPES.moonPhase().id()); + assertEquals("bed_rule", TYPES.bedRule().id()); + assertEquals("particle", TYPES.particle().id()); + assertEquals("ambient_particles", TYPES.ambientParticles().id()); + assertEquals("background_music", TYPES.backgroundMusic().id()); + assertEquals("ambient_sounds", TYPES.ambientSounds().id()); + assertEquals("mob_spawn_settings", TYPES.mobSpawnSettings().id()); + assertEquals("identifier", TYPES.identifier().id()); + assertEquals("identifier_or_tag", TYPES.identifierOrTag().id()); + assertEquals("int_provider", TYPES.intProvider().id()); + } + + @Test + void decodeFailuresReadTheSameEverywhere() { + String bedRule = assertThrows(DecodeException.class, + () -> TYPES.bedRule().decode(map("can_sleep", "sometimes", "can_set_spawn", "always"), PLAIN)).getMessage(); + assertEquals("\"can_sleep\" of bed rule: unknown bed rule \"sometimes\", expected one of [always, when_dark, never]", bedRule); + String moonPhase = assertThrows(DecodeException.class, () -> TYPES.moonPhase().decode("x", PLAIN)).getMessage(); + assertTrue(moonPhase.startsWith("unknown moon phase \"x\", expected one of [full_moon, "), moonPhase); + } + + @Test + void enumsAreStringIdentifiable() { + assertEquals("waxing_gibbous", MoonPhase.WAXING_GIBBOUS.getID()); + assertEquals("when_dark", BedRule.Rule.WHEN_DARK.getID()); + assertEquals("new_moon", TYPES.moonPhase().encode(MoonPhase.NEW_MOON)); + } + + @Test + void ambientParticlesAppend() throws DecodeException { + AttributeType> t = TYPES.ambientParticles(); + List one = t.decode(List.of(map("particle", map("type", "minecraft:crimson_spore"), "probability", 0.025)), PLAIN); + List two = t.decode(List.of(map("particle", map("type", "minecraft:white_ash"), "probability", 0.1)), PLAIN); + assertEquals(1, one.size()); + assertEquals(0.025f, one.get(0).probability(), EPS); + assertEquals(new RawValue(map("type", "minecraft:crimson_spore")), one.get(0).particle()); + assertEquals(one, t.apply(Operation.APPEND, one, List.of())); + assertEquals(two, t.apply(Operation.APPEND, List.of(), two)); + assertEquals(List.of(one.get(0), two.get(0)), t.apply(Operation.APPEND, one, two)); + assertEquals(List.of(one.get(0), two.get(0)), + mod(t, Operation.APPEND, one, List.of(map("particle", map("type", "minecraft:white_ash"), "probability", 0.1)))); + } + + @Test + void ambientParticleValidation() { + AttributeType> t = TYPES.ambientParticles(); + assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", map("type", "x"), "probability", 1.5)), PLAIN)); + assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", map("type", "x"))), PLAIN)); + assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", "x", "probability", 0.5)), PLAIN)); + assertThrows(DecodeException.class, + () -> t.decode(List.of(map("particle", map("type", "x"), "probability", 0.5, "extra", 1)), PLAIN)); + assertThrows(DecodeException.class, () -> t.decode(map("particle", map("type", "x"), "probability", 0.5), PLAIN)); + } + + private static MobSpawnSettings spawns(Map raw) throws DecodeException { + return TYPES.mobSpawnSettings().decode(raw, PLAIN); + } + + private static Map spawner(String type, int weight, int count) { + return map("type", type, "weight", weight, "count", count); + } + + @Test + void mobSpawnDecode() throws DecodeException { + MobSpawnSettings s = spawns(map( + "spawns_by_category", map("ambient", List.of(spawner("minecraft:bat", 10, 8))), + "spawn_costs", map("minecraft:enderman", map("energy_budget", 0.7, "charge", 0.15)))); + MobSpawnSettings.Spawner sp = s.spawnsByCategory().get("ambient").get(0); + assertEquals(RegistryKey.parse("minecraft:bat"), sp.type()); + assertEquals(10, sp.weight()); + assertEquals(8, sp.count().constant().getAsInt()); + assertEquals(0.7, s.spawnCosts().get(RegistryKey.parse("minecraft:enderman")).energyBudget(), 1e-9); + assertEquals(0.15, s.spawnCosts().get(RegistryKey.parse("minecraft:enderman")).charge(), 1e-9); + assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map("bogus", List.of()), "spawn_costs", map()))); + assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map()))); + assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map(), "spawn_costs", map(), "x", 1))); + } + + @Test + void mobSpawnCountMapIsKeptRaw() throws DecodeException { + MobSpawnSettings s = spawns(map("spawns_by_category", map("monster", List.of( + map("type", "minecraft:zombie", "weight", 5, + "count", map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3)))), + "spawn_costs", map())); + IntProviderValue c = s.spawnsByCategory().get("monster").get(0).count(); + assertTrue(c.constant().isEmpty()); + assertTrue(c.provider().isPresent()); + } + + @Test + void mobSpawnOverlayRules() throws DecodeException { + AttributeType t = TYPES.mobSpawnSettings(); + MobSpawnSettings empty = MobSpawnSettings.EMPTY; + MobSpawnSettings a = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1))), + "spawn_costs", map())); + assertSame(a, t.apply(Operation.OVERLAY, empty, a)); + assertSame(a, t.apply(Operation.OVERLAY, a, empty)); + MobSpawnSettings sup = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:husk", 1, 1)), + "creature", List.of(spawner("minecraft:pig", 1, 1))), "spawn_costs", map())); + assertSame(sup, t.apply(Operation.OVERLAY, a, sup)); + MobSpawnSettings s = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1)), + "creature", List.of(spawner("minecraft:cow", 1, 1))), + "spawn_costs", map("minecraft:a", map("energy_budget", 1, "charge", 1)))); + MobSpawnSettings arg = spawns(map("spawns_by_category", map("ambient", List.of(spawner("minecraft:bat", 1, 1)), + "creature", List.of(spawner("minecraft:pig", 1, 1))), + "spawn_costs", map("minecraft:b", map("energy_budget", 2, "charge", 2)))); + MobSpawnSettings r = t.apply(Operation.OVERLAY, s, arg); + assertEquals(RegistryKey.parse("minecraft:zombie"), r.spawnsByCategory().get("monster").get(0).type()); + assertEquals(RegistryKey.parse("minecraft:pig"), r.spawnsByCategory().get("creature").get(0).type()); + assertEquals(RegistryKey.parse("minecraft:bat"), r.spawnsByCategory().get("ambient").get(0).type()); + assertEquals(Set.of(RegistryKey.parse("minecraft:a"), RegistryKey.parse("minecraft:b")), r.spawnCosts().keySet()); + } + + @Test + void mobSpawnOverlayEmptyCategoryClears() throws DecodeException { + AttributeType t = TYPES.mobSpawnSettings(); + MobSpawnSettings s = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1)), + "creature", List.of(spawner("minecraft:cow", 1, 1))), "spawn_costs", map())); + MobSpawnSettings arg = spawns(map("spawns_by_category", map("monster", List.of()), "spawn_costs", map())); + MobSpawnSettings r = mod(t, Operation.OVERLAY, s, map("spawns_by_category", map("monster", List.of()), "spawn_costs", map())); + assertTrue(r.spawnsByCategory().get("monster").isEmpty()); + assertEquals(1, r.spawnsByCategory().get("creature").size()); + assertEquals(r, t.apply(Operation.OVERLAY, s, arg)); + } + + @Test + void ambientSoundsDecode() throws DecodeException { + AmbientSounds a = TYPES.ambientSounds().decode(map( + "additions", map("sound", "minecraft:ambient.crimson_forest.additions", "tick_chance", 0.0111), + "loop", "minecraft:ambient.crimson_forest.loop", + "mood", map("block_search_extent", 8, "offset", 2.0, "sound", "minecraft:ambient.crimson_forest.mood", "tick_delay", 6000)), + PLAIN); + assertEquals(1, a.additions().size()); + assertEquals(0.0111, a.additions().get(0).tickChance(), 1e-9); + assertEquals(RegistryKey.parse("minecraft:ambient.crimson_forest.loop"), a.loop().orElseThrow().id()); + assertEquals(6000, a.mood().orElseThrow().tickDelay()); + assertEquals(8, a.mood().orElseThrow().blockSearchExtent()); + assertEquals(2.0, a.mood().orElseThrow().offset(), 1e-9); + + AmbientSounds list = TYPES.ambientSounds().decode(map( + "additions", List.of(map("sound", "a:b", "tick_chance", 0.1), map("sound", "a:c", "tick_chance", 0.2))), PLAIN); + assertEquals(2, list.additions().size()); + assertTrue(list.loop().isEmpty()); + assertEquals(AmbientSounds.EMPTY, TYPES.ambientSounds().decode(map(), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("looop", "a:b"), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("mood", map("sound", "a:b")), PLAIN)); + } + + @Test + void soundRefForms() throws DecodeException { + AmbientSounds a = TYPES.ambientSounds().decode(map("loop", map("sound_id", "a:b", "range", 16)), PLAIN); + assertEquals(RegistryKey.parse("a:b"), a.loop().orElseThrow().id()); + assertEquals(16.0, a.loop().orElseThrow().range().getAsDouble(), 1e-9); + AmbientSounds b = TYPES.ambientSounds().decode(map("loop", map("sound_id", "a:b")), PLAIN); + assertTrue(b.loop().orElseThrow().range().isEmpty()); + assertEquals(RegistryKey.parse("minecraft:ambient.cave"), + TYPES.ambientSounds().decode(map("loop", "ambient.cave"), PLAIN).loop().orElseThrow().id()); + assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", 5), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", "Not Valid"), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", map("range", 1)), PLAIN)); + } + + @Test + void upperCaseIdRejected() { + DecodeException e = assertThrows(DecodeException.class, () -> CODECS.soundRef().decode("minecraft:Ambient.Cave", PLAIN)); + assertEquals("expected an identifier like \"minecraft:id\", got \"minecraft:Ambient.Cave\"", e.getMessage()); + assertEquals(path("minecraft:Ambient.Cave"), e.getCause().getMessage()); + assertEquals(namespace("Minecraft:x"), lowerCaseFailure(() -> CODECS.soundRef().decode("Minecraft:x", PLAIN))); + } + + private static String path(String written) { + return "invalid ID \"" + written + "\": the path must be non-empty and use only a-z, 0-9, _, ., / and -"; + } + + private static String namespace(String written) { + return "invalid ID \"" + written + "\": the namespace must be non-empty and use only a-z, 0-9, _, . and -"; + } + + private static String lowerCaseFailure(Executable decode) { + Throwable t = assertThrows(DecodeException.class, decode); + while(t != null && !(t instanceof IllegalArgumentException)) t = t.getCause(); + assertNotNull(t, "no lower-case rule failure in the cause chain"); + return t.getMessage(); + } + + @Test + void lowerCaseIds() { + assertEquals(path("minecraft:Music.Game"), + lowerCaseFailure(() -> TYPES.ambientSounds().decode(Map.of("loop", "minecraft:Music.Game"), PLAIN))); + assertEquals(path("Music.Game"), lowerCaseFailure(() -> TYPES.backgroundMusic().decode( + map("default", map("sound", "Music.Game", "min_delay", 1, "max_delay", 2)), PLAIN))); + assertEquals(path("minecraft:Flame"), lowerCaseFailure(() -> TYPES.particle().decode(map("type", "minecraft:Flame"), PLAIN))); + assertEquals(path("Idle"), lowerCaseFailure(() -> TYPES.identifier().decode("Idle", PLAIN))); + assertEquals(path("#minecraft:Logs"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("#minecraft:Logs", PLAIN))); + assertEquals(path("#Logs"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("#Logs", PLAIN))); + assertEquals(namespace("Minecraft:stone"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("Minecraft:stone", PLAIN))); + assertEquals(path("minecraft:Zombie"), lowerCaseFailure(() -> spawns(map( + "spawns_by_category", map("monster", List.of(spawner("minecraft:Zombie", 1, 1))), "spawn_costs", map())))); + assertEquals(namespace("Minecraft:enderman"), lowerCaseFailure(() -> spawns(map("spawns_by_category", map(), + "spawn_costs", map("Minecraft:enderman", map("energy_budget", 1, "charge", 1)))))); + } + + @Test + void requireLowerCase() { + RegistryKey key = RegistryKey.parse("minecraft:visual/fog_color"); + assertSame(key, MinecraftIds.requireLowerCase(key)); + assertSame(key, MinecraftIds.requireLowerCase(key, "visual/fog_color")); + assertEquals(namespace("Mod:thing"), + assertThrows(IllegalArgumentException.class, () -> MinecraftIds.requireLowerCase(RegistryKey.parse("Mod:thing"))).getMessage()); + assertEquals(path("mod:Thing"), + assertThrows(IllegalArgumentException.class, () -> MinecraftIds.requireLowerCase(RegistryKey.parse("mod:Thing"))).getMessage()); + assertEquals(path("Thing"), assertThrows(IllegalArgumentException.class, + () -> MinecraftIds.requireLowerCase(RegistryKey.parse("minecraft:Thing"), "Thing")).getMessage()); + } + + @Test + void integersFollowTheCoreRule() { + String weight = assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", + map("monster", List.of(map("type", "minecraft:zombie", "weight", 1.5, "count", 1))), "spawn_costs", map()))).getMessage(); + assertTrue(weight.endsWith("\"weight\" of mob spawner: expected an integer, got 1.5"), weight); + assertThrows(DecodeException.class, () -> TYPES.intProvider().decode(99999999999L, PLAIN)); + } + + @Test + void backgroundMusicDecode() throws DecodeException { + BackgroundMusic m = TYPES.backgroundMusic().decode(map( + "default", map("max_delay", 24000, "min_delay", 12000, "sound", "minecraft:music.game", "replace_current_music", true), + "underwater", map("max_delay", 24000, "min_delay", 12000, "sound", "minecraft:music.under_water")), PLAIN); + assertTrue(m.defaultMusic().orElseThrow().replaceCurrentMusic()); + assertFalse(m.underwater().orElseThrow().replaceCurrentMusic()); + assertEquals(12000, m.underwater().orElseThrow().minDelay()); + assertEquals(24000, m.underwater().orElseThrow().maxDelay()); + assertTrue(m.creative().isEmpty()); + assertEquals(BackgroundMusic.EMPTY, TYPES.backgroundMusic().decode(map(), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.backgroundMusic().decode(map("bogus", 1), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.backgroundMusic().decode(map("default", map("sound", "a:b", "min_delay", 1)), PLAIN)); + assertThrows(DecodeException.class, + () -> TYPES.backgroundMusic().decode(map("default", map("sound", "a:b", "min_delay", -1, "max_delay", 1)), PLAIN)); + } + + @Test + void bedRuleDecode() throws DecodeException { + BedRule r = TYPES.bedRule().decode(map("can_set_spawn", "never", "can_sleep", "when_dark", "destroy_on_leave", true, + "error_message", map("translate", "block.minecraft.bed.no_sleep")), PLAIN); + assertEquals(BedRule.Rule.WHEN_DARK, r.canSleep()); + assertEquals(BedRule.Rule.NEVER, r.canSetSpawn()); + assertFalse(r.destroyOnUse()); + assertTrue(r.destroyOnLeave()); + assertTrue(r.errorMessage().isPresent()); + BedRule plain = TYPES.bedRule().decode(map("can_set_spawn", "always", "can_sleep", "always"), PLAIN); + assertTrue(plain.errorMessage().isEmpty()); + assertThrows(DecodeException.class, () -> TYPES.bedRule().decode(map("can_sleep", "always"), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.bedRule().decode(map("can_sleep", "sometimes", "can_set_spawn", "always"), PLAIN)); + assertThrows(DecodeException.class, + () -> TYPES.bedRule().decode(map("can_sleep", "always", "can_set_spawn", "always", "nope", 1), PLAIN)); + } + + @Test + void simpleTypesDecode() throws DecodeException { + assertEquals(MoonPhase.NEW_MOON, TYPES.moonPhase().decode("new_moon", PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.moonPhase().decode("blue_moon", PLAIN)); + assertEquals(RegistryKey.parse("minecraft:idle"), TYPES.identifier().decode("minecraft:idle", PLAIN)); + assertEquals(RegistryKey.parse("minecraft:idle"), TYPES.identifier().decode("idle", PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.identifier().decode("Not Valid", PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.identifier().decode(3, PLAIN)); + assertEquals("expected an identifier, not a tag, got \"#minecraft:logs\"", + assertThrows(DecodeException.class, () -> TYPES.identifier().decode("#minecraft:logs", PLAIN)).getMessage()); + assertEquals(Either.left(RegistryKey.parse("minecraft:stone")), TYPES.identifierOrTag().decode("stone", PLAIN)); + assertEquals(Either.right(TagKey.parse("#minecraft:logs")), TYPES.identifierOrTag().decode("#logs", PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.identifierOrTag().decode("#", PLAIN)); + } + + @Test + void particleDecode() throws DecodeException { + RawValue p = TYPES.particle().decode(map("type", "minecraft:dripping_dripstone_lava"), PLAIN); + assertEquals(new RawValue(map("type", "minecraft:dripping_dripstone_lava")), p); + assertThrows(DecodeException.class, () -> TYPES.particle().decode(map("color", 1), PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.particle().decode("minecraft:flame", PLAIN)); + } + + @Test + void intProviderDecode() throws DecodeException { + IntProviderValue c = TYPES.intProvider().decode(7, PLAIN); + assertEquals(7, c.constant().getAsInt()); + assertTrue(c.provider().isEmpty()); + IntProviderValue p = TYPES.intProvider().decode(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3), PLAIN); + assertTrue(p.constant().isEmpty()); + assertTrue(p.provider().isPresent()); + assertThrows(DecodeException.class, () -> TYPES.intProvider().decode("x", PLAIN)); + assertThrows(DecodeException.class, () -> TYPES.intProvider().decode(1.5, PLAIN)); + } + + @Test + void overrideArgumentDecodesWithValueDecoder() throws DecodeException { + assertEquals(MoonPhase.NEW_MOON, mod(TYPES.moonPhase(), Operation.OVERRIDE, MoonPhase.FULL_MOON, "new_moon")); + } + + @Test + void nestedDecodeContext() throws DecodeException { + List seen = new ArrayList<>(); + DecodeContext recording = new DecodeContext() { + @Override + public V load(Type type, Object raw) throws DecodeException { + seen.add(raw); + return PLAIN.load(type, raw); + } + + @Override + public Object resolve(Object raw) { + return raw; + } + }; + Map music = map("sound", "minecraft:music.game", "min_delay", 1, "max_delay", 2); + TYPES.backgroundMusic().decode(map("default", music), recording); + assertTrue(seen.contains("minecraft:music.game"), seen.toString()); + assertTrue(seen.contains(1), seen.toString()); + assertTrue(seen.contains(2), seen.toString()); + assertTrue(seen.contains(music), seen.toString()); + } + + private static DecodeContext referencing(Map targets) { + return new DecodeContext() { + @Override + public V load(Type type, Object raw) throws DecodeException { + return PLAIN.load(type, raw); + } + + @Override + public Object resolve(Object raw) { + if(raw instanceof String s && targets.containsKey(s)) return resolve(targets.get(s)); + if(raw instanceof Map m) { + Map out = new LinkedHashMap<>(); + m.forEach((k, v) -> out.put((String) k, resolve(v))); + return out; + } + if(raw instanceof List l) return l.stream().map(this::resolve).toList(); + return raw; + } + }; + } + + @Test + void resolveBeforeShape() throws DecodeException { + DecodeContext context = referencing(map( + "@sound", map("sound_id", "minecraft:ambient.cave", "range", 4.0), + "@additions", List.of(map("sound", "minecraft:a", "tick_chance", 0.5), map("sound", "minecraft:b", "tick_chance", 0.25)), + "@provider", map("type", "minecraft:uniform", "min_inclusive", "@min", "max_inclusive", 4), + "@min", 1, + "@flame", "minecraft:flame", + "@message", map("translate", "@key"), + "@key", "block.minecraft.bed.no_sleep")); + + AmbientSounds sounds = TYPES.ambientSounds().decode(map("loop", "@sound", "additions", "@additions"), context); + assertEquals(4.0, sounds.loop().orElseThrow().range().orElseThrow()); + assertEquals(2, sounds.additions().size()); + + IntProviderValue provider = TYPES.intProvider().decode("@provider", context); + assertEquals(new RawValue(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 4)), + provider.provider().orElseThrow()); + + List particles = TYPES.ambientParticles().decode( + List.of(map("particle", map("type", "@flame"), "probability", 0.5)), context); + assertEquals(new RawValue(map("type", "minecraft:flame")), particles.get(0).particle()); + + BedRule rule = TYPES.bedRule().decode(map("can_sleep", "never", "can_set_spawn", "never", "error_message", "@message"), + context); + assertEquals(new RawValue(map("translate", "block.minecraft.bed.no_sleep")), rule.errorMessage().orElseThrow()); + } + + @Test + void mapKeysInsideValuesAreNotPreprocessed() throws DecodeException { + DecodeContext context = referencing(map("minecraft:zombie", "minecraft:cow")); + MobSpawnSettings settings = TYPES.mobSpawnSettings().decode(map( + "spawns_by_category", map(), + "spawn_costs", map("minecraft:zombie", map("energy_budget", 1.0, "charge", 0.5))), context); + assertEquals(List.of(RegistryKey.parse("minecraft:zombie")), List.copyOf(settings.spawnCosts().keySet())); + } +} diff --git a/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesAddonTest.java b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesAddonTest.java new file mode 100644 index 000000000..ccefbdcc0 --- /dev/null +++ b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesAddonTest.java @@ -0,0 +1,99 @@ +package attribute.minecraft; + +import ca.solostudios.strata.Versions; +import ca.solostudios.strata.version.Version; +import ca.solostudios.strata.version.VersionRange; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.Map; + +import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes; +import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributesAddon; +import com.dfsek.terra.api.Platform; +import com.dfsek.terra.api.addon.BaseAddon; +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.event.EventManager; +import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent; +import com.dfsek.terra.api.inject.Injector; +import com.dfsek.terra.api.registry.CheckedRegistry; +import com.dfsek.terra.api.util.reflection.TypeKey; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.event.EventManagerImpl; +import com.dfsek.terra.registry.CheckedRegistryImpl; +import com.dfsek.terra.registry.OpenRegistryImpl; +import com.dfsek.terra.world.attribute.AttributeHandleImpl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class MinecraftAttributesAddonTest { + private static final BaseAddon ADDON = new BaseAddon() { + @Override + public String getID() { + return "minecraft-attributes"; + } + + @Override + public Version getVersion() { + return null; + } + }; + + private static final VersionRange ONE = Versions.getVersionRange(Versions.getVersion(1, 0, 0), true, Versions.getVersion(2, 0, 0), + false); + + private static Platform platform(EventManager events, AttributeHandle handle) { + return (Platform) Proxy.newProxyInstance(Platform.class.getClassLoader(), new Class[]{ Platform.class }, + (proxy, method, args) -> switch(method.getName()) { + case "getEventManager" -> events; + case "getAttributeHandle" -> handle; + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + + private static ConfigPack pack(Map addons) { + Map, CheckedRegistry> registries = new HashMap<>(); + return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class[]{ ConfigPack.class }, + (proxy, method, args) -> switch(method.getName()) { + case "addons" -> addons; + case "getOrCreateRegistry" -> registries.computeIfAbsent((TypeKey) args[0], + type -> new CheckedRegistryImpl<>(new OpenRegistryImpl<>(type))); + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + + @Test + void dependentPacksOnly() { + EventManager events = new EventManagerImpl(); + AttributeHandle handle = new AttributeHandleImpl(); + MinecraftAttributesAddon initializer = new MinecraftAttributesAddon(); + Injector platformInjector = Injector.get(platform(events, handle)); + platformInjector.addExplicitTarget(Platform.class); + platformInjector.inject(initializer); + Injector addonInjector = Injector.get(ADDON); + addonInjector.addExplicitTarget(BaseAddon.class); + addonInjector.inject(initializer); + initializer.initialize(); + + ConfigPack dependent = pack(Map.of(ADDON, ONE)); + ConfigPack other = pack(Map.of()); + events.callEvent(new ConfigPackPreLoadEvent(dependent, template -> { })); + events.callEvent(new ConfigPackPreLoadEvent(other, template -> { })); + + CheckedRegistry> registered = dependent.getOrCreateRegistry(Attribute.REGISTRY_TYPE); + assertEquals(79, registered.entries().size()); + assertTrue(other.getOrCreateRegistry(Attribute.REGISTRY_TYPE).entries().isEmpty()); + Attribute fog = MinecraftAttributes.VISUAL_FOG_COLOR.lookup(registered).orElseThrow(); + assertSame(fog, registered.get(fog.getRegistryKey()).orElseThrow()); + + ConfigPack second = pack(Map.of(ADDON, ONE)); + events.callEvent(new ConfigPackPreLoadEvent(second, template -> { })); + assertSame(fog, MinecraftAttributes.VISUAL_FOG_COLOR.lookup(second.getOrCreateRegistry(Attribute.REGISTRY_TYPE)).orElseThrow()); + assertEquals(79, handle.attributeCount()); + } +} diff --git a/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesTest.java b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesTest.java new file mode 100644 index 000000000..d336dd70b --- /dev/null +++ b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftAttributesTest.java @@ -0,0 +1,194 @@ +package attribute.minecraft; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue; +import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTable; +import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes; +import com.dfsek.terra.api.registry.CheckedRegistry; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeScope; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.RawValue; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.registry.CheckedRegistryImpl; +import com.dfsek.terra.registry.OpenRegistryImpl; +import com.dfsek.terra.world.attribute.AttributeHandleImpl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class MinecraftAttributesTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final List> ALL = MinecraftAttributeTable.create(HANDLE); + private static final CheckedRegistry> REGISTRY = registry(); + + private static CheckedRegistry> registry() { + CheckedRegistry> registry = new CheckedRegistryImpl<>(new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE)); + ALL.forEach(attribute -> registry.register(attribute.getRegistryKey(), attribute)); + return registry; + } + + private static Attribute byId(String id) { + return REGISTRY.get(RegistryKey.parse(id)).orElseThrow(); + } + + @SuppressWarnings("unchecked") + private static Attribute typed(String id) { + return (Attribute) byId(id); + } + + @Test + void tableOrder() { + assertEquals(MinecraftAttributes.all(), ALL.stream().map(Attribute::key).toList()); + int first = ALL.get(0).index(); + for(int i = 0; i < ALL.size(); i++) { + assertEquals(first + i, ALL.get(i).index(), ALL.get(i).key().toString()); + assertSame(ALL.get(i), REGISTRY.get(ALL.get(i).getRegistryKey()).orElseThrow()); + } + assertTrue(HANDLE.attributeCount() >= first + ALL.size()); + } + + @Test + void scopes() { + Set packOnly = ALL.stream().filter(a -> a.key().getNamespace().equals("minecraft")) + .filter(a -> a.scope() == AttributeScope.PACK_ONLY).map(a -> a.key().toString()).collect(Collectors.toSet()); + assertEquals(Set.of("minecraft:gameplay/sky_light_level", "minecraft:gameplay/fast_lava"), packOnly); + for(Attribute a : ALL) { + if(!a.key().getNamespace().equals("terra")) continue; + boolean packWide = a.key().getID().startsWith("dimension/") || a.key().getID().startsWith("world/"); + assertEquals(packWide ? AttributeScope.PACK_ONLY : AttributeScope.ANYWHERE, a.scope(), a.key().toString()); + } + } + + @Test + void terraDefaults() { + assertNull(byId("terra:biome/foliage_color").defaultValue()); + assertNull(byId("terra:biome/dry_foliage_color").defaultValue()); + assertNull(byId("terra:biome/grass_color").defaultValue()); + assertEquals(Color.rgb(0x3f76e4), byId("terra:biome/water_color").defaultValue()); + assertEquals(-64, byId("terra:dimension/min_y").defaultValue()); + assertEquals(384, byId("terra:dimension/height").defaultValue()); + assertEquals(Either.right(TagKey.parse("#minecraft:infiniburn_overworld")), + byId("terra:dimension/infiniburn").defaultValue()); + assertEquals(RegistryKey.parse("minecraft:plains"), byId("terra:biome/villager_type").defaultValue()); + assertEquals(RegistryKey.parse("minecraft:overworld"), byId("terra:dimension/default_clock").defaultValue()); + IntProviderValue light = (IntProviderValue) byId("terra:dimension/monster_spawn_light_level").defaultValue(); + assertEquals(Optional.of(new RawValue(Map.of("type", "minecraft:uniform", "min_inclusive", 0, "max_inclusive", 7))), + light.provider()); + } + + @Test + void rangeValidation() throws Exception { + Attribute spawn = typed("minecraft:gameplay/creature_world_gen_spawn_probability"); + assertEquals(0.5f, spawn.validate(0.5f)); + assertThrows(DecodeException.class, () -> spawn.validate(1.0f)); + assertThrows(DecodeException.class, () -> spawn.validate(-0.1f)); + assertThrows(DecodeException.class, () -> spawn.validate(Float.NaN)); + + Attribute unit = typed("minecraft:audio/music_volume"); + assertEquals("value 2.0 is outside [0, 1]", assertThrows(DecodeException.class, () -> unit.validate(2f)).getMessage()); + + Attribute fogEnd = typed("minecraft:visual/fog_end_distance"); + assertThrows(DecodeException.class, () -> fogEnd.validate(-1f)); + assertEquals(1e9f, fogEnd.validate(1e9f)); + assertEquals(-5f, typed("minecraft:visual/fog_start_distance").validate(-5f)); + + Attribute scale = typed("terra:dimension/coordinate_scale"); + assertEquals(1f, scale.validate(1f)); + assertThrows(DecodeException.class, () -> scale.validate(0f)); + Attribute light = typed("terra:dimension/monster_spawn_block_light_limit"); + assertThrows(DecodeException.class, () -> light.validate(16)); + } + + @Test + void dimensionGeometry() throws Exception { + for(String id : List.of("terra:dimension/min_y", "terra:dimension/height", "terra:dimension/logical_height")) { + assertEquals(EnumSet.of(Operation.OVERRIDE), byId(id).type().operations(), id); + } + Attribute minY = typed("terra:dimension/min_y"); + assertEquals(-2032, minY.validate(-2032)); + assertThrows(DecodeException.class, () -> minY.validate(-2048)); + assertThrows(DecodeException.class, () -> minY.validate(2032)); + assertThrows(DecodeException.class, () -> minY.validate(-60)); + Attribute height = typed("terra:dimension/height"); + assertEquals(16, height.validate(16)); + assertThrows(DecodeException.class, () -> height.validate(0)); + assertEquals("value 100 is not a multiple of 16", assertThrows(DecodeException.class, () -> height.validate(100)).getMessage()); + assertEquals(37, typed("terra:dimension/logical_height").validate(37)); + } + + @Test + void sanitizeClamps() { + Attribute sky = typed("minecraft:gameplay/sky_light_level"); + assertEquals(15f, sky.sanitize(20f)); + assertEquals(0f, sky.sanitize(-3f)); + assertEquals(7f, sky.sanitize(7f)); + Attribute flag = typed("minecraft:gameplay/can_start_raid"); + assertEquals(true, flag.sanitize(true)); + Attribute height = typed("terra:dimension/height"); + assertEquals(4064, height.sanitize(9999)); + } + + @Test + void typedKeys() throws ReflectiveOperationException { + Set> constants = new HashSet<>(); + for(Field field : MinecraftAttributes.class.getFields()) { + if(!Modifier.isStatic(field.getModifiers()) || field.getType() != AttributeKey.class) continue; + AttributeKey key = (AttributeKey) field.get(null); + Type argument = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; + Class valueClass = (Class) (argument instanceof ParameterizedType p ? p.getRawType() : argument); + + Attribute attribute = key.lookup(REGISTRY).orElseThrow(() -> new AssertionError("Not registered: " + key)); + assertSame(key, attribute.key(), field.getName()); + Object defaultValue = attribute.defaultValue(); + if(defaultValue != null) { + assertTrue(valueClass.isInstance(defaultValue), + field.getName() + ": " + defaultValue.getClass() + " is not a " + valueClass); + } + constants.add(key); + } + assertEquals(79, constants.size()); + assertEquals(Set.copyOf(MinecraftAttributes.all()), constants); + assertEquals(79, ALL.size()); + } + + @Test + void typedLookup() { + AttributeKey lookalike = AttributeKey.parse("minecraft:visual/fog_color"); + assertEquals(MinecraftAttributes.VISUAL_FOG_COLOR, lookalike); + assertTrue(lookalike.lookup(REGISTRY).isEmpty()); + assertTrue(REGISTRY.get(lookalike.getRegistryKey()).isPresent()); + } + + @Test + void keyIds() { + for(AttributeKey key : MinecraftAttributes.all()) { + String namespace = key.getRegistryKey().getNamespace(); + String path = key.getRegistryKey().getID(); + assertTrue(namespace.matches("[a-z0-9_.-]+") && path.matches("[a-z0-9_./-]+"), key.toString()); + } + } +} diff --git a/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftCodecRoundTripTest.java b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftCodecRoundTripTest.java new file mode 100644 index 000000000..f51d895c0 --- /dev/null +++ b/common/addons/minecraft-attributes/src/test/java/attribute/minecraft/MinecraftCodecRoundTripTest.java @@ -0,0 +1,177 @@ +package attribute.minecraft; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalDouble; +import java.util.OptionalInt; + +import com.dfsek.terra.addons.attribute.minecraft.AmbientParticle; +import com.dfsek.terra.addons.attribute.minecraft.AmbientSounds; +import com.dfsek.terra.addons.attribute.minecraft.BackgroundMusic; +import com.dfsek.terra.addons.attribute.minecraft.BedRule; +import com.dfsek.terra.addons.attribute.minecraft.CardinalLight; +import com.dfsek.terra.addons.attribute.minecraft.GrassColorModifier; +import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue; +import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTypes; +import com.dfsek.terra.addons.attribute.minecraft.MobSpawnSettings; +import com.dfsek.terra.addons.attribute.minecraft.MoonPhase; +import com.dfsek.terra.addons.attribute.minecraft.Music; +import com.dfsek.terra.addons.attribute.minecraft.Skybox; +import com.dfsek.terra.addons.attribute.minecraft.SoundRef; +import com.dfsek.terra.addons.attribute.minecraft.TemperatureModifier; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.AttributeTypes; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.RawValue; +import com.dfsek.terra.world.attribute.AttributeHandleImpl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + + +class MinecraftCodecRoundTripTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final AttributeTypes CORE = HANDLE.types(); + private static final MinecraftAttributeTypes TYPES = new MinecraftAttributeTypes(HANDLE); + private static final DecodeContext PLAIN = HANDLE.plainContext(); + + private static final RawValue FLAME = new RawValue(map("type", "minecraft:flame")); + private static final RawValue UNIFORM = new RawValue(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3)); + private static final SoundRef SOUND = new SoundRef(RegistryKey.parse("minecraft:music.game"), OptionalDouble.empty()); + private static final SoundRef RANGED_SOUND = new SoundRef(RegistryKey.parse("minecraft:ambient.cave"), OptionalDouble.of(16)); + + private static Map map(Object... kv) { + Map m = new LinkedHashMap<>(); + for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]); + return m; + } + + private record Case(AttributeType type, List values, Map> arguments) { } + + private static Case of(AttributeType type, List values, Object... opArgs) { + Map> arguments = new LinkedHashMap<>(); + for(int i = 0; i < opArgs.length; i += 2) arguments.put((Operation) opArgs[i], (List) opArgs[i + 1]); + return new Case<>(type, values, arguments); + } + + private static List> cases() { + MobSpawnSettings spawns = new MobSpawnSettings( + Map.of("monster", List.of( + new MobSpawnSettings.Spawner(RegistryKey.parse("minecraft:zombie"), 95, + new IntProviderValue(OptionalInt.of(4), Optional.empty())), + new MobSpawnSettings.Spawner(RegistryKey.parse("minecraft:husk"), 5, + new IntProviderValue(OptionalInt.empty(), Optional.of(UNIFORM)))), + "ambient", List.of()), + Map.of(RegistryKey.parse("minecraft:enderman"), new MobSpawnSettings.Cost(0.7, 0.15))); + + return List.of( + of(TYPES.moonPhase(), List.of(MoonPhase.values())), + of(TYPES.bedRule(), List.of( + new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.NEVER, true, false, + Optional.of(new RawValue(map("translate", "block.minecraft.bed.no_sleep")))), + new BedRule(BedRule.Rule.ALWAYS, BedRule.Rule.ALWAYS, false, true, Optional.empty()))), + of(TYPES.particle(), List.of(FLAME, new RawValue(map("type", "minecraft:dust", "color", List.of(1.0, 0.5, 0.0), "scale", 2)))), + of(TYPES.ambientParticles(), List.of(List.of(), List.of(new AmbientParticle(FLAME, 0.025f))), + Operation.APPEND, List.of(List.of(new AmbientParticle(FLAME, 0.5f), new AmbientParticle(FLAME, 1f)))), + of(TYPES.backgroundMusic(), List.of(BackgroundMusic.EMPTY, + new BackgroundMusic(Optional.of(new Music(SOUND, 12000, 24000, true)), Optional.empty(), + Optional.of(new Music(RANGED_SOUND, 0, 1, false))))), + of(TYPES.ambientSounds(), List.of(AmbientSounds.EMPTY, + new AmbientSounds(Optional.of(RANGED_SOUND), Optional.of(new AmbientSounds.Mood(SOUND, 6000, 8, 2.0)), + List.of(new AmbientSounds.Additions(SOUND, 0.0111), new AmbientSounds.Additions(RANGED_SOUND, 0.5))))), + of(TYPES.mobSpawnSettings(), List.of(MobSpawnSettings.EMPTY, spawns), + Operation.OVERLAY, List.of(MobSpawnSettings.EMPTY, spawns)), + of(TYPES.identifier(), List.of(RegistryKey.parse("minecraft:stone"), RegistryKey.parse("my.pack:a/b"))), + of(TYPES.identifierOrTag(), List.>of( + Either.left(RegistryKey.parse("minecraft:stone")), Either.right(TagKey.parse("#my.pack:logs")))), + of(TYPES.intProvider(), List.of(new IntProviderValue(OptionalInt.of(-4), Optional.empty()), + new IntProviderValue(OptionalInt.empty(), Optional.of(UNIFORM)))), + of(CORE.enumType("skybox", Skybox.class), List.of(Skybox.values())), + of(CORE.enumType("cardinal_light", CardinalLight.class), List.of(CardinalLight.values())), + of(CORE.enumType("grass_color_modifier", GrassColorModifier.class), List.of(GrassColorModifier.values())), + of(CORE.enumType("temperature_modifier", TemperatureModifier.class), List.of(TemperatureModifier.values()))); + } + + private static void assertPlain(Object encoded, String where) { + if(encoded == null || encoded instanceof Number || encoded instanceof Boolean || encoded instanceof String) return; + if(encoded instanceof List list) { + for(Object element : list) assertPlain(element, where); + return; + } + if(encoded instanceof Map m) { + m.forEach((k, v) -> { + assertTrue(k instanceof String, where + ": map key " + k + " is not a string"); + assertPlain(v, where); + }); + return; + } + fail(where + ": encoded a " + encoded.getClass().getName() + ": " + encoded); + } + + private static void assertValuesRoundTrip(Case c) throws DecodeException { + for(T value : c.values()) { + Object encoded = c.type().encode(value); + assertPlain(encoded, c.type().id()); + assertEquals(value, c.type().decode(encoded, PLAIN), c.type().id() + " via " + encoded); + } + } + + @Test + void everyMinecraftType() throws DecodeException { + for(Case c : cases()) assertValuesRoundTrip(c); + } + + @Test + void everyArgument() throws DecodeException { + for(Case c : cases()) { + AttributeType type = c.type(); + List unsampled = new ArrayList<>(type.operations()); + unsampled.remove(Operation.OVERRIDE); + unsampled.removeAll(c.arguments().keySet()); + assertTrue(unsampled.isEmpty(), type.id() + " has no sample argument for " + unsampled); + + Map> arguments = new LinkedHashMap<>(c.arguments()); + arguments.put(Operation.OVERRIDE, c.values()); + for(Map.Entry> e : arguments.entrySet()) { + for(Object argument : e.getValue()) { + Object encoded = type.encodeArgument(e.getKey(), argument); + assertPlain(encoded, type.id() + " " + e.getKey().getID()); + assertEquals(argument, type.decodeArgument(e.getKey(), encoded, PLAIN), + type.id() + " " + e.getKey().getID() + " via " + encoded); + } + } + } + } + + @Test + void canonicalForms() { + assertEquals("minecraft:stone", TYPES.identifier().encode(RegistryKey.parse("minecraft:stone"))); + assertEquals("#minecraft:logs", TYPES.identifierOrTag().encode(Either.right(TagKey.parse("#minecraft:logs")))); + assertEquals("minecraft:stone", TYPES.identifierOrTag().encode(Either.left(RegistryKey.parse("minecraft:stone")))); + assertEquals("new_moon", TYPES.moonPhase().encode(MoonPhase.NEW_MOON)); + assertEquals("end", CORE.enumType("skybox", Skybox.class).encode(Skybox.END)); + assertEquals(map("type", "minecraft:flame"), TYPES.particle().encode(FLAME)); + assertEquals(7, TYPES.intProvider().encode(new IntProviderValue(OptionalInt.of(7), Optional.empty()))); + Map plainLoop = (Map) TYPES.ambientSounds().encode(new AmbientSounds(Optional.of(SOUND), Optional.empty(), List.of())); + assertEquals("minecraft:music.game", plainLoop.get("loop")); + Map rangedLoop = (Map) TYPES.ambientSounds().encode( + new AmbientSounds(Optional.of(RANGED_SOUND), Optional.empty(), List.of())); + assertEquals(map("sound_id", "minecraft:ambient.cave", "range", 16.0), rangedLoop.get("loop")); + Map bedRule = (Map) TYPES.bedRule().encode( + new BedRule(BedRule.Rule.NEVER, BedRule.Rule.NEVER, false, false, Optional.empty())); + assertFalse(bedRule.containsKey("error_message")); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/Platform.java b/common/api/src/main/java/com/dfsek/terra/api/Platform.java index 217b4dd69..5bda18bb4 100644 --- a/common/api/src/main/java/com/dfsek/terra/api/Platform.java +++ b/common/api/src/main/java/com/dfsek/terra/api/Platform.java @@ -23,6 +23,8 @@ import com.dfsek.terra.api.profiler.Profiler; import com.dfsek.terra.api.registry.CheckedRegistry; import com.dfsek.terra.api.registry.Registry; import com.dfsek.terra.api.tectonic.LoaderRegistrar; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeParents; /** @@ -89,4 +91,17 @@ public interface Platform extends LoaderRegistrar { @Contract(pure = true) int getGenerationThreads(); + + @NotNull + @Contract(pure = true) + AttributeHandle getAttributeHandle(); + + /** + * Each pack reads these once, when it loads. + */ + @NotNull + @Contract(pure = true) + default AttributeParents getAttributeParents() { + return AttributeParents.NONE; + } } diff --git a/common/api/src/main/java/com/dfsek/terra/api/properties/Context.java b/common/api/src/main/java/com/dfsek/terra/api/properties/Context.java index c8f5d807f..4643d3115 100644 --- a/common/api/src/main/java/com/dfsek/terra/api/properties/Context.java +++ b/common/api/src/main/java/com/dfsek/terra/api/properties/Context.java @@ -52,6 +52,14 @@ public class Context { return (T) list[key.key]; } + /** + * Unlike {@link #get(PropertyKey)}, safe for keys created after this context last stored a value. + */ + public boolean has(PropertyKey key) { + Properties[] current = list; + return key.key < current.length && current[key.key] != null; + } + public boolean has(Class test) { return map.containsKey(test); } diff --git a/common/api/src/main/java/com/dfsek/terra/api/registry/key/RegistryKey.java b/common/api/src/main/java/com/dfsek/terra/api/registry/key/RegistryKey.java index ebcf4b0a4..64262f515 100644 --- a/common/api/src/main/java/com/dfsek/terra/api/registry/key/RegistryKey.java +++ b/common/api/src/main/java/com/dfsek/terra/api/registry/key/RegistryKey.java @@ -1,29 +1,31 @@ package com.dfsek.terra.api.registry.key; -import java.util.Objects; import java.util.regex.Pattern; public final class RegistryKey implements StringIdentifiable, Namespaced { - private static final Pattern ID_PATTERN = Pattern.compile("^[a-zA-Z0-9_-]*$"); + private static final Pattern NAMESPACE_PATTERN = Pattern.compile("^[a-zA-Z0-9_.-]*$"); + private static final Pattern ID_PATTERN = Pattern.compile("^[a-zA-Z0-9_./-]*$"); private final String namespace; private final String id; + private final int hash; private RegistryKey(String namespace, String id) { - if(!ID_PATTERN.matcher(namespace).matches()) { + if(!NAMESPACE_PATTERN.matcher(namespace).matches()) { throw new IllegalArgumentException( - "Namespace must only contain alphanumeric characters, hyphens, and underscores. \"" + namespace + + "Namespace must only contain alphanumeric characters, hyphens, underscores, and periods. \"" + namespace + "\" is not a valid namespace."); } if(!ID_PATTERN.matcher(id).matches()) { throw new IllegalArgumentException( - "ID must only contain alphanumeric characters, hyphens, and underscores. \"" + id + + "ID must only contain alphanumeric characters, hyphens, underscores, periods, and slashes. \"" + id + "\" is not a valid ID."); } this.namespace = namespace; this.id = id; + this.hash = 31 * (31 + namespace.hashCode()) + id.hashCode(); } public static RegistryKey parse(String key) { @@ -36,6 +38,37 @@ public final class RegistryKey implements StringIdentifiable, Namespaced { return new RegistryKey(namespace, id); } + /** + * Parses {@code namespace:id}, or {@code id} in {@code defaultNamespace}. + * + * @throws IllegalArgumentException if a part is empty or invalid, or the key holds more than one {@code :} + */ + public static RegistryKey parse(String key, String defaultNamespace) { + // Shown to users in config warnings: no Java type names. + if(key == null) throw new IllegalArgumentException("malformed ID: none given"); + int colon = key.indexOf(':'); + if(colon != key.lastIndexOf(':')) throw new IllegalArgumentException(malformed(key, "more than one ':'")); + String namespace = colon < 0 ? defaultNamespace : key.substring(0, colon); + String id = key.substring(colon + 1); + if(namespace == null || namespace.isEmpty()) throw new IllegalArgumentException(malformed(key, "empty namespace")); + if(id.isEmpty()) throw new IllegalArgumentException(malformed(key, "empty ID")); + return new RegistryKey(namespace, id); + } + + private static String malformed(String key, String reason) { + return "malformed ID \"" + key + "\": " + reason; + } + + /** + * @throws IllegalArgumentException if the key has no namespace or is otherwise invalid + */ + public static RegistryKey parseNamespaced(String key) { + if(key != null && key.indexOf(':') < 0) { + throw new IllegalArgumentException("a namespace is required, as in \"namespace:" + key + "\""); + } + return parse(key, ""); + } + public static RegistryKey of(String namespace, String id) { return new RegistryKey(namespace, id); } @@ -52,13 +85,14 @@ public final class RegistryKey implements StringIdentifiable, Namespaced { @Override public int hashCode() { - return Objects.hash(namespace, id); + return hash; } @Override public boolean equals(Object obj) { + if(this == obj) return true; if(obj instanceof RegistryKey that) { - return this.id.equals(that.id) && this.namespace.equals(that.namespace); + return this.hash == that.hash && this.id.equals(that.id) && this.namespace.equals(that.namespace); } return false; } diff --git a/common/api/src/main/java/com/dfsek/terra/api/registry/key/TagKey.java b/common/api/src/main/java/com/dfsek/terra/api/registry/key/TagKey.java new file mode 100644 index 000000000..1b09e52ae --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/registry/key/TagKey.java @@ -0,0 +1,63 @@ +package com.dfsek.terra.api.registry.key; + +public final class TagKey { + private final RegistryKey key; + + private TagKey(RegistryKey key) { + this.key = key; + } + + public static TagKey of(RegistryKey key) { + return new TagKey(key); + } + + /** + * @throws IllegalArgumentException if the string does not start with {@code #}, has no namespace, or is not a valid + * {@link RegistryKey} + */ + public static TagKey parse(String tag) { + String body = body(tag); + try { + return new TagKey(RegistryKey.parseNamespaced(body)); + } catch(IllegalArgumentException e) { + if(body.indexOf(':') < 0) { + throw new IllegalArgumentException( + "invalid tag \"" + tag + "\": a namespace is required, as in \"#namespace:" + body + "\"", e); + } + throw e; + } + } + + /** + * Parses {@code #namespace:id}, or {@code #id} in {@code defaultNamespace}. + * + * @throws IllegalArgumentException if the string does not start with {@code #} or is not a valid {@link RegistryKey} + */ + public static TagKey parse(String tag, String defaultNamespace) { + return new TagKey(RegistryKey.parse(body(tag), defaultNamespace)); + } + + private static String body(String tag) { + if(tag == null || !tag.startsWith("#")) throw new IllegalArgumentException("invalid tag (expected #namespace:id): \"" + tag + "\""); + return tag.substring(1); + } + + public RegistryKey key() { + return key; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof TagKey that && key.equals(that.key); + } + + @Override + public int hashCode() { + return key.hashCode(); + } + + @Override + public String toString() { + return "#" + key; + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/Attribute.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/Attribute.java new file mode 100644 index 000000000..3a114bcf6 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/Attribute.java @@ -0,0 +1,63 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; + +import com.dfsek.terra.api.registry.key.Keyed; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.util.reflection.TypeKey; + + +/** + * Build each attribute once and register the same instance in every pack: every build takes a new {@link #index()}. + */ +public interface Attribute extends Keyed> { + TypeKey> REGISTRY_TYPE = new TypeKey<>() { }; + + AttributeKey key(); + + AttributeType type(); + + /** + * {@code null} means no override. + */ + @Nullable + T defaultValue(); + + AttributeScope scope(); + + /** + * @throws DecodeException if the value is outside this attribute's range or not a required multiple + */ + T validate(T value) throws DecodeException; + + /** + * Clamps numeric values to this attribute's range; returns other values unchanged. + */ + T sanitize(T value); + + /** + * Dense, from 0, below {@link AttributeHandle#attributeCount()}. + */ + @ApiStatus.Internal + int index(); + + @Override + default RegistryKey getRegistryKey() { + return key().getRegistryKey(); + } + + + interface Builder { + /** + * Values must lie in {@code [min, max]}; resolved values are clamped to it. + */ + Builder range(Number min, Number max); + + Builder multipleOf(int multipleOf); + + Builder packOnly(); + + Attribute build(); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodec.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodec.java new file mode 100644 index 000000000..88fc7b898 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodec.java @@ -0,0 +1,14 @@ +package com.dfsek.terra.api.world.attribute; + +public interface AttributeCodec { + /** + * @param raw a number, string, boolean, list, string-keyed map, or {@code null} + */ + T decode(Object raw, DecodeContext context) throws DecodeException; + + /** + * Returns a number, boolean, string, list or string-keyed map of those, or {@code null}. {@link #decode} must read it + * back to an equal value. + */ + Object encode(T value); +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodecs.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodecs.java new file mode 100644 index 000000000..de18a0b8d --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeCodecs.java @@ -0,0 +1,127 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.StringIdentifiable; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; + + +public interface AttributeCodecs { + @FunctionalInterface + interface Decoder { + T decode(Object raw, DecodeContext context) throws DecodeException; + } + + + @FunctionalInterface + interface Encoder { + Object encode(T value); + } + + + /** + * Not thread safe. + */ + interface ObjectReader { + /** + * In config order. + */ + List keys(); + + /** + * @throws DecodeException if the key is missing or its value does not decode + */ + V required(String key, AttributeCodec codec) throws DecodeException; + + Optional optional(String key, AttributeCodec codec) throws DecodeException; + + V orDefault(String key, AttributeCodec codec, V fallback) throws DecodeException; + + /** + * @throws DecodeException if the object has a key that was not read + */ + void finish() throws DecodeException; + } + + + /** + * Not thread safe. Keeps fields in the order written. + */ + interface ObjectWriter { + ObjectWriter put(String key, AttributeCodec codec, V value); + + ObjectWriter optional(String key, AttributeCodec codec, Optional value); + + Map map(); + } + + AttributeCodec of(Decoder decoder, Encoder encoder); + + /** + * Names {@code value} for messages, such as {@code "text"}, {@code an object} or {@code nothing}. + */ + String describe(@Nullable Object value); + + AttributeCodec booleanCodec(); + + AttributeCodec floatCodec(); + + AttributeCodec doubleCodec(); + + /** + * Rejects fractions and values outside the {@code int} range. + */ + AttributeCodec intCodec(); + + AttributeCodec nonNegativeInt(); + + AttributeCodec unitFloat(); + + /** + * @param expected the start of the message when the value is not a string, as in {@code expected a sound ID} + */ + AttributeCodec string(String expected); + + AttributeCodec raw(); + + AttributeCodec> list(AttributeCodec element); + + /** + * Also reads a single element as a list of one. Always encodes a list. + */ + AttributeCodec> compactList(AttributeCodec element); + + /** + * Reads constants by {@link StringIdentifiable#getID() ID}. + * + * @param name names the enum in messages, such as {@code moon phase} + * + * @throws IllegalArgumentException if two constants share an ID + */ + & StringIdentifiable> AttributeCodec enumCodec(String name, Class type); + + /** + * A bare ID takes {@code defaultNamespace}. Tags are rejected. + */ + AttributeCodec identifier(String defaultNamespace); + + /** + * A bare ID takes {@code defaultNamespace}. + */ + AttributeCodec> identifierOrTag(String defaultNamespace); + + /** + * @param what names the object in messages, such as {@code music} + * + * @throws DecodeException if {@code raw} is not an object, or has a key that is not a string + */ + ObjectReader reader(String what, Object raw, DecodeContext context) throws DecodeException; + + ObjectWriter writer(); +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeEntry.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeEntry.java new file mode 100644 index 000000000..65a6cf740 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeEntry.java @@ -0,0 +1,43 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; + + +public record AttributeEntry(@NotNull Operation operation, @Nullable Object argument) { + /** + * @throws IllegalArgumentException if {@code argument} is {@code null} and {@code operation} is not {@link Operation#OVERRIDE} + */ + public AttributeEntry { + Objects.requireNonNull(operation, "operation"); + if(argument == null && operation != Operation.OVERRIDE) { + throw new IllegalArgumentException("modifier " + operation.getID() + " needs an argument"); + } + } + + @NotNull + @Contract("_ -> new") + public static AttributeEntry override(@Nullable T value) { + return new AttributeEntry<>(Operation.OVERRIDE, value); + } + + /** + * @throws IllegalArgumentException if {@code argument} is {@code null} and {@code op} is not {@link Operation#OVERRIDE} + */ + @NotNull + @Contract("_, _ -> new") + public static AttributeEntry of(@NotNull Operation op, @Nullable Object argument) { + return new AttributeEntry<>(op, argument); + } + + public T apply(@NotNull AttributeType type, T subject) { + return type.apply(operation, subject, argument); + } + + public boolean isOverride() { + return operation == Operation.OVERRIDE; + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeHandle.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeHandle.java new file mode 100644 index 000000000..fc20d02fc --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeHandle.java @@ -0,0 +1,110 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.Optional; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult; + + +public interface AttributeHandle { + @NotNull + @Contract(pure = true) + AttributeTypes types(); + + /** + * Applies no config preprocessing. + */ + @NotNull + @Contract(pure = true) + DecodeContext plainContext(); + + @NotNull + @Contract(pure = true) + AttributeCodecs codecs(); + + @NotNull + @Contract("_, _ -> new") + AttributeType.Builder typeBuilder(@NotNull String id, @NotNull AttributeCodec codec); + + @NotNull + @Contract("_, _, _ -> new") + Attribute.Builder attributeBuilder(@NotNull AttributeKey key, @NotNull AttributeType type, @Nullable T defaultValue); + + /** + * Only grows. Every {@link Attribute#index()} is below it. + */ + @ApiStatus.Internal + int attributeCount(); + + /** + * Applies each non-null layer, bottom first, to the default, then sanitizes. A {@code null} value only changes on an override. + */ + @SuppressWarnings("unchecked") + @Contract(pure = true) + @Nullable T resolve(@NotNull Attribute attribute, AttributeEntry... layersBottomToTop); + + /** + * Allocation-free {@link #resolve(Attribute, AttributeEntry[])}, bottom layer first. + */ + @Contract(pure = true) + @Nullable T resolve(@NotNull Attribute attribute, @Nullable AttributeEntry first, @Nullable AttributeEntry second, + @Nullable AttributeEntry third); + + /** + * Allocation-free {@link #resolve(Attribute, AttributeEntry[])}, bottom layer first. + */ + @Contract(pure = true) + @Nullable T resolve(@NotNull Attribute attribute, @Nullable AttributeEntry first, @Nullable AttributeEntry second, + @Nullable AttributeEntry third, @Nullable AttributeEntry fourth); + + /** + * Composes two layers into one entry that applies like {@code lower} then {@code upper}. Empty when both are {@code null} + * or they don't compose; fall back to an override of the {@link #resolve resolved} value. Float results may differ by rounding. + */ + @NotNull + @Contract(pure = true) + Optional> compose(@NotNull Attribute attribute, @Nullable AttributeEntry lower, + @Nullable AttributeEntry upper); + + /** + * Reads a bare value as an override, or a {@code modifier} and {@code argument} map. Resolves {@code raw} first. + */ + @NotNull + AttributeEntry decodeEntry(@NotNull Attribute attribute, @Nullable Object raw, @NotNull DecodeContext context) + throws DecodeException; + + /** + * @throws IllegalArgumentException if {@code entry} is an override of {@code null} + */ + @NotNull + @Contract(pure = true) + Object encodeEntry(@NotNull Attribute attribute, @NotNull AttributeEntry entry); + + /** + * {@code raw} must already be {@link DecodeContext#resolve resolved}. A bad track is dropped; other problems skip the schedule. + */ + @NotNull + ScheduleDecodeResult decodeSchedule(@NotNull RegistryKey id, @NotNull Map raw, @NotNull AttributeLookup attributes, + @NotNull DecodeContext context); + + /** + * @throws IllegalArgumentException if a keyframe's argument is {@code null} + */ + @NotNull + @Contract(pure = true) + Map encodeSchedule(@NotNull AttributeSchedule schedule); + + /** + * Empty unless the {@code config-attributes} addon loaded {@code pack}. + */ + @NotNull + Optional pack(@NotNull ConfigPack pack); +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeKey.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeKey.java new file mode 100644 index 000000000..e79bc04b1 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeKey.java @@ -0,0 +1,71 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; + +import com.dfsek.terra.api.registry.Registry; +import com.dfsek.terra.api.registry.key.Keyed; +import com.dfsek.terra.api.registry.key.RegistryKey; + + +public final class AttributeKey implements Keyed> { + private final RegistryKey key; + + private AttributeKey(RegistryKey key) { + this.key = key; + } + + @NotNull + public static AttributeKey of(@NotNull RegistryKey key) { + return new AttributeKey<>(key); + } + + /** + * {@code T} is unchecked: {@link #lookup} returns empty for a key made here. + * + * @throws IllegalArgumentException if the key has no namespace or is not a valid {@link RegistryKey} + */ + @NotNull + public static AttributeKey parse(@NotNull String key) { + if(key == null) throw new IllegalArgumentException("invalid attribute key: null"); + try { + return new AttributeKey<>(RegistryKey.parseNamespaced(key)); + } catch(IllegalArgumentException e) { + if(key.indexOf(':') < 0) throw new IllegalArgumentException("invalid attribute key \"" + key + "\": " + e.getMessage(), e); + throw new IllegalArgumentException("invalid attribute key: \"" + key + "\"", e); + } + } + + /** + * Empty unless the registered attribute's {@link Attribute#key()} is this instance. + */ + @SuppressWarnings("unchecked") + @NotNull + public Optional> lookup(@NotNull Registry> registry) { + Optional> attribute = registry.get(key); + if(attribute.isEmpty() || attribute.get().key() != this) return Optional.empty(); + return Optional.of((Attribute) attribute.get()); + } + + @Override + public RegistryKey getRegistryKey() { + return key; + } + + @Override + public boolean equals(Object obj) { + if(this == obj) return true; + return obj instanceof AttributeKey that && key.equals(that.key); + } + + @Override + public int hashCode() { + return key.hashCode(); + } + + @Override + public String toString() { + return key.toString(); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeLookup.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeLookup.java new file mode 100644 index 000000000..d18cde027 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeLookup.java @@ -0,0 +1,9 @@ +package com.dfsek.terra.api.world.attribute; + +@FunctionalInterface +public interface AttributeLookup { + /** + * @throws DecodeException if {@code key} names no usable attribute; the message is reported as the reason + */ + Attribute find(String key) throws DecodeException; +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeMap.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeMap.java new file mode 100644 index 000000000..820f7e355 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeMap.java @@ -0,0 +1,103 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + + +public final class AttributeMap { + private static final AttributeMap EMPTY = new AttributeMap(Map.of()); + + private final Map, AttributeEntry> entries; + + private AttributeMap(Map, AttributeEntry> entries) { + this.entries = entries; + } + + @NotNull + @Contract(pure = true) + public static AttributeMap empty() { + return EMPTY; + } + + @NotNull + @Contract("-> new") + public static Builder builder() { + return new Builder(); + } + + @NotNull + @SuppressWarnings("unchecked") + public Optional> get(@NotNull AttributeKey key) { + return Optional.ofNullable((AttributeEntry) entries.get(key)); + } + + /** + * In insertion order. Unmodifiable. + */ + @NotNull + public Set> keys() { + return entries.keySet(); + } + + public boolean isEmpty() { + return entries.isEmpty(); + } + + /** + * {@code top}'s entries replace this map's per key. + */ + @NotNull + public AttributeMap overlay(@NotNull AttributeMap top) { + Objects.requireNonNull(top, "top"); + if(top.entries.isEmpty()) return this; + if(entries.isEmpty()) return top; + Map, AttributeEntry> merged = new LinkedHashMap<>(entries); + merged.putAll(top.entries); + return new AttributeMap(Collections.unmodifiableMap(merged)); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof AttributeMap that && entries.equals(that.entries); + } + + @Override + public int hashCode() { + return entries.hashCode(); + } + + @Override + public String toString() { + return "AttributeMap" + entries; + } + + + public static final class Builder { + private final Map, AttributeEntry> entries = new LinkedHashMap<>(); + + private Builder() { + } + + public Builder put(AttributeKey key, AttributeEntry entry) { + entries.put(Objects.requireNonNull(key, "key"), Objects.requireNonNull(entry, "entry")); + return this; + } + + public Builder remove(AttributeKey key) { + entries.remove(key); + return this; + } + + public AttributeMap build() { + if(entries.isEmpty()) return EMPTY; + return new AttributeMap(Collections.unmodifiableMap(new LinkedHashMap<>(entries))); + } + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeModifier.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeModifier.java new file mode 100644 index 000000000..a56e6d6ad --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeModifier.java @@ -0,0 +1,6 @@ +package com.dfsek.terra.api.world.attribute; + +@FunctionalInterface +public interface AttributeModifier { + T apply(T subject, A argument); +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeParents.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeParents.java new file mode 100644 index 000000000..fd2bb50aa --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeParents.java @@ -0,0 +1,33 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.Nullable; + +import com.dfsek.terra.api.world.biome.Biome; + + +/** + * Called on read paths: must not allocate. + */ +public interface AttributeParents { + AttributeParents NONE = new AttributeParents() { + @Override + public @Nullable AttributeEntry biomeOrNull(Biome biome, Attribute attribute) { + return null; + } + + @Override + public @Nullable AttributeEntry packOrNull(PackAttributes pack, Attribute attribute) { + return null; + } + }; + + /** + * Sits between the pack entry and the biome's own entry. + */ + @Nullable AttributeEntry biomeOrNull(Biome biome, Attribute attribute); + + /** + * Sits between the attribute's default and the pack entry. + */ + @Nullable AttributeEntry packOrNull(PackAttributes pack, Attribute attribute); +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeScope.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeScope.java new file mode 100644 index 000000000..46d97a72e --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeScope.java @@ -0,0 +1,6 @@ +package com.dfsek.terra.api.world.attribute; + +public enum AttributeScope { + ANYWHERE, + PACK_ONLY +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeType.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeType.java new file mode 100644 index 000000000..99204bea5 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeType.java @@ -0,0 +1,61 @@ +package com.dfsek.terra.api.world.attribute; + +import java.util.Optional; +import java.util.Set; +import java.util.function.BinaryOperator; + + +public interface AttributeType { + String id(); + + /** + * Always includes {@link Operation#OVERRIDE}. Unmodifiable. + */ + Set operations(); + + T decode(Object raw, DecodeContext context) throws DecodeException; + + Object encode(T value); + + /** + * @throws DecodeException if {@code op} is not valid for this type, or the argument does not decode + */ + Object decodeArgument(Operation op, Object raw, DecodeContext context) throws DecodeException; + + /** + * @throws IllegalArgumentException if {@code op} is not valid for this type + */ + Object encodeArgument(Operation op, Object argument); + + /** + * @throws IllegalArgumentException if {@code op} is not valid for this type + */ + T apply(Operation op, T subject, Object argument); + + /** + * @return empty when the type has no composer for {@code op} + * + * @throws NullPointerException if the composer returns {@code null} + */ + Optional compose(Operation op, Object lower, Object upper); + + + interface Builder { + /** + * Replaces an earlier {@code op} and drops its composer. + * + * @throws IllegalArgumentException if {@code op} is {@link Operation#OVERRIDE} + */ + Builder op(Operation op, AttributeCodec argumentCodec, AttributeModifier modifier); + + /** + * {@code combine(lower, upper)} must apply like {@code lower} then {@code upper}. {@code A} must be the argument type + * {@code op} was added with. + * + * @throws IllegalArgumentException if {@code op} is {@link Operation#OVERRIDE} or was not added first + */ + Builder composable(Operation op, BinaryOperator combine); + + AttributeType build(); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeTypes.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeTypes.java new file mode 100644 index 000000000..f9fd2f693 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/AttributeTypes.java @@ -0,0 +1,68 @@ +package com.dfsek.terra.api.world.attribute; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.StringIdentifiable; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.api.world.attribute.value.TriState; + + +public interface AttributeTypes { + /** + * {@code and}, {@code nand}, {@code or}, {@code nor}, {@code xor}, {@code xnor}. + */ + AttributeType booleanType(); + + /** + * Override only. + */ + AttributeType triState(); + + /** + * {@code alpha_blend}, {@code add}, {@code subtract}, {@code multiply}, {@code minimum}, {@code maximum}. + */ + AttributeType floatType(); + + /** + * The {@link #floatType()} library. + */ + AttributeType angleDegrees(); + + /** + * {@code alpha_blend}, {@code add}, {@code subtract}, {@code multiply}, {@code blend_to_gray}. + */ + AttributeType rgbColor(); + + /** + * {@code alpha_blend}, {@code add}, {@code subtract}, {@code multiply}, {@code blend_to_gray}. + */ + AttributeType argbColor(); + + /** + * {@code add}, {@code subtract}, {@code multiply}, {@code minimum}, {@code maximum}. + */ + AttributeType integer(); + + /** + * Override only. + */ + AttributeType integerOverrideOnly(); + + /** + * Any ID; a bare ID takes {@code defaultNamespace}. Tags are rejected. Override only. + */ + AttributeType identifier(String defaultNamespace); + + /** + * An ID or a {@code #tag}; a bare ID takes {@code defaultNamespace}. Override only. + */ + AttributeType> identifierOrTag(String defaultNamespace); + + /** + * An enum identified by its {@link StringIdentifiable#getID() ID}. Override only. + * + * @param type its constants' IDs must be distinct + */ + & StringIdentifiable> AttributeType enumType(String id, Class type); +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeContext.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeContext.java new file mode 100644 index 000000000..4446b4ff5 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeContext.java @@ -0,0 +1,17 @@ +package com.dfsek.terra.api.world.attribute; + +import java.lang.reflect.Type; + + +public interface DecodeContext { + /** + * {@code type} is {@code Float}, {@code Integer}, {@code Double}, {@code Boolean}, {@code String}, {@code List}, + * {@code Map} or {@code Object}. + */ + V load(Type type, Object raw) throws DecodeException; + + /** + * Call before checking a value's shape. Numeric expressions stay strings; {@link #load} evaluates them. + */ + Object resolve(Object raw) throws DecodeException; +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeException.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeException.java new file mode 100644 index 000000000..06af170cb --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/DecodeException.java @@ -0,0 +1,14 @@ +package com.dfsek.terra.api.world.attribute; + +/** + * The message is shown to users in config warnings. + */ +public class DecodeException extends Exception { + public DecodeException(String message) { + super(message); + } + + public DecodeException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/Operation.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/Operation.java new file mode 100644 index 000000000..91e557ee8 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/Operation.java @@ -0,0 +1,44 @@ +package com.dfsek.terra.api.world.attribute; + +import com.dfsek.terra.api.registry.key.StringIdentifiable; + + +public enum Operation implements StringIdentifiable { + OVERRIDE("override"), + ALPHA_BLEND("alpha_blend"), + ADD("add"), + SUBTRACT("subtract"), + MULTIPLY("multiply"), + BLEND_TO_GRAY("blend_to_gray"), + MINIMUM("minimum"), + MAXIMUM("maximum"), + AND("and"), + NAND("nand"), + OR("or"), + NOR("nor"), + XOR("xor"), + XNOR("xnor"), + APPEND("append"), + OVERLAY("overlay"); + + private final String id; + + Operation(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } + + /** + * @throws IllegalArgumentException if no operation has this {@link #getID() ID} + */ + public static Operation parse(String name) { + for(Operation value : values()) { + if(value.id.equals(name)) return value; + } + throw new IllegalArgumentException("unknown modifier \"" + name + "\""); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/PackAttributes.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/PackAttributes.java new file mode 100644 index 000000000..a22882288 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/PackAttributes.java @@ -0,0 +1,64 @@ +package com.dfsek.terra.api.world.attribute; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.properties.Properties; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule; +import com.dfsek.terra.api.world.biome.Biome; + + +/** + * Reads resolve the static layers only; schedules are not applied. + */ +public interface PackAttributes extends Properties { + @NotNull + AttributeMap entries(); + + /** + * By config key, in config order. Unmodifiable. + */ + @NotNull + Map parents(); + + /** + * In config order. + */ + @NotNull + List> scheduleRefs(); + + /** + * By ID, in config order. Unmodifiable. + */ + @NotNull + Map scheduleDefinitions(); + + /** + * {@code null} if the biome is not from this pack. Allocation-free. + */ + @Nullable + AttributeEntry biomeEntryOrNull(@NotNull Attribute attribute, @NotNull Biome biome); + + /** + * Merged across the biome's {@code extends} chain. Empty if the biome is not from this pack. + */ + @NotNull + AttributeMap biomeEntries(@NotNull Biome biome); + + /** + * Layers, bottom first: default, {@link AttributeParents#packOrNull pack parent}, pack entry, + * {@link AttributeParents#biomeOrNull biome parent}, biome entry. + */ + @Nullable T resolve(@NotNull Attribute attribute, @NotNull Biome biome); + + /** + * Layers, bottom first: default, {@link AttributeParents#packOrNull pack parent}, pack entry. + */ + @Nullable T resolvePack(@NotNull Attribute attribute); +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/RawValue.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/RawValue.java new file mode 100644 index 000000000..ad45ce155 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/RawValue.java @@ -0,0 +1,34 @@ +package com.dfsek.terra.api.world.attribute; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + + +public record RawValue(Object value) { + public RawValue { + value = copy(value); + } + + private static Object copy(Object o) { + if(o == null || o instanceof String || o instanceof Number || o instanceof Boolean) return o; + if(o instanceof List list) { + List out = new ArrayList<>(list.size()); + for(Object e : list) out.add(copy(e)); + return Collections.unmodifiableList(out); + } + if(o instanceof Map map) { + Map out = new LinkedHashMap<>(); + for(Map.Entry e : map.entrySet()) { + if(!(e.getKey() instanceof String key)) { + throw new IllegalArgumentException("unsupported value: map keys must be strings"); + } + out.put(key, copy(e.getValue())); + } + return Collections.unmodifiableMap(out); + } + throw new IllegalArgumentException("unsupported value"); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/AttributeSchedule.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/AttributeSchedule.java new file mode 100644 index 000000000..d37c81276 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/AttributeSchedule.java @@ -0,0 +1,21 @@ +package com.dfsek.terra.api.world.attribute.schedule; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.OptionalInt; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.attribute.Attribute; + + +/** + * Both maps are unmodifiable copies in the given order. + */ +public record AttributeSchedule(RegistryKey clock, OptionalInt periodTicks, Map, ScheduleTrack> tracks, + Map timeMarkers) { + public AttributeSchedule { + tracks = Collections.unmodifiableMap(new LinkedHashMap<>(tracks)); + timeMarkers = Collections.unmodifiableMap(new LinkedHashMap<>(timeMarkers)); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Easing.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Easing.java new file mode 100644 index 000000000..44f3dd80b --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Easing.java @@ -0,0 +1,29 @@ +package com.dfsek.terra.api.world.attribute.schedule; + +import java.util.Set; + + +public sealed interface Easing { + Set NAMES = Set.of( + "constant", "linear", + "in_back", "in_bounce", "in_circ", "in_cubic", "in_elastic", "in_expo", "in_quad", "in_quart", "in_quint", "in_sine", + "in_out_back", "in_out_bounce", "in_out_circ", "in_out_cubic", "in_out_elastic", "in_out_expo", "in_out_quad", + "in_out_quart", "in_out_quint", "in_out_sine", + "out_back", "out_bounce", "out_circ", "out_cubic", "out_elastic", "out_expo", "out_quad", "out_quart", "out_quint", + "out_sine"); + + + record Named(String name) implements Easing { + public Named { + if(!NAMES.contains(name)) throw new IllegalArgumentException("unknown easing \"" + name + "\""); + } + } + + + record CubicBezier(float x1, float y1, float x2, float y2) implements Easing { + public CubicBezier { + if(!(x1 >= 0f && x1 <= 1f)) throw new IllegalArgumentException("cubic_bezier x1 is outside [0, 1]"); + if(!(x2 >= 0f && x2 <= 1f)) throw new IllegalArgumentException("cubic_bezier x2 is outside [0, 1]"); + } + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Keyframe.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Keyframe.java new file mode 100644 index 000000000..13cb04aa2 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/Keyframe.java @@ -0,0 +1,6 @@ +package com.dfsek.terra.api.world.attribute.schedule; + +/** + * {@code argument} comes from {@link com.dfsek.terra.api.world.attribute.AttributeType#decodeArgument}. + */ +public record Keyframe(int ticks, Object argument) { } diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleDecodeResult.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleDecodeResult.java new file mode 100644 index 000000000..8daeb1b2f --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleDecodeResult.java @@ -0,0 +1,20 @@ +package com.dfsek.terra.api.world.attribute.schedule; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; + + +public record ScheduleDecodeResult(Optional schedule, List droppedTracks, Optional skipped) { + public ScheduleDecodeResult { + Objects.requireNonNull(schedule, "schedule"); + droppedTracks = List.copyOf(droppedTracks); + Objects.requireNonNull(skipped, "skipped"); + if(schedule.isPresent() == skipped.isPresent()) { + throw new IllegalArgumentException("exactly one of schedule and skipped must be present"); + } + } + + + public record Problem(String key, String reason) { } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleTrack.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleTrack.java new file mode 100644 index 000000000..84c53a784 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/ScheduleTrack.java @@ -0,0 +1,12 @@ +package com.dfsek.terra.api.world.attribute.schedule; + +import java.util.List; + +import com.dfsek.terra.api.world.attribute.Operation; + + +public record ScheduleTrack(Operation operation, List keyframes, Easing ease) { + public ScheduleTrack { + keyframes = List.copyOf(keyframes); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/TimeMarker.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/TimeMarker.java new file mode 100644 index 000000000..400a7af49 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/schedule/TimeMarker.java @@ -0,0 +1,3 @@ +package com.dfsek.terra.api.world.attribute.schedule; + +public record TimeMarker(int ticks, boolean showInCommands) { } diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/BlendToGray.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/BlendToGray.java new file mode 100644 index 000000000..5d52aa695 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/BlendToGray.java @@ -0,0 +1,6 @@ +package com.dfsek.terra.api.world.attribute.value; + +/** + * Both in [0, 1]. + */ +public record BlendToGray(float brightness, float factor) { } diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/Color.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/Color.java new file mode 100644 index 000000000..096e9077c --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/Color.java @@ -0,0 +1,97 @@ +package com.dfsek.terra.api.world.attribute.value; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.List; +import java.util.regex.Pattern; + + +/** + * Channels are in [0, 1]. + */ +public record Color(float r, float g, float b, float a) { + private static final Pattern HEX6 = Pattern.compile("#[0-9a-fA-F]{6}"); + private static final Pattern HEX8 = Pattern.compile("#[0-9a-fA-F]{8}"); + + public static Color rgb(int rgb) { + return new Color(((rgb >> 16) & 0xFF) / 255f, ((rgb >> 8) & 0xFF) / 255f, (rgb & 0xFF) / 255f, 1f); + } + + public static Color argb(int argb) { + return new Color(((argb >> 16) & 0xFF) / 255f, ((argb >> 8) & 0xFF) / 255f, (argb & 0xFF) / 255f, ((argb >>> 24) & 0xFF) / 255f); + } + + /** + * Accepts {@code "#rrggbb"}, a list of 3 floats, or an integer {@code 0xRRGGBB} (alpha bits ignored). + */ + public static Color parseRgb(Object o) { + if(o instanceof String s) { + if(!HEX6.matcher(s).matches()) throw new IllegalArgumentException("invalid RGB color (expected #rrggbb): \"" + s + "\""); + return rgb(Integer.parseInt(s.substring(1), 16)); + } + if(o instanceof List l) { + if(l.size() != 3) throw new IllegalArgumentException("color list must have 3 elements, got " + l); + return new Color(channel(l.get(0)), channel(l.get(1)), channel(l.get(2)), 1f); + } + if(o instanceof Number n) return rgb(integral(n, Integer.MAX_VALUE)); + throw new IllegalArgumentException("invalid RGB color: " + o); + } + + /** + * Accepts {@code "#aarrggbb"}, a list of 4 floats (r, g, b, a), or an integer {@code 0xAARRGGBB}, signed or unsigned. + */ + public static Color parseArgb(Object o) { + if(o instanceof String s) { + if(!HEX8.matcher(s).matches()) throw new IllegalArgumentException("invalid ARGB color (expected #aarrggbb): \"" + s + "\""); + return argb((int) Long.parseLong(s.substring(1), 16)); + } + if(o instanceof List l) { + if(l.size() != 4) throw new IllegalArgumentException("color list must have 4 elements, got " + l); + return new Color(channel(l.get(0)), channel(l.get(1)), channel(l.get(2)), channel(l.get(3))); + } + if(o instanceof Number n) return argb(integral(n, 0xFFFFFFFFL)); + throw new IllegalArgumentException("invalid ARGB color: " + o); + } + + private static int integral(Number n, long max) { + BigInteger value; + try { + value = exact(n).toBigIntegerExact(); + } catch(ArithmeticException | NumberFormatException e) { + throw new IllegalArgumentException("color integer must be integral: " + n); + } + if(value.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0 || value.compareTo(BigInteger.valueOf(max)) > 0) { + throw new IllegalArgumentException("value " + n + " is outside [" + Integer.MIN_VALUE + ", " + max + "]"); + } + return value.intValue(); + } + + private static BigDecimal exact(Number n) { + if(n instanceof Integer || n instanceof Long || n instanceof Short || n instanceof Byte) return BigDecimal.valueOf(n.longValue()); + if(n instanceof BigDecimal d) return d; + if(n instanceof BigInteger i) return new BigDecimal(i); + if(n instanceof Double || n instanceof Float) { + double d = n.doubleValue(); + if(!Double.isFinite(d)) throw new NumberFormatException(); + return new BigDecimal(d); + } + return new BigDecimal(n.toString()); + } + + private static float channel(Object o) { + if(o instanceof Number n) return n.floatValue(); + throw new IllegalArgumentException("color channel must be a number: " + o); + } + + private static int to255(float c) { + return Math.max(0, Math.min(255, Math.round(c * 255))); + } + + public int toRgbInt() { + return (to255(r) << 16) | (to255(g) << 8) | to255(b); + } + + public int toArgbInt() { + return (to255(a) << 24) | toRgbInt(); + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/FloatWithAlpha.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/FloatWithAlpha.java new file mode 100644 index 000000000..735d32cf6 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/FloatWithAlpha.java @@ -0,0 +1,6 @@ +package com.dfsek.terra.api.world.attribute.value; + +/** + * {@code alpha} is in [0, 1]. + */ +public record FloatWithAlpha(float value, float alpha) { } diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/TriState.java b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/TriState.java new file mode 100644 index 000000000..51b19cde0 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/attribute/value/TriState.java @@ -0,0 +1,21 @@ +package com.dfsek.terra.api.world.attribute.value; + +import com.dfsek.terra.api.registry.key.StringIdentifiable; + + +public enum TriState implements StringIdentifiable { + TRUE("true"), + FALSE("false"), + DEFAULT("default"); + + private final String id; + + TriState(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } +} diff --git a/common/api/src/test/java/com/dfsek/terra/api/registry/key/RegistryKeyTest.java b/common/api/src/test/java/com/dfsek/terra/api/registry/key/RegistryKeyTest.java new file mode 100644 index 000000000..f5aa9be5c --- /dev/null +++ b/common/api/src/test/java/com/dfsek/terra/api/registry/key/RegistryKeyTest.java @@ -0,0 +1,113 @@ +package com.dfsek.terra.api.registry.key; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.Objects; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +public class RegistryKeyTest { + @ParameterizedTest + @CsvSource({ + "mypack:visual/fog_color, mypack, visual/fog_color", + "mypack:ambient.cave, mypack, ambient.cave", + "my.pack:thing, my.pack, thing", + "terra:overworld_biome-1, terra, overworld_biome-1", + "MyPack:Seasons, MyPack, Seasons", + }) + void validKeysParse(String key, String namespace, String id) { + RegistryKey parsed = RegistryKey.parse(key); + assertEquals(RegistryKey.of(namespace, id), parsed); + assertEquals(namespace, parsed.getNamespace()); + assertEquals(id, parsed.getID()); + assertEquals(key, parsed.toString()); + assertEquals(parsed, RegistryKey.parse(key, "other")); + assertEquals(parsed, RegistryKey.parseNamespaced(key)); + } + + @ParameterizedTest + @ValueSource(strings = { "a/b:thing", "bad key", "a:b:c", "a:b c", "a b:c" }) + void invalidKeysAreRejected(String key) { + assertThrows(IllegalArgumentException.class, () -> RegistryKey.parse(key)); + } + + @Test + void invalidCharacterMessage() { + String id = assertThrows(IllegalArgumentException.class, () -> RegistryKey.of("a", "b c")).getMessage(); + assertTrue(id.contains("slashes") && id.contains("periods") && id.contains("\"b c\""), id); + String ns = assertThrows(IllegalArgumentException.class, () -> RegistryKey.of("a b", "c")).getMessage(); + assertTrue(ns.contains("periods") && !ns.contains("slashes") && ns.contains("\"a b\""), ns); + } + + @Test + void hashAndEquals() { + RegistryKey key = RegistryKey.parse("mypack:visual/fog_color"); + RegistryKey same = RegistryKey.of("mypack", "visual/fog_color"); + assertEquals(Objects.hash("mypack", "visual/fog_color"), key.hashCode()); + assertEquals(key, same); + assertEquals(key.hashCode(), same.hashCode()); + assertNotEquals(key, RegistryKey.of("mypack", "visual/sky_color")); + assertNotEquals(key, RegistryKey.of("terra", "visual/fog_color")); + assertNotEquals(RegistryKey.of("a", "bc"), RegistryKey.of("ab", "c")); + assertNotEquals(key, "mypack:visual/fog_color"); + } + + @Test + void parseWithDefaultNamespace() { + assertEquals(RegistryKey.of("mypack", "fog"), RegistryKey.parse("fog", "mypack")); + assertEquals(RegistryKey.of("my.pack", "a/b"), RegistryKey.parse("my.pack:a/b", "mypack")); + } + + @ParameterizedTest + @CsvSource(nullValues = "NULL", value = { + ":x, mypack, 'malformed ID \":x\": empty namespace'", + "x:, mypack, 'malformed ID \"x:\": empty ID'", + "'', mypack, 'malformed ID \"\": empty ID'", + "NULL, mypack, 'malformed ID: none given'", + "x, NULL, 'malformed ID \"x\": empty namespace'", + "a:b:c, mypack, 'malformed ID \"a:b:c\": more than one '':'''", + }) + void parseWithDefaultNamespaceRejects(String key, String defaultNamespace, String message) { + assertEquals(message, assertThrows(IllegalArgumentException.class, () -> RegistryKey.parse(key, defaultNamespace)).getMessage()); + } + + @Test + void parseNamespacedWithoutNamespace() { + assertEquals("a namespace is required, as in \"namespace:overworld\"", + assertThrows(IllegalArgumentException.class, () -> RegistryKey.parseNamespaced("overworld")).getMessage()); + } + + @ParameterizedTest + @NullSource + @ValueSource(strings = { "mypack:Bad Id", "#mypack:tag", "mypack:", ":overworld", "a:b:c" }) + void parseNamespacedRejects(String key) { + assertThrows(IllegalArgumentException.class, () -> RegistryKey.parseNamespaced(key)); + } + + @Test + void tagKey() { + TagKey tag = TagKey.parse("#mypack:infiniburn"); + assertEquals(RegistryKey.parse("mypack:infiniburn"), tag.key()); + assertEquals("#mypack:infiniburn", tag.toString()); + assertEquals(tag, TagKey.parse("#infiniburn", "mypack")); + assertEquals(tag, TagKey.of(RegistryKey.parse("mypack:infiniburn"))); + assertEquals(RegistryKey.of("mypack", "Music.Game"), TagKey.parse("#mypack:Music.Game").key()); + assertEquals(RegistryKey.of("MyPack", "Logs"), TagKey.parse("#Logs", "MyPack").key()); + assertEquals("invalid tag \"#stone\": a namespace is required, as in \"#namespace:stone\"", + assertThrows(IllegalArgumentException.class, () -> TagKey.parse("#stone")).getMessage()); + } + + @ParameterizedTest + @ValueSource(strings = { "mypack:stone", "#mypack:", "#mypack:bad id" }) + void tagKeyRejects(String tag) { + assertThrows(IllegalArgumentException.class, () -> TagKey.parse(tag)); + } +} diff --git a/common/api/src/test/java/com/dfsek/terra/api/world/attribute/AttributeMapTest.java b/common/api/src/test/java/com/dfsek/terra/api/world/attribute/AttributeMapTest.java new file mode 100644 index 000000000..19c51aefb --- /dev/null +++ b/common/api/src/test/java/com/dfsek/terra/api/world/attribute/AttributeMapTest.java @@ -0,0 +1,72 @@ +package com.dfsek.terra.api.world.attribute; + +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class AttributeMapTest { + private static final AttributeKey A = AttributeKey.parse("test:a"); + private static final AttributeKey B = AttributeKey.parse("test:b"); + + @Test + void emptyIsShared() { + assertSame(AttributeMap.empty(), AttributeMap.builder().build()); + assertSame(AttributeMap.empty(), AttributeMap.builder().put(A, AttributeEntry.override(1)).remove(A).build()); + assertTrue(AttributeMap.empty().get(A).isEmpty()); + } + + @Test + void overlayReplacesPerKey() { + AttributeEntry bottomA = AttributeEntry.override(1); + AttributeMap bottom = AttributeMap.builder().put(A, bottomA).put(B, AttributeEntry.override(2)).build(); + AttributeMap top = AttributeMap.builder().put(B, AttributeEntry.override(3)).build(); + AttributeMap merged = bottom.overlay(top); + assertEquals(List.of(A, B), List.copyOf(merged.keys())); + assertSame(bottomA, merged.get(A).orElseThrow()); + assertEquals(AttributeEntry.override(3), merged.get(B).orElseThrow()); + assertEquals(AttributeEntry.override(2), bottom.get(B).orElseThrow()); + } + + @Test + void builderRemove() { + AttributeMap map = AttributeMap.builder().put(A, AttributeEntry.override(1)).put(B, AttributeEntry.override(2)).remove(A).build(); + assertEquals(Set.of(B), map.keys()); + assertTrue(map.get(AttributeKey.parse("test:b")).isPresent()); + assertThrows(UnsupportedOperationException.class, () -> map.keys().clear()); + } + + @Test + void nullsThrow() { + AttributeMap.Builder builder = AttributeMap.builder(); + assertThrows(NullPointerException.class, () -> builder.put(null, AttributeEntry.override(1))); + assertThrows(NullPointerException.class, () -> builder.put(A, null)); + assertEquals("top", assertThrows(NullPointerException.class, () -> AttributeMap.empty().overlay(null)).getMessage()); + } + + @Test + void nullArgument() { + assertNull(AttributeEntry.override(null).argument()); + assertNull(AttributeEntry.of(Operation.OVERRIDE, null).argument()); + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> AttributeEntry.of(Operation.ADD, null)); + assertEquals("modifier add needs an argument", e.getMessage()); + assertThrows(IllegalArgumentException.class, () -> new AttributeEntry(Operation.MULTIPLY, null)); + } + + @Test + void equalByContent() { + AttributeMap one = AttributeMap.builder().put(A, AttributeEntry.override(1)).build(); + AttributeMap two = AttributeMap.builder().put(A, AttributeEntry.override(1)).build(); + assertEquals(one, two); + assertEquals(one.hashCode(), two.hashCode()); + assertNotEquals(one, AttributeMap.builder().put(A, AttributeEntry.override(2)).build()); + } +} diff --git a/common/api/src/test/java/com/dfsek/terra/api/world/attribute/ValueTypesTest.java b/common/api/src/test/java/com/dfsek/terra/api/world/attribute/ValueTypesTest.java new file mode 100644 index 000000000..7ef9856ba --- /dev/null +++ b/common/api/src/test/java/com/dfsek/terra/api/world/attribute/ValueTypesTest.java @@ -0,0 +1,132 @@ +package com.dfsek.terra.api.world.attribute; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Stream; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.attribute.schedule.Easing; +import com.dfsek.terra.api.world.attribute.value.Color; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.params.provider.Arguments.arguments; + + +public class ValueTypesTest { + @Test + public void attributeKey() { + RegistryKey registryKey = RegistryKey.parse("my.pack:visual/Fog_Color"); + AttributeKey key = AttributeKey.parse("my.pack:visual/Fog_Color"); + assertEquals(registryKey, key.getRegistryKey()); + assertEquals("my.pack:visual/Fog_Color", key.toString()); + AttributeKey wrapped = AttributeKey.of(registryKey); + assertSame(registryKey, wrapped.getRegistryKey()); + assertEquals(wrapped, key); + assertEquals(registryKey.hashCode(), key.hashCode()); + assertNotEquals(key, AttributeKey.parse("my.pack:visual/other")); + assertEquals("invalid attribute key \"visual/fog_color\": a namespace is required, as in \"namespace:visual/fog_color\"", + assertThrows(IllegalArgumentException.class, () -> AttributeKey.parse("visual/fog_color")).getMessage()); + } + + @ParameterizedTest + @NullSource + @ValueSource(strings = { "Bad Key", "mypack:", ":visual/fog_color", "a:b:c" }) + public void attributeKeyRejects(String key) { + assertThrows(IllegalArgumentException.class, () -> AttributeKey.parse(key)); + } + + @Test + public void parseFailureMessages() { + assertEquals("unknown modifier \"frobnicate\"", + assertThrows(IllegalArgumentException.class, () -> Operation.parse("frobnicate")).getMessage()); + assertEquals("unknown easing \"x\"", + assertThrows(IllegalArgumentException.class, () -> new Easing.Named("x")).getMessage()); + for(Operation op : Operation.values()) assertSame(op, Operation.parse(op.getID())); + } + + private static Arguments rgb(Object raw, int expected) { + return arguments(raw, (Function) Color::parseRgb, Color.rgb(expected)); + } + + private static Arguments argb(Object raw, int expected) { + return arguments(raw, (Function) Color::parseArgb, Color.argb(expected)); + } + + static Stream colors() { + return Stream.of( + rgb("#050533", 0x050533), + arguments(List.of(1.0, 0.5, 0.0), (Function) Color::parseRgb, new Color(1f, 0.5f, 0f, 1f)), + rgb(16777215, 0xFFFFFF), + rgb(16777215L, 0xFFFFFF), + rgb(1.6777215E7, 0xFFFFFF), + rgb(BigInteger.valueOf(0x102030), 0x102030), + rgb(new BigDecimal("1056816.0"), 0x102030), + rgb(0xFF102030, 0x102030), + argb("#80ff0000", 0x80FF0000), + argb(0xFF102030L, 0xFF102030), + argb(0xFF102030, 0xFF102030), + argb(BigInteger.valueOf(0xFFFFFFFFL), 0xFFFFFFFF)); + } + + @ParameterizedTest + @MethodSource + public void colors(Object raw, Function parser, Color expected) { + assertEquals(expected, parser.apply(raw)); + } + + private static Arguments rejectRgb(Object raw, String message) { + return arguments(raw, (Function) Color::parseRgb, message); + } + + private static Arguments rejectArgb(Object raw, String message) { + return arguments(raw, (Function) Color::parseArgb, message); + } + + static Stream colorsRejected() { + return Stream.of( + rejectRgb("#12345", null), + rejectRgb(0.5, null), + rejectArgb(0.5, null), + rejectRgb(new BigDecimal("1.5"), "color integer must be integral: 1.5"), + rejectArgb(new BigDecimal("1.5"), null), + rejectRgb(Double.NaN, null), + rejectRgb(Double.POSITIVE_INFINITY, null), + rejectRgb(0xFFFFFFFFL, "value 4294967295 is outside [-2147483648, 2147483647]"), + rejectRgb(new BigInteger("100000000000"), null), + rejectArgb(0x100000000L, "value 4294967296 is outside [-2147483648, 4294967295]"), + rejectArgb(-2147483649L, null)); + } + + @ParameterizedTest + @MethodSource + public void colorsRejected(Object raw, Function parser, String message) { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> parser.apply(raw)); + if(message != null) assertEquals(message, e.getMessage()); + } + + @Test + public void rawValueDeepCopy() { + Map inner = new HashMap<>(); + inner.put("a", 1); + Map map = new HashMap<>(); + map.put("inner", inner); + RawValue raw = new RawValue(map); + map.put("b", 2); + inner.put("c", 3); + @SuppressWarnings("unchecked") + Map copy = (Map) raw.value(); + assertEquals(1, copy.size()); + assertEquals(Map.of("a", 1), copy.get("inner")); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java b/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java index 9a4097108..8a3ce64b5 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java @@ -67,6 +67,7 @@ import com.dfsek.terra.api.registry.key.StringIdentifiable; import com.dfsek.terra.api.util.generic.pair.Pair; import com.dfsek.terra.api.util.mutable.MutableBoolean; import com.dfsek.terra.api.util.reflection.TypeKey; +import com.dfsek.terra.api.world.attribute.AttributeHandle; import com.dfsek.terra.config.GenericLoaders; import com.dfsek.terra.config.PluginConfigImpl; import com.dfsek.terra.event.EventManagerImpl; @@ -77,6 +78,7 @@ import com.dfsek.terra.registry.OpenRegistryImpl; import com.dfsek.terra.registry.master.ConfigRegistry; import com.dfsek.terra.registry.master.ConfigRegistry.PackLoadFailuresException; import com.dfsek.terra.registry.master.MetaConfigRegistry; +import com.dfsek.terra.world.attribute.AttributeHandleImpl; /** @@ -103,6 +105,8 @@ public abstract class AbstractPlatform implements Platform { private final GenericLoaders loaders = new GenericLoaders(this); private final PluginConfigImpl config = new PluginConfigImpl(); private final CheckedRegistry addonRegistry = new CheckedRegistryImpl<>(new OpenRegistryImpl<>(TypeKey.of(BaseAddon.class))); + // Must exist before addons initialize: it creates the attribute context keys. + private final AttributeHandle attributeHandle = new AttributeHandleImpl(); private final Registry lockedAddonRegistry = new LockedRegistryImpl<>(addonRegistry); public static int getGenerationThreadsWithReflection(String className, String fieldName, String project) { @@ -434,6 +438,11 @@ public abstract class AbstractPlatform implements Platform { return profiler; } + @Override + public @NotNull AttributeHandle getAttributeHandle() { + return attributeHandle; + } + @Override public int getGenerationThreads() { return 1; diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaListLikePreprocessor.java b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaListLikePreprocessor.java index 2e6707c9d..6ccf27cd7 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaListLikePreprocessor.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaListLikePreprocessor.java @@ -68,8 +68,7 @@ public class MetaListLikePreprocessor extends MetaPreprocessor { if(!(metaValue instanceof List)) { throw new LoadException( - "Meta list / set injection (via <<) must point to a list. '" + meta + "' points to type " + - metaValue.getClass().getCanonicalName(), + "Meta list / set injection (via <<) must point to a list. '" + meta + "' points to " + describe(metaValue), depthTracker); } diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaMapPreprocessor.java b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaMapPreprocessor.java index 3a05e8112..96f5f8a9a 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaMapPreprocessor.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaMapPreprocessor.java @@ -63,7 +63,7 @@ public class MetaMapPreprocessor extends MetaPreprocessor { Object meta = pair.getRight(); if(!(meta instanceof Map)) { throw new LoadException( - "MetaMap injection candidate must be list, is type " + meta.getClass().getCanonicalName(), + "MetaMap injection candidate must be map, is " + describe(meta), depthTracker); } newMap.putAll((Map) meta); diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaPreprocessor.java b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaPreprocessor.java index 2f4b0d231..def8a608e 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaPreprocessor.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaPreprocessor.java @@ -35,8 +35,13 @@ public abstract class MetaPreprocessor implements ValuePre this.configs = configs; } + protected static String describe(Object value) { + return value == null ? "null" : "type " + value.getClass().getCanonicalName(); + } + protected Pair getMetaValue(String meta, DepthTracker depthTracker) { int sep = meta.indexOf(':'); + if(sep < 0) throw new LoadException("meta reference \"" + meta + "\" must have the form file:key", depthTracker); String file = meta.substring(0, sep); String key = meta.substring(sep + 1); @@ -44,10 +49,16 @@ public abstract class MetaPreprocessor implements ValuePre Configuration config = configs.get(file); - if(!config.contains(key)) { - throw new LoadException("Cannot fetch metavalue: No such key " + key + " in configuration " + config.getName(), depthTracker); + try { + if(!config.contains(key)) { + throw new LoadException("Cannot fetch metavalue: No such key " + key + " in configuration " + config.getName(), + depthTracker); + } + return Pair.of(config, config.get(key)); + } catch(IllegalArgumentException e) { + // Tectonic's key path messages are Java-style. + throw new LoadException("meta reference \"" + meta + "\" has an invalid key path: use \\. for a dot in a key and \\\\ " + + "for a backslash", e, depthTracker); } - - return Pair.of(config, config.get(key)); } } diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaStringPreprocessor.java b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaStringPreprocessor.java index 8869a0228..dcb37e068 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaStringPreprocessor.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/config/preprocessor/MetaStringPreprocessor.java @@ -43,8 +43,8 @@ public class MetaStringPreprocessor extends MetaPreprocessor { StringSubstitutor substitutor = new StringSubstitutor(key -> { Object meta = getMetaValue(key, depthTracker).getRight(); if(!(meta instanceof String) && !(meta instanceof Number) && !(meta instanceof Character) && !(meta instanceof Boolean)) { - throw new LoadException("MetaString template injection candidate must be string or primitive, is type " + - meta.getClass().getCanonicalName(), depthTracker); + throw new LoadException("MetaString template injection candidate must be string or primitive, is " + describe(meta), + depthTracker); } return meta.toString(); }); diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeCodecsImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeCodecsImpl.java new file mode 100644 index 000000000..9f90e5d1b --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeCodecsImpl.java @@ -0,0 +1,107 @@ +package com.dfsek.terra.world.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.StringIdentifiable; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.AttributeCodec; +import com.dfsek.terra.api.world.attribute.AttributeCodecs; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.RawValue; + + +final class AttributeCodecsImpl implements AttributeCodecs { + static final AttributeCodecsImpl INSTANCE = new AttributeCodecsImpl(); + + private AttributeCodecsImpl() { } + + @Override + public AttributeCodec of(Decoder decoder, Encoder encoder) { + return ValueDecoders.codec(decoder, encoder); + } + + @Override + public String describe(@Nullable Object value) { + return ValueDecoders.got(value); + } + + @Override + public AttributeCodec booleanCodec() { + return ValueDecoders.BOOLEAN; + } + + @Override + public AttributeCodec floatCodec() { + return ValueDecoders.FLOAT; + } + + @Override + public AttributeCodec doubleCodec() { + return ValueDecoders.DOUBLE; + } + + @Override + public AttributeCodec intCodec() { + return ValueDecoders.INT; + } + + @Override + public AttributeCodec nonNegativeInt() { + return ValueDecoders.NON_NEGATIVE_INT; + } + + @Override + public AttributeCodec unitFloat() { + return ValueDecoders.UNIT_FLOAT; + } + + @Override + public AttributeCodec string(String expected) { + return ValueDecoders.string(expected); + } + + @Override + public AttributeCodec raw() { + return ValueDecoders.RAW; + } + + @Override + public AttributeCodec> list(AttributeCodec element) { + return ValueDecoders.list(element); + } + + @Override + public AttributeCodec> compactList(AttributeCodec element) { + return ValueDecoders.compactList(element); + } + + @Override + public & StringIdentifiable> AttributeCodec enumCodec(String name, Class type) { + return ValueDecoders.identifiableEnum(name, type); + } + + @Override + public AttributeCodec identifier(String defaultNamespace) { + return ValueDecoders.identifier(defaultNamespace); + } + + @Override + public AttributeCodec> identifierOrTag(String defaultNamespace) { + return ValueDecoders.identifierOrTag(defaultNamespace); + } + + @Override + public ObjectReader reader(String what, Object raw, DecodeContext context) throws DecodeException { + return new ValueDecoders.Fields(what, raw, context); + } + + @Override + public ObjectWriter writer() { + return new ValueDecoders.Encoded(); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeHandleImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeHandleImpl.java new file mode 100644 index 000000000..40f90fc0a --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeHandleImpl.java @@ -0,0 +1,137 @@ +package com.dfsek.terra.world.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.properties.Properties; +import com.dfsek.terra.api.properties.PropertyKey; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeCodec; +import com.dfsek.terra.api.world.attribute.AttributeCodecs; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeLookup; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.AttributeTypes; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.PackAttributes; +import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult; +import com.dfsek.terra.world.attribute.format.EntryFormat; +import com.dfsek.terra.world.attribute.format.ScheduleFormat; + + +/** + * Create one per platform, at construction: {@link Context#create} is not thread safe. + */ +public final class AttributeHandleImpl implements AttributeHandle { + private final PropertyKey packKey = Context.create(PackAttributes.class); + private final AtomicInteger attributeIndices = new AtomicInteger(); + + private static Optional read(Context context, PropertyKey key) { + if(!context.has(key)) return Optional.empty(); + return Optional.ofNullable(context.get(key)); + } + + @Override + public AttributeTypes types() { + return AttributeTypesImpl.INSTANCE; + } + + @Override + public AttributeCodecs codecs() { + return AttributeCodecsImpl.INSTANCE; + } + + @Override + public DecodeContext plainContext() { + return PlainDecodeContext.INSTANCE; + } + + @Override + public AttributeType.Builder typeBuilder(String id, AttributeCodec codec) { + return AttributeTypeImpl.builder(id, codec); + } + + @Override + public Attribute.Builder attributeBuilder(AttributeKey key, AttributeType type, @Nullable T defaultValue) { + return AttributeImpl.builder(key, type, defaultValue, attributeIndices); + } + + @Override + public int attributeCount() { + return attributeIndices.get(); + } + + @Override + @SafeVarargs + @SuppressWarnings("varargs") + public final @Nullable T resolve(Attribute attribute, AttributeEntry... layersBottomToTop) { + return AttributeLayers.resolve(attribute, layersBottomToTop); + } + + @Override + public @Nullable T resolve(Attribute attribute, @Nullable AttributeEntry first, @Nullable AttributeEntry second, + @Nullable AttributeEntry third) { + return AttributeLayers.resolve(attribute, first, second, third, null); + } + + @Override + public @Nullable T resolve(Attribute attribute, @Nullable AttributeEntry first, @Nullable AttributeEntry second, + @Nullable AttributeEntry third, @Nullable AttributeEntry fourth) { + return AttributeLayers.resolve(attribute, first, second, third, fourth); + } + + @Override + @SuppressWarnings("unchecked") + public Optional> compose(Attribute attribute, @Nullable AttributeEntry lower, + @Nullable AttributeEntry upper) { + if(lower == null) return Optional.ofNullable(upper); + if(upper == null) return Optional.of(lower); + if(upper.isOverride()) return Optional.of(upper); + if(lower.isOverride()) { + T value = (T) lower.argument(); + if(value == null) return Optional.of(lower); + return Optional.of(AttributeEntry.override(upper.apply(attribute.type(), value))); + } + Operation op = upper.operation(); + if(op != lower.operation()) return Optional.empty(); + return attribute.type().compose(op, lower.argument(), upper.argument()).map(argument -> AttributeEntry.of(op, argument)); + } + + @Override + public AttributeEntry decodeEntry(Attribute attribute, @Nullable Object raw, DecodeContext context) + throws DecodeException { + return EntryFormat.decode(attribute, raw, context); + } + + @Override + public Object encodeEntry(Attribute attribute, AttributeEntry entry) { + return EntryFormat.encode(attribute, entry); + } + + @Override + public ScheduleDecodeResult decodeSchedule(RegistryKey id, Map raw, AttributeLookup attributes, + DecodeContext context) { + return ScheduleFormat.decode(id, raw, attributes, context); + } + + @Override + public Map encodeSchedule(AttributeSchedule schedule) { + return ScheduleFormat.encode(schedule); + } + + @Override + public Optional pack(ConfigPack pack) { + return read(pack.getContext(), packKey); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeImpl.java new file mode 100644 index 000000000..fc81f8b25 --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeImpl.java @@ -0,0 +1,159 @@ +package com.dfsek.terra.world.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeScope; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.DecodeException; + + +final class AttributeImpl implements Attribute { + private final AttributeKey key; + private final AttributeType type; + private final @Nullable T defaultValue; + private final AttributeScope scope; + private final boolean ranged; + private final double min; + private final double max; + private final int multipleOf; + private final int index; + + private AttributeImpl(Builder builder, int index) { + this.key = builder.key; + this.type = builder.type; + this.defaultValue = builder.defaultValue; + this.scope = builder.scope; + this.ranged = builder.ranged; + this.min = builder.min; + this.max = builder.max; + this.multipleOf = builder.multipleOf; + this.index = index; + } + + static Builder builder(AttributeKey key, AttributeType type, @Nullable T defaultValue, AtomicInteger indices) { + return new Builder<>(key, type, defaultValue, indices); + } + + @Override + public AttributeKey key() { + return key; + } + + @Override + public AttributeType type() { + return type; + } + + @Override + public @Nullable T defaultValue() { + return defaultValue; + } + + @Override + public AttributeScope scope() { + return scope; + } + + @Override + public int index() { + return index; + } + + @Override + public T validate(T value) throws DecodeException { + if(value instanceof Number number) { + if(ranged && !inRange(number)) { + throw new DecodeException("value " + value + " is outside " + rangeString()); + } + if(multipleOf > 1 && number.intValue() % multipleOf != 0) { + throw new DecodeException("value " + value + " is not a multiple of " + multipleOf); + } + } + return value; + } + + @Override + @SuppressWarnings("unchecked") + public T sanitize(T value) { + if(!ranged) return value; + if(value instanceof Float f) { + if(f.isNaN()) return value; + return (T) Float.valueOf(Math.max((float) min, Math.min((float) max, f))); + } + if(value instanceof Integer i) { + return (T) Integer.valueOf((int) Math.max(min, Math.min(max, i))); + } + return value; + } + + private boolean inRange(Number number) { + if(number instanceof Float f) return f >= (float) min && f <= (float) max; + double d = number.doubleValue(); + return d >= min && d <= max; + } + + private String rangeString() { + String upper = Double.isInfinite(max) ? "∞)" : format(max) + "]"; + return "[" + format(min) + ", " + upper; + } + + private static String format(double d) { + if(d == Math.rint(d) && Math.abs(d) < 1e15) return Long.toString((long) d); + return Double.toString(d); + } + + @Override + public String toString() { + return "Attribute[" + key + "]"; + } + + + static final class Builder implements Attribute.Builder { + private final AttributeKey key; + private final AttributeType type; + private final @Nullable T defaultValue; + private final AtomicInteger indices; + private AttributeScope scope = AttributeScope.ANYWHERE; + private boolean ranged; + private double min; + private double max; + private int multipleOf = 1; + + private Builder(AttributeKey key, AttributeType type, @Nullable T defaultValue, AtomicInteger indices) { + this.key = Objects.requireNonNull(key, "key"); + this.type = Objects.requireNonNull(type, "type"); + this.defaultValue = defaultValue; + this.indices = indices; + } + + @Override + public Builder range(Number min, Number max) { + this.ranged = true; + this.min = min.doubleValue(); + this.max = max.doubleValue(); + return this; + } + + @Override + public Builder multipleOf(int multipleOf) { + this.multipleOf = multipleOf; + return this; + } + + @Override + public Builder packOnly() { + this.scope = AttributeScope.PACK_ONLY; + return this; + } + + @Override + public Attribute build() { + return new AttributeImpl<>(this, indices.getAndIncrement()); + } + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeLayers.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeLayers.java new file mode 100644 index 000000000..c0eaa73aa --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeLayers.java @@ -0,0 +1,60 @@ +package com.dfsek.terra.world.attribute; + +import org.jetbrains.annotations.Nullable; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; + + +final class AttributeLayers { + private AttributeLayers() { } + + @SafeVarargs + static @Nullable T resolve(Attribute attribute, AttributeEntry... layersBottomToTop) { + T value = attribute.defaultValue(); + boolean applied = false; + for(AttributeEntry entry : layersBottomToTop) { + if(entry == null) continue; + if(value == null) { + if(!entry.isOverride()) continue; + value = entry.apply(attribute.type(), null); + } else { + value = entry.apply(attribute.type(), value); + } + applied = true; + } + if(value == null || !applied) return value; + return attribute.sanitize(value); + } + + /** + * Unrolled to allocate nothing. + */ + static @Nullable T resolve(Attribute attribute, @Nullable AttributeEntry first, @Nullable AttributeEntry second, + @Nullable AttributeEntry third, @Nullable AttributeEntry fourth) { + T value = attribute.defaultValue(); + boolean applied = false; + if(applies(value, first)) { + value = first.apply(attribute.type(), value); + applied = true; + } + if(applies(value, second)) { + value = second.apply(attribute.type(), value); + applied = true; + } + if(applies(value, third)) { + value = third.apply(attribute.type(), value); + applied = true; + } + if(applies(value, fourth)) { + value = fourth.apply(attribute.type(), value); + applied = true; + } + if(value == null || !applied) return value; + return attribute.sanitize(value); + } + + private static boolean applies(@Nullable T value, @Nullable AttributeEntry entry) { + return entry != null && (value != null || entry.isOverride()); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypeImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypeImpl.java new file mode 100644 index 000000000..94cfa19c7 --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypeImpl.java @@ -0,0 +1,155 @@ +package com.dfsek.terra.world.attribute; + +import org.jetbrains.annotations.Nullable; + +import java.util.Collections; +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.BinaryOperator; + +import com.dfsek.terra.api.world.attribute.AttributeCodec; +import com.dfsek.terra.api.world.attribute.AttributeModifier; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; + + +final class AttributeTypeImpl implements AttributeType { + private record Op(AttributeCodec argumentCodec, AttributeModifier modifier, + @Nullable BinaryOperator composer) { + Op withComposer(BinaryOperator composer) { + return new Op<>(argumentCodec, modifier, composer); + } + } + + + private static final Operation[] OPERATIONS = Operation.values(); + + private final String id; + private final AttributeCodec codec; + private final Op[] ops; + private final Set operations; + + @SuppressWarnings("unchecked") + private AttributeTypeImpl(String id, AttributeCodec codec, Map> ops) { + this.id = id; + this.codec = codec; + this.ops = (Op[]) new Op[OPERATIONS.length]; + ops.forEach((op, o) -> this.ops[op.ordinal()] = o); + this.operations = Collections.unmodifiableSet(EnumSet.copyOf(ops.keySet())); + } + + static Builder builder(String id, AttributeCodec codec) { + return new Builder<>(id, codec); + } + + @Override + public String id() { + return id; + } + + @Override + public Set operations() { + return operations; + } + + @Override + public T decode(Object raw, DecodeContext context) throws DecodeException { + return codec.decode(raw, context); + } + + @Override + public Object encode(T value) { + return codec.encode(value); + } + + @Override + public Object decodeArgument(Operation op, Object raw, DecodeContext context) throws DecodeException { + Op o = ops[op.ordinal()]; + if(o == null) throw new DecodeException(invalid(op)); + return o.argumentCodec().decode(raw, context); + } + + @Override + public Object encodeArgument(Operation op, Object argument) { + return op(op).argumentCodec().encode(argument); + } + + @Override + public T apply(Operation op, T subject, Object argument) { + return op(op).modifier().apply(subject, argument); + } + + @Override + public Optional compose(Operation op, Object lower, Object upper) { + Op o = ops[op.ordinal()]; + if(o == null || o.composer() == null) return Optional.empty(); + Object composed = o.composer().apply(lower, upper); + if(composed == null) throw new NullPointerException("composer for " + op.getID() + " of " + id + " returned null"); + return Optional.of(composed); + } + + private Op op(Operation op) { + Op o = ops[op.ordinal()]; + if(o == null) throw new IllegalArgumentException(invalid(op)); + return o; + } + + private String invalid(Operation op) { + return "modifier " + op.getID() + " is not valid for " + id; + } + + @Override + public String toString() { + return "AttributeType[" + id + "]"; + } + + + static final class Builder implements AttributeType.Builder { + private final String id; + private final AttributeCodec codec; + private final Map> ops = new EnumMap<>(Operation.class); + + @SuppressWarnings("unchecked") + private Builder(String id, AttributeCodec codec) { + this.id = Objects.requireNonNull(id, "id"); + this.codec = Objects.requireNonNull(codec, "codec"); + ops.put(Operation.OVERRIDE, new Op<>((AttributeCodec) codec, (s, a) -> (T) a, null)); + } + + @Override + @SuppressWarnings("unchecked") + public Builder op(Operation op, AttributeCodec argumentCodec, AttributeModifier modifier) { + if(op == Operation.OVERRIDE) { + throw new IllegalArgumentException("modifier override cannot be replaced"); + } + Objects.requireNonNull(argumentCodec, "argumentCodec"); + Objects.requireNonNull(modifier, "modifier"); + ops.put(op, new Op<>((AttributeCodec) argumentCodec, (s, a) -> modifier.apply(s, (A) a), null)); + return this; + } + + @Override + @SuppressWarnings("unchecked") + public Builder composable(Operation op, BinaryOperator combine) { + if(op == Operation.OVERRIDE) { + throw new IllegalArgumentException("modifier override cannot be composed"); + } + Objects.requireNonNull(combine, "combine"); + Op o = ops.get(op); + if(o == null) throw new IllegalArgumentException("modifier " + op.getID() + " must be added before it is made composable"); + ops.put(op, o.withComposer((a, b) -> combine.apply((A) a, (A) b))); + return this; + } + + @Override + public AttributeType build() { + return new AttributeTypeImpl<>(id, codec, ops); + } + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypesImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypesImpl.java new file mode 100644 index 000000000..5084d9ca9 --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/AttributeTypesImpl.java @@ -0,0 +1,186 @@ +package com.dfsek.terra.world.attribute; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.StringIdentifiable; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.AttributeTypes; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.world.attribute.value.BlendToGray; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.api.world.attribute.value.TriState; + + +final class AttributeTypesImpl implements AttributeTypes { + static final AttributeTypesImpl INSTANCE = new AttributeTypesImpl(); + + private final AttributeType booleanType = AttributeTypeImpl.builder("boolean", ValueDecoders.BOOLEAN) + .op(Operation.AND, ValueDecoders.BOOLEAN, (s, a) -> a && s) + .op(Operation.NAND, ValueDecoders.BOOLEAN, (s, a) -> !a || !s) + .op(Operation.OR, ValueDecoders.BOOLEAN, (s, a) -> a || s) + .op(Operation.NOR, ValueDecoders.BOOLEAN, (s, a) -> !a && !s) + .op(Operation.XOR, ValueDecoders.BOOLEAN, (s, a) -> a ^ s) + .op(Operation.XNOR, ValueDecoders.BOOLEAN, (s, a) -> a == s) + .build(); + + private final AttributeType triState = AttributeTypeImpl.builder("tri_state", ValueDecoders.TRI_STATE).build(); + + private final AttributeType floatType = floatType("float"); + + private final AttributeType angleDegrees = floatType("angle_degrees"); + + private final AttributeType rgbColor = AttributeTypeImpl.builder("rgb_color", ValueDecoders.RGB) + .op(Operation.ALPHA_BLEND, ValueDecoders.ARGB, AttributeTypesImpl::rgbAlphaBlend) + .op(Operation.ADD, ValueDecoders.RGB, (s, a) -> new Color(Math.min(s.r() + a.r(), 1f), Math.min(s.g() + a.g(), 1f), + Math.min(s.b() + a.b(), 1f), 1f)) + .op(Operation.SUBTRACT, ValueDecoders.RGB, (s, a) -> new Color(Math.max(s.r() - a.r(), 0f), Math.max(s.g() - a.g(), 0f), + Math.max(s.b() - a.b(), 0f), 1f)) + .op(Operation.MULTIPLY, ValueDecoders.RGB, (s, a) -> multiply(s, a, false)) + .op(Operation.BLEND_TO_GRAY, ValueDecoders.BLEND_TO_GRAY, AttributeTypesImpl::blendToGray) + .build(); + + private final AttributeType argbColor = AttributeTypeImpl.builder("argb_color", ValueDecoders.ARGB) + .op(Operation.ALPHA_BLEND, ValueDecoders.ARGB, AttributeTypesImpl::argbAlphaBlend) + .op(Operation.ADD, ValueDecoders.RGB, (s, a) -> new Color(Math.min(s.r() + a.r(), 1f), Math.min(s.g() + a.g(), 1f), + Math.min(s.b() + a.b(), 1f), s.a())) + .op(Operation.SUBTRACT, ValueDecoders.RGB, (s, a) -> new Color(Math.max(s.r() - a.r(), 0f), Math.max(s.g() - a.g(), 0f), + Math.max(s.b() - a.b(), 0f), s.a())) + .op(Operation.MULTIPLY, ValueDecoders.ARGB, (s, a) -> multiply(s, a, true)) + .op(Operation.BLEND_TO_GRAY, ValueDecoders.BLEND_TO_GRAY, AttributeTypesImpl::blendToGray) + .build(); + + private final AttributeType integer = integerType("integer"); + + private final AttributeType integerOverrideOnly = AttributeTypeImpl.builder("integer_override_only", ValueDecoders.INT) + .build(); + + private final Map> identifiers = new ConcurrentHashMap<>(); + + private final Map>> identifiersOrTags = new ConcurrentHashMap<>(); + + private AttributeTypesImpl() { } + + @Override + public AttributeType booleanType() { + return booleanType; + } + + @Override + public AttributeType triState() { + return triState; + } + + @Override + public AttributeType floatType() { + return floatType; + } + + @Override + public AttributeType angleDegrees() { + return angleDegrees; + } + + @Override + public AttributeType rgbColor() { + return rgbColor; + } + + @Override + public AttributeType argbColor() { + return argbColor; + } + + @Override + public AttributeType integer() { + return integer; + } + + @Override + public AttributeType integerOverrideOnly() { + return integerOverrideOnly; + } + + @Override + public AttributeType identifier(String defaultNamespace) { + return identifiers.computeIfAbsent(defaultNamespace, + ns -> AttributeTypeImpl.builder("identifier", ValueDecoders.identifier(ns)).build()); + } + + @Override + public AttributeType> identifierOrTag(String defaultNamespace) { + return identifiersOrTags.computeIfAbsent(defaultNamespace, + ns -> AttributeTypeImpl.builder("identifier_or_tag", ValueDecoders.identifierOrTag(ns)).build()); + } + + @Override + public & StringIdentifiable> AttributeType enumType(String id, Class type) { + return AttributeTypeImpl.builder(id, ValueDecoders.identifiableEnum(id.replace('_', ' '), type)).build(); + } + + private static AttributeType floatType(String id) { + return AttributeTypeImpl.builder(id, ValueDecoders.FLOAT) + .op(Operation.ALPHA_BLEND, ValueDecoders.FLOAT_WITH_ALPHA, (s, a) -> s + a.alpha() * (a.value() - s)) + .op(Operation.ADD, ValueDecoders.FLOAT, (s, a) -> s + a) + .op(Operation.SUBTRACT, ValueDecoders.FLOAT, (s, a) -> s - a) + .op(Operation.MULTIPLY, ValueDecoders.FLOAT, (s, a) -> s * a) + .op(Operation.MINIMUM, ValueDecoders.FLOAT, (s, a) -> Math.min(s, a)) + .op(Operation.MAXIMUM, ValueDecoders.FLOAT, (s, a) -> Math.max(s, a)) + .composable(Operation.ADD, Float::sum) + .composable(Operation.MULTIPLY, (a, b) -> a * b) + .build(); + } + + private static AttributeType integerType(String id) { + return AttributeTypeImpl.builder(id, ValueDecoders.INT) + .op(Operation.ADD, ValueDecoders.INT, (s, a) -> s + a) + .op(Operation.SUBTRACT, ValueDecoders.INT, (s, a) -> s - a) + .op(Operation.MULTIPLY, ValueDecoders.INT, (s, a) -> s * a) + .op(Operation.MINIMUM, ValueDecoders.INT, (s, a) -> Math.min(s, a)) + .op(Operation.MAXIMUM, ValueDecoders.INT, (s, a) -> Math.max(s, a)) + .composable(Operation.ADD, Integer::sum) + .composable(Operation.MULTIPLY, (a, b) -> a * b) + .build(); + } + + private static float lerp(float t, float from, float to) { + return from + t * (to - from); + } + + private static float clamp01(float v) { + return Math.max(0f, Math.min(1f, v)); + } + + private static boolean white(Color c, boolean withAlpha) { + return c.r() == 1f && c.g() == 1f && c.b() == 1f && (!withAlpha || c.a() == 1f); + } + + private static Color multiply(Color s, Color a, boolean withAlpha) { + if(white(s, withAlpha)) return a; + if(white(a, withAlpha)) return s; + return new Color(s.r() * a.r(), s.g() * a.g(), s.b() * a.b(), withAlpha ? s.a() * a.a() : 1f); + } + + private static Color rgbAlphaBlend(Color dst, Color src) { + if(src.a() == 0f) return dst; + return new Color(lerp(src.a(), dst.r(), src.r()), lerp(src.a(), dst.g(), src.g()), lerp(src.a(), dst.b(), src.b()), 1f); + } + + private static Color argbAlphaBlend(Color dst, Color src) { + float sa = src.a(); + if(sa == 1f) return src; + if(sa == 0f) return dst; + float a = sa + dst.a() * (1f - sa); + return new Color((src.r() * sa + dst.r() * (a - sa)) / a, (src.g() * sa + dst.g() * (a - sa)) / a, + (src.b() * sa + dst.b() * (a - sa)) / a, a); + } + + private static Color blendToGray(Color s, BlendToGray arg) { + float g = 0.3f * s.r() + 0.59f * s.g() + 0.11f * s.b(); + float grey = clamp01(g * arg.brightness()); + return new Color(lerp(arg.factor(), s.r(), grey), lerp(arg.factor(), s.g(), grey), lerp(arg.factor(), s.b(), grey), s.a()); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/PlainDecodeContext.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/PlainDecodeContext.java new file mode 100644 index 000000000..58c15787d --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/PlainDecodeContext.java @@ -0,0 +1,63 @@ +package com.dfsek.terra.world.attribute; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; + +import static com.dfsek.terra.world.attribute.ValueDecoders.got; + + +final class PlainDecodeContext implements DecodeContext { + static final PlainDecodeContext INSTANCE = new PlainDecodeContext(); + + private PlainDecodeContext() { } + + private static Class rawClass(Type type) { + if(type instanceof Class c) return c; + if(type instanceof ParameterizedType p && p.getRawType() instanceof Class c) return c; + return null; + } + + @Override + public Object resolve(Object raw) { + return raw; + } + + @Override + @SuppressWarnings("unchecked") + public V load(Type type, Object raw) throws DecodeException { + Class c = rawClass(type); + Object value; + if(c == Object.class) value = raw; + else if(c == Float.class) value = number(raw).floatValue(); + else if(c == Double.class) value = number(raw).doubleValue(); + else if(c == Integer.class) { + if(!(raw instanceof Number n)) throw new DecodeException("expected an integer, got " + got(raw)); + value = ValueDecoders.integer(n, raw); + } else if(c == Boolean.class) { + if(!(raw instanceof Boolean)) throw new DecodeException("expected a boolean (true or false), got " + got(raw)); + value = raw; + } else if(c == String.class) { + if(!(raw instanceof String)) throw new DecodeException("expected a string, got " + got(raw)); + value = raw; + } else if(c == List.class) { + if(!(raw instanceof List)) throw new DecodeException("expected a list, got " + got(raw)); + value = raw; + } else if(c == Map.class) { + if(!(raw instanceof Map)) throw new DecodeException("expected an object, got " + got(raw)); + value = raw; + } else { + throw new DecodeException("cannot load this kind of value"); + } + return (V) value; + } + + private static Number number(Object raw) throws DecodeException { + if(raw instanceof Number n) return n; + throw new DecodeException("expected a number, got " + got(raw)); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/ValueDecoders.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/ValueDecoders.java new file mode 100644 index 000000000..48d5c5ae0 --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/ValueDecoders.java @@ -0,0 +1,412 @@ +package com.dfsek.terra.world.attribute; + +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.StringIdentifiable; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.util.reflection.TypeKey; +import com.dfsek.terra.api.world.attribute.AttributeCodec; +import com.dfsek.terra.api.world.attribute.AttributeCodecs.Decoder; +import com.dfsek.terra.api.world.attribute.AttributeCodecs.Encoder; +import com.dfsek.terra.api.world.attribute.AttributeCodecs.ObjectReader; +import com.dfsek.terra.api.world.attribute.AttributeCodecs.ObjectWriter; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.RawValue; +import com.dfsek.terra.api.world.attribute.value.BlendToGray; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.api.world.attribute.value.FloatWithAlpha; +import com.dfsek.terra.api.world.attribute.value.TriState; + + +/** + * Colours encode as hex, or as float channels when a channel isn't a multiple of 1/255. + */ +final class ValueDecoders { + private static final Type LIST = new TypeKey>() { }.getType(); + private static final Type MAP = new TypeKey>() { }.getType(); + + private ValueDecoders() { } + + private record Codec(Decoder decoder, Encoder encoder) implements AttributeCodec { + @Override + public T decode(Object raw, DecodeContext context) throws DecodeException { + return decoder.decode(raw, context); + } + + @Override + public Object encode(T value) { + return encoder.encode(value); + } + } + + static AttributeCodec codec(Decoder decoder, Encoder encoder) { + return new Codec<>(decoder, encoder); + } + + private static Object identity(T value) { + return value; + } + + static String got(Object o) { + if(o == null) return "nothing"; + if(o instanceof String s) return "\"" + s + "\""; + if(o instanceof Map) return "an object"; + if(o instanceof List) return "a list"; + return String.valueOf(o); + } + + static int integer(Number n, Object raw) throws DecodeException { + if(n instanceof Integer || n instanceof Short || n instanceof Byte) return n.intValue(); + if(n instanceof Long l) { + if(l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) throw new DecodeException("expected an integer, got " + l); + return (int) (long) l; + } + try { + return exact(n).intValueExact(); + } catch(ArithmeticException | NumberFormatException e) { + throw new DecodeException("expected an integer, got " + got(raw)); + } + } + + private static BigDecimal exact(Number n) { + if(n instanceof BigDecimal d) return d; + if(n instanceof BigInteger i) return new BigDecimal(i); + if(n instanceof Double || n instanceof Float) { + double d = n.doubleValue(); + if(!Double.isFinite(d)) throw new NumberFormatException(); + return new BigDecimal(d); + } + return new BigDecimal(n.toString()); + } + + private static String string(Object raw, DecodeContext context, String expected) throws DecodeException { + Object value = context.resolve(raw); + if(!(value instanceof String)) throw new DecodeException(expected + ", got " + got(value)); + return context.load(String.class, value); + } + + static AttributeCodec string(String expected) { + return codec((raw, context) -> string(raw, context, expected), ValueDecoders::identity); + } + + private static List loadList(Object raw, DecodeContext context, String expected) throws DecodeException { + Object value = context.resolve(raw); + try { + return context.load(LIST, value); + } catch(DecodeException e) { + if(value instanceof List) throw e; + throw new DecodeException(expected + ", got " + got(value), e); + } + } + + private static Map loadMap(Object raw, DecodeContext context, String expected) throws DecodeException { + Object value = context.resolve(raw); + try { + return context.load(MAP, value); + } catch(DecodeException e) { + if(value instanceof Map) throw e; + throw new DecodeException(expected + ", got " + got(value), e); + } + } + + static final AttributeCodec BOOLEAN = codec((raw, context) -> context.load(Boolean.class, raw), ValueDecoders::identity); + + static final AttributeCodec FLOAT = codec((raw, context) -> context.load(Float.class, raw), ValueDecoders::identity); + + static final AttributeCodec DOUBLE = codec((raw, context) -> context.load(Double.class, raw), ValueDecoders::identity); + + static final AttributeCodec INT = codec((raw, context) -> { + Object value = context.resolve(raw); + if(value instanceof Number n) integer(n, value); + return context.load(Integer.class, value); + }, ValueDecoders::identity); + + static final AttributeCodec NON_NEGATIVE_INT = codec((raw, context) -> { + int i = INT.decode(raw, context); + if(i < 0) throw new DecodeException("expected a non-negative integer, got " + i); + return i; + }, ValueDecoders::identity); + + static final AttributeCodec UNIT_FLOAT = codec((raw, context) -> { + float f = FLOAT.decode(raw, context); + if(!(f >= 0f && f <= 1f)) throw new DecodeException("value " + f + " is outside [0, 1]"); + return f; + }, ValueDecoders::identity); + + static final AttributeCodec RAW = codec((raw, context) -> { + Object value = context.resolve(raw); + try { + return new RawValue(value); + } catch(IllegalArgumentException e) { + throw new DecodeException(e.getMessage(), e); + } + }, RawValue::value); + + private static String expectedIdentifier(String defaultNamespace) { + return "expected an identifier like \"" + defaultNamespace + ":id\""; + } + + static AttributeCodec identifier(String defaultNamespace) { + String expected = expectedIdentifier(defaultNamespace); + return codec((raw, context) -> { + String s = string(raw, context, expected); + if(s.startsWith("#")) throw new DecodeException("expected an identifier, not a tag, got " + got(s)); + try { + return RegistryKey.parse(s, defaultNamespace); + } catch(IllegalArgumentException e) { + throw new DecodeException(expected + ", got " + got(s), e); + } + }, RegistryKey::toString); + } + + static AttributeCodec> identifierOrTag(String defaultNamespace) { + String expected = expectedIdentifier(defaultNamespace); + return codec((raw, context) -> { + String s = string(raw, context, expected); + try { + if(s.startsWith("#")) return Either.right(TagKey.parse(s, defaultNamespace)); + return Either.left(RegistryKey.parse(s, defaultNamespace)); + } catch(IllegalArgumentException e) { + throw new DecodeException(expected + ", got " + got(s), e); + } + }, either -> either.hasLeft() ? either.getLeft().orElseThrow().toString() : either.getRight().orElseThrow().toString()); + } + + private static Object colorParts(Object value, DecodeContext context) throws DecodeException { + if(value instanceof String) return context.load(String.class, value); + if(value instanceof Number) return context.load(Double.class, value); + if(value instanceof List) { + List channels = context.load(LIST, value); + List out = new ArrayList<>(channels.size()); + for(Object channel : channels) out.add(context.load(Float.class, channel)); + return out; + } + return value; + } + + private static boolean hexExact(float channel) { + return channel >= 0f && channel <= 1f && Math.round(channel * 255) / 255f == channel; + } + + static final AttributeCodec RGB = codec((raw, context) -> { + Object value = context.resolve(raw); + try { + return Color.parseRgb(colorParts(value, context)); + } catch(IllegalArgumentException | DecodeException e) { + throw new DecodeException("expected a color like \"#rrggbb\", got " + got(value), e); + } + }, color -> hexExact(color.r()) && hexExact(color.g()) && hexExact(color.b()) + ? String.format(Locale.ROOT, "#%06x", color.toRgbInt()) + : List.of(color.r(), color.g(), color.b())); + + static final AttributeCodec ARGB = codec((raw, context) -> { + Object value = context.resolve(raw); + try { + return Color.parseArgb(colorParts(value, context)); + } catch(IllegalArgumentException | DecodeException e) { + throw new DecodeException("expected a color like \"#aarrggbb\", got " + got(value), e); + } + }, color -> hexExact(color.r()) && hexExact(color.g()) && hexExact(color.b()) && hexExact(color.a()) + ? String.format(Locale.ROOT, "#%08x", color.toArgbInt()) + : List.of(color.r(), color.g(), color.b(), color.a())); + + @FunctionalInterface + interface Parser { + E parse(String name); + } + + static AttributeCodec stringEnum(String what, Parser parser, Encoder encoder) { + return codec((raw, context) -> { + String s = string(raw, context, "expected a " + what + " name"); + try { + return parser.parse(s); + } catch(IllegalArgumentException e) { + throw new DecodeException(e.getMessage(), e); + } + }, encoder); + } + + static & StringIdentifiable> AttributeCodec identifiableEnum(String what, Class type) { + Map byId = new LinkedHashMap<>(); + for(E constant : type.getEnumConstants()) { + E previous = byId.put(constant.getID(), constant); + if(previous != null) { + throw new IllegalArgumentException(type.getCanonicalName() + " constants " + previous + " and " + constant + + " share the ID \"" + constant.getID() + "\""); + } + } + Map ids = Collections.unmodifiableMap(byId); + return stringEnum(what, name -> { + E value = ids.get(name); + if(value == null) throw new IllegalArgumentException("unknown " + what + " \"" + name + "\", expected one of " + ids.keySet()); + return value; + }, StringIdentifiable::getID); + } + + static final AttributeCodec TRI_STATE = triState(identifiableEnum("tri-state", TriState.class)); + + private static AttributeCodec triState(AttributeCodec byId) { + return codec((raw, context) -> { + Object resolved = context.resolve(raw); + if(resolved instanceof Boolean) return context.load(Boolean.class, resolved) ? TriState.TRUE : TriState.FALSE; + if(resolved instanceof String) return byId.decode(resolved, context); + throw new DecodeException("expected true, false or a tri-state name (\"true\", \"false\", \"default\"), got " + got(resolved)); + }, value -> switch(value) { + case TRUE -> true; + case FALSE -> false; + case DEFAULT -> byId.encode(value); + }); + } + + static final class Fields implements ObjectReader { + private final String what; + private final DecodeContext context; + private final Map map; + private final Set used = new LinkedHashSet<>(); + + Fields(String what, Object raw, DecodeContext context) throws DecodeException { + this.what = what; + this.context = context; + Map m = loadMap(raw, context, "expected an object for " + what); + Map copy = new LinkedHashMap<>(); + for(Map.Entry e : m.entrySet()) { + if(!(e.getKey() instanceof String k)) { + throw new DecodeException("keys of " + what + " must be strings, got " + got(e.getKey())); + } + copy.put(k, e.getValue()); + } + this.map = copy; + } + + @Override + public List keys() { + return List.copyOf(map.keySet()); + } + + @Override + public V required(String key, AttributeCodec codec) throws DecodeException { + if(!map.containsKey(key)) throw new DecodeException(what + " is missing required key \"" + key + "\""); + return read(key, codec); + } + + @Override + public Optional optional(String key, AttributeCodec codec) throws DecodeException { + if(!map.containsKey(key)) return Optional.empty(); + return Optional.of(read(key, codec)); + } + + @Override + public V orDefault(String key, AttributeCodec codec, V fallback) throws DecodeException { + if(!map.containsKey(key)) return fallback; + return read(key, codec); + } + + private V read(String key, AttributeCodec codec) throws DecodeException { + used.add(key); + try { + return codec.decode(map.get(key), context); + } catch(DecodeException e) { + throw new DecodeException("\"" + key + "\" of " + what + ": " + e.getMessage(), e); + } + } + + @Override + public void finish() throws DecodeException { + for(String k : map.keySet()) { + if(!used.contains(k)) throw new DecodeException("unknown key \"" + k + "\" in " + what); + } + } + } + + static final class Encoded implements ObjectWriter { + private final Map map = new LinkedHashMap<>(); + + @Override + public Encoded put(String key, AttributeCodec codec, V value) { + map.put(key, codec.encode(value)); + return this; + } + + @Override + public Encoded optional(String key, AttributeCodec codec, Optional value) { + value.ifPresent(v -> map.put(key, codec.encode(v))); + return this; + } + + @Override + public Map map() { + return map; + } + } + + static AttributeCodec> list(AttributeCodec element) { + return codec((raw, context) -> { + List l = loadList(raw, context, "expected a list"); + List out = new ArrayList<>(l.size()); + for(int i = 0; i < l.size(); i++) { + try { + out.add(element.decode(l.get(i), context)); + } catch(DecodeException e) { + throw new DecodeException("element " + i + ": " + e.getMessage(), e); + } + } + return Collections.unmodifiableList(out); + }, values -> { + List out = new ArrayList<>(values.size()); + for(V value : values) out.add(element.encode(value)); + return out; + }); + } + + static AttributeCodec> compactList(AttributeCodec element) { + AttributeCodec> asList = list(element); + return codec((raw, context) -> { + Object value = context.resolve(raw); + return value instanceof List ? asList.decode(value, context) : List.of(element.decode(value, context)); + }, asList::encode); + } + + static final AttributeCodec FLOAT_WITH_ALPHA = codec((raw, context) -> { + Object resolved = context.resolve(raw); + if(resolved instanceof Map) { + Fields f = new Fields("alpha_blend argument", resolved, context); + float value = f.required("value", FLOAT); + float alpha = f.orDefault("alpha", UNIT_FLOAT, 1f); + f.finish(); + return new FloatWithAlpha(value, alpha); + } + try { + return new FloatWithAlpha(FLOAT.decode(resolved, context), 1f); + } catch(DecodeException e) { + throw new DecodeException("expected a number or a {value, alpha} object, got " + got(resolved), e); + } + }, value -> new Encoded() + .put("value", FLOAT, value.value()) + .put("alpha", UNIT_FLOAT, value.alpha()) + .map()); + + static final AttributeCodec BLEND_TO_GRAY = codec((raw, context) -> { + Fields f = new Fields("blend_to_gray argument", raw, context); + float brightness = f.required("brightness", UNIT_FLOAT); + float factor = f.required("factor", UNIT_FLOAT); + f.finish(); + return new BlendToGray(brightness, factor); + }, value -> new Encoded() + .put("brightness", UNIT_FLOAT, value.brightness()) + .put("factor", UNIT_FLOAT, value.factor()) + .map()); +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/EntryFormat.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/EntryFormat.java new file mode 100644 index 000000000..5548b22b1 --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/EntryFormat.java @@ -0,0 +1,73 @@ +package com.dfsek.terra.world.attribute.format; + +import org.jetbrains.annotations.Nullable; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; + + +public final class EntryFormat { + private static final String MODIFIER = "modifier"; + private static final String ARGUMENT = "argument"; + private static final Set MODIFIER_KEYS = Set.of(MODIFIER, ARGUMENT); + + private EntryFormat() { } + + public static AttributeEntry decode(Attribute attribute, @Nullable Object raw, DecodeContext context) + throws DecodeException { + if(raw == null) throw new DecodeException("missing value"); + Object value = context.resolve(raw); + if(value == null) throw new DecodeException("missing value"); + if(value instanceof Map map && map.containsKey(MODIFIER)) { + return decodeModifier(attribute, map, context); + } + return AttributeEntry.override(attribute.validate(attribute.type().decode(value, context))); + } + + @SuppressWarnings("unchecked") + public static Object encode(Attribute attribute, AttributeEntry entry) { + if(entry.isOverride()) { + if(entry.argument() == null) { + throw new IllegalArgumentException("a null override has no pack-format form"); + } + return attribute.type().encode((T) entry.argument()); + } + Map encoded = new LinkedHashMap<>(); + encoded.put(MODIFIER, entry.operation().getID()); + encoded.put(ARGUMENT, attribute.type().encodeArgument(entry.operation(), entry.argument())); + return encoded; + } + + private static AttributeEntry decodeModifier(Attribute attribute, Map map, DecodeContext context) + throws DecodeException { + if(!map.keySet().equals(MODIFIER_KEYS)) { + throw new DecodeException("modifier entry must have exactly the keys \"modifier\" and \"argument\""); + } + Operation operation; + try { + operation = Operation.parse(context.load(String.class, map.get(MODIFIER))); + } catch(IllegalArgumentException e) { + throw new DecodeException(e.getMessage(), e); + } catch(DecodeException e) { + throw new DecodeException("\"modifier\": " + e.getMessage(), e); + } + if(!attribute.type().operations().contains(operation)) { + throw new DecodeException("modifier " + operation.getID() + " is not valid for " + attribute.key()); + } + Object argument = attribute.type().decodeArgument(operation, map.get(ARGUMENT), context); + if(argument == null && operation != Operation.OVERRIDE) throw new DecodeException("\"argument\": missing value"); + if(operation == Operation.OVERRIDE) { + @SuppressWarnings("unchecked") + T value = (T) argument; + attribute.validate(value); + } + return AttributeEntry.of(operation, argument); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/ScheduleFormat.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/ScheduleFormat.java new file mode 100644 index 000000000..f64fda2bb --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/format/ScheduleFormat.java @@ -0,0 +1,299 @@ +package com.dfsek.terra.world.attribute.format; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalInt; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeLookup; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule; +import com.dfsek.terra.api.world.attribute.schedule.Easing; +import com.dfsek.terra.api.world.attribute.schedule.Keyframe; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult.Problem; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleTrack; +import com.dfsek.terra.api.world.attribute.schedule.TimeMarker; + + +public final class ScheduleFormat { + private static final String CLOCK = "clock"; + private static final String PERIOD_TICKS = "period_ticks"; + private static final String TIME_MARKERS = "time_markers"; + private static final String TRACKS = "tracks"; + private static final String TICKS = "ticks"; + private static final String SHOW_IN_COMMANDS = "show_in_commands"; + private static final String MODIFIER = "modifier"; + private static final String EASE = "ease"; + private static final String CUBIC_BEZIER = "cubic_bezier"; + private static final String KEYFRAMES = "keyframes"; + private static final String VALUE = "value"; + private static final Easing LINEAR = new Easing.Named("linear"); + + private ScheduleFormat() { } + + + private static final class Invalid extends Exception { + Invalid(String message) { + super(message, null, false, false); + } + } + + + private static final class TrackDropped extends Exception { + TrackDropped(String message) { + super(message, null, false, false); + } + } + + public static ScheduleDecodeResult decode(RegistryKey id, Map raw, AttributeLookup attributes, + DecodeContext context) { + List dropped = new ArrayList<>(); + try { + AttributeSchedule schedule = readDefinition(raw, attributes, context, dropped); + return new ScheduleDecodeResult(Optional.of(schedule), dropped, Optional.empty()); + } catch(Invalid e) { + return new ScheduleDecodeResult(Optional.empty(), dropped, Optional.of(new Problem(id.toString(), e.getMessage()))); + } + } + + public static Map encode(AttributeSchedule schedule) { + Map encoded = new LinkedHashMap<>(); + encoded.put(CLOCK, schedule.clock().toString()); + schedule.periodTicks().ifPresent(period -> encoded.put(PERIOD_TICKS, period)); + if(!schedule.tracks().isEmpty()) { + Map tracks = new LinkedHashMap<>(); + schedule.tracks().forEach((attribute, track) -> tracks.put(attribute.getRegistryKey().toString(), encodeTrack(attribute, track))); + encoded.put(TRACKS, tracks); + } + if(!schedule.timeMarkers().isEmpty()) { + Map markers = new LinkedHashMap<>(); + schedule.timeMarkers().forEach((key, marker) -> { + Map encodedMarker = new LinkedHashMap<>(); + encodedMarker.put(TICKS, marker.ticks()); + if(marker.showInCommands()) encodedMarker.put(SHOW_IN_COMMANDS, true); + markers.put(key.toString(), encodedMarker); + }); + encoded.put(TIME_MARKERS, markers); + } + return encoded; + } + + private static AttributeSchedule readDefinition(Map raw, AttributeLookup attributes, DecodeContext context, + List dropped) throws Invalid { + RegistryKey clock = identifier(raw.get(CLOCK), "clock"); + + OptionalInt period = OptionalInt.empty(); + if(raw.get(PERIOD_TICKS) != null) { + int ticks = integer(raw.get(PERIOD_TICKS), "period_ticks", context); + if(ticks <= 0) throw new Invalid("period_ticks must be positive"); + period = OptionalInt.of(ticks); + } + + Map markers = new LinkedHashMap<>(); + if(raw.get(TIME_MARKERS) != null) { + for(Map.Entry entry : map(raw.get(TIME_MARKERS), "time_markers").entrySet()) { + RegistryKey marker = identifier(entry.getKey(), "time marker key"); + markers.put(marker, marker(marker, entry.getValue(), period, context)); + } + } + + Map, ScheduleTrack> tracks = new LinkedHashMap<>(); + if(raw.get(TRACKS) != null) { + for(Map.Entry entry : map(raw.get(TRACKS), "tracks").entrySet()) { + String keyString = String.valueOf(entry.getKey()); + Attribute attribute; + try { + attribute = attributes.find(keyString); + } catch(DecodeException e) { + dropped.add(new Problem(keyString, e.getMessage())); + continue; + } + try { + tracks.put(attribute, track(attribute, map(entry.getValue(), "track " + keyString), period, context)); + } catch(TrackDropped e) { + dropped.add(new Problem(keyString, e.getMessage())); + } + } + } + return new AttributeSchedule(clock, period, tracks, markers); + } + + private static TimeMarker marker(RegistryKey key, Object value, OptionalInt period, DecodeContext context) throws Invalid { + int ticks; + boolean show = false; + if(value instanceof Map map) { + if(!map.containsKey(TICKS) || !map.keySet().stream().allMatch(k -> TICKS.equals(k) || SHOW_IN_COMMANDS.equals(k))) { + throw new Invalid("time marker " + key + " must have \"ticks\" and optionally \"show_in_commands\""); + } + ticks = integer(map.get(TICKS), "time marker " + key + " ticks", context); + Object flag = map.get(SHOW_IN_COMMANDS); + if(flag != null) { + if(!(flag instanceof Boolean b)) throw new Invalid("time marker " + key + " show_in_commands must be a boolean"); + show = b; + } + } else { + ticks = integer(value, "time marker " + key, context); + } + if(ticks < 0) throw new Invalid("time marker " + key + " ticks must not be negative"); + if(period.isPresent() && ticks >= period.getAsInt()) { + throw new Invalid("time marker " + key + " ticks " + ticks + " must be less than period_ticks " + period.getAsInt()); + } + return new TimeMarker(ticks, show); + } + + private static ScheduleTrack track(Attribute attribute, Map raw, OptionalInt period, DecodeContext context) + throws Invalid, TrackDropped { + Operation operation = Operation.OVERRIDE; + if(raw.get(MODIFIER) != null) { + try { + operation = Operation.parse(String.valueOf(raw.get(MODIFIER))); + } catch(IllegalArgumentException e) { + throw new Invalid(e.getMessage()); + } + } + Easing ease = raw.get(EASE) == null ? LINEAR : easing(raw.get(EASE), context); + + if(!(raw.get(KEYFRAMES) instanceof List frames)) throw new Invalid("keyframes must be a list"); + if(frames.isEmpty()) throw new Invalid("keyframes must not be empty"); + List ticksList = new ArrayList<>(frames.size()); + int previous = Integer.MIN_VALUE; + int sameTick = 0; + for(Object frame : frames) { + if(!(frame instanceof Map map) || !map.containsKey(TICKS) || !map.containsKey(VALUE) + || !map.keySet().stream().allMatch(k -> TICKS.equals(k) || VALUE.equals(k))) { + throw new Invalid("each keyframe must have exactly \"ticks\" and \"value\""); + } + int ticks = integer(map.get(TICKS), "keyframe ticks", context); + if(ticks < 0) throw new Invalid("keyframe ticks must not be negative"); + if(ticks < previous) throw new Invalid("keyframes must be sorted by ticks"); + sameTick = ticks == previous ? sameTick + 1 : 1; + if(sameTick > 2) throw new Invalid("at most 2 keyframes may share tick " + ticks); + if(period.isPresent() && ticks > period.getAsInt()) { + throw new Invalid("keyframe ticks " + ticks + " must be within period_ticks " + period.getAsInt()); + } + previous = ticks; + ticksList.add(ticks); + } + + // From here on, a failure drops only this track. + if(!attribute.type().operations().contains(operation)) { + throw new TrackDropped("modifier " + operation.getID() + " is not valid for " + attribute.key()); + } + List decoded = new ArrayList<>(frames.size()); + for(int i = 0; i < frames.size(); i++) { + Object rawValue = ((Map) frames.get(i)).get(VALUE); + decoded.add(new Keyframe(ticksList.get(i), argument(attribute, operation, rawValue, context))); + } + return new ScheduleTrack<>(operation, decoded, ease); + } + + private static Object argument(Attribute attribute, Operation operation, Object raw, DecodeContext context) + throws TrackDropped { + try { + if(raw == null) throw new DecodeException("missing keyframe value"); + Object argument = attribute.type().decodeArgument(operation, raw, context); + if(operation == Operation.OVERRIDE) { + @SuppressWarnings("unchecked") + T value = (T) argument; + attribute.validate(value); + } + return argument; + } catch(DecodeException | RuntimeException e) { + throw new TrackDropped(e.getMessage() == null ? "unexpected error" : e.getMessage()); + } + } + + private static Easing easing(Object raw, DecodeContext context) throws Invalid { + if(raw instanceof String name) { + try { + return new Easing.Named(name); + } catch(IllegalArgumentException e) { + throw new Invalid(e.getMessage()); + } + } + if(raw instanceof Map map && map.size() == 1 && map.containsKey(CUBIC_BEZIER) + && map.get(CUBIC_BEZIER) instanceof List list && list.size() == 4) { + float[] v = new float[4]; + for(int i = 0; i < 4; i++) { + Object element = list.get(i); + float f; + if(element instanceof Number n) { + f = n.floatValue(); + } else if(element instanceof String) { + try { + f = context.load(Float.class, element); + } catch(DecodeException e) { + throw new Invalid("cubic_bezier must be a list of 4 numbers: " + e.getMessage()); + } + } else { + throw new Invalid("cubic_bezier must be a list of 4 numbers"); + } + if(!Float.isFinite(f)) throw new Invalid("cubic_bezier must be a list of 4 numbers"); + v[i] = f; + } + try { + return new Easing.CubicBezier(v[0], v[1], v[2], v[3]); + } catch(IllegalArgumentException e) { + throw new Invalid(e.getMessage()); + } + } + throw new Invalid("ease must be an easing name or {cubic_bezier: [x1, y1, x2, y2]}"); + } + + private static RegistryKey identifier(Object raw, String what) throws Invalid { + if(!(raw instanceof String string)) throw new Invalid(what + " must be an identifier string"); + if(string.startsWith("#")) throw new Invalid(what + " must not be a tag"); + try { + return RegistryKey.parseNamespaced(string); + } catch(IllegalArgumentException e) { + throw new Invalid(what + ": " + e.getMessage()); + } + } + + private static int integer(Object raw, String what, DecodeContext context) throws Invalid { + try { + return context.load(Integer.class, raw); + } catch(DecodeException e) { + throw new Invalid(what + " must be an integer: " + e.getMessage()); + } + } + + private static Map map(Object raw, String what) throws Invalid { + if(raw instanceof Map map) return map; + throw new Invalid(what + " must be a map"); + } + + private static Map encodeTrack(Attribute attribute, ScheduleTrack track) { + Map encoded = new LinkedHashMap<>(); + Operation operation = track.operation(); + if(operation != Operation.OVERRIDE) encoded.put(MODIFIER, operation.getID()); + if(!track.ease().equals(LINEAR)) encoded.put(EASE, encodeEasing(track.ease())); + List keyframes = new ArrayList<>(track.keyframes().size()); + for(int i = 0; i < track.keyframes().size(); i++) { + Keyframe keyframe = track.keyframes().get(i); + if(keyframe.argument() == null) { + throw new IllegalArgumentException("keyframe " + i + " of " + attribute.key() + ": a null value has no pack-format form"); + } + Map frame = new LinkedHashMap<>(); + frame.put(TICKS, keyframe.ticks()); + frame.put(VALUE, attribute.type().encodeArgument(operation, keyframe.argument())); + keyframes.add(frame); + } + encoded.put(KEYFRAMES, keyframes); + return encoded; + } + + private static Object encodeEasing(Easing ease) { + return switch(ease) { + case Easing.Named named -> named.name(); + case Easing.CubicBezier bezier -> Map.of(CUBIC_BEZIER, List.of(bezier.x1(), bezier.y1(), bezier.x2(), bezier.y2())); + }; + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecRoundTripTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecRoundTripTest.java new file mode 100644 index 000000000..0bcb70593 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecRoundTripTest.java @@ -0,0 +1,163 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.StringIdentifiable; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.AttributeTypes; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.world.attribute.value.BlendToGray; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.api.world.attribute.value.FloatWithAlpha; +import com.dfsek.terra.api.world.attribute.value.TriState; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + + +class AttributeCodecRoundTripTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final AttributeTypes TYPES = HANDLE.types(); + private static final DecodeContext PLAIN = HANDLE.plainContext(); + + record Case(AttributeType type, List values, Map> arguments) { } + + private static Case of(AttributeType type, List values, Object... opArgs) { + Map> arguments = new LinkedHashMap<>(); + for(int i = 0; i < opArgs.length; i += 2) arguments.put((Operation) opArgs[i], (List) opArgs[i + 1]); + return new Case<>(type, values, arguments); + } + + static List> cases() { + List floats = List.of(0.25f, -3f, 1.5e7f); + List withAlpha = List.of(new FloatWithAlpha(2f, 0.5f), new FloatWithAlpha(3f, 1f)); + List rgb = List.of(Color.rgb(0x102030), Color.rgb(0xFFFFFF), new Color(0.1f, 0.2f, 0.3f, 1f)); + List argb = List.of(Color.argb(0x80112233), Color.argb(0x00000000), new Color(0.1f, 0.2f, 0.3f, 0.4f)); + List gray = List.of(new BlendToGray(0.6f, 0.75f)); + List ints = List.of(7, -2, Integer.MAX_VALUE); + List bools = List.of(true, false); + + return List.of( + of(TYPES.booleanType(), bools, + Operation.AND, bools, Operation.NAND, bools, Operation.OR, bools, Operation.NOR, bools, Operation.XOR, bools, + Operation.XNOR, bools), + of(TYPES.triState(), List.of(TriState.TRUE, TriState.FALSE, TriState.DEFAULT)), + of(TYPES.floatType(), floats, + Operation.ALPHA_BLEND, withAlpha, Operation.ADD, floats, Operation.SUBTRACT, floats, Operation.MULTIPLY, floats, + Operation.MINIMUM, floats, Operation.MAXIMUM, floats), + of(TYPES.angleDegrees(), floats, + Operation.ALPHA_BLEND, withAlpha, Operation.ADD, floats, Operation.SUBTRACT, floats, Operation.MULTIPLY, floats, + Operation.MINIMUM, floats, Operation.MAXIMUM, floats), + of(TYPES.rgbColor(), rgb, + Operation.ALPHA_BLEND, argb, Operation.ADD, rgb, Operation.SUBTRACT, rgb, Operation.MULTIPLY, rgb, + Operation.BLEND_TO_GRAY, gray), + of(TYPES.argbColor(), argb, + Operation.ALPHA_BLEND, argb, Operation.ADD, rgb, Operation.SUBTRACT, rgb, Operation.MULTIPLY, argb, + Operation.BLEND_TO_GRAY, gray), + of(TYPES.integer(), ints, + Operation.ADD, ints, Operation.SUBTRACT, ints, Operation.MULTIPLY, ints, Operation.MINIMUM, ints, Operation.MAXIMUM, ints), + of(TYPES.integerOverrideOnly(), ints), + of(TYPES.identifier("mypack"), List.of(RegistryKey.parse("mypack:stone"), RegistryKey.parse("my.pack:A/b"))), + of(TYPES.identifierOrTag("mypack"), List.>of( + Either.left(RegistryKey.parse("mypack:stone")), Either.right(TagKey.parse("#my.pack:logs")))), + of(TYPES.enumType("test_weather", Weather.class), List.of(Weather.values()))); + } + + private enum Weather implements StringIdentifiable { + CLEAR("sunny"), + STORM("thunder"); + + private final String id; + + Weather(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } + } + + private static void assertPlain(Object encoded, String where) { + if(encoded == null || encoded instanceof Number || encoded instanceof Boolean || encoded instanceof String) return; + if(encoded instanceof List list) { + for(Object element : list) assertPlain(element, where); + return; + } + if(encoded instanceof Map m) { + m.forEach((k, v) -> { + assertTrue(k instanceof String, where + ": map key " + k + " is not a string"); + assertPlain(v, where); + }); + return; + } + fail(where + ": encoded a " + encoded.getClass().getName() + ": " + encoded); + } + + private static void assertValuesRoundTrip(Case c) throws DecodeException { + for(T value : c.values()) { + Object encoded = c.type().encode(value); + assertPlain(encoded, c.type().id()); + assertEquals(value, c.type().decode(encoded, PLAIN), c.type().id() + " via " + encoded); + } + } + + @Test + void everyCoreType() throws DecodeException { + for(Case c : cases()) assertValuesRoundTrip(c); + } + + @Test + void everyArgument() throws DecodeException { + for(Case c : cases()) { + AttributeType type = c.type(); + List unsampled = new ArrayList<>(type.operations()); + unsampled.remove(Operation.OVERRIDE); + unsampled.removeAll(c.arguments().keySet()); + assertTrue(unsampled.isEmpty(), type.id() + " has no sample argument for " + unsampled); + + Map> arguments = new LinkedHashMap<>(c.arguments()); + arguments.put(Operation.OVERRIDE, c.values()); + for(Map.Entry> e : arguments.entrySet()) { + for(Object argument : e.getValue()) { + Object encoded = type.encodeArgument(e.getKey(), argument); + assertPlain(encoded, type.id() + " " + e.getKey().getID()); + assertEquals(argument, type.decodeArgument(e.getKey(), encoded, PLAIN), + type.id() + " " + e.getKey().getID() + " via " + encoded); + } + } + } + } + + @Test + void encodeArgumentInvalidOperation() { + assertThrows(IllegalArgumentException.class, () -> TYPES.booleanType().encodeArgument(Operation.ADD, 1f)); + } + + @Test + void canonicalForms() { + assertEquals("#102030", TYPES.rgbColor().encode(Color.rgb(0x102030))); + assertEquals("#80112233", TYPES.argbColor().encode(Color.argb(0x80112233))); + assertEquals("#abcdef", TYPES.rgbColor().encode(Color.rgb(0xABCDEF))); + assertEquals("mypack:stone", TYPES.identifier("mypack").encode(RegistryKey.parse("mypack:stone"))); + assertEquals("#mypack:logs", TYPES.identifierOrTag("mypack").encode(Either.right(TagKey.parse("#mypack:logs")))); + assertEquals("mypack:stone", TYPES.identifierOrTag("mypack").encode(Either.left(RegistryKey.parse("mypack:stone")))); + assertEquals("thunder", TYPES.enumType("test_weather", Weather.class).encode(Weather.STORM)); + assertEquals(true, TYPES.triState().encode(TriState.TRUE)); + assertEquals("default", TYPES.triState().encode(TriState.DEFAULT)); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecsTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecsTest.java new file mode 100644 index 000000000..21c36baf3 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeCodecsTest.java @@ -0,0 +1,119 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import com.dfsek.terra.api.registry.key.StringIdentifiable; +import com.dfsek.terra.api.world.attribute.AttributeCodec; +import com.dfsek.terra.api.world.attribute.AttributeCodecs; +import com.dfsek.terra.api.world.attribute.AttributeCodecs.ObjectReader; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + + +class AttributeCodecsTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final AttributeCodecs CODECS = HANDLE.codecs(); + private static final DecodeContext PLAIN = HANDLE.plainContext(); + + private record Point(int x, float weight) { } + + + private static final AttributeCodec POINT = CODECS.of((raw, context) -> { + ObjectReader f = CODECS.reader("point", raw, context); + int x = f.required("x", CODECS.intCodec()); + float weight = f.orDefault("weight", CODECS.unitFloat(), 1f); + f.finish(); + return new Point(x, weight); + }, value -> CODECS.writer() + .put("x", CODECS.intCodec(), value.x()) + .put("weight", CODECS.unitFloat(), value.weight()) + .optional("label", CODECS.string("expected a label"), Optional.empty()) + .map()); + + private enum Weather implements StringIdentifiable { + CLEAR("sunny"), + STORM("thunder"); + + private final String id; + + Weather(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } + } + + private static Map map(Object... kv) { + Map m = new LinkedHashMap<>(); + for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]); + return m; + } + + @Test + void ofRoundTrips() throws DecodeException { + Point point = new Point(3, 0.5f); + Object encoded = POINT.encode(point); + assertEquals(map("x", 3, "weight", 0.5f), encoded); + assertEquals(point, POINT.decode(encoded, PLAIN)); + assertEquals(new Point(4, 1f), POINT.decode(map("x", 4), PLAIN)); + + AttributeCodec> points = CODECS.compactList(POINT); + assertEquals(List.of(point), points.decode(encoded, PLAIN)); + assertEquals(List.of(encoded), points.encode(List.of(point))); + } + + @Test + void intFailures() { + assertEquals("\"x\" of point: expected an integer, got 1.5", + assertThrows(DecodeException.class, () -> POINT.decode(map("x", 1.5), PLAIN)).getMessage()); + assertEquals("expected a non-negative integer, got -1", + assertThrows(DecodeException.class, () -> CODECS.nonNegativeInt().decode(-1, PLAIN)).getMessage()); + } + + @Test + void readerUnknownField() { + assertEquals("unknown key \"y\" in point", + assertThrows(DecodeException.class, () -> POINT.decode(map("x", 1, "y", 2), PLAIN)).getMessage()); + assertEquals("point is missing required key \"x\"", + assertThrows(DecodeException.class, () -> POINT.decode(map(), PLAIN)).getMessage()); + assertEquals("expected an object for point, got a list", + assertThrows(DecodeException.class, () -> POINT.decode(List.of(), PLAIN)).getMessage()); + } + + @Test + void enumUnknownId() throws DecodeException { + AttributeCodec weather = CODECS.enumCodec("weather", Weather.class); + assertSame(Weather.STORM, weather.decode("thunder", PLAIN)); + assertEquals("thunder", weather.encode(Weather.STORM)); + assertEquals("unknown weather \"storm\", expected one of [sunny, thunder]", + assertThrows(DecodeException.class, () -> weather.decode("storm", PLAIN)).getMessage()); + } + + @Test + void listFailingElement() { + assertEquals("element 1: expected an integer, got 2.5", + assertThrows(DecodeException.class, () -> CODECS.list(CODECS.intCodec()).decode(List.of(1, 2.5), PLAIN)).getMessage()); + } + + @Test + void describeValues() { + assertEquals("\"a\"", CODECS.describe("a")); + assertEquals("an object", CODECS.describe(Map.of())); + assertEquals("a list", CODECS.describe(List.of())); + assertEquals("nothing", CODECS.describe(null)); + assertEquals("3", CODECS.describe(3)); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeComposeTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeComposeTest.java new file mode 100644 index 000000000..4ac849b92 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeComposeTest.java @@ -0,0 +1,151 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeCodec; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.AttributeTypes; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.value.Color; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class AttributeComposeTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final AttributeTypes TYPES = HANDLE.types(); + + private static final Attribute FOG_END = attribute("test:fog_end", TYPES.floatType(), 1024f).range(0, Double.POSITIVE_INFINITY) + .build(); + private static final Attribute SUN_ANGLE = attribute("test:sun_angle", TYPES.angleDegrees(), 0f).build(); + private static final Attribute SEA_LEVEL = attribute("test:sea_level", TYPES.integer(), 63).build(); + private static final Attribute FOG_COLOR = attribute("test:fog_color", TYPES.rgbColor(), Color.rgb(0)).build(); + private static final Attribute GRASS_COLOR = attribute("test:grass_color", TYPES.rgbColor(), null).build(); + + private static Attribute.Builder attribute(String key, AttributeType type, T defaultValue) { + return HANDLE.attributeBuilder(AttributeKey.parse(key), type, defaultValue); + } + + private static AttributeEntry composed(Attribute attribute, AttributeEntry lower, AttributeEntry upper) { + return HANDLE.compose(attribute, lower, upper).orElseThrow(() -> new AssertionError("empty")); + } + + private static void assertEntry(Operation operation, Object argument, AttributeEntry entry) { + assertEquals(operation, entry.operation()); + assertEquals(argument, entry.argument()); + } + + @Test + void nullOrUpperOverride() { + assertTrue(HANDLE.compose(FOG_END, null, null).isEmpty()); + AttributeEntry lower = AttributeEntry.override(10f); + AttributeEntry upper = AttributeEntry.of(Operation.MULTIPLY, 2f); + assertSame(lower, composed(FOG_END, lower, null)); + assertSame(upper, composed(FOG_END, null, upper)); + AttributeEntry override = AttributeEntry.override(5f); + assertSame(override, composed(FOG_END, lower, override)); + assertSame(override, composed(FOG_END, AttributeEntry.of(Operation.ADD, 3f), override)); + } + + @Test + void lowerOverride() { + assertEntry(Operation.OVERRIDE, 30f, composed(FOG_END, AttributeEntry.override(10f), AttributeEntry.of(Operation.MULTIPLY, 3f))); + assertEntry(Operation.OVERRIDE, 13f, composed(FOG_END, AttributeEntry.override(10f), AttributeEntry.of(Operation.ADD, 3f))); + assertEntry(Operation.OVERRIDE, 2000f, composed(FOG_END, AttributeEntry.override(1000f), AttributeEntry.of(Operation.MULTIPLY, 2f))); + Color base = Color.parseRgb("#102030"); + Color add = Color.parseRgb("#010101"); + assertEntry(Operation.OVERRIDE, FOG_COLOR.type().apply(Operation.ADD, base, add), + composed(FOG_COLOR, AttributeEntry.override(base), AttributeEntry.of(Operation.ADD, add))); + } + + @Test + void lowerNullOverride() { + AttributeEntry lower = AttributeEntry.override(null); + assertSame(lower, composed(GRASS_COLOR, lower, AttributeEntry.of(Operation.MULTIPLY, Color.parseRgb("#808080")))); + } + + @Test + void builtinTypesCompose() { + assertEntry(Operation.ADD, 5f, composed(FOG_END, AttributeEntry.of(Operation.ADD, 2f), AttributeEntry.of(Operation.ADD, 3f))); + assertEntry(Operation.MULTIPLY, 6f, + composed(FOG_END, AttributeEntry.of(Operation.MULTIPLY, 2f), AttributeEntry.of(Operation.MULTIPLY, 3f))); + assertEntry(Operation.ADD, 50f, composed(SUN_ANGLE, AttributeEntry.of(Operation.ADD, 20f), AttributeEntry.of(Operation.ADD, 30f))); + assertEntry(Operation.MULTIPLY, 1.5f, + composed(SUN_ANGLE, AttributeEntry.of(Operation.MULTIPLY, 0.5f), AttributeEntry.of(Operation.MULTIPLY, 3f))); + assertEntry(Operation.ADD, 7, composed(SEA_LEVEL, AttributeEntry.of(Operation.ADD, 3), AttributeEntry.of(Operation.ADD, 4))); + assertEntry(Operation.MULTIPLY, 12, + composed(SEA_LEVEL, AttributeEntry.of(Operation.MULTIPLY, 3), AttributeEntry.of(Operation.MULTIPLY, 4))); + } + + private static final AttributeCodec INT_CODEC = new AttributeCodec<>() { + @Override + public Integer decode(Object raw, DecodeContext context) throws DecodeException { + return context.load(Integer.class, raw); + } + + @Override + public Object encode(Integer value) { + return value; + } + }; + + private static Attribute counter(AttributeType type) { + return HANDLE.attributeBuilder(AttributeKey.parse("test:counter"), type, 0).build(); + } + + @Test + void addonTypeComposes() { + AttributeType composable = HANDLE.typeBuilder("test:counter", INT_CODEC) + .op(Operation.ADD, INT_CODEC, Integer::sum) + .composable(Operation.ADD, Integer::sum) + .build(); + assertEntry(Operation.ADD, 5, composed(counter(composable), AttributeEntry.of(Operation.ADD, 2), AttributeEntry.of(Operation.ADD, 3))); + + AttributeType plain = HANDLE.typeBuilder("test:counter", INT_CODEC).op(Operation.ADD, INT_CODEC, Integer::sum).build(); + assertTrue(HANDLE.compose(counter(plain), AttributeEntry.of(Operation.ADD, 2), AttributeEntry.of(Operation.ADD, 3)).isEmpty()); + } + + @Test + void composerReturningNull() { + AttributeType broken = HANDLE.typeBuilder("test:counter", INT_CODEC) + .op(Operation.ADD, INT_CODEC, Integer::sum) + .composable(Operation.ADD, (a, b) -> null) + .build(); + NullPointerException e = assertThrows(NullPointerException.class, () -> broken.compose(Operation.ADD, 2, 3)); + assertEquals("composer for add of test:counter returned null", e.getMessage()); + } + + @Test + void composableWithoutOperation() { + AttributeType.Builder builder = HANDLE.typeBuilder("test:counter", INT_CODEC); + assertThrows(IllegalArgumentException.class, () -> builder.composable(Operation.ADD, Integer::sum)); + assertThrows(IllegalArgumentException.class, () -> builder.composable(Operation.OVERRIDE, (a, b) -> b)); + } + + @Test + @SuppressWarnings("unchecked") + void composedResolvesLikeLayers() { + AttributeEntry pack = AttributeEntry.override(60); + AttributeEntry lower = AttributeEntry.of(Operation.ADD, 3); + AttributeEntry upper = AttributeEntry.of(Operation.ADD, -10); + assertEquals(HANDLE.resolve(SEA_LEVEL, pack, lower, upper), HANDLE.resolve(SEA_LEVEL, pack, composed(SEA_LEVEL, lower, upper))); + } + + @Test + void notComposable() { + assertTrue(HANDLE.compose(FOG_END, AttributeEntry.of(Operation.ADD, 2f), AttributeEntry.of(Operation.MULTIPLY, 3f)).isEmpty()); + assertTrue(HANDLE.compose(FOG_END, AttributeEntry.of(Operation.MINIMUM, 2f), AttributeEntry.of(Operation.MINIMUM, 3f)).isEmpty()); + assertTrue(HANDLE.compose(FOG_END, AttributeEntry.of(Operation.SUBTRACT, 2f), AttributeEntry.of(Operation.SUBTRACT, 3f)).isEmpty()); + Color add = Color.parseRgb("#010101"); + assertTrue(HANDLE.compose(FOG_COLOR, AttributeEntry.of(Operation.ADD, add), AttributeEntry.of(Operation.ADD, add)).isEmpty()); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeIndexTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeIndexTest.java new file mode 100644 index 000000000..7cf013bc2 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeIndexTest.java @@ -0,0 +1,51 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; + +import java.util.Set; + +import com.dfsek.terra.api.registry.CheckedRegistry; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.registry.CheckedRegistryImpl; +import com.dfsek.terra.registry.OpenRegistryImpl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class AttributeIndexTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + + private static Attribute build(String key) { + return HANDLE.attributeBuilder(AttributeKey.parse(key), HANDLE.types().floatType(), 0f).build(); + } + + @Test + void denseIndices() { + Attribute a = build("test:a"); + Attribute b = build("test:b"); + Attribute c = build("test:c"); + assertEquals(3, Set.of(a.index(), b.index(), c.index()).size()); + assertEquals(a.index() + 1, b.index()); + assertEquals(b.index() + 1, c.index()); + assertTrue(a.index() >= 0); + assertTrue(HANDLE.attributeCount() >= c.index() + 1, () -> HANDLE.attributeCount() + " <= " + c.index()); + } + + @Test + void lookupIsTyped() { + CheckedRegistry> registry = new CheckedRegistryImpl<>(new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE)); + Attribute fog = build("test:visual/fog"); + registry.register(fog.getRegistryKey(), fog); + + assertSame(fog, fog.key().lookup(registry).orElseThrow()); + AttributeKey lookalike = AttributeKey.parse("test:visual/fog"); + assertEquals(fog.key(), lookalike); + assertTrue(lookalike.lookup(registry).isEmpty()); + assertSame(fog, registry.get(lookalike.getRegistryKey()).orElseThrow()); + assertTrue(AttributeKey.parse("test:nothing").lookup(registry).isEmpty()); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeLayersTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeLayersTest.java new file mode 100644 index 000000000..d9c52515e --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeLayersTest.java @@ -0,0 +1,88 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Proxy; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeParents; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.AttributeTypes; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.PackAttributes; +import com.dfsek.terra.api.world.attribute.value.Color; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +@SuppressWarnings("unchecked") +class AttributeLayersTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final AttributeTypes TYPES = HANDLE.types(); + + private static final Attribute FOG_END = attribute("test:fog_end", TYPES.floatType(), 1024f) + .range(0, Double.POSITIVE_INFINITY).build(); + private static final Attribute WATER_FOG_END = attribute("test:water_fog_end", TYPES.floatType(), 96f) + .range(0, Double.POSITIVE_INFINITY).build(); + private static final Attribute FOG_COLOR = attribute("test:fog_color", TYPES.rgbColor(), Color.rgb(0)).build(); + private static final Attribute FOLIAGE_COLOR = attribute("test:foliage_color", TYPES.rgbColor(), null).build(); + private static final Attribute STAR_BRIGHTNESS = attribute("test:star_brightness", TYPES.floatType(), 0f).range(0, 1).build(); + + private static Attribute.Builder attribute(String key, AttributeType type, T defaultValue) { + return HANDLE.attributeBuilder(AttributeKey.parse(key), type, defaultValue); + } + + @Test + void layerOrder() { + assertEquals(1024f, HANDLE.resolve(FOG_END), "default alone"); + assertEquals(5f, HANDLE.resolve(FOG_END, null, AttributeEntry.override(5f), null), "null layers are skipped"); + assertEquals(1f, HANDLE.resolve(STAR_BRIGHTNESS, AttributeEntry.override(2f)), "the range clamps the result"); + assertEquals(81.6f, HANDLE.resolve(WATER_FOG_END, AttributeEntry.override(96f), AttributeEntry.of(Operation.MULTIPLY, 0.85f)), + 1e-3f, "pack then biome multiply"); + + AttributeEntry pack = AttributeEntry.override(Color.rgb(0x808080)); + AttributeEntry vanilla = AttributeEntry.override(Color.rgb(0xc0d8ff)); + AttributeEntry terra = AttributeEntry.of(Operation.ADD, Color.rgb(0x101010)); + assertEquals(0xc0d8ff, HANDLE.resolve(FOG_COLOR, pack, vanilla).toRgbInt(), "vanilla parent wins over the pack override"); + assertEquals(0xd0e8ff, HANDLE.resolve(FOG_COLOR, pack, vanilla, terra).toRgbInt(), "Terra modifier on the vanilla parent"); + } + + @Test + void modifiersOnNull() { + AttributeEntry add = AttributeEntry.of(Operation.ADD, Color.rgb(0x101010)); + assertNull(HANDLE.resolve(FOLIAGE_COLOR)); + assertNull(HANDLE.resolve(FOLIAGE_COLOR, add)); + assertEquals(0x305070, HANDLE.resolve(FOLIAGE_COLOR, add, AttributeEntry.override(Color.rgb(0x204060)), add).toRgbInt()); + } + + @Test + void parentsNoneIsEmpty() { + assertNull(AttributeParents.NONE.biomeOrNull(null, FOG_END)); + assertNull(AttributeParents.NONE.packOrNull(null, FOG_END)); + } + + @Test + void packAttributesFromContext() { + Context context = new Context(); + ConfigPack pack = (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class[]{ ConfigPack.class }, + (proxy, method, args) -> switch(method.getName()) { + case "getContext" -> context; + default -> throw new UnsupportedOperationException(method.getName()); + }); + assertTrue(HANDLE.pack(pack).isEmpty()); + PackAttributes attributes = (PackAttributes) Proxy.newProxyInstance(PackAttributes.class.getClassLoader(), + new Class[]{ PackAttributes.class }, (proxy, method, args) -> { + throw new UnsupportedOperationException(method.getName()); + }); + context.put(Context.create(PackAttributes.class), attributes); + assertSame(attributes, HANDLE.pack(pack).orElseThrow()); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeTypesTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeTypesTest.java new file mode 100644 index 000000000..cc713e826 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/AttributeTypesTest.java @@ -0,0 +1,382 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Named; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.StringIdentifiable; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.AttributeCodec; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.AttributeTypes; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.api.world.attribute.value.TriState; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.params.provider.Arguments.arguments; + + +public class AttributeTypesTest { + private static final float EPS = 1e-6f; + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final AttributeTypes TYPES = HANDLE.types(); + private static final DecodeContext PLAIN = HANDLE.plainContext(); + private static final AttributeType WEATHER = TYPES.enumType("test_weather", Weather.class); + private static final AttributeCodec FLOAT = new AttributeCodec<>() { + @Override + public Float decode(Object raw, DecodeContext context) throws DecodeException { + return context.load(Float.class, raw); + } + + @Override + public Object encode(Float value) { + return value; + } + }; + + private enum Weather implements StringIdentifiable { + CLEAR("sunny"), + STORM("thunder"); + + private final String id; + + Weather(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } + } + + private static T mod(AttributeType type, Operation op, T subject, Object rawArg) throws DecodeException { + return type.apply(op, subject, type.decodeArgument(op, rawArg, PLAIN)); + } + + private static void assertColor(float r, float g, float b, float a, Color c) { + assertEquals(r, c.r(), EPS, "r"); + assertEquals(g, c.g(), EPS, "g"); + assertEquals(b, c.b(), EPS, "b"); + assertEquals(a, c.a(), EPS, "a"); + } + + private static void assertValue(Object expected, Object actual) { + if(expected instanceof Color e && actual instanceof Color c) assertColor(e.r(), e.g(), e.b(), e.a(), c); + else if(expected instanceof Float e && actual instanceof Float f) assertEquals(e, f, EPS); + else assertEquals(expected, actual); + } + + private static Map map(Object... kv) { + Map m = new LinkedHashMap<>(); + for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]); + return m; + } + + private static Named> named(AttributeType type) { + return Named.of(type.id(), type); + } + + private static Color color(float r, float g, float b, float a) { + return new Color(r, g, b, a); + } + + @Test + public void booleanOps() throws DecodeException { + AttributeType t = TYPES.booleanType(); + for(boolean s : new boolean[]{ true, false }) { + for(boolean a : new boolean[]{ true, false }) { + assertEquals(a && s, mod(t, Operation.AND, s, a)); + assertEquals(!a || !s, mod(t, Operation.NAND, s, a)); + assertEquals(a || s, mod(t, Operation.OR, s, a)); + assertEquals(!a && !s, mod(t, Operation.NOR, s, a)); + assertEquals(a ^ s, mod(t, Operation.XOR, s, a)); + assertEquals(a == s, mod(t, Operation.XNOR, s, a)); + } + } + assertEquals(true, mod(t, Operation.OVERRIDE, false, true)); + } + + private static Arguments modifier(AttributeType type, Operation op, Object subject, Object rawArg, Object expected) { + return arguments(named(type), op, subject, rawArg, expected); + } + + static Stream modifiers() { + float sa = 0.5f; + float da = 0.2f; + float a = sa + da * (1 - sa); + Color dst = color(0.8f, 0.2f, 0.4f, 0.2f); + return Stream.of( + modifier(TYPES.floatType(), Operation.ADD, 5f, 2.5, 7.5f), + modifier(TYPES.floatType(), Operation.SUBTRACT, 5f, 2.5, 2.5f), + modifier(TYPES.floatType(), Operation.MULTIPLY, 5f, 2, 10f), + modifier(TYPES.floatType(), Operation.MINIMUM, 5f, 2.5, 2.5f), + modifier(TYPES.floatType(), Operation.MAXIMUM, 5f, 2.5, 5f), + modifier(TYPES.angleDegrees(), Operation.ADD, 1f, 0.5, 1.5f), + modifier(TYPES.floatType(), Operation.ALPHA_BLEND, 2f, 8, 8f), + modifier(TYPES.floatType(), Operation.ALPHA_BLEND, 2f, map("value", 6, "alpha", 0.5), 4f), + modifier(TYPES.floatType(), Operation.ALPHA_BLEND, 2f, map("value", 6), 6f), + modifier(TYPES.integer(), Operation.ADD, 5, 3, 8), + modifier(TYPES.integer(), Operation.SUBTRACT, 5, 3, 2), + modifier(TYPES.integer(), Operation.MULTIPLY, 5, 3, 15), + modifier(TYPES.integer(), Operation.MINIMUM, 5, 3, 3), + modifier(TYPES.integer(), Operation.MAXIMUM, 5, 3, 5), + modifier(TYPES.rgbColor(), Operation.ADD, color(0.5f, 0.9f, 0.1f, 1f), List.of(0.25, 0.25, 0.5), color(0.75f, 1f, 0.6f, 1f)), + modifier(TYPES.rgbColor(), Operation.SUBTRACT, color(0.5f, 0.9f, 0.1f, 1f), List.of(0.25, 0.25, 0.5), + color(0.25f, 0.65f, 0f, 1f)), + modifier(TYPES.rgbColor(), Operation.MULTIPLY, color(0.5f, 0.5f, 0.6f, 1f), List.of(0.8, 0.8, 0.8), + color(0.4f, 0.4f, 0.48f, 1f)), + modifier(TYPES.rgbColor(), Operation.MULTIPLY, color(0.3f, 0.4f, 0.5f, 1f), List.of(1, 1, 1), color(0.3f, 0.4f, 0.5f, 1f)), + modifier(TYPES.rgbColor(), Operation.MULTIPLY, color(1f, 1f, 1f, 1f), List.of(0.3, 0.4, 0.5), color(0.3f, 0.4f, 0.5f, 1f)), + modifier(TYPES.rgbColor(), Operation.ALPHA_BLEND, color(0f, 0f, 1f, 1f), List.of(1, 0, 0, 0), color(0f, 0f, 1f, 1f)), + modifier(TYPES.rgbColor(), Operation.ALPHA_BLEND, color(0f, 0f, 1f, 1f), List.of(1, 0, 0, 0.5), color(0.5f, 0f, 0.5f, 1f)), + modifier(TYPES.rgbColor(), Operation.ALPHA_BLEND, color(0f, 0f, 1f, 1f), "#ffff0000", color(1f, 0f, 0f, 1f)), + modifier(TYPES.rgbColor(), Operation.BLEND_TO_GRAY, color(1f, 0f, 0f, 1f), map("brightness", 0.6, "factor", 0.75), + color(0.385f, 0.135f, 0.135f, 1f)), + modifier(TYPES.argbColor(), Operation.ADD, color(0.5f, 0.5f, 0.5f, 0.3f), List.of(0.25, 0.25, 0.75), + color(0.75f, 0.75f, 1f, 0.3f)), + modifier(TYPES.argbColor(), Operation.SUBTRACT, color(0.5f, 0.5f, 0.5f, 0.3f), List.of(0.25, 0.25, 0.75), + color(0.25f, 0.25f, 0f, 0.3f)), + modifier(TYPES.argbColor(), Operation.MULTIPLY, color(0.5f, 0.5f, 0.5f, 0.5f), List.of(0.5, 0.5, 0.5, 0.3), + color(0.25f, 0.25f, 0.25f, 0.15f)), + modifier(TYPES.argbColor(), Operation.MULTIPLY, color(0.2f, 0.3f, 0.4f, 0.5f), List.of(1, 1, 1, 1), + color(0.2f, 0.3f, 0.4f, 0.5f)), + modifier(TYPES.argbColor(), Operation.MULTIPLY, color(1f, 1f, 1f, 1f), List.of(0.2, 0.3, 0.4, 0.5), + color(0.2f, 0.3f, 0.4f, 0.5f)), + modifier(TYPES.argbColor(), Operation.ALPHA_BLEND, dst, List.of(0, 1, 0, 1), color(0f, 1f, 0f, 1f)), + modifier(TYPES.argbColor(), Operation.ALPHA_BLEND, dst, List.of(0, 1, 0, 0), dst), + modifier(TYPES.argbColor(), Operation.ALPHA_BLEND, dst, List.of(0, 1, 0, 0.5), + color((0f * sa + 0.8f * (a - sa)) / a, (1f * sa + 0.2f * (a - sa)) / a, (0f * sa + 0.4f * (a - sa)) / a, a)), + modifier(TYPES.argbColor(), Operation.BLEND_TO_GRAY, color(1f, 0f, 0f, 0.7f), map("brightness", 0.6, "factor", 0.75), + color(0.385f, 0.135f, 0.135f, 0.7f)), + modifier(TYPES.rgbColor(), Operation.OVERRIDE, color(0f, 0f, 0f, 1f), "#ff0000", color(1f, 0f, 0f, 1f)), + modifier(WEATHER, Operation.OVERRIDE, Weather.CLEAR, "thunder", Weather.STORM)); + } + + @ParameterizedTest + @MethodSource + @SuppressWarnings("unchecked") + public void modifiers(AttributeType type, Operation op, Object subject, Object rawArg, Object expected) + throws DecodeException { + assertValue(expected, mod(type, op, subject, rawArg)); + } + + private static Arguments invalid(AttributeType type, Operation op, Object raw, String message) { + return arguments(named(type), op, raw, message); + } + + static Stream invalidArguments() { + return Stream.of( + invalid(TYPES.booleanType(), Operation.MULTIPLY, true, "modifier multiply is not valid for boolean"), + invalid(TYPES.floatType(), Operation.AND, true, null), + invalid(TYPES.triState(), Operation.ADD, 1, null), + invalid(TYPES.floatType(), Operation.ALPHA_BLEND, map("value", 6, "alpha", 1.5), null), + invalid(TYPES.floatType(), Operation.ALPHA_BLEND, map("value", 6, "bogus", 1), null), + invalid(TYPES.floatType(), Operation.ALPHA_BLEND, map("alpha", 0.5), null), + invalid(TYPES.rgbColor(), Operation.BLEND_TO_GRAY, map("brightness", 1.5, "factor", 0.5), null), + invalid(TYPES.rgbColor(), Operation.BLEND_TO_GRAY, map("brightness", 0.5), null), + invalid(TYPES.rgbColor(), Operation.BLEND_TO_GRAY, map("brightness", 0.5, "factor", 0.5, "extra", 1), null), + invalid(TYPES.argbColor(), Operation.ADD, List.of(0.1, 0.1, 0.1, 0.1), null)); + } + + @ParameterizedTest + @MethodSource + public void invalidArguments(AttributeType type, Operation op, Object raw, String message) { + DecodeException e = assertThrows(DecodeException.class, () -> type.decodeArgument(op, raw, PLAIN)); + if(message != null) assertEquals(message, e.getMessage()); + } + + private static Arguments decode(AttributeType type, Object raw, Object expected) { + return arguments(named(type), raw, expected); + } + + static Stream decodes() { + return Stream.of( + decode(TYPES.integer(), 7, 7), + decode(TYPES.integer(), 7L, 7), + decode(TYPES.integer(), (short) 7, 7), + decode(TYPES.integer(), (byte) 7, 7), + decode(TYPES.integer(), 7.0, 7), + decode(TYPES.integer(), 7.0f, 7), + decode(TYPES.integer(), BigInteger.valueOf(7), 7), + decode(TYPES.integer(), new BigDecimal("7.00"), 7), + decode(TYPES.integer(), (double) Integer.MIN_VALUE, Integer.MIN_VALUE), + decode(TYPES.integer(), BigInteger.valueOf(Integer.MAX_VALUE), Integer.MAX_VALUE), + decode(TYPES.floatType(), 3, 3f), + decode(TYPES.floatType(), 0.25, 0.25f), + decode(TYPES.rgbColor(), "#050533", Color.rgb(0x050533)), + decode(TYPES.rgbColor(), List.of(0.1, 0.2, 0.3), color(0.1f, 0.2f, 0.3f, 1f)), + decode(TYPES.rgbColor(), 0xFF0000, color(1f, 0f, 0f, 1f)), + decode(TYPES.argbColor(), "#44112233", Color.argb(0x44112233)), + decode(TYPES.triState(), "default", TriState.DEFAULT), + decode(TYPES.triState(), true, TriState.TRUE), + decode(TYPES.identifier("mypack"), "mypack:idle", RegistryKey.parse("mypack:idle")), + decode(TYPES.identifier("mypack"), "idle", RegistryKey.parse("mypack:idle")), + decode(TYPES.identifier("mypack"), "other:idle", RegistryKey.parse("other:idle")), + decode(TYPES.identifier("mypack"), "Mod:Music.Game", RegistryKey.parse("Mod:Music.Game")), + decode(TYPES.identifierOrTag("mypack"), "stone", Either.left(RegistryKey.parse("mypack:stone"))), + decode(TYPES.identifierOrTag("mypack"), "#logs", Either.right(TagKey.parse("#mypack:logs"))), + decode(TYPES.identifierOrTag("mypack"), "#Mod:Logs", Either.right(TagKey.parse("#Mod:Logs"))), + decode(WEATHER, "sunny", Weather.CLEAR), + decode(WEATHER, "thunder", Weather.STORM)); + } + + @ParameterizedTest + @MethodSource + public void decodes(AttributeType type, Object raw, Object expected) throws DecodeException { + assertValue(expected, type.decode(raw, PLAIN)); + } + + private static Arguments reject(AttributeType type, Object raw, String message) { + return arguments(named(type), raw, message); + } + + static Stream decodeFailures() { + return Stream.of( + reject(TYPES.integer(), 4.5, "expected an integer, got 4.5"), + reject(TYPES.integer(), 99999999999L, "expected an integer, got 99999999999"), + reject(TYPES.integer(), new BigDecimal("1.5"), "expected an integer, got 1.5"), + reject(TYPES.integer(), BigInteger.valueOf(1L << 31), "expected an integer, got 2147483648"), + reject(TYPES.integer(), new BigInteger("100000000000000000000"), null), + reject(TYPES.integer(), 2147483648.0, null), + reject(TYPES.integer(), Double.NaN, null), + reject(TYPES.integer(), Float.POSITIVE_INFINITY, null), + reject(TYPES.integer(), 1.5f, null), + reject(TYPES.integer(), "4", null), + reject(TYPES.floatType(), "1.0", null), + reject(TYPES.floatType(), true, null), + reject(TYPES.booleanType(), "yes", "expected a boolean (true or false), got \"yes\""), + reject(TYPES.booleanType(), 1, null), + reject(TYPES.rgbColor(), true, "expected a color like \"#rrggbb\", got true"), + reject(TYPES.rgbColor(), "#12345", null), + reject(TYPES.rgbColor(), 0.5, null), + reject(TYPES.triState(), "maybe", null), + reject(TYPES.identifier("mypack"), "Not Valid", "expected an identifier like \"mypack:id\", got \"Not Valid\""), + reject(TYPES.identifier("mypack"), "#mypack:logs", "expected an identifier, not a tag, got \"#mypack:logs\""), + reject(TYPES.identifier("mypack"), "mypack:", null), + reject(TYPES.identifier("mypack"), 3, null), + reject(TYPES.identifierOrTag("mypack"), "#", null), + reject(WEATHER, "storm", "unknown test weather \"storm\", expected one of [sunny, thunder]"), + reject(WEATHER, "CLEAR", null), + reject(WEATHER, 1, null)); + } + + @ParameterizedTest + @MethodSource + public void decodeFailures(AttributeType type, Object raw, String message) { + DecodeException e = assertThrows(DecodeException.class, () -> type.decode(raw, PLAIN)); + if(message != null) assertEquals(message, e.getMessage()); + } + + @Test + public void builder() throws DecodeException { + AttributeType.Builder builder = HANDLE.typeBuilder("test", FLOAT); + assertThrows(IllegalArgumentException.class, () -> builder.op(Operation.OVERRIDE, FLOAT, (s, a) -> a)); + AttributeType built = builder.build(); + assertEquals(EnumSet.of(Operation.OVERRIDE), built.operations()); + builder.op(Operation.ADD, FLOAT, Float::sum); + assertEquals(EnumSet.of(Operation.OVERRIDE), built.operations()); + assertThrows(UnsupportedOperationException.class, () -> built.operations().add(Operation.ADD)); + assertThrows(DecodeException.class, () -> built.decodeArgument(Operation.ADD, 1, PLAIN)); + assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.ADD), builder.build().operations()); + assertEquals(3f, builder.build().apply(Operation.ADD, 1f, 2f), EPS); + } + + @Test + public void nestedLoads() throws DecodeException { + List seen = new ArrayList<>(); + DecodeContext recording = new DecodeContext() { + @Override + public V load(Type type, Object raw) throws DecodeException { + seen.add(raw); + return HANDLE.plainContext().load(type, raw); + } + + @Override + public Object resolve(Object raw) { + return raw; + } + }; + Map argument = map("value", 6, "alpha", 0.5); + TYPES.floatType().decodeArgument(Operation.ALPHA_BLEND, argument, recording); + TYPES.identifier("mypack").decode("mypack:thing", recording); + assertTrue(seen.contains(argument), seen.toString()); + assertTrue(seen.contains(6), seen.toString()); + assertTrue(seen.contains(0.5), seen.toString()); + assertTrue(seen.contains("mypack:thing"), seen.toString()); + } + + private static DecodeContext referencing(Map targets) { + return new DecodeContext() { + @Override + public V load(Type type, Object raw) throws DecodeException { + return HANDLE.plainContext().load(type, raw); + } + + @Override + public Object resolve(Object raw) { + if(raw instanceof String s && targets.containsKey(s)) return resolve(targets.get(s)); + if(raw instanceof Map m) { + Map out = new LinkedHashMap<>(); + m.forEach((k, v) -> out.put((String) k, resolve(v))); + return out; + } + if(raw instanceof List l) return l.stream().map(this::resolve).toList(); + return raw; + } + }; + } + + @Test + public void resolveBeforeShape() throws DecodeException { + DecodeContext context = referencing(map( + "@alpha", map("value", "@two", "alpha", 0.5), + "@two", 2, + "@yes", true, + "@channels", List.of(1, 0, 0), + "@gray", map("brightness", 0.6, "factor", 0.75))); + + AttributeType floats = TYPES.floatType(); + assertEquals(1.5f, floats.apply(Operation.ALPHA_BLEND, 1f, floats.decodeArgument(Operation.ALPHA_BLEND, "@alpha", context)), EPS); + assertEquals(TriState.TRUE, TYPES.triState().decode("@yes", context)); + assertColor(1, 0, 0, 1, TYPES.rgbColor().decode("@channels", context)); + AttributeType rgb = TYPES.rgbColor(); + assertColor(0.385f, 0.135f, 0.135f, 1f, + rgb.apply(Operation.BLEND_TO_GRAY, new Color(1f, 0f, 0f, 1f), rgb.decodeArgument(Operation.BLEND_TO_GRAY, "@gray", context))); + } + + @Test + public void plainContext() throws DecodeException { + DecodeContext plain = HANDLE.plainContext(); + Map value = map("a", List.of("$meta.yml:b")); + assertSame(value, plain.resolve(value)); + assertEquals(3f, plain.load(Float.class, 3), EPS); + assertEquals(3.0, plain.load(Double.class, 3)); + assertEquals(4, plain.load(Integer.class, 4.0)); + assertEquals("a", plain.load(String.class, "a")); + assertEquals(true, plain.load(Boolean.class, true)); + assertEquals(List.of(1), plain.load(List.class, List.of(1))); + assertEquals(Map.of("a", 1), plain.load(Map.class, Map.of("a", 1))); + assertEquals("expected a number, got \"${1}\"", + assertThrows(DecodeException.class, () -> plain.load(Float.class, "${1}")).getMessage()); + assertThrows(DecodeException.class, () -> plain.load(String.class, 1)); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/EntryFormatTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/EntryFormatTest.java new file mode 100644 index 000000000..cfe1f3c94 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/EntryFormatTest.java @@ -0,0 +1,79 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.world.attribute.AttributeCodecRoundTripTest.Case; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + + +class EntryFormatTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + + private static Attribute attribute(Case c) { + return HANDLE.attributeBuilder(AttributeKey.parse("test:" + c.type().id()), c.type(), null).build(); + } + + private static void assertRoundTrip(Case c) throws DecodeException { + Attribute attribute = attribute(c); + Map> arguments = new LinkedHashMap<>(c.arguments()); + arguments.put(Operation.OVERRIDE, c.values()); + assertEquals(c.type().operations(), arguments.keySet(), c.type().id() + " samples every operation"); + for(Map.Entry> e : arguments.entrySet()) { + for(Object argument : e.getValue()) { + AttributeEntry entry = AttributeEntry.of(e.getKey(), argument); + Object encoded = HANDLE.encodeEntry(attribute, entry); + assertEquals(entry, HANDLE.decodeEntry(attribute, encoded, HANDLE.plainContext()), + c.type().id() + " " + e.getKey().getID() + " via " + encoded); + } + } + } + + @Test + void roundTrip() throws DecodeException { + for(Case c : AttributeCodecRoundTripTest.cases()) assertRoundTrip(c); + } + + @Test + void encodeForms() { + Attribute fog = HANDLE.attributeBuilder(AttributeKey.parse("test:fog"), HANDLE.types().rgbColor(), null).build(); + assertEquals("#102030", HANDLE.encodeEntry(fog, AttributeEntry.override(Color.rgb(0x102030)))); + Attribute fogEnd = HANDLE.attributeBuilder(AttributeKey.parse("test:fog_end"), HANDLE.types().floatType(), 0f) + .build(); + assertEquals(Map.of("modifier", "multiply", "argument", 0.85f), + HANDLE.encodeEntry(fogEnd, AttributeEntry.of(Operation.MULTIPLY, 0.85f))); + } + + @Test + void encodeNullOverride() { + Attribute colour = HANDLE.attributeBuilder(AttributeKey.parse("test:sky"), HANDLE.types().rgbColor(), null).build(); + Attribute number = HANDLE.attributeBuilder(AttributeKey.parse("test:height"), HANDLE.types().floatType(), null) + .build(); + for(Attribute attribute : List.of(colour, number)) { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, + () -> HANDLE.encodeEntry(attribute, AttributeEntry.override(null))); + assertEquals("a null override has no pack-format form", e.getMessage()); + } + } + + @Test + void decodeInvalidModifier() { + Attribute flag = HANDLE.attributeBuilder(AttributeKey.parse("test:flag"), HANDLE.types().booleanType(), false) + .build(); + DecodeException e = assertThrows(DecodeException.class, + () -> HANDLE.decodeEntry(flag, Map.of("modifier", "add", "argument", 1), HANDLE.plainContext())); + assertEquals("modifier add is not valid for test:flag", e.getMessage()); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/FixedArityResolveTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/FixedArityResolveTest.java new file mode 100644 index 000000000..5af6974c4 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/FixedArityResolveTest.java @@ -0,0 +1,67 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.value.Color; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +@SuppressWarnings("unchecked") +class FixedArityResolveTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final DecodeContext PLAIN = HANDLE.plainContext(); + + private static List> choices(AttributeType type, T override, Object... modifiers) throws DecodeException { + List> choices = new ArrayList<>(Arrays.asList(null, AttributeEntry.override(override))); + for(int i = 0; i < modifiers.length; i += 2) { + Operation op = (Operation) modifiers[i]; + choices.add(AttributeEntry.of(op, type.decodeArgument(op, modifiers[i + 1], PLAIN))); + } + return choices; + } + + private static T varargs(Attribute attribute, AttributeEntry... layers) { + return HANDLE.resolve(attribute, (AttributeEntry[]) layers); + } + + private static void assertSameLayering(Attribute attribute, List> choices) { + for(AttributeEntry a : choices) { + for(AttributeEntry b : choices) { + for(AttributeEntry c : choices) { + assertEquals(varargs(attribute, a, b, c), HANDLE.resolve(attribute, a, b, c)); + for(AttributeEntry d : choices) { + assertEquals(varargs(attribute, a, b, c, d), HANDLE.resolve(attribute, a, b, c, d), + () -> List.of(String.valueOf(a), String.valueOf(b), String.valueOf(c), String.valueOf(d)).toString()); + } + } + } + } + } + + @Test + void withDefault() throws DecodeException { + AttributeType type = HANDLE.types().floatType(); + Attribute attribute = HANDLE.attributeBuilder(AttributeKey.parse("test:float"), type, 1f).range(0, 10).build(); + assertSameLayering(attribute, choices(type, 4f, Operation.ADD, 3.0, Operation.MULTIPLY, 2.0)); + } + + @Test + void withoutDefault() throws DecodeException { + AttributeType type = HANDLE.types().rgbColor(); + Attribute attribute = HANDLE.attributeBuilder(AttributeKey.parse("test:color"), type, null).build(); + assertSameLayering(attribute, choices(type, Color.parseRgb("#102030"), Operation.ADD, "#010101")); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/ScheduleFormatTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/ScheduleFormatTest.java new file mode 100644 index 000000000..3832141c1 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/ScheduleFormatTest.java @@ -0,0 +1,416 @@ +package com.dfsek.terra.world.attribute; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.lang.reflect.Type; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.OptionalInt; +import java.util.Set; +import java.util.stream.Stream; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.StringIdentifiable; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeLookup; +import com.dfsek.terra.api.world.attribute.AttributeType; +import com.dfsek.terra.api.world.attribute.AttributeTypes; +import com.dfsek.terra.api.world.attribute.DecodeContext; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule; +import com.dfsek.terra.api.world.attribute.schedule.Easing; +import com.dfsek.terra.api.world.attribute.schedule.Keyframe; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult.Problem; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleTrack; +import com.dfsek.terra.api.world.attribute.schedule.TimeMarker; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Named.named; +import static org.junit.jupiter.params.provider.Arguments.arguments; + + +class ScheduleFormatTest { + private static final RegistryKey ID = RegistryKey.parse("terra:test"); + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final AttributeTypes TYPES = HANDLE.types(); + private static final Map> ATTRIBUTES = new LinkedHashMap<>(); + private static final Attribute SUN_ANGLE = attribute("minecraft:visual/sun_angle", TYPES.angleDegrees(), 0f); + private static final Attribute MOON_PHASE = attribute("minecraft:visual/moon_phase", + TYPES.enumType("moon_phase", MoonPhase.class), MoonPhase.FULL_MOON); + private static final Attribute PATROL = attribute("minecraft:gameplay/can_pillager_patrol_spawn", TYPES.booleanType(), + true); + private static final Attribute STAR_BRIGHTNESS = HANDLE.attributeBuilder( + AttributeKey.parse("minecraft:visual/star_brightness"), TYPES.floatType(), 0f).range(0, 1).build(); + private static final AttributeLookup LOOKUP = ScheduleFormatTest::find; + private static final List ORDERED_TRACKS = List.of("minecraft:visual/water_fog_start_distance", + "minecraft:visual/sun_angle", "minecraft:visual/fog_start_distance", "minecraft:visual/star_angle", + "minecraft:visual/moon_angle", "minecraft:visual/fog_end_distance", "minecraft:visual/cloud_fog_end_distance", + "minecraft:visual/sky_fog_end_distance"); + private static final List ORDERED_MARKERS = List.of("terra:z", "terra:a", "terra:m", "terra:b", "terra:y", "terra:c", + "terra:x", "terra:d"); + + static { + ATTRIBUTES.put(STAR_BRIGHTNESS.key().toString(), STAR_BRIGHTNESS); + for(String id : ORDERED_TRACKS) { + if(!ATTRIBUTES.containsKey(id)) attribute(id, TYPES.floatType(), 0f); + } + } + + private static Attribute attribute(String key, AttributeType type, T defaultValue) { + Attribute attribute = HANDLE.attributeBuilder(AttributeKey.parse(key), type, defaultValue).build(); + ATTRIBUTES.put(key, attribute); + return attribute; + } + + private static Attribute find(String key) throws DecodeException { + Attribute attribute = ATTRIBUTES.get(key); + if(attribute == null) throw new DecodeException("unknown attribute"); + return attribute; + } + + private enum MoonPhase implements StringIdentifiable { + FULL_MOON("full_moon"), + WANING_GIBBOUS("waning_gibbous"); + + private final String id; + + MoonPhase(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } + } + + private static ScheduleDecodeResult read(Map raw) { + return HANDLE.decodeSchedule(ID, raw, LOOKUP, HANDLE.plainContext()); + } + + private static Map keyframe(int ticks, Object value) { + return Map.of("ticks", ticks, "value", value); + } + + private static Map schedule(Object period, Map tracks) { + Map raw = new LinkedHashMap<>(); + raw.put("clock", "minecraft:overworld"); + if(period != null) raw.put("period_ticks", period); + raw.put("tracks", tracks); + return raw; + } + + private static Map sunTrack(Object... frames) { + return Map.of("keyframes", List.of(frames)); + } + + private static Map easedTrack(Object ease, Object... frames) { + return Map.of("keyframes", List.of(frames), "ease", ease); + } + + private static void assertRejected(ScheduleDecodeResult r, String reasonPart) { + assertTrue(r.schedule().isEmpty(), "schedule should be skipped"); + assertTrue(r.droppedTracks().isEmpty(), r.droppedTracks().toString()); + Problem skipped = r.skipped().orElseThrow(); + assertTrue(skipped.reason().contains(reasonPart), skipped.reason()); + } + + private static void assertClean(ScheduleDecodeResult r) { + assertTrue(r.droppedTracks().isEmpty(), r.droppedTracks().toString()); + assertTrue(r.skipped().isEmpty(), r.skipped().toString()); + } + + private static DecodeContext expressions(Map values) { + return new DecodeContext() { + @Override + public V load(Type type, Object raw) throws DecodeException { + return HANDLE.plainContext().load(type, raw instanceof String s && values.containsKey(s) ? values.get(s) : raw); + } + + @Override + public Object resolve(Object raw) { + return raw; + } + }; + } + + private static final DecodeContext EXPRESSIONS = expressions( + Map.of("20 * 60 * 20", 24000.0, "1 / 10", 0.1, "6000 * 2", 12000.0, "3000 * 2", 6000)); + + private static Map earlyGameSchedule() { + return Map.of( + "clock", "minecraft:overworld", + "tracks", Map.of("minecraft:gameplay/can_pillager_patrol_spawn", Map.of( + "modifier", "and", + "keyframes", List.of(keyframe(0, false), keyframe(120000, true))))); + } + + private static Map dayStyle() { + Map raw = schedule(24000, Map.of("minecraft:visual/sun_angle", + sunTrack(keyframe(0, 270.0), keyframe(6000, 360.0), keyframe(6000, 0.0), keyframe(18000, 180.0)))); + raw.put("time_markers", Map.of( + "minecraft:noon", Map.of("ticks", 6000, "show_in_commands", true), + "minecraft:wake_up_from_sleep", 0)); + return raw; + } + + private static Map moonStyle() { + return schedule(192000, Map.of("minecraft:visual/moon_phase", + easedTrack("constant", keyframe(0, "full_moon"), keyframe(24000, "waning_gibbous")))); + } + + private static Map cubicBezier() { + return schedule(null, Map.of("minecraft:visual/sun_angle", + easedTrack(Map.of("cubic_bezier", List.of(0.25, 0.1, 1, 1.0)), keyframe(0, 0.0), keyframe(10, 90.0)))); + } + + private static Map keyframeAtPeriod() { + return schedule(100, Map.of("minecraft:visual/sun_angle", sunTrack(keyframe(0, 0.0), keyframe(100, 1.0)))); + } + + private static Map upperCaseClock() { + return Map.of("clock", "minecraft:Overworld", "tracks", Map.of()); + } + + private static Map ordered() { + Map tracks = new LinkedHashMap<>(); + for(String id : ORDERED_TRACKS) tracks.put(id, sunTrack(keyframe(0, 10.0))); + Map markers = new LinkedHashMap<>(); + for(int i = 0; i < ORDERED_MARKERS.size(); i++) markers.put(ORDERED_MARKERS.get(i), i * 100); + Map raw = schedule(24000, tracks); + raw.put("time_markers", markers); + return raw; + } + + private static Map expressionSchedule() { + Map raw = schedule("20 * 60 * 20", Map.of("minecraft:visual/sun_angle", + easedTrack(Map.of("cubic_bezier", List.of(0.25, "1 / 10", 0.25, 1)), keyframe(0, 270.0), + Map.of("ticks", "6000 * 2", "value", 0.0)))); + raw.put("time_markers", Map.of("minecraft:noon", Map.of("ticks", "3000 * 2"), "minecraft:dusk", "6000 * 2")); + return raw; + } + + @Test + void numberExpressions() { + ScheduleDecodeResult r = HANDLE.decodeSchedule(ID, expressionSchedule(), LOOKUP, EXPRESSIONS); + assertClean(r); + AttributeSchedule def = r.schedule().orElseThrow(); + assertEquals(24000, def.periodTicks().orElseThrow()); + assertEquals(new TimeMarker(6000, false), def.timeMarkers().get(RegistryKey.parse("minecraft:noon"))); + assertEquals(new TimeMarker(12000, false), def.timeMarkers().get(RegistryKey.parse("minecraft:dusk"))); + ScheduleTrack track = def.tracks().get(SUN_ANGLE); + assertEquals(12000, track.keyframes().get(1).ticks()); + assertEquals(new Easing.CubicBezier(0.25f, 0.1f, 0.25f, 1f), track.ease()); + } + + @Test + void integralDouble() { + ScheduleDecodeResult r = read(schedule(24000.0, Map.of("minecraft:visual/sun_angle", sunTrack(keyframe(0, 270.0))))); + assertClean(r); + assertEquals(24000, r.schedule().orElseThrow().periodTicks().orElseThrow()); + Map raw = schedule(24000, Map.of("minecraft:visual/sun_angle", sunTrack(Map.of("ticks", 6000.0, "value", 0.0)))); + raw.put("time_markers", Map.of("minecraft:noon", 6000L)); + AttributeSchedule def = read(raw).schedule().orElseThrow(); + assertEquals(6000, def.tracks().get(SUN_ANGLE).keyframes().getFirst().ticks()); + assertEquals(new TimeMarker(6000, false), def.timeMarkers().get(RegistryKey.parse("minecraft:noon"))); + } + + @Test + void decodesVanillaStyleSchedules() { + ScheduleDecodeResult early = read(earlyGameSchedule()); + assertClean(early); + AttributeSchedule def = early.schedule().orElseThrow(); + assertEquals(RegistryKey.parse("minecraft:overworld"), def.clock()); + assertTrue(def.periodTicks().isEmpty()); + ScheduleTrack patrol = def.tracks().get(PATROL); + assertEquals(Operation.AND, patrol.operation()); + assertEquals(new Easing.Named("linear"), patrol.ease()); + assertEquals(List.of(new Keyframe(0, false), new Keyframe(120000, true)), patrol.keyframes()); + + ScheduleDecodeResult day = read(dayStyle()); + assertClean(day); + def = day.schedule().orElseThrow(); + assertEquals(24000, def.periodTicks().orElseThrow()); + assertEquals(Operation.OVERRIDE, def.tracks().get(SUN_ANGLE).operation()); + assertEquals(4, def.tracks().get(SUN_ANGLE).keyframes().size()); + assertEquals(new TimeMarker(6000, true), def.timeMarkers().get(RegistryKey.parse("minecraft:noon"))); + assertEquals(new TimeMarker(0, false), def.timeMarkers().get(RegistryKey.parse("minecraft:wake_up_from_sleep"))); + + ScheduleDecodeResult moon = read(moonStyle()); + assertClean(moon); + ScheduleTrack phase = moon.schedule().orElseThrow().tracks().get(MOON_PHASE); + assertEquals(new Keyframe(24000, MoonPhase.WANING_GIBBOUS), phase.keyframes().get(1)); + assertEquals(new Easing.Named("constant"), phase.ease()); + + assertEquals(new Easing.CubicBezier(0.25f, 0.1f, 1f, 1f), read(cubicBezier()).schedule().orElseThrow().tracks().get(SUN_ANGLE).ease()); + assertEquals(RegistryKey.parse("minecraft:Overworld"), read(upperCaseClock()).schedule().orElseThrow().clock()); + } + + private static Map withMarkers(Map raw, Map markers) { + raw.put("time_markers", markers); + return raw; + } + + static Stream rejected() { + DecodeContext plain = HANDLE.plainContext(); + Map sun = Map.of("minecraft:visual/sun_angle", sunTrack(keyframe(0, 270.0))); + return Stream.of( + arguments(named("expression that is not an integer", schedule("5 / 2", sun)), expressions(Map.of("5 / 2", 2.5)), + "period_ticks must be an integer"), + arguments(named("fractional period", schedule(24000.5, sun)), plain, "period_ticks must be an integer"), + arguments(named("expression in a plain context", schedule("20 * 60 * 20", sun)), plain, "period_ticks must be an integer"), + arguments(named("non-positive period", schedule(0, Map.of())), plain, "period_ticks"), + arguments(named("unsorted keyframes", schedule(null, Map.of("minecraft:visual/sun_angle", + sunTrack(keyframe(10, 0.0), keyframe(5, 1.0))))), plain, "sorted"), + arguments(named("three keyframes on one tick", schedule(null, Map.of("minecraft:visual/sun_angle", + sunTrack(keyframe(5, 0.0), keyframe(5, 1.0), keyframe(5, 2.0))))), plain, "tick"), + arguments(named("no keyframes", schedule(null, Map.of("minecraft:visual/sun_angle", sunTrack()))), plain, "keyframes"), + arguments(named("keyframe beyond the period", schedule(100, Map.of("minecraft:visual/sun_angle", + sunTrack(keyframe(0, 0.0), keyframe(101, 1.0))))), plain, "period"), + arguments(named("marker equal to the period", withMarkers(schedule(100, Map.of()), Map.of("minecraft:noon", 100))), plain, + "period"), + arguments(named("bezier x out of range", schedule(null, Map.of("minecraft:visual/sun_angle", + easedTrack(Map.of("cubic_bezier", List.of(1.5, 0, 0.5, 1)), keyframe(0, 0.0), keyframe(10, 1.0))))), plain, + "cubic_bezier"), + arguments(named("unknown easing", schedule(null, Map.of("minecraft:visual/sun_angle", + easedTrack("wobbly", keyframe(0, 0.0), keyframe(10, 1.0))))), plain, "wobbly"), + arguments(named("missing clock", Map.of("tracks", Map.of())), plain, "clock"), + arguments(named("tag clock", Map.of("clock", "#minecraft:clocks", "tracks", Map.of())), plain, "clock must not be a tag"), + arguments(named("bare clock", Map.of("clock", "overworld", "tracks", Map.of())), plain, + "clock: a namespace is required, as in \"namespace:overworld\""), + arguments(named("bare time marker", withMarkers(schedule(24000, Map.of()), Map.of("noon", 6000))), plain, + "time marker key: a namespace is required, as in \"namespace:noon\"")); + } + + @ParameterizedTest + @MethodSource + void rejected(Map raw, DecodeContext context, String reasonPart) { + ScheduleDecodeResult r = HANDLE.decodeSchedule(ID, raw, LOOKUP, context); + assertRejected(r, reasonPart); + assertEquals("terra:test", r.skipped().orElseThrow().key()); + } + + static Stream droppedTrack() { + return Stream.of( + arguments(named("unknown attribute", sunTrack(keyframe(0, 0.0))), "minecraft:visual/not_real", "unknown attribute"), + arguments(named("bad keyframe value", sunTrack(keyframe(0, "not_a_phase"))), "minecraft:visual/moon_phase", + "unknown moon phase \"not_a_phase\", expected one of [full_moon, waning_gibbous]"), + arguments(named("modifier not valid for the type", Map.of("modifier", "add", "keyframes", List.of(keyframe(0, "full_moon")))), + "minecraft:visual/moon_phase", "modifier add is not valid for minecraft:visual/moon_phase"), + arguments(named("override out of range", sunTrack(keyframe(0, 5.0))), "minecraft:visual/star_brightness", + "value 5.0 is outside [0, 1]")); + } + + @ParameterizedTest + @MethodSource + void droppedTrack(Map track, String key, String reason) { + ScheduleDecodeResult r = read(schedule(null, Map.of(key, track, "minecraft:visual/sun_angle", sunTrack(keyframe(0, 0.0))))); + assertEquals(List.of(new Problem(key, reason)), r.droppedTracks()); + assertTrue(r.skipped().isEmpty()); + assertEquals(Set.of(SUN_ANGLE), r.schedule().orElseThrow().tracks().keySet()); + } + + @Test + void droppedTracksOnSkip() { + Map tracks = new LinkedHashMap<>(); + tracks.put("minecraft:visual/not_real", sunTrack(keyframe(0, 0.0))); + tracks.put("minecraft:visual/sun_angle", sunTrack(keyframe(0, 0.0), keyframe(200, 1.0))); + ScheduleDecodeResult r = read(schedule(100, tracks)); + assertTrue(r.schedule().isEmpty()); + assertEquals(List.of(new Problem("minecraft:visual/not_real", "unknown attribute")), r.droppedTracks()); + assertEquals(new Problem("terra:test", "keyframe ticks 200 must be within period_ticks 100"), r.skipped().orElseThrow()); + } + + @Test + void configOrder() { + ScheduleDecodeResult r = read(ordered()); + assertClean(r); + AttributeSchedule def = r.schedule().orElseThrow(); + assertEquals(ORDERED_TRACKS, def.tracks().keySet().stream().map(attribute -> attribute.getRegistryKey().toString()).toList()); + assertEquals(ORDERED_MARKERS, def.timeMarkers().keySet().stream().map(RegistryKey::toString).toList()); + } + + private static AttributeSchedule decode(Map raw, DecodeContext context) { + ScheduleDecodeResult r = HANDLE.decodeSchedule(ID, raw, LOOKUP, context); + assertClean(r); + return r.schedule().orElseThrow(); + } + + @Test + void roundTrip() { + Map> fixtures = new LinkedHashMap<>(); + fixtures.put("earlyGame", earlyGameSchedule()); + fixtures.put("dayStyle", dayStyle()); + fixtures.put("moonStyle", moonStyle()); + fixtures.put("cubicBezier", cubicBezier()); + fixtures.put("keyframeAtPeriod", keyframeAtPeriod()); + fixtures.put("upperCaseClock", upperCaseClock()); + fixtures.put("ordered", ordered()); + fixtures.forEach((name, raw) -> { + AttributeSchedule schedule = decode(raw, HANDLE.plainContext()); + Map encoded = HANDLE.encodeSchedule(schedule); + AttributeSchedule again = decode(encoded, HANDLE.plainContext()); + assertEquals(schedule, again, name + " via " + encoded); + assertEquals(List.copyOf(schedule.tracks().keySet()), List.copyOf(again.tracks().keySet()), name + " track order"); + assertEquals(List.copyOf(schedule.timeMarkers().keySet()), List.copyOf(again.timeMarkers().keySet()), + name + " marker order"); + }); + AttributeSchedule evaluated = decode(expressionSchedule(), EXPRESSIONS); + assertEquals(evaluated, decode(HANDLE.encodeSchedule(evaluated), HANDLE.plainContext())); + } + + @Test + void encodeOmitsDefaults() { + AttributeSchedule schedule = new AttributeSchedule(RegistryKey.parse("minecraft:overworld"), OptionalInt.empty(), + Map.of(SUN_ANGLE, new ScheduleTrack(Operation.OVERRIDE, List.of(new Keyframe(0, 270f)), new Easing.Named("linear"))), + Map.of(RegistryKey.parse("minecraft:noon"), new TimeMarker(6000, false))); + assertEquals(Map.of( + "clock", "minecraft:overworld", + "tracks", Map.of("minecraft:visual/sun_angle", Map.of("keyframes", List.of(Map.of("ticks", 0, "value", 270f)))), + "time_markers", Map.of("minecraft:noon", Map.of("ticks", 6000))), + HANDLE.encodeSchedule(schedule)); + AttributeSchedule empty = new AttributeSchedule(RegistryKey.parse("minecraft:overworld"), OptionalInt.empty(), Map.of(), Map.of()); + assertEquals(Map.of("clock", "minecraft:overworld"), HANDLE.encodeSchedule(empty)); + } + + @Test + void encodeNullKeyframe() { + AttributeSchedule schedule = new AttributeSchedule(RegistryKey.parse("mypack:day"), OptionalInt.empty(), + Map.of(SUN_ANGLE, new ScheduleTrack(Operation.OVERRIDE, List.of(new Keyframe(0, null)), new Easing.Named("linear"))), + Map.of()); + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> HANDLE.encodeSchedule(schedule)); + assertEquals("keyframe 0 of minecraft:visual/sun_angle: a null value has no pack-format form", e.getMessage()); + } + + @Test + void encodeNonDefaults() { + AttributeSchedule schedule = new AttributeSchedule(RegistryKey.parse("mypack:day"), OptionalInt.of(24000), + Map.of(SUN_ANGLE, new ScheduleTrack(Operation.ADD, List.of(new Keyframe(0, 1f), new Keyframe(10, 2f)), + new Easing.CubicBezier(0.25f, 0.1f, 1f, 1f)), + MOON_PHASE, new ScheduleTrack(Operation.OVERRIDE, List.of(new Keyframe(0, MoonPhase.WANING_GIBBOUS)), + new Easing.Named("constant"))), + Map.of(RegistryKey.parse("mypack:noon"), new TimeMarker(6000, true))); + Map encoded = HANDLE.encodeSchedule(schedule); + assertEquals("mypack:day", encoded.get("clock")); + assertEquals(24000, encoded.get("period_ticks")); + assertEquals(Map.of("mypack:noon", Map.of("ticks", 6000, "show_in_commands", true)), encoded.get("time_markers")); + Map tracks = (Map) encoded.get("tracks"); + assertEquals(Map.of( + "modifier", "add", + "ease", Map.of("cubic_bezier", List.of(0.25f, 0.1f, 1f, 1f)), + "keyframes", List.of(Map.of("ticks", 0, "value", 1f), Map.of("ticks", 10, "value", 2f))), + tracks.get("minecraft:visual/sun_angle")); + assertEquals(Map.of( + "ease", "constant", + "keyframes", List.of(Map.of("ticks", 0, "value", "waning_gibbous"))), + tracks.get("minecraft:visual/moon_phase")); + } +} diff --git a/platforms/cli/build.gradle.kts b/platforms/cli/build.gradle.kts index c28c25f17..caa5bb1f5 100644 --- a/platforms/cli/build.gradle.kts +++ b/platforms/cli/build.gradle.kts @@ -17,7 +17,9 @@ dependencies { shadedImplementation("ch.qos.logback", "logback-classic", Versions.CLI.logback) - + // Addon class loaders find minecraft-attributes on the test class path first; its entrypoint needs the manifest addon API. + testImplementation(project(":common:addons:minecraft-attributes")) + testImplementation(project(":common:addons:manifest-addon-loader")) } tasks.withType { diff --git a/platforms/cli/src/test/java/com/dfsek/terra/cli/AttributePackTest.java b/platforms/cli/src/test/java/com/dfsek/terra/cli/AttributePackTest.java new file mode 100644 index 000000000..a713a2d01 --- /dev/null +++ b/platforms/cli/src/test/java/com/dfsek/terra/cli/AttributePackTest.java @@ -0,0 +1,410 @@ +package com.dfsek.terra.cli; + +import org.jetbrains.annotations.Nullable; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.lang.management.ManagementFactory; +import java.lang.reflect.Method; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.OptionalDouble; +import java.util.Set; +import java.util.stream.Stream; + +import com.dfsek.terra.addons.attribute.minecraft.AmbientParticle; +import com.dfsek.terra.addons.attribute.minecraft.AmbientSounds; +import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes; +import com.dfsek.terra.addons.attribute.minecraft.Music; +import com.dfsek.terra.addons.attribute.minecraft.SoundRef; +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent; +import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.properties.Properties; +import com.dfsek.terra.api.properties.PropertyKey; +import com.dfsek.terra.api.registry.Registry; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.registry.key.TagKey; +import com.dfsek.terra.api.util.generic.either.Either; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.AttributeMap; +import com.dfsek.terra.api.world.attribute.AttributeParents; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.api.world.attribute.PackAttributes; +import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule; +import com.dfsek.terra.api.world.attribute.schedule.ScheduleTrack; +import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.config.pack.ConfigPackImpl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class AttributePackTest { + private static volatile AttributeParents parents = AttributeParents.NONE; + + private static final AttributeParents FORWARDING = new AttributeParents() { + @Override + public @Nullable AttributeEntry biomeOrNull(Biome biome, Attribute attribute) { + return parents.biomeOrNull(biome, attribute); + } + + @Override + public @Nullable AttributeEntry packOrNull(PackAttributes pack, Attribute attribute) { + return parents.packOrNull(pack, attribute); + } + }; + + private static CLIPlatform platform; + private static AttributeHandle handle; + private static ConfigPack pack; + + @BeforeAll + static void setUp() throws Exception { + platform = new CLIPlatform() { + @Override + public AttributeParents getAttributeParents() { + return FORWARDING; + } + }; + platform.getEventManager().callEvent(new PlatformInitializationEvent()); + handle = platform.getAttributeHandle(); + pack = load(); + } + + @AfterEach + void resetParents() { + parents = AttributeParents.NONE; + } + + private static Path fixture() throws URISyntaxException { + return Path.of(AttributePackTest.class.getResource("/packs/attribute-test/pack.yml").toURI()).getParent(); + } + + private static ConfigPack load() throws Exception { + return new ConfigPackImpl(fixture(), platform); + } + + private static Biome biome(ConfigPack pack, String id) { + return pack.getRegistry(Biome.class).getByID(id).orElseThrow(() -> new AssertionError("No biome " + id)); + } + + private static PackAttributes packAttributes(ConfigPack pack) { + return handle.pack(pack).orElseThrow(() -> new AssertionError("No PackAttributes on " + pack.getID())); + } + + private static AttributeMap biomeEntries(ConfigPack pack, String id) { + return packAttributes(pack).biomeEntries(biome(pack, id)); + } + + private static Registry> attributes(ConfigPack pack) { + return pack.getRegistry(Attribute.REGISTRY_TYPE); + } + + private static Attribute attribute(AttributeKey key) { + return key.lookup(attributes(pack)).orElseThrow(() -> new AssertionError("No attribute " + key)); + } + + @SuppressWarnings("unchecked") + private static List warnings(PackAttributes attributes) throws ReflectiveOperationException { + return (List) attributes.getClass().getMethod("warnings").invoke(attributes); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static List biomeWarnings(String biome) throws ReflectiveOperationException { + Class type = packAttributes(pack).getClass().getClassLoader() + .loadClass("com.dfsek.terra.addons.attribute.BiomeAttributeEntries"); + PropertyKey key = Context.create((Class) type.asSubclass(Properties.class)); + Object entries = biome(pack, biome).getContext().get(key); + Method warnings = type.getDeclaredMethod("warnings"); + warnings.setAccessible(true); + return (List) warnings.invoke(entries); + } + + private static T declared(String biome, AttributeKey key) { + AttributeEntry entry = biomeEntries(pack, biome).get(key).orElseThrow(() -> new AssertionError(biome + " has no " + key)); + assertEquals(Operation.OVERRIDE, entry.operation()); + @SuppressWarnings("unchecked") + T value = (T) entry.argument(); + return value; + } + + private static AttributeMap overrides(Object... keysAndValues) { + AttributeMap.Builder builder = AttributeMap.builder(); + for(int i = 0; i < keysAndValues.length; i += 2) put(builder, (AttributeKey) keysAndValues[i], keysAndValues[i + 1]); + return builder.build(); + } + + @SuppressWarnings("unchecked") + private static void put(AttributeMap.Builder builder, AttributeKey key, Object value) { + builder.put(key, AttributeEntry.override((T) value)); + } + + private static Stream declaredEntries() { + Color child = Color.parseRgb("#a0b0c0"); + Color base = Color.parseRgb("#405060"); + Color white = Color.parseRgb("#ffffff"); + Color shared = Color.parseRgb("#0a0b0c"); + return Stream.of( + Arguments.of("PLAIN", overrides()), + Arguments.of("CHILD", overrides(MinecraftAttributes.VISUAL_FOG_COLOR, child, MinecraftAttributes.VISUAL_SKY_COLOR, base, + MinecraftAttributes.BIOME_TEMPERATURE, 0.8f)), + Arguments.of("NULLED", overrides(MinecraftAttributes.VISUAL_FOG_COLOR, child, MinecraftAttributes.BIOME_TEMPERATURE, 0.8f)), + Arguments.of("META", overrides(MinecraftAttributes.VISUAL_FOG_COLOR, white, MinecraftAttributes.VISUAL_SKY_COLOR, shared, + MinecraftAttributes.BIOME_DOWNFALL, 0.25f)), + Arguments.of("META_CHILD", overrides(MinecraftAttributes.VISUAL_FOG_COLOR, white, MinecraftAttributes.VISUAL_SKY_COLOR, + shared, MinecraftAttributes.BIOME_DOWNFALL, 0.75f, MinecraftAttributes.BIOME_WATER_COLOR, + Color.parseRgb("#112233")))); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("declaredEntries") + void declaredEntriesFollowInheritanceAndMeta(String biome, AttributeMap expected) throws ReflectiveOperationException { + assertEquals(expected, biomeEntries(pack, biome)); + assertEquals(List.of(), biomeWarnings(biome)); + } + + @Test + void metaInsideValues() throws ReflectiveOperationException { + Music music = declared("EXPR", MinecraftAttributes.AUDIO_BACKGROUND_MUSIC).defaultMusic().orElseThrow(); + assertEquals(RegistryKey.parse("minecraft:music.game"), music.sound().id()); + assertEquals(12000, music.minDelay()); + assertEquals(24000, music.maxDelay()); + + AttributeEntry fog = biomeEntries(pack, "EXPR").get(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE).orElseThrow(); + assertEquals(Operation.MULTIPLY, fog.operation()); + assertEquals(0.5f, fog.argument()); + assertEquals(48f, packAttributes(pack).resolve(attribute(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE), + biome(pack, "EXPR"))); + + AmbientSounds sounds = declared("EXPR", MinecraftAttributes.AUDIO_AMBIENT_SOUNDS); + assertEquals(RegistryKey.parse("minecraft:ambient.cave"), sounds.loop().orElseThrow().id()); + AmbientSounds.Mood mood = sounds.mood().orElseThrow(); + assertEquals(RegistryKey.parse("minecraft:ambient.cave"), mood.sound().id()); + assertEquals(6000, mood.tickDelay()); + assertEquals(8, mood.blockSearchExtent()); + assertEquals(2.0, mood.offset()); + assertEquals(List.of( + new AmbientSounds.Additions(new SoundRef(RegistryKey.parse("minecraft:ambient.crimson_forest.additions"), + OptionalDouble.empty()), 0.0111), + new AmbientSounds.Additions(new SoundRef(RegistryKey.parse("minecraft:ambient.basalt_deltas.additions"), + OptionalDouble.empty()), 0.5)), sounds.additions()); + + AmbientParticle particle = declared("EXPR", MinecraftAttributes.VISUAL_AMBIENT_PARTICLES).get(0); + assertEquals(0.025f, particle.probability(), 1e-6f); + Map body = (Map) particle.particle().value(); + assertEquals(Map.of("type", "minecraft:dust", "color", List.of(1.0, 0.0, 0.0), "scale", 1.0), body); + + assertEquals(List.of(), biomeWarnings("EXPR")); + } + + @Test + void chainedReferenceResolvesOnce() throws ReflectiveOperationException { + assertTrue(biomeEntries(pack, "CHAIN").isEmpty()); + List warnings = biomeWarnings("CHAIN"); + assertEquals(2, warnings.size(), warnings.toString()); + for(String key : List.of("minecraft:visual/sky_color", "minecraft:visual/fog_color")) { + String warning = warnings.stream().filter(w -> w.contains("\"" + key + "\"")).findFirst() + .orElseThrow(() -> new AssertionError(warnings.toString())); + assertTrue(warning.contains("got \"$meta.yml:sky-hex\""), warning); + } + } + + @Test + void tectonicErrorBecomesWarning() throws ReflectiveOperationException { + assertEquals(overrides(MinecraftAttributes.VISUAL_FOG_COLOR, Color.parseRgb("#123456")), biomeEntries(pack, "EXPR_BAD")); + + List warnings = biomeWarnings("EXPR_BAD"); + assertEquals(2, warnings.size(), warnings.toString()); + String missingKey = warnings.stream().filter(w -> w.contains("\"minecraft:visual/fog_start_distance\"")).findFirst() + .orElseThrow(() -> new AssertionError(warnings.toString())); + assertTrue(missingKey.contains("No such key no-such-key"), missingKey); + String malformed = warnings.stream().filter(w -> w.contains("\"minecraft:visual/sky_fog_end_distance\"")).findFirst() + .orElseThrow(() -> new AssertionError(warnings.toString())); + assertTrue(malformed.contains("\"EXPR_BAD\""), malformed); + assertTrue(malformed.contains("meta reference \"2 * 6000\" must have the form file:key"), malformed); + assertFalse(malformed.contains("java."), malformed); + assertFalse(malformed.contains("Exception"), malformed); + } + + @Test + void badEntryIsSkippedWithWarning() throws ReflectiveOperationException { + assertEquals(overrides(MinecraftAttributes.VISUAL_FOG_COLOR, Color.parseRgb("#00ff00")), biomeEntries(pack, "BAD")); + assertEquals(List.of("Pack \"ATTRIBUTE_TEST\", config \"BAD\": attribute \"minecraft:visual/sky_color\" skipped: " + + "expected a color like \"#rrggbb\", got \"not a colour\""), biomeWarnings("BAD")); + } + + @Test + void packLevelFields() throws ReflectiveOperationException { + PackAttributes attributes = packAttributes(pack); + assertEquals(overrides(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE, 96f, MinecraftAttributes.GAMEPLAY_FAST_LAVA, true), + attributes.entries()); + assertEquals(true, attributes.resolvePack(attribute(MinecraftAttributes.GAMEPLAY_FAST_LAVA))); + assertEquals(Map.of("vanilla", RegistryKey.parse("minecraft:overworld"), + "vanilla-generation", RegistryKey.parse("minecraft:overworld")), attributes.parents()); + assertEquals(List.of(Either.right(TagKey.parse("#minecraft:in_overworld"))), attributes.scheduleRefs()); + assertEquals(List.of(), warnings(attributes)); + } + + @Test + void scheduleDefinitionLoads() { + PackAttributes attributes = packAttributes(pack); + assertEquals(Set.of(RegistryKey.parse("terra:test_cycle")), attributes.scheduleDefinitions().keySet()); + AttributeSchedule definition = attributes.scheduleDefinitions().get(RegistryKey.parse("terra:test_cycle")); + assertEquals(RegistryKey.parse("minecraft:overworld"), definition.clock()); + assertEquals(24000, definition.periodTicks().orElseThrow()); + ScheduleTrack track = definition.tracks().get(attribute(MinecraftAttributes.VISUAL_SKY_COLOR)); + assertEquals(Operation.OVERRIDE, track.operation()); + assertEquals(2, track.keyframes().size()); + assertEquals(Color.parseRgb("#000000"), track.keyframes().get(0).argument()); + assertEquals(12000, track.keyframes().get(1).ticks()); + assertEquals(Color.parseRgb("#ffffff"), track.keyframes().get(1).argument()); + } + + @Test + void resolveWithoutParents() { + PackAttributes attributes = packAttributes(pack); + Biome plain = biome(pack, "PLAIN"); + Attribute precipitation = attribute(MinecraftAttributes.BIOME_HAS_PRECIPITATION); + assertNull(attributes.biomeEntryOrNull(precipitation, plain)); + assertEquals(precipitation.defaultValue(), attributes.resolve(precipitation, plain)); + Attribute temperature = attribute(MinecraftAttributes.BIOME_TEMPERATURE); + assertNull(attributes.biomeEntryOrNull(temperature, plain)); + assertEquals(0.5f, attributes.resolve(temperature, plain)); + Attribute sky = attribute(MinecraftAttributes.VISUAL_SKY_COLOR); + assertNull(attributes.biomeEntryOrNull(sky, biome(pack, "NULLED"))); + assertEquals(sky.defaultValue(), attributes.resolve(sky, biome(pack, "NULLED"))); + + assertEquals(81.6f, attributes.resolve(attribute(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE), biome(pack, "FOGGY")), + 1e-4f); + } + + @Test + void layersApplyInOrder() { + PackAttributes attributes = packAttributes(pack); + Biome child = biome(pack, "CHILD"); + parents = new AttributeParents() { + @Override + @SuppressWarnings("unchecked") + public @Nullable AttributeEntry biomeOrNull(Biome biome, Attribute attribute) { + if(biome != child) return null; + AttributeKey key = attribute.key(); + if(key == MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE) return (AttributeEntry) AttributeEntry.override(50f); + if(key == MinecraftAttributes.VISUAL_FOG_COLOR) return (AttributeEntry) AttributeEntry.override(Color.rgb(0x111111)); + return null; + } + + @Override + @SuppressWarnings("unchecked") + public @Nullable AttributeEntry packOrNull(PackAttributes pack, Attribute attribute) { + assertEquals(RegistryKey.parse("minecraft:overworld"), pack.parents().get("vanilla")); + AttributeKey key = attribute.key(); + if(key == MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE) return (AttributeEntry) AttributeEntry.override(40f); + if(key == MinecraftAttributes.VISUAL_SKY_FOG_END_DISTANCE) return (AttributeEntry) AttributeEntry.override(30f); + return null; + } + }; + Attribute waterFogEnd = attribute(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE); + Attribute skyFogEnd = attribute(MinecraftAttributes.VISUAL_SKY_FOG_END_DISTANCE); + assertEquals(50f, attributes.resolve(waterFogEnd, child)); + assertEquals(Color.parseRgb("#a0b0c0"), attributes.resolve(attribute(MinecraftAttributes.VISUAL_FOG_COLOR), child)); + assertEquals(30f, attributes.resolve(skyFogEnd, biome(pack, "PLAIN"))); + assertEquals(96f, attributes.resolve(waterFogEnd, biome(pack, "PLAIN"))); + assertEquals(96f, attributes.resolvePack(waterFogEnd)); + assertEquals(30f, attributes.resolvePack(skyFogEnd)); + } + + @Test + void columnsAreIdenticalAcrossLoads() throws Exception { + Map, AttributeEntry>> first = null; + for(int i = 0; i < 20; i++) { + ConfigPack loaded = load(); + Map, AttributeEntry>> columns = columns(loaded); + assertFalse(columns.get("CHILD").isEmpty()); + if(first == null) first = columns; + else assertEquals(first, columns, "Load " + i + " differs"); + } + } + + private static Map, AttributeEntry>> columns(ConfigPack loaded) { + PackAttributes attributes = packAttributes(loaded); + Map, AttributeEntry>> columns = new HashMap<>(); + loaded.getRegistry(Biome.class).forEach((key, biome) -> { + Map, AttributeEntry> row = new HashMap<>(); + AttributeMap declared = attributes.biomeEntries(biome); + for(Attribute attribute : attributes(loaded).entries()) { + AttributeEntry entry = attributes.biomeEntryOrNull(attribute, biome); + assertEquals(declared.get(attribute.key()).orElse(null), entry, biome.getID() + " " + attribute.key()); + if(entry != null) row.put(attribute.key(), entry); + } + assertEquals(declared.keys(), row.keySet(), biome.getID()); + columns.put(biome.getID(), row); + }); + return columns; + } + + @Test + void resolveAllocatesNothing() { + PackAttributes attributes = packAttributes(pack); + Biome child = biome(pack, "CHILD"); + Biome plain = biome(pack, "PLAIN"); + Attribute fogColor = attribute(MinecraftAttributes.VISUAL_FOG_COLOR); + Attribute precipitation = attribute(MinecraftAttributes.BIOME_HAS_PRECIPITATION); + Attribute fastLava = attribute(MinecraftAttributes.GAMEPLAY_FAST_LAVA); + com.sun.management.ThreadMXBean threads = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean(); + long thread = Thread.currentThread().threadId(); + + int sink = 0; + for(int i = 0; i < 100_000; i++) sink += reads(attributes, child, plain, fogColor, precipitation, fastLava); + long before = threads.getThreadAllocatedBytes(thread); + for(int i = 0; i < 10_000; i++) sink += reads(attributes, child, plain, fogColor, precipitation, fastLava); + long allocated = threads.getThreadAllocatedBytes(thread) - before; + + assertTrue(sink != 0); + assertTrue(allocated < 1024, allocated + " bytes allocated"); + } + + private static int reads(PackAttributes attributes, Biome child, Biome plain, Attribute fogColor, + Attribute precipitation, Attribute fastLava) { + int hash = System.identityHashCode(attributes.resolve(fogColor, child)); + hash += attributes.resolve(precipitation, plain) ? 1 : 2; + hash += attributes.resolvePack(fastLava) ? 1 : 2; + hash += attributes.biomeEntryOrNull(fogColor, child) == null ? 0 : 1; + return hash; + } + + @Test + void scheduleIdsAreChecked() throws Exception { + PackAttributes attributes = packAttributes(new ConfigPackImpl(scheduleFixture(), platform)); + assertEquals(List.of(Either.right(TagKey.parse("#minecraft:in_overworld"))), attributes.scheduleRefs()); + assertEquals(Set.of(RegistryKey.parse("mypack:seasons"), RegistryKey.parse("mypack:dropping")), + attributes.scheduleDefinitions().keySet()); + List warnings = warnings(attributes); + assertEquals(List.of( + "Pack \"SCHEDULE_TEST\": schedule \"seasons\" skipped: schedule IDs must include a namespace, e.g. \"mypack:seasons\"", + "Pack \"SCHEDULE_TEST\": schedule \"#mypack:tagged\" skipped: schedule IDs must not be tags"), + warnings.stream().filter(w -> w.contains("skipped: schedule IDs")).toList()); + assertEquals(4, warnings.size(), warnings.toString()); + assertTrue(warnings.contains("Pack \"SCHEDULE_TEST\": schedule \"mypack:dropping\" track \"minecraft:visual/moon_phase\" " + + "dropped: modifier add is not valid for minecraft:visual/moon_phase"), warnings.toString()); + assertTrue(warnings.stream().anyMatch(w -> w.startsWith("Pack \"SCHEDULE_TEST\": schedule \"mypack:not valid\" skipped: ")), + warnings.toString()); + } + + private static Path scheduleFixture() throws URISyntaxException { + return Path.of(AttributePackTest.class.getResource("/packs/schedule-test/pack.yml").toURI()).getParent(); + } +} diff --git a/platforms/cli/src/test/java/com/dfsek/terra/cli/FeatureStagePackTest.java b/platforms/cli/src/test/java/com/dfsek/terra/cli/FeatureStagePackTest.java new file mode 100644 index 000000000..66900af1b --- /dev/null +++ b/platforms/cli/src/test/java/com/dfsek/terra/cli/FeatureStagePackTest.java @@ -0,0 +1,56 @@ +package com.dfsek.terra.cli; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent; +import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.properties.Properties; +import com.dfsek.terra.api.properties.PropertyKey; +import com.dfsek.terra.api.registry.key.StringIdentifiable; +import com.dfsek.terra.api.structure.feature.Feature; +import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.chunk.generation.stage.GenerationStage; +import com.dfsek.terra.config.pack.ConfigPackImpl; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +class FeatureStagePackTest { + private static ConfigPack pack; + + @BeforeAll + static void setUp() throws Exception { + CLIPlatform platform = new CLIPlatform(); + platform.getEventManager().callEvent(new PlatformInitializationEvent()); + Path fixture = Path.of(FeatureStagePackTest.class.getResource("/packs/feature-stage-test/pack.yml").toURI()).getParent(); + pack = new ConfigPackImpl(fixture, platform); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static Map> featuresByStage(Biome biome) throws ReflectiveOperationException { + GenerationStage stage = pack.getStages().getFirst(); + Class biomeFeatures = stage.getClass().getClassLoader() + .loadClass("com.dfsek.terra.addons.generation.feature.config.BiomeFeatures"); + PropertyKey key = Context.create((Class) biomeFeatures.asSubclass(Properties.class)); + Object properties = biome.getContext().get(key); + Map> features = (Map>) biomeFeatures.getMethod("getFeatures").invoke(properties); + Map> byId = new HashMap<>(); + features.forEach((s, list) -> byId.put(((StringIdentifiable) s).getID(), list.stream().map(Feature::getID).toList())); + return byId; + } + + @Test + void dottedStageIdReadsNestedPath() throws ReflectiveOperationException { + Biome plain = pack.getRegistry(Biome.class).getByID("PLAIN").orElseThrow(); + Map> features = featuresByStage(plain); + assertEquals(List.of("ROCK"), features.get("nested.stage")); + assertEquals(List.of("ROCK"), features.get("flat")); + } +} diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/bad.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/bad.yml new file mode 100644 index 000000000..65f922c2d --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/bad.yml @@ -0,0 +1,7 @@ +id: BAD +type: BIOME +extends: GROUND + +attributes: + minecraft:visual/fog_color: "#00ff00" + minecraft:visual/sky_color: "not a colour" diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/base.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/base.yml new file mode 100644 index 000000000..ef1ca037a --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/base.yml @@ -0,0 +1,9 @@ +id: BASE +type: BIOME +abstract: true +extends: GROUND + +attributes: + minecraft:visual/fog_color: "#102030" + minecraft:visual/sky_color: "#405060" + terra:biome/temperature: 0.8 diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/chain.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/chain.yml new file mode 100644 index 000000000..24c2b30e5 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/chain.yml @@ -0,0 +1,11 @@ +# A reference to a reference is followed once, at the top level and nested alike, as for a @Meta String field: both entries +# get the literal "$meta.yml:sky-hex", which is not a colour, and are skipped with a warning. +id: CHAIN +type: BIOME +extends: GROUND + +attributes: + minecraft:visual/sky_color: "$meta.yml:chained-color" + minecraft:visual/fog_color: + modifier: override + argument: "$meta.yml:chained-color" diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/child.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/child.yml new file mode 100644 index 000000000..0fab86440 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/child.yml @@ -0,0 +1,6 @@ +id: CHILD +type: BIOME +extends: BASE + +attributes: + minecraft:visual/fog_color: "#a0b0c0" diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/expr.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/expr.yml new file mode 100644 index 000000000..276292c84 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/expr.yml @@ -0,0 +1,31 @@ +# Meta features inside attribute values: number expressions, "${file:key}" interpolation, "$file:key" references and "<<" includes +# at every depth of a value, including a modifier argument and an opaque particle body. +id: EXPR +type: BIOME +extends: GROUND + +attributes: + minecraft:audio/background_music: + default: + sound: minecraft:music.game + min_delay: "2 * 6000" + max_delay: "${meta.yml:music-delay} * 4" + minecraft:visual/water_fog_end_distance: + modifier: multiply + argument: "$meta.yml:fog-scale" + minecraft:audio/ambient_sounds: + loop: "$meta.yml:cave-loop" + mood: + "<<": + - meta.yml:cave-mood + tick_delay: "3000 * 2" + additions: + - "<< meta.yml:cave-additions" + - sound: minecraft:ambient.basalt_deltas.additions + tick_chance: 0.5 + minecraft:visual/ambient_particles: + - particle: + "<<": + - meta.yml:particle-options + type: "minecraft:${meta.yml:particle-name}" + probability: "1 / 40" diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/expr_bad.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/expr_bad.yml new file mode 100644 index 000000000..37846ba99 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/expr_bad.yml @@ -0,0 +1,11 @@ +# Config preprocessing errors inside attribute values: each warns once for its entry, and the other entries still load. +id: EXPR_BAD +type: BIOME +extends: GROUND + +attributes: + minecraft:visual/fog_color: "#123456" + minecraft:visual/fog_start_distance: "${meta.yml:no-such-key} * 2" + minecraft:visual/sky_fog_end_distance: + modifier: add + argument: "${2 * 6000}" diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/foggy.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/foggy.yml new file mode 100644 index 000000000..643a35e04 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/foggy.yml @@ -0,0 +1,8 @@ +id: FOGGY +type: BIOME +extends: GROUND + +attributes: + minecraft:visual/water_fog_end_distance: + modifier: multiply + argument: 0.85 diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/ground.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/ground.yml new file mode 100644 index 000000000..fe9379f24 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/ground.yml @@ -0,0 +1,14 @@ +# Terrain and palette shared by every fixture biome, kept apart from BASE so that only BASE's children inherit its attributes. +id: GROUND +type: BIOME +abstract: true + +vanilla: minecraft:plains + +terrain: + sampler: + type: CONSTANT + value: 0 + +palette: + - BLOCK:minecraft:stone: 319 diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_child.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_child.yml new file mode 100644 index 000000000..8406b5755 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_child.yml @@ -0,0 +1,8 @@ +# Extends META, so META's meta include is expanded while it is an inherited layer. The water colour is a "$file:key" meta value. +id: META_CHILD +type: BIOME +extends: META + +attributes: + terra:biome/downfall: 0.75 + terra:biome/water_color: $meta.yml:shared-water-color diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_include.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_include.yml new file mode 100644 index 000000000..a6f63d6ef --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/meta_include.yml @@ -0,0 +1,8 @@ +id: META +type: BIOME +extends: GROUND + +attributes: + "<<": + - meta.yml:shared-attributes + minecraft:visual/fog_color: "#ffffff" diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/nulled.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/nulled.yml new file mode 100644 index 000000000..fe8457fc9 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/nulled.yml @@ -0,0 +1,6 @@ +id: NULLED +type: BIOME +extends: CHILD + +attributes: + minecraft:visual/sky_color: null diff --git a/platforms/cli/src/test/resources/packs/attribute-test/biomes/plain.yml b/platforms/cli/src/test/resources/packs/attribute-test/biomes/plain.yml new file mode 100644 index 000000000..aa1136d6f --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/biomes/plain.yml @@ -0,0 +1,3 @@ +id: PLAIN +type: BIOME +extends: GROUND diff --git a/platforms/cli/src/test/resources/packs/attribute-test/meta.yml b/platforms/cli/src/test/resources/packs/attribute-test/meta.yml new file mode 100644 index 000000000..376ba4365 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/meta.yml @@ -0,0 +1,22 @@ +shared-attributes: + minecraft:visual/fog_color: "#010203" + minecraft:visual/sky_color: "#0a0b0c" + terra:biome/downfall: 0.25 +shared-water-color: "#112233" +music-delay: 6000 +fog-scale: 0.5 +cave-loop: minecraft:ambient.cave +cave-mood: + sound: minecraft:ambient.cave + block_search_extent: 8 + offset: 2.0 +cave-additions: + - sound: minecraft:ambient.crimson_forest.additions + tick_chance: 0.0111 +particle-name: dust +particle-options: + color: [1.0, 0.0, 0.0] + scale: 1.0 +night-sky: "#000000" +chained-color: "$meta.yml:sky-hex" +sky-hex: "#0a0b0c" diff --git a/platforms/cli/src/test/resources/packs/attribute-test/pack.yml b/platforms/cli/src/test/resources/packs/attribute-test/pack.yml new file mode 100644 index 000000000..9008b1946 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/attribute-test/pack.yml @@ -0,0 +1,43 @@ +id: ATTRIBUTE_TEST +version: 1.0.0 +author: Terra contributors + +generator: NOISE_3D + +vanilla: minecraft:overworld +vanilla-generation: minecraft:overworld + +addons: + biome-provider-single: "1.+" + chunk-generator-noise-3d: "1.+" + config-attributes: "1.+" + config-biome: "1.+" + config-noise-function: "1.+" + config-palette: "1.+" + language-yaml: "1.+" + minecraft-attributes: "1.+" + palette-block-shortcut: "1.+" + +biomes: + type: SINGLE + biome: PLAIN + +attributes: + minecraft:visual/water_fog_end_distance: 96 + minecraft:gameplay/fast_lava: true + minecraft:visual/fog_color: null + +schedules: + - "#minecraft:in_overworld" + +schedule-definitions: + terra:test_cycle: + clock: minecraft:overworld + period_ticks: "20 * 60 * 20" + tracks: + minecraft:visual/sky_color: + keyframes: + - ticks: 0 + value: "$meta.yml:night-sky" + - ticks: "6000 * 2" + value: "#ffffff" diff --git a/platforms/cli/src/test/resources/packs/feature-stage-test/biomes/plain.yml b/platforms/cli/src/test/resources/packs/feature-stage-test/biomes/plain.yml new file mode 100644 index 000000000..afe5ab7ed --- /dev/null +++ b/platforms/cli/src/test/resources/packs/feature-stage-test/biomes/plain.yml @@ -0,0 +1,19 @@ +id: PLAIN +type: BIOME + +vanilla: minecraft:plains + +terrain: + sampler: + type: CONSTANT + value: 0 + +palette: + - BLOCK:minecraft:stone: 319 + +features: + nested: + stage: + - ROCK + flat: + - ROCK diff --git a/platforms/cli/src/test/resources/packs/feature-stage-test/features/rock.yml b/platforms/cli/src/test/resources/packs/feature-stage-test/features/rock.yml new file mode 100644 index 000000000..a9d7acc6c --- /dev/null +++ b/platforms/cli/src/test/resources/packs/feature-stage-test/features/rock.yml @@ -0,0 +1,15 @@ +id: ROCK +type: FEATURE + +distributor: + type: "NO" + +locator: + type: SURFACE + range: 0 + +structures: + distribution: + type: CONSTANT + value: 0 + structures: BLOCK:minecraft:stone diff --git a/platforms/cli/src/test/resources/packs/feature-stage-test/pack.yml b/platforms/cli/src/test/resources/packs/feature-stage-test/pack.yml new file mode 100644 index 000000000..2a44f9495 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/feature-stage-test/pack.yml @@ -0,0 +1,30 @@ +id: FEATURE_STAGE_TEST +version: 1.0.0 +author: Terra contributors + +generator: NOISE_3D + +addons: + biome-provider-single: "1.+" + chunk-generator-noise-3d: "1.+" + config-biome: "1.+" + config-distributors: "1.+" + config-feature: "1.+" + config-locators: "1.+" + config-noise-function: "1.+" + config-palette: "1.+" + generation-stage-feature: "1.+" + language-yaml: "1.+" + palette-block-shortcut: "1.+" + structure-block-shortcut: "1.+" + +biomes: + type: SINGLE + biome: PLAIN + +# A dotted stage ID reads a nested path in biome configs: "nested.stage" reads features.nested.stage. +stages: + - id: nested.stage + type: FEATURE + - id: flat + type: FEATURE diff --git a/platforms/cli/src/test/resources/packs/schedule-test/biomes/plain.yml b/platforms/cli/src/test/resources/packs/schedule-test/biomes/plain.yml new file mode 100644 index 000000000..0693ad28f --- /dev/null +++ b/platforms/cli/src/test/resources/packs/schedule-test/biomes/plain.yml @@ -0,0 +1,12 @@ +id: PLAIN +type: BIOME + +vanilla: minecraft:plains + +terrain: + sampler: + type: CONSTANT + value: 0 + +palette: + - BLOCK:minecraft:stone: 319 diff --git a/platforms/cli/src/test/resources/packs/schedule-test/pack.yml b/platforms/cli/src/test/resources/packs/schedule-test/pack.yml new file mode 100644 index 000000000..1bcf8f2b7 --- /dev/null +++ b/platforms/cli/src/test/resources/packs/schedule-test/pack.yml @@ -0,0 +1,49 @@ +id: SCHEDULE_TEST +version: 1.0.0 +author: Terra contributors + +generator: NOISE_3D + +vanilla: minecraft:overworld +vanilla-generation: minecraft:overworld + +addons: + biome-provider-single: "1.+" + chunk-generator-noise-3d: "1.+" + config-attributes: "1.+" + config-biome: "1.+" + config-noise-function: "1.+" + config-palette: "1.+" + language-yaml: "1.+" + minecraft-attributes: "1.+" + palette-block-shortcut: "1.+" + +biomes: + type: SINGLE + biome: PLAIN + +schedules: "#minecraft:in_overworld" + +schedule-definitions: + mypack:seasons: + clock: minecraft:overworld + period_ticks: 24000 + tracks: + minecraft:visual/sky_color: + keyframes: + - ticks: 0 + value: "#000000" + seasons: + clock: minecraft:overworld + "#mypack:tagged": + clock: minecraft:overworld + "mypack:not valid": + clock: minecraft:overworld + mypack:dropping: + clock: minecraft:overworld + tracks: + minecraft:visual/moon_phase: + modifier: add + keyframes: + - ticks: 0 + value: full_moon From bebcb775fc82441c50010b9719c16b78439d4d48 Mon Sep 17 00:00:00 2001 From: Zoe Gidiere Date: Sun, 8 Nov 2026 19:37:29 -0700 Subject: [PATCH 41/44] 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", From 2f36b2d5c4ba60cba17e93d358b703a0b68416c0 Mon Sep 17 00:00:00 2001 From: Zoe Gidiere Date: Sun, 8 Nov 2026 20:56:00 -0700 Subject: [PATCH 42/44] fix: make config pack registration thread-safe --- .../addons/terrascript/TerraScriptAddon.java | 5 +- .../terra/config/pack/ConfigPackImpl.java | 95 +++++++--- .../terra/registry/OpenRegistryImpl.java | 44 +++-- .../ConfigPackRegistryConcurrencyTest.java | 173 ++++++++++++++++++ .../master/ConfigRegistryConcurrencyTest.java | 141 ++++++++++++++ 5 files changed, 413 insertions(+), 45 deletions(-) create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/config/pack/ConfigPackRegistryConcurrencyTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/registry/master/ConfigRegistryConcurrencyTest.java diff --git a/common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/TerraScriptAddon.java b/common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/TerraScriptAddon.java index 25c4e3ca8..e3adf0b68 100644 --- a/common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/TerraScriptAddon.java +++ b/common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/TerraScriptAddon.java @@ -40,6 +40,8 @@ public class TerraScriptAddon implements AddonInitializer { .then(event -> { CheckedRegistry structureRegistry = event.getPack().getOrCreateRegistry(Structure.class); CheckedRegistry lootRegistry = event.getPack().getOrCreateRegistry(LootTable.class); + // Pack registries must not be created from worker threads. + CheckedRegistry functionRegistry = event.getPack().getOrCreateRegistry(FunctionBuilder.class); try { FileUtil.filesWithExtension(event.getPack().getRootPath(), ".tesf") .entrySet() @@ -53,11 +55,12 @@ public class TerraScriptAddon implements AddonInitializer { platform, structureRegistry, lootRegistry, - event.getPack().getOrCreateRegistry(FunctionBuilder.class)); + functionRegistry); } catch(ParseException | IOException e) { throw new RuntimeException("Failed to load script \"" + entry.getKey() + "\"", e); } }) + .toList() .forEach(structureRegistry::register); } catch(IOException e) { throw new RuntimeException("Error occurred while reading config pack files", e); diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java index 6bb0ce13d..c5d315c8f 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java @@ -111,7 +111,12 @@ public class ConfigPackImpl implements ConfigPack { private final BiomeTagIndex biomeTagIndex = new BiomeTagIndex(); - private final Map> registryMap = new HashMap<>(); + /** + * Guards writes to registryMap, shortcuts, configTypes and the loaders' type maps. Reads of registryMap take no lock: + * publish a registry there only after its loaders are registered. + */ + private final Object registrationLock = new Object(); + private final Map> registryMap = new ConcurrentHashMap<>(); private final Map> shortcuts = new HashMap<>(); private final OpenRegistry> configTypeRegistry; @@ -266,33 +271,41 @@ public class ConfigPackImpl implements ConfigPack { @Override public ConfigPackImpl applyLoader(Type type, TypeLoader loader) { - abstractConfigLoader.registerLoader(type, loader); - selfLoader.registerLoader(type, loader); + synchronized(registrationLock) { + abstractConfigLoader.registerLoader(type, loader); + selfLoader.registerLoader(type, loader); + } return this; } @Override public ConfigPackImpl applyLoader(Type type, Supplier> loader) { - abstractConfigLoader.registerLoader(type, loader); - selfLoader.registerLoader(type, loader); + synchronized(registrationLock) { + abstractConfigLoader.registerLoader(type, loader); + selfLoader.registerLoader(type, loader); + } return this; } @Override public void register(TypeRegistry registry) { - registry.registerLoader(ConfigType.class, configTypeRegistry); - registryMap.forEach(registry::registerLoader); - shortcuts.forEach(registry::registerLoader); // overwrite with delegated shortcuts if present + synchronized(registrationLock) { + registry.registerLoader(ConfigType.class, configTypeRegistry); + registryMap.forEach(registry::registerLoader); + shortcuts.forEach(registry::registerLoader); // overwrite with delegated shortcuts if present + } } @Override public ConfigPack registerConfigType(ConfigType type, RegistryKey key, int priority) { - Set contained = new HashSet<>(); - configTypes.forEach((p, configs) -> configs.forEach(pair -> { - if(contained.contains(pair.getLeft())) throw new IllegalArgumentException("Duplicate config key: " + key); - contained.add(key); - })); - configTypes.computeIfAbsent(priority, p -> new ArrayList<>()).add(Pair.of(key, type)); + synchronized(registrationLock) { + Set contained = new HashSet<>(); + configTypes.forEach((p, configs) -> configs.forEach(pair -> { + if(contained.contains(pair.getLeft())) throw new IllegalArgumentException("Duplicate config key: " + key); + contained.add(key); + })); + configTypes.computeIfAbsent(priority, p -> new ArrayList<>()).add(Pair.of(key, type)); + } return this; } @@ -313,7 +326,12 @@ public class ConfigPackImpl implements ConfigPack { @Override public CheckedRegistry getOrCreateRegistry(TypeKey typeKey) { - return (CheckedRegistry) registryMap.computeIfAbsent(typeKey.getType(), c -> { + Type c = typeKey.getType(); + CheckedRegistryImpl existing = registryMap.get(c); + if(existing != null) return (CheckedRegistry) existing; + synchronized(registrationLock) { + existing = registryMap.get(c); + if(existing != null) return (CheckedRegistry) existing; OpenRegistry registry = new OpenRegistryImpl<>(typeKey); selfLoader.registerLoader(c, registry); abstractConfigLoader.registerLoader(c, registry); @@ -339,8 +357,10 @@ public class ConfigPackImpl implements ConfigPack { } } - return new CheckedRegistryImpl<>(registry); - }); + CheckedRegistryImpl checked = new CheckedRegistryImpl<>(registry); + registryMap.put(c, checked); + return checked; + } } @Override @@ -371,11 +391,16 @@ public class ConfigPackImpl implements ConfigPack { @SuppressWarnings("rawtypes") @Override public ConfigPack registerShortcut(TypeKey clazz, String shortcut, ShortcutLoader loader) { - ShortcutHolder holder = shortcuts - .computeIfAbsent(clazz.getType(), c -> new ShortcutHolder<>(getOrCreateRegistry(clazz))) - .register(shortcut, (ShortcutLoader) loader); - selfLoader.registerLoader(clazz.getType(), holder); - abstractConfigLoader.registerLoader(clazz.getType(), holder); + synchronized(registrationLock) { + ShortcutHolder holder = shortcuts.get(clazz.getType()); + if(holder == null) { + holder = new ShortcutHolder<>(getOrCreateRegistry(clazz)); + shortcuts.put(clazz.getType(), holder); + } + holder.register(shortcut, (ShortcutLoader) loader); + selfLoader.registerLoader(clazz.getType(), holder); + abstractConfigLoader.registerLoader(clazz.getType(), holder); + } return this; } @@ -388,15 +413,25 @@ public class ConfigPackImpl implements ConfigPack { return new OpenRegistryImpl<>(new LinkedHashMap<>(), CONFIG_TYPE_TYPE_KEY) { @Override public boolean register(@NotNull RegistryKey key, @NotNull ConfigType value) { - if(!registryMap - .containsKey(value.getTypeKey() - .getType())) { - OpenRegistry openRegistry = new OpenRegistryImpl<>(value.getTypeKey()); - selfLoader.registerLoader(value.getTypeKey().getType(), openRegistry); - abstractConfigLoader.registerLoader(value.getTypeKey().getType(), openRegistry); - registryMap.put(value.getTypeKey().getType(), new CheckedRegistryImpl<>(openRegistry)); + synchronized(registrationLock) { + if(!registryMap + .containsKey(value.getTypeKey() + .getType())) { + OpenRegistry openRegistry = new OpenRegistryImpl<>(value.getTypeKey()); + selfLoader.registerLoader(value.getTypeKey().getType(), openRegistry); + abstractConfigLoader.registerLoader(value.getTypeKey().getType(), openRegistry); + registryMap.put(value.getTypeKey().getType(), new CheckedRegistryImpl<>(openRegistry)); + } + return super.register(key, value); + } + } + + @Override + public void registerChecked(@NotNull RegistryKey key, @NotNull ConfigType value) { + // Same lock order as register: registrationLock, then the registry's own lock. + synchronized(registrationLock) { + super.registerChecked(key, value); } - return super.register(key, value); } }; } diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/OpenRegistryImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/OpenRegistryImpl.java index 60bea757e..c95588bbf 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/registry/OpenRegistryImpl.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/OpenRegistryImpl.java @@ -20,14 +20,13 @@ package com.dfsek.terra.registry; import com.dfsek.tectonic.api.depth.DepthTracker; import com.dfsek.tectonic.api.exception.LoadException; import com.dfsek.tectonic.api.loader.ConfigLoader; -import com.google.common.collect.ListMultimap; -import com.google.common.collect.Multimaps; import org.jetbrains.annotations.NotNull; import java.lang.reflect.AnnotatedType; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -46,15 +45,20 @@ import com.dfsek.terra.api.util.reflection.TypeKey; /** * Registry implementation with read/write access. For internal use only. + *

+ * {@link #registerChecked} calls {@link #register} under a private lock: a subclass that locks in {@code register} must take + * that lock first in {@code registerChecked} too. * * @param */ public class OpenRegistryImpl implements OpenRegistry { private static final Entry NULL = new Entry<>(null); private final Map> objects; - private final ListMultimap>> objectIDs = Multimaps.newListMultimap(new ConcurrentHashMap<>(), - ArrayList::new); + /** Lists are immutable and replaced on write. */ + private final Map>>> objectIDs = new ConcurrentHashMap<>(); private final TypeKey typeKey; + /** Not {@code this}: {@code ConfigRegistry.loadAll} holds the monitor while workers register. */ + private final Object mutationLock = new Object(); public OpenRegistryImpl(TypeKey typeKey) { this(new ConcurrentHashMap<>(), typeKey); @@ -92,22 +96,34 @@ public class OpenRegistryImpl implements OpenRegistry { @Override public void registerChecked(@NotNull RegistryKey identifier, @NotNull T value) throws DuplicateEntryException { - if(objects.containsKey(identifier)) - throw new DuplicateEntryException("Value with identifier \"" + identifier + "\" is already defined in registry."); - register(identifier, value); + synchronized(mutationLock) { + if(objects.containsKey(identifier)) + throw new DuplicateEntryException("Value with identifier \"" + identifier + "\" is already defined in registry."); + register(identifier, value); + } } @Override public void clear() { - objects.clear(); - objectIDs.clear(); + synchronized(mutationLock) { + objects.clear(); + objectIDs.clear(); + } } private boolean register(RegistryKey identifier, Entry value) { - boolean exists = objects.containsKey(identifier); - objects.put(identifier, value); - objectIDs.put(identifier.getID(), Pair.of(identifier, value)); - return exists; + synchronized(mutationLock) { + boolean exists = objects.containsKey(identifier); + objects.put(identifier, value); + Pair> pair = Pair.of(identifier, value); + objectIDs.merge(identifier.getID(), List.of(pair), (existing, added) -> { + List>> merged = new ArrayList<>(existing.size() + 1); + merged.addAll(existing); + merged.add(pair); + return List.copyOf(merged); + }); + return exists; + } } @SuppressWarnings("unchecked") @@ -149,7 +165,7 @@ public class OpenRegistryImpl implements OpenRegistry { @Override public Map getMatches(String id) { return objectIDs - .get(id) + .getOrDefault(id, List.of()) .stream() .collect(HashMap::new, (map, pair) -> map.put(pair.getLeft(), pair.getRight().getValue()), Map::putAll); } diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/config/pack/ConfigPackRegistryConcurrencyTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/config/pack/ConfigPackRegistryConcurrencyTest.java new file mode 100644 index 000000000..6dc4a7a88 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/config/pack/ConfigPackRegistryConcurrencyTest.java @@ -0,0 +1,173 @@ +package com.dfsek.terra.config.pack; + +import com.dfsek.tectonic.api.loader.AbstractConfigLoader; +import com.dfsek.tectonic.api.loader.ConfigLoader; +import com.dfsek.tectonic.api.loader.type.TypeLoader; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.lang.reflect.Field; +import java.lang.reflect.Proxy; +import java.lang.reflect.Type; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import com.dfsek.terra.api.Platform; +import com.dfsek.terra.api.event.EventManager; +import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent; +import com.dfsek.terra.api.registry.CheckedRegistry; +import com.dfsek.terra.api.util.reflection.TypeKey; +import com.dfsek.terra.registry.CheckedRegistryImpl; +import com.dfsek.terra.registry.ShortcutHolder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.fail; + + +class ConfigPackRegistryConcurrencyTest { + private static final int ITERATIONS = 60; + private static final int THREADS = 16; + private static final int TYPES = 96; + private static final int SHORTCUT_TYPES = 8; + + @TempDir + Path packDir; + + @Test + void concurrentRegistryCreation() throws Exception { + Files.writeString(packDir.resolve("pack.yml"), "id: TEST\n"); + List> keys = typeKeys(); + ExecutorService executor = Executors.newFixedThreadPool(THREADS); + try { + for(int iteration = 0; iteration < ITERATIONS; iteration++) { + hammer(newPack(), keys, executor, iteration); + } + } finally { + executor.shutdownNow(); + } + } + + private void hammer(ConfigPackImpl pack, List> keys, ExecutorService executor, int iteration) throws Exception { + CountDownLatch gate = new CountDownLatch(1); + List>>> futures = new ArrayList<>(); + for(int thread = 0; thread < THREADS; thread++) { + int id = thread; + futures.add(executor.submit(() -> { + List order = new ArrayList<>(); + for(int i = 0; i < TYPES; i++) order.add(i); + Collections.shuffle(order, new Random(iteration * 31L + id)); + List> seen = new ArrayList<>(Collections.nCopies(TYPES, null)); + gate.await(); + for(int i : order) { + TypeKey key = keys.get(i); + if(i < SHORTCUT_TYPES) pack.registerShortcut(key, "T" + id, (loader, input, tracker) -> input); + seen.set(i, pack.getOrCreateRegistry(key)); + } + return seen; + })); + } + gate.countDown(); + + List>> results = new ArrayList<>(); + for(Future>> future : futures) { + try { + results.add(future.get(30, TimeUnit.SECONDS)); + } catch(java.util.concurrent.ExecutionException e) { + fail("Iteration " + iteration + ": concurrent registry creation threw", e.getCause()); + } + } + + Map> selfLoaders = loaders(field(pack, "selfLoader", ConfigLoader.class)); + Map> abstractLoaders = loaders( + field(field(pack, "abstractConfigLoader", AbstractConfigLoader.class), "delegate", ConfigLoader.class)); + + for(int i = 0; i < TYPES; i++) { + Type type = keys.get(i).getType(); + CheckedRegistry registry = pack.getRegistry(type); + assertNotNull(registry, "Iteration " + iteration + ": registry lost for " + type.getTypeName()); + for(List> seen : results) { + assertSame(registry, seen.get(i), "Iteration " + iteration + ": registry created twice for " + type.getTypeName()); + } + TypeLoader selfLoader = selfLoaders.get(type); + if(i < SHORTCUT_TYPES) { + ShortcutHolder holder = assertInstanceOf(ShortcutHolder.class, selfLoader, + "Iteration " + iteration + ": shortcut loader missing for " + type.getTypeName()); + assertSame(holder, abstractLoaders.get(type)); + Map shortcuts = field(holder, "shortcuts", Map.class); + assertEquals(THREADS, shortcuts.size(), "Iteration " + iteration + ": shortcuts lost for " + type.getTypeName()); + } else { + Object open = ((CheckedRegistryImpl) registry).getRegistry(); + assertSame(open, selfLoader, "Iteration " + iteration + ": self loader not the registry for " + type.getTypeName()); + assertSame(open, abstractLoaders.get(type), + "Iteration " + iteration + ": abstract loader not the registry for " + type.getTypeName()); + } + } + } + + private ConfigPackImpl newPack() { + ConfigPackImpl[] captured = new ConfigPackImpl[1]; + EventManager events = (EventManager) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ EventManager.class }, + (proxy, method, args) -> { + if(method.getName().equals("callEvent")) { + if(args[0] instanceof ConfigPackPreLoadEvent preLoad) { + captured[0] = (ConfigPackImpl) preLoad.getPack(); + throw new StopLoad(); + } + return args[0]; + } + return null; + }); + Platform platform = (Platform) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ Platform.class }, + (proxy, method, args) -> method.getName().equals("getEventManager") ? events : null); + try { + new ConfigPackImpl(packDir, platform); + fail("pack load should stop at pre-load"); + } catch(StopLoad expected) { + } catch(Exception e) { + throw new AssertionError(e); + } + return captured[0]; + } + + @SuppressWarnings("unchecked") + private static List> typeKeys() throws ClassNotFoundException { + List> keys = new ArrayList<>(); + String[] components = { "Ljava.lang.Object;", "Ljava.lang.String;", "I", "J" }; + for(int depth = 1; keys.size() < TYPES; depth++) { + for(String component : components) { + if(keys.size() < TYPES) keys.add(TypeKey.of((Class) Class.forName("[".repeat(depth) + component))); + } + } + return keys; + } + + @SuppressWarnings("unchecked") + private static Map> loaders(ConfigLoader loader) throws ReflectiveOperationException { + return field(loader, "loaders", Map.class); + } + + private static T field(Object owner, String name, Class type) throws ReflectiveOperationException { + Field field = owner.getClass().getDeclaredField(name); + field.setAccessible(true); + return type.cast(field.get(owner)); + } + + private static final class StopLoad extends RuntimeException { + StopLoad() { + super(null, null, false, false); + } + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/registry/master/ConfigRegistryConcurrencyTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/registry/master/ConfigRegistryConcurrencyTest.java new file mode 100644 index 000000000..2c2bb3571 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/registry/master/ConfigRegistryConcurrencyTest.java @@ -0,0 +1,141 @@ +package com.dfsek.terra.registry.master; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.registry.exception.DuplicateEntryException; +import com.dfsek.terra.api.registry.key.RegistryKey; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class ConfigRegistryConcurrencyTest { + private static final int ITERATIONS = 200; + private static final int THREADS = 16; + + @Test + void concurrentDuplicatePacks() throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(THREADS); + List failures = new ArrayList<>(); + try { + for(int iteration = 0; iteration < ITERATIONS; iteration++) { + ConfigRegistry registry = new ConfigRegistry(); + RegistryKey key = RegistryKey.of("terra", "PACK"); + List packs = new ArrayList<>(); + for(int thread = 0; thread < THREADS; thread++) packs.add(pack()); + List results = race(executor, THREADS, thread -> registry.registerChecked(key, packs.get(thread))); + + List winners = new ArrayList<>(); + int duplicates = 0; + for(int thread = 0; thread < THREADS; thread++) { + Object result = results.get(thread); + if(result == null) { + winners.add(packs.get(thread)); + } else if(result instanceof DuplicateEntryException e) { + assertEquals("Value with identifier \"terra:PACK\" is already defined in registry.", e.getMessage()); + duplicates++; + } else { + throw new AssertionError("unexpected failure", (Throwable) result); + } + } + if(winners.size() != 1 || duplicates != THREADS - 1) { + failures.add("iteration " + iteration + ": " + winners.size() + " registered, " + duplicates + " duplicates"); + continue; + } + assertSame(winners.getFirst(), registry.get(key).orElseThrow(), "iteration " + iteration); + assertSame(winners.getFirst(), registry.getByID("PACK").orElseThrow(), "iteration " + iteration); + assertEquals(1, registry.getMatches("PACK").size(), "iteration " + iteration); + } + } finally { + executor.shutdownNow(); + } + assertTrue(failures.isEmpty(), failures.size() + "/" + ITERATIONS + " iterations raced: " + failures); + } + + @Test + void concurrentPacksSharingId() throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(THREADS); + List failures = new ArrayList<>(); + try { + for(int iteration = 0; iteration < ITERATIONS; iteration++) { + ConfigRegistry registry = new ConfigRegistry(); + List packs = new ArrayList<>(); + for(int thread = 0; thread < THREADS; thread++) packs.add(pack()); + List results = race(executor, THREADS, + thread -> registry.registerChecked(RegistryKey.of("ns" + thread, "PACK"), packs.get(thread))); + for(Object result : results) { + if(result != null) throw new AssertionError("unexpected failure", (Throwable) result); + } + + Map matches = registry.getMatches("PACK"); + boolean complete = matches.size() == THREADS; + for(int thread = 0; thread < THREADS && complete; thread++) { + complete = matches.get(RegistryKey.of("ns" + thread, "PACK")) == packs.get(thread); + } + if(!complete) failures.add("iteration " + iteration + ": " + matches.size() + "/" + THREADS + " found by ID"); + assertEquals(THREADS, registry.keys().size(), "iteration " + iteration); + } + } finally { + executor.shutdownNow(); + } + assertTrue(failures.isEmpty(), failures.size() + "/" + ITERATIONS + " iterations lost entries: " + failures); + } + + private static List race(ExecutorService executor, int threads, ThreadAction action) throws Exception { + CountDownLatch ready = new CountDownLatch(threads); + CountDownLatch gate = new CountDownLatch(1); + List> futures = new ArrayList<>(); + for(int thread = 0; thread < threads; thread++) { + int id = thread; + futures.add(executor.submit(() -> { + ready.countDown(); + gate.await(); + try { + action.run(id); + return null; + } catch(RuntimeException e) { + return e; + } + })); + } + ready.await(); + gate.countDown(); + List results = new ArrayList<>(); + for(Future future : futures) { + try { + results.add(future.get(30, TimeUnit.SECONDS)); + } catch(ExecutionException e) { + throw new AssertionError(e.getCause()); + } + } + return results; + } + + private static ConfigPack pack() { + return (ConfigPack) Proxy.newProxyInstance(ConfigRegistryConcurrencyTest.class.getClassLoader(), new Class[]{ ConfigPack.class }, + (proxy, method, args) -> switch(method.getName()) { + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == args[0]; + case "toString" -> "pack@" + Integer.toHexString(System.identityHashCode(proxy)); + default -> null; + }); + } + + @FunctionalInterface + private interface ThreadAction { + void run(int thread); + } +} From 44408a1b722019dc34840e933eaa861ae45f1545 Mon Sep 17 00:00:00 2001 From: Zoe Gidiere Date: Sun, 8 Nov 2026 22:07:19 -0700 Subject: [PATCH 43/44] build: rerun addon resource processing when versions change --- buildSrc/src/main/kotlin/CompilationConfig.kt | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/buildSrc/src/main/kotlin/CompilationConfig.kt b/buildSrc/src/main/kotlin/CompilationConfig.kt index 002b4c7f6..d93443b49 100644 --- a/buildSrc/src/main/kotlin/CompilationConfig.kt +++ b/buildSrc/src/main/kotlin/CompilationConfig.kt @@ -41,22 +41,26 @@ fun Project.configureCompilation() { } } + // Gradle doesn't fingerprint filter arguments; the tokens are declared as inputs. + val metadataTokens = mapOf( + "DESCRIPTION" to properties["terra.description"], + "WIKI" to properties["terra.wiki"], + "SOURCE" to properties["terra.source"], + "ISSUES" to properties["terra.issues"], + "LICENSE" to properties["terra.license"] + ) tasks.withType { include("**/*.*") + inputs.properties(metadataTokens.mapKeys { "token.${it.key}" }.mapValues { it.value.toString() }) filter( - "tokens" to mapOf( - "DESCRIPTION" to properties["terra.description"], - "WIKI" to properties["terra.wiki"], - "SOURCE" to properties["terra.source"], - "ISSUES" to properties["terra.issues"], - "LICENSE" to properties["terra.license"] - ) + "tokens" to metadataTokens ) } afterEvaluate { tasks.withType { include("**/*.*") + inputs.property("token.VERSION", version.toString()) filter( "tokens" to mapOf( "VERSION" to version.toString() From bfa126bc12049524601fb4c0299565817ae2d938 Mon Sep 17 00:00:00 2001 From: Zoe Gidiere Date: Mon, 9 Nov 2026 13:27:46 -0700 Subject: [PATCH 44/44] feat: build Bukkit biomes, dimensions and timelines from environment attributes --- buildSrc/src/main/kotlin/Versions.kt | 2 +- .../com/dfsek/terra/AbstractPlatform.java | 6 +- .../attribute/platform}/AttributeReport.java | 11 +- .../attribute/platform}/AttributeSlots.java | 2 +- .../attribute/platform/ParentEntryHolder.java | 8 + .../world/attribute/platform/ParentFold.java | 34 ++ .../platform/AttributeReportTest.java | 51 ++ .../platform/AttributeSlotsTest.java | 27 + .../attribute/platform/ParentFoldTest.java | 54 ++ platforms/bukkit/build.gradle.kts | 9 +- platforms/bukkit/common/build.gradle.kts | 29 +- .../com/dfsek/terra/bukkit/BukkitAddon.java | 13 - .../dfsek/terra/bukkit/BukkitPlatform.java | 100 ++-- .../terra/bukkit/TerraBukkitBootstrap.java | 38 ++ .../dfsek/terra/bukkit/TerraBukkitPlugin.java | 11 +- .../bukkit/attribute/PaperDimensions.java | 331 +++++++++++++ .../terra/bukkit/attribute/PaperVanilla.java | 88 ++++ .../terra/bukkit/attribute/WyckBridge.java | 93 ++++ .../config/BiomeAdditionsSoundTemplate.java | 30 -- .../bukkit/config/BiomeMoodSoundTemplate.java | 40 -- .../config/BiomeParticleConfigTemplate.java | 42 -- .../bukkit/config/EntityTypeTemplate.java | 22 - .../bukkit/config/MusicSoundTemplate.java | 40 -- .../bukkit/config/SoundEventTemplate.java | 29 -- .../terra/bukkit/config/SpawnCostConfig.java | 38 -- .../terra/bukkit/config/SpawnEntryConfig.java | 42 -- .../bukkit/config/SpawnSettingsTemplate.java | 54 -- .../terra/bukkit/config/SpawnTypeConfig.java | 32 -- .../bukkit/config/VanillaBiomeProperties.java | 181 ------- .../bukkit/config/VillagerTypeTemplate.java | 22 - .../bukkit/generator/BukkitBiomeProvider.java | 6 +- .../generator/BukkitBlockPopulator.java | 2 +- .../BukkitChunkGeneratorWrapper.java | 19 +- .../terra/bukkit/listeners/BiomeListener.java | 73 --- .../bukkit/listeners/CommonListener.java | 7 +- .../bukkit/listeners/DimensionListener.java | 41 ++ .../dfsek/terra/bukkit/util/ServerThread.java | 67 +++ .../terra/bukkit/util/VanillaParticles.java | 86 ---- .../terra/bukkit/world/BiomeHandler.java | 445 ++++++++++++----- .../terra/bukkit/world/BukkitBiomeInfo.java | 2 +- .../bukkit/world/BukkitPlatformBiome.java | 16 +- .../src/main/resources/paper-plugin.yml | 1 + .../bukkit/attribute/BukkitParentsTest.java | 141 ++++++ .../bukkit/attribute/PaperBiomeTest.java | 138 ++++++ .../bukkit/attribute/PaperDimensionsTest.java | 462 ++++++++++++++++++ .../terra/bukkit/util/ServerThreadTest.java | 101 ++++ .../terra/bukkit/world/BiomeHandlerTest.java | 286 +++++++++++ platforms/fabric/build.gradle.kts | 3 + platforms/minecraft-common/build.gradle.kts | 33 ++ .../terra/minecraft/attribute/BiomeTags.java | 71 +++ .../attribute/MinecraftAttributeParents.java | 68 +-- .../attribute/MinecraftBiomeFactory.java | 16 +- .../attribute/MinecraftDimensionFactory.java | 69 ++- .../attribute/MinecraftTimelines.java | 75 +-- .../attribute/PackAttributeTable.java | 2 +- .../minecraft}/attribute/PackParents.java | 23 +- .../minecraft/attribute/TimelineRef.java | 38 ++ .../attribute/VanillaAttributeMaps.java | 2 +- .../minecraft}/attribute/VanillaCodecs.java | 2 +- .../minecraft}/attribute/VanillaContext.java | 2 +- .../minecraft}/attribute/VanillaIds.java | 2 +- .../attribute/VanillaParentReader.java | 3 +- .../minecraft/attribute/WorldSettings.java | 4 + .../minecraft/attribute/BiomeTagsTest.java} | 22 +- .../MinecraftAttributeParentsTest.java | 168 +++---- .../attribute/MinecraftBiomeFactoryTest.java | 143 +++--- .../MinecraftDimensionFactoryTest.java | 210 +++----- .../attribute/MinecraftTimelinesTest.java | 160 +++--- .../attribute/VanillaCodecHarnessTest.java | 26 +- .../attribute/VanillaContextTest.java | 6 +- .../attribute/VanillaParentReaderTest.java | 54 +- .../attribute/FakePackAttributes.java | 8 +- .../attribute/MinecraftTestSupport.java | 22 +- .../terra/minecraft}/attribute/TestBiome.java | 15 +- .../attribute/TestPlatformBiome.java | 37 ++ platforms/mixin-common/build.gradle.kts | 5 +- .../java/com/dfsek/terra/mod/ModPlatform.java | 4 +- .../terra/mod/config/ProtoPlatformBiome.java | 6 +- .../com/dfsek/terra/mod/util/BiomeUtil.java | 5 +- .../com/dfsek/terra/mod/util/PresetUtil.java | 50 +- .../com/dfsek/terra/mod/util/TagUtil.java | 56 +-- platforms/mixin-lifecycle/build.gradle.kts | 1 + .../lifecycle/RegistryDataLoaderMixin.java | 2 +- .../lifecycle/util/LifecycleBiomeUtil.java | 15 +- .../terra/lifecycle/util/LifecycleUtil.java | 12 +- 85 files changed, 3191 insertions(+), 1621 deletions(-) rename {platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute => common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform}/AttributeReport.java (84%) rename {platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute => common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform}/AttributeSlots.java (95%) create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/ParentEntryHolder.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/ParentFold.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/AttributeReportTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/AttributeSlotsTest.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/ParentFoldTest.java create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitBootstrap.java create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/PaperDimensions.java create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/PaperVanilla.java create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/WyckBridge.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeAdditionsSoundTemplate.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeMoodSoundTemplate.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeParticleConfigTemplate.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/EntityTypeTemplate.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/MusicSoundTemplate.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SoundEventTemplate.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnCostConfig.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnEntryConfig.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnSettingsTemplate.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnTypeConfig.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VanillaBiomeProperties.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VillagerTypeTemplate.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/BiomeListener.java create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/DimensionListener.java create mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/ServerThread.java delete mode 100644 platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VanillaParticles.java create mode 100644 platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/BukkitParentsTest.java create mode 100644 platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/PaperBiomeTest.java create mode 100644 platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/PaperDimensionsTest.java create mode 100644 platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/util/ServerThreadTest.java create mode 100644 platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/world/BiomeHandlerTest.java create mode 100644 platforms/minecraft-common/build.gradle.kts create mode 100644 platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/BiomeTags.java rename platforms/{mixin-common/src/main/java/com/dfsek/terra/mod => minecraft-common/src/main/java/com/dfsek/terra/minecraft}/attribute/MinecraftAttributeParents.java (70%) rename platforms/{mixin-common/src/main/java/com/dfsek/terra/mod => minecraft-common/src/main/java/com/dfsek/terra/minecraft}/attribute/MinecraftBiomeFactory.java (93%) rename platforms/{mixin-common/src/main/java/com/dfsek/terra/mod => minecraft-common/src/main/java/com/dfsek/terra/minecraft}/attribute/MinecraftDimensionFactory.java (72%) rename platforms/{mixin-common/src/main/java/com/dfsek/terra/mod => minecraft-common/src/main/java/com/dfsek/terra/minecraft}/attribute/MinecraftTimelines.java (84%) rename platforms/{mixin-common/src/main/java/com/dfsek/terra/mod => minecraft-common/src/main/java/com/dfsek/terra/minecraft}/attribute/PackAttributeTable.java (99%) rename platforms/{mixin-common/src/main/java/com/dfsek/terra/mod => minecraft-common/src/main/java/com/dfsek/terra/minecraft}/attribute/PackParents.java (71%) create mode 100644 platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/TimelineRef.java rename platforms/{mixin-common/src/main/java/com/dfsek/terra/mod => minecraft-common/src/main/java/com/dfsek/terra/minecraft}/attribute/VanillaAttributeMaps.java (98%) rename platforms/{mixin-common/src/main/java/com/dfsek/terra/mod => minecraft-common/src/main/java/com/dfsek/terra/minecraft}/attribute/VanillaCodecs.java (96%) rename platforms/{mixin-common/src/main/java/com/dfsek/terra/mod => minecraft-common/src/main/java/com/dfsek/terra/minecraft}/attribute/VanillaContext.java (98%) rename platforms/{mixin-common/src/main/java/com/dfsek/terra/mod => minecraft-common/src/main/java/com/dfsek/terra/minecraft}/attribute/VanillaIds.java (92%) rename platforms/{mixin-common/src/main/java/com/dfsek/terra/mod => minecraft-common/src/main/java/com/dfsek/terra/minecraft}/attribute/VanillaParentReader.java (97%) create mode 100644 platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/WorldSettings.java rename platforms/{mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TagUtilTest.java => minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/BiomeTagsTest.java} (82%) rename platforms/{mixin-common/src/test/java/com/dfsek/terra/mod => minecraft-common/src/test/java/com/dfsek/terra/minecraft}/attribute/MinecraftAttributeParentsTest.java (77%) rename platforms/{mixin-common/src/test/java/com/dfsek/terra/mod => minecraft-common/src/test/java/com/dfsek/terra/minecraft}/attribute/MinecraftBiomeFactoryTest.java (83%) rename platforms/{mixin-common/src/test/java/com/dfsek/terra/mod => minecraft-common/src/test/java/com/dfsek/terra/minecraft}/attribute/MinecraftDimensionFactoryTest.java (65%) rename platforms/{mixin-common/src/test/java/com/dfsek/terra/mod => minecraft-common/src/test/java/com/dfsek/terra/minecraft}/attribute/MinecraftTimelinesTest.java (78%) rename platforms/{mixin-common/src/test/java/com/dfsek/terra/mod => minecraft-common/src/test/java/com/dfsek/terra/minecraft}/attribute/VanillaCodecHarnessTest.java (93%) rename platforms/{mixin-common/src/test/java/com/dfsek/terra/mod => minecraft-common/src/test/java/com/dfsek/terra/minecraft}/attribute/VanillaContextTest.java (96%) rename platforms/{mixin-common/src/test/java/com/dfsek/terra/mod => minecraft-common/src/test/java/com/dfsek/terra/minecraft}/attribute/VanillaParentReaderTest.java (89%) rename platforms/{mixin-common/src/test/java/com/dfsek/terra/mod => minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft}/attribute/FakePackAttributes.java (91%) rename platforms/{mixin-common/src/test/java/com/dfsek/terra/mod => minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft}/attribute/MinecraftTestSupport.java (74%) rename platforms/{mixin-common/src/test/java/com/dfsek/terra/mod => minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft}/attribute/TestBiome.java (72%) create mode 100644 platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/TestPlatformBiome.java diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index bdfec58ce..64a681d91 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -63,7 +63,7 @@ object Versions { const val paperBuild = "$minecraft.build.244-stable" const val paper = paperBuild const val runPaper = "3.0.2" - const val wyck = "4.0.0-837d6ec" + const val wyck = "4.0.0-0f573ad7" const val cloud = "2.0.1" const val multiverse = "5.3.0" } diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java b/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java index 8a3ce64b5..aad800abe 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java @@ -129,11 +129,9 @@ public abstract class AbstractPlatform implements Platform { public static int getMoonriseGenerationThreadsWithReflection() { try { - Class prioritisedThreadPoolClazz = Class.forName("ca.spottedleaf.concurrentutil.executor.thread.PrioritisedThreadPool"); - Method getCoreThreadsMethod = prioritisedThreadPoolClazz.getDeclaredMethod("getCoreThreads"); - getCoreThreadsMethod.setAccessible(true); Class moonriseCommonClazz = Class.forName("ca.spottedleaf.moonrise.common.util.MoonriseCommon"); - Object pool = moonriseCommonClazz.getDeclaredField("WORKER_POOL").get(null); + Object pool = moonriseCommonClazz.getField("WORKER_POOL").get(null); + Method getCoreThreadsMethod = pool.getClass().getMethod("getCoreThreads"); int threads = ((Thread[]) getCoreThreadsMethod.invoke(pool)).length; logger.info("{} found, setting {} generation threads.", moonrise, threads); return threads; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeReport.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/AttributeReport.java similarity index 84% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeReport.java rename to common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/AttributeReport.java index ac10cbf38..1a8091487 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeReport.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/AttributeReport.java @@ -1,8 +1,9 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.world.attribute.platform; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -22,6 +23,7 @@ public final class AttributeReport { private final Consumer warn; private final Consumer debug; private final Set notApplied = ConcurrentHashMap.newKeySet(); + private final Set> notAppliedToWorld = ConcurrentHashMap.newKeySet(); public AttributeReport(String pack, Consumer warn, Consumer debug) { this.pack = Objects.requireNonNull(pack, "pack"); @@ -65,4 +67,11 @@ public final class AttributeReport { public void notApplied(String key) { if(notApplied.add(key)) debug.accept("Pack \"" + pack + "\": attribute \"" + key + "\" is not applied on this platform"); } + + public void notAppliedToWorld(String key, String world) { + if(notAppliedToWorld.add(Map.entry(key, world))) { + debug.accept("Pack \"" + pack + "\": attribute \"" + key + "\" is not applied to world \"" + world + + "\": it is fixed when the world is created"); + } + } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeSlots.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/AttributeSlots.java similarity index 95% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeSlots.java rename to common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/AttributeSlots.java index 067f03c80..4574b0d64 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeSlots.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/AttributeSlots.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.world.attribute.platform; import org.jetbrains.annotations.Nullable; diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/ParentEntryHolder.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/ParentEntryHolder.java new file mode 100644 index 000000000..8c805e57a --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/ParentEntryHolder.java @@ -0,0 +1,8 @@ +package com.dfsek.terra.world.attribute.platform; + +public interface ParentEntryHolder { + /** + * {@link AttributeSlots#EMPTY} until the platform sets them. + */ + AttributeSlots parentEntries(); +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/ParentFold.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/ParentFold.java new file mode 100644 index 000000000..4c394e539 --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/ParentFold.java @@ -0,0 +1,34 @@ +package com.dfsek.terra.world.attribute.platform; + +import java.util.Objects; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; + + +public final class ParentFold { + private ParentFold() { + } + + /** + * Composes {@code upper} over {@code lower} per attribute, or overrides with their resolved value when they don't compose. + */ + public static AttributeSlots fold(AttributeHandle handle, Iterable> attributes, AttributeSlots lower, + AttributeSlots upper) { + Objects.requireNonNull(lower, "lower"); + Objects.requireNonNull(upper, "upper"); + AttributeEntry[] slots = new AttributeEntry[handle.attributeCount()]; + for(Attribute attribute : attributes) fold(handle, attribute, lower, upper, slots); + return AttributeSlots.of(slots); + } + + private static void fold(AttributeHandle handle, Attribute attribute, AttributeSlots lower, AttributeSlots upper, + AttributeEntry[] slots) { + AttributeEntry below = lower.get(attribute); + AttributeEntry above = upper.get(attribute); + if(below == null && above == null) return; + slots[attribute.index()] = handle.compose(attribute, below, above) + .orElseGet(() -> AttributeEntry.override(handle.resolve(attribute, below, above, null))); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/AttributeReportTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/AttributeReportTest.java new file mode 100644 index 000000000..eb997f3dc --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/AttributeReportTest.java @@ -0,0 +1,51 @@ +package com.dfsek.terra.world.attribute.platform; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +class AttributeReportTest { + private final List warnings = new ArrayList<>(); + private final List debugs = new ArrayList<>(); + private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add); + + @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 notAppliedToWorldOnce() { + report.notAppliedToWorld("terra:dimension/min_y", "world"); + report.notAppliedToWorld("terra:dimension/min_y", "world"); + + assertEquals(List.of(), warnings); + assertEquals(List.of( + "Pack \"test\": attribute \"terra:dimension/min_y\" is not applied to world \"world\": it is fixed when the world is created"), + debugs); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/AttributeSlotsTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/AttributeSlotsTest.java new file mode 100644 index 000000000..2c1702cc3 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/AttributeSlotsTest.java @@ -0,0 +1,27 @@ +package com.dfsek.terra.world.attribute.platform; + +import org.junit.jupiter.api.Test; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.world.attribute.AttributeHandleImpl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + + +class AttributeSlotsTest { + @Test + void outOfRangeIsNull() { + AttributeHandle handle = new AttributeHandleImpl(); + Attribute attribute = null; + for(int i = 0; i <= 5; i++) { + attribute = handle.attributeBuilder(AttributeKey.parse("test:a" + i), handle.types().floatType(), 0f).build(); + } + assertEquals(5, attribute.index()); + + assertNull(AttributeSlots.of(new AttributeEntry[1]).get(attribute)); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/ParentFoldTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/ParentFoldTest.java new file mode 100644 index 000000000..0ee531cbb --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/ParentFoldTest.java @@ -0,0 +1,54 @@ +package com.dfsek.terra.world.attribute.platform; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.world.attribute.AttributeHandleImpl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + + +class ParentFoldTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final Attribute FOG_END = HANDLE.attributeBuilder(AttributeKey.parse("test:fog_end"), + HANDLE.types().floatType(), 1024f).build(); + + private static AttributeSlots slots(AttributeEntry entry) { + AttributeEntry[] entries = new AttributeEntry[HANDLE.attributeCount()]; + entries[FOG_END.index()] = entry; + return AttributeSlots.of(entries); + } + + private static AttributeEntry fold(AttributeEntry lower, AttributeEntry upper) { + return ParentFold.fold(HANDLE, List.of(FOG_END), slots(lower), slots(upper)).get(FOG_END); + } + + @Test + void foldComposes() { + assertNull(fold(null, null)); + AttributeEntry lower = AttributeEntry.override(2f); + assertSame(lower, fold(lower, null)); + AttributeEntry upper = AttributeEntry.override(2f); + assertSame(upper, fold(null, upper)); + assertEquals(AttributeEntry.of(Operation.ADD, 3f), fold(AttributeEntry.of(Operation.ADD, 1f), AttributeEntry.of(Operation.ADD, 2f))); + } + + @Test + void foldOverrides() { + AttributeEntry lower = AttributeEntry.of(Operation.ADD, 1f); + AttributeEntry upper = AttributeEntry.of(Operation.MULTIPLY, 2f); + AttributeEntry folded = fold(lower, upper); + assertNotNull(folded); + assertEquals(Operation.OVERRIDE, folded.operation()); + assertEquals(HANDLE.resolve(FOG_END, lower, upper, null), folded.argument()); + } +} diff --git a/platforms/bukkit/build.gradle.kts b/platforms/bukkit/build.gradle.kts index 19e82e6ae..5f006ce52 100644 --- a/platforms/bukkit/build.gradle.kts +++ b/platforms/bukkit/build.gradle.kts @@ -27,11 +27,18 @@ tasks { minecraftVersion(Versions.Bukkit.minecraft) dependsOn(shadowJar) pluginJars(shadowJar.get().archiveFile) + // Modrinth's Wyck lacks our fixes. + val wyckJar = file("${System.getProperty("user.home")}/Wyck/paper/build/libs/Wyck-${Versions.Bukkit.wyck}.jar") + pluginJars(wyckJar) + doFirst { + if(!wyckJar.isFile) { + throw GradleException("No Wyck plugin jar at $wyckJar: build and publish ~/Wyck (Wyck ${Versions.Bukkit.wyck}) first") + } + } downloadPlugins { modrinth("viaversion", "5.12.2") modrinth("viabackwards", "5.12.2") - modrinth("wyck", Versions.Bukkit.wyck) } } } diff --git a/platforms/bukkit/common/build.gradle.kts b/platforms/bukkit/common/build.gradle.kts index 3a3d3805a..bd5750e05 100644 --- a/platforms/bukkit/common/build.gradle.kts +++ b/platforms/bukkit/common/build.gradle.kts @@ -1,6 +1,19 @@ -repositories { - +plugins { + id("dev.architectury.loom-no-remap") version Versions.Mod.architecturyLoom } + +// Loom here is in another classloader than minecraft-common's and must not read its extension. +extra["fabric.loom.disableProjectDependentMods"] = "true" + +loom { + accessWidenerPath.set(project(":platforms:mixin-common").file("src/main/resources/terra.accesswidener")) +} + +// Paper and Multiverse declare runtime-only libraries that break Loom's mod scan. +configurations.matching { it.name.endsWith("CompileDependencyResolve") }.configureEach { + attributes.attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_API)) +} + tasks.withType().configureEach { options.release = 25 } @@ -8,13 +21,23 @@ tasks.withType().configureEach { dependencies { shadedApi(project(":common:implementation:base")) + // Paper runs vanilla unobfuscated and Mojang-named. + minecraft("com.mojang:minecraft:${Versions.Bukkit.minecraft}") + + implementation(project(":platforms:minecraft-common")) { isTransitive = false } + shaded(project(":platforms:minecraft-common")) { isTransitive = false } + compileOnly("io.papermc.paper", "paper-api", Versions.Bukkit.paper) - compileOnly("dev.wyck", "Wyck", Versions.Bukkit.wyck) + compileOnly("com.dfsek.wyck", "Wyck", Versions.Bukkit.wyck) compileOnly("org.mvplugins.multiverse.core", "multiverse-core", Versions.Bukkit.multiverse) shadedApi("com.google.guava", "guava", Versions.Libraries.Internal.guava) shadedApi("org.incendo", "cloud-paper", Versions.Bukkit.cloud) + + testImplementation(testFixtures(project(":platforms:minecraft-common"))) + testImplementation(project(":common:addons:minecraft-attributes")) + testImplementation("io.papermc.paper", "paper-api", Versions.Bukkit.paper) } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitAddon.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitAddon.java index 958096c87..720cc664c 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitAddon.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitAddon.java @@ -4,12 +4,9 @@ import ca.solostudios.strata.Versions; import ca.solostudios.strata.version.Version; 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.ConfigPackPreLoadEvent; import com.dfsek.terra.api.event.functional.FunctionalEventHandler; -import com.dfsek.terra.api.world.biome.Biome; import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions; -import com.dfsek.terra.bukkit.config.VanillaBiomeProperties; public class BukkitAddon implements BaseAddon { @@ -28,16 +25,6 @@ public class BukkitAddon implements BaseAddon { .register(this, ConfigPackPreLoadEvent.class) .then(event -> event.getPack().getContext().put(event.loadTemplate(new PreLoadCompatibilityOptions()))) .global(); - - terraBukkitPlugin.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/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java index b3491ef77..1d3cc1c09 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java @@ -22,61 +22,48 @@ import com.dfsek.tectonic.api.depth.DepthTracker; import com.dfsek.tectonic.api.exception.LoadException; import com.dfsek.terra.api.addon.BaseAddon; -import com.dfsek.terra.bukkit.config.BiomeAdditionsSoundTemplate; -import com.dfsek.terra.bukkit.config.BiomeMoodSoundTemplate; -import com.dfsek.terra.bukkit.config.BiomeParticleConfigTemplate; -import com.dfsek.terra.bukkit.config.EntityTypeTemplate; -import com.dfsek.terra.bukkit.config.MusicSoundTemplate; -import com.dfsek.terra.bukkit.config.SoundEventTemplate; -import com.dfsek.terra.bukkit.config.SpawnCostConfig; -import com.dfsek.terra.bukkit.config.SpawnEntryConfig; -import com.dfsek.terra.bukkit.config.SpawnSettingsTemplate; -import com.dfsek.terra.bukkit.config.SpawnTypeConfig; -import com.dfsek.terra.bukkit.config.VillagerTypeTemplate; -import dev.wyck.biome.TemperatureModifier; -import dev.wyck.biome.entity.MobCategory; -import dev.wyck.biome.entity.MobSpawnSettings; -import dev.wyck.environment.GrassColorModifier; -import dev.wyck.environment.particle.ParticleCatalog; -import dev.wyck.environment.sounds.AmbientAdditionsSettings; -import dev.wyck.environment.sounds.AmbientMoodSettings; -import dev.wyck.environment.sounds.Music; -import dev.wyck.environment.sounds.SoundEvent; -import dev.wyck.keys.ResourceKey; import io.papermc.paper.registry.RegistryAccess; import io.papermc.paper.registry.RegistryKey; import org.bukkit.Bukkit; import org.bukkit.NamespacedKey; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Villager; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.List; -import java.util.Locale; +import java.util.concurrent.CancellationException; import com.dfsek.terra.AbstractPlatform; import com.dfsek.terra.api.block.state.BlockState; 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.bukkit.attribute.PaperDimensions; import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper; import com.dfsek.terra.bukkit.handles.BukkitItemHandle; import com.dfsek.terra.bukkit.handles.BukkitWorldHandle; +import com.dfsek.terra.bukkit.util.ServerThread; import com.dfsek.terra.bukkit.world.BiomeHandler; import com.dfsek.terra.bukkit.world.BukkitPlatformBiome; +import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents; public class BukkitPlatform extends AbstractPlatform { private static final Logger LOGGER = LoggerFactory.getLogger(BukkitPlatform.class); + private static final long SERVER_THREAD_POLL_MILLIS = 50; private final ItemHandle itemHandle = new BukkitItemHandle(); private final WorldHandle handle = new BukkitWorldHandle(); + private final MinecraftAttributeParents attributeParents = new MinecraftAttributeParents(getAttributeHandle()); + + private final PaperDimensions dimensions = new PaperDimensions(getAttributeHandle(), attributeParents, + () -> !Bukkit.getOnlinePlayers().isEmpty()); + private final TerraBukkitPlugin plugin; private int generationThreads; @@ -94,12 +81,44 @@ public class BukkitPlatform extends AbstractPlatform { return plugin; } + @Override + public AttributeParents getAttributeParents() { + return attributeParents; + } + + public MinecraftAttributeParents attributeParents() { + return attributeParents; + } + + public PaperDimensions dimensions() { + return dimensions; + } + @Override public boolean reload() { getTerraConfig().load(this); - boolean succeed = loadConfigPacks(); - BiomeHandler.registerBiomes(getRawConfigRegistry()); - BiomeHandler.addToVanillaTags(getRawConfigRegistry()); + attributeParents.beginPackReload(); + try { + boolean succeed = loadConfigPacks(); + // Packs load off the server thread; registries, tags and generators change on it. + ServerThread.run(this::applyReloadedPacks, task -> plugin.getGlobalRegionScheduler().execute(plugin, task), + Bukkit::isGlobalTickThread, () -> Bukkit.isStopping() || !plugin.isEnabled(), SERVER_THREAD_POLL_MILLIS); + if(succeed) { + LOGGER.info("Packs reloaded; dimension types, generation settings, timelines and existing biomes need a restart."); + } + + return succeed; + } catch(CancellationException e) { + LOGGER.warn("Packs not reloaded: the server stopped before they could be applied"); + return false; + } finally { + attributeParents.endPackReload(); + } + } + + private void applyReloadedPacks() { + BiomeHandler.registerBiomes(this); + BiomeHandler.addToVanillaTags(this); Bukkit.getWorlds().forEach(world -> { if(world.getGenerator() instanceof BukkitChunkGeneratorWrapper wrapper) { @@ -109,8 +128,6 @@ public class BukkitPlatform extends AbstractPlatform { }); } }); - - return succeed; } @Override @@ -152,30 +169,7 @@ public class BukkitPlatform extends AbstractPlatform { public void register(TypeRegistry registry) { super.register(registry); registry.registerLoader(BlockState.class, (type, o, loader, depthTracker) -> handle.createBlockState((String) o)) - .registerLoader(PlatformBiome.class, (type, o, loader, depthTracker) -> parseBiome((String) o, depthTracker)) - .registerLoader(ResourceKey.class, (type, o, loader, depthTracker) -> { - NamespacedKey key = NamespacedKey.fromString(((String) o).toLowerCase(Locale.ROOT)); - if(key == null) throw new LoadException("Invalid identifier: " + o, depthTracker); - return ResourceKey.of(key); - }) - .registerLoader(GrassColorModifier.class, - (type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase( - Locale.ROOT))) - .registerLoader(TemperatureModifier.class, - (type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase( - Locale.ROOT))) - .registerLoader(MobCategory.class, (type, o, loader, depthTracker) -> MobCategory.valueOf((String) o)) - .registerLoader(ParticleCatalog.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(Villager.Type.class, VillagerTypeTemplate::new); + .registerLoader(PlatformBiome.class, (type, o, loader, depthTracker) -> parseBiome((String) o, depthTracker)); } protected BukkitPlatformBiome parseBiome(String id, DepthTracker depthTracker) throws LoadException { diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitBootstrap.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitBootstrap.java new file mode 100644 index 000000000..681bf2435 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitBootstrap.java @@ -0,0 +1,38 @@ +/* + * This file is part of Terra. + * + * Terra is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Terra is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Terra. If not, see . + */ +package com.dfsek.terra.bukkit; + +import io.papermc.paper.plugin.bootstrap.BootstrapContext; +import io.papermc.paper.plugin.bootstrap.PluginBootstrap; +import io.papermc.paper.plugin.lifecycle.event.registrar.ReloadableRegistrarEvent; +import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents; +import io.papermc.paper.registry.RegistryKey; + +import com.dfsek.terra.bukkit.world.BiomeHandler; + + +/** + * Paper only offers tag lifecycle events to a bootstrapper. + */ +public class TerraBukkitBootstrap implements PluginBootstrap { + @Override + public void bootstrap(BootstrapContext context) { + context.getLifecycleManager().registerEventHandler(LifecycleEvents.TAGS.postFlatten(RegistryKey.BIOME), event -> { + if(event.cause() == ReloadableRegistrarEvent.Cause.RELOAD) BiomeHandler.addToReloadedTags(event.registrar()); + }); + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java index 5caa27e39..2edb9872a 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java @@ -38,9 +38,10 @@ import com.dfsek.terra.api.command.CommandSender; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.event.events.platform.CommandRegistrationEvent; import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent; +import com.dfsek.terra.bukkit.attribute.PaperVanilla; import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper; -import com.dfsek.terra.bukkit.listeners.BiomeListener; import com.dfsek.terra.bukkit.listeners.CommonListener; +import com.dfsek.terra.bukkit.listeners.DimensionListener; import com.dfsek.terra.bukkit.world.BiomeHandler; import com.dfsek.terra.bukkit.world.BukkitAdapter; @@ -56,8 +57,10 @@ public class TerraBukkitPlugin extends JavaPlugin { platform = new BukkitPlatform(this); platform.getEventManager().callEvent(new PlatformInitializationEvent()); // Loads config packs - BiomeHandler.registerBiomes(platform.getRawConfigRegistry()); - BiomeHandler.addToVanillaTags(platform.getRawConfigRegistry()); + platform.attributeParents().beginLoad(PaperVanilla.context(PaperVanilla.server().registryAccess())); + BiomeHandler.registerBiomes(platform); + platform.dimensions().registerPacks(platform.getRawConfigRegistry().entries()); + BiomeHandler.addToVanillaTags(platform); try { PaperCommandManager commandManager = getCommandSenderPaperCommandManager(); @@ -76,7 +79,7 @@ public class TerraBukkitPlugin extends JavaPlugin { } Bukkit.getPluginManager().registerEvents(new CommonListener(platform), this); // Register master event listener - Bukkit.getPluginManager().registerEvents(new BiomeListener(platform), this); + Bukkit.getPluginManager().registerEvents(new DimensionListener(platform.dimensions()), this); } @NotNull diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/PaperDimensions.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/PaperDimensions.java new file mode 100644 index 000000000..ba2e1d13d --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/PaperDimensions.java @@ -0,0 +1,331 @@ +/* + * This file is part of Terra. + * + * Terra is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Terra is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Terra. If not, see . + */ +package com.dfsek.terra.bukkit.attribute; + +import net.minecraft.core.Holder; +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.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.attribute.EnvironmentAttributeSystem; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.timeline.Timeline; +import org.bukkit.World; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; + +import com.dfsek.terra.api.config.ConfigPack; +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.DecodeException; +import com.dfsek.terra.api.world.attribute.PackAttributes; +import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper; +import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents; +import com.dfsek.terra.minecraft.attribute.MinecraftDimensionFactory; +import com.dfsek.terra.minecraft.attribute.MinecraftTimelines; +import com.dfsek.terra.minecraft.attribute.PackAttributeTable; +import com.dfsek.terra.minecraft.attribute.PackParents; +import com.dfsek.terra.minecraft.attribute.TimelineRef; +import com.dfsek.terra.minecraft.attribute.VanillaCodecs; +import com.dfsek.terra.minecraft.attribute.VanillaContext; +import com.dfsek.terra.minecraft.attribute.WorldSettings; +import com.dfsek.terra.world.attribute.platform.AttributeReport; + + +public final class PaperDimensions { + // Paper fixes these when it builds the level. + static final List LEVEL_FIXED = List.of("min_y", "height", "has_skylight"); + + private static final Logger LOGGER = LoggerFactory.getLogger(PaperDimensions.class); + private static final String PACK_CONFIG = "pack.yml"; + private static final String NOT_ON_THIS_PLATFORM = "not applied on this platform"; + private static final String VANILLA_GENERATION = "vanilla-generation"; + private static final String HEIGHT = "height"; + private static final String LOGICAL_HEIGHT = "logical_height"; + private static final List> UNSUPPORTED_GENERATION = List.of(AttributeKey.parse("terra:world/sea_level"), + AttributeKey.parse("terra:world/spawn_height")); + + private final AttributeHandle handle; + private final MinecraftAttributeParents parents; + private final BooleanSupplier playersOnline; + private final Server server; + private final Consumer info; + private final Consumer warn; + // Direct lists survive tag reloads. + private final Map resolvedTimelines = new ConcurrentHashMap<>(); + + public PaperDimensions(AttributeHandle handle, MinecraftAttributeParents parents, BooleanSupplier playersOnline) { + this(handle, parents, playersOnline, new PaperServer(), LOGGER::info, LOGGER::warn); + } + + PaperDimensions(AttributeHandle handle, MinecraftAttributeParents parents, BooleanSupplier playersOnline, Server server, + Consumer info, Consumer warn) { + this.handle = Objects.requireNonNull(handle, "handle"); + this.parents = Objects.requireNonNull(parents, "parents"); + this.playersOnline = Objects.requireNonNull(playersOnline, "playersOnline"); + this.server = Objects.requireNonNull(server, "server"); + this.info = Objects.requireNonNull(info, "info"); + this.warn = Objects.requireNonNull(warn, "warn"); + } + + public void registerPacks(Iterable packs) { + VanillaContext context = context(); + for(ConfigPack pack : packs) { + try { + registerPack(pack, context); + } catch(RuntimeException e) { + LOGGER.debug("Failed to read the attributes of pack {}", pack.getID(), e); + warn.accept("Pack \"" + pack.getID() + "\": timelines and dimension type skipped: its attributes could not be read"); + } + } + } + + private void registerPack(ConfigPack pack, VanillaContext context) { + Optional attributes = handle.pack(pack); + if(attributes.isEmpty()) return; + PackParents packParents = prepare(pack, attributes); + warnUnsupportedGeneration(attributes.get(), packParents.report()); + + if(!attributes.get().scheduleDefinitions().isEmpty()) { + try { + server.registerTimelines(registry -> MinecraftTimelines.register(pack, packParents, registry, handle, context)); + } catch(RuntimeException e) { + LOGGER.debug("Wyck failed to register the timelines of pack {}", pack.getID(), e); + packParents.report().ignored(PACK_CONFIG, "schedule-definitions", "wyck could not register the timelines"); + } + } + try { + recordTimelines(pack, server.timelines()); + } catch(RuntimeException e) { + LOGGER.debug("Failed to resolve the schedules of pack {}", pack.getID(), e); + packParents.report().ignored(PACK_CONFIG, "schedules", "the timelines could not be resolved; the parent's are kept"); + } + } + + private static void warnUnsupportedGeneration(PackAttributes attributes, AttributeReport report) { + for(AttributeKey key : UNSUPPORTED_GENERATION) { + if(attributes.entries().get(key).isPresent()) report.ignored(PACK_CONFIG, key.toString(), NOT_ON_THIS_PLATFORM); + } + if(attributes.parents().containsKey(VANILLA_GENERATION)) report.ignored(PACK_CONFIG, VANILLA_GENERATION, NOT_ON_THIS_PLATFORM); + } + + void recordTimelines(ConfigPack pack, Registry registry) { + PackParents packParents = prepare(pack, handle.pack(pack)); + MinecraftTimelines.Pending pending = MinecraftTimelines.pending(pack, packParents); + if(pending == null) { + resolvedTimelines.remove(pack.getID()); + return; + } + MinecraftTimelines.Pending named = new MinecraftTimelines.Pending(pending.report(), pending.refs(), HolderSet.empty()); + List> contents = MinecraftTimelines.contents(named, + tag -> registry.get(tag).map(set -> set.stream().toList()).orElse(null), registry); + if(contents.isEmpty()) { + resolvedTimelines.remove(pack.getID()); + return; + } + List> keys = contents.stream().flatMap(holder -> holder.unwrapKey().stream()).toList(); + resolvedTimelines.put(pack.getID(), new TimelineRef.Direct(keys)); + } + + public Optional typeFor(ConfigPack pack, ResourceKey worldTypeKey, DimensionType worldType, String worldName) { + Optional attributes = handle.pack(pack); + if(attributes.isEmpty()) return Optional.empty(); + VanillaContext context = context(); + PackParents packParents = parents.prepare(pack, attributes, AttributeReport.logging(pack), worldTypeKey); + MinecraftDimensionFactory factory = new MinecraftDimensionFactory(handle, context); + DimensionType type = factory.create(packParents, resolvedTimelines.get(pack.getID())); + + Map encoded = (Map) VanillaCodecs.encode(DimensionType.DIRECT_CODEC, type, context.ops()); + Map world = (Map) VanillaCodecs.encode(DimensionType.DIRECT_CODEC, worldType, context.ops()); + Map pinned = new LinkedHashMap<>(encoded); + for(String field : LEVEL_FIXED) pinned.put(field, world.get(field)); + reportPinned(packParents, world, worldName); + if(pinned.get(LOGICAL_HEIGHT) instanceof Number logical && world.get(HEIGHT) instanceof Number height + && logical.intValue() > height.intValue()) { + pinned.put(LOGICAL_HEIGHT, height); + reportLogicalHeight(packParents, attributes.get(), height, worldName); + } + + Identifier key = MinecraftDimensionFactory.typeId(pack, worldTypeKey, !pinned.equals(encoded)); + if(!pinned.equals(encoded)) { + try { + type = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, pinned, context.ops()); + } catch(DecodeException e) { + throw new IllegalStateException("the dimension type with the world's fields was rejected: " + e.getMessage(), e); + } + } + return Optional.of(new Built(key, type, factory.worldSettings(packParents, type))); + } + + private void reportPinned(PackParents packParents, Map world, String worldName) { + for(String field : LEVEL_FIXED) { + for(PackAttributeTable.Field bound : packParents.table().dimension()) { + if(!bound.name().equals(field)) continue; + Object value = resolveEncoded(bound.attribute(), packParents); + if(value != null && !sameValue(value, world.get(field))) { + packParents.report().notAppliedToWorld(bound.attribute().getRegistryKey().toString(), worldName); + } + } + } + } + + private void reportLogicalHeight(PackParents packParents, PackAttributes attributes, Number height, String worldName) { + for(PackAttributeTable.Field bound : packParents.table().dimension()) { + if(!bound.name().equals(LOGICAL_HEIGHT) || attributes.entries().get(bound.attribute().key()).isEmpty()) continue; + if(resolveEncoded(bound.attribute(), packParents) instanceof Number value && value.intValue() > height.intValue()) { + packParents.report().notAppliedToWorld(bound.attribute().getRegistryKey().toString(), worldName); + } + } + } + + private @Nullable Object resolveEncoded(Attribute attribute, PackParents packParents) { + T value = packParents.resolvePack(handle, attribute); + return value == null ? null : attribute.type().encode(value); + } + + private static boolean sameValue(Object value, @Nullable Object other) { + if(value instanceof Number number && other instanceof Number otherNumber) { + return number.doubleValue() == otherNumber.doubleValue(); + } + return value.equals(other); + } + + /** + * A new type isn't registered while players are online: their clients already hold the registries. + */ + public void onWorldInit(World world, BukkitChunkGeneratorWrapper wrapper) { + ConfigPack pack = wrapper.getPack(); + String keeps = "Pack \"" + pack.getID() + "\": world \"" + world.getName() + "\" keeps its dimension type"; + Built built; + try { + Holder current = server.dimensionType(world); + ResourceKey currentKey = current.unwrapKey() + .orElseThrow(() -> new IllegalStateException("the world's dimension type has no key")); + Optional typed = typeFor(pack, currentKey, current.value(), world.getName()); + if(typed.isEmpty()) return; + built = typed.get(); + } catch(RuntimeException e) { + LOGGER.debug("Failed to build the dimension type of pack {} for world {}", pack.getID(), world.getName(), e); + warn.accept(keeps + ": the pack's could not be built"); + return; + } + wrapper.setMobGeneration(built.settings().mobGeneration()); + + try { + boolean registered = server.isRegistered(built.key()); + boolean online = playersOnline.getAsBoolean(); + if(shouldRegister(registered, online)) { + server.registerDimension(built.key(), built.type()); + } else if(!registered) { + info.accept(keeps + " until the server restarts, since players are online"); + return; + } + } catch(RuntimeException e) { + LOGGER.debug("Failed to register dimension type {}", built.key(), e); + warn.accept(keeps + ": the pack's could not be registered"); + return; + } + try { + server.applyDimension(world, built.key()); + } catch(RuntimeException e) { + LOGGER.debug("Wyck failed to give world {} dimension type {}", world.getName(), built.key(), e); + warn.accept(keeps + ": wyck could not apply the pack's"); + } + } + + static boolean shouldRegister(boolean registered, boolean playersOnline) { + return !registered && !playersOnline; + } + + private VanillaContext context() { + VanillaContext context = parents.context(); + if(context == null) throw new IllegalStateException("no registry load has begun"); + return context; + } + + private PackParents prepare(ConfigPack pack, Optional attributes) { + return parents.prepare(pack, attributes, AttributeReport.logging(pack)); + } + + + public record Built(Identifier key, DimensionType type, WorldSettings settings) { } + + + interface Server { + void registerTimelines(Consumer> registration); + + Registry timelines(); + + Holder dimensionType(World world); + + boolean isRegistered(Identifier key); + + void registerDimension(Identifier key, DimensionType type); + + void applyDimension(World world, Identifier key); + } + + + private static final class PaperServer implements Server { + @Override + public void registerTimelines(Consumer> registration) { + WyckBridge.registerTimelines(registration); + } + + @Override + public Registry timelines() { + return PaperVanilla.server().registryAccess().lookupOrThrow(Registries.TIMELINE); + } + + @Override + public Holder dimensionType(World world) { + return PaperVanilla.level(world).dimensionTypeRegistration(); + } + + @Override + public boolean isRegistered(Identifier key) { + return PaperVanilla.server().registryAccess().lookupOrThrow(Registries.DIMENSION_TYPE).containsKey(key); + } + + @Override + public void registerDimension(Identifier key, DimensionType type) { + WyckBridge.registerDimension(key, type); + } + + @Override + public void applyDimension(World world, Identifier key) { + WyckBridge.applyDimension(world, key); + ServerLevel level = PaperVanilla.level(world); + level.setEnvironmentAttributes(EnvironmentAttributeSystem.builder().addDefaultLayers(level).build()); + level.updateSkyBrightness(); + } + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/PaperVanilla.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/PaperVanilla.java new file mode 100644 index 000000000..b81a0c42f --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/PaperVanilla.java @@ -0,0 +1,88 @@ +/* + * This file is part of Terra. + * + * Terra is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Terra is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Terra. If not, see . + */ +package com.dfsek.terra.bukkit.attribute; + +import net.minecraft.core.HolderLookup; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.npc.villager.VillagerType; +import net.minecraft.world.level.biome.Biome; +import org.bukkit.Bukkit; +import org.bukkit.World; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + +import com.dfsek.terra.minecraft.attribute.VanillaContext; + + +public final class PaperVanilla { + private static volatile Map, ResourceKey> villagerTypes; + + private PaperVanilla() { } + + public static MinecraftServer server() { + try { + Object server = Bukkit.getServer(); + if(server != null && server.getClass().getMethod("getServer").invoke(server) instanceof MinecraftServer minecraft) { + return minecraft; + } + } catch(ReflectiveOperationException | RuntimeException e) { + throw new IllegalStateException("not running on Paper", e); + } + throw new IllegalStateException("not running on Paper"); + } + + /** + * CraftBukkit isn't on the compile classpath. + */ + public static ServerLevel level(World world) { + try { + if(world.getClass().getMethod("getHandle").invoke(world) instanceof ServerLevel level) return level; + } catch(ReflectiveOperationException e) { + throw new IllegalStateException("not a Paper world", e); + } + throw new IllegalStateException("not a Paper world"); + } + + @SuppressWarnings("unchecked") + public static Map, ResourceKey> villagerTypes() { + Map, ResourceKey> cached = villagerTypes; + if(cached != null) return cached; + synchronized(PaperVanilla.class) { + if(villagerTypes == null) { + Object byBiome; + try { + Field field = VillagerType.class.getDeclaredField("BY_BIOME"); + field.setAccessible(true); + byBiome = field.get(null); + } catch(ReflectiveOperationException e) { + throw new IllegalStateException("villager types by biome are not readable", e); + } + if(!(byBiome instanceof HashMap map)) throw new IllegalStateException("villager types by biome is not a hash map"); + villagerTypes = (Map, ResourceKey>) map; + } + return villagerTypes; + } + } + + public static VanillaContext context(HolderLookup.Provider registries) { + return VanillaContext.of(registries, villagerTypes()::get); + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/WyckBridge.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/WyckBridge.java new file mode 100644 index 000000000..e5ffb3c37 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/WyckBridge.java @@ -0,0 +1,93 @@ +/* + * This file is part of Terra. + * + * Terra is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Terra is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Terra. If not, see . + */ +package com.dfsek.terra.bukkit.attribute; + +import com.mojang.serialization.Lifecycle; +import dev.wyck.keys.ResourceKey; +import dev.wyck.level.dimension.Dimension; +import dev.wyck.registry.BiomeRegistry; +import dev.wyck.registry.DimensionRegistry; +import dev.wyck.registry.internal.RegistryId; +import dev.wyck.registry.internal.WyckRegistry; +import dev.wyck.registry.level.LevelStemEditor; +import dev.wyck.tags.TagSet; +import net.minecraft.core.MappedRegistry; +import net.minecraft.core.RegistrationInfo; +import net.minecraft.core.WritableRegistry; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.tags.TagKey; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.timeline.Timeline; +import org.bukkit.World; + +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Consumer; + + +public final class WyckBridge { + private WyckBridge() { } + + /** + * Wyck's decoder refuses a biome without a registered key. + */ + public static dev.wyck.biome.Biome biome(Identifier key, Biome biome) { + MappedRegistry owner = new MappedRegistry<>(Registries.BIOME, Lifecycle.stable()); + var holder = owner.register(net.minecraft.resources.ResourceKey.create(Registries.BIOME, key), biome, RegistrationInfo.BUILT_IN); + owner.freeze(); + return dev.wyck.biome.Biome.decode(holder).toBuilder().resourceKey(key(key)).build(); + } + + private static Dimension dimension(Identifier key, DimensionType type) { + MappedRegistry owner = new MappedRegistry<>(Registries.DIMENSION_TYPE, Lifecycle.stable()); + var holder = owner.register(net.minecraft.resources.ResourceKey.create(Registries.DIMENSION_TYPE, key), type, + RegistrationInfo.BUILT_IN); + owner.freeze(); + return Dimension.decode(holder).toBuilder().resourceKey(key(key)).build(); + } + + @SuppressWarnings("unchecked") + public static void registerTimelines(Consumer> registration) { + WyckRegistry.of(RegistryId.TIMELINE).whileUnfrozen(r -> registration.accept((WritableRegistry) r.registry())); + } + + public static void registerDimension(Identifier key, DimensionType type) { + DimensionRegistry.registry().register(dimension(key, type)); + } + + public static void applyDimension(World world, Identifier key) { + LevelStemEditor.create().dimension(Dimension.reference(key(key))).apply(world); + } + + public static void registerBiomes(List biomes) { + BiomeRegistry.registry().register(biomes); + } + + public static void appendBiomeTag(TagKey tag, Collection biomes) { + Set members = new LinkedHashSet<>(); + for(Identifier biome : biomes) members.add(dev.wyck.biome.Biome.reference(key(biome))); + TagSet.ofBiomes(key(tag.location()), members).append(); + } + + private static ResourceKey key(Identifier id) { + return ResourceKey.of(id.getNamespace(), id.getPath()); + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeAdditionsSoundTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeAdditionsSoundTemplate.java deleted file mode 100644 index ae39c84ac..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeAdditionsSoundTemplate.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.dfsek.terra.bukkit.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 dev.wyck.environment.sounds.AmbientAdditionsSettings; -import dev.wyck.environment.sounds.SoundEvent; - - -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 AmbientAdditionsSettings.builder() - .soundEvent(sound) - .tickChance(soundChance) - .build(); - } - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeMoodSoundTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeMoodSoundTemplate.java deleted file mode 100644 index 37f621819..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeMoodSoundTemplate.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.dfsek.terra.bukkit.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 dev.wyck.environment.sounds.AmbientMoodSettings; -import dev.wyck.environment.sounds.SoundEvent; - - -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 AmbientMoodSettings.builder() - .soundEvent(sound) - .tickDelay(soundCultivationTicks) - .blockSearchExtent(soundSpawnRange) - .soundPositionOffset(soundExtraDistance) - .build(); - } - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeParticleConfigTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeParticleConfigTemplate.java deleted file mode 100644 index bf567032c..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeParticleConfigTemplate.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.dfsek.terra.bukkit.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.exceptions.CommandSyntaxException; -import dev.wyck.environment.particle.AmbientParticle; -import dev.wyck.environment.particle.ParticleCatalog; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; - -import com.dfsek.terra.bukkit.util.VanillaParticles; - - -public class BiomeParticleConfigTemplate implements ObjectTemplate { - private static final Logger LOGGER = LoggerFactory.getLogger(BiomeParticleConfigTemplate.class); - - @Value("particle") - @Default - private String particle = null; - - @Value("probability") - @Default - private Float probability = 0.1f; - - @Override - public ParticleCatalog get() { - if(particle == null) { - return null; - } - - try { - AmbientParticle parsed = VanillaParticles.parse(particle, probability); - return parsed == null ? null : new ParticleCatalog(List.of(parsed)); - } catch(CommandSyntaxException | RuntimeException e) { - LOGGER.warn("Skipping particle \"{}\": {}", particle, e.getMessage()); - return null; - } - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/EntityTypeTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/EntityTypeTemplate.java deleted file mode 100644 index 5472bad00..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/EntityTypeTemplate.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.dfsek.terra.bukkit.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 dev.wyck.keys.ResourceKey; -import io.papermc.paper.registry.RegistryAccess; -import io.papermc.paper.registry.RegistryKey; -import org.bukkit.entity.EntityType; - - -public class EntityTypeTemplate implements ObjectTemplate { - @Value("id") - @Default - private ResourceKey id = null; - - @Override - public EntityType get() { - return RegistryAccess.registryAccess().getRegistry(RegistryKey.ENTITY_TYPE) - .getOrThrow(id); - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/MusicSoundTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/MusicSoundTemplate.java deleted file mode 100644 index d5438675e..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/MusicSoundTemplate.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.dfsek.terra.bukkit.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 dev.wyck.environment.sounds.Music; -import dev.wyck.environment.sounds.SoundEvent; - - -public class MusicSoundTemplate implements ObjectTemplate { - @Value("sound") - @Default - private SoundEvent sound = null; - - @Value("min-delay") - @Default - private Integer minDelay = null; - - @Value("max-delay") - @Default - private Integer maxDelay = null; - - @Value("replace-current-music") - @Default - private Boolean replaceCurrentMusic = null; - - @Override - public Music get() { - if(sound == null || minDelay == null || maxDelay == null || replaceCurrentMusic == null) { - return null; - } else { - return Music.builder() - .sound(sound) - .minDelay(minDelay) - .maxDelay(maxDelay) - .replaceCurrentMusic(replaceCurrentMusic) - .build(); - } - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SoundEventTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SoundEventTemplate.java deleted file mode 100644 index 6af7bee60..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SoundEventTemplate.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.dfsek.terra.bukkit.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 dev.wyck.environment.sounds.SoundEvent; -import dev.wyck.keys.ResourceKey; - - -public class SoundEventTemplate implements ObjectTemplate { - @Value("id") - @Default - private ResourceKey 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.variableRange(id); - } else { - return SoundEvent.fixedRange(id, distanceToTravel); - } - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnCostConfig.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnCostConfig.java deleted file mode 100644 index eb5b522d5..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnCostConfig.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.dfsek.terra.bukkit.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 org.bukkit.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/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnEntryConfig.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnEntryConfig.java deleted file mode 100644 index 7369822ce..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnEntryConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.dfsek.terra.bukkit.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; - -import dev.wyck.worldgen.valueproviders.IntProvider; -import org.bukkit.entity.EntityType; - - -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 EntityType getType() { - return type; - } - - public IntProvider getCount() { - return IntProvider.uniform(groupSize.getMin(), groupSize.getMax()); - } - - @Override - public SpawnEntryConfig get() { - return this; - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnSettingsTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnSettingsTemplate.java deleted file mode 100644 index 686524c28..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnSettingsTemplate.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.dfsek.terra.bukkit.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 dev.wyck.biome.entity.MobCategory; -import dev.wyck.biome.entity.MobSpawnSettings; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - - -public class SpawnSettingsTemplate implements ObjectTemplate { - - private static final Logger LOGGER = LoggerFactory.getLogger(SpawnSettingsTemplate.class); - private static final AtomicBoolean PROBABILITY_WARNING_LOGGED = new AtomicBoolean(false); - - @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 = MobSpawnSettings.builder(); - if(spawns != null) { - for(SpawnTypeConfig spawn : spawns) { - MobCategory group = spawn.getGroup(); - for(SpawnEntryConfig entry : spawn.getEntries()) { - builder.addSpawn(entry.getType(), group, entry.getWeight(), entry.getCount()); - } - } - } - if(costs != null) { - for(SpawnCostConfig cost : costs) { - builder.addMobSpawnCost(cost.getType(), cost.getMass(), cost.getGravity()); - } - } - if(probability != null && PROBABILITY_WARNING_LOGGED.compareAndSet(false, true)) { - LOGGER.warn("Biome spawning.probability is ignored on this server version."); - } - - return builder.build(); - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnTypeConfig.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnTypeConfig.java deleted file mode 100644 index 577857bc9..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnTypeConfig.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.dfsek.terra.bukkit.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 dev.wyck.biome.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; - } -} \ No newline at end of file diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VanillaBiomeProperties.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VanillaBiomeProperties.java deleted file mode 100644 index c6c30bb0d..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VanillaBiomeProperties.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.dfsek.terra.bukkit.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 com.dfsek.terra.api.properties.Properties; - -import dev.wyck.biome.TemperatureModifier; -import dev.wyck.biome.entity.MobSpawnSettings; -import dev.wyck.environment.GrassColorModifier; -import dev.wyck.environment.particle.AmbientParticle; -import dev.wyck.environment.particle.ParticleCatalog; -import dev.wyck.environment.sounds.AmbientAdditionsSettings; -import dev.wyck.environment.sounds.AmbientMoodSettings; -import dev.wyck.environment.sounds.Music; -import dev.wyck.environment.sounds.SoundEvent; -import org.bukkit.entity.Villager; - - -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 ParticleCatalog particleConfig = null; - - @Value("climate.precipitation") - @Default - private Boolean precipitation = true; - - @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 Villager.Type villagerType = null; - - public Integer getFogColor() { - return fogColor; - } - - public Integer getFoliageColor() { - return foliageColor; - } - - public Integer getDryFoliageColor() { - return dryFoliageColor; - } - - public Integer getGrassColor() { - return grassColor; - } - - public Integer getWaterColor() { - return waterColor; - } - - public Integer getWaterFogColor() { - return waterFogColor; - } - - public Integer getSkyColor() { - return skyColor; - } - - public GrassColorModifier getGrassColorModifier() { - return grassColorModifier; - } - - public ParticleCatalog getParticles() { - 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 Villager.Type getVillagerType() { - return villagerType; - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VillagerTypeTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VillagerTypeTemplate.java deleted file mode 100644 index ff3974d3e..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VillagerTypeTemplate.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.dfsek.terra.bukkit.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 dev.wyck.keys.ResourceKey; -import io.papermc.paper.registry.RegistryAccess; -import io.papermc.paper.registry.RegistryKey; -import org.bukkit.entity.Villager; - - -public class VillagerTypeTemplate implements ObjectTemplate { - @Value("id") - @Default - private ResourceKey id = null; - - @Override - public Villager.Type get() { - return RegistryAccess.registryAccess().getRegistry(RegistryKey.VILLAGER_TYPE) - .getOrThrow(id); - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBiomeProvider.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBiomeProvider.java index 04c8f3be9..1ffe29967 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBiomeProvider.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBiomeProvider.java @@ -15,10 +15,14 @@ import com.dfsek.terra.bukkit.world.BukkitPlatformBiome; public class BukkitBiomeProvider extends BiomeProvider implements Handle { - private final com.dfsek.terra.api.world.biome.generation.BiomeProvider delegate; + private volatile com.dfsek.terra.api.world.biome.generation.BiomeProvider delegate; public BukkitBiomeProvider(com.dfsek.terra.api.world.biome.generation.BiomeProvider delegate) { this.delegate = delegate; } + public void setDelegate(com.dfsek.terra.api.world.biome.generation.BiomeProvider delegate) { + this.delegate = delegate; + } + @Override public @NotNull org.bukkit.block.Biome getBiome(@NotNull WorldInfo worldInfo, int x, int y, int z) { return toBukkit(delegate.getBiome(x, y, z, worldInfo.getSeed())); diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBlockPopulator.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBlockPopulator.java index 27f52de47..b008b788a 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBlockPopulator.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBlockPopulator.java @@ -14,7 +14,7 @@ import com.dfsek.terra.bukkit.world.BukkitProtoWorld; public class BukkitBlockPopulator extends BlockPopulator { private final BlockState air; - private ConfigPack pack; + private volatile ConfigPack pack; public BukkitBlockPopulator(ConfigPack pack, BlockState air) { this.pack = pack; diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitChunkGeneratorWrapper.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitChunkGeneratorWrapper.java index 7f60527aa..708bac0d5 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitChunkGeneratorWrapper.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitChunkGeneratorWrapper.java @@ -47,8 +47,10 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener private static final Logger LOGGER = LoggerFactory.getLogger(BukkitChunkGeneratorWrapper.class); private final BlockState air; private final BukkitBlockPopulator blockPopulator; - private ChunkGenerator delegate; - private ConfigPack pack; + private volatile @Nullable BukkitBiomeProvider biomeProvider; + private volatile ChunkGenerator delegate; + private volatile ConfigPack pack; + private volatile boolean mobGeneration = true; public BukkitChunkGeneratorWrapper(ChunkGenerator delegate, ConfigPack pack, BlockState air) { @@ -64,7 +66,9 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener @Override public @Nullable BiomeProvider getDefaultBiomeProvider(@NotNull WorldInfo worldInfo) { - return new BukkitBiomeProvider(pack.getBiomeProvider()); + BukkitBiomeProvider provider = new BukkitBiomeProvider(pack.getBiomeProvider()); + biomeProvider = provider; + return provider; } @Override @@ -117,7 +121,11 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener @Override public boolean shouldGenerateMobs() { - return true; + return mobGeneration; + } + + public void setMobGeneration(boolean mobGeneration) { + this.mobGeneration = mobGeneration; } @Override @@ -132,6 +140,9 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener public void setPack(ConfigPack pack) { this.pack = pack; setDelegate(pack.getGeneratorProvider().newInstance(pack)); + BukkitBiomeProvider provider = biomeProvider; + if(provider != null) provider.setDelegate(pack.getBiomeProvider()); + blockPopulator.setPack(pack); } @Override diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/BiomeListener.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/BiomeListener.java deleted file mode 100644 index 7e7321f7b..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/BiomeListener.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.dfsek.terra.bukkit.listeners; - -import io.papermc.paper.event.server.ServerResourcesReloadedEvent; -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Villager; -import org.bukkit.entity.ZombieVillager; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; -import org.bukkit.event.entity.EntityBreedEvent; - -import java.util.Set; - -import com.dfsek.terra.bukkit.BukkitPlatform; -import com.dfsek.terra.bukkit.world.BiomeHandler; - - -public class BiomeListener implements Listener { - private static final Set BIOME_TYPED_VILLAGER_REASONS = Set.of( - SpawnReason.SPAWNER_EGG, SpawnReason.DISPENSE_EGG, SpawnReason.SPAWNER, SpawnReason.COMMAND); - - private final BukkitPlatform platform; - - public BiomeListener(BukkitPlatform platform) { - this.platform = platform; - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onResourcesReloaded(ServerResourcesReloadedEvent event) { - BiomeHandler.addToVanillaTags(platform.getRawConfigRegistry()); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onCreatureSpawn(CreatureSpawnEvent event) { - SpawnReason reason = event.getSpawnReason(); - if(event.getEntity() instanceof Villager villager && BIOME_TYPED_VILLAGER_REASONS.contains(reason)) { - applyBiomeType(villager); - } else if(event.getEntity() instanceof ZombieVillager zombieVillager && reason != SpawnReason.INFECTION) { - Villager.Type type = biomeType(zombieVillager); - if(type != null && zombieVillager.getVillagerType() == Villager.Type.PLAINS) { - zombieVillager.setVillagerType(type); - } - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBreed(EntityBreedEvent event) { - if(event.getEntity() instanceof Villager child && isNotPlains(event.getMother()) && isNotPlains(event.getFather())) { - applyBiomeType(child); - } - } - - private static void applyBiomeType(Villager villager) { - Villager.Type type = biomeType(villager); - if(type != null && villager.getVillagerType() == Villager.Type.PLAINS) { - villager.setVillagerType(type); - } - } - - private static Villager.Type biomeType(Entity entity) { - Location location = entity.getLocation(); - if(!entity.getWorld().isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) return null; - return BiomeHandler.getVillagerType(entity.getWorld().getBiome(location)); - } - - private static boolean isNotPlains(LivingEntity parent) { - return parent instanceof Villager villager && villager.getVillagerType() != Villager.Type.PLAINS; - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/CommonListener.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/CommonListener.java index 9a06dd3c9..4071bb71a 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/CommonListener.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/CommonListener.java @@ -36,6 +36,7 @@ import java.util.List; import com.dfsek.terra.api.Platform; import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.properties.Context; import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper; import com.dfsek.terra.bukkit.hooks.MultiverseGeneratorPluginHook; import com.dfsek.terra.bukkit.world.BukkitBiomeInfo; @@ -89,10 +90,8 @@ public class CommonListener implements Listener { ResourceKey biomeKey = ResourceKey.of(wolf.getWorld().getBiome(wolf.getLocation()).getKey()); pack.getBiomeProvider().stream() .filter(biome -> { - ResourceKey key = ((BukkitPlatformBiome) biome.getPlatformBiome()).getContext() - .get(BukkitBiomeInfo.class) - .biomeKey(); - return key.equals(biomeKey); + Context context = ((BukkitPlatformBiome) biome.getPlatformBiome()).getContext(); + return context.has(BukkitBiomeInfo.class) && context.get(BukkitBiomeInfo.class).biomeKey().equals(biomeKey); }) .findFirst() .ifPresent(biome -> { diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/DimensionListener.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/DimensionListener.java new file mode 100644 index 000000000..352a911e1 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/DimensionListener.java @@ -0,0 +1,41 @@ +/* + * This file is part of Terra. + * + * Terra is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Terra is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Terra. If not, see . + */ +package com.dfsek.terra.bukkit.listeners; + +import org.bukkit.World; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.world.WorldInitEvent; + +import com.dfsek.terra.bukkit.attribute.PaperDimensions; +import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper; + + +public class DimensionListener implements Listener { + private final PaperDimensions dimensions; + + public DimensionListener(PaperDimensions dimensions) { + this.dimensions = dimensions; + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onWorldInit(WorldInitEvent event) { + World world = event.getWorld(); + if(world.getGenerator() instanceof BukkitChunkGeneratorWrapper wrapper) dimensions.onWorldInit(world, wrapper); + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/ServerThread.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/ServerThread.java new file mode 100644 index 000000000..ee2c9f0a6 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/ServerThread.java @@ -0,0 +1,67 @@ +package com.dfsek.terra.bukkit.util; + +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BooleanSupplier; + + +public final class ServerThread { + private static final int PENDING = 0; + private static final int RUNNING = 1; + private static final int ABANDONED = 2; + + private ServerThread() { } + + /** + * The caller must not hold a lock the server thread could wait on. + */ + public static void run(Runnable task, Executor serverThread, BooleanSupplier onServerThread, BooleanSupplier stopping, + long pollMillis) { + if(onServerThread.getAsBoolean()) { + task.run(); + return; + } + AtomicInteger state = new AtomicInteger(PENDING); + CompletableFuture done = new CompletableFuture<>(); + serverThread.execute(() -> { + if(!state.compareAndSet(PENDING, RUNNING)) return; + try { + task.run(); + done.complete(null); + } catch(Throwable t) { + done.completeExceptionally(t); + } + }); + + boolean interrupted = false; + try { + while(true) { + try { + done.get(pollMillis, TimeUnit.MILLISECONDS); + return; + } catch(TimeoutException e) { + if(stopping.getAsBoolean() && state.compareAndSet(PENDING, ABANDONED)) { + throw new CancellationException("the server stopped before the task ran"); + } + } catch(InterruptedException e) { + interrupted = true; + if(state.compareAndSet(PENDING, ABANDONED)) throw new CancellationException("interrupted before the task ran"); + } catch(ExecutionException e) { + switch(e.getCause()) { + case RuntimeException runtime -> throw runtime; + case Error error -> throw error; + default -> throw new CompletionException(e.getCause()); + } + } + } + } finally { + if(interrupted) Thread.currentThread().interrupt(); + } + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VanillaParticles.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VanillaParticles.java deleted file mode 100644 index 5f22c6868..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VanillaParticles.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.dfsek.terra.bukkit.util; - -import com.mojang.brigadier.LiteralMessage; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; -import dev.wyck.environment.particle.AmbientParticle; -import org.bukkit.Bukkit; -import org.jetbrains.annotations.Nullable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; - - -public final class VanillaParticles { - private static final Logger LOGGER = LoggerFactory.getLogger(VanillaParticles.class); - private static final SimpleCommandExceptionType TRAILING_DATA = new SimpleCommandExceptionType( - new LiteralMessage("Unexpected text after the particle")); - - private VanillaParticles() { - } - - public static @Nullable AmbientParticle parse(String particle, float probability) throws CommandSyntaxException { - Handles handles = Holder.HANDLES; - if(handles == null) return null; - - StringReader reader = new StringReader(particle.strip()); - Object options; - Object ambient; - try { - options = handles.readParticle.invokeExact(reader, handles.registries); - ambient = handles.ambientParticle.invokeExact(options, probability); - } catch(CommandSyntaxException | RuntimeException | Error e) { - throw e; - } catch(Throwable e) { - throw new IllegalStateException(e); - } - if(reader.canRead()) throw TRAILING_DATA.createWithContext(reader); - return AmbientParticle.decode(ambient); - } - - private static @Nullable Handles resolve() { - String step = "net.minecraft.server.MinecraftServer"; - try { - ClassLoader loader = Bukkit.getServer().getClass().getClassLoader(); - MethodHandles.Lookup lookup = MethodHandles.publicLookup(); - - Class server = Class.forName(step, false, loader); - step = "MinecraftServer.getServer()"; - Object instance = lookup.findStatic(server, "getServer", MethodType.methodType(server)).invoke(); - if(instance == null) throw new IllegalStateException("the server has not started"); - step = "MinecraftServer.registryAccess()"; - Object registries = lookup.findVirtual(server, "registryAccess", - MethodType.methodType(Class.forName("net.minecraft.core.RegistryAccess$Frozen", false, loader))).invoke(instance); - - step = "ParticleArgument.readParticle(StringReader, HolderLookup.Provider)"; - Class provider = Class.forName("net.minecraft.core.HolderLookup$Provider", false, loader); - Class options = Class.forName("net.minecraft.core.particles.ParticleOptions", false, loader); - MethodHandle readParticle = lookup.findStatic(Class.forName("net.minecraft.commands.arguments.ParticleArgument", false, loader), - "readParticle", MethodType.methodType(options, StringReader.class, provider)) - .asType(MethodType.methodType(Object.class, StringReader.class, Object.class)); - - step = "AmbientParticle(ParticleOptions, float)"; - MethodHandle ambientParticle = lookup.findConstructor(Class.forName("net.minecraft.world.attribute.AmbientParticle", false, loader), - MethodType.methodType(void.class, options, float.class)) - .asType(MethodType.methodType(Object.class, Object.class, float.class)); - - return new Handles(readParticle, registries, ambientParticle); - } catch(Throwable e) { - LOGGER.warn("Biome particles are disabled: could not find vanilla's {} ({}). " + - "This Minecraft version is probably not supported yet.", step, e.toString()); - return null; - } - } - - private record Handles(MethodHandle readParticle, Object registries, MethodHandle ambientParticle) { - } - - - private static final class Holder { - private static final @Nullable Handles HANDLES = resolve(); - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java index e89517d1f..baf27b448 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java @@ -1,22 +1,21 @@ package com.dfsek.terra.bukkit.world; -import dev.wyck.biome.Biome; -import dev.wyck.biome.BiomeSpecialEffects; -import dev.wyck.biome.ClimateSettings; -import dev.wyck.environment.attribute.EnvironmentAttributeMap; -import dev.wyck.environment.attribute.EnvironmentAttributeSupplier; -import dev.wyck.environment.attribute.EnvironmentAttributes; -import dev.wyck.environment.sounds.AmbientSounds; -import dev.wyck.environment.sounds.BackgroundMusic; -import dev.wyck.keys.ResourceKey; -import dev.wyck.registry.BiomeRegistry; -import dev.wyck.tags.TagSet; import io.papermc.paper.registry.RegistryAccess; import io.papermc.paper.registry.RegistryKey; import io.papermc.paper.registry.TypedKey; -import io.papermc.paper.registry.tag.Tag; +import io.papermc.paper.tag.PostFlattenTagRegistrar; +import net.kyori.adventure.key.Key; +import net.minecraft.core.Holder; +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.world.entity.npc.villager.VillagerType; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeGenerationSettings; +import org.bukkit.Bukkit; import org.bukkit.NamespacedKey; -import org.bukkit.entity.Villager; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -24,133 +23,340 @@ import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiConsumer; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; import com.dfsek.terra.api.config.ConfigPack; -import com.dfsek.terra.api.properties.Context; -import com.dfsek.terra.bukkit.config.VanillaBiomeProperties; -import com.dfsek.terra.registry.master.ConfigRegistry; +import com.dfsek.terra.bukkit.BukkitPlatform; +import com.dfsek.terra.bukkit.attribute.PaperVanilla; +import com.dfsek.terra.bukkit.attribute.WyckBridge; +import com.dfsek.terra.minecraft.attribute.BiomeTags; +import com.dfsek.terra.minecraft.attribute.BiomeTags.PlatformTagSource; +import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents; +import com.dfsek.terra.minecraft.attribute.MinecraftBiomeFactory; +import com.dfsek.terra.minecraft.attribute.PackParents; +import com.dfsek.terra.minecraft.attribute.VanillaContext; +import com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; public final class BiomeHandler { private static final Logger LOGGER = LoggerFactory.getLogger(BiomeHandler.class); - private static final Map VILLAGER_TYPES = new ConcurrentHashMap<>(); + private static final Map> BY_PARENT = new HashMap<>(); + private static final Map PLATFORM_TAGS = new HashMap<>(); private BiomeHandler() { } - public static void registerBiomes(ConfigRegistry configRegistry) { + /** + * Must run on the server thread. + */ + public static synchronized void registerBiomes(BukkitPlatform platform) { + MinecraftAttributeParents parents = platform.attributeParents(); + VanillaContext context = parents.context(); + if(context == null) throw new IllegalStateException("no registry load has begun"); + MinecraftBiomeFactory factory = new MinecraftBiomeFactory(platform.getAttributeHandle(), context); + Registry registry = PaperVanilla.server().registryAccess().lookupOrThrow(Registries.BIOME); org.bukkit.Registry bukkitRegistry = RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME); - List toRegister = new ArrayList<>(); - List afterRegistration = new ArrayList<>(); + boolean playersOnline = !Bukkit.getOnlinePlayers().isEmpty(); + AtomicInteger deferred = new AtomicInteger(); - configRegistry.forEach(pack -> pack.getRegistry(com.dfsek.terra.api.world.biome.Biome.class).forEach((key, biome) -> { - BukkitPlatformBiome platformBiome = (BukkitPlatformBiome) biome.getPlatformBiome(); - ResourceKey vanillaKey = ResourceKey.of(platformBiome.getHandle().getKey()); - ResourceKey terraKey = ResourceKey.of("terra", createBiomeID(pack, key)); - - NamespacedKey bukkitKey = new NamespacedKey(terraKey.namespace(), terraKey.path()); - VanillaBiomeProperties properties = biome.getContext().has(VanillaBiomeProperties.class) - ? biome.getContext().get(VanillaBiomeProperties.class) - : new VanillaBiomeProperties(); - - if(bukkitRegistry.get(bukkitKey) == null) { - toRegister.add(createBiome(terraKey, getBiomeOrThrow(vanillaKey), properties)); - } - - afterRegistration.add(() -> { - org.bukkit.block.Biome bukkitBiome = bukkitRegistry.getOrThrow(bukkitKey); - platformBiome.getContext().put(new BukkitBiomeInfo(terraKey, vanillaKey, bukkitBiome)); - if(properties.getVillagerType() != null) { - VILLAGER_TYPES.put(bukkitKey, properties.getVillagerType()); + Run run = collect(platform.getRawConfigRegistry().entries(), + pack -> parents.prepare(pack, platform.getAttributeHandle().pack(pack), AttributeReport.logging(pack)), + (pack, packParents, packRun) -> pack.getRegistry(com.dfsek.terra.api.world.biome.Biome.class).forEach((id, biome) -> { + BukkitPlatformBiome platformBiome = (BukkitPlatformBiome) biome.getPlatformBiome(); + ResourceKey parentKey = ResourceKey.create(Registries.BIOME, + Identifier.parse(platformBiome.getHandle().getKey().toString())); + Biome parent = registry.getValue(parentKey); + if(parent == null) { + LOGGER.error("Pack \"{}\", config \"{}\": biome skipped: no vanilla biome \"{}\"", pack.getID(), biome.getID(), + parentKey.identifier()); + return; } - }); - })); + platformBiome.setParentEntries(parentEntries(() -> parents.biomeEntries(packParents, parentKey, parent), pack.getID(), + biome.getID(), LOGGER::warn)); - LOGGER.info("Registering {} custom biomes through Wyck...", toRegister.size()); - BiomeRegistry.registry().register(toRegister); - afterRegistration.forEach(Runnable::run); + Identifier terraId = Identifier.fromNamespaceAndPath("terra", createBiomeID(pack, id)); + packRun.add(terraId, parentKey.identifier(), registry.containsKey(terraId), () -> { + if(playersOnline) { + deferred.incrementAndGet(); + return null; + } + ResourceKey parentVillagerType = Objects.requireNonNullElse(context.villagerTypes().apply(parentKey), + VillagerType.PLAINS); + return registration(() -> build(factory, parentKey, parent, biome, packParents), b -> WyckBridge.biome(terraId, b), + parent, parentVillagerType, pack.getID(), biome.getID(), LOGGER::warn); + }, new PlatformTagSource(packParents.report(), biome.getID(), biome.getPlatformTags()), () -> { + NamespacedKey bukkitKey = new NamespacedKey(terraId.getNamespace(), terraId.getPath()); + org.bukkit.block.Biome bukkitBiome = bukkitRegistry.get(bukkitKey); + if(bukkitBiome == null) { + LOGGER.error("Pack \"{}\", config \"{}\": biome not registered as \"{}\"", pack.getID(), biome.getID(), + terraId); + return; + } + platformBiome.getContext().put(new BukkitBiomeInfo(dev.wyck.keys.ResourceKey.of(bukkitKey), bukkitBiome)); + }, pack.getID(), biome.getID(), LOGGER::warn); + }), LOGGER::warn); + + if(deferred.get() > 0) { + LOGGER.info("Players are online, so {} new custom biomes generate as their vanilla biomes until the server restarts.", + deferred.get()); + } + registerNew(run.toRegister, WyckBridge::registerBiomes, LOGGER::info); + Map, ResourceKey> villagerTypes = PaperVanilla.villagerTypes(); + run.villagerTypes.forEach((terraId, type) -> villagerTypes.put(ResourceKey.create(Registries.BIOME, terraId), type)); + BY_PARENT.clear(); + BY_PARENT.putAll(run.byParent); + PLATFORM_TAGS.clear(); + PLATFORM_TAGS.putAll(run.platformTags); + run.afterRegistration.forEach(Runnable::run); } - public static void addToVanillaTags(ConfigRegistry configRegistry) { - Map, Set> terraBiomesByVanilla = new HashMap<>(); - configRegistry.forEach(pack -> pack.getRegistry(com.dfsek.terra.api.world.biome.Biome.class).forEach(biome -> { - Context context = ((BukkitPlatformBiome) biome.getPlatformBiome()).getContext(); - if(context.has(BukkitBiomeInfo.class)) { - BukkitBiomeInfo info = context.get(BukkitBiomeInfo.class); - TypedKey vanillaKey = TypedKey.create(RegistryKey.BIOME, info.vanillaKey().key()); - terraBiomesByVanilla.computeIfAbsent(vanillaKey, k -> new HashSet<>()).add(Biome.reference(info.biomeKey())); + static Run collect(Iterable packs, Function prepare, PackCollector collectPack, + Consumer warn) { + Run run = new Run<>(null); + for(ConfigPack pack : packs) { + P prepared; + try { + prepared = prepare.apply(pack); + } catch(RuntimeException e) { + LOGGER.debug("Failed to read the attributes of pack {}", pack.getID(), e); + warn.accept("Pack \"" + pack.getID() + "\": biomes skipped: its attributes could not be read"); + continue; } - })); + Run packRun = new Run<>(run); + try { + collectPack.collect(pack, prepared, packRun); + } catch(RuntimeException e) { + LOGGER.debug("Failed to collect the biomes of pack {}", pack.getID(), e); + warn.accept("Pack \"" + pack.getID() + "\": biomes skipped: they could not be built"); + continue; + } + run.addAll(packRun); + } + return run; + } - org.bukkit.Registry bukkitRegistry = RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME); - int count = 0; - for(Tag tag : bukkitRegistry.getTags()) { - Set members = new HashSet<>(); - terraBiomesByVanilla.forEach((vanillaKey, terraBiomes) -> { - if(tag.contains(vanillaKey)) { - members.addAll(terraBiomes); + @FunctionalInterface + interface PackCollector { + void collect(ConfigPack pack, P prepared, Run run); + } + + static AttributeSlots parentEntries(Supplier read, String pack, String config, Consumer warn) { + try { + return read.get(); + } catch(RuntimeException e) { + LOGGER.debug("Failed to read the parent attributes of Terra biome {} of pack {}", config, pack, e); + warn.accept("Pack \"" + pack + "\", config \"" + config + "\": parent attributes ignored: they could not be read"); + return AttributeSlots.EMPTY; + } + } + + static final class Run { + private final @Nullable Run before; + final List toRegister = new ArrayList<>(); + final Map> villagerTypes = new LinkedHashMap<>(); + final Map> byParent = new LinkedHashMap<>(); + final Map platformTags = new LinkedHashMap<>(); + final List afterRegistration = new ArrayList<>(); + + Run(@Nullable Run before) { + this.before = before; + } + + void add(Identifier terraId, Identifier parent, boolean registered, Supplier<@Nullable Registration> registration, + PlatformTagSource tags, Runnable after, String pack, String config, Consumer warn) { + if(recorded(terraId)) { + warn.accept("Pack \"" + pack + "\", config \"" + config + "\": biome \"" + terraId + + "\" shared with another config: their IDs differ only in case"); + afterRegistration.add(after); + return; + } + if(!registered) { + Registration queued = registration.get(); + if(queued == null) return; + toRegister.add(queued.biome()); + villagerTypes.put(terraId, queued.villagerType()); + } + byParent.computeIfAbsent(parent, i -> new ArrayList<>()).add(terraId); + platformTags.put(terraId, tags); + afterRegistration.add(after); + } + + private boolean recorded(Identifier terraId) { + return platformTags.containsKey(terraId) || (before != null && before.recorded(terraId)); + } + + private void addAll(Run run) { + toRegister.addAll(run.toRegister); + villagerTypes.putAll(run.villagerTypes); + run.byParent.forEach((parent, biomes) -> byParent.computeIfAbsent(parent, i -> new ArrayList<>()).addAll(biomes)); + platformTags.putAll(run.platformTags); + afterRegistration.addAll(run.afterRegistration); + } + } + + static void registerNew(List biomes, Consumer> register, Consumer info) { + if(biomes.isEmpty()) { + info.accept("No new custom biomes to register."); + return; + } + info.accept("Registering " + biomes.size() + " custom biomes through Wyck..."); + register.accept(biomes); + } + + public static MinecraftBiomeFactory.Built build(MinecraftBiomeFactory factory, ResourceKey parentKey, Biome parent, + com.dfsek.terra.api.world.biome.Biome terraBiome, PackParents pack) { + return factory.create(parentKey, parent, terraBiome, pack, pack.report(), BiomeGenerationSettings.EMPTY); + } + + /** + * Must run on the server thread. + */ + public static synchronized void addToVanillaTags(BukkitPlatform platform) { + Registry registry = PaperVanilla.server().registryAccess().lookupOrThrow(Registries.BIOME); + Map, List>> before = new LinkedHashMap<>(); + registry.getTags().forEach(tag -> before.put(tag.key(), new ArrayList<>(tag.stream().toList()))); + Map, List>> after = new LinkedHashMap<>(); + before.forEach((tag, members) -> after.put(tag, new ArrayList<>(members))); + + BiomeTags.addTerraBiomes(after, id -> registry.get(id).map(h -> h), BY_PARENT, PLATFORM_TAGS); + + Map, List> additions = additions(before, after); + int added = appendAll(additions, WyckBridge::appendBiomeTag, "wyck could not append to the tag", LOGGER::warn); + LOGGER.info("Added Terra biomes to {} biome tags.", added); + } + + /** + * Must not throw: an exception fails the data pack reload. + */ + public static synchronized void addToReloadedTags(PostFlattenTagRegistrar registrar) { + try { + Registry registry = PaperVanilla.server().registryAccess().lookupOrThrow(Registries.BIOME); + Map, List> tags = new LinkedHashMap<>(); + registrar.getAllTags().forEach((tag, members) -> tags.put(TagKey.create(Registries.BIOME, identifier(tag.key())), + members.stream().map(member -> identifier(member.key())).toList())); + + Map, List> additions = reloadAdditions(tags, id -> registry.get(id).map(h -> h), BY_PARENT, + PLATFORM_TAGS); + int added = appendAll(additions, (tag, biomes) -> registrar.addToTag( + io.papermc.paper.registry.tag.TagKey.create(RegistryKey.BIOME, key(tag.location())), + biomes.stream().map(biome -> TypedKey.create(RegistryKey.BIOME, key(biome))).toList()), + "the reload could not add them", LOGGER::warn); + LOGGER.info("Added Terra biomes to {} reloaded biome tags.", added); + } catch(RuntimeException e) { + LOGGER.debug("Failed to add Terra biomes to the reloaded biome tags", e); + LOGGER.warn("Terra biomes not added to the reloaded biome tags; restart the server to restore them"); + } + } + + /** + * Parent tags come from {@code tags}: the parent's holder still has its pre-reload tags. + */ + static Map, List> reloadAdditions(Map, List> tags, + Function>> lookup, + Map> byParent, + Map platformTags) { + Map, List>> before = new LinkedHashMap<>(); + Map, List>> after = new LinkedHashMap<>(); + tags.forEach((tag, members) -> { + List> old = members.stream().map(lookup).flatMap(Optional::stream).toList(); + List> biomes = new ArrayList<>(old); + for(Identifier member : members) { + for(Identifier terra : byParent.getOrDefault(member, List.of())) { + lookup.apply(terra).ifPresentOrElse(biomes::add, + () -> LOGGER.debug("Terra biome {} is not registered, so it is not added to the reloaded tag {}", terra, + tag.location())); } - }); - if(!members.isEmpty()) { - TagSet.ofBiomes(ResourceKey.of(tag.tagKey().key()), members).append(); - count++; + } + before.put(tag, old); + after.put(tag, biomes); + }); + BiomeTags.addTerraBiomes(after, lookup, Map.of(), platformTags); + return additions(before, after); + } + + private static Identifier identifier(Key key) { + return Identifier.fromNamespaceAndPath(key.namespace(), key.value()); + } + + private static Key key(Identifier id) { + return Key.key(id.getNamespace(), id.getPath()); + } + + public static Map, List> additions(Map, List>> before, + Map, List>> after) { + Map, List> additions = new LinkedHashMap<>(); + after.forEach((tag, members) -> { + Set> old = new HashSet<>(before.getOrDefault(tag, List.of())); + Set added = new LinkedHashSet<>(); + for(Holder member : members) { + if(!old.contains(member)) member.unwrapKey().ifPresent(key -> added.add(key.identifier())); + } + if(!added.isEmpty()) additions.put(tag, List.copyOf(added)); + }); + return additions; + } + + record Registration(B biome, ResourceKey villagerType) { } + + static @Nullable Registration registration(Supplier build, Function wyck, + Biome parent, ResourceKey parentVillagerType, String pack, + String config, Consumer warn) { + String prefix = "Pack \"" + pack + "\", config \"" + config + "\": "; + MinecraftBiomeFactory.Built built; + try { + built = build.get(); + } catch(RuntimeException e) { + LOGGER.debug("Failed to build Terra biome {} of pack {}", config, pack, e); + return parent(wyck, parent, parentVillagerType, prefix, "its attributes could not be applied", + "its attributes could not be applied, and wyck could not read its parent", warn); + } + try { + return new Registration<>(wyck.apply(built.biome()), built.villagerType()); + } catch(RuntimeException e) { + LOGGER.debug("Wyck failed to read Terra biome {} of pack {}", config, pack, e); + return parent(wyck, parent, parentVillagerType, prefix, "wyck could not read its attributes", + "wyck could not read its attributes or its parent", warn); + } + } + + private static @Nullable Registration parent(Function wyck, Biome parent, ResourceKey villagerType, + String prefix, String reason, String skipReason, Consumer warn) { + try { + Registration registration = new Registration<>(wyck.apply(parent), villagerType); + warn.accept(prefix + "biome built from its parent: " + reason); + return registration; + } catch(RuntimeException e) { + LOGGER.debug("Wyck failed to read the parent of a Terra biome", e); + warn.accept(prefix + "biome skipped: " + skipReason); + return null; + } + } + + static int appendAll(Map, List> additions, BiConsumer, List> append, + String failure, Consumer warn) { + int appended = 0; + for(Map.Entry, List> entry : additions.entrySet()) { + try { + append.accept(entry.getKey(), entry.getValue()); + appended++; + } catch(RuntimeException e) { + LOGGER.debug("Failed to append Terra biomes to biome tag {}", entry.getKey().location(), e); + warn.accept("Biome tag \"" + entry.getKey().location() + "\": terra biomes not added: " + failure); } } - LOGGER.info("Added Terra biomes to {} vanilla biome tags.", count); - } - - public static @Nullable Villager.Type getVillagerType(org.bukkit.block.Biome biome) { - return VILLAGER_TYPES.get(biome.getKey()); - } - - public static Biome getBiomeOrThrow(ResourceKey key) { - return Biome.reference(key).wrap(); - } - - public static Biome createBiome(ResourceKey key, Biome vanilla, VanillaBiomeProperties properties) { - EnvironmentAttributeMap attributes = vanilla.attributes(); - attributes = override(attributes, EnvironmentAttributes.FOG_COLOR, properties.getFogColor()); - attributes = override(attributes, EnvironmentAttributes.WATER_FOG_COLOR, properties.getWaterFogColor()); - attributes = override(attributes, EnvironmentAttributes.SKY_COLOR, properties.getSkyColor()); - attributes = override(attributes, EnvironmentAttributes.AMBIENT_PARTICLES, properties.getParticles()); - attributes = override(attributes, EnvironmentAttributes.MUSIC_VOLUME, properties.getMusicVolume()); - attributes = override(attributes, EnvironmentAttributes.NATURAL_MOB_SPAWNS, properties.getSpawnSettings()); - if(properties.getMusic() != null) { - attributes = attributes.with(EnvironmentAttributes.BACKGROUND_MUSIC, - BackgroundMusic.builder().defaultMusic(properties.getMusic()).build()); - } - if(properties.getLoopSound() != null || properties.getMoodSound() != null || properties.getAdditionsSound() != null) { - AmbientSounds sounds = Objects.requireNonNullElse(attributes.get(EnvironmentAttributes.AMBIENT_SOUNDS), AmbientSounds.EMPTY); - attributes = attributes.with(EnvironmentAttributes.AMBIENT_SOUNDS, AmbientSounds.of( - properties.getLoopSound() != null ? properties.getLoopSound() : sounds.loop().orElse(null), - properties.getMoodSound() != null ? properties.getMoodSound() : sounds.mood().orElse(null), - properties.getAdditionsSound() != null ? List.of(properties.getAdditionsSound()) : sounds.additions())); - } - - ClimateSettings climate = vanilla.climateSettings(); - BiomeSpecialEffects effects = vanilla.specialEffects(); - - return Biome.builder(key) - .attributes(attributes) - .climateSettings(ClimateSettings.builder() - .hasPrecipitation(Objects.requireNonNullElse(properties.getPrecipitation(), climate.hasPrecipitation())) - .temperature(Objects.requireNonNullElse(properties.getTemperature(), climate.temperature())) - .temperatureModifier(Objects.requireNonNullElse(properties.getTemperatureModifier(), climate.temperatureModifier())) - .downfall(Objects.requireNonNullElse(properties.getDownfall(), climate.downfall())) - .build()) - .specialEffects(BiomeSpecialEffects.builder() - .waterColor(Objects.requireNonNullElse(properties.getWaterColor(), effects.waterColor())) - .grassColorModifier(Objects.requireNonNullElse(properties.getGrassColorModifier(), effects.grassColorModifier())) - .grassColorOverride(orElse(properties.getGrassColor(), effects.grassColorOverride().orElse(null))) - .foliageColorOverride(orElse(properties.getFoliageColor(), effects.foliageColorOverride().orElse(null))) - .dryFoliageColorOverride(orElse(properties.getDryFoliageColor(), effects.dryFoliageColorOverride().orElse(null))) - .build()) - .build(); + return appended; } public static String createBiomeID(ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey biomeID) { @@ -158,13 +364,4 @@ public final class BiomeHandler { + "/" + biomeID.getNamespace().toLowerCase(Locale.ROOT) + "/" + biomeID.getID().toLowerCase(Locale.ROOT); } - - private static EnvironmentAttributeMap override(EnvironmentAttributeMap map, EnvironmentAttributeSupplier attribute, - @Nullable T value) { - return value == null ? map : map.with(attribute, value); - } - - private static @Nullable Integer orElse(@Nullable Integer value, @Nullable Integer fallback) { - return value != null ? value : fallback; - } } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java index 5be1be7d8..c11a6e024 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java @@ -5,5 +5,5 @@ import dev.wyck.keys.ResourceKey; import com.dfsek.terra.api.properties.Properties; -public record BukkitBiomeInfo(ResourceKey biomeKey, ResourceKey vanillaKey, org.bukkit.block.Biome bukkitBiome) implements Properties { +public record BukkitBiomeInfo(ResourceKey biomeKey, org.bukkit.block.Biome bukkitBiome) implements Properties { } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitPlatformBiome.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitPlatformBiome.java index 9af8e9db5..386a0faa1 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitPlatformBiome.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitPlatformBiome.java @@ -17,14 +17,19 @@ package com.dfsek.terra.bukkit.world; +import java.util.Objects; + import com.dfsek.terra.api.properties.Context; import com.dfsek.terra.api.properties.PropertyHolder; import com.dfsek.terra.api.world.biome.PlatformBiome; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; +import com.dfsek.terra.world.attribute.platform.ParentEntryHolder; -public class BukkitPlatformBiome implements PlatformBiome, PropertyHolder { +public class BukkitPlatformBiome implements PlatformBiome, PropertyHolder, ParentEntryHolder { private final org.bukkit.block.Biome biome; private final Context context = new Context(); + private volatile AttributeSlots parentEntries = AttributeSlots.EMPTY; public BukkitPlatformBiome(org.bukkit.block.Biome biome) { this.biome = biome; @@ -39,4 +44,13 @@ public class BukkitPlatformBiome implements PlatformBiome, PropertyHolder { public Context getContext() { return context; } + + @Override + public AttributeSlots parentEntries() { + return parentEntries; + } + + public void setParentEntries(AttributeSlots parentEntries) { + this.parentEntries = Objects.requireNonNull(parentEntries, "parentEntries"); + } } diff --git a/platforms/bukkit/common/src/main/resources/paper-plugin.yml b/platforms/bukkit/common/src/main/resources/paper-plugin.yml index 2a1b472a5..d69c8e10d 100644 --- a/platforms/bukkit/common/src/main/resources/paper-plugin.yml +++ b/platforms/bukkit/common/src/main/resources/paper-plugin.yml @@ -1,5 +1,6 @@ name: "Terra" main: "com.dfsek.terra.bukkit.TerraBukkitPlugin" +bootstrapper: "com.dfsek.terra.bukkit.TerraBukkitBootstrap" version: "@VERSION@" load: "STARTUP" authors: [ "dfsek", "duplexsystem", "Astrash", "solonovamax", "Sancires", "Aureus", "RogueShade", "OakLoaf" ] diff --git a/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/BukkitParentsTest.java b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/BukkitParentsTest.java new file mode 100644 index 000000000..47438ee8e --- /dev/null +++ b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/BukkitParentsTest.java @@ -0,0 +1,141 @@ +/* + * This file is part of Terra. + * + * Terra is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Terra is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Terra. If not, see . + */ +package com.dfsek.terra.bukkit.attribute; + +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 net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.Biomes; +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 com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes; +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.registry.Registry; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeMap; +import com.dfsek.terra.api.world.biome.PlatformBiome; +import com.dfsek.terra.bukkit.world.BukkitPlatformBiome; +import com.dfsek.terra.minecraft.attribute.FakePackAttributes; +import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents; +import com.dfsek.terra.minecraft.attribute.PackParents; +import com.dfsek.terra.minecraft.attribute.TestBiome; +import com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; + +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.registry; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class BukkitParentsTest { + private static final Registry> REGISTRY = registry(); + private static final ConfigPack PACK = pack("test"); + private static final Attribute PRECIPITATION = attribute(MinecraftAttributes.BIOME_HAS_PRECIPITATION.getRegistryKey().toString()); + private static final Attribute HAS_CEILING = attribute(MinecraftAttributes.DIMENSION_HAS_CEILING.getRegistryKey().toString()); + + private final List warnings = new ArrayList<>(); + private final AttributeReport report = new AttributeReport("test", warnings::add, s -> { }); + private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE); + + private static ConfigPack pack(String id) { + return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class[]{ ConfigPack.class }, + (proxy, method, args) -> switch(method.getName()) { + case "getID" -> id; + case "getRegistry" -> REGISTRY; + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == args[0]; + case "toString" -> "ConfigPack[" + id + "]"; + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + + private static Biome desert() { + return REGISTRIES.lookupOrThrow(Registries.BIOME).getOrThrow(Biomes.DESERT).value(); + } + + @Test + void vanillaVillagerTypes() { + Map, ResourceKey> types = PaperVanilla.villagerTypes(); + assertSame(types, PaperVanilla.villagerTypes(), "read once"); + assertEquals(VillagerType.DESERT, types.get(Biomes.DESERT)); + + ResourceKey test = ResourceKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("terra", "test_biome")); + ResourceKey before = types.get(test); + try { + types.put(test, VillagerType.SNOW); + assertEquals(VillagerType.SNOW, types.get(test)); + assertEquals(VillagerType.SNOW, PaperVanilla.context(REGISTRIES).villagerTypes().apply(test)); + } finally { + if(before == null) types.remove(test); + else types.put(test, before); + } + assertEquals(before, types.get(test)); + } + + @Test + void parentEntriesAllocationFree() { + parents.beginLoad(CONTEXT); + FakePackAttributes fake = new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(), Map.of()); + PackParents pack = parents.prepare(PACK, Optional.of(fake), report); + BukkitPlatformBiome platformBiome = new BukkitPlatformBiome(null); + assertSame(AttributeSlots.EMPTY, platformBiome.parentEntries()); + assertThrows(NullPointerException.class, () -> platformBiome.setParentEntries(null)); + TestBiome biome = new TestBiome("DESERT", 0, platformBiome); + assertNull(parents.biomeOrNull(biome, PRECIPITATION)); + platformBiome.setParentEntries(parents.biomeEntries(pack, Biomes.DESERT, desert())); + assertEquals(AttributeEntry.override(false), parents.biomeOrNull(biome, PRECIPITATION)); + TestBiome plain = new TestBiome("PLAIN", 1, (PlatformBiome) () -> "plain"); + assertEquals(List.of(), warnings); + assertEquals(7, reads(fake, biome, plain), "every read sees the expected entry"); + + 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, biome, plain); + long before = threads.getThreadAllocatedBytes(thread); + for(int i = 0; i < 10_000; i++) sink += reads(fake, biome, plain); + long allocated = threads.getThreadAllocatedBytes(thread) - before; + + assertEquals(110_000 * 7, sink); + assertTrue(allocated < 1024, allocated + " bytes allocated"); + } + + private int reads(FakePackAttributes fake, 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; + return hash; + } +} diff --git a/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/PaperBiomeTest.java b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/PaperBiomeTest.java new file mode 100644 index 000000000..b8aa1c6da --- /dev/null +++ b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/PaperBiomeTest.java @@ -0,0 +1,138 @@ +/* + * This file is part of Terra. + * + * Terra is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Terra is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Terra. If not, see . + */ +package com.dfsek.terra.bukkit.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.registries.Registries; +import net.minecraft.resources.Identifier; +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.biome.Biomes; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.bukkit.world.BiomeHandler; +import com.dfsek.terra.bukkit.world.BukkitPlatformBiome; +import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents; +import com.dfsek.terra.minecraft.attribute.MinecraftBiomeFactory; +import com.dfsek.terra.minecraft.attribute.PackParents; +import com.dfsek.terra.minecraft.attribute.TestBiome; +import com.dfsek.terra.minecraft.attribute.VanillaCodecs; +import com.dfsek.terra.minecraft.attribute.VanillaContext; +import com.dfsek.terra.world.attribute.platform.AttributeReport; + +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class PaperBiomeTest { + private static final String CONFIG = "BIOME"; + private static final VanillaContext PAPER = PaperVanilla.context(REGISTRIES); + + 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 MinecraftBiomeFactory factory = new MinecraftBiomeFactory(HANDLE, PAPER); + + private static ConfigPack pack(String id) { + return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class[]{ ConfigPack.class }, + (proxy, method, args) -> switch(method.getName()) { + case "getID" -> id; + case "getRegistry" -> null; + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == args[0]; + case "toString" -> "ConfigPack[" + id + "]"; + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + + private static Holder.Reference vanilla(ResourceKey key) { + return REGISTRIES.lookupOrThrow(Registries.BIOME).getOrThrow(key); + } + + private static Object network(Biome biome) { + return VanillaCodecs.encode(Biome.NETWORK_CODEC, biome, PAPER.ops()); + } + + private MinecraftBiomeFactory.Built build(TestBiome biome, PackParents pack, ResourceKey parent) { + Biome parentBiome = vanilla(parent).value(); + ((BukkitPlatformBiome) biome.getPlatformBiome()).setParentEntries(parents.biomeEntries(pack, parent, parentBiome)); + return BiomeHandler.build(factory, parent, parentBiome, biome, pack); + } + + @Test + void noAttributesMatchesParent() { + Biome desert = vanilla(Biomes.DESERT).value(); + assertFalse(desert.getGenerationSettings().features().isEmpty(), "the desert has features"); + assertTrue(desert.getGenerationSettings().getCarvers().iterator().hasNext(), "the desert has carvers"); + parents.beginLoad(PAPER); + PackParents bare = parents.prepare(pack("bare"), Optional.empty(), report); + TestBiome biome = new TestBiome(CONFIG, 0, new BukkitPlatformBiome(null)); + + MinecraftBiomeFactory.Built built = build(biome, bare, Biomes.DESERT); + + assertEquals(network(desert), network(built.biome())); + assertEquals(List.of(), built.biome().getGenerationSettings().features()); + assertFalse(built.biome().getGenerationSettings().getCarvers().iterator().hasNext(), "no carvers"); + assertEquals(VillagerType.DESERT, built.villagerType()); + assertEquals(List.of(), warnings); + assertEquals(List.of(), debugs); + } + + @Test + void additionsListOnlyNewMembers() { + MappedRegistry biomes = new MappedRegistry<>(Registries.BIOME, Lifecycle.stable()); + Holder forest = biomes.register(Biomes.FOREST, vanilla(Biomes.FOREST).value(), RegistrationInfo.BUILT_IN); + Holder ocean = biomes.register(Biomes.OCEAN, vanilla(Biomes.OCEAN).value(), RegistrationInfo.BUILT_IN); + Identifier terraId = Identifier.fromNamespaceAndPath("terra", "t/b"); + Holder terra = biomes.register(ResourceKey.create(Registries.BIOME, terraId), vanilla(Biomes.PLAINS).value(), + RegistrationInfo.BUILT_IN); + TagKey isForest = TagKey.create(Registries.BIOME, Identifier.withDefaultNamespace("is_forest")); + TagKey isOcean = TagKey.create(Registries.BIOME, Identifier.withDefaultNamespace("is_ocean")); + TagKey hasSnow = TagKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("mypack", "has_snow")); + + Map, List>> before = new LinkedHashMap<>(); + before.put(isForest, List.of(forest)); + before.put(isOcean, List.of(ocean)); + Map, List>> after = new LinkedHashMap<>(); + after.put(isForest, List.of(forest, terra)); + after.put(isOcean, List.of(ocean)); + after.put(hasSnow, List.of(terra)); + + assertEquals(Map.of(isForest, List.of(terraId), hasSnow, List.of(terraId)), BiomeHandler.additions(before, after)); + + before.put(isForest, List.of(forest, terra)); + after.put(isForest, List.of(forest, terra, terra)); + assertEquals(Map.of(hasSnow, List.of(terraId)), BiomeHandler.additions(before, after)); + } +} diff --git a/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/PaperDimensionsTest.java b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/PaperDimensionsTest.java new file mode 100644 index 000000000..31488daa8 --- /dev/null +++ b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/PaperDimensionsTest.java @@ -0,0 +1,462 @@ +/* + * This file is part of Terra. + * + * Terra is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Terra is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Terra. If not, see . + */ +package com.dfsek.terra.bukkit.attribute; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.JavaOps; +import com.mojang.serialization.Lifecycle; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.MappedRegistry; +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.RegistryOps; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.TagKey; +import net.minecraft.tags.TimelineTags; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.timeline.Timeline; +import net.minecraft.world.timeline.Timelines; +import org.bukkit.World; +import org.jetbrains.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.lang.reflect.Proxy; +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.Set; +import java.util.function.Consumer; +import java.util.function.Supplier; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.properties.Context; +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.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeMap; +import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.api.world.attribute.PackAttributes; +import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper; +import com.dfsek.terra.minecraft.attribute.FakePackAttributes; +import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents; +import com.dfsek.terra.minecraft.attribute.VanillaCodecs; +import com.dfsek.terra.minecraft.attribute.VanillaContext; +import com.dfsek.terra.world.attribute.platform.AttributeReport; + +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute; +import static com.dfsek.terra.minecraft.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.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class PaperDimensionsTest { + private static final com.dfsek.terra.api.registry.Registry> REGISTRY = registry(); + private static final VanillaContext PAPER = PaperVanilla.context(REGISTRIES); + private static final Map NETHER = Map.of("vanilla", RegistryKey.parse("minecraft:the_nether")); + private static final Map OVERWORLD = Map.of("vanilla", RegistryKey.parse("minecraft:overworld")); + private static final ResourceKey SEASONS = ResourceKey.create(Registries.TIMELINE, Identifier.parse("mypack:seasons")); + + 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 List worldInfos = new ArrayList<>(); + private final List worldWarnings = new ArrayList<>(); + private final FakeServer server = new FakeServer(); + private boolean playersOnline; + private final PaperDimensions dimensions = new PaperDimensions(HANDLE, parents, () -> playersOnline, server, worldInfos::add, + worldWarnings::add); + + private static ConfigPack pack(@Nullable PackAttributes attributes) { + Context context = new Context(); + if(attributes != null) context.put(Context.create(PackAttributes.class), attributes); + return pack("test", () -> context); + } + + private static ConfigPack pack(String id, Supplier context) { + return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class[]{ ConfigPack.class }, + (proxy, method, args) -> switch(method.getName()) { + case "getID" -> id; + case "getRegistry" -> REGISTRY; + case "getContext" -> context.get(); + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == args[0]; + case "toString" -> "ConfigPack[" + id + "]"; + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + + private FakePackAttributes attributes(Map entries, Map parentIds, + List> refs) { + AttributeMap.Builder builder = AttributeMap.builder(); + entries.forEach((id, raw) -> put(builder, attribute(id), decoded(id, raw))); + return new FakePackAttributes(HANDLE, parents, builder.build(), parentIds, Map.of(), refs, Map.of()); + } + + private FakePackAttributes attributes(Map entries, Map parentIds) { + return attributes(entries, parentIds, List.of()); + } + + 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); + } + } + + @SuppressWarnings("unchecked") + private static void put(AttributeMap.Builder builder, Attribute attribute, AttributeEntry entry) { + builder.put(attribute.key(), (AttributeEntry) entry); + } + + private ConfigPack prepared(VanillaContext context, ConfigPack pack) { + parents.beginLoad(context); + parents.prepare(pack, HANDLE.pack(pack), report); + return pack; + } + + private ConfigPack prepared(@Nullable PackAttributes attributes) { + return prepared(PAPER, pack(attributes)); + } + + private static DimensionType dimensionType(VanillaContext context, ResourceKey key) { + return context.dimensionTypes().getOrThrow(key).value(); + } + + private PaperDimensions.Built typeFor(VanillaContext context, ConfigPack pack, ResourceKey world, String worldName) { + return dimensions.typeFor(pack, world, dimensionType(context, world), worldName).orElseThrow(); + } + + private PaperDimensions.Built typeFor(ConfigPack pack, ResourceKey world) { + return typeFor(PAPER, pack, world, "world"); + } + + private static String notApplied(String key) { + return notApplied(key, "world"); + } + + private static String notApplied(String key, String world) { + return "Pack \"test\": attribute \"" + key + "\" is not applied to world \"" + world + + "\": it is fixed when the world is created"; + } + + private static MappedRegistry timelines() { + MappedRegistry timelines = new MappedRegistry<>(Registries.TIMELINE, Lifecycle.stable()); + REGISTRIES.lookupOrThrow(Registries.TIMELINE).listElements() + .forEach(holder -> timelines.register(holder.key(), holder.value(), RegistrationInfo.BUILT_IN)); + RegistryOps ops = PAPER.ops(); + Timeline moon = REGISTRIES.lookupOrThrow(Registries.TIMELINE).getOrThrow(Timelines.MOON).value(); + timelines.register(SEASONS, reread(Timeline.DIRECT_CODEC, moon, ops, ops), RegistrationInfo.BUILT_IN); + + Map, List>> tags = new HashMap<>(); + REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).listElements() + .forEach(type -> type.value().timelines().unwrapKey().ifPresent(tag -> tags.put(tag, List.of()))); + tags.put(TimelineTags.IN_OVERWORLD, List.of(timelines.get(Timelines.OVERWORLD_DAY).orElseThrow(), + timelines.get(Timelines.MOON).orElseThrow(), + timelines.get(Timelines.VILLAGER_SCHEDULE).orElseThrow())); + timelines.bindTags(tags); + timelines.freeze(); + return timelines; + } + + private static VanillaContext contextWith(MappedRegistry timelines) { + Map, HolderLookup.RegistryLookup> lookups = new LinkedHashMap<>(); + REGISTRIES.listRegistries().forEach(lookup -> lookups.put(lookup.key(), lookup)); + lookups.put(Registries.TIMELINE, timelines); + RegistryOps ops = HolderLookup.Provider.create(lookups.values().stream()).createSerializationContext(JavaOps.INSTANCE); + + MappedRegistry types = new MappedRegistry<>(Registries.DIMENSION_TYPE, Lifecycle.stable()); + REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).listElements().forEach(holder -> types.register(holder.key(), + reread(DimensionType.DIRECT_CODEC, holder.value(), PAPER.ops(), ops), RegistrationInfo.BUILT_IN)); + types.freeze(); + lookups.put(Registries.DIMENSION_TYPE, types); + return PaperVanilla.context(HolderLookup.Provider.create(lookups.values().stream())); + } + + private static T reread(Codec codec, T value, RegistryOps from, RegistryOps to) { + try { + return VanillaCodecs.parse(codec, VanillaCodecs.encode(codec, value, from), to); + } catch(DecodeException e) { + throw new AssertionError(e.getMessage(), e); + } + } + + 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 List> keys(DimensionType type) { + return type.timelines().stream().map(holder -> holder.unwrapKey().orElseThrow()).toList(); + } + + @Test + void pinnedFieldsFollowWorld() { + ConfigPack pack = prepared(attributes(Map.of(), NETHER)); + + PaperDimensions.Built built = typeFor(pack, BuiltinDimensionTypes.OVERWORLD); + DimensionType type = built.type(); + + assertEquals(Identifier.parse("terra:test/minecraft/overworld"), built.key()); + + assertEquals(-64, type.minY()); + assertEquals(384, type.height()); + assertTrue(type.hasSkyLight()); + assertEquals(0.1f, type.ambientLight()); + assertTrue(type.hasCeiling()); + assertEquals(Optional.empty(), type.defaultClock()); + assertEquals(List.of(), warnings); + assertEquals(List.of(notApplied("terra:dimension/min_y"), notApplied("terra:dimension/height"), + notApplied("terra:dimension/has_skylight")), debugs); + } + + @Test + void worldTypeIsDefaultParent() { + ConfigPack pack = prepared(attributes(Map.of(), Map.of())); + DimensionType nether = dimensionType(PAPER, BuiltinDimensionTypes.NETHER); + + PaperDimensions.Built inOverworld = typeFor(PAPER, pack, BuiltinDimensionTypes.OVERWORLD, "world"); + PaperDimensions.Built inNether = typeFor(PAPER, pack, BuiltinDimensionTypes.NETHER, "world_nether"); + + assertNotSame(nether, inNether.type()); + assertEquals(nether, inNether.type()); + assertEquals(Identifier.parse("terra:test/minecraft/the_nether"), inNether.key()); + DimensionType overworld = dimensionType(PAPER, BuiltinDimensionTypes.OVERWORLD); + assertNotSame(overworld, inOverworld.type()); + assertEquals(overworld, inOverworld.type()); + assertEquals(Identifier.parse("terra:test"), inOverworld.key()); + assertEquals(List.of(), warnings); + assertEquals(List.of(), debugs); + } + + @Test + void directTimelinesFromRefs() { + MappedRegistry timelines = timelines(); + VanillaContext context = contextWith(timelines); + ConfigPack pack = prepared(context, pack(attributes(Map.of(), Map.of(), List.of(tag("minecraft", "in_overworld"), + id("mypack:seasons"))))); + + dimensions.recordTimelines(pack, timelines); + DimensionType type = typeFor(context, pack, BuiltinDimensionTypes.OVERWORLD, "world").type(); + + assertEquals(List.of(Timelines.OVERWORLD_DAY, Timelines.MOON, Timelines.VILLAGER_SCHEDULE, SEASONS), keys(type)); + assertEquals(List.of(), warnings); + } + + @Test + void noValidRefKeepsParent() { + MappedRegistry timelines = timelines(); + VanillaContext context = contextWith(timelines); + ConfigPack pack = prepared(context, pack(attributes(Map.of(), Map.of(), List.of(id("mypack:nope"))))); + + dimensions.recordTimelines(pack, timelines); + DimensionType type = typeFor(context, pack, BuiltinDimensionTypes.OVERWORLD, "world").type(); + typeFor(context, pack, BuiltinDimensionTypes.OVERWORLD, "other"); + DimensionType nether = typeFor(context, pack, BuiltinDimensionTypes.NETHER, "world_nether").type(); + + assertEquals(List.of(Timelines.OVERWORLD_DAY, Timelines.MOON, Timelines.VILLAGER_SCHEDULE), keys(type)); + assertEquals(keys(dimensionType(context, BuiltinDimensionTypes.NETHER)), keys(nether)); + assertEquals(List.of("Pack \"test\": schedule \"mypack:nope\" skipped: no such timeline", + "Pack \"test\", config \"pack.yml\": \"schedules\" ignored: no valid schedule; " + + "the parent's timelines are kept"), + warnings); + } + + @Test + void noAttributesLeavesWorld() { + ConfigPack pack = prepared(null); + + assertEquals(Optional.empty(), dimensions.typeFor(pack, BuiltinDimensionTypes.OVERWORLD, + dimensionType(PAPER, BuiltinDimensionTypes.OVERWORLD), "world")); + assertEquals(List.of(), warnings); + assertEquals(List.of(), debugs); + } + + @Test + void unsupportedGenerationWarnsOnce() { + ConfigPack pack = prepared(attributes(Map.of("terra:world/sea_level", 40, "terra:world/spawn_height", 80), + Map.of("vanilla-generation", RegistryKey.parse("minecraft:nether")))); + + dimensions.registerPacks(List.of(pack)); + typeFor(PAPER, pack, BuiltinDimensionTypes.OVERWORLD, "world"); + typeFor(PAPER, pack, BuiltinDimensionTypes.NETHER, "world_nether"); + + assertEquals(List.of("Pack \"test\", config \"pack.yml\": \"terra:world/sea_level\" ignored: not applied on this platform", + "Pack \"test\", config \"pack.yml\": \"terra:world/spawn_height\" ignored: not applied on this platform", + "Pack \"test\", config \"pack.yml\": \"vanilla-generation\" ignored: not applied on this platform"), + warnings); + } + + @Test + void logicalHeightCappedToWorld() { + String reported = notApplied("terra:dimension/logical_height", "world_nether"); + PaperDimensions.Built inherited = typeFor(PAPER, prepared(attributes(Map.of(), OVERWORLD)), BuiltinDimensionTypes.NETHER, + "world_nether"); + + assertEquals(256, inherited.type().logicalHeight()); + assertEquals(256, inherited.type().height()); + assertEquals(Identifier.parse("terra:test/minecraft/the_nether"), inherited.key()); + assertFalse(debugs.contains(reported), String.valueOf(debugs)); + + ConfigPack set = prepared(attributes(Map.of("terra:dimension/logical_height", 384), OVERWORLD)); + typeFor(PAPER, set, BuiltinDimensionTypes.NETHER, "world_nether"); + assertEquals(256, typeFor(PAPER, set, BuiltinDimensionTypes.NETHER, "world_nether").type().logicalHeight()); + + assertEquals(1, debugs.stream().filter(reported::equals).count(), String.valueOf(debugs)); + assertEquals(List.of(), warnings); + } + + @Test + void unreadablePackSkipped() { + ConfigPack broken = pack("broken", () -> { + throw new IllegalStateException("boom"); + }); + ConfigPack pack = prepared(attributes(Map.of("terra:world/sea_level", 40), Map.of())); + + dimensions.registerPacks(List.of(broken, pack)); + + assertEquals(List.of("Pack \"broken\": timelines and dimension type skipped: its attributes could not be read"), worldWarnings); + assertEquals(List.of("Pack \"test\", config \"pack.yml\": \"terra:world/sea_level\" ignored: not applied on this platform"), + warnings); + } + + private static World world() { + return (World) Proxy.newProxyInstance(World.class.getClassLoader(), new Class[]{ World.class }, + (proxy, method, args) -> switch(method.getName()) { + case "getName" -> "world"; + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == args[0]; + case "toString" -> "World[world]"; + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + + private BukkitChunkGeneratorWrapper initialise() { + BukkitChunkGeneratorWrapper wrapper = new BukkitChunkGeneratorWrapper(null, prepared(attributes( + Map.of("terra:world/mob_generation", false), OVERWORLD)), null); + dimensions.onWorldInit(world(), wrapper); + return wrapper; + } + + private static final Identifier TERRA_TEST = Identifier.parse("terra:test"); + private static final String KEEPS = "Pack \"test\": world \"world\" keeps its dimension type"; + + @ParameterizedTest(name = "registered {0}, players online {1}") + @CsvSource({ + "false, false, true, true, false", + "true, false, false, true, false", + "false, true, false, false, true", + "true, true, false, true, false" + }) + void worldInitRegistersThenApplies(boolean registered, boolean online, boolean registers, boolean applies, boolean keeps) { + if(registered) server.registered.add(TERRA_TEST); + playersOnline = online; + + assertFalse(initialise().shouldGenerateMobs()); + + assertEquals(registers ? List.of(TERRA_TEST) : List.of(), server.registrations); + assertEquals(applies ? List.of(TERRA_TEST) : List.of(), server.applications); + assertEquals(keeps ? List.of(KEEPS + " until the server restarts, since players are online") : List.of(), worldInfos); + assertEquals(List.of(), worldWarnings); + } + + @ParameterizedTest(name = "{0} fails") + @CsvSource(delimiter = '|', quoteCharacter = '"', value = { + "lookup | false | : the pack's could not be registered", + "register | false | : the pack's could not be registered", + "apply | true | : wyck could not apply the pack's" + }) + void failedStepKeepsTheWorldsType(String step, boolean registers, String warning) { + IllegalStateException boom = new IllegalStateException("boom"); + switch(step) { + case "lookup" -> server.lookupFailure = boom; + case "register" -> server.registerFailure = boom; + case "apply" -> server.applyFailure = boom; + default -> throw new IllegalArgumentException(step); + } + + assertFalse(initialise().shouldGenerateMobs()); + + assertEquals(registers ? List.of(TERRA_TEST) : List.of(), server.registrations); + assertEquals(List.of(), server.applications); + assertEquals(List.of(KEEPS + warning), worldWarnings); + } + + + private static final class FakeServer implements PaperDimensions.Server { + private final Set registered = new HashSet<>(); + private final List registrations = new ArrayList<>(); + private final List applications = new ArrayList<>(); + private @Nullable RuntimeException lookupFailure; + private @Nullable RuntimeException registerFailure; + private @Nullable RuntimeException applyFailure; + + @Override + public void registerTimelines(Consumer> registration) { + registration.accept(new MappedRegistry<>(Registries.TIMELINE, Lifecycle.stable())); + } + + @Override + public Registry timelines() { + return PaperDimensionsTest.timelines(); + } + + @Override + public Holder dimensionType(World world) { + return REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(BuiltinDimensionTypes.OVERWORLD); + } + + @Override + public boolean isRegistered(Identifier key) { + if(lookupFailure != null) throw lookupFailure; + return registered.contains(key); + } + + @Override + public void registerDimension(Identifier key, DimensionType type) { + if(registerFailure != null) throw registerFailure; + registrations.add(key); + registered.add(key); + } + + @Override + public void applyDimension(World world, Identifier key) { + if(applyFailure != null) throw applyFailure; + applications.add(key); + } + } +} diff --git a/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/util/ServerThreadTest.java b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/util/ServerThreadTest.java new file mode 100644 index 000000000..ec201cef0 --- /dev/null +++ b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/util/ServerThreadTest.java @@ -0,0 +1,101 @@ +package com.dfsek.terra.bukkit.util; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +@Timeout(10) +class ServerThreadTest { + private final ExecutorService server = Executors.newSingleThreadExecutor(r -> new Thread(r, "server")); + + @AfterEach + void stopServer() { + server.shutdownNow(); + } + + @Test + void runsOnServerThread() { + AtomicReference ranOn = new AtomicReference<>(); + + ServerThread.run(() -> ranOn.set(Thread.currentThread().getName()), server, () -> false, () -> false, 10); + + assertEquals("server", ranOn.get()); + } + + @Test + void runsDirectlyOnServerThread() { + List ran = new ArrayList<>(); + + ServerThread.run(() -> ran.add(Thread.currentThread().getName()), task -> { + throw new AssertionError("scheduled from the server thread"); + }, () -> true, () -> false, 10); + + assertEquals(List.of(Thread.currentThread().getName()), ran); + } + + @Test + void rethrowsTaskException() { + IllegalStateException boom = new IllegalStateException("boom"); + + assertSame(boom, assertThrows(IllegalStateException.class, () -> ServerThread.run(() -> { + throw boom; + }, server, () -> false, () -> false, 10))); + } + + @Test + void dropsPendingTaskOnStop() { + List scheduled = new ArrayList<>(); + AtomicBoolean ran = new AtomicBoolean(); + + assertThrows(CancellationException.class, () -> ServerThread.run(() -> ran.set(true), scheduled::add, () -> false, () -> true, + 10)); + scheduled.forEach(Runnable::run); + + assertFalse(ran.get()); + } + + @Test + void waitsForStartedTaskOnStop() throws InterruptedException { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + AtomicBoolean finished = new AtomicBoolean(); + AtomicBoolean stopping = new AtomicBoolean(); + Thread caller = new Thread(() -> ServerThread.run(() -> { + started.countDown(); + try { + release.await(); + } catch(InterruptedException e) { + throw new IllegalStateException(e); + } + finished.set(true); + }, server, () -> false, stopping::get, 10)); + caller.start(); + + assertTrue(started.await(5, TimeUnit.SECONDS)); + stopping.set(true); + caller.interrupt(); + Thread.sleep(50); + assertTrue(caller.isAlive(), "the caller waits for the running task"); + release.countDown(); + caller.join(); + + assertTrue(finished.get()); + } +} diff --git a/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/world/BiomeHandlerTest.java b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/world/BiomeHandlerTest.java new file mode 100644 index 000000000..3020dd90c --- /dev/null +++ b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/world/BiomeHandlerTest.java @@ -0,0 +1,286 @@ +/* + * This file is part of Terra. + * + * Terra is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Terra is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Terra. If not, see . + */ +package com.dfsek.terra.bukkit.world; + +import net.minecraft.core.Holder; +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.entity.npc.villager.VillagerType; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.Biomes; +import org.jetbrains.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +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.Stream; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.minecraft.attribute.BiomeTags.PlatformTagSource; +import com.dfsek.terra.minecraft.attribute.MinecraftBiomeFactory; +import com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; + +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES; +import static org.junit.jupiter.api.Named.named; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + + +class BiomeHandlerTest { + private static final Biome PARENT = biome(Biomes.DESERT); + private static final Biome BUILT = biome(Biomes.PLAINS); + private static final String PREFIX = "Pack \"test\", config \"BIOME\": "; + + private final List warnings = new ArrayList<>(); + + private static Biome biome(net.minecraft.resources.ResourceKey key) { + return REGISTRIES.lookupOrThrow(Registries.BIOME).getOrThrow(key).value(); + } + + private BiomeHandler.Registration register(MinecraftBiomeFactory.Built built, Function wyck) { + return BiomeHandler.registration(() -> { + if(built == null) throw new IllegalStateException("boom"); + return built; + }, wyck, PARENT, VillagerType.DESERT, "test", "BIOME", warnings::add); + } + + private static Biome rejecting(Biome biome, Biome rejected) { + if(biome == rejected) throw new IllegalArgumentException("boom"); + return biome; + } + + private static Stream registrations() { + Function readsAll = b -> b; + Function rejectsBuilt = b -> rejecting(b, BUILT); + Function rejectsAll = b -> rejecting(b, b); + return Stream.of( + Arguments.of(true, named("wyck reads all", readsAll), BUILT, VillagerType.SNOW, null), + Arguments.of(false, named("wyck reads all", readsAll), PARENT, VillagerType.DESERT, + "biome built from its parent: its attributes could not be applied"), + Arguments.of(true, named("wyck rejects the built biome", rejectsBuilt), PARENT, VillagerType.DESERT, + "biome built from its parent: wyck could not read its attributes"), + Arguments.of(true, named("wyck rejects all", rejectsAll), null, null, + "biome skipped: wyck could not read its attributes or its parent"), + Arguments.of(false, named("wyck rejects all", rejectsAll), null, null, + "biome skipped: its attributes could not be applied, and wyck could not read its parent")); + } + + @ParameterizedTest(name = "builds {0}, {1}") + @MethodSource("registrations") + void registrationFallsBackToTheParent(boolean builds, Function wyck, @Nullable Biome biome, + @Nullable ResourceKey villagerType, @Nullable String warning) { + BiomeHandler.Registration registration = register(builds ? new MinecraftBiomeFactory.Built(BUILT, VillagerType.SNOW) + : null, wyck); + + if(biome == null) { + assertNull(registration); + } else { + assertSame(biome, registration.biome()); + assertEquals(villagerType, registration.villagerType()); + } + assertEquals(warning == null ? List.of() : List.of(PREFIX + warning), warnings); + } + + @Test + void failedAppendSkipsTag() { + TagKey isForest = TagKey.create(Registries.BIOME, Identifier.withDefaultNamespace("is_forest")); + TagKey isOcean = TagKey.create(Registries.BIOME, Identifier.withDefaultNamespace("is_ocean")); + TagKey hasSnow = TagKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("mypack", "has_snow")); + List terra = List.of(Identifier.fromNamespaceAndPath("terra", "t/b")); + Map, List> additions = new LinkedHashMap<>(); + additions.put(isForest, terra); + additions.put(isOcean, terra); + additions.put(hasSnow, terra); + List> appended = new ArrayList<>(); + + int count = BiomeHandler.appendAll(additions, (tag, biomes) -> { + if(tag == isOcean) throw new IllegalStateException("boom"); + appended.add(tag); + }, "wyck could not append to the tag", warnings::add); + + assertEquals(2, count); + assertEquals(List.of(isForest, hasSnow), appended); + assertEquals(List.of("Biome tag \"minecraft:is_ocean\": terra biomes not added: wyck could not append to the tag"), warnings); + } + + @Test + void nothingNewSkipsRegistration() { + List info = new ArrayList<>(); + List> registered = new ArrayList<>(); + + BiomeHandler.registerNew(List.of(), registered::add, info::add); + BiomeHandler.registerNew(List.of("a", "b"), registered::add, info::add); + + assertEquals(List.of(List.of("a", "b")), registered); + assertEquals(List.of("No new custom biomes to register.", "Registering 2 custom biomes through Wyck..."), info); + } + + private static ConfigPack pack(String id) { + return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class[]{ ConfigPack.class }, + (proxy, method, args) -> switch(method.getName()) { + case "getID" -> id; + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == args[0]; + case "toString" -> "ConfigPack[" + id + "]"; + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + + private static final Identifier PLAINS = Biomes.PLAINS.identifier(); + private static final Identifier DESERT = Biomes.DESERT.identifier(); + + private PlatformTagSource tags(String pack, String config) { + return new PlatformTagSource(new AttributeReport(pack, warnings::add, m -> { }), config, Set.of()); + } + + private void add(BiomeHandler.Run run, String pack, String config, String key, Identifier parent, boolean registered, + net.minecraft.resources.ResourceKey type, List after) { + run.add(Identifier.fromNamespaceAndPath("terra", key), parent, registered, + () -> new BiomeHandler.Registration<>(pack + "/" + config, type), tags(pack, config), () -> after.add(pack + "/" + config), + pack, config, warnings::add); + } + + @Test + void unreadablePackSkipped() { + List after = new ArrayList<>(); + + BiomeHandler.Run run = BiomeHandler.collect( + List.of(pack("first"), pack("unreadable"), pack("broken"), pack("last")), pack -> { + if(pack.getID().equals("unreadable")) throw new ClassCastException("boom"); + return pack.getID(); + }, (pack, prepared, packRun) -> { + add(packRun, prepared, "a", prepared + "/a", PLAINS, false, VillagerType.PLAINS, after); + if(prepared.equals("broken")) throw new IllegalArgumentException("boom"); + }, warnings::add); + run.afterRegistration.forEach(Runnable::run); + + assertEquals(List.of("Pack \"unreadable\": biomes skipped: its attributes could not be read", + "Pack \"broken\": biomes skipped: they could not be built"), warnings); + assertEquals(List.of("first/a", "last/a"), run.toRegister); + assertEquals(List.of(Identifier.parse("terra:first/a"), Identifier.parse("terra:last/a")), + List.copyOf(run.villagerTypes.keySet())); + assertEquals(Map.of(PLAINS, List.of(Identifier.parse("terra:first/a"), Identifier.parse("terra:last/a"))), run.byParent); + assertEquals(Set.of(Identifier.parse("terra:first/a"), Identifier.parse("terra:last/a")), run.platformTags.keySet()); + assertEquals(List.of("first/a", "last/a"), after); + } + + @Test + void registeredBiomeNotQueued() { + List after = new ArrayList<>(); + BiomeHandler.Run run = new BiomeHandler.Run<>(null); + + add(run, "test", "a", "test/a", PLAINS, true, VillagerType.PLAINS, after); + + assertEquals(List.of(), run.toRegister); + assertEquals(Map.of(), run.villagerTypes); + assertEquals(Map.of(PLAINS, List.of(Identifier.parse("terra:test/a"))), run.byParent); + assertEquals(1, run.afterRegistration.size()); + } + + @Test + void sameKeyIsQueuedOnce() { + List after = new ArrayList<>(); + + BiomeHandler.Run run = BiomeHandler.collect(List.of(pack("test"), pack("TEST")), pack -> pack, + (pack, prepared, packRun) -> { + if(pack.getID().equals("test")) { + add(packRun, "test", "Snowy", "test/snowy", PLAINS, false, VillagerType.SNOW, after); + add(packRun, "test", "SNOWY", "test/snowy", DESERT, false, VillagerType.DESERT, after); + } else { + add(packRun, "TEST", "snowy", "test/snowy", DESERT, false, VillagerType.DESERT, after); + } + }, warnings::add); + run.afterRegistration.forEach(Runnable::run); + + Identifier snowy = Identifier.parse("terra:test/snowy"); + assertEquals(List.of("test/Snowy"), run.toRegister); + assertEquals(Map.of(snowy, VillagerType.SNOW), run.villagerTypes); + assertEquals(Map.of(PLAINS, List.of(snowy)), run.byParent); + assertEquals("Snowy", run.platformTags.get(snowy).config()); + assertEquals(List.of("test/Snowy", "test/SNOWY", "TEST/snowy"), after); + assertEquals(List.of( + "Pack \"test\", config \"SNOWY\": biome \"terra:test/snowy\" shared with another config: their IDs differ only in case", + "Pack \"TEST\", config \"snowy\": biome \"terra:test/snowy\" shared with another config: their IDs differ only in case"), + warnings); + } + + @Test + void unreadableParentEntriesAreEmpty() { + AttributeSlots entries = BiomeHandler.parentEntries(() -> { + throw new ClassCastException("boom"); + }, "test", "BIOME", warnings::add); + + assertSame(AttributeSlots.EMPTY, entries); + assertEquals(List.of(PREFIX + "parent attributes ignored: they could not be read"), warnings); + } + + private static TagKey tag(String id) { + return TagKey.create(Registries.BIOME, Identifier.parse(id)); + } + + private static Optional> lookup(Identifier id) { + return REGISTRIES.lookupOrThrow(Registries.BIOME).get(net.minecraft.resources.ResourceKey.create(Registries.BIOME, id)) + .map(h -> h); + } + + @Test + void reloadedTagsGetTerraBiomesOnce() { + Identifier plains = Biomes.PLAINS.identifier(); + Identifier forest = Biomes.FOREST.identifier(); + Identifier terra = Biomes.DESERT.identifier(); + TagKey villagePlains = tag("minecraft:has_structure/village_plains"); + TagKey isForest = tag("minecraft:is_forest"); + TagKey hasSnow = tag("mypack:has_snow"); + TagKey isOcean = tag("minecraft:is_ocean"); + Map, List> tags = new LinkedHashMap<>(); + tags.put(villagePlains, List.of(plains)); + tags.put(isForest, List.of(forest)); + tags.put(isOcean, List.of(Biomes.OCEAN.identifier())); + Set platformTags = new LinkedHashSet<>(List.of(RegistryKey.parse("mypack:has_snow"), + RegistryKey.parse("minecraft:is_forest"))); + PlatformTagSource source = new PlatformTagSource(new AttributeReport("test", warnings::add, m -> { }), "BIOME", platformTags); + + Map, List> additions = BiomeHandler.reloadAdditions(tags, BiomeHandlerTest::lookup, + Map.of(plains, List.of(terra)), Map.of(terra, source)); + + assertEquals(List.of(villagePlains, isForest, hasSnow), List.copyOf(additions.keySet())); + assertEquals(List.of(terra), additions.get(villagePlains)); + assertEquals(List.of(terra), additions.get(isForest)); + assertEquals(List.of(terra), additions.get(hasSnow)); + assertEquals(List.of(), warnings); + + Map, List> reloaded = new LinkedHashMap<>(tags); + additions.forEach((tag, ids) -> reloaded.merge(tag, ids, (old, added) -> Stream.concat(old.stream(), added.stream()).toList())); + assertEquals(Map.of(), BiomeHandler.reloadAdditions(reloaded, BiomeHandlerTest::lookup, Map.of(plains, List.of(terra)), + Map.of(terra, source))); + } +} diff --git a/platforms/fabric/build.gradle.kts b/platforms/fabric/build.gradle.kts index 02a3458bf..f6af74c43 100644 --- a/platforms/fabric/build.gradle.kts +++ b/platforms/fabric/build.gradle.kts @@ -16,6 +16,9 @@ dependencies { implementation(project(":platforms:mixin-common")) { isTransitive = false } "developmentFabric"(project(":platforms:mixin-common")) { isTransitive = false } shaded(project(path = ":platforms:mixin-common", configuration = "transformProductionFabric")) { isTransitive = false } + implementation(project(":platforms:minecraft-common")) { isTransitive = false } + "developmentFabric"(project(":platforms:minecraft-common")) { isTransitive = false } + shaded(project(path = ":platforms:minecraft-common", configuration = "transformProductionFabric")) { isTransitive = false } implementation(project(":platforms:mixin-lifecycle")) { isTransitive = false } "developmentFabric"(project(":platforms:mixin-lifecycle")) { isTransitive = false } shaded(project(path = ":platforms:mixin-lifecycle", configuration = "transformProductionFabric")) { isTransitive = false } diff --git a/platforms/minecraft-common/build.gradle.kts b/platforms/minecraft-common/build.gradle.kts new file mode 100644 index 000000000..7bdf05c70 --- /dev/null +++ b/platforms/minecraft-common/build.gradle.kts @@ -0,0 +1,33 @@ +plugins { + id("dev.architectury.loom-no-remap") version Versions.Mod.architecturyLoom + id("architectury-plugin") version Versions.Mod.architecturyPlugin + `java-test-fixtures` +} + +loom { + accessWidenerPath.set(project(":platforms:mixin-common").file("src/main/resources/terra.accesswidener")) +} + +dependencies { + shadedApi(project(":common:implementation:base")) + + minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") + + // Tests only: the addon ships as its own jar. + testImplementation(project(":common:addons:minecraft-attributes")) + testFixturesImplementation(project(":common:addons:minecraft-attributes")) +} + +architectury { + common("fabric") + minecraft = Versions.Mod.minecraft +} + +// Loom puts Minecraft on the main and test classpaths only. +configurations.matching { it.name == "minecraftNamedCompile" }.configureEach { + configurations["testFixturesCompileClasspath"].extendsFrom(this) +} + +tasks.withType().configureEach { + options.release = 25 +} diff --git a/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/BiomeTags.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/BiomeTags.java new file mode 100644 index 000000000..c18b93122 --- /dev/null +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/BiomeTags.java @@ -0,0 +1,71 @@ +package com.dfsek.terra.minecraft.attribute; + +import net.minecraft.core.Holder; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.tags.TagKey; +import net.minecraft.world.level.biome.Biome; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +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 com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.world.attribute.platform.AttributeReport; + + +public final class BiomeTags { + private static final Logger logger = LoggerFactory.getLogger(BiomeTags.class); + + private BiomeTags() { + + } + + public record PlatformTagSource(AttributeReport report, String config, Set tags) { } + + 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/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParents.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftAttributeParents.java similarity index 70% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParents.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftAttributeParents.java index 6950dc9ca..ed213f699 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParents.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftAttributeParents.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.core.HolderGetter; import net.minecraft.core.Registry; @@ -24,7 +24,10 @@ 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; +import com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; +import com.dfsek.terra.world.attribute.platform.ParentEntryHolder; +import com.dfsek.terra.world.attribute.platform.ParentFold; public final class MinecraftAttributeParents implements AttributeParents { @@ -67,20 +70,32 @@ public final class MinecraftAttributeParents implements AttributeParents { return state.context(); } - public synchronized PackParents prepare(ConfigPack pack, Optional attributes, AttributeReport report) { + public PackParents prepare(ConfigPack pack, Optional attributes, AttributeReport report) { + return prepare(pack, attributes, report, BuiltinDimensionTypes.OVERWORLD); + } + + public synchronized PackParents prepare(ConfigPack pack, Optional attributes, AttributeReport report, + ResourceKey defaultDimension) { State current = state; VanillaContext context = current.context(); if(context == null) throw new IllegalStateException("no registry load has begun"); + ResourceKey fallback = context.dimensionTypes().get(defaultDimension).isPresent() + ? defaultDimension + : BuiltinDimensionTypes.OVERWORLD; 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]; + PackParents candidate = prepared[i]; + if(candidate.pack() == pack && candidate.attributes() == packAttributes + && (!candidate.dimensionDefaulted() || candidate.dimensionKey().equals(fallback))) return candidate; } - 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); + ResourceKey named = parent(packAttributes, VANILLA, Registries.DIMENSION_TYPE, context.dimensionTypes(), + "dimension type", report); + ResourceKey dimensionKey = named == null ? fallback : named; + ResourceKey namedGeneration = parent(packAttributes, VANILLA_GENERATION, Registries.NOISE_SETTINGS, + context.noiseSettings(), "noise settings", report); + ResourceKey generationKey = namedGeneration == null ? NoiseGeneratorSettings.OVERWORLD : namedGeneration; DimensionType dimension = context.dimensionTypes().getOrThrow(dimensionKey).value(); NoiseGeneratorSettings generation = context.noiseSettings().getOrThrow(generationKey).value(); @@ -89,7 +104,7 @@ public final class MinecraftAttributeParents implements AttributeParents { 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, + PackParents parents = new PackParents(pack, dimensionKey, named == null, dimension, generationKey, generation, table, fold(table, dimensionSlots, generationSlots), packAttributes, report, reader); PackParents[] packs = Arrays.copyOf(prepared, prepared.length + 1); packs[packs.length - 1] = parents; @@ -114,9 +129,10 @@ public final class MinecraftAttributeParents implements AttributeParents { @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; + return biome.getPlatformBiome() instanceof ParentEntryHolder holder ? holder.parentEntries().get(attribute) : null; } + // Hot path: no allocation, hashing or boxing. @Override public @Nullable AttributeEntry packOrNull(PackAttributes pack, Attribute attribute) { PackParents[] packs = state.packs(); @@ -126,38 +142,30 @@ public final class MinecraftAttributeParents implements AttributeParents { return null; } - private static ResourceKey parent(@Nullable PackAttributes attributes, String configKey, - ResourceKey> registry, HolderGetter getter, - ResourceKey fallback, String what, AttributeReport report) { + private static @Nullable ResourceKey parent(@Nullable PackAttributes attributes, String configKey, + ResourceKey> registry, HolderGetter getter, + String what, AttributeReport report) { RegistryKey id = attributes == null ? null : attributes.parents().get(configKey); - if(id == null) return fallback; + if(id == null) return null; ResourceKey key; try { key = ResourceKey.create(registry, VanillaIds.identifier(id)); } catch(IllegalArgumentException e) { report.ignored(PACK_CONFIG, configKey, e.getMessage()); - return fallback; + return null; } if(getter.get(key).isPresent()) return key; report.ignored(PACK_CONFIG, configKey, "no such " + what + " \"" + key.identifier() + "\""); - return fallback; + return null; } 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))); + List> attributes = new ArrayList<>(); + for(PackAttributeTable.Bound bound : table.environment()) attributes.add(bound.attribute()); + for(PackAttributeTable.Field field : table.dimension()) attributes.add(field.attribute()); + if(table.seaLevel() != null) attributes.add(table.seaLevel()); + if(table.mobGeneration() != null) attributes.add(table.mobGeneration()); + return ParentFold.fold(handle, attributes, dimension, generation); } static BiConsumer, String> parentSkipped(AttributeReport report, String parent) { diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactory.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftBiomeFactory.java similarity index 93% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactory.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftBiomeFactory.java index 7b4e5a331..0c8cd9f04 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactory.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftBiomeFactory.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Codec; import net.minecraft.core.registries.BuiltInRegistries; @@ -8,6 +8,7 @@ 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.BiomeGenerationSettings; import net.minecraft.world.level.biome.BiomeSpecialEffects; import org.jetbrains.annotations.Nullable; @@ -22,7 +23,9 @@ 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; +import com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; +import com.dfsek.terra.world.attribute.platform.ParentEntryHolder; public final class MinecraftBiomeFactory { @@ -40,7 +43,8 @@ public final class MinecraftBiomeFactory { * {@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) { + AttributeReport report, BiomeGenerationSettings generation) { + Objects.requireNonNull(generation, "generation"); String config = terraBiome.getID(); PackAttributes attributes = pack.attributes(); PackAttributeTable table = pack.table(); @@ -67,7 +71,7 @@ public final class MinecraftBiomeFactory { .downfall(climate.downfall()) .specialEffects(effects) .putAttributes(environment) - .generationSettings(parent.getGenerationSettings()) + .generationSettings(generation) .build(); return new Built(biome, villagerType); } @@ -119,8 +123,8 @@ public final class MinecraftBiomeFactory { 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 parentSlots = terraBiome.getPlatformBiome() instanceof ParentEntryHolder holder + ? holder.parentEntries() : AttributeSlots.EMPTY; Map, AttributeEntry> entries = new LinkedHashMap<>(); for(PackAttributeTable.Bound bound : table.environment()) { diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactory.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftDimensionFactory.java similarity index 72% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactory.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftDimensionFactory.java index cd0163fc6..6f424c9ca 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactory.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftDimensionFactory.java @@ -1,27 +1,30 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; -import net.minecraft.tags.TagKey; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; 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.jetbrains.annotations.Nullable; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; 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.config.ConfigPack; 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; +import com.dfsek.terra.world.attribute.platform.AttributeReport; public final class MinecraftDimensionFactory { + private static final String TERRA = "terra"; private static final String PACK_CONFIG = "pack.yml"; private static final String ATTRIBUTES = "attributes"; private static final String TIMELINES = "timelines"; @@ -38,7 +41,7 @@ public final class MinecraftDimensionFactory { this.maps = new VanillaAttributeMaps(handle, context); } - public DimensionType create(PackParents pack, @Nullable TagKey timelines) { + public DimensionType create(PackParents pack, @Nullable TimelineRef timelines) { DimensionType parent = pack.dimension(); PackAttributes attributes = pack.attributes(); PackAttributeTable table = pack.table(); @@ -47,25 +50,36 @@ public final class MinecraftDimensionFactory { 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); + for(PackAttributeTable.Field field : table.dimension()) set(all, field, pack); 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(timelines != null) all.put(TIMELINES, timelines.encoded()); 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); + built = fieldByField(parent, original, all, table.dimension(), pack, 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; } + /** + * Fabric saves this ID in the world: it must not depend on the pack's {@code vanilla} parent. Overworld keeps + * {@code terra:} for worlds from older Terra versions. + */ + public static Identifier typeId(ConfigPack pack, ResourceKey base, boolean baseValuesApplied) { + String id = pack.getID().toLowerCase(Locale.ROOT); + if(!baseValuesApplied && BuiltinDimensionTypes.OVERWORLD.equals(base)) return Identifier.fromNamespaceAndPath(TERRA, id); + Identifier key = base.identifier(); + return Identifier.fromNamespaceAndPath(TERRA, id + "/" + key.getNamespace() + "/" + key.getPath()); + } + // 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(), @@ -75,8 +89,9 @@ public final class MinecraftDimensionFactory { } private DimensionType fieldByField(DimensionType parent, Map original, Map all, - List fields, @Nullable PackAttributes attributes, - @Nullable TagKey timelines, AttributeReport report) { + List fields, PackParents pack, + @Nullable TimelineRef timelines, AttributeReport report) { + PackAttributes attributes = pack.attributes(); DimensionType value = parent; Map accepted = new LinkedHashMap<>(original); if(all.containsKey(ATTRIBUTES)) { @@ -93,7 +108,7 @@ public final class MinecraftDimensionFactory { for(PackAttributeTable.Field field : fields) { if(attributes.entries().get(field.attribute().key()).isEmpty()) continue; Map trial = new LinkedHashMap<>(accepted); - set(trial, field, attributes); + set(trial, field, pack); if(trial.equals(accepted)) continue; try { value = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, trial, context.ops()); @@ -115,8 +130,8 @@ public final class MinecraftDimensionFactory { return value; } - private static void set(Map fields, PackAttributeTable.Field field, PackAttributes attributes) { - Object value = resolveEncoded(field.attribute(), attributes); + private void set(Map fields, PackAttributeTable.Field field, PackParents pack) { + Object value = resolveEncoded(field.attribute(), pack); if(value == null) { fields.remove(field.name()); } else { @@ -124,15 +139,15 @@ public final class MinecraftDimensionFactory { } } - private static @Nullable Object resolveEncoded(Attribute attribute, PackAttributes attributes) { - T value = attributes.resolvePack(attribute); + private @Nullable Object resolveEncoded(Attribute attribute, PackParents pack) { + T value = pack.resolvePack(handle, 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); + AttributeEntry entry = entry(bound.attribute(), pack, attributes); if(entry != null) entries.put(bound.attribute(), entry); } EnvironmentAttributeMap map = entries.isEmpty() ? parent : maps.toVanilla(parent, entries, false, @@ -140,15 +155,15 @@ public final class MinecraftDimensionFactory { return VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, map, context.ops()); } - private @Nullable AttributeEntry entry(Attribute attribute, AttributeSlots packEntries, PackAttributes attributes) { + private @Nullable AttributeEntry entry(Attribute attribute, PackParents pack, 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))); + return handle.compose(attribute, pack.packEntries().get(attribute), entry.get()) + .orElseGet(() -> AttributeEntry.override(pack.resolvePack(handle, attribute))); } @SuppressWarnings("deprecation") // disableMobGeneration is still what vanilla's settings carry - public GenerationSettings generationSettings(PackParents pack, DimensionType dimension) { + public WorldSettings worldSettings(PackParents pack, DimensionType dimension) { PackAttributes attributes = pack.attributes(); PackAttributeTable table = pack.table(); int minY = dimension.minY(); @@ -157,17 +172,17 @@ public final class MinecraftDimensionFactory { 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) { + seaLevel = intValue(table.seaLevel(), pack, seaLevel); + spawnHeight = intValue(table.spawnHeight(), pack, spawnHeight); + if(table.mobGeneration() != null && resolveEncoded(table.mobGeneration(), pack) instanceof Boolean value) { mobGeneration = value; } } - return new GenerationSettings(new ConstantRange(minY, minY + height), seaLevel, mobGeneration, spawnHeight); + return new WorldSettings(minY, height, seaLevel, mobGeneration, spawnHeight); } - private static int intValue(@Nullable Attribute attribute, PackAttributes attributes, int fallback) { + private int intValue(@Nullable Attribute attribute, PackParents pack, int fallback) { if(attribute == null) return fallback; - return resolveEncoded(attribute, attributes) instanceof Number value ? value.intValue() : fallback; + return resolveEncoded(attribute, pack) instanceof Number value ? value.intValue() : fallback; } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftTimelines.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftTimelines.java similarity index 84% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftTimelines.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftTimelines.java index f512d27e8..e02eaab77 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftTimelines.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftTimelines.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.datafixers.util.Either; import net.minecraft.core.Holder; @@ -24,10 +24,10 @@ 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 java.util.function.Function; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.registry.key.RegistryKey; @@ -38,11 +38,11 @@ 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; +import com.dfsek.terra.world.attribute.platform.AttributeReport; 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"; @@ -177,7 +177,17 @@ public final class MinecraftTimelines { return markers; } - public static @Nullable TagKey tagFor(ConfigPack pack, PackParents parents) { + public static @Nullable TagKey tagFor(Identifier type, ConfigPack pack, PackParents parents) { + Pending pending = pending(pack, parents); + if(pending == null) return null; + TagKey key = TagKey.create(Registries.TIMELINE, type); + synchronized(PENDING) { + PENDING.put(key, pending); + } + return key; + } + + public static @Nullable Pending pending(ConfigPack pack, PackParents parents) { PackAttributes attributes = parents.attributes(); if(attributes == null || attributes.scheduleRefs().isEmpty()) return null; AttributeReport report = parents.report(); @@ -196,12 +206,7 @@ public final class MinecraftTimelines { 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; + return new Pending(report, refs, parents.dimension().timelines()); } /** @@ -220,33 +225,39 @@ public final class MinecraftTimelines { 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)); - }); + PENDING.forEach((key, pending) -> collect.put(key, contents(pending, collect::get, registry))); } } - private static void parentTimelines(HolderSet parent, Map, List>> collect, + public static List> contents(Pending pending, Function, @Nullable List>> tags, + Registry registry) { + 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 = tags.apply(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(), tags, registry, contents); + } + return List.copyOf(contents); + } + + private static void parentTimelines(HolderSet parent, Function, @Nullable List>> tags, Registry registry, Set> contents) { parent.unwrap() - .ifLeft(tag -> contents.addAll(collect.getOrDefault(tag, List.of()))) + .ifLeft(tag -> { + List> members = tags.apply(tag); + if(members != null) contents.addAll(members); + }) .ifRight(direct -> { for(Holder holder : direct) holder.unwrapKey().flatMap(registry::get).ifPresent(contents::add); }); diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackAttributeTable.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/PackAttributeTable.java similarity index 99% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackAttributeTable.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/PackAttributeTable.java index dfafb53e4..724664b4b 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackAttributeTable.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/PackAttributeTable.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.Identifier; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackParents.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/PackParents.java similarity index 71% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackParents.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/PackParents.java index 4c08d03a3..2d80b8d0b 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackParents.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/PackParents.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.biome.Biome; @@ -10,12 +10,18 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.dfsek.terra.api.config.ConfigPack; +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.PackAttributes; +import com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; public final class PackParents { private final ConfigPack pack; private final ResourceKey dimensionKey; + private final boolean dimensionDefaulted; private final DimensionType dimension; private final ResourceKey generationKey; private final NoiseGeneratorSettings generation; @@ -26,11 +32,12 @@ public final class PackParents { private final VanillaParentReader reader; private final Map, AttributeSlots> biomeEntries = new ConcurrentHashMap<>(); - PackParents(ConfigPack pack, ResourceKey dimensionKey, DimensionType dimension, + PackParents(ConfigPack pack, ResourceKey dimensionKey, boolean dimensionDefaulted, DimensionType dimension, ResourceKey generationKey, NoiseGeneratorSettings generation, PackAttributeTable table, AttributeSlots packEntries, @Nullable PackAttributes attributes, AttributeReport report, VanillaParentReader reader) { this.pack = pack; this.dimensionKey = dimensionKey; + this.dimensionDefaulted = dimensionDefaulted; this.dimension = dimension; this.generationKey = generationKey; this.generation = generation; @@ -45,6 +52,10 @@ public final class PackParents { return dimensionKey; } + public boolean dimensionDefaulted() { + return dimensionDefaulted; + } + public DimensionType dimension() { return dimension; } @@ -65,6 +76,14 @@ public final class PackParents { return packEntries; } + /** + * Unlike {@link PackAttributes#resolvePack}, uses these parents, which may be another default's. Allocates. + */ + public @Nullable T resolvePack(AttributeHandle handle, Attribute attribute) { + AttributeEntry own = attributes == null ? null : attributes.entries().get(attribute.key()).orElse(null); + return handle.resolve(attribute, packEntries.get(attribute), own, null); + } + public @Nullable PackAttributes attributes() { return attributes; } diff --git a/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/TimelineRef.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/TimelineRef.java new file mode 100644 index 000000000..f557b3bb3 --- /dev/null +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/TimelineRef.java @@ -0,0 +1,38 @@ +package com.dfsek.terra.minecraft.attribute; + +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.TagKey; +import net.minecraft.world.timeline.Timeline; + +import java.util.List; +import java.util.Objects; + + +public sealed interface TimelineRef { + Object encoded(); + + record Tag(TagKey key) implements TimelineRef { + public Tag { + Objects.requireNonNull(key, "key"); + } + + @Override + public Object encoded() { + return "#" + key.location(); + } + } + + /** + * Every key must be registered where the dimension type is decoded. + */ + record Direct(List> keys) implements TimelineRef { + public Direct { + keys = List.copyOf(keys); + } + + @Override + public Object encoded() { + return keys.stream().map(key -> key.identifier().toString()).toList(); + } + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaAttributeMaps.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaAttributeMaps.java similarity index 98% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaAttributeMaps.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaAttributeMaps.java index 537b490bb..325875891 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaAttributeMaps.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaAttributeMaps.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Codec; import net.minecraft.core.registries.BuiltInRegistries; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaCodecs.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaCodecs.java similarity index 96% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaCodecs.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaCodecs.java index b0cd768c2..f4ceabef6 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaCodecs.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaCodecs.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaContext.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaContext.java similarity index 98% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaContext.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaContext.java index 48bfeac6b..49bbbac85 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaContext.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaContext.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.JavaOps; import net.minecraft.core.Holder; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaIds.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaIds.java similarity index 92% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaIds.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaIds.java index 5bb5f35dc..2e3e32a4c 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaIds.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaIds.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.resources.Identifier; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaParentReader.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaParentReader.java similarity index 97% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaParentReader.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaParentReader.java index e1400c0de..83eeac62f 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaParentReader.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaParentReader.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Codec; import net.minecraft.resources.ResourceKey; @@ -16,6 +16,7 @@ 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.world.attribute.platform.AttributeSlots; final class VanillaParentReader { diff --git a/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/WorldSettings.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/WorldSettings.java new file mode 100644 index 000000000..71c33c4ed --- /dev/null +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/WorldSettings.java @@ -0,0 +1,4 @@ +package com.dfsek.terra.minecraft.attribute; + +public record WorldSettings(int minY, int height, int seaLevel, boolean mobGeneration, int spawnHeight) { +} diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TagUtilTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/BiomeTagsTest.java similarity index 82% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TagUtilTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/BiomeTagsTest.java index 5b2ee4bcb..fd7ab79dd 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TagUtilTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/BiomeTagsTest.java @@ -1,11 +1,10 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.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; @@ -22,17 +21,18 @@ 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 com.dfsek.terra.minecraft.attribute.BiomeTags.PlatformTagSource; +import com.dfsek.terra.world.attribute.platform.AttributeReport; -import static com.dfsek.terra.mod.attribute.VanillaContextTest.copy; +import static com.dfsek.terra.minecraft.attribute.VanillaContextTest.copy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -class TagUtilTest { +class BiomeTagsTest { private static final Identifier TERRA_ID = Identifier.parse("terra:test/biome"); private static final TagKey HAS_SNOW = tag("mypack:has_snow"); + private static final TagKey IS_FOREST = net.minecraft.tags.BiomeTags.IS_FOREST; private final List warnings = new ArrayList<>(); private final AttributeReport report = new AttributeReport("test", warnings::add, m -> { }); @@ -52,7 +52,7 @@ class TagUtilTest { 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))); + BiomeTags.addTerraBiomes(collect, this::lookup, byParent, Map.of(TERRA_ID, new PlatformTagSource(report, "BIOME", keys))); } private static void bindTags(Holder holder, TagKey tag) throws ReflectiveOperationException { @@ -64,24 +64,24 @@ class TagUtilTest { @Test void platformTagsAreAdded() { Holder forest = registry.get(Biomes.FOREST).orElseThrow(); - collect.put(BiomeTags.IS_FOREST, new ArrayList<>(List.of(forest))); + collect.put(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(forest, terra), collect.get(IS_FOREST)); assertEquals(List.of(), warnings); } @Test void inheritedTagsStillApply() throws ReflectiveOperationException { Holder forest = registry.get(Biomes.FOREST).orElseThrow(); - bindTags(forest, BiomeTags.IS_FOREST); + bindTags(forest, 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(terra), collect.get(IS_FOREST)); assertEquals(List.of(), warnings); } diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParentsTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftAttributeParentsTest.java similarity index 77% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParentsTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftAttributeParentsTest.java index fa9558f87..58ba6aff0 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParentsTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftAttributeParentsTest.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Lifecycle; import net.minecraft.core.MappedRegistry; @@ -29,12 +29,14 @@ 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 com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; -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.minecraft.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute; +import static com.dfsek.terra.minecraft.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; @@ -91,39 +93,6 @@ class MinecraftAttributeParentsTest { 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); @@ -153,29 +122,48 @@ class MinecraftAttributeParentsTest { } @Test - void vanillaParentIsUsed() { + void namedParentsAreUsed() { parents.beginLoad(CONTEXT); - FakePackAttributes fake = fake(Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))); - PackParents pack = parents.prepare(PACK, Optional.of(fake), report); + FakePackAttributes dimension = fake(Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))); + PackParents nether = parents.prepare(PACK, Optional.of(dimension), report); + assertEquals(BuiltinDimensionTypes.NETHER, nether.dimensionKey()); + assertSame(value(Registries.DIMENSION_TYPE, BuiltinDimensionTypes.NETHER), nether.dimension()); + assertEquals(AttributeEntry.override(true), parents.packOrNull(dimension, HAS_CEILING)); + assertEquals(AttributeEntry.override(4f), parents.packOrNull(dimension, SKY_LIGHT)); + assertEquals(NoiseGeneratorSettings.OVERWORLD, nether.generationKey()); + assertEquals(AttributeEntry.override(63), parents.packOrNull(dimension, SEA_LEVEL)); - 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)); + FakePackAttributes generation = fake(Map.of("vanilla-generation", RegistryKey.parse("minecraft:nether"))); + PackParents netherGeneration = parents.prepare(PACK, Optional.of(generation), report); + assertEquals(NoiseGeneratorSettings.NETHER, netherGeneration.generationKey()); + assertEquals(AttributeEntry.override(32), parents.packOrNull(generation, SEA_LEVEL)); + assertEquals(BuiltinDimensionTypes.OVERWORLD, netherGeneration.dimensionKey()); assertEquals(List.of(), warnings); } @Test - void generationParentSuppliesWorld() { + void givenDefaultDimension() { parents.beginLoad(CONTEXT); - FakePackAttributes fake = fake(Map.of("vanilla-generation", RegistryKey.parse("minecraft:nether"))); - PackParents pack = parents.prepare(PACK, Optional.of(fake), report); + FakePackAttributes fake = fake(Map.of()); + PackParents nether = parents.prepare(PACK, Optional.of(fake), report, BuiltinDimensionTypes.NETHER); + assertEquals(BuiltinDimensionTypes.NETHER, nether.dimensionKey()); + assertTrue(nether.dimensionDefaulted()); + assertEquals(AttributeEntry.override(true), nether.packEntries().get(HAS_CEILING)); + assertSame(nether, parents.prepare(PACK, Optional.of(fake), report, BuiltinDimensionTypes.NETHER)); - assertEquals(NoiseGeneratorSettings.NETHER, pack.generationKey()); - assertEquals(AttributeEntry.override(32), parents.packOrNull(fake, SEA_LEVEL)); - assertEquals(BuiltinDimensionTypes.OVERWORLD, pack.dimensionKey()); + PackParents overworld = parents.prepare(PACK, Optional.of(fake), report); + assertNotSame(nether, overworld); + assertEquals(BuiltinDimensionTypes.OVERWORLD, overworld.dimensionKey()); + assertTrue(overworld.dimensionDefaulted()); + + ResourceKey missing = ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse("terra:nope")); + assertSame(overworld, parents.prepare(PACK, Optional.of(fake), report, missing)); + + FakePackAttributes named = fake(Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))); + PackParents explicit = parents.prepare(PACK, Optional.of(named), report, BuiltinDimensionTypes.OVERWORLD); + assertEquals(BuiltinDimensionTypes.NETHER, explicit.dimensionKey()); + assertFalse(explicit.dimensionDefaulted()); + assertSame(explicit, parents.prepare(PACK, Optional.of(named), report, BuiltinDimensionTypes.END)); assertEquals(List.of(), warnings); } @@ -184,9 +172,9 @@ class MinecraftAttributeParentsTest { 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); + FakePackAttributes unknownIds = fake(Map.of("vanilla", RegistryKey.parse("minecraft:nope"), + "vanilla-generation", RegistryKey.parse("minecraft:nope"))); + PackParents unknown = parents.prepare(PACK, Optional.of(unknownIds), report); assertEquals(List.of( "Pack \"test\", config \"pack.yml\": \"vanilla\" ignored: invalid ID \"minecraft:The_Nether\": Minecraft IDs use only " @@ -199,6 +187,12 @@ class MinecraftAttributeParentsTest { assertEquals(NoiseGeneratorSettings.OVERWORLD, pack.generationKey()); assertEquals(AttributeEntry.override(false), pack.packEntries().get(HAS_CEILING)); } + + assertSame(unknown, parents.prepare(PACK, Optional.of(unknownIds), report)); + assertEquals(3, warnings.size(), warnings.toString()); + PackParents bare = parents.prepare(PACK, Optional.empty(), report); + assertNotSame(unknown, bare); + assertSame(bare, parents.prepare(PACK, Optional.empty(), report)); } @Test @@ -224,16 +218,16 @@ class MinecraftAttributeParentsTest { } @Test - void biomeOrNullReadsProtoBiome() { + void biomeOrNullReadsEntryHolder() { 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()); + assertSame(AttributeSlots.EMPTY, biome.platform().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); + biome.platform().setParentEntries(desert); assertEquals(AttributeEntry.override(false), parents.biomeOrNull(biome, PRECIPITATION)); PlatformBiome other = () -> "other"; @@ -271,7 +265,7 @@ class MinecraftAttributeParentsTest { 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))); + biome.platform().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"); @@ -305,7 +299,7 @@ class MinecraftAttributeParentsTest { } @Test - void beginLoadDropsOldPacks() { + void beginLoadAndClearPacksDropOldPacks() { parents.beginLoad(CONTEXT); FakePackAttributes fake = fake(Map.of()); PackParents first = parents.prepare(PACK, Optional.of(fake), report); @@ -316,10 +310,23 @@ class MinecraftAttributeParentsTest { PackParents second = parents.prepare(PACK, Optional.of(fake), report); assertNotSame(first, second); assertEquals(AttributeEntry.override(false), parents.packOrNull(fake, HAS_CEILING)); + AttributeSlots desert = parents.biomeEntries(second, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)); parents.clearPacks(); assertSame(CONTEXT, parents.context()); assertNull(parents.packOrNull(fake, HAS_CEILING)); + FakePackAttributes reloaded = fake(Map.of()); + assertNull(parents.packOrNull(reloaded, HAS_CEILING)); + PackParents third = parents.prepare(PACK, Optional.of(reloaded), report); + + assertNotSame(second, third); + assertSame(third, 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(third, 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 @@ -349,28 +356,6 @@ class MinecraftAttributeParentsTest { 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()); @@ -382,19 +367,4 @@ class MinecraftAttributeParentsTest { 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/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftBiomeFactoryTest.java similarity index 83% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactoryTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftBiomeFactoryTest.java index e041dfbc0..206c5784c 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactoryTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftBiomeFactoryTest.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Codec; import com.mojang.serialization.Lifecycle; @@ -13,6 +13,7 @@ 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.BiomeGenerationSettings; import net.minecraft.world.level.biome.BiomeSpecialEffects; import net.minecraft.world.level.biome.Biomes; import org.junit.jupiter.api.Test; @@ -35,14 +36,16 @@ 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 com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; -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 com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.ATTRIBUTES; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.registry; +import static com.dfsek.terra.minecraft.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; @@ -113,7 +116,11 @@ class MinecraftBiomeFactoryTest { 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); + return create(report, parent.getGenerationSettings()); + } + + MinecraftBiomeFactory.Built create(AttributeReport report, BiomeGenerationSettings generation) { + return factory.create(parentKey, parent, biome, pack, report, generation); } } @@ -130,7 +137,7 @@ class MinecraftBiomeFactoryTest { 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)); + biome.platform().setParentEntries(parents.biomeEntries(prepared, parentKey, parent)); return new Fixture(biome, attributes, prepared, new MinecraftBiomeFactory(HANDLE, context), parentKey, parent); } @@ -157,41 +164,33 @@ class MinecraftBiomeFactoryTest { @Test void noEntriesMatchesParent() { Biome plains = biome(Biomes.PLAINS); - MinecraftBiomeFactory.Built built = fixture(Biomes.PLAINS, plains, Map.of()).create(report); + Fixture fixture = fixture(Biomes.PLAINS, plains, Map.of()); + MinecraftBiomeFactory.Built built = fixture.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.biome(), RegistrationInfo.BUILT_IN)); - assertDoesNotThrow(() -> registry.register(key, built, RegistrationInfo.BUILT_IN)); - } + Biome empty = fixture.create(report, BiomeGenerationSettings.EMPTY).biome(); + assertSame(BiomeGenerationSettings.EMPTY, empty.getGenerationSettings()); + assertEquals(plains.climateSettings, empty.climateSettings); + assertEquals(climate(plains), climate(empty)); + assertEquals(effects(plains), effects(empty)); + assertEquals(environment(plains), environment(empty)); - @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()); + biome.platform().setParentEntries(parents.biomeEntries(bare, Biomes.PLAINS, plains)); + MinecraftBiomeFactory.Built withoutAttributes = new MinecraftBiomeFactory(HANDLE, CONTEXT).create(Biomes.PLAINS, plains, biome, + bare, report, plains.getGenerationSettings()); + assertMatches(plains, withoutAttributes.biome()); + assertNotSame(plains, withoutAttributes.biome()); + assertEquals(VillagerType.PLAINS, withoutAttributes.villagerType()); assertEquals(List.of(), warnings); assertEquals(List.of(), debugs); } @@ -270,7 +269,7 @@ class MinecraftBiomeFactoryTest { 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"); + assertEquals(blend, fixture.biome().platform().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(); @@ -288,19 +287,32 @@ class MinecraftBiomeFactoryTest { } @Test - void badEntryIsSkippedAlone() { + void rejectedEntriesAreSkippedAlone() { Biome plains = biome(Biomes.PLAINS); Object oldParticle = Map.of("type", "minecraft:falling_dust", "block_state", Map.of("Name", "minecraft:sand")); - Map, AttributeEntry> entries = entries( + PackAttributeTable.Bound nonPositional = PackAttributeTable.of(REGISTRY).environment().stream() + .filter(b -> !b.vanilla().isPositional() && b.attribute().defaultValue() != null) + .findFirst().orElseThrow(); + String nonPositionalId = nonPositional.attribute().getRegistryKey().toString(); + Map, AttributeEntry> entries = new LinkedHashMap<>(entries( AMBIENT_PARTICLES, List.of(Map.of("particle", oldParticle, "probability", 0.01)), - FOG_COLOR, "#123456"); + FOG_COLOR, "#123456")); + entries.put(nonPositional.attribute(), AttributeEntry.override(nonPositional.attribute().defaultValue())); 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); + List expected = new ArrayList<>(); + for(PackAttributeTable.Bound bound : PackAttributeTable.of(REGISTRY).environment()) { + String id = bound.attribute().getRegistryKey().toString(); + if(id.equals(AMBIENT_PARTICLES) || id.equals(nonPositionalId)) { + expected.add("Pack \"test\", config \"BIOME\": attribute \"" + id + "\" skipped: " + + rejection(id, entries.get(bound.attribute()))); + } + } + assertEquals(expected, warnings); assertEquals(plains.getAttributes().contains(EnvironmentAttributes.AMBIENT_PARTICLES), built.getAttributes().contains(EnvironmentAttributes.AMBIENT_PARTICLES)); + assertFalse(built.getAttributes().contains(nonPositional.vanilla())); assertFogApplied(entries.get(attribute(FOG_COLOR)), built); } @@ -346,25 +358,6 @@ class MinecraftBiomeFactoryTest { 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); @@ -377,7 +370,7 @@ class MinecraftBiomeFactoryTest { 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"); + assertNull(fixture.biome().platform().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)); @@ -415,27 +408,26 @@ class MinecraftBiomeFactoryTest { .create(report).villagerType()); assertEquals(List.of("Pack \"test\", config \"BIOME\": attribute \"terra:biome/villager_type\" skipped: " + "no such villager type \"minecraft:nope\""), warnings); + warnings.clear(); + + Map, AttributeEntry> upper = Map.of(attribute(VILLAGER_TYPE), + AttributeEntry.override(RegistryKey.of("minecraft", "Snow"))); + assertEquals(VillagerType.DESERT, fixture(villagers, PACK, Biomes.DESERT, desert, upper).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()); + warnings.clear(); 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)); + biome.platform().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()); + new MinecraftBiomeFactory(HANDLE, villagers).create(Biomes.DESERT, desert, biome, bare, report, + desert.getGenerationSettings()).villagerType()); + assertEquals(List.of(), warnings); } @Test @@ -454,8 +446,9 @@ class MinecraftBiomeFactoryTest { 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(); + biome.platform().setParentEntries(parents.biomeEntries(again, Biomes.PLAINS, plains)); + Biome second = new MinecraftBiomeFactory(HANDLE, CONTEXT).create(Biomes.PLAINS, plains, biome, again, report, + plains.getGenerationSettings()).biome(); assertEquals(0.3f, second.getBaseTemperature()); assertEquals(climate(first), climate(second)); diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactoryTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftDimensionFactoryTest.java similarity index 65% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactoryTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftDimensionFactoryTest.java index 7f5a03565..1dbe03dea 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactoryTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftDimensionFactoryTest.java @@ -1,6 +1,7 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Lifecycle; +import net.minecraft.core.Holder; import net.minecraft.core.HolderLookup; import net.minecraft.core.HolderSet; import net.minecraft.core.MappedRegistry; @@ -14,6 +15,7 @@ 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 net.minecraft.world.timeline.Timelines; import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -31,20 +33,20 @@ 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 com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; -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 com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.ATTRIBUTES; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.registry; +import static com.dfsek.terra.minecraft.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; @@ -100,39 +102,35 @@ class MinecraftDimensionFactoryTest { return parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report); } + @Test + void typeIdFollowsFilledDimension() { + Identifier plain = Identifier.parse("terra:test"); + Identifier nether = Identifier.parse("terra:test/minecraft/the_nether"); + + assertEquals(plain, MinecraftDimensionFactory.typeId(PACK, BuiltinDimensionTypes.OVERWORLD, false)); + assertEquals(nether, MinecraftDimensionFactory.typeId(PACK, BuiltinDimensionTypes.NETHER, false)); + assertEquals(nether, MinecraftDimensionFactory.typeId(PACK, BuiltinDimensionTypes.NETHER, true)); + assertEquals(Identifier.parse("terra:test/minecraft/overworld"), + MinecraftDimensionFactory.typeId(PACK, BuiltinDimensionTypes.OVERWORLD, true)); + } + @Test void noEntriesMatchesParent() { - DimensionType overworld = dimensionType(BuiltinDimensionTypes.OVERWORLD); - DimensionType built = factory.create(prepare(Map.of()), null); - - assertEquals(overworld, built); - assertNotSame(overworld, built); + assertRegistersBesideParent(BuiltinDimensionTypes.OVERWORLD, factory.create(prepare(Map.of()), null)); + assertRegistersBesideParent(BuiltinDimensionTypes.OVERWORLD, factory.create(bare(), null)); + assertRegistersBesideParent(BuiltinDimensionTypes.NETHER, factory.create( + prepare(PACK, Map.of(), Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))), null)); 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) { + private static void assertRegistersBesideParent(ResourceKey parentKey, DimensionType built) { + DimensionType parent = dimensionType(parentKey); + assertEquals(parent, built, parentKey.toString()); MappedRegistry registry = new MappedRegistry<>(Registries.DIMENSION_TYPE, Lifecycle.stable()); - registry.register(BuiltinDimensionTypes.OVERWORLD, dimensionType(BuiltinDimensionTypes.OVERWORLD), RegistrationInfo.BUILT_IN); + registry.register(parentKey, parent, RegistrationInfo.BUILT_IN); ResourceKey key = ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.fromNamespaceAndPath("terra", "test")); - assertDoesNotThrow(() -> registry.register(key, built, RegistrationInfo.BUILT_IN)); + assertDoesNotThrow(() -> registry.register(key, built, RegistrationInfo.BUILT_IN), parentKey.toString()); } @Test @@ -174,60 +172,29 @@ class MinecraftDimensionFactoryTest { 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"; + String ambientLight = "terra:dimension/ambient_light"; Map, AttributeEntry> entries = new LinkedHashMap<>(); entries.put(attribute(height), AttributeEntry.override(100)); entries.put(attribute(fastLava), decoded(fastLava, true)); - assertInvalidHeightKeepsFastLava(prepare(entries), fastLava); + entries.put(attribute(ambientLight), decoded(ambientLight, 0.5)); + PackParents pack = prepare(entries); + DimensionType built = assertInvalidHeightKeepsFastLava(pack, fastLava); + assertEquals(0.5f, built.ambientLight()); + assertEquals(384, factory.worldSettings(pack, built).height()); warnings.clear(); OpenRegistryImpl> narrow = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE); narrow.register(attribute(height).getRegistryKey(), attribute(height)); narrow.register(attribute(fastLava).getRegistryKey(), attribute(fastLava)); + entries.remove(attribute(ambientLight)); assertInvalidHeightKeepsFastLava(prepare(MinecraftAttributeParentsTest.pack("test", narrow), entries, Map.of()), fastLava); } - private void assertInvalidHeightKeepsFastLava(PackParents pack, String fastLava) { + private DimensionType assertInvalidHeightKeepsFastLava(PackParents pack, String fastLava) { DimensionType built = factory.create(pack, null); assertEquals(List.of("Pack \"test\", config \"pack.yml\": attribute \"terra:dimension/height\" skipped: " @@ -235,37 +202,25 @@ class MinecraftDimensionFactoryTest { assertEquals(384, built.height()); assertTrue(built.attributes().contains(vanilla(fastLava))); assertEquals(true, environment(built.attributes()).get(fastLava)); + return built; } @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() { + void timelinesAreUsed() { 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); + PackParents netherPack = prepare(PACK, Map.of(), Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))); + DimensionType tagged = factory.create(netherPack, new TimelineRef.Tag(tag)); - assertTrue(built.timelines() instanceof HolderSet.Named, String.valueOf(built.timelines())); - assertEquals(Optional.of(tag), built.timelines().unwrapKey()); + assertTrue(tagged.timelines() instanceof HolderSet.Named, String.valueOf(tagged.timelines())); + assertEquals(Optional.of(tag), tagged.timelines().unwrapKey()); + + List> keys = List.of(Timelines.OVERWORLD_DAY, Timelines.MOON); + DimensionType direct = factory.create(prepare(Map.of()), new TimelineRef.Direct(keys)); + + assertTrue(direct.timelines() instanceof HolderSet.Direct, String.valueOf(direct.timelines())); + assertEquals(keys.stream().map(Optional::of).toList(), direct.timelines().stream().map(Holder::unwrapKey).toList()); assertEquals(List.of(), warnings); } @@ -288,7 +243,7 @@ class MinecraftDimensionFactoryTest { .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); + DimensionType built = strict.create(prepare(Map.of()), new TimelineRef.Tag(tag)); assertEquals(1, warnings.size(), String.valueOf(warnings)); String prefix = "Pack \"test\", config \"pack.yml\": \"schedules\" ignored: "; @@ -309,50 +264,29 @@ class MinecraftDimensionFactoryTest { 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())); - + void worldSettingsFromAttributes() { 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)); + PackParents noWorldPack = prepare(MinecraftAttributeParentsTest.pack("noworld", noWorld), Map.of(), Map.of()); + assertNull(noWorldPack.table().seaLevel()); + for(PackParents pack : List.of(noWorldPack, prepare(Map.of()), bare())) { + assertEquals(new WorldSettings(-64, 384, 63, true, 64), factory.worldSettings(pack, factory.create(pack, null))); + } + + Map, AttributeEntry> entries = new LinkedHashMap<>(); + for(Map.Entry entry : Map.of("terra:dimension/min_y", -128, "terra:dimension/height", 512, + "terra:world/sea_level", 40, "terra:world/spawn_height", 90, + "terra:world/mob_generation", false).entrySet()) { + entries.put(attribute(entry.getKey()), decoded(entry.getKey(), entry.getValue())); + } + PackParents pack = prepare(entries); + DimensionType built = factory.create(pack, null); + assertEquals(-128, built.minY()); + assertEquals(512, built.height()); + assertEquals(new WorldSettings(-128, 512, 40, false, 90), factory.worldSettings(pack, built)); assertEquals(List.of(), warnings); } } diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTimelinesTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftTimelinesTest.java similarity index 78% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTimelinesTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftTimelinesTest.java index 0e0200e98..abb520d8b 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTimelinesTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftTimelinesTest.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; @@ -8,7 +8,9 @@ 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.TagLoader.LoadResult; import net.minecraft.tags.TimelineTags; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; import net.minecraft.world.clock.WorldClock; import net.minecraft.world.timeline.Timeline; import net.minecraft.world.timeline.Timelines; @@ -37,15 +39,15 @@ 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 com.dfsek.terra.world.attribute.platform.AttributeReport; -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 com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.registry; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.vanilla; +import static com.dfsek.terra.minecraft.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; @@ -159,42 +161,6 @@ class MinecraftTimelinesTest { @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<>(); @@ -205,11 +171,37 @@ class MinecraftTimelinesTest { Timeline timeline = MinecraftTimelines.create(SEASONS, schedule, 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("Pack \"test\": attribute \"terra:biome/temperature\" is not applied on this platform"), debugs); } + @Test + void badIdsSkipSchedule() { + Map cases = new LinkedHashMap<>(); + cases.put(skipped("mypack:Seasons", "invalid ID \"mypack:Seasons\""), + () -> assertNull(MinecraftTimelines.create(RegistryKey.parse("mypack:Seasons"), skySchedule(), TABLE, HANDLE, CONTEXT, + report))); + cases.put(skipped("mypack:seasons", "invalid ID \"minecraft:Overworld\""), + () -> assertNull(MinecraftTimelines.create(SEASONS, schedule(RegistryKey.parse("minecraft:Overworld"), Map.of()), TABLE, + HANDLE, CONTEXT, report))); + cases.put(skipped("mypack:seasons", "invalid ID \"mypack:Noon\""), + () -> assertNull(MinecraftTimelines.create(SEASONS, schedule(OVERWORLD, Map.of(RegistryKey.parse("mypack:Noon"), + new TimeMarker(6000, false))), + TABLE, HANDLE, CONTEXT, report))); + cases.put(skipped("mypack:seasons", "no such clock \"test:nope\""), + () -> assertNull(MinecraftTimelines.create(SEASONS, schedule(RegistryKey.parse("test:nope"), Map.of()), TABLE, HANDLE, + CONTEXT, report))); + cases.forEach((prefix, create) -> { + warnings.clear(); + assertDoesNotThrow(create::run, prefix); + assertOneWarningStartingWith(prefix); + }); + } + @Test void definitionsAreRegistered() { Load load = Load.create(); @@ -286,28 +278,16 @@ class MinecraftTimelinesTest { @Test void noRefsMeansNoTag() { - assertNull(MinecraftTimelines.tagFor(PACK, prepare(List.of(), Map.of()))); + PackParents empty = prepare(List.of(), Map.of()); + assertNull(MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, empty)); + assertNull(MinecraftTimelines.pending(PACK, empty)); parents.beginLoad(CONTEXT); - assertNull(MinecraftTimelines.tagFor(PACK, parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), - report))); + PackParents bare = parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report); + assertNull(MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, bare)); + assertNull(MinecraftTimelines.pending(PACK, bare)); 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(); @@ -316,7 +296,7 @@ class MinecraftTimelinesTest { 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(TERRA_TEST, MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, pack)); assertEquals(List.of(), warnings); Map, List>> collect = new HashMap<>(); @@ -335,7 +315,7 @@ class MinecraftTimelinesTest { 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)); + assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, pack)); assertOneWarningStartingWith(skipped("#Mypack:Tag", "invalid ID \"Mypack:Tag\"")); warnings.clear(); @@ -351,6 +331,41 @@ class MinecraftTimelinesTest { warnings); } + @Test + void tagPerDimensionType() { + Load load = Load.create(); + Holder.Reference day = load.timeline(Timelines.OVERWORLD_DAY); + Holder.Reference moon = load.timeline(Timelines.MOON); + PackParents overworld = prepare(List.of(id("minecraft:nope")), Map.of()); + PackParents nether = parents.prepare(PACK, Optional.ofNullable(overworld.attributes()), report, BuiltinDimensionTypes.NETHER); + TagKey netherTag = TagKey.create(Registries.TIMELINE, Identifier.parse("terra:test/minecraft/the_nether")); + assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, overworld)); + assertEquals(netherTag, MinecraftTimelines.tagFor(netherTag.location(), PACK, nether)); + + 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)); + assertFalse(collect.get(netherTag).contains(day), "the nether has no day cycle: " + collect.get(netherTag)); + } + + @Test + void pendingSkipsBadRefs() { + Load load = Load.create(); + PackParents pack = prepare(List.of(tag("Mypack", "Tag"), id("minecraft:day")), Map.of()); + + MinecraftTimelines.Pending pending = assertDoesNotThrow(() -> MinecraftTimelines.pending(PACK, pack)); + + assertNotNull(pending); + assertEquals(List.of(com.mojang.datafixers.util.Either.left(Identifier.parse("minecraft:day"))), pending.refs()); + assertOneWarningStartingWith(skipped("#Mypack:Tag", "invalid ID \"Mypack:Tag\"")); + Map, List>> collect = new HashMap<>(); + MinecraftTimelines.fillTags(collect, load.timelines()); + assertEquals(Map.of(), collect, "nothing recorded"); + assertEquals(1, warnings.size()); + } + @Test void tagRefillsOnReload() { Load load = Load.create(); @@ -361,7 +376,7 @@ class MinecraftTimelinesTest { Map.of(SEASONS, skySchedule())); MinecraftTimelines.register(PACK, pack, load.timelines(), HANDLE, load.context()); - TagKey tag = MinecraftTimelines.tagFor(PACK, pack); + TagKey tag = MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, pack); assertEquals(TERRA_TEST, tag); HolderSet.Named dimensionTimelines = load.context().ops().getter(Registries.TIMELINE).orElseThrow().get(tag) .orElseThrow(); @@ -372,7 +387,7 @@ class MinecraftTimelinesTest { Timeline.validateRegistry(timelines, errors); assertEquals(Map.of(), errors); - TagUtil.registerTimelineTags(timelines); + 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()); @@ -384,7 +399,7 @@ class MinecraftTimelinesTest { 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); + registerTimelineTags(timelines); parents.endPackReload(); assertSame(dimensionTimelines, timelines.get(TERRA_TEST).orElseThrow()); assertEquals(List.of(seasons, day, moon), dimensionTimelines.stream().toList()); @@ -392,6 +407,13 @@ class MinecraftTimelinesTest { assertEquals(List.of(), warnings); } + private static void registerTimelineTags(Registry registry) { + Map, List>> collect = new HashMap<>(); + registry.getTags().forEach(tag -> collect.put(tag.key(), new ArrayList<>(tag.stream().toList()))); + MinecraftTimelines.fillTags(collect, registry); + registry.prepareTagReload(new LoadResult<>(registry.key(), collect)).apply(); + } + private static Map frozenTags(MappedRegistry registry) { try { java.lang.reflect.Field field = MappedRegistry.class.getDeclaredField("frozenTags"); @@ -406,7 +428,7 @@ class MinecraftTimelinesTest { void beginLoadDropsPendingTags() { Load load = Load.create(); PackParents pack = prepare(List.of(id("minecraft:day")), Map.of()); - assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(PACK, pack)); + assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, pack)); parents.beginLoad(CONTEXT); Map, List>> collect = new HashMap<>(); diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaCodecHarnessTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaCodecHarnessTest.java similarity index 93% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaCodecHarnessTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaCodecHarnessTest.java index 26e85d2c4..679c63f7e 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaCodecHarnessTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaCodecHarnessTest.java @@ -1,16 +1,13 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.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; @@ -44,12 +41,12 @@ 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 com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.LOOKUP; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute; +import static com.dfsek.terra.minecraft.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; @@ -91,15 +88,6 @@ class VanillaCodecHarnessTest { 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); diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaContextTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaContextTest.java similarity index 96% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaContextTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaContextTest.java index 71ab528c7..416e2ad1d 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaContextTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaContextTest.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Lifecycle; import net.minecraft.core.Holder; @@ -23,8 +23,8 @@ 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 com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.minecraft.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; diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaParentReaderTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaParentReaderTest.java similarity index 89% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaParentReaderTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaParentReaderTest.java index b4f8c6072..3d2089a7b 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaParentReaderTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaParentReaderTest.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Codec; import net.minecraft.core.Holder; @@ -38,19 +38,20 @@ 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 com.dfsek.terra.world.attribute.platform.AttributeSlots; -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 com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.ATTRIBUTES; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute; +import static com.dfsek.terra.minecraft.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.assertInstanceOf; 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; import static org.junit.jupiter.api.Assertions.fail; @@ -111,8 +112,7 @@ class VanillaParentReaderTest { bound.add(b.vanilla()); } assertEquals(Set.copyOf(BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.stream().toList()), bound); - assertEquals(51, bound.size()); - assertEquals(51, TABLE.environment().size()); + assertEquals(bound.size(), TABLE.environment().size(), "each vanilla attribute is bound once"); assertEquals(List.of(), TABLE.unapplied()); assertEquals(4, TABLE.climate().size()); @@ -140,22 +140,13 @@ class VanillaParentReaderTest { @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()); + assertSame(PackAttributeTable.EMPTY, table); 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 @@ -164,7 +155,7 @@ class VanillaParentReaderTest { .build(); PackAttributeTable table = PackAttributeTable.of(registry(custom)); assertEquals(List.of(custom), table.unapplied()); - assertEquals(51, table.environment().size()); + assertEquals(TABLE.environment(), table.environment()); assertNull(READER.biome(Biomes.PLAINS, biome(Biomes.PLAINS), TABLE, FAIL).get(custom)); } @@ -200,17 +191,14 @@ class VanillaParentReaderTest { @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)); + AttributeEntry old = HANDLE.decodeEntry(particles, List.of(Map.of("particle", oldParticle, "probability", 0.01)), PLAIN); List skipped = new ArrayList<>(); - EnvironmentAttributeMap rejected = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, entries, true, + EnvironmentAttributeMap rejected = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(particles, old), true, (attribute, reason) -> { assertEquals(particles, attribute); skipped.add(reason); @@ -218,7 +206,6 @@ class VanillaParentReaderTest { 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); @@ -240,7 +227,7 @@ class VanillaParentReaderTest { } @Test - void readsBiomeFields() { + void readsBiomeFieldsAndEnvironment() { Attribute temperature = attribute("terra:biome/temperature"); Attribute precipitation = attribute("terra:biome/has_precipitation"); Attribute villager = attribute("terra:biome/villager_type"); @@ -261,19 +248,14 @@ class VanillaParentReaderTest { 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()); + if(biome(Biomes.PLAINS).getAttributes().contains(b.vanilla())) { + assertNotNull(plains.get(b.attribute()), b.attribute().getRegistryKey().toString()); present++; } else { - assertNull(slots.get(b.attribute()), b.attribute().getRegistryKey().toString()); + assertNull(plains.get(b.attribute()), b.attribute().getRegistryKey().toString()); } } assertTrue(present > 0); diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/FakePackAttributes.java b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/FakePackAttributes.java similarity index 91% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/FakePackAttributes.java rename to platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/FakePackAttributes.java index aa200aff6..cebab7087 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/FakePackAttributes.java +++ b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/FakePackAttributes.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import org.jetbrains.annotations.Nullable; @@ -22,7 +22,7 @@ import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule; import com.dfsek.terra.api.world.biome.Biome; -final class FakePackAttributes implements PackAttributes { +public final class FakePackAttributes implements PackAttributes { private static final AttributeEntry UNREAD = AttributeEntry.override(new Object()); private final AttributeHandle handle; @@ -35,12 +35,12 @@ final class FakePackAttributes implements PackAttributes { private final AttributeEntry[] packSlots; private final IdentityHashMap[]> biomeSlots = new IdentityHashMap<>(); - FakePackAttributes(AttributeHandle handle, AttributeParents platformParents, AttributeMap pack, Map parents, + public 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, + public FakePackAttributes(AttributeHandle handle, AttributeParents platformParents, AttributeMap pack, Map parents, Map biomes, List> scheduleRefs, Map scheduleDefinitions) { this.handle = handle; diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTestSupport.java b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/MinecraftTestSupport.java similarity index 74% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTestSupport.java rename to platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/MinecraftTestSupport.java index 4cba2c23f..944dd46e4 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTestSupport.java +++ b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/MinecraftTestSupport.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.SharedConstants; import net.minecraft.core.HolderLookup; @@ -24,20 +24,20 @@ import com.dfsek.terra.registry.OpenRegistryImpl; import com.dfsek.terra.world.attribute.AttributeHandleImpl; -final class MinecraftTestSupport { +public 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); + public static final HolderLookup.Provider REGISTRIES = VanillaRegistries.createWorldLookup(); + public static final VanillaContext CONTEXT = VanillaContext.of(REGISTRIES, key -> null); + public static final AttributeHandle HANDLE = new AttributeHandleImpl(); + public static final List> ATTRIBUTES = MinecraftAttributeTable.create(HANDLE); private static final Registry> TABLE = registry(); - static final AttributeLookup LOOKUP = key -> { + public static final AttributeLookup LOOKUP = key -> { RegistryKey id; try { id = RegistryKey.parseNamespaced(key); @@ -49,11 +49,11 @@ final class MinecraftTestSupport { private MinecraftTestSupport() { } - static List> loadContext(net.minecraft.core.Registry.PendingTags... pending) { + public static List> loadContext(net.minecraft.core.Registry.PendingTags... pending) { return TagLoader.buildUpdatedLookups(RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY), List.of(pending)); } - static Registry> registry(Attribute... extra) { + public 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); @@ -61,12 +61,12 @@ final class MinecraftTestSupport { } @SuppressWarnings("unchecked") - static Attribute attribute(String id) { + public 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) { + public 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/TestBiome.java b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/TestBiome.java similarity index 72% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TestBiome.java rename to platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/TestBiome.java index 32eb2c046..076c973e7 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TestBiome.java +++ b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/TestBiome.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.resources.Identifier; @@ -7,27 +7,26 @@ 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 { +public 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)); + public TestBiome(String id, int intId, Identifier parent) { + this(id, intId, new TestPlatformBiome(parent)); } - TestBiome(String id, int intId, PlatformBiome platformBiome) { + public TestBiome(String id, int intId, PlatformBiome platformBiome) { this.id = id; this.intId = intId; this.platformBiome = platformBiome; } - ProtoPlatformBiome proto() { - return (ProtoPlatformBiome) platformBiome; + public TestPlatformBiome platform() { + return (TestPlatformBiome) platformBiome; } @Override diff --git a/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/TestPlatformBiome.java b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/TestPlatformBiome.java new file mode 100644 index 000000000..3c3a0279f --- /dev/null +++ b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/TestPlatformBiome.java @@ -0,0 +1,37 @@ +package com.dfsek.terra.minecraft.attribute; + +import net.minecraft.resources.Identifier; + +import java.util.Objects; + +import com.dfsek.terra.api.world.biome.PlatformBiome; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; +import com.dfsek.terra.world.attribute.platform.ParentEntryHolder; + + +public final class TestPlatformBiome implements PlatformBiome, ParentEntryHolder { + private final Identifier parent; + private AttributeSlots parentEntries = AttributeSlots.EMPTY; + + public TestPlatformBiome(Identifier parent) { + this.parent = Objects.requireNonNull(parent); + } + + public Identifier parent() { + return parent; + } + + @Override + public Identifier getHandle() { + return parent; + } + + @Override + public AttributeSlots parentEntries() { + return parentEntries; + } + + public void setParentEntries(AttributeSlots parentEntries) { + this.parentEntries = Objects.requireNonNull(parentEntries); + } +} diff --git a/platforms/mixin-common/build.gradle.kts b/platforms/mixin-common/build.gradle.kts index 2d3848be4..9c725ba39 100644 --- a/platforms/mixin-common/build.gradle.kts +++ b/platforms/mixin-common/build.gradle.kts @@ -12,10 +12,9 @@ dependencies { compileOnly("net.fabricmc:sponge-mixin:${Versions.Mod.mixin}") - minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") + api(project(":platforms:minecraft-common")) { isTransitive = false } - // Tests only: the addon ships as its own jar. - testImplementation(project(":common:addons:minecraft-attributes")) + minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") } architectury { 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 503eb9c4a..ebd0fb5c0 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 @@ -24,7 +24,7 @@ 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.attribute.MinecraftAttributeParents; +import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents; import com.dfsek.terra.mod.config.ProtoPlatformBiome; import com.dfsek.terra.mod.handle.MinecraftItemHandle; import com.dfsek.terra.mod.handle.MinecraftWorldHandle; @@ -47,7 +47,7 @@ public abstract class ModPlatform extends AbstractPlatform { getRawConfigRegistry() .forEach(pack -> { boolean packInMetapack = configPacksInMetaPack.contains(pack.getID()); - PresetUtil.createDefault(pack, this, packInMetapack, packInMetapack).apply(registerFunction); + PresetUtil.createDefault(pack, this, packInMetapack).apply(registerFunction); }); } 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 e2bc1703f..7ad853618 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,11 +26,12 @@ 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; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; +import com.dfsek.terra.world.attribute.platform.ParentEntryHolder; -public class ProtoPlatformBiome implements PlatformBiome { +public class ProtoPlatformBiome implements PlatformBiome, ParentEntryHolder { private final Identifier identifier; private Holder delegate; @@ -59,6 +60,7 @@ public class ProtoPlatformBiome implements PlatformBiome { this.delegate = Objects.requireNonNull(delegate); } + @Override public AttributeSlots parentEntries() { return parentEntries; } 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 54079e095..591ae8675 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 @@ -8,13 +8,14 @@ import java.util.Locale; import java.util.Map; import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.minecraft.attribute.BiomeTags.PlatformTagSource; public class BiomeUtil { public static final Map> TERRA_BIOME_MAP = new HashMap<>(); - public static final Map + public static final Map TERRA_BIOME_PLATFORM_TAGS = new HashMap<>(); public static String createBiomeID(ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey biomeID) { @@ -26,7 +27,7 @@ public class BiomeUtil { return Map.copyOf(TERRA_BIOME_MAP); } - public static Map getTerraBiomePlatformTags() { + 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/PresetUtil.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/PresetUtil.java index 8fe0a3307..58905e0a9 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 @@ -5,6 +5,7 @@ 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.world.level.biome.Biome; import net.minecraft.world.level.biome.MultiNoiseBiomeSource; import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterList; @@ -17,6 +18,7 @@ import net.minecraft.world.level.dimension.LevelStem; import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; import net.minecraft.world.level.levelgen.presets.WorldPreset; +import net.minecraft.world.timeline.Timeline; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,24 +30,26 @@ 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.minecraft.attribute.MinecraftAttributeParents; +import com.dfsek.terra.minecraft.attribute.MinecraftDimensionFactory; +import com.dfsek.terra.minecraft.attribute.MinecraftTimelines; +import com.dfsek.terra.minecraft.attribute.PackParents; +import com.dfsek.terra.minecraft.attribute.TimelineRef; +import com.dfsek.terra.minecraft.attribute.VanillaContext; +import com.dfsek.terra.minecraft.attribute.WorldSettings; 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.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; +import com.dfsek.terra.world.attribute.platform.AttributeReport; public class PresetUtil { private static final Logger LOGGER = LoggerFactory.getLogger(PresetUtil.class); private static final List> PRESETS = new ArrayList<>(); - public static Pair createDefault(ConfigPack pack, ModPlatform platform, boolean extended, - boolean packInMetapack) { + public static Pair createDefault(ConfigPack pack, ModPlatform platform, boolean extended) { Registry dimensionTypeRegistry = platform.dimensionTypeRegistry(); Registry chunkGeneratorSettingsRegistry = platform.chunkGeneratorSettingsRegistry(); Registry multiNoiseBiomeSourceParameterLists = @@ -60,7 +64,7 @@ public class PresetUtil { HashMap, LevelStem> dimensionMap = new HashMap<>(); - insertCustom(platform, "minecraft:overworld", pack, dimensionTypeRegistry, dimensionMap, packInMetapack); + insertCustom(platform, "minecraft:overworld", pack, dimensionTypeRegistry, dimensionMap); insertDefaults(dimensionTypeRegistry, chunkGeneratorSettingsRegistry, multiNoiseBiomeSourceParameterLists, platform.biomeRegistry(), dimensionMap); @@ -85,7 +89,7 @@ public class PresetUtil { HashMap, LevelStem> dimensionMap = new HashMap<>(); metaPack.packs().forEach((key, pack) -> { - insertCustom(platform, key, pack, dimensionTypeRegistry, dimensionMap, false); + insertCustom(platform, key, pack, dimensionTypeRegistry, dimensionMap); }); insertDefaults(dimensionTypeRegistry, chunkGeneratorSettingsRegistry, multiNoiseBiomeSourceParameterLists, platform.biomeRegistry(), @@ -97,33 +101,37 @@ public class PresetUtil { } private static void insertCustom(ModPlatform platform, String key, ConfigPack pack, Registry dimensionTypeRegistry, - HashMap, LevelStem> dimensionMap, boolean packInMetapack) { + HashMap, LevelStem> dimensionMap) { Identifier demensionIdentifier = Identifier.parse(key); 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)); + ResourceKey filled = MinecraftUtil.registerDimensionTypeKey(demensionIdentifier); + if(context.dimensionTypes().get(filled).isEmpty()) filled = BuiltinDimensionTypes.OVERWORLD; + PackParents packParents = parents.prepare(pack, platform.getAttributeHandle().pack(pack), AttributeReport.logging(pack), filled); MinecraftDimensionFactory factory = new MinecraftDimensionFactory(platform.getAttributeHandle(), context); - Identifier dimensionTypeID = Identifier.fromNamespaceAndPath("terra", pack.getID().toLowerCase(Locale.ROOT)); + Identifier dimensionTypeID = MinecraftDimensionFactory.typeId(pack, filled, false); + ResourceKey dimensionTypeRegistryKey = MinecraftUtil.registerDimensionTypeKey(dimensionTypeID); DimensionType dimensionType; - if(!packInMetapack) { - dimensionType = factory.create(packParents, MinecraftTimelines.tagFor(pack, packParents)); - ResourceKey dimensionTypeRegistryKey = MinecraftUtil.registerDimensionTypeKey( - dimensionTypeID); - - Registry.registerForHolder(dimensionTypeRegistry, dimensionTypeRegistryKey, dimensionType); + if(dimensionTypeRegistry.containsKey(dimensionTypeRegistryKey)) { + // Relies on Fabric API binding values at register; vanilla binds them at the freeze. + dimensionType = dimensionTypeRegistry.getValue(dimensionTypeRegistryKey); } else { - dimensionType = dimensionTypeRegistry.getValue(dimensionTypeID); + TagKey timelines = MinecraftTimelines.tagFor(dimensionTypeID, pack, packParents); + dimensionType = factory.create(packParents, timelines == null ? null : new TimelineRef.Tag(timelines)); + Registry.registerForHolder(dimensionTypeRegistry, dimensionTypeRegistryKey, dimensionType); } Holder dimensionTypeRegistryEntry = dimensionTypeRegistry.wrapAsHolder(dimensionType); TerraBiomeSource biomeSource = new TerraBiomeSource(pack); - GenerationSettings generatorSettings = factory.generationSettings(packParents, dimensionType); + WorldSettings s = factory.worldSettings(packParents, dimensionType); + GenerationSettings generatorSettings = new GenerationSettings(new ConstantRange(s.minY(), s.minY() + s.height()), + s.seaLevel(), s.mobGeneration(), s.spawnHeight()); 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 bd65a7045..8c6ab0cb1 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,8 +2,6 @@ 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; @@ -15,18 +13,12 @@ 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; +import com.dfsek.terra.minecraft.attribute.BiomeTags; +import com.dfsek.terra.minecraft.attribute.MinecraftTimelines; public final class TagUtil { @@ -77,13 +69,11 @@ public final class TagUtil { 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); - addTerraBiomes(collect, id -> MinecraftUtil.getEntry(registry, id), BiomeUtil.getTerraBiomeMap(), + BiomeTags.addTerraBiomes(collect, id -> MinecraftUtil.getEntry(registry, id), BiomeUtil.getTerraBiomeMap(), BiomeUtil.getTerraBiomePlatformTags()); registry.prepareTagReload(new LoadResult<>(registry.key(), collect)).apply(); @@ -95,44 +85,4 @@ 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-lifecycle/build.gradle.kts b/platforms/mixin-lifecycle/build.gradle.kts index cca5e654a..7a3cae4c3 100644 --- a/platforms/mixin-lifecycle/build.gradle.kts +++ b/platforms/mixin-lifecycle/build.gradle.kts @@ -10,6 +10,7 @@ dependencies { compileOnly("io.github.llamalad7:mixinextras-common:${Versions.Mod.mixinExtras}") implementation(project(":platforms:mixin-common")) { isTransitive = false } + implementation(project(":platforms:minecraft-common")) { isTransitive = false } minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") 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 a366f43a0..cee0bbcdf 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 @@ -33,9 +33,9 @@ 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.minecraft.attribute.VanillaContext; 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; 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 bd102d54c..8e0c8151c 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 @@ -11,18 +11,18 @@ import java.util.ArrayList; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.minecraft.attribute.BiomeTags.PlatformTagSource; +import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents; +import com.dfsek.terra.minecraft.attribute.MinecraftBiomeFactory; +import com.dfsek.terra.minecraft.attribute.PackParents; 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.mixin.access.VillagerTypeAccessor; import com.dfsek.terra.mod.util.BiomeUtil; import com.dfsek.terra.mod.util.MinecraftUtil; -import com.dfsek.terra.mod.util.TagUtil; +import com.dfsek.terra.world.attribute.platform.AttributeReport; public final class LifecycleBiomeUtil { @@ -81,14 +81,15 @@ public final class LifecycleBiomeUtil { // 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()); + MinecraftBiomeFactory.Built built = factory.create(vanilla, vanillaBiome, biome, packParents, packParents.report(), + vanillaBiome.getGenerationSettings()); 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())); + new 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 ded62698d..3409ca484 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 @@ -11,14 +11,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent; +import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents; +import com.dfsek.terra.minecraft.attribute.MinecraftBiomeFactory; +import com.dfsek.terra.minecraft.attribute.MinecraftTimelines; +import com.dfsek.terra.minecraft.attribute.PackParents; +import com.dfsek.terra.minecraft.attribute.VanillaContext; 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; +import com.dfsek.terra.world.attribute.platform.AttributeReport; public final class LifecycleUtil {