[1.18.x] Allow Modders to add custom data-pack registries through RegistryBuilder (#8630)

Co-authored-by: Silverminer007 <[email protected]>
Co-authored-by: Curle <[email protected]>
This commit is contained in:
authored and GitHub committed 2022-06-05 15:27:30 +01:00
1 parent 15bd5f0d30
commit 997d8e0aa2
21 files changed
+525 -10

No files matched your search

@@ -7,17 +7,22 @@ package net.minecraftforge.network;
import com.google.common.collect.Multimap;
import com.mojang.authlib.GameProfile;
import net.minecraft.core.Registry;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
import net.minecraft.network.protocol.login.ClientboundCustomQueryPacket;
import net.minecraft.network.protocol.login.ServerboundCustomQueryPacket;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.server.network.ServerLoginPacketListenerImpl;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.LogMessageAdapter;
import net.minecraftforge.event.entity.player.PlayerNegotiationEvent;
import net.minecraftforge.network.simple.SimpleChannel;
import net.minecraftforge.registries.DataPackRegistriesHooks;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.GameData;
import org.apache.logging.log4j.LogManager;
@@ -180,6 +185,23 @@ public class HandshakeHandler
c.get().getNetworkManager().disconnect(new TextComponent("Connection closed - mismatched mod channel list"));
return;
}
// Validate synced custom datapack registries, client cannot be missing any present on the server.
List<String> missingDataPackRegistries = new ArrayList<>();
Set<ResourceKey<? extends Registry<?>>> clientDataPackRegistries = DataPackRegistriesHooks.getSyncedCustomRegistries();
for (ResourceKey<? extends Registry<?>> key : serverModList.getCustomDataPackRegistries())
{
if (!clientDataPackRegistries.contains(key))
{
ResourceLocation location = key.location();
LOGGER.error(FMLHSMARKER, "Missing required datapack registry: {}", location);
missingDataPackRegistries.add(key.location().toString());
}
}
if (!missingDataPackRegistries.isEmpty())
{
c.get().getNetworkManager().disconnect(new TranslatableComponent("fml.menu.multiplayer.missingdatapackregistries", String.join(", ", missingDataPackRegistries)));
return;
}
NetworkConstants.handshakeChannel.reply(new HandshakeMessages.C2SModListReply(), c.get());
LOGGER.debug(FMLHSMARKER, "Accepted server connection");
@@ -5,11 +5,14 @@
package net.minecraftforge.network;
import net.minecraft.core.Registry;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.forgespi.language.IModInfo;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.registries.DataPackRegistriesHooks;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.RegistryManager;
@@ -17,6 +20,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.IntSupplier;
import java.util.stream.Collectors;
@@ -51,19 +55,22 @@ public class HandshakeMessages
private List<String> mods;
private Map<ResourceLocation, String> channels;
private List<ResourceLocation> registries;
private final List<ResourceKey<? extends Registry<?>>> dataPackRegistries;
public S2CModList()
{
this.mods = ModList.get().getMods().stream().map(IModInfo::getModId).collect(Collectors.toList());
this.channels = NetworkRegistry.buildChannelVersions();
this.registries = RegistryManager.getRegistryNamesForSyncToClient();
this.dataPackRegistries = List.copyOf(DataPackRegistriesHooks.getSyncedCustomRegistries());
}
private S2CModList(List<String> mods, Map<ResourceLocation, String> channels, List<ResourceLocation> registries)
private S2CModList(List<String> mods, Map<ResourceLocation, String> channels, List<ResourceLocation> registries, List<ResourceKey<? extends Registry<?>>> dataPackRegistries)
{
this.mods = mods;
this.channels = channels;
this.registries = registries;
this.dataPackRegistries = dataPackRegistries;
}
public static S2CModList decode(FriendlyByteBuf input)
@@ -83,7 +90,12 @@ public class HandshakeMessages
for (int x = 0; x < len; x++)
registries.add(input.readResourceLocation());
return new S2CModList(mods, channels, registries);
// Datapack Registries may or may not be sent in 1.18.2 due to netcode changes.
// TODO 1.19: Remove optionalness of datapack registry list in the mod list packet.
List<ResourceKey<? extends Registry<?>>> dataPackRegistries = input.isReadable()
? input.readCollection(ArrayList::new, buf -> ResourceKey.createRegistryKey(buf.readResourceLocation()))
: List.of();
return new S2CModList(mods, channels, registries, dataPackRegistries);
}
public void encode(FriendlyByteBuf output)
@@ -99,6 +111,14 @@ public class HandshakeMessages
output.writeVarInt(registries.size());
registries.forEach(output::writeResourceLocation);
// The list of synced datapack registry names is not sent in 1.18.2 if the list is empty.
// TODO 1.19: should send an empty list if the list is empty.
Set<ResourceKey<? extends Registry<?>>> dataPackRegistries = DataPackRegistriesHooks.getSyncedCustomRegistries();
if (!dataPackRegistries.isEmpty())
{
output.writeCollection(dataPackRegistries, (buf,key) -> buf.writeResourceLocation(key.location()));
}
}
public List<String> getModList() {
@@ -112,6 +132,13 @@ public class HandshakeMessages
public Map<ResourceLocation, String> getChannels() {
return this.channels;
}
/**
* @return list of ids of non-vanilla syncable datapack registries on the server.
*/
public List<ResourceKey<? extends Registry<?>>> getCustomDataPackRegistries() {
return this.dataPackRegistries;
}
}
public static class C2SModListReply extends LoginIndexedMessage
@@ -8,6 +8,7 @@ package net.minecraftforge.network;
import io.netty.util.AttributeKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fml.IExtensionPoint.DisplayTest;
import net.minecraftforge.network.HandshakeMessages.S2CModList;
import net.minecraftforge.network.event.EventNetworkChannel;
import net.minecraftforge.network.simple.SimpleChannel;
import org.apache.logging.log4j.Marker;
@@ -20,7 +21,10 @@ import java.util.List;
public class NetworkConstants
{
public static final String FMLNETMARKER = "FML";
public static final int FMLNETVERSION = 2;
/**
* Netversion 3: {@link S2CModList} packet may include a list of non-vanilla synced datapack registry ids.
*/
public static final int FMLNETVERSION = 3;
public static final String NETVERSION = FMLNETMARKER + FMLNETVERSION;
public static final String NOVERSION = "NONE";
@@ -10,6 +10,8 @@ import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.network.event.EventNetworkChannel;
import net.minecraftforge.network.simple.SimpleChannel;
import net.minecraftforge.registries.DataPackRegistriesHooks;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -80,7 +82,7 @@ public class NetworkRegistry
}
public static boolean acceptsVanillaClientConnections() {
return instances.isEmpty() || getServerNonVanillaNetworkMods().isEmpty();
return (instances.isEmpty() || getServerNonVanillaNetworkMods().isEmpty()) && DataPackRegistriesHooks.getSyncedCustomRegistries().isEmpty();
}
public static boolean canConnectToVanillaServer() {
@@ -0,0 +1,60 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.registries;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import com.google.common.collect.ImmutableMap;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.ResourceKey;
@ApiStatus.Internal
public final class DataPackRegistriesHooks
{
private DataPackRegistriesHooks() {} // utility class
private static Map<ResourceKey<? extends Registry<?>>, RegistryAccess.RegistryData<?>> REGISTRY_ACCESS_REGISTRIES_COPY;
private static final Set<ResourceKey<? extends Registry<?>>> SYNCED_CUSTOM_REGISTRIES = new HashSet<>();
private static final Set<ResourceKey<? extends Registry<?>>> SYNCED_CUSTOM_REGISTRIES_VIEW = Collections.unmodifiableSet(SYNCED_CUSTOM_REGISTRIES);
/* Internal forge hook for retaining mutable access to RegistryAccess's codec registry when it bootstraps. */
public static Map<ResourceKey<? extends Registry<?>>, RegistryAccess.RegistryData<?>> grabBuiltinRegistries(ImmutableMap.Builder<ResourceKey<? extends Registry<?>>, RegistryAccess.RegistryData<?>> builder)
{
REGISTRY_ACCESS_REGISTRIES_COPY = new HashMap<>(builder.build());
SYNCED_CUSTOM_REGISTRIES.clear();
return Collections.unmodifiableMap(REGISTRY_ACCESS_REGISTRIES_COPY);
}
/* Internal forge method, registers a datapack registry codec and folder. */
public static <T> void addRegistryCodec(@NotNull RegistryAccess.RegistryData<T> data)
{
ResourceKey<? extends Registry<T>> registryKey = data.key();
REGISTRY_ACCESS_REGISTRIES_COPY.put(registryKey, data);
if (data.networkCodec() != null)
{
SYNCED_CUSTOM_REGISTRIES.add(registryKey);
}
}
/**
* {@return unmodifiable view of the set of synced non-vanilla datapack registry IDs}
* Clients must have each of a server's synced datapack registries to be able to connect to that server;
* vanilla clients therefore cannot connect if this list is non-empty on the server.
*/
public static Set<ResourceKey<? extends Registry<?>>> getSyncedCustomRegistries()
{
return SYNCED_CUSTOM_REGISTRIES_VIEW;
}
}
@@ -7,6 +7,8 @@ package net.minecraftforge.registries;
import com.mojang.logging.LogUtils;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.data.BuiltinRegistries;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.event.IModBusEvent;
import org.jetbrains.annotations.Nullable;
@@ -76,7 +78,16 @@ public class NewRegistryEvent extends Event implements IModBusEvent
builtRegistries.forEach((builder, reg) -> {
try
{
if (builder.getHasWrapper() && !Registry.REGISTRY.containsKey(reg.getRegistryName()))
RegistryAccess.RegistryData<?> dataPackRegistryData = builder.getDataPackRegistryData();
if (dataPackRegistryData != null) // if this is a datapack registry
{
if (!BuiltinRegistries.REGISTRY.containsKey(reg.getRegistryName()))
{
DataPackRegistriesHooks.addRegistryCodec(dataPackRegistryData);
RegistryManager.registerToBuiltinRegistry((ForgeRegistry<?>) reg);
}
}
else if (builder.getHasWrapper() && !Registry.REGISTRY.containsKey(reg.getRegistryName()))
RegistryManager.registerToRootRegistry((ForgeRegistry<?>) reg);
} catch (Exception e)
{
@@ -9,10 +9,17 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.Lists;
import com.mojang.serialization.Codec;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.IForgeRegistry.*;
@@ -38,6 +45,7 @@ public class RegistryBuilder<T extends IForgeRegistryEntry<T>>
private boolean allowOverrides = true;
private boolean allowModifications = false;
private boolean hasWrapper = false;
private Supplier<RegistryAccess.RegistryData<T>> dataPackRegistryData = () -> null; // If present, implies this is a datapack registry.
private DummyFactory<T> dummyFactory;
private MissingFactory<T> missingFactory;
private Set<ResourceLocation> legacyNames = new HashSet<>();
@@ -175,6 +183,11 @@ public class RegistryBuilder<T extends IForgeRegistryEntry<T>>
return this;
}
/**
* Prevents the registry from being synced to clients. Does *not* affect datapack registries, datapack registries are unsynced by default
* unless a non-null network codec is registered via {@link #dataPackRegistry(Codec, Codec)}
* @return this
*/
public RegistryBuilder<T> disableSync()
{
this.sync = false;
@@ -230,6 +243,66 @@ public class RegistryBuilder<T extends IForgeRegistryEntry<T>>
return this;
}
/**
* <p>Register this registry as an unsynced datapack registry, which will cause data to be loaded from
* a datapack folder based on the registry's name. The mod that registers this registry does not need to exist
* on the client to connect to servers with the mod/registry.</p>
* <p>Data JSONs will be loaded from {@code data/<datapack_namespace>/modid/registryname/}, where modid is the mod that registered this registry.</p>
*
* @param codec the codec to be used for loading data from datapacks on servers
* @return this builder
*
* @see #dataPackRegistry(Codec, Codec)
*/
public RegistryBuilder<T> dataPackRegistry(Codec<T> codec)
{
return this.dataPackRegistry(codec, null);
}
/**
* <p>Register this registry as a datapack registry, which will cause data to be loaded from
* a datapack folder based on the registry's name.</p>
* <p>Data JSONs will be loaded from {@code data/<datapack_namespace>/modid/registryname/}, where modid is the mod that registered this registry.</p>
*
* @param codec the codec to be used for loading data from datapacks on servers
* @param networkCodec the codec to be used for syncing loaded data to clients.<br>
* If networkCodec is null, data will not be synced, and clients without the mod that registered this registry can
* connect to servers with the mod.<br>
* If networkCodec is not null, then data will be synced (accessible via {@link ClientPacketListener#registryAccess()}),
* and the mod must be present on a client to connect to servers with the mod.
* @return this builder
*
* @see #dataPackRegistry(Codec)
*/
public RegistryBuilder<T> dataPackRegistry(Codec<T> codec, @Nullable Codec<T> networkCodec)
{
this.hasWrapper(); // A wrapper is required for data pack registries.
this.disableSync(); // Datapack registries are synced using a different system than static registries.
// Supplier averts having to set the registry name before calling this.
this.dataPackRegistryData = Suppliers.memoize(() -> {
// Validate registry key.
if (this.registryName == null)
throw new IllegalStateException("Registry builder cannot build a datapack registry: registry name not set");
ResourceKey<Registry<T>> registryKey = ResourceKey.createRegistryKey(this.registryName);
return new RegistryAccess.RegistryData<>(registryKey, codec, networkCodec);
});
return this;
}
/**
* Retrieves datapack registry information, if any.
*
* @return RegistryData containing the registry's key and codec(s). If returned data is null, this has not been marked as a datapack registry.
*
* @throws IllegalStateException if this has been marked as a datapack registry, but registry name has not been set.
*/
@Nullable
RegistryAccess.RegistryData<T> getDataPackRegistryData()
{
return this.dataPackRegistryData.get();
}
/**
* Modders: Use {@link NewRegistryEvent#create(RegistryBuilder)} instead
*/
@@ -22,6 +22,7 @@ import com.google.common.collect.Sets.SetView;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.WritableRegistry;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.core.Registry;
@@ -161,10 +162,20 @@ public class RegistryManager
return getRegistry(name);
}
@SuppressWarnings("unchecked")
static <V extends IForgeRegistryEntry<V>> void registerToRootRegistry(ForgeRegistry<V> forgeReg)
{
WritableRegistry<Registry<V>> registry = (WritableRegistry<Registry<V>>) Registry.REGISTRY;
injectForgeRegistry(forgeReg, Registry.REGISTRY);
}
static <V extends IForgeRegistryEntry<V>> void registerToBuiltinRegistry(ForgeRegistry<V> forgeReg)
{
injectForgeRegistry(forgeReg, BuiltinRegistries.REGISTRY);
}
@SuppressWarnings("unchecked")
private static <V extends IForgeRegistryEntry<V>> void injectForgeRegistry(ForgeRegistry<V> forgeReg, Registry<? extends Registry<?>> rootRegistry)
{
WritableRegistry<Registry<V>> registry = (WritableRegistry<Registry<V>>) rootRegistry;
Registry<V> wrapper = forgeReg.getWrapper();
if (wrapper != null)
registry.register(forgeReg.getRegistryKey(), wrapper, Lifecycle.experimental());
@@ -11,10 +11,12 @@ import java.nio.file.Path;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import net.minecraft.core.Registry;
import net.minecraft.gametest.framework.GameTestServer;
import net.minecraft.server.packs.repository.PackSource;
import net.minecraft.server.packs.repository.RepositorySource;
@@ -41,6 +43,7 @@ import net.minecraft.network.Connection;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.packs.repository.Pack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.network.chat.TextComponent;
@@ -55,6 +58,7 @@ import net.minecraftforge.event.server.ServerStoppedEvent;
import net.minecraftforge.event.server.ServerStoppingEvent;
import net.minecraftforge.fml.loading.FileUtils;
import net.minecraftforge.forgespi.language.IModInfo;
import net.minecraftforge.registries.DataPackRegistriesHooks;
import net.minecraftforge.registries.GameData;
public class ServerLifecycleHooks
@@ -147,9 +151,25 @@ public class ServerLifecycleHooks
final ConnectionType connectionType = ConnectionType.forVersionFlag(packet.getFMLVersion());
final int versionNumber = connectionType.getFMLVersionNumber(packet.getFMLVersion());
if (connectionType == ConnectionType.MODDED && versionNumber != NetworkConstants.FMLNETVERSION) {
rejectConnection(manager, connectionType, "This modded server is not impl compatible with your modded client. Please verify your Forge version closely matches the server. Got net version "+ versionNumber + " this server is net version "+ NetworkConstants.FMLNETVERSION);
return false;
if (connectionType == ConnectionType.MODDED)
{
// Allow clients with incorrect netcode version to connect to netversion 3 servers,
// if and only if client is netversion 2 and server has no syncable non-vanilla datapack registries.
// TODO 1.19: Remove netcode backwards-compatability in 1.19, as there will be no clients on netversion 2 in 1.19.
Set<ResourceKey<? extends Registry<?>>> customDatapackRegistries = DataPackRegistriesHooks.getSyncedCustomRegistries();
if (versionNumber == 2)
{
if (!customDatapackRegistries.isEmpty())
{
rejectConnection(manager, connectionType, "Missing required datapack registries: " + String.join(", ", customDatapackRegistries.stream().map(key -> key.location().toString()).toList()));
return false;
}
}
else if (versionNumber != NetworkConstants.FMLNETVERSION)
{
rejectConnection(manager, connectionType, "This modded server is not impl compatible with your modded client. Please verify your Forge version closely matches the server. Got net version "+ versionNumber + " this server is net version "+ NetworkConstants.FMLNETVERSION);
return false;
}
}
if (connectionType == ConnectionType.VANILLA && !NetworkRegistry.acceptsVanillaClientConnections()) {