mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-18 19:39:22 +00:00
Cleanup Tag Loading, this migrates thins to more of a vanilla style. (#7898)
This commit is contained in:
1 parent
a336e443f7
commit
d17f10d80c
27 files changed
+178
-590
No files matched your search
@@ -113,7 +113,7 @@ public class ForgeInternalHandler
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public synchronized void tagsUpdated(TagsUpdatedEvent.VanillaTagTypes event)
|
||||
public synchronized void tagsUpdated(TagsUpdatedEvent event)
|
||||
{
|
||||
ForgeHooks.updateBurns();
|
||||
}
|
||||
|
||||
@@ -21,31 +21,25 @@ 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.Map.Entry;
|
||||
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.server.packs.resources.ResourceManager;
|
||||
import net.minecraft.tags.Tag;
|
||||
import net.minecraft.tags.Tag.Named;
|
||||
import net.minecraft.tags.TagCollection;
|
||||
import net.minecraft.tags.TagContainer;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
|
||||
import com.mojang.serialization.Lifecycle;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.tags.StaticTagHelper;
|
||||
import net.minecraft.tags.StaticTags;
|
||||
import net.minecraft.tags.Tag.Named;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagContainer;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraftforge.common.Tags.IOptionalNamedTag;
|
||||
import net.minecraftforge.common.extensions.IForgeTagContainer;
|
||||
import net.minecraftforge.fmllegacy.network.FMLPlayMessages.SyncCustomTagTypes;
|
||||
import net.minecraftforge.registries.ForgeRegistry;
|
||||
import net.minecraftforge.registries.GameData;
|
||||
import net.minecraftforge.registries.IForgeRegistry;
|
||||
import net.minecraftforge.registries.IForgeRegistryEntry;
|
||||
import net.minecraftforge.registries.RegistryManager;
|
||||
@@ -55,20 +49,19 @@ import org.apache.logging.log4j.Logger;
|
||||
public class ForgeTagHandler
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static Map<ResourceLocation, TagCollection<?>> customTagTypes = Collections.emptyMap();
|
||||
private static Set<ResourceLocation> customTagTypeNames = Collections.emptySet();
|
||||
private static boolean tagTypesSet = false;
|
||||
|
||||
@Nullable
|
||||
private static <T extends IForgeRegistryEntry<T>> StaticTagHelper<T> getTagRegistry(IForgeRegistry<T> registry)
|
||||
private static <T extends IForgeRegistryEntry<T>> StaticTagHelper<T> getTagHelper(IForgeRegistry<T> registry)
|
||||
{
|
||||
return (StaticTagHelper<T>) StaticTags.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))
|
||||
//Note: We also check against getTagHelper in case someone decides to use the helpers for tag creation for types supported by vanilla
|
||||
if (getTagHelper(registry) == null && (!(registry instanceof ForgeRegistry) || ((ForgeRegistry<?>) registry).getTagFolder() == null))
|
||||
{
|
||||
throw new IllegalArgumentException("Registry " + registry.getRegistryName() + " does not support tag types.");
|
||||
}
|
||||
@@ -88,7 +81,7 @@ public class ForgeTagHandler
|
||||
validateRegistrySupportsTags(registry);
|
||||
if (tagTypesSet)
|
||||
{
|
||||
StaticTagHelper<T> tagRegistry = getTagRegistry(registry);
|
||||
StaticTagHelper<T> tagRegistry = getTagHelper(registry);
|
||||
if (tagRegistry == null) throw new IllegalArgumentException("Registry " + registry.getRegistryName() + " does not support tag types.");
|
||||
return tagRegistry.bind(name.toString());
|
||||
}
|
||||
@@ -124,7 +117,7 @@ public class ForgeTagHandler
|
||||
validateRegistrySupportsTags(registry);
|
||||
if (tagTypesSet)
|
||||
{
|
||||
StaticTagHelper<T> tagRegistry = getTagRegistry(registry);
|
||||
StaticTagHelper<T> tagRegistry = getTagHelper(registry);
|
||||
if (tagRegistry == null) throw new IllegalArgumentException("Registry " + registry.getRegistryName() + " does not support tag types.");
|
||||
return tagRegistry.createOptional(name, defaults);
|
||||
}
|
||||
@@ -197,27 +190,17 @@ public class ForgeTagHandler
|
||||
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 IForgeTagContainer} and using one of the forge extension getCustomTypeCollection methods
|
||||
*/
|
||||
public static Map<ResourceLocation, TagCollection<?>> 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)
|
||||
public static void setCustomTagTypes(Set<ResourceLocation> customTagTypesNames)
|
||||
{
|
||||
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);
|
||||
customTagTypeNames = ImmutableSet.copyOf(customTagTypesNames);
|
||||
//Add the static references for custom tag types to the proper tag registries
|
||||
// Note: If this ends up being a hotspot due to lots of mods having lots of statically registered tags
|
||||
// that get loaded/registered before the new registry event is fired/processed everywhere then this
|
||||
@@ -228,7 +211,7 @@ public class ForgeTagHandler
|
||||
/**
|
||||
* Creates a map for custom tag type to tag reader
|
||||
*
|
||||
* @apiNote Internal: For use by NetworkTagManager
|
||||
* @apiNote Internal: For use by TagManager
|
||||
*/
|
||||
public static Map<ResourceLocation, TagLoader<?>> createCustomTagTypeReaders()
|
||||
{
|
||||
@@ -246,166 +229,35 @@ public class ForgeTagHandler
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the cached collections for the various custom tag types.
|
||||
* Wraps the forge registry if it supports tags into the internal registry for use in serialization
|
||||
*
|
||||
* @apiNote Internal: For use in TagContainer
|
||||
*/
|
||||
@SuppressWarnings({"OptionalUsedAsFieldOrParameterType", "unchecked"})
|
||||
public static <T> Optional<? extends Registry<T>> getWrapperRegistry(ResourceKey<? extends Registry<T>> key, Optional<? extends Registry<T>> vanillaReg)
|
||||
{
|
||||
if (vanillaReg.isPresent())
|
||||
return vanillaReg;
|
||||
|
||||
ForgeRegistry<?> reg = RegistryManager.ACTIVE.getRegistry(key.location());
|
||||
if (reg == null || reg.getTagFolder() == null)
|
||||
return Optional.empty();
|
||||
|
||||
if (reg.getDefaultKey() == null)
|
||||
return Optional.of((Registry<T>) GameData.getWrapper(reg.getRegistryKey(), Lifecycle.stable()));
|
||||
return Optional.of((Registry<T>) GameData.getWrapper(reg.getRegistryKey(), Lifecycle.stable(), "ignored"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to reinject missing optional tags.
|
||||
*
|
||||
* @apiNote Internal
|
||||
*/
|
||||
public static void resetCachedTagCollections(boolean makeEmpty, boolean withOptional)
|
||||
public static TagContainer reinjectOptionalTags(TagContainer tagCollectionSupplier)
|
||||
{
|
||||
ImmutableMap.Builder<ResourceLocation, TagCollection<?>> builder = ImmutableMap.builder();
|
||||
for (ResourceLocation registryName : customTagTypeNames)
|
||||
{
|
||||
StaticTagHelper<?> tagRegistry = StaticTags.get(registryName);
|
||||
if (tagRegistry != null)
|
||||
{
|
||||
if (makeEmpty)
|
||||
{
|
||||
if (withOptional)
|
||||
builder.put(registryName, tagRegistry.reinjectOptionalTags(TagCollection.of(Collections.emptyMap())));
|
||||
else
|
||||
builder.put(registryName, TagCollection.of(Collections.emptyMap()));
|
||||
}
|
||||
else
|
||||
{
|
||||
builder.put(registryName, TagCollection.of(tagRegistry.getWrappers().stream().distinct().collect(Collectors.toMap(Named::getName, 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 void populateTagCollectionManager()
|
||||
{
|
||||
//Default the tag collections
|
||||
resetCachedTagCollections(false, false);
|
||||
if (!customTagTypes.isEmpty())
|
||||
{
|
||||
LOGGER.debug("Populated the TagCollectionManager with {} extra types", customTagTypes.size());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, TagCollection<?>> builder = ImmutableMap.builder();
|
||||
for (TagCollectionReaderInfo info : tagCollectionReaders)
|
||||
{
|
||||
builder.put(info.tagType, info.reader.build(info.tagBuilders));
|
||||
}
|
||||
customTagTypes = builder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the custom tag types' tags from packet
|
||||
*
|
||||
* @apiNote Internal
|
||||
*/
|
||||
public static void updateCustomTagTypes(SyncCustomTagTypes packet)
|
||||
{
|
||||
customTagTypes = packet.getCustomTagTypes();
|
||||
reinjectOptionalTagsCustomTypes();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(ResourceManager resourceManager, Executor backgroundExecutor, Map<ResourceLocation, TagLoader<?>> readers)
|
||||
{
|
||||
CompletableFuture<List<TagCollectionReaderInfo>> customResults = CompletableFuture.completedFuture(new ArrayList<>());
|
||||
for (Entry<ResourceLocation, TagLoader<?>> entry : readers.entrySet())
|
||||
{
|
||||
CompletableFuture<Map<ResourceLocation, Tag.Builder>> collectionFuture =
|
||||
CompletableFuture.supplyAsync(() -> entry.getValue().load(resourceManager), backgroundExecutor);
|
||||
customResults = customResults.thenCombine(collectionFuture, (results, result) -> {
|
||||
results.add(new TagCollectionReaderInfo(entry.getKey(), entry.getValue(), result));
|
||||
return results;
|
||||
});
|
||||
}
|
||||
return customResults;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add all the missing optional tags back into the custom tag types tag collections
|
||||
*
|
||||
* @apiNote Internal
|
||||
*/
|
||||
public static void reinjectOptionalTagsCustomTypes()
|
||||
{
|
||||
ImmutableMap.Builder<ResourceLocation, TagCollection<?>> builder = ImmutableMap.builder();
|
||||
for (Entry<ResourceLocation, TagCollection<?>> entry : customTagTypes.entrySet())
|
||||
{
|
||||
ResourceLocation registry = entry.getKey();
|
||||
StaticTagHelper<?> tagRegistry = StaticTags.get(registry);
|
||||
TagCollection<?> tagCollection = entry.getValue();
|
||||
builder.put(registry, tagRegistry == null ? tagCollection : tagRegistry.reinjectOptionalTags((TagCollection) tagCollection));
|
||||
}
|
||||
customTagTypes = builder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an {@link IForgeTagContainer} with empty custom tag type collections to allow for checking if the client is requiring any tags of custom tag types.
|
||||
*
|
||||
* @apiNote Internal: For use with validating missing tags when connecting to a vanilla server
|
||||
*/
|
||||
public static TagContainer withNoCustom(TagContainer tagCollectionSupplier)
|
||||
{
|
||||
ImmutableMap.Builder<ResourceLocation, TagCollection<?>> builder = ImmutableMap.builder();
|
||||
for (ResourceLocation registryName : customTagTypeNames)
|
||||
{
|
||||
StaticTagHelper<?> tagRegistry = StaticTags.get(registryName);
|
||||
if (tagRegistry != null)
|
||||
{
|
||||
builder.put(registryName, TagCollection.of(Collections.emptyMap()));
|
||||
}
|
||||
}
|
||||
return withSpecificCustom(tagCollectionSupplier, builder.build());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an {@link IForgeTagContainer} with specific custom tag types for testing if any tags are missing.
|
||||
*
|
||||
* @apiNote Internal
|
||||
*/
|
||||
public static TagContainer withSpecificCustom(TagContainer tagCollectionSupplier, Map<ResourceLocation, TagCollection<?>> customTagTypes)
|
||||
{
|
||||
return new TagContainer(tagCollectionSupplier.collections)
|
||||
{
|
||||
@Override
|
||||
public Map<ResourceLocation, TagCollection<?>> getCustomTagTypes()
|
||||
{
|
||||
return customTagTypes;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 TagLoader<?> reader;
|
||||
private final Map<ResourceLocation, Tag.Builder> tagBuilders;
|
||||
|
||||
private TagCollectionReaderInfo(ResourceLocation tagType, TagLoader<?> reader, Map<ResourceLocation, Tag.Builder> tagBuilders)
|
||||
{
|
||||
this.tagType = tagType;
|
||||
this.reader = reader;
|
||||
this.tagBuilders = tagBuilders;
|
||||
}
|
||||
TagContainer.Builder builder = new TagContainer.Builder();
|
||||
//noinspection unchecked,rawtypes
|
||||
StaticTags.visitHelpers(h -> builder.add(h.getKey(), h.reinjectOptionalTags(tagCollectionSupplier.getOrEmpty((ResourceKey) h.getKey()))));
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ import net.minecraftforge.registries.IForgeRegistryEntry;
|
||||
|
||||
public abstract class ForgeRegistryTagsProvider<T extends IForgeRegistryEntry<T>> extends TagsProvider<T>
|
||||
{
|
||||
//TODO add game event tags here when they become a forge registry
|
||||
//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")
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* 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.TagCollection;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.common.ForgeTagHandler;
|
||||
import net.minecraftforge.registries.IForgeRegistry;
|
||||
import net.minecraftforge.registries.IForgeRegistryEntry;
|
||||
|
||||
public interface IForgeTagContainer
|
||||
{
|
||||
/**
|
||||
* 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, TagCollection<?>> getCustomTagTypes()
|
||||
{
|
||||
return ForgeTagHandler.getCustomTagTypes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link TagCollection} 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 TagCollection<?> 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 TagCollection} 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>> TagCollection<T> getCustomTypeCollection(IForgeRegistry<T> reg)
|
||||
{
|
||||
return (TagCollection<T>) getCustomTypeCollection(reg.getRegistryName());
|
||||
}
|
||||
}
|
||||
@@ -20,11 +20,14 @@
|
||||
package net.minecraftforge.event;
|
||||
|
||||
import net.minecraft.tags.TagContainer;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
|
||||
/**
|
||||
* Fired on the client when {@link ITagCollectionSupplier} has all of its tags synced from the server to the client (just after a client has connected).
|
||||
* Fired on the server when {@link ITagCollectionSupplier} has read all tags from disk (during a data reload).
|
||||
* Fired on the client when :
|
||||
* {@link TagContainer} has all of its tags synced from the server to the client (just after a client has connected).
|
||||
* The integrated server is about to be created see {@link net.minecraft.client.Minecraft#doLoadLevel}
|
||||
* Fired on the server when {@link TagContainer} has read all tags from disk, during initial load and after the reload command is used
|
||||
* This event is fired on the {@link MinecraftForge#EVENT_BUS}
|
||||
* On the client, this event fires on the Client Thread.
|
||||
* On the server, this event may be fired on the Server Thread, or an async reloader thread.
|
||||
@@ -45,26 +48,4 @@ public class TagsUpdatedEvent extends Event
|
||||
{
|
||||
return manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired after the Vanilla Tag types have been processed
|
||||
*/
|
||||
public static class VanillaTagTypes extends TagsUpdatedEvent
|
||||
{
|
||||
public VanillaTagTypes(TagContainer manager)
|
||||
{
|
||||
super(manager);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired after any custom tag types have been processed
|
||||
*/
|
||||
public static class CustomTagTypes extends TagsUpdatedEvent
|
||||
{
|
||||
public CustomTagTypes(TagContainer manager)
|
||||
{
|
||||
super(manager);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,49 +19,27 @@
|
||||
|
||||
package net.minecraftforge.fmllegacy.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.client.Minecraft;
|
||||
import net.minecraft.client.gui.screens.inventory.MenuAccess;
|
||||
import net.minecraft.client.gui.screens.MenuScreens;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.inventory.AbstractContainerMenu;
|
||||
import net.minecraft.world.inventory.MenuType;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.tags.Tag;
|
||||
import net.minecraft.tags.TagCollection;
|
||||
import net.minecraft.tags.TagContainer;
|
||||
import net.minecraft.tags.StaticTags;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraft.network.chat.TranslatableComponent;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraftforge.common.ForgeTagHandler;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.TagsUpdatedEvent;
|
||||
import net.minecraftforge.fmllegacy.LogicalSidedProvider;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraftforge.fmllegacy.common.registry.IEntityAdditionalSpawnData;
|
||||
|
||||
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
|
||||
{
|
||||
@@ -326,113 +304,4 @@ public class FMLPlayMessages
|
||||
return additionalData;
|
||||
}
|
||||
}
|
||||
|
||||
public static class SyncCustomTagTypes
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private final Map<ResourceLocation, TagCollection<?>> customTagTypeCollections;
|
||||
|
||||
SyncCustomTagTypes(Map<ResourceLocation, TagCollection<?>> customTagTypeCollections)
|
||||
{
|
||||
this.customTagTypeCollections = customTagTypeCollections;
|
||||
}
|
||||
|
||||
public Map<ResourceLocation, TagCollection<?>> getCustomTagTypes()
|
||||
{
|
||||
return customTagTypeCollections;
|
||||
}
|
||||
|
||||
public static void encode(SyncCustomTagTypes msg, FriendlyByteBuf buf)
|
||||
{
|
||||
buf.writeVarInt(msg.customTagTypeCollections.size());
|
||||
msg.customTagTypeCollections.forEach((registryName, modded) -> forgeTagCollectionWrite(buf, registryName, modded.getAllTags()));
|
||||
}
|
||||
|
||||
private static <T> void forgeTagCollectionWrite(FriendlyByteBuf buf, ResourceLocation registryName, Map<ResourceLocation, Tag<T>> tags)
|
||||
{
|
||||
buf.writeResourceLocation(registryName);
|
||||
buf.writeVarInt(tags.size());
|
||||
tags.forEach((name, tag) -> {
|
||||
buf.writeResourceLocation(name);
|
||||
List<T> elements = tag.getValues();
|
||||
buf.writeVarInt(elements.size());
|
||||
for (T element : elements)
|
||||
{
|
||||
buf.writeResourceLocation(((IForgeRegistryEntry<?>) element).getRegistryName());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static SyncCustomTagTypes decode(FriendlyByteBuf buf)
|
||||
{
|
||||
ImmutableMap.Builder<ResourceLocation, TagCollection<?>> 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>> TagCollection<T> readTagCollection(FriendlyByteBuf buf, IForgeRegistry<T> registry)
|
||||
{
|
||||
Map<ResourceLocation, Tag<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, Tag.fromSet(elementBuilder.build()));
|
||||
}
|
||||
return TagCollection.of(tags);
|
||||
}
|
||||
|
||||
public static void handle(SyncCustomTagTypes msg, Supplier<NetworkEvent.Context> ctx)
|
||||
{
|
||||
ctx.get().enqueueWork(() -> {
|
||||
if (Minecraft.getInstance().level != null)
|
||||
{
|
||||
TagContainer tagCollectionSupplier = Minecraft.getInstance().level.getTagManager();
|
||||
//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
|
||||
//Override and use the tags from the packet to test for validation before we actually set them
|
||||
Multimap<ResourceKey<? extends Registry<?>>, ResourceLocation> missingTags = StaticTags.getAllMissingTags(ForgeTagHandler.withSpecificCustom(tagCollectionSupplier, msg.customTagTypeCollections));
|
||||
if (missingTags.isEmpty())
|
||||
{
|
||||
//If we have no missing tags, update the custom tag types
|
||||
ForgeTagHandler.updateCustomTagTypes(msg);
|
||||
if (!ctx.get().getNetworkManager().isMemoryConnection())
|
||||
{
|
||||
//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
|
||||
StaticTags.fetchCustomTagTypes(tagCollectionSupplier);
|
||||
MinecraftForge.EVENT_BUS.post(new TagsUpdatedEvent.CustomTagTypes(tagCollectionSupplier));
|
||||
}
|
||||
} else {
|
||||
LOGGER.warn("Incomplete server tags, disconnecting. Missing: {}", missingTags);
|
||||
ctx.get().getNetworkManager().disconnect(new TranslatableComponent("multiplayer.disconnect.missing_tags"));
|
||||
}
|
||||
}
|
||||
});
|
||||
ctx.get().setPacketHandled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,6 @@ import io.netty.channel.ChannelHandlerContext;
|
||||
import net.minecraft.tags.TagCollection;
|
||||
import net.minecraft.tags.TagContainer;
|
||||
import net.minecraft.network.chat.TextComponent;
|
||||
import net.minecraftforge.common.extensions.IForgeTagContainer;
|
||||
import net.minecraftforge.fml.util.thread.EffectiveSide;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
@@ -234,33 +233,6 @@ public class NetworkHooks
|
||||
MinecraftForge.EVENT_BUS.post(new PlayerContainerEvent.Open(player, c));
|
||||
}
|
||||
|
||||
/**
|
||||
* Syncs the custom tag types attached to a {@link IForgeTagContainer} to all connected players.
|
||||
* @param tagCollectionSupplier The tag collection supplier containing the custom tags
|
||||
*/
|
||||
public static void syncCustomTagTypes(TagContainer tagCollectionSupplier)
|
||||
{
|
||||
Map<ResourceLocation, TagCollection<?>> 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 IForgeTagContainer} 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(ServerPlayer player, TagContainer tagCollectionSupplier)
|
||||
{
|
||||
Map<ResourceLocation, TagCollection<?>> customTagTypes = tagCollectionSupplier.getCustomTagTypes();
|
||||
if (!customTagTypes.isEmpty())
|
||||
{
|
||||
FMLNetworkConstants.playChannel.sendTo(new FMLPlayMessages.SyncCustomTagTypes(customTagTypes), player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT);
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static FMLConnectionData getConnectionData(Connection mgr)
|
||||
{
|
||||
|
||||
@@ -97,19 +97,6 @@ class NetworkInitialization {
|
||||
consumer(FMLPlayMessages.OpenContainer::handle).
|
||||
add();
|
||||
|
||||
//TODO Dimensions..
|
||||
// playChannel.messageBuilder(FMLPlayMessages.DimensionInfoMessage.class, 2)
|
||||
// .decoder(FMLPlayMessages.DimensionInfoMessage::decode)
|
||||
// .encoder(FMLPlayMessages.DimensionInfoMessage::encode)
|
||||
// .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;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,18 +21,25 @@ package net.minecraftforge.network;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
import io.netty.channel.ChannelHandler;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.synchronization.ArgumentTypes;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.protocol.game.ClientboundCommandsPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundUpdateTagsPacket;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagCollection;
|
||||
import net.minecraftforge.common.ForgeTagHandler;
|
||||
import net.minecraftforge.fmllegacy.network.NetworkHooks;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
|
||||
@@ -58,6 +65,7 @@ public class VanillaConnectionNetworkFilter extends VanillaPacketFilter
|
||||
ImmutableMap.<Class<? extends Packet<?>>, BiConsumer<Packet<?>, List<? super Packet<?>>>>builder()
|
||||
.put(handler(ClientboundUpdateAttributesPacket.class, VanillaConnectionNetworkFilter::filterEntityProperties))
|
||||
.put(handler(ClientboundCommandsPacket.class, VanillaConnectionNetworkFilter::filterCommandList))
|
||||
.put(handler(ClientboundUpdateTagsPacket.class, VanillaConnectionNetworkFilter::filterCustomTagTypes))
|
||||
.build()
|
||||
);
|
||||
}
|
||||
@@ -99,4 +107,15 @@ public class VanillaConnectionNetworkFilter extends VanillaPacketFilter
|
||||
});
|
||||
return new ClientboundCommandsPacket(newRoot);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters out custom tag types that the vanilla client won't recognize.
|
||||
* It prevents a rare error from logging and reduces the packet size
|
||||
*/
|
||||
private static ClientboundUpdateTagsPacket filterCustomTagTypes(ClientboundUpdateTagsPacket packet) {
|
||||
Map<ResourceKey<? extends Registry<?>>, TagCollection.NetworkPayload> tags = packet.getTags()
|
||||
.entrySet().stream().filter(e -> !ForgeTagHandler.getCustomTagTypeNames().contains(e.getKey().location()))
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
return new ClientboundUpdateTagsPacket(tags);
|
||||
}
|
||||
}
|
||||
@@ -404,7 +404,7 @@ public class GameData
|
||||
{
|
||||
LOGGER.debug(REGISTRIES, "Registering custom tag type for: {}", registryName);
|
||||
customTagTypes.add(registryName);
|
||||
StaticTags.create(ResourceKey.createRegistryKey(registryName), entry.getValue().getTagFolder());
|
||||
StaticTags.create(ResourceKey.createRegistryKey(registryName), "tags/" + entry.getValue().getTagFolder());
|
||||
}
|
||||
}
|
||||
ForgeTagHandler.setCustomTagTypes(customTagTypes);
|
||||
|
||||
Reference in new issue
Block a user