From 6347071976127897c41e6e728804ae86fc42f381 Mon Sep 17 00:00:00 2001 From: sciwhiz12 Date: Sun, 17 Apr 2022 22:12:05 +0000 Subject: [PATCH] Add event for hooking into StructuresBecomeConfiguredFix Fixes #8505 Pass-through unknown structure IDs with "unknown." prefix This avoids the fixer throwing an exception due to the unknown structure, which causes the chunk data to be dropped (and freshly regenerated later). The deserializer logs and ignores the unknown structure ID, avoiding full chunk data loss. --- .../StructuresBecomeConfiguredFix.java.patch | 13 +++ .../net/minecraftforge/common/ForgeHooks.java | 41 +++++-- .../RegisterStructureConversionsEvent.java | 105 ++++++++++++++++++ .../resources/META-INF/accesstransformer.cfg | 1 + 4 files changed, 151 insertions(+), 9 deletions(-) create mode 100644 patches/minecraft/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java.patch create mode 100644 src/main/java/net/minecraftforge/event/RegisterStructureConversionsEvent.java diff --git a/patches/minecraft/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java.patch b/patches/minecraft/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java.patch new file mode 100644 index 0000000000..8d10f012ea --- /dev/null +++ b/patches/minecraft/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java.patch @@ -0,0 +1,13 @@ +--- a/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java ++++ b/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java +@@ -93,7 +_,10 @@ + private Dynamic m_207723_(Pair, Dynamic> p_207724_, Dynamic p_207725_) { + String s = p_207724_.getFirst().asString("UNKNOWN").toLowerCase(Locale.ROOT); + StructuresBecomeConfiguredFix.Conversion structuresbecomeconfiguredfix$conversion = f_207676_.get(s); ++ if (structuresbecomeconfiguredfix$conversion == null) structuresbecomeconfiguredfix$conversion = net.minecraftforge.common.ForgeHooks.getStructureConversion(s); // Forge: hook for mods to register conversions through RegisterStructureConversionsEvent + if (structuresbecomeconfiguredfix$conversion == null) { ++ if (net.minecraftforge.common.ForgeHooks.checkStructureNamespace(s)) return p_207724_.getSecond().createString(s); // Forge: pass-through structure IDs which have a non-"minecraft" namespace ++ if (true) return p_207724_.getSecond().createString("unknown." + s); // Forge: Pass-through with "unknown." prefix, so deserializer logs and ignores rather than fixer throwing an exception and dropping chunk data + throw new IllegalStateException("Found unknown structure: " + s); + } else { + Dynamic dynamic = p_207724_.getSecond(); diff --git a/src/main/java/net/minecraftforge/common/ForgeHooks.java b/src/main/java/net/minecraftforge/common/ForgeHooks.java index 335f114ae7..8eab42e501 100644 --- a/src/main/java/net/minecraftforge/common/ForgeHooks.java +++ b/src/main/java/net/minecraftforge/common/ForgeHooks.java @@ -18,7 +18,6 @@ import java.util.Optional; import java.util.Objects; import java.util.Set; import java.util.Map.Entry; -import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Matcher; @@ -26,6 +25,7 @@ import java.util.regex.Pattern; import com.google.common.base.Strings; import com.google.common.base.Suppliers; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Queues; @@ -35,7 +35,6 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.mojang.datafixers.kinds.App; -import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Codec; import com.mojang.serialization.Lifecycle; import com.mojang.serialization.codecs.RecordCodecBuilder; @@ -50,6 +49,7 @@ import net.minecraft.advancements.Advancement; import net.minecraft.core.*; import net.minecraft.tags.BlockTags; import net.minecraft.tags.TagKey; +import net.minecraft.util.datafix.fixes.StructuresBecomeConfiguredFix; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.entity.ai.attributes.Attribute; import net.minecraft.world.entity.ai.attributes.AttributeModifier; @@ -97,10 +97,7 @@ import net.minecraft.stats.Stats; import net.minecraft.world.phys.Vec3; import net.minecraft.world.*; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; import net.minecraft.world.level.levelgen.WorldGenSettings; -import net.minecraft.world.level.levelgen.feature.StructureFeature; import net.minecraft.world.level.BaseSpawner; import net.minecraft.world.level.block.entity.FurnaceBlockEntity; import net.minecraft.world.level.block.entity.BlockEntity; @@ -118,6 +115,7 @@ import net.minecraftforge.common.loot.IGlobalLootModifier; import net.minecraftforge.common.loot.LootModifierManager; import net.minecraftforge.common.loot.LootTableIdCondition; import net.minecraftforge.common.util.BlockSnapshot; +import net.minecraftforge.common.util.Lazy; import net.minecraftforge.common.util.MavenVersionStringHelper; import net.minecraftforge.common.world.BiomeGenerationSettingsBuilder; import net.minecraftforge.common.world.ForgeWorldPreset; @@ -127,6 +125,7 @@ import net.minecraftforge.event.DifficultyChangeEvent; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.ItemAttributeModifierEvent; import net.minecraftforge.event.ServerChatEvent; +import net.minecraftforge.event.RegisterStructureConversionsEvent; import net.minecraftforge.event.VanillaGameEvent; import net.minecraftforge.event.entity.EntityAttributeCreationEvent; import net.minecraftforge.event.entity.EntityAttributeModificationEvent; @@ -1319,7 +1318,7 @@ public class ForgeHooks boolean generateBonusChest = wgs.generateBonusChest(); Registry originalRegistry = wgs.dimensions(); Optional legacyCustomOptions = wgs.legacyCustomOptions; - + // make a copy of the dimension registry; for dimensions that specify that they should use the server seed instead // of the hardcoded json seed, recreate them with the correct seed MappedRegistry seededRegistry = new MappedRegistry<>(Registry.LEVEL_STEM_REGISTRY, Lifecycle.experimental(), (Function>)null); @@ -1336,10 +1335,10 @@ public class ForgeHooks seededRegistry.register(key, dimension, originalRegistry.lifecycle(dimension)); } } - + return new WorldGenSettings(seed, generateFeatures, generateBonusChest, seededRegistry, legacyCustomOptions); } - + /** Called in the LevelStem codec builder to add extra fields to dimension jsons **/ public static App, LevelStem> expandLevelStemCodec(RecordCodecBuilder.Instance builder, Supplier, LevelStem>> vanillaFieldsSupplier) { @@ -1452,7 +1451,7 @@ public class ForgeHooks return Lifecycle.deprecated(Integer.parseInt(lifecycle.substring(lifecycle.indexOf('=') + 1))); throw new IllegalArgumentException("Unknown lifecycle."); } - + public static void saveMobEffect(CompoundTag nbt, String key, MobEffect effect) { var registryName = effect.getRegistryName(); @@ -1485,4 +1484,28 @@ public class ForgeHooks return mask.isEnderMask(player, enderMan) || MinecraftForge.EVENT_BUS.post(new EnderManAngerEvent(enderMan, player)); } + private static final Lazy> FORGE_CONVERSION_MAP = Lazy.concurrentOf(() -> { + Map map = new HashMap<>(); + MinecraftForge.EVENT_BUS.post(new RegisterStructureConversionsEvent(map)); + return ImmutableMap.copyOf(map); + }); + + // DO NOT CALL from within RegisterStructureConversionsEvent, otherwise you'll get a deadlock + /** + * @hidden For internal use only. + */ + @Nullable + public static StructuresBecomeConfiguredFix.Conversion getStructureConversion(String originalBiome) + { + return FORGE_CONVERSION_MAP.get().get(originalBiome); + } + + /** + * @hidden For internal use only. + */ + public static boolean checkStructureNamespace(String biome) + { + @Nullable ResourceLocation biomeLocation = ResourceLocation.tryParse(biome); + return biomeLocation != null && !biomeLocation.getNamespace().equals(ResourceLocation.DEFAULT_NAMESPACE); + } } diff --git a/src/main/java/net/minecraftforge/event/RegisterStructureConversionsEvent.java b/src/main/java/net/minecraftforge/event/RegisterStructureConversionsEvent.java new file mode 100644 index 0000000000..2844136219 --- /dev/null +++ b/src/main/java/net/minecraftforge/event/RegisterStructureConversionsEvent.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.event; + +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.datafix.fixes.StructuresBecomeConfiguredFix; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.eventbus.api.Cancelable; +import net.minecraftforge.eventbus.api.Event; + +import java.util.Locale; +import java.util.Map; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Fired for registering structure conversions for pre-1.18.2 worlds. This is used by {@link StructuresBecomeConfiguredFix} + * for converting old structure IDs in pre-1.18.2 worlds to their new equivalents, which can be differentiated per biome. + * + *

