Add support for custom tag types (#7289)

This commit is contained in:
Richard Freimer authored and GitHub committed 2020-09-08 19:10:36 -07:00
1 parent 43391c009c
commit 45f8dc5245
27 files changed
+1059 -24

No files matched your search

@@ -110,7 +110,7 @@ public class ForgeInternalHandler
}
@SubscribeEvent
public synchronized void tagsUpdated(TagsUpdatedEvent event)
public synchronized void tagsUpdated(TagsUpdatedEvent.VanillaTagTypes event)
{
ForgeHooks.updateBurns();
}
@@ -0,0 +1,343 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2020.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.entity.EntityType;
import net.minecraft.fluid.Fluid;
import net.minecraft.item.Item;
import net.minecraft.resources.IResourceManager;
import net.minecraft.tags.ITag;
import net.minecraft.tags.ITag.INamedTag;
import net.minecraft.tags.ITagCollection;
import net.minecraft.tags.ITagCollectionSupplier;
import net.minecraft.tags.TagCollectionReader;
import net.minecraft.tags.TagRegistry;
import net.minecraft.tags.TagRegistryManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.Tags.IOptionalNamedTag;
import net.minecraftforge.fml.network.FMLPlayMessages.SyncCustomTagTypes;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.IForgeRegistryEntry;
import net.minecraftforge.registries.RegistryManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ForgeTagHandler
{
private static final Logger LOGGER = LogManager.getLogger();
private static Map<ResourceLocation, ITagCollection<?>> customTagTypes = Collections.emptyMap();
private static Set<ResourceLocation> customTagTypeNames = Collections.emptySet();
private static boolean tagTypesSet = false;
@Nullable
private static <T extends IForgeRegistryEntry<T>> TagRegistry<T> getTagRegistry(IForgeRegistry<T> registry)
{
return (TagRegistry<T>) TagRegistryManager.get(registry.getRegistryName());
}
private static void validateRegistrySupportsTags(IForgeRegistry<?> registry)
{
//Note: We also check against getTagRegistry in case someone decides to use the helpers for tag creation for types supported by vanilla
if (getTagRegistry(registry) == null && (!(registry instanceof ForgeRegistry) || ((ForgeRegistry<?>) registry).getTagFolder() == null))
{
throw new IllegalArgumentException("Registry " + registry.getRegistryName() + " does not support tag types.");
}
}
/**
* Helper method that creates a named tag for a forge registry, erroring if the registry doesn't support custom tag types. If the custom tag types
* have not been set yet, this method falls back and creates the tag reference delaying adding it to the tag registry to allow for statically
* initializing and referencing the tag.
* @param registry Registry the tag is for
* @param name Name of the tag
* @param <T> Type of the registry
* @return A named tag
*/
public static <T extends IForgeRegistryEntry<T>> ITag.INamedTag<T> makeWrapperTag(IForgeRegistry<T> registry, ResourceLocation name)
{
validateRegistrySupportsTags(registry);
if (tagTypesSet)
{
TagRegistry<T> tagRegistry = getTagRegistry(registry);
if (tagRegistry == null) throw new IllegalArgumentException("Registry " + registry.getRegistryName() + " does not support tag types.");
return tagRegistry.func_232937_a_(name.toString());
}
return TagRegistry.createDelayedTag(registry.getRegistryName(), name);
}
/**
* Helper method that creates an optional tag for a forge registry, erroring if the registry doesn't support custom tag types. If the custom tag types
* have not been set yet, this method falls back and creates the tag reference delaying adding it to the tag registry to allow for statically
* initializing and referencing the tag.
* @param registry Registry the tag is for
* @param name Name of the tag
* @param <T> Type of the registry
* @return An optional tag
*/
public static <T extends IForgeRegistryEntry<T>> IOptionalNamedTag<T> createOptionalTag(IForgeRegistry<T> registry, ResourceLocation name)
{
return createOptionalTag(registry, name, null);
}
/**
* Helper method that creates an optional tag for a forge registry, erroring if the registry doesn't support custom tag types. If the custom tag types
* have not been set yet, this method falls back and creates the tag reference delaying adding it to the tag registry to allow for statically
* initializing and referencing the tag.
* @param registry Registry the tag is for
* @param name Name of the tag
* @param defaults Default values for the optional tag
* @param <T> Type of the registry
* @return An optional tag
*/
public static <T extends IForgeRegistryEntry<T>> IOptionalNamedTag<T> createOptionalTag(IForgeRegistry<T> registry, ResourceLocation name, @Nullable Supplier<Set<T>> defaults)
{
validateRegistrySupportsTags(registry);
if (tagTypesSet)
{
TagRegistry<T> tagRegistry = getTagRegistry(registry);
if (tagRegistry == null) throw new IllegalArgumentException("Registry " + registry.getRegistryName() + " does not support tag types.");
return tagRegistry.createOptional(name, defaults);
}
return TagRegistry.createDelayedOptional(registry.getRegistryName(), name, defaults);
}
/**
* Helper method for creating named tags for custom forge registries. If the custom tag types have not been set yet, this method falls back and creates
* the tag reference delaying adding it to the tag registry to allow for statically initializing and referencing the tag.
* @param registryName Name of the registry the tag is for
* @param name Name of the tag
* @param <T> Type of the registry
* @return A named tag
* @implNote This method only errors instantly if tag types have already been set, otherwise the error is delayed until after registries finish initializing
* and we can validate if the custom registry really does support custom tags.
*/
public static <T extends IForgeRegistryEntry<T>> ITag.INamedTag<T> makeWrapperTag(ResourceLocation registryName, ResourceLocation name)
{
if (tagTypesSet)
{
IForgeRegistry<T> registry = RegistryManager.ACTIVE.getRegistry(registryName);
if (registry == null) throw new IllegalArgumentException("Could not find registry named: " + registryName);
return makeWrapperTag(registry, name);
}
return TagRegistry.createDelayedTag(registryName, name);
}
/**
* Helper method for creating optional tags for custom forge registries. If the custom tag types have not been set yet, this method falls back and creates
* the tag reference delaying adding it to the tag registry to allow for statically initializing and referencing the tag.
* @param registryName Name of the registry the tag is for
* @param name Name of the tag
* @param <T> Type of the registry
* @return An optional tag
* @implNote This method only errors instantly if tag types have already been set, otherwise the error is delayed until after registries finish initializing
* and we can validate if the custom registry really does support custom tags.
*/
public static <T extends IForgeRegistryEntry<T>> IOptionalNamedTag<T> createOptionalTag(ResourceLocation registryName, ResourceLocation name)
{
return createOptionalTag(registryName, name, null);
}
/**
* Helper method for creating optional tags for custom forge registries. If the custom tag types have not been set yet, this method falls back and creates
* the tag reference delaying adding it to the tag registry to allow for statically initializing and referencing the tag.
* @param registryName Name of the registry the tag is for
* @param name Name of the tag
* @param defaults Default values for the optional tag
* @param <T> Type of the registry
* @return An optional tag
* @implNote This method only errors instantly if tag types have already been set, otherwise the error is delayed until after registries finish initializing
* and we can validate if the custom registry really does support custom tags.
*/
public static <T extends IForgeRegistryEntry<T>> IOptionalNamedTag<T> createOptionalTag(ResourceLocation registryName, ResourceLocation name, @Nullable Supplier<Set<T>> defaults)
{
if (tagTypesSet)
{
IForgeRegistry<T> registry = RegistryManager.ACTIVE.getRegistry(registryName);
if (registry == null) throw new IllegalArgumentException("Could not find registry named: " + registryName);
return createOptionalTag(registry, name, defaults);
}
return TagRegistry.createDelayedOptional(registryName, name, defaults);
}
/**
* Gets the all the registry names of registries that support custom tag types.
*/
public static Set<ResourceLocation> getCustomTagTypeNames()
{
return customTagTypeNames;
}
/**
* Gets a map of registry name to tag collection for all custom tag types.
*
* @apiNote Prefer interacting with this via the current {@link ITagCollectionSupplier} and using one of the forge extension getCustomTypeCollection methods
*/
public static Map<ResourceLocation, ITagCollection<?>> getCustomTagTypes()
{
return customTagTypes;
}
/**
* Sets the set containing the resource locations representing the registry name of each forge registry that supports custom tag types.
*
* @apiNote Internal: Calling this manually <strong>WILL</strong> cause a crash to occur as it can only be called once, and is done so by
* forge after all registries have been initialized.
*/
public static void setCustomTagTypes(Set<ResourceLocation> customTagTypes)
{
if (tagTypesSet) throw new RuntimeException("Custom tag types have already been set, this method should only be called by forge, and after registries are initialized");
tagTypesSet = true;
customTagTypeNames = ImmutableSet.copyOf(customTagTypes);
TagRegistry.performDelayedAdd();
}
/**
* Creates a map for custom tag type to tag reader
*
* @apiNote Internal: For use by NetworkTagManager
*/
public static Map<ResourceLocation, TagCollectionReader<?>> createCustomTagTypeReaders()
{
LOGGER.debug("Gathering custom tag collection reader from types.");
ImmutableMap.Builder<ResourceLocation, TagCollectionReader<?>> builder = ImmutableMap.builder();
for (ResourceLocation registryName : customTagTypeNames)
{
ForgeRegistry<?> registry = RegistryManager.ACTIVE.getRegistry(registryName);
if (registry != null && registry.getTagFolder() != null)
{
builder.put(registryName, new TagCollectionReader<>(rl -> Optional.ofNullable(registry.getValue(rl)), "tags/" + registry.getTagFolder(), registryName.getPath()));
}
}
return builder.build();
}
/**
* Resets the cached collections for the various custom tag types.
*
* @apiNote Internal
*/
public static void resetCachedTagCollections()
{
ImmutableMap.Builder<ResourceLocation, ITagCollection<?>> builder = ImmutableMap.builder();
for (ResourceLocation registryName : customTagTypeNames)
{
TagRegistry<?> tagRegistry = TagRegistryManager.get(registryName);
if (tagRegistry != null)
{
builder.put(registryName, ITagCollection.func_242202_a(tagRegistry.func_241288_c_().stream().distinct().collect(Collectors.toMap(INamedTag::func_230234_a_, namedTag -> namedTag))));
}
}
customTagTypes = builder.build();
}
/**
* Used to ensure that all custom tag types have a defaulted collection when vanilla is initializing a defaulted TagCollectionManager
*
* @apiNote Internal: For use by TagCollectionManager
*/
public static ITagCollectionSupplier populateTagCollectionManager(ITagCollection<Block> blockTags, ITagCollection<Item> itemTags, ITagCollection<Fluid> fluidTags, ITagCollection<EntityType<?>> entityTypeTags)
{
//Default the tag collections
resetCachedTagCollections();
if (!customTagTypes.isEmpty())
{
LOGGER.debug("Populated the TagCollectionManager with {} extra types", customTagTypes.size());
}
return ITagCollectionSupplier.func_242209_a(blockTags, itemTags, fluidTags, entityTypeTags);
}
/**
* Updates the custom tag types' tags from reloading via NetworkTagManager
*
* @apiNote Internal: For use by NetworkTagManager
*/
public static void updateCustomTagTypes(List<TagCollectionReaderInfo> tagCollectionReaders)
{
ImmutableMap.Builder<ResourceLocation, ITagCollection<?>> builder = ImmutableMap.builder();
for (TagCollectionReaderInfo info : tagCollectionReaders)
{
builder.put(info.tagType, info.reader.func_242226_a(info.tagBuilders));
}
customTagTypes = builder.build();
}
/**
* Updates the custom tag types' tags from packet
*
* @apiNote Internal
*/
public static void updateCustomTagTypes(SyncCustomTagTypes packet)
{
customTagTypes = packet.getCustomTagTypes();
}
/**
* Gets the completable future containing the reload results for all custom tag types.
*
* @apiNote Internal: For use by NetworkTagManager
*/
public static CompletableFuture<List<TagCollectionReaderInfo>> getCustomTagTypeReloadResults(IResourceManager resourceManager, Executor backgroundExecutor, Map<ResourceLocation, TagCollectionReader<?>> readers)
{
CompletableFuture<List<TagCollectionReaderInfo>> customResults = CompletableFuture.completedFuture(new ArrayList<>());
for (Map.Entry<ResourceLocation, TagCollectionReader<?>> entry : readers.entrySet())
{
customResults = customResults.thenCombine(entry.getValue().func_242224_a(resourceManager, backgroundExecutor), (results, result) -> {
results.add(new TagCollectionReaderInfo(entry.getKey(), entry.getValue(), result));
return results;
});
}
return customResults;
}
/**
* Helper storage class for keeping track of various data for all custom tag types in the NetworkTagReader to make the code easier to read.
*
* @apiNote Internal: For use by NetworkTagManager
*/
public static class TagCollectionReaderInfo
{
private final ResourceLocation tagType;
private final TagCollectionReader<?> reader;
private final Map<ResourceLocation, ITag.Builder> tagBuilders;
private TagCollectionReaderInfo(ResourceLocation tagType, TagCollectionReader<?> reader, Map<ResourceLocation, ITag.Builder> tagBuilders)
{
this.tagType = tagType;
this.reader = reader;
this.tagBuilders = tagBuilders;
}
}
}
@@ -0,0 +1,73 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2020.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.data;
import com.google.common.collect.ImmutableMap;
import com.mojang.serialization.Lifecycle;
import java.nio.file.Path;
import java.util.Map;
import javax.annotation.Nullable;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.TagsProvider;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.GameData;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.IForgeRegistryEntry;
public abstract class ForgeRegistryTagsProvider<T extends IForgeRegistryEntry<T>> extends TagsProvider<T>
{
//Special handling for vanilla tag types in case someone decides to use the ForgeRegistryTagsProvider instead of one of the vanilla subtypes
private static final Map<IForgeRegistry<?>, String> vanillaTypes = ImmutableMap.<IForgeRegistry<?>, String>builder()
.put(ForgeRegistries.BLOCKS, "blocks")
.put(ForgeRegistries.ENTITIES, "entity_types")
.put(ForgeRegistries.FLUIDS, "fluids")
.put(ForgeRegistries.ITEMS, "items")
.build();
private static <T extends IForgeRegistryEntry<T>> Registry<T> wrapRegistry(IForgeRegistry<T> registryIn)
{
if (!(registryIn instanceof ForgeRegistry))
throw new IllegalArgumentException("Forge registry " + registryIn.getRegistryName() + " is not an instance of a ForgeRegistry");
ForgeRegistry<T> forgeRegistry = (ForgeRegistry<T>) registryIn;
if (forgeRegistry.getTagFolder() == null && !vanillaTypes.containsKey(registryIn))
throw new IllegalArgumentException("Forge registry " + registryIn.getRegistryName() + " does not have support for tags");
if (forgeRegistry.getDefaultKey() == null)
return GameData.getWrapper(forgeRegistry.getRegistryKey(), Lifecycle.experimental());
return GameData.getWrapper(forgeRegistry.getRegistryKey(), Lifecycle.experimental(), "default");
}
private final String folder;
public ForgeRegistryTagsProvider(DataGenerator generatorIn, IForgeRegistry<T> registryIn, String modId, @Nullable ExistingFileHelper existingFileHelper)
{
super(generatorIn, wrapRegistry(registryIn), modId, existingFileHelper);
String tagFolder = ((ForgeRegistry<T>) registryIn).getTagFolder();
folder = tagFolder == null ? vanillaTypes.get(registryIn) : tagFolder;
}
@Override
protected Path makePath(ResourceLocation id)
{
return generator.getOutputFolder().resolve("data/" + id.getNamespace() + "/tags/" + folder + "/" + id.getPath() + ".json");
}
}
@@ -21,6 +21,7 @@ package net.minecraftforge.common.extensions;
import net.minecraft.data.TagsProvider;
import net.minecraft.tags.ITag;
import net.minecraft.util.RegistryKey;
import net.minecraft.util.ResourceLocation;
//TODO, Tag removal support.
@@ -40,6 +41,14 @@ public interface IForgeTagBuilder<T>
return builder;
}
default TagsProvider.Builder<T> add(RegistryKey<T>... keys) {
TagsProvider.Builder<T> builder = getBuilder();
for (RegistryKey<T> key : keys) {
builder.getInternalBuilder().func_232961_a_(key.func_240901_a_(), getBuilder().getModID());
}
return builder;
}
default TagsProvider.Builder<T> replace() {
return replace(true);
}
@@ -0,0 +1,61 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2020.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.extensions;
import java.util.Map;
import net.minecraft.tags.ITagCollection;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.ForgeTagHandler;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.IForgeRegistryEntry;
public interface IForgeTagCollectionSupplier
{
/**
* Gets the tag map of registry names to tag collections for the various custom tag types.
*
* @apiNote Prefer using one of the getCustomTypeCollection methods
*/
default Map<ResourceLocation, ITagCollection<?>> getCustomTagTypes()
{
return ForgeTagHandler.getCustomTagTypes();
}
/**
* Gets the {@link ITagCollection} for a forge registry with the given name, or throws an exception if the registry doesn't support custom tag types.
* @param regName Name of the forge registry
* @return The tag collection
*/
default ITagCollection<?> getCustomTypeCollection(ResourceLocation regName)
{
if (!ForgeTagHandler.getCustomTagTypeNames().contains(regName)) throw new IllegalArgumentException("Registry " + regName + ", does not support custom tag types");
return getCustomTagTypes().get(regName);
}
/**
* Gets the {@link ITagCollection} for a forge registry, or throws an exception if the registry doesn't support custom tag types.
* @param reg Forge registry
* @return The tag collection
*/
default <T extends IForgeRegistryEntry<T>> ITagCollection<T> getCustomTypeCollection(IForgeRegistry<T> reg)
{
return (ITagCollection<T>) getCustomTypeCollection(reg.getRegistryName());
}
}
@@ -45,4 +45,26 @@ public class TagsUpdatedEvent extends Event
{
return manager;
}
/**
* Fired after the Vanilla Tag types have been processed
*/
public static class VanillaTagTypes extends TagsUpdatedEvent
{
public VanillaTagTypes(ITagCollectionSupplier manager)
{
super(manager);
}
}
/**
* Fired after any custom tag types have been processed
*/
public static class CustomTagTypes extends TagsUpdatedEvent
{
public CustomTagTypes(ITagCollectionSupplier manager)
{
super(manager);
}
}
}
@@ -198,6 +198,8 @@ public class ModLoader
CapabilityManager.INSTANCE.injectCapabilities(modList.getAllScanData());
statusConsumer.ifPresent(c->c.accept("Populating registries"));
dispatchAndHandleError(ModLoadingStage.LOAD_REGISTRIES, syncExecutor, parallelExecutor, periodicTask);
statusConsumer.ifPresent(c->c.accept("Adding custom tag types"));
GameData.setCustomTagTypesFromRegistries();
statusConsumer.ifPresent(c->c.accept("Early mod loading complete"));
}
@@ -19,7 +19,14 @@
package net.minecraftforge.fml.network;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import io.netty.buffer.Unpooled;
import java.util.List;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.IHasContainer;
import net.minecraft.client.gui.ScreenManager;
@@ -27,23 +34,36 @@ import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.fluid.Fluid;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.ContainerType;
import net.minecraft.item.Item;
import net.minecraft.network.PacketBuffer;
import net.minecraft.tags.ITag;
import net.minecraft.tags.ITagCollection;
import net.minecraft.tags.ITagCollectionSupplier;
import net.minecraft.tags.TagRegistryManager;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World;
import net.minecraft.world.biome.FuzzedBiomeMagnifier;
import net.minecraftforge.common.ForgeTagHandler;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.TagsUpdatedEvent;
import net.minecraftforge.fml.LogicalSidedProvider;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData;
import net.minecraftforge.registries.ForgeRegistries;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Supplier;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.IForgeRegistryEntry;
import net.minecraftforge.registries.RegistryManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class FMLPlayMessages
{
@@ -308,4 +328,144 @@ public class FMLPlayMessages
return additionalData;
}
}
public static class SyncCustomTagTypes
{
private static final Logger LOGGER = LogManager.getLogger();
private final Map<ResourceLocation, ITagCollection<?>> customTagTypeCollections;
SyncCustomTagTypes(Map<ResourceLocation, ITagCollection<?>> customTagTypeCollections)
{
this.customTagTypeCollections = customTagTypeCollections;
}
public Map<ResourceLocation, ITagCollection<?>> getCustomTagTypes()
{
return customTagTypeCollections;
}
public static void encode(SyncCustomTagTypes msg, PacketBuffer buf)
{
buf.writeVarInt(msg.customTagTypeCollections.size());
msg.customTagTypeCollections.forEach((registryName, modded) -> forgeTagCollectionWrite(buf, registryName, modded.func_241833_a()));
}
private static <T> void forgeTagCollectionWrite(PacketBuffer buf, ResourceLocation registryName, Map<ResourceLocation, ITag<T>> tags)
{
buf.writeResourceLocation(registryName);
buf.writeVarInt(tags.size());
tags.forEach((name, tag) -> {
buf.writeResourceLocation(name);
List<T> elements = tag.func_230236_b_();
buf.writeVarInt(elements.size());
for (T element : elements)
{
buf.writeResourceLocation(((IForgeRegistryEntry<?>) element).getRegistryName());
}
});
}
public static SyncCustomTagTypes decode(PacketBuffer buf)
{
ImmutableMap.Builder<ResourceLocation, ITagCollection<?>> builder = ImmutableMap.builder();
int size = buf.readVarInt();
for (int i = 0; i < size; i++)
{
ResourceLocation regName = buf.readResourceLocation();
IForgeRegistry<?> registry = RegistryManager.ACTIVE.getRegistry(regName);
if (registry != null)
{
builder.put(regName, readTagCollection(buf, registry));
}
}
return new SyncCustomTagTypes(builder.build());
}
private static <T extends IForgeRegistryEntry<T>> ITagCollection<T> readTagCollection(PacketBuffer buf, IForgeRegistry<T> registry)
{
Map<ResourceLocation, ITag<T>> tags = Maps.newHashMap();
int totalTags = buf.readVarInt();
for (int i = 0; i < totalTags; i++)
{
ImmutableSet.Builder<T> elementBuilder = ImmutableSet.builder();
ResourceLocation name = buf.readResourceLocation();
int totalElements = buf.readVarInt();
for (int j = 0; j < totalElements; j++)
{
T element = registry.getValue(buf.readResourceLocation());
if (element != null)
{
elementBuilder.add(element);
}
}
tags.put(name, ITag.func_232946_a_(elementBuilder.build()));
}
return ITagCollection.func_242202_a(tags);
}
public static void handle(SyncCustomTagTypes msg, Supplier<NetworkEvent.Context> ctx)
{
ctx.get().enqueueWork(() -> {
if (Minecraft.getInstance().world != null)
{
ITagCollectionSupplier tagCollectionSupplier = Minecraft.getInstance().world.getTags();
//Validate that all the tags exist using the tag type collections from the packet
// We mimic vanilla in that we validate before updating the actual stored tags so that it can gracefully fallback
// to the last working set of tags
//Note: We gracefully ignore any tag types the server may have that we don't as they won't be in our tag registry
// so they won't be validated
Multimap<ResourceLocation, ResourceLocation> missingTags = TagRegistryManager.func_242198_b(new ITagCollectionSupplier()
{
@Override
public ITagCollection<Block> func_241835_a()
{
return tagCollectionSupplier.func_241835_a();
}
@Override
public ITagCollection<Item> func_241836_b()
{
return tagCollectionSupplier.func_241836_b();
}
@Override
public ITagCollection<Fluid> func_241837_c()
{
return tagCollectionSupplier.func_241837_c();
}
@Override
public ITagCollection<EntityType<?>> func_241838_d()
{
return tagCollectionSupplier.func_241838_d();
}
@Override
public Map<ResourceLocation, ITagCollection<?>> getCustomTagTypes()
{
//Override and use the tags from the packet to test for validation before we actually set them
return msg.customTagTypeCollections;
}
});
if (missingTags.isEmpty())
{
//If we have no missing tags, update the custom tag types
ForgeTagHandler.updateCustomTagTypes(msg);
if (!ctx.get().getNetworkManager().isLocalChannel())
{
//And if everything hasn't already been set due to being in single player
// Fetch and update the custom tag types. We skip vanilla tag types as they have already been fetched
// And fire an event that the custom tag types have been updated
TagRegistryManager.fetchCustomTagTypes(tagCollectionSupplier);
MinecraftForge.EVENT_BUS.post(new TagsUpdatedEvent.CustomTagTypes(tagCollectionSupplier));
}
} else {
LOGGER.warn("Incomplete server tags, disconnecting. Missing: {}", missingTags);
ctx.get().getNetworkManager().closeChannel(new TranslationTextComponent("multiplayer.disconnect.missing_tags"));
}
}
});
ctx.get().setPacketHandled(true);
}
}
}
@@ -19,6 +19,7 @@
package net.minecraftforge.fml.network;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
@@ -26,6 +27,8 @@ import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import net.minecraft.tags.ITagCollection;
import net.minecraft.tags.ITagCollectionSupplier;
import net.minecraft.util.text.StringTextComponent;
import net.minecraftforge.fml.common.thread.EffectiveSide;
import org.apache.logging.log4j.LogManager;
@@ -208,4 +211,31 @@ public class NetworkHooks
player.openContainer.addListener(player);
MinecraftForge.EVENT_BUS.post(new PlayerContainerEvent.Open(player, c));
}
/**
* Syncs the custom tag types attached to a {@link ITagCollectionSupplier} to all connected players.
* @param tagCollectionSupplier The tag collection supplier containing the custom tags
*/
public static void syncCustomTagTypes(ITagCollectionSupplier tagCollectionSupplier)
{
Map<ResourceLocation, ITagCollection<?>> customTagTypes = tagCollectionSupplier.getCustomTagTypes();
if (!customTagTypes.isEmpty())
{
FMLNetworkConstants.playChannel.send(PacketDistributor.ALL.noArg(), new FMLPlayMessages.SyncCustomTagTypes(customTagTypes));
}
}
/**
* Syncs the custom tag types attached to a {@link ITagCollectionSupplier} to the given player.
* @param player The player to sync the custom tags to.
* @param tagCollectionSupplier The tag collection supplier containing the custom tags
*/
public static void syncCustomTagTypes(ServerPlayerEntity player, ITagCollectionSupplier tagCollectionSupplier)
{
Map<ResourceLocation, ITagCollection<?>> customTagTypes = tagCollectionSupplier.getCustomTagTypes();
if (!customTagTypes.isEmpty())
{
FMLNetworkConstants.playChannel.sendTo(new FMLPlayMessages.SyncCustomTagTypes(customTagTypes), player.connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
}
}
}
@@ -105,6 +105,12 @@ class NetworkInitialization {
// .consumer(FMLPlayMessages.DimensionInfoMessage::handle)
// .add();
playChannel.messageBuilder(FMLPlayMessages.SyncCustomTagTypes.class, 3).
decoder(FMLPlayMessages.SyncCustomTagTypes::decode).
encoder(FMLPlayMessages.SyncCustomTagTypes::encode).
consumer(FMLPlayMessages.SyncCustomTagTypes::handle).
add();
return playChannel;
}
@@ -91,6 +91,8 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
private final int max;
private final boolean allowOverrides;
private final boolean isModifiable;
@Nullable
private final String tagFolder;
private V defaultValue = null;
boolean isFrozen = false;
@@ -120,6 +122,7 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
this.isDelegated = ForgeRegistryEntry.class.isAssignableFrom(superType); //TODO: Make this IDelegatedRegistryEntry?
this.allowOverrides = builder.getAllowOverrides();
this.isModifiable = builder.getAllowModifications();
this.tagFolder = builder.getTagFolder();
if (this.create != null)
this.create.onCreate(this, stage);
}
@@ -175,6 +178,12 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
return superType;
}
@Nullable
public String getTagFolder()
{
return tagFolder;
}
@Override
public void registerAll(@SuppressWarnings("unchecked") V... values)
{
@@ -22,6 +22,8 @@ package net.minecraftforge.registries;
import com.google.common.collect.*;
import com.mojang.serialization.Lifecycle;
import java.util.HashSet;
import java.util.Set;
import net.minecraft.block.AirBlock;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
@@ -47,6 +49,7 @@ import net.minecraft.potion.Effect;
import net.minecraft.potion.Potion;
import net.minecraft.state.StateContainer;
import net.minecraft.stats.StatType;
import net.minecraft.tags.TagRegistryManager;
import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.ObjectIntIdentityMap;
import net.minecraft.util.RegistryKey;
@@ -68,6 +71,7 @@ import net.minecraft.world.gen.foliageplacer.FoliagePlacerType;
import net.minecraft.world.gen.placement.Placement;
import net.minecraft.world.gen.surfacebuilders.SurfaceBuilder;
import net.minecraft.world.gen.treedecorator.TreeDecoratorType;
import net.minecraftforge.common.ForgeTagHandler;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.loot.GlobalLootModifierSerializer;
import net.minecraftforge.event.RegistryEvent;
@@ -175,7 +179,7 @@ public class GameData
makeRegistry(TREE_DECORATOR_TYPES, c(TreeDecoratorType.class)).disableSaving().disableSync().create();
// Dynamic Worldgen
makeRegistry(BIOMES, Biome.class).create();
makeRegistry(BIOMES, Biome.class).tagFolder("biomes").create();
// Custom forge registries
makeRegistry(DATA_SERIALIZERS, DataSerializerEntry.class, 256 /*vanilla space*/, MAX_VARINT).disableSaving().disableOverrides().addCallback(SerializerCallbacks.INSTANCE).create();
@@ -190,11 +194,11 @@ public class GameData
}
private static <T extends IForgeRegistryEntry<T>> RegistryBuilder<T> makeRegistry(RegistryKey<? extends Registry<T>> key, Class<T> type, int min, int max)
{
return new RegistryBuilder<T>().setName(key.func_240901_a_()).setType(type).setIDRange(min, max).addCallback(new NamespacedWrapper.Factory<T>());
return new RegistryBuilder<T>().setName(key.func_240901_a_()).setType(type).setIDRange(min, max).hasWrapper();
}
private static <T extends IForgeRegistryEntry<T>> RegistryBuilder<T> makeRegistry(RegistryKey<? extends Registry<T>> key, Class<T> type, String _default)
{
return new RegistryBuilder<T>().setName(key.func_240901_a_()).setType(type).setMaxID(MAX_VARINT).addCallback(new NamespacedDefaultedWrapper.Factory<T>()).setDefaultKey(new ResourceLocation(_default));
return new RegistryBuilder<T>().setName(key.func_240901_a_()).setType(type).setMaxID(MAX_VARINT).hasWrapper().setDefaultKey(new ResourceLocation(_default));
}
public static <T extends IForgeRegistryEntry<T>> SimpleRegistry<T> getWrapper(RegistryKey<? extends Registry<T>> key, Lifecycle lifecycle)
@@ -360,6 +364,22 @@ public class GameData
};
}
public static void setCustomTagTypesFromRegistries()
{
Set<ResourceLocation> customTagTypes = new HashSet<>();
for (Map.Entry<ResourceLocation, ForgeRegistry<? extends IForgeRegistryEntry<?>>> entry : RegistryManager.ACTIVE.registries.entrySet())
{
ResourceLocation registryName = entry.getKey();
if (entry.getValue().getTagFolder() != null && TagRegistryManager.get(registryName) == null)
{
LOGGER.debug(REGISTRIES, "Registering custom tag type for: {}", registryName);
customTagTypes.add(registryName);
TagRegistryManager.func_242196_a(registryName, tagCollectionSupplier -> tagCollectionSupplier.getCustomTypeCollection(registryName));
}
}
ForgeTagHandler.setCustomTagTypes(customTagTypes);
}
//Lets us clear the map so we can rebuild it.
private static class ClearableObjectIntIdentityMap<I> extends ObjectIntIdentityMap<I>
{
@@ -48,6 +48,9 @@ public class RegistryBuilder<T extends IForgeRegistryEntry<T>>
private boolean sync = true;
private boolean allowOverrides = true;
private boolean allowModifications = false;
private boolean hasWrapper = false;
@Nullable
private String tagFolder;
private DummyFactory<T> dummyFactory;
private MissingFactory<T> missingFactory;
private Set<ResourceLocation> legacyNames = new HashSet<>();
@@ -203,6 +206,21 @@ public class RegistryBuilder<T extends IForgeRegistryEntry<T>>
return this;
}
RegistryBuilder<T> hasWrapper()
{
this.hasWrapper = true;
return this;
}
public RegistryBuilder<T> tagFolder(String tagFolder)
{
if (tagFolder == null || !tagFolder.matches("[a-z_/]+")) throw new IllegalArgumentException("Non [a-z_/] character in tag folder " + tagFolder);
this.tagFolder = tagFolder;
//Also mark this registry as having a wrapper to a vanilla registry so that it can be used in data generators properly
hasWrapper();
return this;
}
public RegistryBuilder<T> legacyName(String name)
{
return legacyName(new ResourceLocation(name));
@@ -216,6 +234,13 @@ public class RegistryBuilder<T extends IForgeRegistryEntry<T>>
public IForgeRegistry<T> create()
{
if (hasWrapper)
{
if (getDefault() == null)
addCallback(new NamespacedWrapper.Factory<T>());
else
addCallback(new NamespacedDefaultedWrapper.Factory<T>());
}
return RegistryManager.ACTIVE.createRegistry(registryName, this);
}
@@ -325,6 +350,12 @@ public class RegistryBuilder<T extends IForgeRegistryEntry<T>>
return allowModifications;
}
@Nullable
public String getTagFolder()
{
return tagFolder;
}
@Nullable
public DummyFactory<T> getDummyFactory()
{