From 884829421008a34b4721448747ccba5b9d5c7025 Mon Sep 17 00:00:00 2001 From: LexManos Date: Tue, 7 May 2024 22:53:14 -0700 Subject: [PATCH] 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 <4958241+MrCrayfish@users.noreply.github.com> Co-authored-by: Paint_Ninja --- .../net/minecraftforge/fml/LogicalSide.java | 10 +- .../network/FriendlyByteBuf.java.patch | 11 + .../RegistryFriendlyByteBuf.java.patch | 14 + .../common/custom/DiscardedPayload.java.patch | 16 +- .../ClientboundCustomQueryPacket.java.patch | 5 +- ...verboundCustomQueryAnswerPacket.java.patch | 5 +- .../DiscardedQueryAnswerPayload.java.patch | 11 +- .../custom/DiscardedQueryPayload.java.patch | 16 +- .../net/minecraftforge/common/ForgeHooks.java | 19 +- .../common/util/LogicalSidedProvider.java | 33 +- .../common/util/PacketLogger.java | 4 +- .../event/network/CustomPayloadEvent.java | 21 +- .../net/minecraftforge/network/Channel.java | 35 +- .../network/EventNetworkChannel.java | 4 +- .../network/ForgePacketHandler.java | 12 +- .../minecraftforge/network/ICustomPacket.java | 4 - .../network/NetworkDirection.java | 90 +---- .../network/NetworkInitialization.java | 124 +++--- .../network/NetworkInstance.java | 6 +- .../network/NetworkProtocol.java | 66 ++++ .../network/PacketDistributor.java | 12 +- .../minecraftforge/network/SimpleChannel.java | 363 +++++++++++++++--- .../network/packets/Acknowledge.java | 3 + .../network/packets/ChannelVersions.java | 7 +- .../network/packets/ConfigData.java | 3 + .../network/packets/LoginWrapper.java | 46 ++- .../network/packets/MismatchData.java | 2 + .../network/packets/ModVersions.java | 3 + .../network/packets/OpenContainer.java | 5 +- .../network/packets/RegistryData.java | 3 + .../network/packets/RegistryList.java | 3 + .../network/packets/SpawnEntity.java | 9 +- .../network/simple/BaseProtocol.java | 74 ++++ .../network/simple/SimpleBuildable.java | 16 + .../network/simple/SimpleConnection.java | 138 +++++++ .../network/simple/SimpleFlow.java | 35 ++ .../network/simple/SimpleProtocol.java | 14 + .../simple/handler/SimpleHandlerFlow.java | 42 ++ .../simple/handler/SimpleHandlerProtocol.java | 19 + .../network/simple/handler/SimplePacket.java | 19 + .../network/tasks/ChannelVersionsTask.java | 2 +- .../network/tasks/ModVersionsTask.java | 2 +- .../network/tasks/SyncConfigTask.java | 2 +- .../network/tasks/SyncRegistriesTask.java | 9 +- 44 files changed, 989 insertions(+), 348 deletions(-) create mode 100644 patches/minecraft/net/minecraft/network/FriendlyByteBuf.java.patch create mode 100644 patches/minecraft/net/minecraft/network/RegistryFriendlyByteBuf.java.patch create mode 100644 src/main/java/net/minecraftforge/network/NetworkProtocol.java create mode 100644 src/main/java/net/minecraftforge/network/simple/BaseProtocol.java create mode 100644 src/main/java/net/minecraftforge/network/simple/SimpleBuildable.java create mode 100644 src/main/java/net/minecraftforge/network/simple/SimpleConnection.java create mode 100644 src/main/java/net/minecraftforge/network/simple/SimpleFlow.java create mode 100644 src/main/java/net/minecraftforge/network/simple/SimpleProtocol.java create mode 100644 src/main/java/net/minecraftforge/network/simple/handler/SimpleHandlerFlow.java create mode 100644 src/main/java/net/minecraftforge/network/simple/handler/SimpleHandlerProtocol.java create mode 100644 src/main/java/net/minecraftforge/network/simple/handler/SimplePacket.java diff --git a/fmlcore/src/main/java/net/minecraftforge/fml/LogicalSide.java b/fmlcore/src/main/java/net/minecraftforge/fml/LogicalSide.java index d492b6c7fa..5f6434f0c6 100644 --- a/fmlcore/src/main/java/net/minecraftforge/fml/LogicalSide.java +++ b/fmlcore/src/main/java/net/minecraftforge/fml/LogicalSide.java @@ -16,8 +16,7 @@ import net.minecraftforge.api.distmarker.Dist; * * @see Dist */ -public enum LogicalSide -{ +public enum LogicalSide { /** * The logical client of the Minecraft game, which interfaces with the player's inputs and renders the player's * viewpoint. @@ -27,6 +26,7 @@ public enum LogicalSide * @see Dist#CLIENT */ CLIENT, + /** * The logical server of the Minecraft game, responsible for connecting to clients and running the simulation logic * on the level. @@ -41,16 +41,14 @@ public enum LogicalSide /** * {@return if this logical side is the server} */ - public boolean isServer() - { + public boolean isServer() { return !isClient(); } /** * {@return if the logical side is the client} */ - public boolean isClient() - { + public boolean isClient() { return this == CLIENT; } } diff --git a/patches/minecraft/net/minecraft/network/FriendlyByteBuf.java.patch b/patches/minecraft/net/minecraft/network/FriendlyByteBuf.java.patch new file mode 100644 index 0000000000..428ea89b9e --- /dev/null +++ b/patches/minecraft/net/minecraft/network/FriendlyByteBuf.java.patch @@ -0,0 +1,11 @@ +--- a/net/minecraft/network/FriendlyByteBuf.java ++++ b/net/minecraft/network/FriendlyByteBuf.java +@@ -1589,4 +_,8 @@ + public boolean release(int p_130347_) { + return this.source.release(p_130347_); + } ++ ++ public FriendlyByteBuf wrap(ByteBuf data) { ++ return new FriendlyByteBuf(data); ++ } + } diff --git a/patches/minecraft/net/minecraft/network/RegistryFriendlyByteBuf.java.patch b/patches/minecraft/net/minecraft/network/RegistryFriendlyByteBuf.java.patch new file mode 100644 index 0000000000..ea99a5b55f --- /dev/null +++ b/patches/minecraft/net/minecraft/network/RegistryFriendlyByteBuf.java.patch @@ -0,0 +1,14 @@ +--- a/net/minecraft/network/RegistryFriendlyByteBuf.java ++++ b/net/minecraft/network/RegistryFriendlyByteBuf.java +@@ -16,6 +_,11 @@ + return this.registryAccess; + } + ++ @Override ++ public RegistryFriendlyByteBuf wrap(ByteBuf data) { ++ return new RegistryFriendlyByteBuf(data, this.registryAccess); ++ } ++ + public static Function decorator(RegistryAccess p_336066_) { + return p_328649_ -> new RegistryFriendlyByteBuf(p_328649_, p_336066_); + } diff --git a/patches/minecraft/net/minecraft/network/protocol/common/custom/DiscardedPayload.java.patch b/patches/minecraft/net/minecraft/network/protocol/common/custom/DiscardedPayload.java.patch index 346029f20b..89299209d8 100644 --- a/patches/minecraft/net/minecraft/network/protocol/common/custom/DiscardedPayload.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/common/custom/DiscardedPayload.java.patch @@ -1,22 +1,24 @@ --- a/net/minecraft/network/protocol/common/custom/DiscardedPayload.java +++ b/net/minecraft/network/protocol/common/custom/DiscardedPayload.java -@@ -4,18 +_,24 @@ +@@ -4,18 +_,26 @@ import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; -public record DiscardedPayload(ResourceLocation id) implements CustomPacketPayload { -+public record DiscardedPayload(ResourceLocation id, @org.jetbrains.annotations.Nullable FriendlyByteBuf data) implements CustomPacketPayload { ++public record DiscardedPayload(ResourceLocation id, ++ @org.jetbrains.annotations.Nullable FriendlyByteBuf data, ++ java.util.function.Consumer encoder ++) implements CustomPacketPayload { public static StreamCodec codec(ResourceLocation p_328904_, int p_334650_) { return CustomPacketPayload.codec((p_330619_, p_329210_) -> { -+ if (p_330619_.data != null) { -+ p_329210_.writeBytes(p_330619_.data.slice()); -+ } ++ p_330619_.encoder().accept(p_329210_); }, p_333509_ -> { int i = p_333509_.readableBytes(); if (i >= 0 && i <= p_334650_) { - p_333509_.skipBytes(i); - return new DiscardedPayload(p_328904_); -+ return new DiscardedPayload(p_328904_, new FriendlyByteBuf(p_333509_.readBytes(i))); ++ var data = p_333509_.wrap(p_333509_.readBytes(i)); ++ return new DiscardedPayload(p_328904_, data, buf -> buf.writeBytes(data.slice())); } else { throw new IllegalArgumentException("Payload may not be larger than " + p_334650_ + " bytes"); } @@ -24,7 +26,7 @@ + } + + public DiscardedPayload(ResourceLocation id) { -+ this(id, null); ++ this(id, null, buf -> {}); } @Override diff --git a/patches/minecraft/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java.patch index 271c998112..d3d2d62cd7 100644 --- a/patches/minecraft/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java.patch @@ -9,13 +9,14 @@ public static final StreamCodec STREAM_CODEC = Packet.codec( ClientboundCustomQueryPacket::write, ClientboundCustomQueryPacket::new ); -@@ -25,8 +_,7 @@ +@@ -25,8 +_,8 @@ private static DiscardedQueryPayload readUnknownPayload(ResourceLocation p_299981_, FriendlyByteBuf p_297706_) { int i = p_297706_.readableBytes(); if (i >= 0 && i <= 1048576) { - p_297706_.skipBytes(i); - return new DiscardedQueryPayload(p_299981_); -+ return new DiscardedQueryPayload(p_299981_, new FriendlyByteBuf(p_297706_.readBytes(i))); ++ var data = p_297706_.wrap(p_297706_.readBytes(i)); ++ return new DiscardedQueryPayload(p_299981_, data, buf -> buf.writeBytes(data.slice())); } else { throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes"); } diff --git a/patches/minecraft/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java.patch index 87b362ea33..011221cccb 100644 --- a/patches/minecraft/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java.patch @@ -9,13 +9,14 @@ public static final StreamCodec STREAM_CODEC = Packet.codec( ServerboundCustomQueryAnswerPacket::write, ServerboundCustomQueryAnswerPacket::read ); -@@ -26,8 +_,7 @@ +@@ -26,8 +_,8 @@ private static CustomQueryAnswerPayload readUnknownPayload(FriendlyByteBuf p_299934_) { int i = p_299934_.readableBytes(); if (i >= 0 && i <= 1048576) { - p_299934_.skipBytes(i); - return DiscardedQueryAnswerPayload.INSTANCE; -+ return new DiscardedQueryAnswerPayload(new FriendlyByteBuf(p_299934_.readBytes(i))); ++ var data = p_299934_.wrap(p_299934_.readBytes(i)); ++ return new DiscardedQueryAnswerPayload(data, buf -> buf.writeBytes(data.slice())); } else { throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes"); } diff --git a/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java.patch b/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java.patch index de96425590..61030cbb4c 100644 --- a/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java.patch @@ -1,21 +1,26 @@ --- a/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java +++ b/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java -@@ -2,10 +_,17 @@ +@@ -2,10 +_,22 @@ import net.minecraft.network.FriendlyByteBuf; -public record DiscardedQueryAnswerPayload() implements CustomQueryAnswerPayload { -+public record DiscardedQueryAnswerPayload(@javax.annotation.Nullable FriendlyByteBuf data) implements CustomQueryAnswerPayload { ++public record DiscardedQueryAnswerPayload( ++ @javax.annotation.Nullable FriendlyByteBuf data, ++ java.util.function.Consumer encoder ++) implements CustomQueryAnswerPayload { public static final DiscardedQueryAnswerPayload INSTANCE = new DiscardedQueryAnswerPayload(); + public DiscardedQueryAnswerPayload() { -+ this(null); ++ this(null, buf -> {}); + } + @Override public void write(FriendlyByteBuf p_299186_) { + if (this.data != null) { + p_299186_.writeBytes(this.data.slice()); ++ } else { ++ encoder.accept(p_299186_); + } } } diff --git a/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java.patch b/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java.patch index d47bc82c69..cba026e18e 100644 --- a/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java.patch @@ -1,23 +1,25 @@ --- a/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java +++ b/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java -@@ -3,12 +_,18 @@ +@@ -3,9 +_,21 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; -public record DiscardedQueryPayload(ResourceLocation id) implements CustomQueryPayload { -+public record DiscardedQueryPayload(ResourceLocation id, @org.jetbrains.annotations.Nullable FriendlyByteBuf data) implements CustomQueryPayload { ++public record DiscardedQueryPayload(ResourceLocation id, ++ @org.jetbrains.annotations.Nullable FriendlyByteBuf data, ++ java.util.function.Consumer encoder ++) implements CustomQueryPayload { + public DiscardedQueryPayload(ResourceLocation id) { -+ this(id, null); ++ this(id, null, buf -> {}); + } + @Override public void write(FriendlyByteBuf p_299949_) { + if (this.data != null) { + p_299949_.writeBytes(this.data.slice()); ++ } else { ++ encoder.accept(p_299949_); + } } -- @Override - public ResourceLocation id() { - return this.id; - } + @Override diff --git a/src/main/java/net/minecraftforge/common/ForgeHooks.java b/src/main/java/net/minecraftforge/common/ForgeHooks.java index aa51c196a7..acec9d4be0 100644 --- a/src/main/java/net/minecraftforge/common/ForgeHooks.java +++ b/src/main/java/net/minecraftforge/common/ForgeHooks.java @@ -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 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)NetworkDirection.PLAY_TO_CLIENT.buildPacket(data, play.getName()).getThis(); - return pkt; + return (Packet)NetworkDirection.PLAY_TO_CLIENT.buildPacket(NetworkInitialization.PLAY, new SpawnEntity(entity)); } @ApiStatus.Internal diff --git a/src/main/java/net/minecraftforge/common/util/LogicalSidedProvider.java b/src/main/java/net/minecraftforge/common/util/LogicalSidedProvider.java index e4654faaad..8020174ac0 100644 --- a/src/main/java/net/minecraftforge/common/util/LogicalSidedProvider.java +++ b/src/main/java/net/minecraftforge/common/util/LogicalSidedProvider.java @@ -16,34 +16,41 @@ import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; -public class LogicalSidedProvider -{ +import org.jetbrains.annotations.ApiStatus; + +public class LogicalSidedProvider { public static final LogicalSidedProvider> WORKQUEUE = new LogicalSidedProvider<>(Supplier::get, Supplier::get); public static final LogicalSidedProvider> 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 client; private static Supplier server; - // INTERNAL, DO NOT CALL - public static void setClient(Supplier client) - { + @ApiStatus.Internal + public static void setClient(Supplier client) { LogicalSidedProvider.client = client; } - public static void setServer(Supplier server) - { + + @ApiStatus.Internal + public static void setServer(Supplier server) { LogicalSidedProvider.server = server; } - private LogicalSidedProvider(Function, T> clientSide, Function, T> serverSide) - { + private LogicalSidedProvider(Function, T> clientSide, Function, T> serverSide) { this.clientSide = clientSide; this.serverSide = serverSide; } private final Function, T> clientSide; private final Function, T> serverSide; - - public T get(final LogicalSide side) { - return side==LogicalSide.CLIENT ? clientSide.apply(client) : serverSide.apply(server); - } } diff --git a/src/main/java/net/minecraftforge/common/util/PacketLogger.java b/src/main/java/net/minecraftforge/common/util/PacketLogger.java index f7e53dc228..26051c915c 100644 --- a/src/main/java/net/minecraftforge/common/util/PacketLogger.java +++ b/src/main/java/net/minecraftforge/common/util/PacketLogger.java @@ -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()); } diff --git a/src/main/java/net/minecraftforge/event/network/CustomPayloadEvent.java b/src/main/java/net/minecraftforge/event/network/CustomPayloadEvent.java index 058ad83490..6f514d5615 100644 --- a/src/main/java/net/minecraftforge/event/network/CustomPayloadEvent.java +++ b/src/main/java/net/minecraftforge/event/network/CustomPayloadEvent.java @@ -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 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()) diff --git a/src/main/java/net/minecraftforge/network/Channel.java b/src/main/java/net/minecraftforge/network/Channel.java index 5752e54636..60babc3597 100644 --- a/src/main/java/net/minecraftforge/network/Channel.java +++ b/src/main/java/net/minecraftforge/network/Channel.java @@ -38,29 +38,24 @@ public abstract class Channel { 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 { * @param 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) { diff --git a/src/main/java/net/minecraftforge/network/EventNetworkChannel.java b/src/main/java/net/minecraftforge/network/EventNetworkChannel.java index 20f3a5d4f6..0dff5f4d29 100644 --- a/src/main/java/net/minecraftforge/network/EventNetworkChannel.java +++ b/src/main/java/net/minecraftforge/network/EventNetworkChannel.java @@ -42,7 +42,7 @@ public class EventNetworkChannel extends Channel { } @Override - public FriendlyByteBuf toBuffer(FriendlyByteBuf message) { - return message; + public void encode(FriendlyByteBuf out, FriendlyByteBuf message) { + out.writeBytes(message.slice()); } } diff --git a/src/main/java/net/minecraftforge/network/ForgePacketHandler.java b/src/main/java/net/minecraftforge/network/ForgePacketHandler.java index e5d576ac54..66b83ede91 100644 --- a/src/main/java/net/minecraftforge/network/ForgePacketHandler.java +++ b/src/main/java/net/minecraftforge/network/ForgePacketHandler.java @@ -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) { diff --git a/src/main/java/net/minecraftforge/network/ICustomPacket.java b/src/main/java/net/minecraftforge/network/ICustomPacket.java index d6aa7c6201..daaf111d0f 100644 --- a/src/main/java/net/minecraftforge/network/ICustomPacket.java +++ b/src/main/java/net/minecraftforge/network/ICustomPacket.java @@ -24,10 +24,6 @@ public interface ICustomPacket> { int getIndex(); - default NetworkDirection getDirection() { - return NetworkDirection.directionFor(this.getClass()); - } - @SuppressWarnings("unchecked") default T getThis() { return (T)this; diff --git a/src/main/java/net/minecraftforge/network/NetworkDirection.java b/src/main/java/net/minecraftforge/network/NetworkDirection.java index 7c53dc0ebe..ee0abfb423 100644 --- a/src/main/java/net/minecraftforge/network/NetworkDirection.java +++ b/src/main/java/net/minecraftforge/network/NetworkDirection.java @@ -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(NetworkProtocol protocol, PacketFlow direction) { + public static final NetworkDirection PLAY_TO_CLIENT = new NetworkDirection<>(NetworkProtocol.PLAY, PacketFlow.CLIENTBOUND); + public static final NetworkDirection PLAY_TO_SERVER = new NetworkDirection<>(NetworkProtocol.PLAY, PacketFlow.SERVERBOUND); + public static final NetworkDirection LOGIN_TO_CLIENT = new NetworkDirection<>(NetworkProtocol.LOGIN, PacketFlow.CLIENTBOUND); + public static final NetworkDirection LOGIN_TO_SERVER = new NetworkDirection<>(NetworkProtocol.LOGIN, PacketFlow.SERVERBOUND); + public static final NetworkDirection CONFIGURATION_TO_CLIENT = new NetworkDirection<>(NetworkProtocol.CONFIGURATION, PacketFlow.CLIENTBOUND); + public static final NetworkDirection CONFIGURATION_TO_SERVER = new NetworkDirection<>(NetworkProtocol.CONFIGURATION, PacketFlow.SERVERBOUND); - private final LogicalSide logicalSide; - private final Class packetClass; - private final int otherWay; - private final Factory factory; - - private static final Reference2ReferenceArrayMap, 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 clazz, int i, Factory factory) { - this.logicalSide = logicalSide; - this.packetClass = clazz; - this.otherWay = i; - this.factory = factory; - } - - private Class getPacketClass() { - return packetClass; - } - - public static > NetworkDirection directionFor(Class 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 > ICustomPacket buildPacket(FriendlyByteBuf data, ResourceLocation channelName) { - return this.factory.create(data, 0, channelName); - } - - private interface Factory> { - ICustomPacket 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 , MSG> ICustomPacket buildPacket(Channel channel, MSG packet) { + return this.protocol().buildPacket(this.direction(), channel, packet); } } diff --git a/src/main/java/net/minecraftforge/network/NetworkInitialization.java b/src/main/java/net/minecraftforge/network/NetworkInitialization.java index a71c7cdcda..4be8c83254 100644 --- a/src/main/java/net/minecraftforge/network/NetworkInitialization.java +++ b/src/main/java/net/minecraftforge/network/NetworkInitialization.java @@ -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 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 { + void handle(ForgePacketHandler handler, MSG msg, CustomPayloadEvent.Context ctx); + } + + private static BiConsumer ctx(Handler handler) { + return (msg, ctx) -> { + var inst = ctx.getConnection().channel().attr(CONTEXT).get(); + handler.handle(inst, msg, ctx); + }; } } diff --git a/src/main/java/net/minecraftforge/network/NetworkInstance.java b/src/main/java/net/minecraftforge/network/NetworkInstance.java index d0d7ec3e0b..c23dd2f2f0 100644 --- a/src/main/java/net/minecraftforge/network/NetworkInstance.java +++ b/src/main/java/net/minecraftforge/network/NetworkInstance.java @@ -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; diff --git a/src/main/java/net/minecraftforge/network/NetworkProtocol.java b/src/main/java/net/minecraftforge/network/NetworkProtocol.java new file mode 100644 index 0000000000..b50632c06c --- /dev/null +++ b/src/main/java/net/minecraftforge/network/NetworkProtocol.java @@ -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 { + public static final NetworkProtocol PLAY = new NetworkProtocol<>(ConnectionProtocol.PLAY); + public static final NetworkProtocol LOGIN = new NetworkProtocol<>(ConnectionProtocol.LOGIN); + public static final NetworkProtocol 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 , MSG> ICustomPacket buildPacket(PacketFlow direction, Channel channel, MSG packet) { + var name = channel.getName(); + var encoder = (Consumer)(buf -> channel.encode(buf, packet)); + + switch (this.protocol) { + case PLAY, CONFIGURATION: + if (direction == PacketFlow.CLIENTBOUND) + return (ICustomPacket)new ClientboundCustomPayloadPacket(new DiscardedPayload(name, null, encoder)); + else + return (ICustomPacket)new ServerboundCustomPayloadPacket(new DiscardedPayload(name, null, encoder)); + + case LOGIN: + if (direction == PacketFlow.CLIENTBOUND) + return (ICustomPacket)new ClientboundCustomQueryPacket(0, new DiscardedQueryPayload(name, null, encoder)); + else + return (ICustomPacket)new ServerboundCustomQueryAnswerPacket(0, new DiscardedQueryAnswerPayload(null, encoder)); + + default: + throw new IllegalArgumentException("Invalid protocol, shouldn't be possible as this is a private class.."); + } + } +} diff --git a/src/main/java/net/minecraftforge/network/PacketDistributor.java b/src/main/java/net/minecraftforge/network/PacketDistributor.java index 0deb9ee8f2..7ead06bc42 100644 --- a/src/main/java/net/minecraftforge/network/PacketDistributor.java +++ b/src/main/java/net/minecraftforge/network/PacketDistributor.java @@ -29,55 +29,63 @@ import org.jetbrains.annotations.Nullable; * * @param */ -public record PacketDistributor(BiFunction, T, Consumer>> functor, NetworkDirection direction) { +public record PacketDistributor(BiFunction, T, Consumer>> functor, NetworkDirection direction) { /** * Send to the player specified in the Supplier *
* {@link #with(T)} Player */ public static final PacketDistributor PLAYER = new PacketDistributor<>(PacketDistributor::playerConsumer); + /** * Send to everyone in the dimension specified in the Supplier *
* {@link #with(T)} DimensionType */ public static final PacketDistributor> DIMENSION = new PacketDistributor<>(PacketDistributor::playerListDimConsumer); + /** * Send to everyone near the {@link TargetPoint} specified in the Supplier *
* {@link #with(T)} TargetPoint */ public static final PacketDistributor NEAR = new PacketDistributor<>(PacketDistributor::playerListPointConsumer); + /** * Send to everyone *
* {@link #noArg()} */ public static final PacketDistributor ALL = new PacketDistributor<>(PacketDistributor::playerListAll); + /** * Send to the server (CLIENT to SERVER) *
* {@link #noArg()} */ public static final PacketDistributor SERVER = new PacketDistributor<>(PacketDistributor::clientToServer, NetworkDirection.PLAY_TO_SERVER); + /** * Send to all tracking the Entity in the Supplier *
* {@link #with(T)} Entity */ public static final PacketDistributor TRACKING_ENTITY = new PacketDistributor<>(PacketDistributor::trackingEntity); + /** * Send to all tracking the Entity and Player in the Supplier *
* {@link #with(T)} Entity */ public static final PacketDistributor TRACKING_ENTITY_AND_SELF = new PacketDistributor<>(PacketDistributor::trackingEntityAndSelf); + /** * Send to all tracking the Chunk in the Supplier *
* {@link #with(T)} Chunk */ public static final PacketDistributor TRACKING_CHUNK = new PacketDistributor<>(PacketDistributor::trackingChunk); + /** * Send to the supplied list of NetworkManager instances in the Supplier *
@@ -99,7 +107,7 @@ public record PacketDistributor(BiFunction, T, Consumer< * * @see Channel#send(Object, PacketTarget) */ - public record PacketTarget(Consumer> packetConsumer, NetworkDirection direction) { + public record PacketTarget(Consumer> packetConsumer, NetworkDirection direction) { public void send(Packet packet) { packetConsumer.accept(packet); } diff --git a/src/main/java/net/minecraftforge/network/SimpleChannel.java b/src/main/java/net/minecraftforge/network/SimpleChannel.java index fa86891a67..28de4efd8e 100644 --- a/src/main/java/net/minecraftforge/network/SimpleChannel.java +++ b/src/main/java/net/minecraftforge/network/SimpleChannel.java @@ -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 { +public class SimpleChannel extends Channel implements SimpleConnection { 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 { instance.addListener(this::networkEventListener); } + @Override + public SimpleProtocol protocol(NetworkProtocol protocol) { + return new Protocol<>(new SimpleContext(this).protocol(protocol)); + } + + @Override + public > SimpleHandlerProtocol protocol(AttributeKey context, NetworkProtocol protocol) { + return new HandlerProtocol<>(context, new SimpleContext(this).protocol(protocol)); + } + /** * Build a new MessageBuilder, using the next available discriminator. * * @param type Type of message * @param Type of type */ - public MessageBuilder messageBuilder(final Class type) { + public MessageBuilder messageBuilder(Class type) { return messageBuilder(type, nextIndex()); } @@ -55,8 +74,19 @@ public class SimpleChannel extends Channel { * @param discriminator Manually configured discriminator, Must be a positive number. * @param Type of type */ - public MessageBuilder messageBuilder(final Class type, int discriminator) { - return messageBuilder(type, discriminator, null); + public MessageBuilder messageBuilder(Class type, int discriminator) { + return messageBuilder(type, discriminator, (NetworkProtocol)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 Type of type + */ + public MessageBuilder messageBuilder(Class type, NetworkProtocol protocol) { + return messageBuilder(type, nextIndex(), protocol); } /** @@ -67,8 +97,21 @@ public class SimpleChannel extends Channel { * enforce strict sided handling to prevent spoofing. * @param Type of type */ - public MessageBuilder messageBuilder(final Class type, NetworkDirection direction) { - return messageBuilder(type, nextIndex(), direction); + public MessageBuilder messageBuilder(Class type, NetworkDirection 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 Type of type + */ + public MessageBuilder messageBuilder(Class type, int discriminator, NetworkProtocol protocol) { + checkBuilt(); + return new MessageBuilder<>(this, type, discriminator, protocol); } /** @@ -80,41 +123,68 @@ public class SimpleChannel extends Channel { * enforce strict sided handling to prevent spoofing. * @param Type of type */ - public MessageBuilder messageBuilder(final Class type, int discriminator, NetworkDirection direction) { - return new MessageBuilder<>(this, type, discriminator, direction); + public MessageBuilder messageBuilder(Class type, int discriminator, NetworkDirection direction) { + return messageBuilder(type, discriminator, direction.protocol()).direction(direction.direction()); } - public static class MessageBuilder { + /** + * 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 { private final SimpleChannel channel; private final Class type; private final int id; - private final Optional direction; + private final NetworkProtocol protocol; - private BiConsumer encoder; - private Function decoder; + private BiConsumer encoder; + private Function decoder; private BiConsumer consumer; + private PacketFlow direction; - private MessageBuilder(final SimpleChannel channel, final Class type, int id, @Nullable NetworkDirection networkDirection) { + private MessageBuilder(SimpleChannel channel, Class type, int id, @Nullable NetworkProtocol 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 direction(PacketFlow direction) { + this.direction = direction; + return this; } /** * Set the message encoder, which writes this message to a {@link FriendlyByteBuf}. *

- * The encoder is called immediately {@linkplain #send(PacketDistributor.PacketTarget, Object) when the + * The encoder is called immediately {@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. *

- * 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 encoder(BiConsumer encoder) { + public MessageBuilder encoder(BiConsumer encoder) { this.encoder = encoder; return this; } @@ -123,17 +193,50 @@ public class SimpleChannel extends Channel { * Set the message decoder, which reads the message from a {@link FriendlyByteBuf}. *

* 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 decoder(Function decoder) { + public MessageBuilder decoder(Function decoder) { this.decoder = decoder; return this; } + /** + * Set the StreamCodec to be used for marshaling the message object to and from a {@link FriendlyByteBuf} + *

+ * 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 codec(StreamCodec 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. + *

+ * 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 consumer(BiConsumer 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 { * * @see #consumerMainThread(BiConsumer) */ - public MessageBuilder consumerNetworkThread(BiConsumer consumer) { - this.consumer = consumer; - return this; + public MessageBuilder consumerNetworkThread(BiConsumer consumer) { + return this.consumer(consumer); } /** @@ -160,7 +262,7 @@ public class SimpleChannel extends Channel { *

* 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 { * * @see #consumerMainThread(BiConsumer) */ - public MessageBuilder consumerNetworkThread(AttributeKey key, TriConsumer consumer) { + public MessageBuilder consumerNetworkThread(AttributeKey key, TriConsumer 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 { * * @see #consumerNetworkThread(BiConsumer) */ - public MessageBuilder consumerNetworkThread(ToBooleanBiFunction handler) { + public MessageBuilder consumerNetworkThread(ToBooleanBiFunction handler) { this.consumer = (msg, ctx) -> ctx.setPacketHandled(handler.applyAsBool(msg, ctx)); return this; } @@ -190,7 +292,7 @@ public class SimpleChannel extends Channel { * * @see #consumerNetworkThread(AttributeKey,TriConsumer) */ - public MessageBuilder consumerNetworkThread(AttributeKey key, ToBooleanTriFunction handler) { + public MessageBuilder consumerNetworkThread(AttributeKey key, ToBooleanTriFunction 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 { * * @see #consumerNetworkThread(BiConsumer) */ - public MessageBuilder consumerMainThread(BiConsumer consumer) { + public MessageBuilder consumerMainThread(BiConsumer consumer) { this.consumer = (msg, context) -> { var ctx = context; ctx.enqueueWork(() -> consumer.accept(msg, context)); @@ -231,7 +333,7 @@ public class SimpleChannel extends Channel { * * @see #consumerNetworkThread(BiConsumer) */ - public MessageBuilder consumerMainThread(AttributeKey key, TriConsumer consumer) { + public MessageBuilder consumerMainThread(AttributeKey key, TriConsumer consumer) { this.consumer = (msg, ctx) -> { ctx.enqueueWork(() -> { var inst = ctx.getConnection().channel().attr(key).get(); @@ -257,10 +359,15 @@ public class SimpleChannel extends Channel { * @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( + 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 { channel.byId.put(msg.index(), msg); channel.byType.put(msg.type(), msg); + return this.channel; } } + private record SimpleContext(SimpleChannel channel, @Nullable NetworkProtocol protocol, @Nullable PacketFlow flow) { + public SimpleContext(SimpleChannel channel) { + this(channel, null, null); + } + + public SimpleContext protocol(NetworkProtocol protocol) { + return new SimpleContext<>(channel, protocol, flow); + } + + private SimpleContext flow(@Nullable PacketFlow flow) { + return new SimpleContext<>(channel, protocol, flow); + } + } + + private record Protocol(SimpleContext ctx) implements ProtocolFactory, SimpleProtocol { + @Override + public SimpleFlow flow(@Nullable PacketFlow flow) { + return new Flow<>(ctx.flow(flow)); + } + } + + private record HandlerProtocol>( + AttributeKey key, + SimpleContext ctx + ) implements ProtocolFactory, SimpleHandlerProtocol { + @Override + public SimpleHandlerFlow flow(@Nullable PacketFlow flow) { + return new HandlerFlow<>(key, ctx.flow(flow)); + } + } + + private record Flow(SimpleContext ctx) implements ProtocolFactory, SimpleFlow { + @Override + public Flow add(Class type, StreamCodec codec, BiConsumer handler) { + ctx.channel.messageBuilder(type, ctx.protocol) + .codec(codec) + .consumer(handler) + .direction(ctx.flow()) + .add(); + return this; + } + + @Override + public SimpleFlow flow(@Nullable PacketFlow flow) { + return new Flow<>(ctx.flow(flow)); + } + } + + private record HandlerFlow>( + AttributeKey key, + SimpleContext ctx + ) implements ProtocolFactory, SimpleHandlerFlow { + @Override + public SimpleHandlerFlow add(Class type, StreamCodec codec) { + return this.add(type, codec, (msg, ctx) -> { + var inst = ctx.getConnection().channel().attr(key).get(); + ctx.setPacketHandled(msg.handle(inst, ctx)); + }); + } + + @Override + public SimpleHandlerFlow addMain(Class type, StreamCodec 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 SimpleHandlerFlow add(Class type, StreamCodec codec, BiConsumer handler) { + ctx.channel.messageBuilder(type, ctx.protocol) + .codec(codec) + .consumer(handler) + .direction(ctx.flow()) + .add(); + return this; + } + + @Override + public SimpleHandlerFlow flow(@Nullable PacketFlow flow) { + return new HandlerFlow<>(key, ctx.flow(flow)); + } + } + + private interface ProtocolFactory extends SimpleConnection, SimpleBuildable { + SimpleContext ctx(); + + @Override + default SimpleProtocol protocol(NetworkProtocol protocol) { + return ctx().channel.protocol(protocol); + } + + @Override + default > SimpleHandlerProtocol protocol(AttributeKey context, NetworkProtocol protocol) { + return ctx().channel.protocol(context, protocol); + } + + @Override + default SimpleChannel build() { + return ctx().channel.build(); + } + } + /* =================================================================================== * INTERNAL BELOW THIS * =================================================================================== */ - private int lastIndex = 0; - private Int2ObjectMap> byId = new Int2ObjectArrayMap<>(); - private Object2ObjectMap, Message> byType = new Object2ObjectArrayMap<>(); + protected int lastIndex = 0; + protected Int2ObjectMap> byId = new Int2ObjectArrayMap<>(); + protected Object2ObjectMap, Message> byType = new Object2ObjectArrayMap<>(); - private record Message( + protected record Message( int index, Class type, - Optional direction, - BiConsumer encoder, - Function decoder, + NetworkProtocol protocol, + PacketFlow direction, + BiConsumer encoder, + Function decoder, BiConsumer consumer ){ }; - private int nextIndex() { + protected int nextIndex() { while (byId.containsKey(lastIndex)) { lastIndex++; if (lastIndex < 0) @@ -307,17 +522,22 @@ public class SimpleChannel extends Channel { } int id = data.readVarInt(); - var msg = byId.get(id); + @SuppressWarnings("unchecked") + var msg = (Message)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 { } // Yay generics - private static void decodeAndDispatch(FriendlyByteBuf data, CustomPayloadEvent.Context ctx, Message msg) { + private static void decodeAndDispatch(FriendlyByteBuf data, CustomPayloadEvent.Context ctx, Message 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)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)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); } } diff --git a/src/main/java/net/minecraftforge/network/packets/Acknowledge.java b/src/main/java/net/minecraftforge/network/packets/Acknowledge.java index 2951f4e406..a771ca3271 100644 --- a/src/main/java/net/minecraftforge/network/packets/Acknowledge.java +++ b/src/main/java/net/minecraftforge/network/packets/Acknowledge.java @@ -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 STREAM_CODEC = StreamCodec.ofMember(Acknowledge::encode, Acknowledge::decode); + public void encode(FriendlyByteBuf buf) { buf.writeVarInt(token); } diff --git a/src/main/java/net/minecraftforge/network/packets/ChannelVersions.java b/src/main/java/net/minecraftforge/network/packets/ChannelVersions.java index 4953f17902..7df44aab2f 100644 --- a/src/main/java/net/minecraftforge/network/packets/ChannelVersions.java +++ b/src/main/java/net/minecraftforge/network/packets/ChannelVersions.java @@ -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 channels) { + public static StreamCodec 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); } } \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/network/packets/ConfigData.java b/src/main/java/net/minecraftforge/network/packets/ConfigData.java index 8392a1845e..a5d5242e05 100644 --- a/src/main/java/net/minecraftforge/network/packets/ConfigData.java +++ b/src/main/java/net/minecraftforge/network/packets/ConfigData.java @@ -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 STREAM_CODEC = StreamCodec.ofMember(ConfigData::encode, ConfigData::decode); + public void encode(final FriendlyByteBuf buf) { buf.writeUtf(this.name()); buf.writeByteArray(this.data()); diff --git a/src/main/java/net/minecraftforge/network/packets/LoginWrapper.java b/src/main/java/net/minecraftforge/network/packets/LoginWrapper.java index e4a32c2708..17fdf6dcbe 100644 --- a/src/main/java/net/minecraftforge/network/packets/LoginWrapper.java +++ b/src/main/java/net/minecraftforge/network/packets/LoginWrapper.java @@ -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 STREAM_CODEC = StreamCodec.ofMember(LoginWrapper::encode, LoginWrapper::new); + private final ResourceLocation name; + private FriendlyByteBuf data; + private final Channel channel; + private final Object packet; + + public LoginWrapper(Channel 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)channel; + this.packet = packet; } public void encode(FriendlyByteBuf buf) { - buf.writeResourceLocation(channel); + buf.writeResourceLocation(name); + + if (data == null) { + data = buf.wrap(Unpooled.buffer()); + ((Channel)channel).encode(data, packet); + } + buf.writeVarInt(data.readableBytes()); buf.writeBytes(data.slice()); } + + public ResourceLocation name() { + return this.name; + } + + public FriendlyByteBuf data() { + return this.data; + } } diff --git a/src/main/java/net/minecraftforge/network/packets/MismatchData.java b/src/main/java/net/minecraftforge/network/packets/MismatchData.java index ec16c4d04a..effb96366c 100644 --- a/src/main/java/net/minecraftforge/network/packets/MismatchData.java +++ b/src/main/java/net/minecraftforge/network/packets/MismatchData.java @@ -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 mismatched, Set missing ) { + public static final StreamCodec STREAM_CODEC = StreamCodec.ofMember(MismatchData::encode, MismatchData::decode); private static final int MAX_LENGTH = 0x100; public MismatchData(NetworkMismatchData data) { diff --git a/src/main/java/net/minecraftforge/network/packets/ModVersions.java b/src/main/java/net/minecraftforge/network/packets/ModVersions.java index eb1d347d8c..ced848b1c7 100644 --- a/src/main/java/net/minecraftforge/network/packets/ModVersions.java +++ b/src/main/java/net/minecraftforge/network/packets/ModVersions.java @@ -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 mods) { + public static final StreamCodec STREAM_CODEC = StreamCodec.ofMember(ModVersions::encode, ModVersions::decode); + private static final int MAX_LENGTH = 0x100; public static ModVersions create() { diff --git a/src/main/java/net/minecraftforge/network/packets/OpenContainer.java b/src/main/java/net/minecraftforge/network/packets/OpenContainer.java index a8cbb76f40..f4aa4bd3ee 100644 --- a/src/main/java/net/minecraftforge/network/packets/OpenContainer.java +++ b/src/main/java/net/minecraftforge/network/packets/OpenContainer.java @@ -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 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); } diff --git a/src/main/java/net/minecraftforge/network/packets/RegistryData.java b/src/main/java/net/minecraftforge/network/packets/RegistryData.java index e5444b1e30..7b0e38706d 100644 --- a/src/main/java/net/minecraftforge/network/packets/RegistryData.java +++ b/src/main/java/net/minecraftforge/network/packets/RegistryData.java @@ -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 STREAM_CODEC = StreamCodec.ofMember(RegistryData::encode, RegistryData::decode); + public void encode(FriendlyByteBuf buf) { buf.writeVarInt(token); buf.writeResourceLocation(name); diff --git a/src/main/java/net/minecraftforge/network/packets/RegistryList.java b/src/main/java/net/minecraftforge/network/packets/RegistryList.java index f13f655d07..8ef37486b8 100644 --- a/src/main/java/net/minecraftforge/network/packets/RegistryList.java +++ b/src/main/java/net/minecraftforge/network/packets/RegistryList.java @@ -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 normal, List>> datapacks) { + public static final StreamCodec STREAM_CODEC = StreamCodec.ofMember(RegistryList::encode, RegistryList::decode); + public RegistryList(int token) { this(token, RegistryManager.getRegistryNamesForSyncToClient(), List.copyOf(DataPackRegistriesHooks.getSyncedCustomRegistries())); } diff --git a/src/main/java/net/minecraftforge/network/packets/SpawnEntity.java b/src/main/java/net/minecraftforge/network/packets/SpawnEntity.java index 5a56501ce9..61faef0494 100644 --- a/src/main/java/net/minecraftforge/network/packets/SpawnEntity.java +++ b/src/main/java/net/minecraftforge/network/packets/SpawnEntity.java @@ -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 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 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; diff --git a/src/main/java/net/minecraftforge/network/simple/BaseProtocol.java b/src/main/java/net/minecraftforge/network/simple/BaseProtocol.java new file mode 100644 index 0000000000..418296aa17 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/simple/BaseProtocol.java @@ -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 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 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 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 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 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 consumer) { + return bidirectional(consumer); + } +} diff --git a/src/main/java/net/minecraftforge/network/simple/SimpleBuildable.java b/src/main/java/net/minecraftforge/network/simple/SimpleBuildable.java new file mode 100644 index 0000000000..736618633d --- /dev/null +++ b/src/main/java/net/minecraftforge/network/simple/SimpleBuildable.java @@ -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(); +} diff --git a/src/main/java/net/minecraftforge/network/simple/SimpleConnection.java b/src/main/java/net/minecraftforge/network/simple/SimpleConnection.java new file mode 100644 index 0000000000..a13ab98a78 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/simple/SimpleConnection.java @@ -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 { + /** + * 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. + */ + SimpleProtocol protocol(NetworkProtocol 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. + */ + > SimpleHandlerProtocol protocol(AttributeKey context, NetworkProtocol protocol); + + /** + * Consumer version of {@link #protocol(NetworkProtocol)}. The Consumer will immediately be called with the created protocol. + */ + default SimpleConnection protocol(NetworkProtocol protocol, Consumer> consumer) { + var tmp = this.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 > SimpleConnection protocol(AttributeKey context, NetworkProtocol protocol, Consumer> consumer) { + var tmp = this.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 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 > SimpleHandlerProtocol configuration(AttributeKey context) { + return protocol(context, NetworkProtocol.CONFIGURATION); + } + + /** + * Consumer version of {@link #configuration()}. The Consumer will immediately be called with the created protocol. + */ + default SimpleConnection configuration(Consumer> consumer) { + return protocol(NetworkProtocol.CONFIGURATION, consumer); + } + + /** + * Consumer version of {@link #configuration(AttributeKey)}. The Consumer will immediately be called with the created protocol. + */ + default > SimpleConnection configuration(AttributeKey context, Consumer> 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 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 > SimpleHandlerProtocol login(AttributeKey context) { + return protocol(context, NetworkProtocol.LOGIN); + } + + /** + * Consumer version of {@link #login()}. The Consumer will immediately be called with the created protocol. + */ + default SimpleConnection login(Consumer> consumer) { + return protocol(NetworkProtocol.LOGIN, consumer); + } + + /** + * Consumer version of {@link #login(AttributeKey)}. The Consumer will immediately be called with the created protocol. + */ + default > SimpleConnection login(AttributeKey context, Consumer> 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 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 > SimpleHandlerProtocol play(AttributeKey context) { + return protocol(context, NetworkProtocol.PLAY); + } + + + /** + * Consumer version of {@link #play()}. The Consumer will immediately be called with the created protocol. + */ + default SimpleConnection play(Consumer> consumer) { + return protocol(NetworkProtocol.PLAY, consumer); + } + + /** + * Consumer version of {@link #play(AttributeKey)}. The Consumer will immediately be called with the created protocol. + */ + default > SimpleConnection play(AttributeKey context, Consumer> consumer) { + return protocol(context, NetworkProtocol.PLAY, consumer); + } +} diff --git a/src/main/java/net/minecraftforge/network/simple/SimpleFlow.java b/src/main/java/net/minecraftforge/network/simple/SimpleFlow.java new file mode 100644 index 0000000000..bd9f3a5b1e --- /dev/null +++ b/src/main/java/net/minecraftforge/network/simple/SimpleFlow.java @@ -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 extends SimpleProtocol, SimpleBuildable { + /** + * Adds a packet to this channel that has it's protocol validated whenever sent or received. + *

+ * 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. + */ + SimpleFlow add(Class type, StreamCodec codec, BiConsumer handler); + + /** + * Adds a packet to this channel that has it's protocol validated whenever sent or received. + *

+ * 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 SimpleFlow addMain(Class type, StreamCodec codec, BiConsumer handler) { + return add(type, codec, (msg, ctx) -> { + ctx.enqueueWork(() -> handler.accept(msg, ctx)); + ctx.setPacketHandled(true); + }); + } +} diff --git a/src/main/java/net/minecraftforge/network/simple/SimpleProtocol.java b/src/main/java/net/minecraftforge/network/simple/SimpleProtocol.java new file mode 100644 index 0000000000..4ba63c8a6d --- /dev/null +++ b/src/main/java/net/minecraftforge/network/simple/SimpleProtocol.java @@ -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 extends BaseProtocol, SimpleProtocol>, SimpleConnection { +} diff --git a/src/main/java/net/minecraftforge/network/simple/handler/SimpleHandlerFlow.java b/src/main/java/net/minecraftforge/network/simple/handler/SimpleHandlerFlow.java new file mode 100644 index 0000000000..48a1f47f1e --- /dev/null +++ b/src/main/java/net/minecraftforge/network/simple/handler/SimpleHandlerFlow.java @@ -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 extends SimpleHandlerProtocol, SimpleBuildable { + /** + * Adds a packet to this channel that has it's protocol validated whenever sent or received. + *

+ * 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. + */ + SimpleHandlerFlow add(Class type, StreamCodec codec); + + /** + * Adds a packet to this channel that has it's protocol validated whenever sent or received. + *

+ * Unlike {@link #add(Class,StreamCodec)}, the consumer is called on the main thread, and so can + * interact with most game state by default. + */ + SimpleHandlerFlow addMain(Class type, StreamCodec codec); + + /** + * Adds a packet to this channel that has it's protocol validated whenever sent or received. + *

+ * 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. + */ + SimpleHandlerFlow add(Class type, StreamCodec codec, BiConsumer handler); +} diff --git a/src/main/java/net/minecraftforge/network/simple/handler/SimpleHandlerProtocol.java b/src/main/java/net/minecraftforge/network/simple/handler/SimpleHandlerProtocol.java new file mode 100644 index 0000000000..623109570a --- /dev/null +++ b/src/main/java/net/minecraftforge/network/simple/handler/SimpleHandlerProtocol.java @@ -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 extends BaseProtocol, SimpleHandlerProtocol>, SimpleConnection { +} diff --git a/src/main/java/net/minecraftforge/network/simple/handler/SimplePacket.java b/src/main/java/net/minecraftforge/network/simple/handler/SimplePacket.java new file mode 100644 index 0000000000..0d2799df0e --- /dev/null +++ b/src/main/java/net/minecraftforge/network/simple/handler/SimplePacket.java @@ -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 The type of the context object + */ +public interface SimplePacket { + boolean handle(C handler, CustomPayloadEvent.Context event); +} diff --git a/src/main/java/net/minecraftforge/network/tasks/ChannelVersionsTask.java b/src/main/java/net/minecraftforge/network/tasks/ChannelVersionsTask.java index 245529a13e..641c553b28 100644 --- a/src/main/java/net/minecraftforge/network/tasks/ChannelVersionsTask.java +++ b/src/main/java/net/minecraftforge/network/tasks/ChannelVersionsTask.java @@ -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 diff --git a/src/main/java/net/minecraftforge/network/tasks/ModVersionsTask.java b/src/main/java/net/minecraftforge/network/tasks/ModVersionsTask.java index cc00121695..3cdc6cc95b 100644 --- a/src/main/java/net/minecraftforge/network/tasks/ModVersionsTask.java +++ b/src/main/java/net/minecraftforge/network/tasks/ModVersionsTask.java @@ -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 diff --git a/src/main/java/net/minecraftforge/network/tasks/SyncConfigTask.java b/src/main/java/net/minecraftforge/network/tasks/SyncConfigTask.java index 9f680f5abb..30d0cda37e 100644 --- a/src/main/java/net/minecraftforge/network/tasks/SyncConfigTask.java +++ b/src/main/java/net/minecraftforge/network/tasks/SyncConfigTask.java @@ -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")); diff --git a/src/main/java/net/minecraftforge/network/tasks/SyncRegistriesTask.java b/src/main/java/net/minecraftforge/network/tasks/SyncRegistriesTask.java index 9d020e47f6..99d7a0d611 100644 --- a/src/main/java/net/minecraftforge/network/tasks/SyncRegistriesTask.java +++ b/src/main/java/net/minecraftforge/network/tasks/SyncRegistriesTask.java @@ -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