Update SimpleChannel to make StreamCodecs easier (#9959)

Rework networking so that RegistryFriendlyByteBuf is useable for modders
Simple support for StreamCodec in SimpleChannel
Codecify all Forge packets
Make simpler builder pattern for SimpleChannel. Will eventually deprecate the old MessageBuilder as it's verbose and poorly written.

Co-authored-by: MrCrayfish <[email protected]>
Co-authored-by: Paint_Ninja <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-05-07 22:53:14 -07:00
1 parent 0e28336fc0
commit 8848294210
44 files changed
+989 -348

No files matched your search

@@ -100,6 +100,7 @@ import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraft.network.syncher.EntityDataSerializer;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket;
@@ -114,7 +115,6 @@ import net.minecraft.world.level.biome.BiomeGenerationSettings;
import net.minecraft.world.level.biome.MobSpawnSettings;
import net.minecraftforge.common.crafting.conditions.ConditionCodec;
import net.minecraftforge.common.crafting.conditions.ICondition;
import net.minecraftforge.common.crafting.conditions.ICondition.IContext;
import net.minecraftforge.common.crafting.ingredients.IIngredientSerializer;
import net.minecraftforge.common.util.BlockSnapshot;
import net.minecraftforge.common.util.BrainBuilder;
@@ -155,6 +155,7 @@ import net.minecraftforge.event.level.NoteBlockEvent;
import net.minecraftforge.event.network.CustomPayloadEvent;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.ModLoader;
import net.minecraftforge.fml.config.ConfigTracker;
@@ -164,6 +165,7 @@ import net.minecraftforge.network.ICustomPacket;
import net.minecraftforge.network.NetworkContext;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkInitialization;
import net.minecraftforge.network.NetworkProtocol;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.packets.SpawnEntity;
import net.minecraftforge.resource.ResourcePackLoader;
@@ -1121,13 +1123,14 @@ public final class ForgeHooks {
}
@ApiStatus.Internal
public static boolean onCustomPayload(final ICustomPacket<?> packet, final Connection connection) {
if (packet.getDirection().getReceptionSide() != EffectiveSide.get()) {
public static boolean onCustomPayload(ICustomPacket<?> packet, Connection connection) {
var expectedSide = connection.getReceiving() == PacketFlow.CLIENTBOUND ? LogicalSide.CLIENT : LogicalSide.SERVER;
if (expectedSide != EffectiveSide.get()) {
connection.disconnect(Component.literal("Illegal packet received, terminating connection"));
return false;
}
var context = new CustomPayloadEvent.Context(connection, packet.getDirection());
var context = new CustomPayloadEvent.Context(connection);
return onCustomPayload(new CustomPayloadEvent(packet, context));
}
@@ -1155,17 +1158,13 @@ public final class ForgeHooks {
LOGGER.info("Connected to a modded server.");
}
@SuppressWarnings("unchecked")
@ApiStatus.Internal
public static Packet<ClientGamePacketListener> getEntitySpawnPacket(Entity entity) {
if (!(entity instanceof IEntityAdditionalSpawnData add))
throw new IllegalArgumentException(entity.getClass() + " is not an instance of " + IEntityAdditionalSpawnData.class);
var play = NetworkInitialization.PLAY;
var msg = new SpawnEntity(entity);
var data = play.toBuffer(msg);
@SuppressWarnings("unchecked")
var pkt = (Packet<ClientGamePacketListener>)NetworkDirection.PLAY_TO_CLIENT.buildPacket(data, play.getName()).getThis();
return pkt;
return (Packet<ClientGamePacketListener>)NetworkDirection.PLAY_TO_CLIENT.buildPacket(NetworkInitialization.PLAY, new SpawnEntity(entity));
}
@ApiStatus.Internal
@@ -16,34 +16,41 @@ import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
public class LogicalSidedProvider<T>
{
import org.jetbrains.annotations.ApiStatus;
public class LogicalSidedProvider<T> {
public static final LogicalSidedProvider<BlockableEventLoop<? super TickTask>> WORKQUEUE = new LogicalSidedProvider<>(Supplier::get, Supplier::get);
public static final LogicalSidedProvider<Optional<Level>> CLIENTWORLD = new LogicalSidedProvider<>((c)-> Optional.of(c.get().level), (s)->Optional.empty());
public T get(LogicalSide side) {
return side == LogicalSide.CLIENT ? clientSide.apply(client) : serverSide.apply(server);
}
public T get(boolean client) {
return get(client ? LogicalSide.CLIENT : LogicalSide.SERVER);
}
// =========================================
// Everything below this is internal
// =========================================
private static Supplier<Minecraft> client;
private static Supplier<MinecraftServer> server;
// INTERNAL, DO NOT CALL
public static void setClient(Supplier<Minecraft> client)
{
@ApiStatus.Internal
public static void setClient(Supplier<Minecraft> client) {
LogicalSidedProvider.client = client;
}
public static void setServer(Supplier<MinecraftServer> server)
{
@ApiStatus.Internal
public static void setServer(Supplier<MinecraftServer> server) {
LogicalSidedProvider.server = server;
}
private LogicalSidedProvider(Function<Supplier<Minecraft>, T> clientSide, Function<Supplier<MinecraftServer>, T> serverSide)
{
private LogicalSidedProvider(Function<Supplier<Minecraft>, T> clientSide, Function<Supplier<MinecraftServer>, T> serverSide) {
this.clientSide = clientSide;
this.serverSide = serverSide;
}
private final Function<Supplier<Minecraft>, T> clientSide;
private final Function<Supplier<MinecraftServer>, T> serverSide;
public T get(final LogicalSide side) {
return side==LogicalSide.CLIENT ? clientSide.apply(client) : serverSide.apply(server);
}
}
@@ -10,9 +10,7 @@ import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import io.netty.buffer.Unpooled;
import net.minecraft.network.Connection;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket;
@@ -48,7 +46,7 @@ public class PacketLogger {
enabled = false;
if (packet instanceof ICustomPacket custom && custom.getInternalData() != null) {
LOGGER.info(MARKER, "{} {} {}\n{}", side(side), dir(flow), packet.getClass().getName(), HexDumper.dump(custom.getInternalData()));
LOGGER.info(MARKER, "{} {} {} {}\n{}", side(side), dir(flow), packet.getClass().getName(), custom.getName(), HexDumper.dump(custom.getInternalData()));
} else {
LOGGER.info(MARKER, "{} {} {}", side(side), dir(flow), packet.getClass().getName());
}
@@ -15,10 +15,8 @@ import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.network.Connection;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.util.thread.BlockableEventLoop;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.network.ICustomPacket;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.common.util.LogicalSidedProvider;
import org.jetbrains.annotations.Nullable;
@@ -67,31 +65,23 @@ public class CustomPayloadEvent extends Event {
* The {@link Connection} for this message.
*/
private final Connection connection;
/**
* The {@link NetworkDirection} this message has been received on.
*/
private final NetworkDirection networkDirection;
private final boolean client;
private boolean packetHandled;
public Context(Connection connection, NetworkDirection networkDirection) {
public Context(Connection connection) {
this.connection = connection;
this.networkDirection = networkDirection;
this.client = connection.getReceiving() == PacketFlow.CLIENTBOUND;
}
public boolean isClientSide() {
return getConnection().getReceiving() == PacketFlow.CLIENTBOUND;
return client;
}
public boolean isServerSide() {
return !isClientSide();
}
public NetworkDirection getDirection() {
return networkDirection;
}
public Connection getConnection() {
return connection;
}
@@ -109,7 +99,8 @@ public class CustomPayloadEvent extends Event {
}
public CompletableFuture<Void> enqueueWork(Runnable runnable) {
BlockableEventLoop<?> executor = LogicalSidedProvider.WORKQUEUE.get(getDirection().getReceptionSide());
var executor = LogicalSidedProvider.WORKQUEUE.get(isClientSide());
// Must check ourselves as Minecraft will sometimes delay tasks even when they are received on the client thread
// Same logic as ThreadTaskExecutor#runImmediately without the join
if (!executor.isSameThread())
@@ -38,29 +38,24 @@ public abstract class Channel<MSG> {
return NetworkContext.get(connection).getRemoteChannels().contains(getName());
}
public abstract FriendlyByteBuf toBuffer(MSG message);
public abstract void encode(FriendlyByteBuf out, MSG message);
// Package private so we can call from ourselves.
Packet<?> toVanillaPacket(Connection connection, MSG message) {
protected Packet<?> toVanillaPacket(Connection connection, MSG message) {
var protocol = connection.getProtocol();
var serverbound = connection.getSending() == PacketFlow.SERVERBOUND;
var data = toBuffer(message);
var handler = switch (protocol) {
case LOGIN -> NetworkProtocol.LOGIN;
case CONFIGURATION -> NetworkProtocol.CONFIGURATION;
case PLAY -> NetworkProtocol.PLAY;
default -> throw new IllegalStateException("Unsupported protocol " + protocol.name() + " in Forge Networking Channel");
};
if (protocol == ConnectionProtocol.LOGIN) {
// Login Protocol C->S packets do not contain the plugin channel name. As they are meant to be replies.
// So fuck it lets just wrap in our own packet that DOES include the channel name
if (serverbound) {
if (this != NetworkInitialization.LOGIN)
return NetworkInitialization.LOGIN.toVanillaPacket(connection, new LoginWrapper(getName(), data));
else
return NetworkDirection.LOGIN_TO_SERVER.buildPacket(data, getName()).getThis();
}
return NetworkDirection.LOGIN_TO_CLIENT.buildPacket(data, getName()).getThis();
} else if (protocol == ConnectionProtocol.PLAY || protocol == ConnectionProtocol.CONFIGURATION) {
var dir = serverbound ? NetworkDirection.PLAY_TO_SERVER : NetworkDirection.PLAY_TO_CLIENT;
return dir.buildPacket(data, getName()).getThis();
} else
throw new IllegalStateException("Unsupported protocol " + protocol.name() + " in Forge Networking Channel");
// Login Protocol C->S packets do not contain the plugin channel name. As they are meant to be replies.
// So fuck it lets just wrap in our own packet that DOES include the channel name
if (protocol == ConnectionProtocol.LOGIN && this != NetworkInitialization.LOGIN && connection.getSending() == PacketFlow.SERVERBOUND)
return NetworkInitialization.LOGIN.toVanillaPacket(connection, new LoginWrapper(this, message));
return handler.buildPacket(connection.getSending(), this, message).getThis();
}
public void send(MSG msg, Connection connection) {
@@ -79,7 +74,7 @@ public abstract class Channel<MSG> {
* @param <MSG> The type of the message
*/
public void send(MSG msg, PacketDistributor.PacketTarget target) {
target.send(target.direction().buildPacket(toBuffer(msg), getName()).getThis());
target.send(target.direction().buildPacket(this, msg).getThis());
}
public void reply(MSG msg, CustomPayloadEvent.Context context) {
@@ -42,7 +42,7 @@ public class EventNetworkChannel extends Channel<FriendlyByteBuf> {
}
@Override
public FriendlyByteBuf toBuffer(FriendlyByteBuf message) {
return message;
public void encode(FriendlyByteBuf out, FriendlyByteBuf message) {
out.writeBytes(message.slice());
}
}
@@ -73,7 +73,7 @@ public class ForgePacketHandler {
}
void handleLoginWrapper(LoginWrapper msg, CustomPayloadEvent.Context ctx) {
ForgeHooks.onCustomPayload(new CustomPayloadEvent(msg.channel(), msg.data(), ctx, -1));
ForgeHooks.onCustomPayload(new CustomPayloadEvent(msg.name(), msg.data(), ctx, -1));
}
void handleClientAck(Acknowledge msg, CustomPayloadEvent.Context ctx) {
@@ -96,7 +96,7 @@ public class ForgePacketHandler {
nctx.modList.putAll(list.mods());
if (ctx.isClientSide()) {
NetworkInitialization.PLAY.send(ModVersions.create(), ctx.getConnection());
NetworkInitialization.CONFIG.send(ModVersions.create(), ctx.getConnection());
/*
* Set the modded marker on the channel so we know we got packets
* TODO: NETWORKING: Move modded marker to it's own handler? Its here just because this is the first packet sent from the server to the client
@@ -121,14 +121,14 @@ public class ForgePacketHandler {
nctx.mismatchData = new NetworkMismatchData(invalid.mismatched(), invalid.missing(), invalid.fromServer(), nctx.getModList());
if (ctx.isServerSide())
NetworkInitialization.PLAY.reply(new MismatchData(nctx.mismatchData), ctx);
NetworkInitialization.CONFIG.reply(new MismatchData(nctx.mismatchData), ctx);
ctx.getConnection().disconnect(Component.literal("Connection closed - mismatched mod channel list"));
return;
}
if (ctx.isClientSide())
NetworkInitialization.PLAY.send(new ChannelVersions(), ctx.getConnection());
NetworkInitialization.CONFIG.send(new ChannelVersions(), ctx.getConnection());
else
nctx.finishTask(ChannelVersionsTask.TYPE);
@@ -162,7 +162,7 @@ public class ForgePacketHandler {
return;
}
NetworkInitialization.PLAY.reply(new Acknowledge(list.token()), ctx);
NetworkInitialization.CONFIG.reply(new Acknowledge(list.token()), ctx);
this.registriesToReceive = new HashSet<>(list.normal());
this.registrySnapshots.clear();
@@ -187,7 +187,7 @@ public class ForgePacketHandler {
if (!continueHandshake)
LOGGER.error(MARKER, "Connection closed, not continuing handshake");
else
NetworkInitialization.PLAY.reply(new Acknowledge(msg.token()), ctx);
NetworkInitialization.CONFIG.reply(new Acknowledge(msg.token()), ctx);
}
private boolean handleRegistryLoading(CustomPayloadEvent.Context ctx) {
@@ -24,10 +24,6 @@ public interface ICustomPacket<T extends Packet<?>> {
int getIndex();
default NetworkDirection getDirection() {
return NetworkDirection.directionFor(this.getClass());
}
@SuppressWarnings("unchecked")
default T getThis() {
return (T)this;
@@ -5,88 +5,20 @@
package net.minecraftforge.network;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceArrayMap;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket;
import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket;
import net.minecraft.network.protocol.common.custom.DiscardedPayload;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.login.ClientboundCustomQueryPacket;
import net.minecraft.network.protocol.login.ServerboundCustomQueryAnswerPacket;
import net.minecraft.network.protocol.login.custom.DiscardedQueryAnswerPayload;
import net.minecraft.network.protocol.login.custom.DiscardedQueryPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fml.LogicalSide;
import net.minecraft.network.RegistryFriendlyByteBuf;
@SuppressWarnings("rawtypes")
public enum NetworkDirection {
PLAY_TO_SERVER(LogicalSide.CLIENT, ServerboundCustomPayloadPacket.class, 1, NetworkDirection::playServerbound),
PLAY_TO_CLIENT(LogicalSide.SERVER, ClientboundCustomPayloadPacket.class, 0, NetworkDirection::playClientbound),
LOGIN_TO_SERVER(LogicalSide.CLIENT, ServerboundCustomQueryAnswerPacket.class, 3, NetworkDirection::loginServerbound),
LOGIN_TO_CLIENT(LogicalSide.SERVER, ClientboundCustomQueryPacket.class, 2, NetworkDirection::loginClientbound);
public record NetworkDirection<B extends FriendlyByteBuf>(NetworkProtocol<B> protocol, PacketFlow direction) {
public static final NetworkDirection<RegistryFriendlyByteBuf> PLAY_TO_CLIENT = new NetworkDirection<>(NetworkProtocol.PLAY, PacketFlow.CLIENTBOUND);
public static final NetworkDirection<RegistryFriendlyByteBuf> PLAY_TO_SERVER = new NetworkDirection<>(NetworkProtocol.PLAY, PacketFlow.SERVERBOUND);
public static final NetworkDirection<FriendlyByteBuf> LOGIN_TO_CLIENT = new NetworkDirection<>(NetworkProtocol.LOGIN, PacketFlow.CLIENTBOUND);
public static final NetworkDirection<FriendlyByteBuf> LOGIN_TO_SERVER = new NetworkDirection<>(NetworkProtocol.LOGIN, PacketFlow.SERVERBOUND);
public static final NetworkDirection<FriendlyByteBuf> CONFIGURATION_TO_CLIENT = new NetworkDirection<>(NetworkProtocol.CONFIGURATION, PacketFlow.CLIENTBOUND);
public static final NetworkDirection<FriendlyByteBuf> CONFIGURATION_TO_SERVER = new NetworkDirection<>(NetworkProtocol.CONFIGURATION, PacketFlow.SERVERBOUND);
private final LogicalSide logicalSide;
private final Class<? extends Packet> packetClass;
private final int otherWay;
private final Factory factory;
private static final Reference2ReferenceArrayMap<Class<? extends Packet>, NetworkDirection> packetLookup = new Reference2ReferenceArrayMap<>();
private static final NetworkDirection[] values = values();
static {
for (var value : values)
packetLookup.put(value.getPacketClass(), value);
}
private NetworkDirection(LogicalSide logicalSide, Class<? extends Packet> clazz, int i, Factory factory) {
this.logicalSide = logicalSide;
this.packetClass = clazz;
this.otherWay = i;
this.factory = factory;
}
private Class<? extends Packet> getPacketClass() {
return packetClass;
}
public static <T extends ICustomPacket<?>> NetworkDirection directionFor(Class<T> customPacket) {
return packetLookup.get(customPacket);
}
public NetworkDirection reply() {
return values[this.otherWay];
}
public LogicalSide getOriginationSide() {
return logicalSide;
}
public LogicalSide getReceptionSide() {
return reply().logicalSide;
}
@SuppressWarnings("unchecked")
public <T extends Packet<?>> ICustomPacket<T> buildPacket(FriendlyByteBuf data, ResourceLocation channelName) {
return this.factory.create(data, 0, channelName);
}
private interface Factory<T extends Packet<?>> {
ICustomPacket<T> create(FriendlyByteBuf data, Integer index, ResourceLocation channelName);
}
private static ServerboundCustomPayloadPacket playServerbound(FriendlyByteBuf data, Integer index, ResourceLocation channelName) {
return new ServerboundCustomPayloadPacket(new DiscardedPayload(channelName, data));
}
private static ClientboundCustomPayloadPacket playClientbound(FriendlyByteBuf data, Integer index, ResourceLocation channelName) {
return new ClientboundCustomPayloadPacket(new DiscardedPayload(channelName, data));
}
private static ServerboundCustomQueryAnswerPacket loginServerbound(FriendlyByteBuf data, Integer index, ResourceLocation channelName) {
return new ServerboundCustomQueryAnswerPacket(index, new DiscardedQueryAnswerPayload(data));
}
private static ClientboundCustomQueryPacket loginClientbound(FriendlyByteBuf data, Integer index, ResourceLocation channelName) {
return new ClientboundCustomQueryPacket(index, new DiscardedQueryPayload(channelName, data));
public <T extends Packet<?>, MSG> ICustomPacket<T> buildPacket(Channel<MSG> channel, MSG packet) {
return this.protocol().buildPacket(this.direction(), channel, packet);
}
}
@@ -5,113 +5,79 @@
package net.minecraftforge.network;
import io.netty.util.AttributeKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.event.network.CustomPayloadEvent;
import net.minecraftforge.network.packets.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import org.jetbrains.annotations.ApiStatus;
import io.netty.util.AttributeKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.network.packets.Acknowledge;
import net.minecraftforge.network.packets.ChannelVersions;
import net.minecraftforge.network.packets.LoginWrapper;
import net.minecraftforge.network.packets.OpenContainer;
import net.minecraftforge.network.packets.RegistryList;
import net.minecraftforge.network.packets.RegistryData;
import net.minecraftforge.network.packets.ConfigData;
import net.minecraftforge.network.packets.MismatchData;
import net.minecraftforge.network.packets.ModVersions;
import net.minecraftforge.network.packets.SpawnEntity;
import java.util.function.BiConsumer;
@ApiStatus.Internal
public class NetworkInitialization {
public final class NetworkInitialization {
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker MARKER = MarkerManager.getMarker("FORGE_NETWORK");
public static final ResourceLocation LOGIN_NAME = new ResourceLocation("forge", "login");
public static final ResourceLocation HANDSHAKE_NAME = new ResourceLocation("forge", "handshake");
public static final ResourceLocation PLAY_NAME = new ResourceLocation("forge", "play");
private static final ResourceLocation HANDSHAKE_NAME = new ResourceLocation("forge", "handshake");
private static final ResourceLocation PLAY_NAME = new ResourceLocation("forge", "network");
public static final AttributeKey<ForgePacketHandler> CONTEXT = AttributeKey.newInstance(HANDSHAKE_NAME.toString());
public static SimpleChannel LOGIN = ChannelBuilder
public static final SimpleChannel LOGIN = ChannelBuilder
.named(LOGIN_NAME)
.optional()
.networkProtocolVersion(0)
.attribute(CONTEXT, ForgePacketHandler::new) // Shared across all of our channels
.simpleChannel()
.login()
.serverbound()
.add(LoginWrapper.class, LoginWrapper.STREAM_CODEC, ctx(ForgePacketHandler::handleLoginWrapper))
.build();
.messageBuilder(LoginWrapper.class)
.decoder(LoginWrapper::decode)
.encoder(LoginWrapper::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleLoginWrapper)
.add();
public static SimpleChannel PLAY = ChannelBuilder
public static final SimpleChannel CONFIG = ChannelBuilder
.named(HANDSHAKE_NAME)
.optional()
.networkProtocolVersion(0)
.attribute(CONTEXT, ForgePacketHandler::new)
.simpleChannel()
.configuration()
.serverbound()
.add(Acknowledge.class, Acknowledge.STREAM_CODEC, ctx(ForgePacketHandler::handleClientAck))
.bidirectional()
.add(ModVersions.class, ModVersions.STREAM_CODEC, ctx(ForgePacketHandler::handleModVersions))
.add(ChannelVersions.class, ChannelVersions.STREAM_CODEC, ctx(ForgePacketHandler::handleChannelVersions))
.clientbound()
.add(RegistryList.class, RegistryList.STREAM_CODEC, ctx(ForgePacketHandler::handleRegistryList))
.add(RegistryData.class, RegistryData.STREAM_CODEC, ctx(ForgePacketHandler::handleRegistryData))
.add(ConfigData.class, ConfigData.STREAM_CODEC, ctx(ForgePacketHandler::handleConfigSync))
.add(MismatchData.class, MismatchData.STREAM_CODEC, ctx(ForgePacketHandler::handleModMismatchData))
.play() // TODO: Move to it's own channel, so that we can keep the core handshake channel clean/simple and thus not need to bump the version ever As it is the one responsible for validating versions
.clientbound()
.add(SpawnEntity.class, SpawnEntity.STREAM_CODEC, SpawnEntity::handle)
.add(OpenContainer.class, OpenContainer.STREAM_CODEC, OpenContainer::handle)
.build();
.messageBuilder(Acknowledge.class, NetworkDirection.PLAY_TO_SERVER)
.decoder(Acknowledge::decode)
.encoder(Acknowledge::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleClientAck)
.add()
.messageBuilder(ModVersions.class)
.decoder(ModVersions::decode)
.encoder(ModVersions::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleModVersions)
.add()
.messageBuilder(ChannelVersions.class)
.decoder(ChannelVersions::decode)
.encoder(ChannelVersions::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleChannelVersions)
.add()
.messageBuilder(RegistryList.class, NetworkDirection.PLAY_TO_CLIENT)
.decoder(RegistryList::decode)
.encoder(RegistryList::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleRegistryList)
.add()
.messageBuilder(RegistryData.class, NetworkDirection.PLAY_TO_CLIENT)
.decoder(RegistryData::decode)
.encoder(RegistryData::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleRegistryData)
.add()
.messageBuilder(ConfigData.class, NetworkDirection.PLAY_TO_CLIENT)
.decoder(ConfigData::decode)
.encoder(ConfigData::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleConfigSync)
.add()
.messageBuilder(MismatchData.class, NetworkDirection.PLAY_TO_CLIENT)
.decoder(MismatchData::decode)
.encoder(MismatchData::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleModMismatchData)
.add()
.messageBuilder(SpawnEntity.class, NetworkDirection.PLAY_TO_CLIENT)
.decoder(SpawnEntity::decode)
.encoder(SpawnEntity::encode)
.consumerMainThread(SpawnEntity::handle)
.add()
.messageBuilder(OpenContainer.class)
.decoder(OpenContainer::decode)
.encoder(OpenContainer::encode)
.consumerMainThread(OpenContainer::handle)
.add();
public static final SimpleChannel PLAY = CONFIG;;
public static void init() {
for (var channel : new Channel[]{ LOGIN, PLAY, ChannelListManager.REGISTER, ChannelListManager.UNREGISTER})
for (var channel : new Channel[]{ LOGIN, CONFIG, PLAY, ChannelListManager.REGISTER, ChannelListManager.UNREGISTER})
LOGGER.debug(MARKER, "Registering Network {} v{}", channel.getName(), channel.getProtocolVersion());
}
public static int getVersion() {
return PLAY.getProtocolVersion();
return CONFIG.getProtocolVersion();
}
private interface Handler<MSG> {
void handle(ForgePacketHandler handler, MSG msg, CustomPayloadEvent.Context ctx);
}
private static <MSG> BiConsumer<MSG, CustomPayloadEvent.Context> ctx(Handler<MSG> handler) {
return (msg, ctx) -> {
var inst = ctx.getConnection().channel().attr(CONTEXT).get();
handler.handle(inst, msg, ctx);
};
}
}
@@ -27,8 +27,10 @@ import io.netty.util.AttributeKey;
* as the internal API and {@link Channel} as the public.
*/
@ApiStatus.Internal
public class NetworkInstance {
private final IEventBus networkEventBus; // TODO: Evaluate why we even use event bus for this...
public final class NetworkInstance {
// We use an event bus here so that we don't have to have a handle(event) public function on Channel.
// Should this be changed so that modders can fire other channel's handlers?
private final IEventBus networkEventBus;
private final ResourceLocation channelName;
private final int networkProtocolVersion;
final VersionTest clientAcceptedVersions;
@@ -0,0 +1,66 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket;
import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket;
import net.minecraft.network.protocol.common.custom.DiscardedPayload;
import java.util.function.Consumer;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.protocol.login.ClientboundCustomQueryPacket;
import net.minecraft.network.protocol.login.ServerboundCustomQueryAnswerPacket;
import net.minecraft.network.protocol.login.custom.DiscardedQueryAnswerPayload;
import net.minecraft.network.protocol.login.custom.DiscardedQueryPayload;
public class NetworkProtocol<B extends FriendlyByteBuf> {
public static final NetworkProtocol<RegistryFriendlyByteBuf> PLAY = new NetworkProtocol<>(ConnectionProtocol.PLAY);
public static final NetworkProtocol<FriendlyByteBuf> LOGIN = new NetworkProtocol<>(ConnectionProtocol.LOGIN);
public static final NetworkProtocol<FriendlyByteBuf> CONFIGURATION = new NetworkProtocol<>(ConnectionProtocol.CONFIGURATION);
private final ConnectionProtocol protocol;
private NetworkProtocol(ConnectionProtocol protocol) {
this.protocol = protocol;
}
@Override
public String toString() {
return this.protocol.name();
}
public ConnectionProtocol toVanilla() {
return this.protocol;
}
@SuppressWarnings("unchecked")
public <T extends Packet<?>, MSG> ICustomPacket<T> buildPacket(PacketFlow direction, Channel<MSG> channel, MSG packet) {
var name = channel.getName();
var encoder = (Consumer<FriendlyByteBuf>)(buf -> channel.encode(buf, packet));
switch (this.protocol) {
case PLAY, CONFIGURATION:
if (direction == PacketFlow.CLIENTBOUND)
return (ICustomPacket<T>)new ClientboundCustomPayloadPacket(new DiscardedPayload(name, null, encoder));
else
return (ICustomPacket<T>)new ServerboundCustomPayloadPacket(new DiscardedPayload(name, null, encoder));
case LOGIN:
if (direction == PacketFlow.CLIENTBOUND)
return (ICustomPacket<T>)new ClientboundCustomQueryPacket(0, new DiscardedQueryPayload(name, null, encoder));
else
return (ICustomPacket<T>)new ServerboundCustomQueryAnswerPacket(0, new DiscardedQueryAnswerPayload(null, encoder));
default:
throw new IllegalArgumentException("Invalid protocol, shouldn't be possible as this is a private class..");
}
}
}
@@ -29,55 +29,63 @@ import org.jetbrains.annotations.Nullable;
*
* @param <T>
*/
public record PacketDistributor<T>(BiFunction<PacketDistributor<T>, T, Consumer<Packet<?>>> functor, NetworkDirection direction) {
public record PacketDistributor<T>(BiFunction<PacketDistributor<T>, T, Consumer<Packet<?>>> functor, NetworkDirection<?> direction) {
/**
* Send to the player specified in the Supplier
* <br/>
* {@link #with(T)} Player
*/
public static final PacketDistributor<ServerPlayer> PLAYER = new PacketDistributor<>(PacketDistributor::playerConsumer);
/**
* Send to everyone in the dimension specified in the Supplier
* <br/>
* {@link #with(T)} DimensionType
*/
public static final PacketDistributor<ResourceKey<Level>> DIMENSION = new PacketDistributor<>(PacketDistributor::playerListDimConsumer);
/**
* Send to everyone near the {@link TargetPoint} specified in the Supplier
* <br/>
* {@link #with(T)} TargetPoint
*/
public static final PacketDistributor<TargetPoint> NEAR = new PacketDistributor<>(PacketDistributor::playerListPointConsumer);
/**
* Send to everyone
* <br/>
* {@link #noArg()}
*/
public static final PacketDistributor<Void> ALL = new PacketDistributor<>(PacketDistributor::playerListAll);
/**
* Send to the server (CLIENT to SERVER)
* <br/>
* {@link #noArg()}
*/
public static final PacketDistributor<Void> SERVER = new PacketDistributor<>(PacketDistributor::clientToServer, NetworkDirection.PLAY_TO_SERVER);
/**
* Send to all tracking the Entity in the Supplier
* <br/>
* {@link #with(T)} Entity
*/
public static final PacketDistributor<Entity> TRACKING_ENTITY = new PacketDistributor<>(PacketDistributor::trackingEntity);
/**
* Send to all tracking the Entity and Player in the Supplier
* <br/>
* {@link #with(T)} Entity
*/
public static final PacketDistributor<Entity> TRACKING_ENTITY_AND_SELF = new PacketDistributor<>(PacketDistributor::trackingEntityAndSelf);
/**
* Send to all tracking the Chunk in the Supplier
* <br/>
* {@link #with(T)} Chunk
*/
public static final PacketDistributor<LevelChunk> TRACKING_CHUNK = new PacketDistributor<>(PacketDistributor::trackingChunk);
/**
* Send to the supplied list of NetworkManager instances in the Supplier
* <br/>
@@ -99,7 +107,7 @@ public record PacketDistributor<T>(BiFunction<PacketDistributor<T>, T, Consumer<
*
* @see Channel#send(Object, PacketTarget)
*/
public record PacketTarget(Consumer<Packet<?>> packetConsumer, NetworkDirection direction) {
public record PacketTarget(Consumer<Packet<?>> packetConsumer, NetworkDirection<?> direction) {
public void send(Packet<?> packet) {
packetConsumer.accept(packet);
}
@@ -5,14 +5,26 @@
package net.minecraftforge.network;
import io.netty.util.AttributeKey;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.minecraft.network.Connection;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraftforge.event.network.CustomPayloadEvent;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Function;
import net.minecraftforge.event.network.CustomPayloadEvent.Context;
import net.minecraftforge.network.simple.handler.SimpleHandlerFlow;
import net.minecraftforge.network.simple.handler.SimpleHandlerProtocol;
import net.minecraftforge.network.simple.handler.SimplePacket;
import net.minecraftforge.network.simple.SimpleBuildable;
import net.minecraftforge.network.simple.SimpleConnection;
import net.minecraftforge.network.simple.SimpleFlow;
import net.minecraftforge.network.simple.SimpleProtocol;
import org.apache.commons.lang3.function.TriConsumer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -21,16 +33,13 @@ import org.apache.logging.log4j.MarkerManager;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import io.netty.buffer.Unpooled;
import io.netty.util.AttributeKey;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import java.util.function.BiConsumer;
import java.util.function.Function;
public class SimpleChannel extends Channel<Object> {
public class SimpleChannel extends Channel<Object> implements SimpleConnection<Object> {
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker MARKER = MarkerManager.getMarker("SIMPLE_CHANNEL");
private boolean built = false;
@ApiStatus.Internal
SimpleChannel(NetworkInstance instance) {
@@ -38,13 +47,23 @@ public class SimpleChannel extends Channel<Object> {
instance.addListener(this::networkEventListener);
}
@Override
public <NEWBUF extends FriendlyByteBuf, NEWBASE> SimpleProtocol<NEWBUF, NEWBASE> protocol(NetworkProtocol<NEWBUF> protocol) {
return new Protocol<>(new SimpleContext<NEWBUF, NEWBASE>(this).protocol(protocol));
}
@Override
public <NEWBUF extends FriendlyByteBuf, CTX, NEWBASE extends SimplePacket<CTX>> SimpleHandlerProtocol<NEWBUF, NEWBASE> protocol(AttributeKey<CTX> context, NetworkProtocol<NEWBUF> protocol) {
return new HandlerProtocol<>(context, new SimpleContext<NEWBUF, NEWBASE>(this).protocol(protocol));
}
/**
* Build a new MessageBuilder, using the next available discriminator.
*
* @param type Type of message
* @param <M> Type of type
*/
public <M> MessageBuilder<M> messageBuilder(final Class<M> type) {
public <M> MessageBuilder<M, FriendlyByteBuf> messageBuilder(Class<M> type) {
return messageBuilder(type, nextIndex());
}
@@ -55,8 +74,19 @@ public class SimpleChannel extends Channel<Object> {
* @param discriminator Manually configured discriminator, Must be a positive number.
* @param <M> Type of type
*/
public <M> MessageBuilder<M> messageBuilder(final Class<M> type, int discriminator) {
return messageBuilder(type, discriminator, null);
public <M> MessageBuilder<M, FriendlyByteBuf> messageBuilder(Class<M> type, int discriminator) {
return messageBuilder(type, discriminator, (NetworkProtocol<FriendlyByteBuf>)null);
}
/**
* Build a new MessageBuilder, using the next available discriminator.
*
* @param type Type of message
* @param protocol The protocol that this packet is allowed to be sent/received in, Use enforce strict state handling to prevent spoofing.
* @param <M> Type of type
*/
public <M, B extends FriendlyByteBuf> MessageBuilder<M, B> messageBuilder(Class<M> type, NetworkProtocol<B> protocol) {
return messageBuilder(type, nextIndex(), protocol);
}
/**
@@ -67,8 +97,21 @@ public class SimpleChannel extends Channel<Object> {
* enforce strict sided handling to prevent spoofing.
* @param <M> Type of type
*/
public <M> MessageBuilder<M> messageBuilder(final Class<M> type, NetworkDirection direction) {
return messageBuilder(type, nextIndex(), direction);
public <M, B extends FriendlyByteBuf> MessageBuilder<M, B> messageBuilder(Class<M> type, NetworkDirection<B> direction) {
return messageBuilder(type, nextIndex(), direction.protocol()).direction(direction.direction());
}
/**
* Build a new MessageBuilder, using the next available discriminator.
*
* @param type Type of message
* @param discriminator Manually configured discriminator, Must be a positive number.
* @param protocol The protocol that this packet is allowed to be sent/received in, Use enforce strict state handling to prevent spoofing.
* @param <M> Type of type
*/
public <M, B extends FriendlyByteBuf> MessageBuilder<M, B> messageBuilder(Class<M> type, int discriminator, NetworkProtocol<B> protocol) {
checkBuilt();
return new MessageBuilder<>(this, type, discriminator, protocol);
}
/**
@@ -80,41 +123,68 @@ public class SimpleChannel extends Channel<Object> {
* enforce strict sided handling to prevent spoofing.
* @param <M> Type of type
*/
public <M> MessageBuilder<M> messageBuilder(final Class<M> type, int discriminator, NetworkDirection direction) {
return new MessageBuilder<>(this, type, discriminator, direction);
public <M, B extends FriendlyByteBuf> MessageBuilder<M, B> messageBuilder(Class<M> type, int discriminator, NetworkDirection<B> direction) {
return messageBuilder(type, discriminator, direction.protocol()).direction(direction.direction());
}
public static class MessageBuilder<MSG> {
/**
* Finishes off the builder side of the SimpleChanel. This prevents adding more messages to this channel.
*/
public SimpleChannel build() {
checkBuilt();
this.built = true;
return this;
}
protected void checkBuilt() {
if (built)
throw new IllegalStateException("SimpleChannel builder is fully built, can not modify it any more");
}
public static class MessageBuilder<MSG, BUF extends FriendlyByteBuf> {
private final SimpleChannel channel;
private final Class<MSG> type;
private final int id;
private final Optional<NetworkDirection> direction;
private final NetworkProtocol<BUF> protocol;
private BiConsumer<MSG, FriendlyByteBuf> encoder;
private Function<FriendlyByteBuf, MSG> decoder;
private BiConsumer<MSG, BUF> encoder;
private Function<BUF, MSG> decoder;
private BiConsumer<MSG, CustomPayloadEvent.Context> consumer;
private PacketFlow direction;
private MessageBuilder(final SimpleChannel channel, final Class<MSG> type, int id, @Nullable NetworkDirection networkDirection) {
private MessageBuilder(SimpleChannel channel, Class<MSG> type, int id, @Nullable NetworkProtocol<BUF> protocol) {
this.channel = channel;
this.type = type;
this.id = id;
this.direction = Optional.ofNullable(networkDirection);
this.protocol = protocol;
}
/**
* Set the direction that this packet is allowed to be sent/received.
* Use to enforce strict sided handling to prevent spoofing.
*
* @param direction The direction this packet is allowed on.
* @return This message builder, for chaining.
*/
public MessageBuilder<MSG, BUF> direction(PacketFlow direction) {
this.direction = direction;
return this;
}
/**
* Set the message encoder, which writes this message to a {@link FriendlyByteBuf}.
* <p>
* The encoder is called <em>immediately</em> {@linkplain #send(PacketDistributor.PacketTarget, Object) when the
* The encoder is called <em>immediately</em> {@linkplain #send(Object, PacketDistributor.PacketTarget)} when the
* packet is sent}. This means encoding typically occurs on the main server/client thread rather than on the
* network thread.
* <p>
* However, this behaviour should not be relied on, and the encoder should try to be thread-safe and not
* However, this behavior should not be relied on, and the encoder should try to be thread-safe and not
* interact with the current game state.
*
* @param encoder The message encoder.
* @return This message builder, for chaining.
*/
public MessageBuilder<MSG> encoder(BiConsumer<MSG, FriendlyByteBuf> encoder) {
public MessageBuilder<MSG, BUF> encoder(BiConsumer<MSG, BUF> encoder) {
this.encoder = encoder;
return this;
}
@@ -123,17 +193,50 @@ public class SimpleChannel extends Channel<Object> {
* Set the message decoder, which reads the message from a {@link FriendlyByteBuf}.
* <p>
* The decoder is called when the message is received on the network thread. The decoder should not attempt to
* access or mutate any game state, deferring that until the {@linkplain #consumer(ToBooleanBiFunction) the
* access or mutate any game state, deferring that until the {@linkplain #consumer(BiConsumer) the
* message is handled}.
*
* @param decoder The message decoder.
* @return The message builder, for chaining.
*/
public MessageBuilder<MSG> decoder(Function<FriendlyByteBuf, MSG> decoder) {
public MessageBuilder<MSG, BUF> decoder(Function<BUF, MSG> decoder) {
this.decoder = decoder;
return this;
}
/**
* Set the StreamCodec to be used for marshaling the message object to and from a {@link FriendlyByteBuf}
* <p>
* This has all the same limitations of {@link #encoder(BiConsumer)} and {@link #decoder(Function)} as it is equivalent of calling those functions
* with the codec's encode and decode functions.
*
* @param codec The codec to use.
* @return The message builder, for chaining.
*/
public MessageBuilder<MSG, BUF> codec(StreamCodec<BUF, MSG> codec) {
return this.encoder((msg, buf) -> codec.encode(buf, msg))
.decoder(codec::decode);
}
/**
* Set the message consumer, which is called once a message has been decoded. This accepts the decoded message
* object and the message's context.
* <p>
* The consumer is called on the network thread, and so should not interact with most game state by default.
* {@link CustomPayloadEvent.Context#enqueueWork(Runnable)} can be used to handle the message on the main server or
* client thread. Alternatively one can use {@link #consumerMainThread(BiConsumer)} to run the handler on the
* main thread.
*
* @param consumer The message consumer.
* @return The message builder, for chaining.
*
* @see #consumerMainThread(BiConsumer)
*/
public MessageBuilder<MSG, BUF> consumer(BiConsumer<MSG, CustomPayloadEvent.Context> consumer) {
this.consumer = consumer;
return this;
}
/**
* Set the message consumer, which is called once a message has been decoded. This accepts the decoded message
* object and the message's context.
@@ -148,9 +251,8 @@ public class SimpleChannel extends Channel<Object> {
*
* @see #consumerMainThread(BiConsumer)
*/
public MessageBuilder<MSG> consumerNetworkThread(BiConsumer<MSG, CustomPayloadEvent.Context> consumer) {
this.consumer = consumer;
return this;
public MessageBuilder<MSG, BUF> consumerNetworkThread(BiConsumer<MSG, CustomPayloadEvent.Context> consumer) {
return this.consumer(consumer);
}
/**
@@ -160,7 +262,7 @@ public class SimpleChannel extends Channel<Object> {
* <p>
* The consumer is called on the network thread, and so should not interact with most game state by default.
* {@link CustomPayloadEvent.Context#enqueueWork(Runnable)} can be used to handle the message on the main server or
* client thread. Alternatively one can use {@link #consumerMainThread(TriConsumer)} to run the handler on the
* client thread. Alternatively one can use {@link #consumerMainThread(BiConsumer)} to run the handler on the
* main thread.
*
* @param consumer The message consumer.
@@ -168,7 +270,7 @@ public class SimpleChannel extends Channel<Object> {
*
* @see #consumerMainThread(BiConsumer)
*/
public <C> MessageBuilder<MSG> consumerNetworkThread(AttributeKey<C> key, TriConsumer<C, MSG, CustomPayloadEvent.Context> consumer) {
public <C> MessageBuilder<MSG, BUF> consumerNetworkThread(AttributeKey<C> key, TriConsumer<C, MSG, CustomPayloadEvent.Context> consumer) {
return consumerNetworkThread((msg, ctx) -> {
var inst = ctx.getConnection().channel().attr(key).get();
consumer.accept(inst, msg, ctx);
@@ -180,7 +282,7 @@ public class SimpleChannel extends Channel<Object> {
*
* @see #consumerNetworkThread(BiConsumer)
*/
public MessageBuilder<MSG> consumerNetworkThread(ToBooleanBiFunction<MSG, CustomPayloadEvent.Context> handler) {
public MessageBuilder<MSG, BUF> consumerNetworkThread(ToBooleanBiFunction<MSG, CustomPayloadEvent.Context> handler) {
this.consumer = (msg, ctx) -> ctx.setPacketHandled(handler.applyAsBool(msg, ctx));
return this;
}
@@ -190,7 +292,7 @@ public class SimpleChannel extends Channel<Object> {
*
* @see #consumerNetworkThread(AttributeKey,TriConsumer)
*/
public <C> MessageBuilder<MSG> consumerNetworkThread(AttributeKey<C> key, ToBooleanTriFunction<C, MSG, CustomPayloadEvent.Context> handler) {
public <C> MessageBuilder<MSG, BUF> consumerNetworkThread(AttributeKey<C> key, ToBooleanTriFunction<C, MSG, CustomPayloadEvent.Context> handler) {
return consumerNetworkThread((msg, ctx) -> {
var inst = ctx.getConnection().channel().attr(key).get();
return handler.applyAsBool(inst, msg, ctx);
@@ -209,7 +311,7 @@ public class SimpleChannel extends Channel<Object> {
*
* @see #consumerNetworkThread(BiConsumer)
*/
public MessageBuilder<MSG> consumerMainThread(BiConsumer<MSG, CustomPayloadEvent.Context> consumer) {
public MessageBuilder<MSG, BUF> consumerMainThread(BiConsumer<MSG, CustomPayloadEvent.Context> consumer) {
this.consumer = (msg, context) -> {
var ctx = context;
ctx.enqueueWork(() -> consumer.accept(msg, context));
@@ -231,7 +333,7 @@ public class SimpleChannel extends Channel<Object> {
*
* @see #consumerNetworkThread(BiConsumer)
*/
public <C> MessageBuilder<MSG> consumerMainThread(AttributeKey<C> key, TriConsumer<C, MSG, CustomPayloadEvent.Context> consumer) {
public <C> MessageBuilder<MSG, BUF> consumerMainThread(AttributeKey<C> key, TriConsumer<C, MSG, CustomPayloadEvent.Context> consumer) {
this.consumer = (msg, ctx) -> {
ctx.enqueueWork(() -> {
var inst = ctx.getConnection().channel().attr(key).get();
@@ -257,10 +359,15 @@ public class SimpleChannel extends Channel<Object> {
* @return The attached SimpleChannel to facilitate chaining.
*/
public SimpleChannel add() {
channel.checkBuilt();
if (this.id < 0)
throw new IllegalStateException("Failed to register SimpleChannel message, Invalid ID " + this.id + ": " + this.type.getName());
var msg = new Message<>(this.id, this.type, this.direction, this.encoder, this.decoder, this.consumer);
var msg = new Message<MSG, BUF>(
this.id, this.type, this.protocol, this.direction,
this.encoder, this.decoder, this.consumer
);
if (channel.byId.containsKey(msg.index()))
throw new IllegalStateException("Failed to register SimpleChannel message, ID " + msg.index() + " already claimed: " + msg.type().getName());
@@ -269,28 +376,136 @@ public class SimpleChannel extends Channel<Object> {
channel.byId.put(msg.index(), msg);
channel.byType.put(msg.type(), msg);
return this.channel;
}
}
private record SimpleContext<BUF extends FriendlyByteBuf, BASE>(SimpleChannel channel, @Nullable NetworkProtocol<BUF> protocol, @Nullable PacketFlow flow) {
public SimpleContext(SimpleChannel channel) {
this(channel, null, null);
}
public <NEWBUF extends FriendlyByteBuf> SimpleContext<NEWBUF, BASE> protocol(NetworkProtocol<NEWBUF> protocol) {
return new SimpleContext<>(channel, protocol, flow);
}
private SimpleContext<BUF, BASE> flow(@Nullable PacketFlow flow) {
return new SimpleContext<>(channel, protocol, flow);
}
}
private record Protocol<BUF extends FriendlyByteBuf, BASE>(SimpleContext<BUF, BASE> ctx) implements ProtocolFactory<BUF, BASE>, SimpleProtocol<BUF, BASE> {
@Override
public SimpleFlow<BUF, BASE> flow(@Nullable PacketFlow flow) {
return new Flow<>(ctx.flow(flow));
}
}
private record HandlerProtocol<BUF extends FriendlyByteBuf, CTX, BASE extends SimplePacket<CTX>>(
AttributeKey<CTX> key,
SimpleContext<BUF, BASE> ctx
) implements ProtocolFactory<BUF, BASE>, SimpleHandlerProtocol<BUF, BASE> {
@Override
public SimpleHandlerFlow<BUF, BASE> flow(@Nullable PacketFlow flow) {
return new HandlerFlow<>(key, ctx.flow(flow));
}
}
private record Flow<BUF extends FriendlyByteBuf, BASE>(SimpleContext<BUF, BASE> ctx) implements ProtocolFactory<BUF, BASE>, SimpleFlow<BUF, BASE> {
@Override
public <MSG extends BASE> Flow<BUF, BASE> add(Class<MSG> type, StreamCodec<BUF, MSG> codec, BiConsumer<MSG, Context> handler) {
ctx.channel.messageBuilder(type, ctx.protocol)
.codec(codec)
.consumer(handler)
.direction(ctx.flow())
.add();
return this;
}
@Override
public SimpleFlow<BUF, BASE> flow(@Nullable PacketFlow flow) {
return new Flow<>(ctx.flow(flow));
}
}
private record HandlerFlow<BUF extends FriendlyByteBuf, CTX, BASE extends SimplePacket<CTX>>(
AttributeKey<CTX> key,
SimpleContext<BUF, BASE> ctx
) implements ProtocolFactory<BUF, BASE>, SimpleHandlerFlow<BUF, BASE> {
@Override
public <MSG extends BASE> SimpleHandlerFlow<BUF, BASE> add(Class<MSG> type, StreamCodec<BUF, MSG> codec) {
return this.add(type, codec, (msg, ctx) -> {
var inst = ctx.getConnection().channel().attr(key).get();
ctx.setPacketHandled(msg.handle(inst, ctx));
});
}
@Override
public <MSG extends BASE> SimpleHandlerFlow<BUF, BASE> addMain(Class<MSG> type, StreamCodec<BUF, MSG> codec) {
return this.add(type, codec, (msg, ctx) -> {
ctx.enqueueWork(() -> {
var inst = ctx.getConnection().channel().attr(key).get();
msg.handle(inst, ctx);
});
ctx.setPacketHandled(true);
});
}
@Override
public <MSG extends BASE> SimpleHandlerFlow<BUF, BASE> add(Class<MSG> type, StreamCodec<BUF, MSG> codec, BiConsumer<MSG, Context> handler) {
ctx.channel.messageBuilder(type, ctx.protocol)
.codec(codec)
.consumer(handler)
.direction(ctx.flow())
.add();
return this;
}
@Override
public SimpleHandlerFlow<BUF, BASE> flow(@Nullable PacketFlow flow) {
return new HandlerFlow<>(key, ctx.flow(flow));
}
}
private interface ProtocolFactory<BUF extends FriendlyByteBuf, BASE> extends SimpleConnection<BASE>, SimpleBuildable {
SimpleContext<BUF, BASE> ctx();
@Override
default <NEWBUF extends FriendlyByteBuf, NEWBASE> SimpleProtocol<NEWBUF, NEWBASE> protocol(NetworkProtocol<NEWBUF> protocol) {
return ctx().channel.protocol(protocol);
}
@Override
default <NEWBUF extends FriendlyByteBuf, CTX, NEWBASE extends SimplePacket<CTX>> SimpleHandlerProtocol<NEWBUF, NEWBASE> protocol(AttributeKey<CTX> context, NetworkProtocol<NEWBUF> protocol) {
return ctx().channel.protocol(context, protocol);
}
@Override
default SimpleChannel build() {
return ctx().channel.build();
}
}
/* ===================================================================================
* INTERNAL BELOW THIS
* ===================================================================================
*/
private int lastIndex = 0;
private Int2ObjectMap<Message<?>> byId = new Int2ObjectArrayMap<>();
private Object2ObjectMap<Class<?>, Message<?>> byType = new Object2ObjectArrayMap<>();
protected int lastIndex = 0;
protected Int2ObjectMap<Message<?, ?>> byId = new Int2ObjectArrayMap<>();
protected Object2ObjectMap<Class<?>, Message<?, ?>> byType = new Object2ObjectArrayMap<>();
private record Message<MSG>(
protected record Message<MSG, BUF extends FriendlyByteBuf>(
int index,
Class<MSG> type,
Optional<NetworkDirection> direction,
BiConsumer<MSG, FriendlyByteBuf> encoder,
Function<FriendlyByteBuf, MSG> decoder,
NetworkProtocol<BUF> protocol,
PacketFlow direction,
BiConsumer<MSG, BUF> encoder,
Function<BUF, MSG> decoder,
BiConsumer<MSG, CustomPayloadEvent.Context> consumer
){ };
private int nextIndex() {
protected int nextIndex() {
while (byId.containsKey(lastIndex)) {
lastIndex++;
if (lastIndex < 0)
@@ -307,17 +522,22 @@ public class SimpleChannel extends Channel<Object> {
}
int id = data.readVarInt();
var msg = byId.get(id);
@SuppressWarnings("unchecked")
var msg = (Message<?, FriendlyByteBuf>)byId.get(id);
if (msg == null) {
LOGGER.error(MARKER, "Received invalid discriminator {} on channel {}", id, getName());
return;
}
var con = event.getSource().getConnection();
var dir = event.getSource().getDirection();
var protocol = msg.protocol() == null ? con.getProtocol() : msg.protocol().toVanilla();
var direction = msg.direction() == null ? con.getReceiving() : msg.direction();
if (protocol != con.getProtocol() || direction != con.getReceiving()) {
var error = "Illegal packet received, terminating connection. " + msg.type().getName() + " expected " +
direction.name() + " " + protocol.name() + " but was " +
con.getReceiving().name() + " " + con.getProtocol().name();
if (msg.direction.isPresent() && msg.direction.get() != dir) {
var error = "Illegal packet received, terminating connection. " + msg.type().getName() + " expexted " + msg.direction.get() + " but was " + dir;
LOGGER.error(MARKER, error);
con.disconnect(Component.literal(error));
throw new IllegalStateException(error);
@@ -327,25 +547,48 @@ public class SimpleChannel extends Channel<Object> {
}
// Yay generics
private static <MSG> void decodeAndDispatch(FriendlyByteBuf data, CustomPayloadEvent.Context ctx, Message<MSG> msg) {
private static <MSG> void decodeAndDispatch(FriendlyByteBuf data, CustomPayloadEvent.Context ctx, Message<MSG, FriendlyByteBuf> msg) {
var message = msg.decoder().apply(data);
msg.consumer.accept(message, ctx);
}
@SuppressWarnings("unchecked")
@Override
public FriendlyByteBuf toBuffer(Object message) {
protected Packet<?> toVanillaPacket(Connection con, Object message) {
var msg = byType.get(message.getClass());
if (msg == null) {
LOGGER.error(MARKER, "Attempted to send invalid message {} on channel {}", message.getClass().getName(), getName());
throw new IllegalArgumentException("Invalid message " + message.getClass().getName());
}
var ret = new FriendlyByteBuf(Unpooled.buffer());
ret.writeVarInt(msg.index());
if (msg.encoder() != null)
((BiConsumer<Object, FriendlyByteBuf>)msg.encoder()).accept(message, ret);
return ret;
var protocol = msg.protocol() == null ? con.getProtocol() : msg.protocol().toVanilla();
var direction = msg.direction() == null ? con.getSending() : msg.direction();
if (protocol != con.getProtocol() || direction != con.getSending()) {
var error = "Illegal packet sent, terminating connection. " + msg.type().getName() + " expected " +
direction.name() + " " + protocol.name() + " but was " +
con.getSending().name() + " " + con.getProtocol().name();
LOGGER.error(MARKER, error);
con.disconnect(Component.literal(error));
throw new IllegalStateException(error);
}
return super.toVanillaPacket(con, message);
}
@Override
public void encode(FriendlyByteBuf out, Object message) {
@SuppressWarnings("unchecked")
var msg = (Message<Object, FriendlyByteBuf>)byType.get(message.getClass());
if (msg == null) {
LOGGER.error(MARKER, "Attempted to send invalid message {} on channel {}", message.getClass().getName(), getName());
throw new IllegalArgumentException("Invalid message " + message.getClass().getName());
}
out.writeVarInt(msg.index());
if (msg.encoder() != null)
msg.encoder().accept(message, out);
}
}
@@ -6,12 +6,15 @@
package net.minecraftforge.network.packets;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
/*
* A simple packet used to acknowledge that the client has received and processed a message sent by the server.
* The token can be anything, ideally it would an identifier sent from the server.
*/
public record Acknowledge(int token) {
public static StreamCodec<FriendlyByteBuf, Acknowledge> STREAM_CODEC = StreamCodec.ofMember(Acknowledge::encode, Acknowledge::decode);
public void encode(FriendlyByteBuf buf) {
buf.writeVarInt(token);
}
@@ -11,19 +11,22 @@ import org.jetbrains.annotations.NotNull;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.network.NetworkRegistry;
public record ChannelVersions(Map<ResourceLocation, @NotNull Integer> channels) {
public static StreamCodec<FriendlyByteBuf, ChannelVersions> STREAM_CODEC = StreamCodec.ofMember(ChannelVersions::encode, ChannelVersions::decode);
public ChannelVersions() {
this(NetworkRegistry.buildChannelVersions());
}
public static ChannelVersions decode(FriendlyByteBuf buf) {
return new ChannelVersions(buf.readMap(Object2IntOpenHashMap::new, FriendlyByteBuf::readResourceLocation, FriendlyByteBuf::readVarInt));
return new ChannelVersions(buf.readMap(Object2IntOpenHashMap::new, FriendlyByteBuf::readResourceLocation, FriendlyByteBuf::readVarInt));
}
public void encode(FriendlyByteBuf buf) {
buf.writeMap(channels, FriendlyByteBuf::writeResourceLocation, FriendlyByteBuf::writeVarInt);
buf.writeMap(channels, FriendlyByteBuf::writeResourceLocation, FriendlyByteBuf::writeVarInt);
}
}
@@ -6,8 +6,11 @@
package net.minecraftforge.network.packets;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
public record ConfigData(String name, byte[] data) {
public static final StreamCodec<FriendlyByteBuf, ConfigData> STREAM_CODEC = StreamCodec.ofMember(ConfigData::encode, ConfigData::decode);
public void encode(final FriendlyByteBuf buf) {
buf.writeUtf(this.name());
buf.writeByteArray(this.data());
@@ -5,20 +5,52 @@
package net.minecraftforge.network.packets;
import io.netty.buffer.Unpooled;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.network.Channel;
public record LoginWrapper(ResourceLocation channel, FriendlyByteBuf data) {
public static LoginWrapper decode(FriendlyByteBuf buf) {
var channel = buf.readResourceLocation();
var len = buf.readVarInt();
var data = new FriendlyByteBuf(buf.readBytes(len));
return new LoginWrapper(channel, data);
public class LoginWrapper {
public static final StreamCodec<FriendlyByteBuf, LoginWrapper> STREAM_CODEC = StreamCodec.ofMember(LoginWrapper::encode, LoginWrapper::new);
private final ResourceLocation name;
private FriendlyByteBuf data;
private final Channel<Object> channel;
private final Object packet;
public <MSG> LoginWrapper(Channel<MSG> channel, MSG packet) {
this(channel.getName(), null, channel, packet);
}
private LoginWrapper(FriendlyByteBuf buf) {
this(buf.readResourceLocation(), buf.wrap(buf.readBytes(buf.readVarInt())), null, null);
}
@SuppressWarnings("unchecked")
private LoginWrapper(ResourceLocation name, FriendlyByteBuf data, Channel<?> channel, Object packet) {
this.name = name;
this.data = data;
this.channel = (Channel<Object>)channel;
this.packet = packet;
}
public void encode(FriendlyByteBuf buf) {
buf.writeResourceLocation(channel);
buf.writeResourceLocation(name);
if (data == null) {
data = buf.wrap(Unpooled.buffer());
((Channel<Object>)channel).encode(data, packet);
}
buf.writeVarInt(data.readableBytes());
buf.writeBytes(data.slice());
}
public ResourceLocation name() {
return this.name;
}
public FriendlyByteBuf data() {
return this.data;
}
}
@@ -10,6 +10,7 @@ import java.util.Map;
import java.util.Set;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.network.NetworkContext.NetworkMismatchData;
import net.minecraftforge.network.NetworkContext.NetworkMismatchData.Version;
@@ -22,6 +23,7 @@ public record MismatchData(
Map<ResourceLocation, Version> mismatched,
Set<ResourceLocation> missing
) {
public static final StreamCodec<FriendlyByteBuf, MismatchData> STREAM_CODEC = StreamCodec.ofMember(MismatchData::encode, MismatchData::decode);
private static final int MAX_LENGTH = 0x100;
public MismatchData(NetworkMismatchData data) {
@@ -8,6 +8,7 @@ package net.minecraftforge.network.packets;
import java.util.Map;
import java.util.stream.Collectors;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.forgespi.language.IModInfo;
@@ -16,6 +17,8 @@ import net.minecraftforge.forgespi.language.IModInfo;
* The mod data is stored as follows: [modId -> [modName, modVersion]]
*/
public record ModVersions(Map<String, Info> mods) {
public static final StreamCodec<FriendlyByteBuf, ModVersions> STREAM_CODEC = StreamCodec.ofMember(ModVersions::encode, ModVersions::decode);
private static final int MAX_LENGTH = 0x100;
public static ModVersions create() {
@@ -12,14 +12,17 @@ import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.MenuScreens;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentSerialization;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraftforge.event.network.CustomPayloadEvent;
// TODO: Reevaluate if this is needed This is the same as ClientboundOpenScreenPacket packet but allows for additional data
public class OpenContainer {
public static final StreamCodec<RegistryFriendlyByteBuf, OpenContainer> STREAM_CODEC = StreamCodec.ofMember(OpenContainer::encode, OpenContainer::decode);
private final int id;
private final int windowId;
private final Component name;
@@ -27,7 +30,6 @@ public class OpenContainer {
/** Use NetworkHooks.openScreen */
@ApiStatus.Internal
@SuppressWarnings("deprecation")
public OpenContainer(MenuType<?> id, int windowId, Component name, FriendlyByteBuf additionalData) {
this(BuiltInRegistries.MENU.getId(id), windowId, name, additionalData);
}
@@ -75,7 +77,6 @@ public class OpenContainer {
}
}
@SuppressWarnings("deprecation")
public final MenuType<?> getType() {
return BuiltInRegistries.MENU.byId(this.id);
}
@@ -6,10 +6,13 @@
package net.minecraftforge.network.packets;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistry.Snapshot;
public record RegistryData(int token, ResourceLocation name, Snapshot data) {
public static final StreamCodec<FriendlyByteBuf, RegistryData> STREAM_CODEC = StreamCodec.ofMember(RegistryData::encode, RegistryData::decode);
public void encode(FriendlyByteBuf buf) {
buf.writeVarInt(token);
buf.writeResourceLocation(name);
@@ -8,6 +8,7 @@ package net.minecraftforge.network.packets;
import java.util.List;
import net.minecraft.core.Registry;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.DataPackRegistriesHooks;
@@ -18,6 +19,8 @@ public record RegistryList(
List<ResourceLocation> normal,
List<ResourceKey<? extends Registry<?>>> datapacks) {
public static final StreamCodec<FriendlyByteBuf, RegistryList> STREAM_CODEC = StreamCodec.ofMember(RegistryList::encode, RegistryList::decode);
public RegistryList(int token) {
this(token, RegistryManager.getRegistryNamesForSyncToClient(), List.copyOf(DataPackRegistriesHooks.getSyncedCustomRegistries()));
}
@@ -5,7 +5,6 @@
package net.minecraftforge.network.packets;
import java.util.Optional;
import java.util.UUID;
import org.jetbrains.annotations.ApiStatus;
@@ -14,11 +13,12 @@ import io.netty.buffer.Unpooled;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.common.util.LogicalSidedProvider;
import net.minecraftforge.entity.IEntityAdditionalSpawnData;
@@ -34,6 +34,7 @@ import net.minecraftforge.event.network.CustomPayloadEvent;
*/
// TODO: Re-write this packet into something simpler. This is literally just ClientboundAddEntityPacket with an extra byte[]
public class SpawnEntity {
public static final StreamCodec<RegistryFriendlyByteBuf, SpawnEntity> STREAM_CODEC = StreamCodec.ofMember(SpawnEntity::encode, SpawnEntity::decode);
private final Entity entity;
private final int typeId;
private final int entityId;
@@ -43,7 +44,6 @@ public class SpawnEntity {
private final int velX, velY, velZ;
private final FriendlyByteBuf buf;
@SuppressWarnings("deprecation")
@ApiStatus.Internal
public SpawnEntity(Entity e) {
this.entity = e;
@@ -128,9 +128,8 @@ public class SpawnEntity {
public static void handle(SpawnEntity msg, CustomPayloadEvent.Context ctx) {
try {
@SuppressWarnings("deprecation")
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.byId(msg.typeId);
Optional<Level> world = LogicalSidedProvider.CLIENTWORLD.get(ctx.getDirection().getReceptionSide());
var world = LogicalSidedProvider.CLIENTWORLD.get(ctx.isClientSide());
Entity e = world.map(w -> type.customClientSpawn(msg, w)).orElse(null);
if (e == null)
return;
@@ -0,0 +1,74 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.simple;
import net.minecraft.network.protocol.PacketFlow;
import org.jetbrains.annotations.Nullable;
import java.util.function.Consumer;
public interface BaseProtocol<FLOW, PROTOCOL extends BaseProtocol<FLOW, PROTOCOL>> {
FLOW flow(@Nullable PacketFlow flow);
/**
* Consumer version of {@link #flow(PacketFlow)}. The Consumer will immediately be called with the created protocol.
*/
default PROTOCOL flow(@Nullable PacketFlow flow, Consumer<FLOW> consumer) {
consumer.accept(flow(flow));
@SuppressWarnings("unchecked")
var ret = (PROTOCOL)this;
return ret;
}
/**
* Creates a builder that validates both current protocol, and that packets are send from Server to Client
*/
default FLOW clientbound() {
return flow(PacketFlow.CLIENTBOUND);
}
/**
* Consumer version of {@link #clientbound()}. The Consumer will immediately be called with the created flow.
*/
default PROTOCOL clientbound(Consumer<FLOW> consumer) {
return flow(PacketFlow.CLIENTBOUND, consumer);
}
/**
* Creates a builder that validates both current protocol, and that packets are send from Client to Server
*/
default FLOW serverbound() {
return flow(PacketFlow.SERVERBOUND);
}
/**
* Consumer version of {@link #serverbound()}. The Consumer will immediately be called with the created flow.
*/
default PROTOCOL serverbound(Consumer<FLOW> consumer) {
return flow(PacketFlow.SERVERBOUND, consumer);
}
/**
* Creates a builder that validates both current protocol, and that packets are send from either flow
*/
default FLOW bidirectional() {
return flow((PacketFlow)null);
}
/**
* Consumer version of {@link #bidirectional()}. The Consumer will immediately be called with the created flow.
*/
default PROTOCOL bidirectional(Consumer<FLOW> consumer) {
return flow(null, consumer);
}
/**
* An alias for {@link #bidirectional(Consumer)}. The Consumer will immediately be called with the created flow.
*/
default PROTOCOL flow(Consumer<FLOW> consumer) {
return bidirectional(consumer);
}
}
@@ -0,0 +1,16 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.simple;
import net.minecraftforge.network.SimpleChannel;
public interface SimpleBuildable {
/*
* This will build the entire channel, locking any future modifications from happening.
* This should be the LAST call in your builder chain and can only be called once.
*/
SimpleChannel build();
}
@@ -0,0 +1,138 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.simple;
import io.netty.util.AttributeKey;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraftforge.network.NetworkProtocol;
import net.minecraftforge.network.simple.handler.SimpleHandlerProtocol;
import net.minecraftforge.network.simple.handler.SimplePacket;
import java.util.function.Consumer;
public interface SimpleConnection<BASE> {
/**
* Creates a builder grouping together all packets under the same protocol.
* This will validate that the protocol matches before the packet is sent or received.
*/
<NEWBUF extends FriendlyByteBuf, NEWBASE> SimpleProtocol<NEWBUF, NEWBASE> protocol(NetworkProtocol<NEWBUF> protocol);
/**
* Creates a builder grouping together all packets under the same protocol.
* This will validate that the protocol matches before the packet is sent or received.
*/
<NEWBUF extends FriendlyByteBuf, CTX, NEWBASE extends SimplePacket<CTX>> SimpleHandlerProtocol<NEWBUF, NEWBASE> protocol(AttributeKey<CTX> context, NetworkProtocol<NEWBUF> protocol);
/**
* Consumer version of {@link #protocol(NetworkProtocol)}. The Consumer will immediately be called with the created protocol.
*/
default <BUF extends FriendlyByteBuf> SimpleConnection<BASE> protocol(NetworkProtocol<BUF> protocol, Consumer<SimpleProtocol<BUF, BASE>> consumer) {
var tmp = this.<BUF, BASE>protocol(protocol);
consumer.accept(tmp);
return this;
}
/**
* Consumer version of {@link #protocol(AttributeKey,NetworkProtocol)}. The Consumer will immediately be called with the created protocol.
*/
default <BUF extends FriendlyByteBuf, CTX, NEWBASE extends SimplePacket<CTX>> SimpleConnection<BASE> protocol(AttributeKey<CTX> context, NetworkProtocol<BUF> protocol, Consumer<SimpleHandlerProtocol<BUF, NEWBASE>> consumer) {
var tmp = this.<BUF, CTX, NEWBASE>protocol(context, protocol);
consumer.accept(tmp);
return this;
}
/**
* Creates a builder grouping together packets that are only valid when under the Configuration protocol.
* This will validate that the protocol matches before the packet is sent or received.
*/
default SimpleProtocol<FriendlyByteBuf, BASE> configuration() {
return protocol(NetworkProtocol.CONFIGURATION);
}
/**
* Creates a builder grouping together packets that are only valid when under the Configuration protocol.
* This will validate that the protocol matches before the packet is sent or received.
*/
default <CTX, NEWBASE extends SimplePacket<CTX>> SimpleHandlerProtocol<FriendlyByteBuf, NEWBASE> configuration(AttributeKey<CTX> context) {
return protocol(context, NetworkProtocol.CONFIGURATION);
}
/**
* Consumer version of {@link #configuration()}. The Consumer will immediately be called with the created protocol.
*/
default SimpleConnection<BASE> configuration(Consumer<SimpleProtocol<FriendlyByteBuf, BASE>> consumer) {
return protocol(NetworkProtocol.CONFIGURATION, consumer);
}
/**
* Consumer version of {@link #configuration(AttributeKey)}. The Consumer will immediately be called with the created protocol.
*/
default <CTX, NEWBASE extends SimplePacket<CTX>> SimpleConnection<BASE> configuration(AttributeKey<CTX> context, Consumer<SimpleHandlerProtocol<FriendlyByteBuf, NEWBASE>> consumer) {
return protocol(context, NetworkProtocol.CONFIGURATION, consumer);
}
/**
* Creates a builder grouping together packets that are only valid when under the Login protocol.
* This will validate that the protocol matches before the packet is sent or received.
*/
default SimpleProtocol<FriendlyByteBuf, BASE> login() {
return protocol(NetworkProtocol.LOGIN);
}
/**
* Creates a builder grouping together packets that are only valid when under the Login protocol.
* This will validate that the protocol matches before the packet is sent or received.
*/
default <CTX, NEWBASE extends SimplePacket<CTX>> SimpleHandlerProtocol<FriendlyByteBuf, NEWBASE> login(AttributeKey<CTX> context) {
return protocol(context, NetworkProtocol.LOGIN);
}
/**
* Consumer version of {@link #login()}. The Consumer will immediately be called with the created protocol.
*/
default SimpleConnection<BASE> login(Consumer<SimpleProtocol<FriendlyByteBuf, BASE>> consumer) {
return protocol(NetworkProtocol.LOGIN, consumer);
}
/**
* Consumer version of {@link #login(AttributeKey)}. The Consumer will immediately be called with the created protocol.
*/
default <CTX, NEWBASE extends SimplePacket<CTX>> SimpleConnection<BASE> login(AttributeKey<CTX> context, Consumer<SimpleHandlerProtocol<FriendlyByteBuf, NEWBASE>> consumer) {
return protocol(context, NetworkProtocol.LOGIN, consumer);
}
/**
* Creates a builder grouping together packets that are only valid when under the Play protocol.
* This will validate that the protocol matches before the packet is sent or received.
*/
default SimpleProtocol<RegistryFriendlyByteBuf, BASE> play() {
return protocol(NetworkProtocol.PLAY);
}
/**
* Creates a builder grouping together packets that are only valid when under the Login protocol.
* This will validate that the protocol matches before the packet is sent or received.
*/
default <CTX, NEWBASE extends SimplePacket<CTX>> SimpleHandlerProtocol<RegistryFriendlyByteBuf, NEWBASE> play(AttributeKey<CTX> context) {
return protocol(context, NetworkProtocol.PLAY);
}
/**
* Consumer version of {@link #play()}. The Consumer will immediately be called with the created protocol.
*/
default SimpleConnection<BASE> play(Consumer<SimpleProtocol<RegistryFriendlyByteBuf, BASE>> consumer) {
return protocol(NetworkProtocol.PLAY, consumer);
}
/**
* Consumer version of {@link #play(AttributeKey)}. The Consumer will immediately be called with the created protocol.
*/
default <CTX, NEWBASE extends SimplePacket<CTX>> SimpleConnection<BASE> play(AttributeKey<CTX> context, Consumer<SimpleHandlerProtocol<RegistryFriendlyByteBuf, NEWBASE>> consumer) {
return protocol(context, NetworkProtocol.PLAY, consumer);
}
}
@@ -0,0 +1,35 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.simple;
import java.util.function.BiConsumer;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraftforge.event.network.CustomPayloadEvent;
public interface SimpleFlow<BUF extends FriendlyByteBuf, BASE> extends SimpleProtocol<BUF, BASE>, SimpleBuildable {
/**
* Adds a packet to this channel that has it's protocol validated whenever sent or received.
* <p>
* The handler is called on the network thread, and so should not interact with most game state by default.
* {@link CustomPayloadEvent.Context#enqueueWork(Runnable)} can be used to handle the message on the main server or
* client thread.
*/
<MSG extends BASE> SimpleFlow<BUF, BASE> add(Class<MSG> type, StreamCodec<BUF, MSG> codec, BiConsumer<MSG, CustomPayloadEvent.Context> handler);
/**
* Adds a packet to this channel that has it's protocol validated whenever sent or received.
* <p>
* Unlike {@link #add(Class,StreamCodec,BiConsumer)}, the consumer is called on the main thread, and so can
* interact with most game state by default.
*/
default <MSG extends BASE> SimpleFlow<BUF, BASE> addMain(Class<MSG> type, StreamCodec<BUF, MSG> codec, BiConsumer<MSG, CustomPayloadEvent.Context> handler) {
return add(type, codec, (msg, ctx) -> {
ctx.enqueueWork(() -> handler.accept(msg, ctx));
ctx.setPacketHandled(true);
});
}
}
@@ -0,0 +1,14 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.simple;
import net.minecraft.network.FriendlyByteBuf;
/**
* Entry point for a {@link net.minecraftforge.network.SimpleChannel SimpleChannel} protocol without any extra context handler marshaling.
*/
public interface SimpleProtocol<BUF extends FriendlyByteBuf, BASE> extends BaseProtocol<SimpleFlow<BUF, BASE>, SimpleProtocol<BUF, BASE>>, SimpleConnection<BASE> {
}
@@ -0,0 +1,42 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.simple.handler;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraftforge.event.network.CustomPayloadEvent;
import net.minecraftforge.network.simple.SimpleBuildable;
import java.util.function.BiConsumer;
public interface SimpleHandlerFlow<BUF extends FriendlyByteBuf, BASE> extends SimpleHandlerProtocol<BUF, BASE>, SimpleBuildable {
/**
* Adds a packet to this channel that has it's protocol validated whenever sent or received.
* <p>
* The handler is called on the network thread, and so should not interact with most game state by default.
* {@link CustomPayloadEvent.Context#enqueueWork(Runnable)} can be used to handle the message on the main server or
* client thread. Alternatively one can use {@link #addMain(Class, StreamCodec)} to run the handler on the
* main thread.
*/
<MSG extends BASE> SimpleHandlerFlow<BUF, BASE> add(Class<MSG> type, StreamCodec<BUF, MSG> codec);
/**
* Adds a packet to this channel that has it's protocol validated whenever sent or received.
* <p>
* Unlike {@link #add(Class,StreamCodec)}, the consumer is called on the main thread, and so can
* interact with most game state by default.
*/
<MSG extends BASE> SimpleHandlerFlow<BUF, BASE> addMain(Class<MSG> type, StreamCodec<BUF, MSG> codec);
/**
* Adds a packet to this channel that has it's protocol validated whenever sent or received.
* <p>
* The handler is called on the network thread, and so should not interact with most game state by default.
* {@link CustomPayloadEvent.Context#enqueueWork(Runnable)} can be used to handle the message on the main server or
* client thread.
*/
<MSG extends BASE> SimpleHandlerFlow<BUF, BASE> add(Class<MSG> type, StreamCodec<BUF, MSG> codec, BiConsumer<MSG, CustomPayloadEvent.Context> handler);
}
@@ -0,0 +1,19 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.simple.handler;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.simple.BaseProtocol;
import net.minecraftforge.network.simple.SimpleConnection;
/**
* Entry point for a {@link net.minecraftforge.network.SimpleChannel SimpleChannel} protocol that mimics vanilla's
* {@link net.minecraft.network.protocol.Packet Packet} system where every packet must implement
* {@link SimplePacket} and will have their {@link SimplePacket#handle(Object, net.minecraftforge.event.network.CustomPayloadEvent.Context) handle(CTX, Context)}
* method called.
*/
public interface SimpleHandlerProtocol<BUF extends FriendlyByteBuf, BASE> extends BaseProtocol<SimpleHandlerFlow<BUF, BASE>, SimpleHandlerProtocol<BUF, BASE>>, SimpleConnection<BASE> {
}
@@ -0,0 +1,19 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.simple.handler;
import net.minecraftforge.event.network.CustomPayloadEvent;
/**
* Interface that all packets must implement if using the
* {@link net.minecraftforge.network.SimpleChannel#protocol(io.netty.util.AttributeKey,net.minecraftforge.network.NetworkProtocol) SimpleChannel.protocol(AttributeKey, NetworkProtocol)}
* function.
*
* @param <C> The type of the context object
*/
public interface SimplePacket<C> {
boolean handle(C handler, CustomPayloadEvent.Context event);
}
@@ -24,7 +24,7 @@ public class ChannelVersionsTask implements ConfigurationTask {
@Override
public void start(ConfigurationTaskContext ctx) {
NetworkInitialization.PLAY.send(new ChannelVersions(), ctx.getConnection());
NetworkInitialization.CONFIG.send(new ChannelVersions(), ctx.getConnection());
}
@Override
@@ -25,7 +25,7 @@ public class ModVersionsTask implements ConfigurationTask {
@Override
public void start(ConfigurationTaskContext ctx) {
NetworkInitialization.PLAY.send(ModVersions.create(), ctx.getConnection());
NetworkInitialization.CONFIG.send(ModVersions.create(), ctx.getConnection());
}
@Override
@@ -35,7 +35,7 @@ class SyncConfigTask extends SimpleConfigurationTask {
for (var cfg : ConfigTracker.INSTANCE.configSets().get(ModConfig.Type.SERVER)) {
try {
var pkt = new ConfigData(cfg.getFileName(), Files.readAllBytes(cfg.getFullPath()));
NetworkInitialization.PLAY.send(pkt, ctx.getConnection());
NetworkInitialization.CONFIG.send(pkt, ctx.getConnection());
} catch (IOException e) {
LOGGER.error(MARKER, "Failed to read config file {} terminating connection", cfg.getFileName(), e);
ctx.getConnection().disconnect(Component.literal("Connection closed - Failed to read config on server"));
@@ -5,9 +5,6 @@
package net.minecraftforge.network.tasks;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
@@ -17,8 +14,6 @@ import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import org.jetbrains.annotations.ApiStatus;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.Packet;
import net.minecraft.resources.ResourceLocation;
@@ -59,7 +54,7 @@ public class SyncRegistriesTask implements ConfigurationTask {
this.snapshot = RegistryManager.ACTIVE.takeSnapshot(false);
expectedToken = handler.expectAck(this::sendRegistries);
NetworkInitialization.PLAY.send(new RegistryList(expectedToken), con);
NetworkInitialization.CONFIG.send(new RegistryList(expectedToken), con);
}
private void sendRegistries(Acknowledge msg, CustomPayloadEvent.Context ctx) {
@@ -79,7 +74,7 @@ public class SyncRegistriesTask implements ConfigurationTask {
var name = this.snapshot.keySet().iterator().next();
var data = this.snapshot.remove(name);
expectedToken = this.handler.expectAck(this::sendRegistries);
NetworkInitialization.PLAY.reply(new RegistryData(expectedToken, name, data), ctx);
NetworkInitialization.CONFIG.reply(new RegistryData(expectedToken, name, data), ctx);
}
@Override