By default, structures whose old ID has a namespace which is not equal to {@value ResourceLocation#DEFAULT_NAMESPACE} + * will be assumed to belong to a modded structure and will be used as the new ID. Mods may choose to register structure + * conversions for their structures, if they wish to override this default behavior.

+ * + *

This event will only fire if {@link StructuresBecomeConfiguredFix} is used, as a result of converting a + * pre-1.18.2 world to the current version.

+ * + *

This event is not {@linkplain Cancelable cancelable}, and does not {@linkplain HasResult have a result}.

+ * + *

This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, + * only on the {@linkplain net.minecraftforge.fml.LogicalSide#SERVER logical server}.

+ * + * @see StructuresBecomeConfiguredFix + * @see #register(String, StructuresBecomeConfiguredFix.Conversion) + */ +public class RegisterStructureConversionsEvent extends Event +{ + private final Map map; + + /** + * @hidden For internal use only. + */ + public RegisterStructureConversionsEvent(Map map) + { + this.map = map; + } + + /** + * Registers a conversion for a structure. + * + *

A structure conversion can be of two kinds:

+ *
    + *
  • A trivial conversion, created using {@link StructuresBecomeConfiguredFix.Conversion#trivial(String)}, + * contains only the new structure ID and simply converts all mentions of the old structure ID to the new + * structure ID.
  • + *
  • A biome-mapped conversion, created using {@link + * StructuresBecomeConfiguredFix.Conversion#biomeMapped(Map, String)}, contains a fallback structure ID, and a + * biome-specific conversion map. Each entry in the map is composed of a list of biome IDs and the new structure + * ID. + * + *

    If a structure is in a biome which exists in the map, the + * structure ID in the corresponding entry is used as the new structure ID. If there is no such biome found, + * the new structure ID will be the fallback structure ID.

    + * + *

    For example, the following registers a biome-mapped conversion for {@code exampleStructure} with the + * following logic:

    + *
      + *
    • If the structure is within either a {@code minecraft:desert} or a {@code minecraft:jungle} biome, + * it is mapped to {@code examplemod:deserted_structure}.
    • + *
    • If the structure is within a {@code minecraft:ocean} biome, it is mapped to + * {@code examplemod:flooded_structure}.
    • + *
    • Otherwise, the structure is mapped to {@code examplemod:structure}.
    • + *
    + *
    {@code
    +     * event.register("exampleStructure", StructuresBecomeConfiguredFix.Conversion.biomeMapped(Map.of(
    +     *     List.of("minecraft:desert", "minecraft:jungle"), "examplemod:deserted_structure",
    +     *     List.of("minecraft:ocean"), "examplemod:flooded_structure"
    +     * ), "examplemod:structure"));
    +     *     }
    + *
  • + *
+ * + * @param oldStructureID the old structure ID, in all lowercase + * @param conversion the conversion data + * @throws NullPointerException if the old structure ID, the conversion data, or the fallback structure ID in + * the conversion data is null + * @throws IllegalArgumentException if the old structure ID is not in full lowercase, or if a conversion for that + * structure ID has already been registered previously + */ + public void register(String oldStructureID, StructuresBecomeConfiguredFix.Conversion conversion) + { + checkNotNull(oldStructureID, "Original structure ID must not be null"); + checkArgument(oldStructureID.toLowerCase(Locale.ROOT).equals(oldStructureID), + "Original structure ID should be in all lowercase"); + checkNotNull(conversion, "Structure conversion must not be null"); + checkNotNull(conversion.fallback(), "Fallback structure ID in structure conversion must not be null"); + if (map.putIfAbsent(oldStructureID.toLowerCase(Locale.ROOT), conversion) != null) + { + throw new IllegalArgumentException("Conversion has already been registered for structure " + oldStructureID); + } + } +} diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index 43048635c8..7e96cc2d86 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -278,6 +278,7 @@ public net.minecraft.tags.Tag$ElementEntry public net.minecraft.tags.Tag$OptionalElementEntry public net.minecraft.tags.Tag$OptionalTagEntry public net.minecraft.tags.Tag$TagEntry +public net.minecraft.util.datafix.fixes.StructuresBecomeConfiguredFix$Conversion public net.minecraft.util.thread.BlockableEventLoop m_18689_(Ljava/lang/Runnable;)Ljava/util/concurrent/CompletableFuture; # submitAsync #group public net.minecraft.world.damagesource.DamageSource *() #All methods public, most are already public net.minecraft.world.damagesource.DamageSource (Ljava/lang/String;)V # constructor