diff --git a/build.gradle b/build.gradle index 9fe9ede03c..0fa882916a 100644 --- a/build.gradle +++ b/build.gradle @@ -248,7 +248,7 @@ project(':clean') { ideaModule "${rootProject.name}.${project.name}.main" main 'net.minecraft.client.main.Main' - workingDirectory project.file('run') + workingDirectory project.file('run/client') args '--gameDir', '.' args '--version', MC_VERSION @@ -263,7 +263,7 @@ project(':clean') { ideaModule "${rootProject.name}.${project.name}.main" main 'net.minecraft.server.Main' - workingDirectory project.file('run') + workingDirectory project.file('run/server') } } } @@ -476,7 +476,6 @@ def sharedFmlonlyForge = { Project prj -> } for (def run : prj.patcher.runs) { if (run.parents) continue // We already added this to the parent run config - run.workingDirectory prj.file('run') if (run.name.contains('client') || run.name.contains('data')) { // Natives are loaded from the classpath now in all cases @@ -652,6 +651,7 @@ project(':forge') { runs { forge_client { + workingDirectory file('run/client') property 'eventbus.checkTypesOnDispatch', 'true' args '--launchTarget', 'forgeclientdev' ideaModule "${rootProject.name}.${project.name}.main" @@ -661,6 +661,7 @@ project(':forge') { } forge_test_client { + workingDirectory file('run/client_test') parent runs.forge_client taskName 'forge_test_client' @@ -675,6 +676,7 @@ project(':forge') { } forge_server { + workingDirectory file('run/server') args '--launchTarget', 'forgeserverdev' ideaModule "${rootProject.name}.${project.name}.main" @@ -684,6 +686,7 @@ project(':forge') { } forge_test_server { + workingDirectory file('run/server_test') parent runs.forge_server taskName 'forge_test_server' diff --git a/fmlcore/src/main/java/net/minecraftforge/fml/IExtensionPoint.java b/fmlcore/src/main/java/net/minecraftforge/fml/IExtensionPoint.java index 731901cb2b..d1fdf4f997 100644 --- a/fmlcore/src/main/java/net/minecraftforge/fml/IExtensionPoint.java +++ b/fmlcore/src/main/java/net/minecraftforge/fml/IExtensionPoint.java @@ -25,6 +25,7 @@ import java.util.function.Supplier; * @param the type of the record which is held by the extension point */ @SuppressWarnings("unused") // Type parameter T +// TODO: Complete re-write, this hasnt actually be used in a generic way by mods and we could make it a lot simpler. public interface IExtensionPoint { /** @@ -40,7 +41,7 @@ public interface IExtensionPoint * where {@code true} means it is from the server and {@code false} means it is from the world save. The return * value of the predicate determines whether the remote version is "compatible" for the purposes of the display test.

* - *

The local compatibility version may be of the value {@link net.minecraftforge.network.NetworkConstants#IGNORESERVERONLY}, + *

The local compatibility version may be of the value {@link DisplayTest#IGNORESERVERONLY}, * in which case clients will ignore the mod's presence if it is present on the server but not on the client. * However, the remote version test predicate must still accept this value as a remote version in order to display * as compatible if the mod is present on the client.

@@ -94,6 +95,6 @@ public interface IExtensionPoint */ @SuppressWarnings("JavadocReference") // reference to NetworkConstants, ForgeHooksClient record DisplayTest(Supplier suppliedVersion, BiPredicate remoteVersionTest) implements IExtensionPoint { - public static final String IGNORESERVERONLY = "OHNOES\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31"; + public static final String IGNORESERVERONLY = "SERVER_ONLY"; } } diff --git a/patches/minecraft/net/minecraft/client/Minecraft.java.patch b/patches/minecraft/net/minecraft/client/Minecraft.java.patch index 16edc79eea..f4888c8910 100644 --- a/patches/minecraft/net/minecraft/client/Minecraft.java.patch +++ b/patches/minecraft/net/minecraft/client/Minecraft.java.patch @@ -79,9 +79,12 @@ Util.m_137521_(p_296164_, (p_296162_) -> { this.m_91239_(p_296162_, minecraft$gameloadcookie); }, () -> { -@@ -575,7 +_,7 @@ +@@ -574,8 +_,10 @@ + this.f_167847_.m_168556_(); this.m_293750_(minecraft$gameloadcookie); ++ if (net.minecraftforge.client.loading.ClientModLoader.completeModLoading()) ++ return; // Do not overwrite the error screen if there are errors }); - }, false)); + }, false).get()); @@ -150,23 +153,6 @@ }); } -@@ -872,13 +_,13 @@ - Bootstrap.m_135875_(p_91333_.m_127526_()); - if (p_91333_.m_127527_() != null) { - Bootstrap.m_135875_("#@!@# Game crashed! Crash report saved to: #@!@# " + p_91333_.m_127527_()); -- System.exit(-1); -+ net.minecraftforge.server.ServerLifecycleHooks.handleExit(-1); - } else if (p_91333_.m_127512_(file2)) { - Bootstrap.m_135875_("#@!@# Game crashed! Crash report saved to: #@!@# " + file2.getAbsolutePath()); -- System.exit(-1); -+ net.minecraftforge.server.ServerLifecycleHooks.handleExit(-1); - } else { - Bootstrap.m_135875_("#@?@# Game crashed! Crash report could not be saved. #@?@#"); -- System.exit(-2); -+ net.minecraftforge.server.ServerLifecycleHooks.handleExit(-2); - } - - } @@ -1003,10 +_,6 @@ f_90982_.error("setScreen called from non-game thread"); } @@ -185,13 +171,13 @@ + net.minecraftforge.client.ForgeHooksClient.clearGuiLayers(this); + Screen old = this.f_91080_; + if (p_91153_ != null) { -+ var event = net.minecraftforge.event.ForgeEventFactory.onScreenOpening(old, p_91153_); ++ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenOpening(old, p_91153_); + if (event == null) return; + p_91153_ = event; + } + + if (old != null && p_91153_ != old) { -+ net.minecraftforge.event.ForgeEventFactory.onScreenClose(old); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenClose(old); + old.m_7861_(); + } + diff --git a/patches/minecraft/net/minecraft/client/MouseHandler.java.patch b/patches/minecraft/net/minecraft/client/MouseHandler.java.patch index ca13b2e2b5..6d7b2b6de1 100644 --- a/patches/minecraft/net/minecraft/client/MouseHandler.java.patch +++ b/patches/minecraft/net/minecraft/client/MouseHandler.java.patch @@ -4,7 +4,7 @@ this.f_91510_ = -1; } -+ if (net.minecraftforge.event.ForgeEventFactory.onMouseButtonPre(p_91532_, p_91533_, p_91534_)) return; ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(p_91532_, p_91533_, p_91534_)) return; boolean[] aboolean = new boolean[]{false}; if (this.f_91503_.m_91265_() == null) { if (this.f_91503_.f_91080_ == null) { @@ -13,19 +13,19 @@ screen.m_169415_(); Screen.m_96579_(() -> { - aboolean[0] = screen.m_6375_(d0, d1, i); -+ aboolean[0] = net.minecraftforge.event.ForgeEventFactory.onScreenMouseClickedPre(screen, d0, d1, i); ++ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClickedPre(screen, d0, d1, i); + if (!aboolean[0]) { + aboolean[0] = this.f_91503_.f_91080_.m_6375_(d0, d1, i); -+ aboolean[0] = net.minecraftforge.event.ForgeEventFactory.onScreenMouseClickedPost(screen, d0, d1, i, aboolean[0]); ++ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClickedPost(screen, d0, d1, i, aboolean[0]); + } }, "mouseClicked event handler", screen.getClass().getCanonicalName()); } else { Screen.m_96579_(() -> { - aboolean[0] = screen.m_6348_(d0, d1, i); -+ aboolean[0] = net.minecraftforge.event.ForgeEventFactory.onScreenMouseReleasedPre(screen, d0, d1, i); ++ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleasedPre(screen, d0, d1, i); + if (!aboolean[0]) { + aboolean[0] = this.f_91503_.f_91080_.m_6348_(d0, d1, i); -+ aboolean[0] = net.minecraftforge.event.ForgeEventFactory.onScreenMouseReleasedPost(screen, d0, d1, i, aboolean[0]); ++ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleasedPost(screen, d0, d1, i, aboolean[0]); + } }, "mouseReleased event handler", screen.getClass().getCanonicalName()); } @@ -34,7 +34,7 @@ } } -+ net.minecraftforge.event.ForgeEventFactory.onMouseButtonPost(p_91532_, p_91533_, p_91534_); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(p_91532_, p_91533_, p_91534_); } } @@ -44,9 +44,9 @@ double d4 = this.f_91508_ * (double)this.f_91503_.m_91268_().m_85446_() / (double)this.f_91503_.m_91268_().m_85444_(); - this.f_91503_.f_91080_.m_6050_(d3, d4, d1, d2); this.f_91503_.f_91080_.m_169415_(); -+ if (net.minecraftforge.event.ForgeEventFactory.onScreenMouseScrollPre(this.f_91503_.f_91080_, d3, d4, d1, d2)) return; ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPre(this.f_91503_.f_91080_, d3, d4, d1, d2)) return; + if (this.f_91503_.f_91080_.m_6050_(d3, d4, d1, d2)) return; -+ net.minecraftforge.event.ForgeEventFactory.onScreenMouseScrollPost(this.f_91503_.f_91080_, d3, d4, d1, d2); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPost(this.f_91503_.f_91080_, d3, d4, d1, d2); } else if (this.f_91503_.f_91074_ != null) { if (this.f_291070_ != 0.0D && Math.signum(d1) != Math.signum(this.f_291070_)) { this.f_291070_ = 0.0D; @@ -54,7 +54,7 @@ this.f_291070_ -= (double)j; this.f_291867_ -= (double)i; int k = i == 0 ? -j : i; -+ if (net.minecraftforge.event.ForgeEventFactory.onMouseScroll(this, d1, d2)) return; ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseScroll(this, d1, d2)) return; if (this.f_91503_.f_91074_.m_5833_()) { if (this.f_91503_.f_91065_.m_93085_().m_94768_()) { this.f_91503_.f_91065_.m_93085_().m_205380_(-k); @@ -63,9 +63,9 @@ double d3 = (p_91564_ - this.f_91508_) * (double)this.f_91503_.m_91268_().m_85446_() / (double)this.f_91503_.m_91268_().m_85444_(); Screen.m_96579_(() -> { - screen.m_7979_(d0, d1, this.f_91510_, d2, d3); -+ if (net.minecraftforge.event.ForgeEventFactory.onScreenMouseDragPre(screen, d0, d1, this.f_91510_, d2, d3)) return; ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseDragPre(screen, d0, d1, this.f_91510_, d2, d3)) return; + if (screen.m_7979_(d0, d1, this.f_91510_, d2, d3)) return; -+ net.minecraftforge.event.ForgeEventFactory.onScreenMouseDragPost(screen, d0, d1, this.f_91510_, d2, d3); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseDragPost(screen, d0, d1, this.f_91510_, d2, d3); }, "mouseDragged event handler", screen.getClass().getCanonicalName()); } diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch index 774457e4f6..501766c4d4 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch @@ -4,7 +4,7 @@ } public void m_293213_(ClientboundCustomPayloadPacket p_298103_) { -+ if (net.minecraftforge.network.NetworkHooks.onCustomPayload(p_298103_, this.f_290549_)) return; ++ if (net.minecraftforge.common.ForgeHooks.onCustomPayload(p_298103_, this.f_290549_)) return; CustomPacketPayload custompacketpayload = p_298103_.f_291001_(); if (!(custompacketpayload instanceof DiscardedPayload)) { PacketUtils.m_131363_(p_298103_, this, this.f_291812_); diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java.patch new file mode 100644 index 0000000000..3b662c3eb3 --- /dev/null +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java.patch @@ -0,0 +1,10 @@ +--- a/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java ++++ b/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java +@@ -71,6 +_,7 @@ + this.f_290549_.m_129505_(new ClientPacketListener(this.f_291812_, this.f_290549_, new CommonListenerCookie(this.f_290697_, this.f_291019_, this.f_291454_, this.f_291167_, this.f_291180_, this.f_291024_, this.f_291028_))); + this.f_290549_.m_294304_(); + this.f_290549_.m_129512_(new ServerboundFinishConfigurationPacket()); ++ net.minecraftforge.common.ForgeHooks.handleClientConfigurationComplete(this.f_290549_); + } + + public void m_9933_() { diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch index 55f97013d8..eb6ccaf610 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch @@ -1,27 +1,18 @@ --- a/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java +++ b/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java -@@ -133,6 +_,7 @@ - this.f_104521_.accept(Component.m_237115_("connect.joining")); - GameProfile gameprofile = p_104547_.m_134774_(); - this.f_104522_.m_129512_(new ServerboundLoginAcknowledgedPacket()); -+ net.minecraftforge.network.NetworkHooks.handleClientLoginSuccess(this.f_104522_); - this.f_104522_.m_129505_(new ClientConfigurationPacketListenerImpl(this.f_104519_, this.f_104522_, new CommonListenerCookie(gameprofile, this.f_104519_.m_261007_().m_285995_(this.f_260722_, this.f_260612_, this.f_285614_), ClientRegistryLayer.m_245874_().m_247579_(), FeatureFlags.f_244332_, (String)null, this.f_243717_, this.f_104520_))); - this.f_104522_.m_129512_(new ServerboundCustomPayloadPacket(new BrandPayload(ClientBrandRetriever.getClientModName()))); - this.f_104522_.m_129512_(new ServerboundClientInformationPacket(this.f_104519_.f_91066_.m_294596_())); -@@ -142,7 +_,7 @@ +@@ -141,6 +_,7 @@ + public void m_7026_(Component p_104543_) { if (this.f_243717_ != null && this.f_243717_.m_295074_()) { this.f_104519_.m_91152_(new DisconnectedRealmsScreen(this.f_104520_, CommonComponents.f_130661_, p_104543_)); ++ } else if (net.minecraftforge.client.ForgeHooksClient.onClientDisconnect(this.f_104522_, this.f_104519_, this.f_104520_, p_104543_)) { } else { -- this.f_104519_.m_91152_(new DisconnectedScreen(this.f_104520_, CommonComponents.f_130661_, p_104543_)); -+ this.f_104519_.m_91152_(net.minecraftforge.network.NetworkHooks.getModMismatchData(f_104522_) != null ? new net.minecraftforge.client.gui.ModMismatchDisconnectedScreen(this.f_104520_, CommonComponents.f_130661_, p_104543_, net.minecraftforge.network.NetworkHooks.getModMismatchData(f_104522_)) : new DisconnectedScreen(this.f_104520_, CommonComponents.f_130661_, p_104543_)); + this.f_104519_.m_91152_(new DisconnectedScreen(this.f_104520_, CommonComponents.f_130661_, p_104543_)); } - - } @@ -163,6 +_,7 @@ } public void m_7254_(ClientboundCustomQueryPacket p_104545_) { -+ if (net.minecraftforge.network.NetworkHooks.onCustomPayload(p_104545_, this.f_104522_)) return; ++ if (net.minecraftforge.common.ForgeHooks.onCustomPayload(p_104545_, this.f_104522_)) return; this.f_104521_.accept(Component.m_237115_("connect.negotiating")); this.f_104522_.m_129512_(new ServerboundCustomQueryAnswerPacket(p_104545_.f_134745_(), (CustomQueryAnswerPayload)null)); } diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch index d8b08099f5..e952da5925 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch @@ -8,14 +8,6 @@ int i = p_105030_.f_132360_(); this.f_291812_.f_91074_.m_20234_(i); this.f_104889_.m_104630_(i, this.f_291812_.f_91074_); -@@ -400,6 +_,7 @@ - this.f_291812_.f_91074_.m_287199_(commonplayerspawninfo.f_291470_()); - this.f_291812_.f_91072_.m_171805_(commonplayerspawninfo.f_291098_(), commonplayerspawninfo.f_290730_()); - this.f_291812_.f_91066_.m_193770_(p_105030_.f_132370_()); -+ net.minecraftforge.network.NetworkHooks.sendMCRegistryPackets(f_290549_, "PLAY_TO_SERVER"); - this.f_252517_ = null; - this.f_244346_ = new LastSeenMessagesTracker(20); - this.f_244113_ = MessageSignatureCache.m_246587_(); @@ -1026,7 +_,9 @@ localplayer1.m_21204_().m_22159_(localplayer.m_21204_()); } diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch index b0d9ccd71e..c6a69be1bf 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch @@ -27,6 +27,6 @@ EntityRendererProvider.Context entityrendererprovider$context = new EntityRendererProvider.Context(this, this.f_173995_, this.f_234576_, this.f_234577_, p_174004_, this.f_173996_, this.f_114365_); this.f_114362_ = EntityRenderers.m_174049_(entityrendererprovider$context); this.f_114363_ = EntityRenderers.m_174051_(entityrendererprovider$context); -+ net.minecraftforge.event.ForgeEventFactory.gatherLayers(f_114362_, f_114363_, entityrendererprovider$context); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.gatherLayers(f_114362_, f_114363_, entityrendererprovider$context); } } diff --git a/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch b/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch index 904c8e3ac3..b317b385ce 100644 --- a/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch +++ b/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch @@ -16,7 +16,7 @@ + if (!DISABLE_PACKET_DEBUG && i > net.minecraft.network.CompressionDecoder.f_182672_) { + p_129453_.markReaderIndex(); + LOGGER.error("Attempted to send packet over maximum protocol size: {} > {}\nData:\n{}", i, net.minecraft.network.CompressionDecoder.f_182672_, -+ net.minecraftforge.logging.PacketDump.getContentDump(p_129453_)); ++ net.minecraftforge.common.util.HexDumper.dump(p_129453_)); + p_129453_.resetReaderIndex(); + } byte[] abyte = new byte[i]; diff --git a/patches/minecraft/net/minecraft/network/Connection.java.patch b/patches/minecraft/net/minecraft/network/Connection.java.patch index 5436876f17..6476259254 100644 --- a/patches/minecraft/net/minecraft/network/Connection.java.patch +++ b/patches/minecraft/net/minecraft/network/Connection.java.patch @@ -1,14 +1,18 @@ --- a/net/minecraft/network/Connection.java +++ b/net/minecraft/network/Connection.java -@@ -102,6 +_,7 @@ +@@ -102,15 +_,19 @@ private volatile Component f_290021_; @Nullable BandwidthDebugMonitor f_291520_; + private java.util.function.Consumer activationHandler; ++ private final net.minecraftforge.common.util.PacketLogger packetLogger; public Connection(PacketFlow p_129482_) { this.f_129466_ = p_129482_; -@@ -111,6 +_,7 @@ ++ this.packetLogger = new net.minecraftforge.common.util.PacketLogger(this); + } + + public void channelActive(ChannelHandlerContext p_129525_) throws Exception { super.channelActive(p_129525_); this.f_129468_ = p_129525_.channel(); this.f_129469_ = this.f_129468_.remoteAddress(); @@ -16,6 +20,32 @@ if (this.f_290021_ != null) { this.m_129507_(this.f_290021_); } +@@ -169,6 +_,7 @@ + } else { + if (packetlistener.m_294638_(p_129488_)) { + try { ++ packetLogger.recv(p_129488_); + m_129517_(p_129488_, packetlistener); + } catch (RunningOnDifferentThreadException runningondifferentthreadexception) { + } catch (RejectedExecutionException rejectedexecutionexception) { +@@ -237,7 +_,8 @@ + this.m_295864_((p_296374_) -> { + p_296374_.m_294993_(p_297789_); + this.m_129505_(p_298739_); +- p_296374_.m_129520_(new ClientIntentionPacket(SharedConstants.m_183709_().m_132495_(), p_300730_, p_300598_, p_297789_), (PacketSendListener)null, true); ++ // TODO: Change this to be a immediately sent login custom payload packet? ++ p_296374_.m_129520_(new ClientIntentionPacket(SharedConstants.m_183709_().m_132495_(), net.minecraftforge.network.NetworkContext.enhanceHostName(p_300730_), p_300598_, p_297789_), (PacketSendListener)null, true); + }); + } + +@@ -289,6 +_,7 @@ + + private void m_243087_(Packet p_243260_, @Nullable PacketSendListener p_243290_, boolean p_299937_) { + ChannelFuture channelfuture = p_299937_ ? this.f_129468_.writeAndFlush(p_243260_) : this.f_129468_.write(p_243260_); ++ channelfuture.addListener(f -> packetLogger.send(p_243260_)); + if (p_243290_ != null) { + channelfuture.addListener((p_243167_) -> { + if (p_243167_.isSuccess()) { @@ -395,7 +_,7 @@ if (this.f_129469_ == null) { return "local"; @@ -30,15 +60,31 @@ public static ChannelFuture m_290025_(InetSocketAddress p_290034_, boolean p_290035_, final Connection p_290031_) { + net.minecraftforge.network.DualStackUtils.checkIPv6(p_290034_.getAddress()); -+ p_290031_.activationHandler = net.minecraftforge.network.NetworkHooks::registerClientLoginChannel; ++ p_290031_.activationHandler = net.minecraftforge.network.NetworkRegistry::onConnectionStart; Class oclass; EventLoopGroup eventloopgroup; if (Epoll.isAvailable() && p_290035_) { +@@ -465,7 +_,14 @@ + PacketFlow packetflow = p_265104_.m_178539_(); + AttributeKey> attributekey = m_295397_(p_265104_); + AttributeKey> attributekey1 = m_295397_(packetflow); +- p_265436_.addLast("splitter", new Varint21FrameDecoder(p_299297_)).addLast("decoder", new PacketDecoder(attributekey)).addLast("prepender", new Varint21LengthFieldPrepender()).addLast("encoder", new PacketEncoder(attributekey1)).addLast("unbundler", new PacketBundleUnpacker(attributekey1)).addLast("bundler", new PacketBundlePacker(attributekey)); ++ p_265436_ ++ .addLast("splitter", new Varint21FrameDecoder(p_299297_)) ++ .addLast("decoder", new PacketDecoder(attributekey)) ++ .addLast("prepender", new Varint21LengthFieldPrepender()) ++ .addLast("encoder", new PacketEncoder(attributekey1)) ++ .addLast("unbundler", new PacketBundleUnpacker(attributekey1)) ++ .addLast("bundler", new PacketBundlePacker(attributekey) ++ ); + } + + public void m_295611_(ChannelPipeline p_300754_) { @@ -485,6 +_,7 @@ public static Connection m_129493_(SocketAddress p_129494_) { final Connection connection = new Connection(PacketFlow.CLIENTBOUND); -+ connection.activationHandler = net.minecraftforge.network.NetworkHooks::registerClientLoginChannel; ++ connection.activationHandler = net.minecraftforge.network.NetworkRegistry::onConnectionStart; (new Bootstrap()).group(f_129464_.get()).handler(new ChannelInitializer() { protected void initChannel(Channel p_129557_) { Connection.m_294111_(p_129557_); @@ -52,8 +98,8 @@ + return this.f_129468_; + } + -+ public PacketFlow getDirection() { -+ return this.f_129466_; ++ public ConnectionProtocol getProtocol() { ++ return this.f_129468_.attr(m_295397_(m_178314_())).get().m_295191_(); } public void m_292855_(SampleLogger p_300126_) { diff --git a/patches/minecraft/net/minecraft/network/ConnectionProtocol.java.patch b/patches/minecraft/net/minecraft/network/ConnectionProtocol.java.patch new file mode 100644 index 0000000000..ced1fce361 --- /dev/null +++ b/patches/minecraft/net/minecraft/network/ConnectionProtocol.java.patch @@ -0,0 +1,240 @@ +--- a/net/minecraft/network/ConnectionProtocol.java ++++ b/net/minecraft/network/ConnectionProtocol.java +@@ -212,11 +_,232 @@ + import org.slf4j.Logger; + + public enum ConnectionProtocol { +- HANDSHAKING("handshake", m_129600_().m_129625_(PacketFlow.CLIENTBOUND, new ConnectionProtocol.PacketSet()).m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ClientIntentionPacket.class, ClientIntentionPacket::new))), +- PLAY("play", m_129600_().m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()).m_264543_(ClientboundBundlePacket.class, ClientboundBundlePacket::new).m_178330_(ClientboundAddEntityPacket.class, ClientboundAddEntityPacket::new).m_178330_(ClientboundAddExperienceOrbPacket.class, ClientboundAddExperienceOrbPacket::new).m_178330_(ClientboundAddPlayerPacket.class, ClientboundAddPlayerPacket::new).m_178330_(ClientboundAnimatePacket.class, ClientboundAnimatePacket::new).m_178330_(ClientboundAwardStatsPacket.class, ClientboundAwardStatsPacket::new).m_178330_(ClientboundBlockChangedAckPacket.class, ClientboundBlockChangedAckPacket::new).m_178330_(ClientboundBlockDestructionPacket.class, ClientboundBlockDestructionPacket::new).m_178330_(ClientboundBlockEntityDataPacket.class, ClientboundBlockEntityDataPacket::new).m_178330_(ClientboundBlockEventPacket.class, ClientboundBlockEventPacket::new).m_178330_(ClientboundBlockUpdatePacket.class, ClientboundBlockUpdatePacket::new).m_178330_(ClientboundBossEventPacket.class, ClientboundBossEventPacket::new).m_178330_(ClientboundChangeDifficultyPacket.class, ClientboundChangeDifficultyPacket::new).m_178330_(ClientboundChunkBatchFinishedPacket.class, ClientboundChunkBatchFinishedPacket::new).m_178330_(ClientboundChunkBatchStartPacket.class, ClientboundChunkBatchStartPacket::new).m_178330_(ClientboundChunksBiomesPacket.class, ClientboundChunksBiomesPacket::new).m_178330_(ClientboundClearTitlesPacket.class, ClientboundClearTitlesPacket::new).m_178330_(ClientboundCommandSuggestionsPacket.class, ClientboundCommandSuggestionsPacket::new).m_178330_(ClientboundCommandsPacket.class, ClientboundCommandsPacket::new).m_178330_(ClientboundContainerClosePacket.class, ClientboundContainerClosePacket::new).m_178330_(ClientboundContainerSetContentPacket.class, ClientboundContainerSetContentPacket::new).m_178330_(ClientboundContainerSetDataPacket.class, ClientboundContainerSetDataPacket::new).m_178330_(ClientboundContainerSetSlotPacket.class, ClientboundContainerSetSlotPacket::new).m_178330_(ClientboundCooldownPacket.class, ClientboundCooldownPacket::new).m_178330_(ClientboundCustomChatCompletionsPacket.class, ClientboundCustomChatCompletionsPacket::new).m_178330_(ClientboundCustomPayloadPacket.class, ClientboundCustomPayloadPacket::new).m_178330_(ClientboundDamageEventPacket.class, ClientboundDamageEventPacket::new).m_178330_(ClientboundDeleteChatPacket.class, ClientboundDeleteChatPacket::new).m_178330_(ClientboundDisconnectPacket.class, ClientboundDisconnectPacket::new).m_178330_(ClientboundDisguisedChatPacket.class, ClientboundDisguisedChatPacket::new).m_178330_(ClientboundEntityEventPacket.class, ClientboundEntityEventPacket::new).m_178330_(ClientboundExplodePacket.class, ClientboundExplodePacket::new).m_178330_(ClientboundForgetLevelChunkPacket.class, ClientboundForgetLevelChunkPacket::new).m_178330_(ClientboundGameEventPacket.class, ClientboundGameEventPacket::new).m_178330_(ClientboundHorseScreenOpenPacket.class, ClientboundHorseScreenOpenPacket::new).m_178330_(ClientboundHurtAnimationPacket.class, ClientboundHurtAnimationPacket::new).m_178330_(ClientboundInitializeBorderPacket.class, ClientboundInitializeBorderPacket::new).m_178330_(ClientboundKeepAlivePacket.class, ClientboundKeepAlivePacket::new).m_178330_(ClientboundLevelChunkWithLightPacket.class, ClientboundLevelChunkWithLightPacket::new).m_178330_(ClientboundLevelEventPacket.class, ClientboundLevelEventPacket::new).m_178330_(ClientboundLevelParticlesPacket.class, ClientboundLevelParticlesPacket::new).m_178330_(ClientboundLightUpdatePacket.class, ClientboundLightUpdatePacket::new).m_178330_(ClientboundLoginPacket.class, ClientboundLoginPacket::new).m_178330_(ClientboundMapItemDataPacket.class, ClientboundMapItemDataPacket::new).m_178330_(ClientboundMerchantOffersPacket.class, ClientboundMerchantOffersPacket::new).m_178330_(ClientboundMoveEntityPacket.Pos.class, ClientboundMoveEntityPacket.Pos::m_179000_).m_178330_(ClientboundMoveEntityPacket.PosRot.class, ClientboundMoveEntityPacket.PosRot::m_179002_).m_178330_(ClientboundMoveEntityPacket.Rot.class, ClientboundMoveEntityPacket.Rot::m_179004_).m_178330_(ClientboundMoveVehiclePacket.class, ClientboundMoveVehiclePacket::new).m_178330_(ClientboundOpenBookPacket.class, ClientboundOpenBookPacket::new).m_178330_(ClientboundOpenScreenPacket.class, ClientboundOpenScreenPacket::new).m_178330_(ClientboundOpenSignEditorPacket.class, ClientboundOpenSignEditorPacket::new).m_178330_(ClientboundPingPacket.class, ClientboundPingPacket::new).m_178330_(ClientboundPongResponsePacket.class, ClientboundPongResponsePacket::new).m_178330_(ClientboundPlaceGhostRecipePacket.class, ClientboundPlaceGhostRecipePacket::new).m_178330_(ClientboundPlayerAbilitiesPacket.class, ClientboundPlayerAbilitiesPacket::new).m_178330_(ClientboundPlayerChatPacket.class, ClientboundPlayerChatPacket::new).m_178330_(ClientboundPlayerCombatEndPacket.class, ClientboundPlayerCombatEndPacket::new).m_178330_(ClientboundPlayerCombatEnterPacket.class, ClientboundPlayerCombatEnterPacket::new).m_178330_(ClientboundPlayerCombatKillPacket.class, ClientboundPlayerCombatKillPacket::new).m_178330_(ClientboundPlayerInfoRemovePacket.class, ClientboundPlayerInfoRemovePacket::new).m_178330_(ClientboundPlayerInfoUpdatePacket.class, ClientboundPlayerInfoUpdatePacket::new).m_178330_(ClientboundPlayerLookAtPacket.class, ClientboundPlayerLookAtPacket::new).m_178330_(ClientboundPlayerPositionPacket.class, ClientboundPlayerPositionPacket::new).m_178330_(ClientboundRecipePacket.class, ClientboundRecipePacket::new).m_178330_(ClientboundRemoveEntitiesPacket.class, ClientboundRemoveEntitiesPacket::new).m_178330_(ClientboundRemoveMobEffectPacket.class, ClientboundRemoveMobEffectPacket::new).m_178330_(ClientboundResourcePackPacket.class, ClientboundResourcePackPacket::new).m_178330_(ClientboundRespawnPacket.class, ClientboundRespawnPacket::new).m_178330_(ClientboundRotateHeadPacket.class, ClientboundRotateHeadPacket::new).m_178330_(ClientboundSectionBlocksUpdatePacket.class, ClientboundSectionBlocksUpdatePacket::new).m_178330_(ClientboundSelectAdvancementsTabPacket.class, ClientboundSelectAdvancementsTabPacket::new).m_178330_(ClientboundServerDataPacket.class, ClientboundServerDataPacket::new).m_178330_(ClientboundSetActionBarTextPacket.class, ClientboundSetActionBarTextPacket::new).m_178330_(ClientboundSetBorderCenterPacket.class, ClientboundSetBorderCenterPacket::new).m_178330_(ClientboundSetBorderLerpSizePacket.class, ClientboundSetBorderLerpSizePacket::new).m_178330_(ClientboundSetBorderSizePacket.class, ClientboundSetBorderSizePacket::new).m_178330_(ClientboundSetBorderWarningDelayPacket.class, ClientboundSetBorderWarningDelayPacket::new).m_178330_(ClientboundSetBorderWarningDistancePacket.class, ClientboundSetBorderWarningDistancePacket::new).m_178330_(ClientboundSetCameraPacket.class, ClientboundSetCameraPacket::new).m_178330_(ClientboundSetCarriedItemPacket.class, ClientboundSetCarriedItemPacket::new).m_178330_(ClientboundSetChunkCacheCenterPacket.class, ClientboundSetChunkCacheCenterPacket::new).m_178330_(ClientboundSetChunkCacheRadiusPacket.class, ClientboundSetChunkCacheRadiusPacket::new).m_178330_(ClientboundSetDefaultSpawnPositionPacket.class, ClientboundSetDefaultSpawnPositionPacket::new).m_178330_(ClientboundSetDisplayObjectivePacket.class, ClientboundSetDisplayObjectivePacket::new).m_178330_(ClientboundSetEntityDataPacket.class, ClientboundSetEntityDataPacket::new).m_178330_(ClientboundSetEntityLinkPacket.class, ClientboundSetEntityLinkPacket::new).m_178330_(ClientboundSetEntityMotionPacket.class, ClientboundSetEntityMotionPacket::new).m_178330_(ClientboundSetEquipmentPacket.class, ClientboundSetEquipmentPacket::new).m_178330_(ClientboundSetExperiencePacket.class, ClientboundSetExperiencePacket::new).m_178330_(ClientboundSetHealthPacket.class, ClientboundSetHealthPacket::new).m_178330_(ClientboundSetObjectivePacket.class, ClientboundSetObjectivePacket::new).m_178330_(ClientboundSetPassengersPacket.class, ClientboundSetPassengersPacket::new).m_178330_(ClientboundSetPlayerTeamPacket.class, ClientboundSetPlayerTeamPacket::new).m_178330_(ClientboundSetScorePacket.class, ClientboundSetScorePacket::new).m_178330_(ClientboundSetSimulationDistancePacket.class, ClientboundSetSimulationDistancePacket::new).m_178330_(ClientboundSetSubtitleTextPacket.class, ClientboundSetSubtitleTextPacket::new).m_178330_(ClientboundSetTimePacket.class, ClientboundSetTimePacket::new).m_178330_(ClientboundSetTitleTextPacket.class, ClientboundSetTitleTextPacket::new).m_178330_(ClientboundSetTitlesAnimationPacket.class, ClientboundSetTitlesAnimationPacket::new).m_178330_(ClientboundSoundEntityPacket.class, ClientboundSoundEntityPacket::new).m_178330_(ClientboundSoundPacket.class, ClientboundSoundPacket::new).m_178330_(ClientboundStartConfigurationPacket.class, ClientboundStartConfigurationPacket::new).m_178330_(ClientboundStopSoundPacket.class, ClientboundStopSoundPacket::new).m_178330_(ClientboundSystemChatPacket.class, ClientboundSystemChatPacket::new).m_178330_(ClientboundTabListPacket.class, ClientboundTabListPacket::new).m_178330_(ClientboundTagQueryPacket.class, ClientboundTagQueryPacket::new).m_178330_(ClientboundTakeItemEntityPacket.class, ClientboundTakeItemEntityPacket::new).m_178330_(ClientboundTeleportEntityPacket.class, ClientboundTeleportEntityPacket::new).m_178330_(ClientboundUpdateAdvancementsPacket.class, ClientboundUpdateAdvancementsPacket::new).m_178330_(ClientboundUpdateAttributesPacket.class, ClientboundUpdateAttributesPacket::new).m_178330_(ClientboundUpdateMobEffectPacket.class, ClientboundUpdateMobEffectPacket::new).m_178330_(ClientboundUpdateRecipesPacket.class, ClientboundUpdateRecipesPacket::new).m_178330_(ClientboundUpdateTagsPacket.class, ClientboundUpdateTagsPacket::new)).m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ServerboundAcceptTeleportationPacket.class, ServerboundAcceptTeleportationPacket::new).m_178330_(ServerboundBlockEntityTagQuery.class, ServerboundBlockEntityTagQuery::new).m_178330_(ServerboundChangeDifficultyPacket.class, ServerboundChangeDifficultyPacket::new).m_178330_(ServerboundChatAckPacket.class, ServerboundChatAckPacket::new).m_178330_(ServerboundChatCommandPacket.class, ServerboundChatCommandPacket::new).m_178330_(ServerboundChatPacket.class, ServerboundChatPacket::new).m_178330_(ServerboundChatSessionUpdatePacket.class, ServerboundChatSessionUpdatePacket::new).m_178330_(ServerboundChunkBatchReceivedPacket.class, ServerboundChunkBatchReceivedPacket::new).m_178330_(ServerboundClientCommandPacket.class, ServerboundClientCommandPacket::new).m_178330_(ServerboundClientInformationPacket.class, ServerboundClientInformationPacket::new).m_178330_(ServerboundCommandSuggestionPacket.class, ServerboundCommandSuggestionPacket::new).m_178330_(ServerboundConfigurationAcknowledgedPacket.class, ServerboundConfigurationAcknowledgedPacket::new).m_178330_(ServerboundContainerButtonClickPacket.class, ServerboundContainerButtonClickPacket::new).m_178330_(ServerboundContainerClickPacket.class, ServerboundContainerClickPacket::new).m_178330_(ServerboundContainerClosePacket.class, ServerboundContainerClosePacket::new).m_178330_(ServerboundCustomPayloadPacket.class, ServerboundCustomPayloadPacket::new).m_178330_(ServerboundEditBookPacket.class, ServerboundEditBookPacket::new).m_178330_(ServerboundEntityTagQuery.class, ServerboundEntityTagQuery::new).m_178330_(ServerboundInteractPacket.class, ServerboundInteractPacket::new).m_178330_(ServerboundJigsawGeneratePacket.class, ServerboundJigsawGeneratePacket::new).m_178330_(ServerboundKeepAlivePacket.class, ServerboundKeepAlivePacket::new).m_178330_(ServerboundLockDifficultyPacket.class, ServerboundLockDifficultyPacket::new).m_178330_(ServerboundMovePlayerPacket.Pos.class, ServerboundMovePlayerPacket.Pos::m_179685_).m_178330_(ServerboundMovePlayerPacket.PosRot.class, ServerboundMovePlayerPacket.PosRot::m_179687_).m_178330_(ServerboundMovePlayerPacket.Rot.class, ServerboundMovePlayerPacket.Rot::m_179689_).m_178330_(ServerboundMovePlayerPacket.StatusOnly.class, ServerboundMovePlayerPacket.StatusOnly::m_179697_).m_178330_(ServerboundMoveVehiclePacket.class, ServerboundMoveVehiclePacket::new).m_178330_(ServerboundPaddleBoatPacket.class, ServerboundPaddleBoatPacket::new).m_178330_(ServerboundPickItemPacket.class, ServerboundPickItemPacket::new).m_178330_(ServerboundPingRequestPacket.class, ServerboundPingRequestPacket::new).m_178330_(ServerboundPlaceRecipePacket.class, ServerboundPlaceRecipePacket::new).m_178330_(ServerboundPlayerAbilitiesPacket.class, ServerboundPlayerAbilitiesPacket::new).m_178330_(ServerboundPlayerActionPacket.class, ServerboundPlayerActionPacket::new).m_178330_(ServerboundPlayerCommandPacket.class, ServerboundPlayerCommandPacket::new).m_178330_(ServerboundPlayerInputPacket.class, ServerboundPlayerInputPacket::new).m_178330_(ServerboundPongPacket.class, ServerboundPongPacket::new).m_178330_(ServerboundRecipeBookChangeSettingsPacket.class, ServerboundRecipeBookChangeSettingsPacket::new).m_178330_(ServerboundRecipeBookSeenRecipePacket.class, ServerboundRecipeBookSeenRecipePacket::new).m_178330_(ServerboundRenameItemPacket.class, ServerboundRenameItemPacket::new).m_178330_(ServerboundResourcePackPacket.class, ServerboundResourcePackPacket::new).m_178330_(ServerboundSeenAdvancementsPacket.class, ServerboundSeenAdvancementsPacket::new).m_178330_(ServerboundSelectTradePacket.class, ServerboundSelectTradePacket::new).m_178330_(ServerboundSetBeaconPacket.class, ServerboundSetBeaconPacket::new).m_178330_(ServerboundSetCarriedItemPacket.class, ServerboundSetCarriedItemPacket::new).m_178330_(ServerboundSetCommandBlockPacket.class, ServerboundSetCommandBlockPacket::new).m_178330_(ServerboundSetCommandMinecartPacket.class, ServerboundSetCommandMinecartPacket::new).m_178330_(ServerboundSetCreativeModeSlotPacket.class, ServerboundSetCreativeModeSlotPacket::new).m_178330_(ServerboundSetJigsawBlockPacket.class, ServerboundSetJigsawBlockPacket::new).m_178330_(ServerboundSetStructureBlockPacket.class, ServerboundSetStructureBlockPacket::new).m_178330_(ServerboundSignUpdatePacket.class, ServerboundSignUpdatePacket::new).m_178330_(ServerboundSwingPacket.class, ServerboundSwingPacket::new).m_178330_(ServerboundTeleportToEntityPacket.class, ServerboundTeleportToEntityPacket::new).m_178330_(ServerboundUseItemOnPacket.class, ServerboundUseItemOnPacket::new).m_178330_(ServerboundUseItemPacket.class, ServerboundUseItemPacket::new))), +- STATUS("status", m_129600_().m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ServerboundStatusRequestPacket.class, ServerboundStatusRequestPacket::new).m_178330_(ServerboundPingRequestPacket.class, ServerboundPingRequestPacket::new)).m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ClientboundStatusResponsePacket.class, ClientboundStatusResponsePacket::new).m_178330_(ClientboundPongResponsePacket.class, ClientboundPongResponsePacket::new))), +- LOGIN("login", m_129600_().m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ClientboundLoginDisconnectPacket.class, ClientboundLoginDisconnectPacket::new).m_178330_(ClientboundHelloPacket.class, ClientboundHelloPacket::new).m_178330_(ClientboundGameProfilePacket.class, ClientboundGameProfilePacket::new).m_178330_(ClientboundLoginCompressionPacket.class, ClientboundLoginCompressionPacket::new).m_178330_(ClientboundCustomQueryPacket.class, ClientboundCustomQueryPacket::new)).m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ServerboundHelloPacket.class, ServerboundHelloPacket::new).m_178330_(ServerboundKeyPacket.class, ServerboundKeyPacket::new).m_178330_(ServerboundCustomQueryAnswerPacket.class, ServerboundCustomQueryAnswerPacket::m_294367_).m_178330_(ServerboundLoginAcknowledgedPacket.class, ServerboundLoginAcknowledgedPacket::new))), +- CONFIGURATION("configuration", m_129600_().m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ClientboundCustomPayloadPacket.class, ClientboundCustomPayloadPacket::new).m_178330_(ClientboundDisconnectPacket.class, ClientboundDisconnectPacket::new).m_178330_(ClientboundFinishConfigurationPacket.class, ClientboundFinishConfigurationPacket::new).m_178330_(ClientboundKeepAlivePacket.class, ClientboundKeepAlivePacket::new).m_178330_(ClientboundPingPacket.class, ClientboundPingPacket::new).m_178330_(ClientboundRegistryDataPacket.class, ClientboundRegistryDataPacket::new).m_178330_(ClientboundResourcePackPacket.class, ClientboundResourcePackPacket::new).m_178330_(ClientboundUpdateEnabledFeaturesPacket.class, ClientboundUpdateEnabledFeaturesPacket::new).m_178330_(ClientboundUpdateTagsPacket.class, ClientboundUpdateTagsPacket::new)).m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ServerboundClientInformationPacket.class, ServerboundClientInformationPacket::new).m_178330_(ServerboundCustomPayloadPacket.class, ServerboundCustomPayloadPacket::new).m_178330_(ServerboundFinishConfigurationPacket.class, ServerboundFinishConfigurationPacket::new).m_178330_(ServerboundKeepAlivePacket.class, ServerboundKeepAlivePacket::new).m_178330_(ServerboundPongPacket.class, ServerboundPongPacket::new).m_178330_(ServerboundResourcePackPacket.class, ServerboundResourcePackPacket::new))); ++ HANDSHAKING("handshake", m_129600_() ++ .m_129625_(PacketFlow.CLIENTBOUND, new ConnectionProtocol.PacketSet<>()) ++ .m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()) ++ .m_178330_(ClientIntentionPacket.class, ClientIntentionPacket::new) ++ ) ++ ), ++ PLAY("play", m_129600_() ++ .m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()) ++ .m_264543_(ClientboundBundlePacket.class, ClientboundBundlePacket::new) ++ .m_178330_(ClientboundAddEntityPacket.class, ClientboundAddEntityPacket::new) ++ .m_178330_(ClientboundAddExperienceOrbPacket.class, ClientboundAddExperienceOrbPacket::new) ++ .m_178330_(ClientboundAddPlayerPacket.class, ClientboundAddPlayerPacket::new) ++ .m_178330_(ClientboundAnimatePacket.class, ClientboundAnimatePacket::new) ++ .m_178330_(ClientboundAwardStatsPacket.class, ClientboundAwardStatsPacket::new) ++ .m_178330_(ClientboundBlockChangedAckPacket.class, ClientboundBlockChangedAckPacket::new) ++ .m_178330_(ClientboundBlockDestructionPacket.class, ClientboundBlockDestructionPacket::new) ++ .m_178330_(ClientboundBlockEntityDataPacket.class, ClientboundBlockEntityDataPacket::new) ++ .m_178330_(ClientboundBlockEventPacket.class, ClientboundBlockEventPacket::new) ++ .m_178330_(ClientboundBlockUpdatePacket.class, ClientboundBlockUpdatePacket::new) ++ .m_178330_(ClientboundBossEventPacket.class, ClientboundBossEventPacket::new) ++ .m_178330_(ClientboundChangeDifficultyPacket.class, ClientboundChangeDifficultyPacket::new) ++ .m_178330_(ClientboundChunkBatchFinishedPacket.class, ClientboundChunkBatchFinishedPacket::new) ++ .m_178330_(ClientboundChunkBatchStartPacket.class, ClientboundChunkBatchStartPacket::new) ++ .m_178330_(ClientboundChunksBiomesPacket.class, ClientboundChunksBiomesPacket::new) ++ .m_178330_(ClientboundClearTitlesPacket.class, ClientboundClearTitlesPacket::new) ++ .m_178330_(ClientboundCommandSuggestionsPacket.class, ClientboundCommandSuggestionsPacket::new) ++ .m_178330_(ClientboundCommandsPacket.class, ClientboundCommandsPacket::new) ++ .m_178330_(ClientboundContainerClosePacket.class, ClientboundContainerClosePacket::new) ++ .m_178330_(ClientboundContainerSetContentPacket.class, ClientboundContainerSetContentPacket::new) ++ .m_178330_(ClientboundContainerSetDataPacket.class, ClientboundContainerSetDataPacket::new) ++ .m_178330_(ClientboundContainerSetSlotPacket.class, ClientboundContainerSetSlotPacket::new) ++ .m_178330_(ClientboundCooldownPacket.class, ClientboundCooldownPacket::new) ++ .m_178330_(ClientboundCustomChatCompletionsPacket.class, ClientboundCustomChatCompletionsPacket::new) ++ .m_178330_(ClientboundCustomPayloadPacket.class, ClientboundCustomPayloadPacket::new) ++ .m_178330_(ClientboundDamageEventPacket.class, ClientboundDamageEventPacket::new) ++ .m_178330_(ClientboundDeleteChatPacket.class, ClientboundDeleteChatPacket::new) ++ .m_178330_(ClientboundDisconnectPacket.class, ClientboundDisconnectPacket::new) ++ .m_178330_(ClientboundDisguisedChatPacket.class, ClientboundDisguisedChatPacket::new) ++ .m_178330_(ClientboundEntityEventPacket.class, ClientboundEntityEventPacket::new) ++ .m_178330_(ClientboundExplodePacket.class, ClientboundExplodePacket::new) ++ .m_178330_(ClientboundForgetLevelChunkPacket.class, ClientboundForgetLevelChunkPacket::new) ++ .m_178330_(ClientboundGameEventPacket.class, ClientboundGameEventPacket::new) ++ .m_178330_(ClientboundHorseScreenOpenPacket.class, ClientboundHorseScreenOpenPacket::new) ++ .m_178330_(ClientboundHurtAnimationPacket.class, ClientboundHurtAnimationPacket::new) ++ .m_178330_(ClientboundInitializeBorderPacket.class, ClientboundInitializeBorderPacket::new) ++ .m_178330_(ClientboundKeepAlivePacket.class, ClientboundKeepAlivePacket::new) ++ .m_178330_(ClientboundLevelChunkWithLightPacket.class, ClientboundLevelChunkWithLightPacket::new) ++ .m_178330_(ClientboundLevelEventPacket.class, ClientboundLevelEventPacket::new) ++ .m_178330_(ClientboundLevelParticlesPacket.class, ClientboundLevelParticlesPacket::new) ++ .m_178330_(ClientboundLightUpdatePacket.class, ClientboundLightUpdatePacket::new) ++ .m_178330_(ClientboundLoginPacket.class, ClientboundLoginPacket::new) ++ .m_178330_(ClientboundMapItemDataPacket.class, ClientboundMapItemDataPacket::new) ++ .m_178330_(ClientboundMerchantOffersPacket.class, ClientboundMerchantOffersPacket::new) ++ .m_178330_(ClientboundMoveEntityPacket.Pos.class, ClientboundMoveEntityPacket.Pos::m_179000_) ++ .m_178330_(ClientboundMoveEntityPacket.PosRot.class, ClientboundMoveEntityPacket.PosRot::m_179002_) ++ .m_178330_(ClientboundMoveEntityPacket.Rot.class, ClientboundMoveEntityPacket.Rot::m_179004_) ++ .m_178330_(ClientboundMoveVehiclePacket.class, ClientboundMoveVehiclePacket::new) ++ .m_178330_(ClientboundOpenBookPacket.class, ClientboundOpenBookPacket::new) ++ .m_178330_(ClientboundOpenScreenPacket.class, ClientboundOpenScreenPacket::new) ++ .m_178330_(ClientboundOpenSignEditorPacket.class, ClientboundOpenSignEditorPacket::new) ++ .m_178330_(ClientboundPingPacket.class, ClientboundPingPacket::new) ++ .m_178330_(ClientboundPongResponsePacket.class, ClientboundPongResponsePacket::new) ++ .m_178330_(ClientboundPlaceGhostRecipePacket.class, ClientboundPlaceGhostRecipePacket::new) ++ .m_178330_(ClientboundPlayerAbilitiesPacket.class, ClientboundPlayerAbilitiesPacket::new) ++ .m_178330_(ClientboundPlayerChatPacket.class, ClientboundPlayerChatPacket::new) ++ .m_178330_(ClientboundPlayerCombatEndPacket.class, ClientboundPlayerCombatEndPacket::new) ++ .m_178330_(ClientboundPlayerCombatEnterPacket.class, ClientboundPlayerCombatEnterPacket::new) ++ .m_178330_(ClientboundPlayerCombatKillPacket.class, ClientboundPlayerCombatKillPacket::new) ++ .m_178330_(ClientboundPlayerInfoRemovePacket.class, ClientboundPlayerInfoRemovePacket::new) ++ .m_178330_(ClientboundPlayerInfoUpdatePacket.class, ClientboundPlayerInfoUpdatePacket::new) ++ .m_178330_(ClientboundPlayerLookAtPacket.class, ClientboundPlayerLookAtPacket::new) ++ .m_178330_(ClientboundPlayerPositionPacket.class, ClientboundPlayerPositionPacket::new) ++ .m_178330_(ClientboundRecipePacket.class, ClientboundRecipePacket::new) ++ .m_178330_(ClientboundRemoveEntitiesPacket.class, ClientboundRemoveEntitiesPacket::new) ++ .m_178330_(ClientboundRemoveMobEffectPacket.class, ClientboundRemoveMobEffectPacket::new) ++ .m_178330_(ClientboundResourcePackPacket.class, ClientboundResourcePackPacket::new) ++ .m_178330_(ClientboundRespawnPacket.class, ClientboundRespawnPacket::new) ++ .m_178330_(ClientboundRotateHeadPacket.class, ClientboundRotateHeadPacket::new) ++ .m_178330_(ClientboundSectionBlocksUpdatePacket.class, ClientboundSectionBlocksUpdatePacket::new) ++ .m_178330_(ClientboundSelectAdvancementsTabPacket.class, ClientboundSelectAdvancementsTabPacket::new) ++ .m_178330_(ClientboundServerDataPacket.class, ClientboundServerDataPacket::new) ++ .m_178330_(ClientboundSetActionBarTextPacket.class, ClientboundSetActionBarTextPacket::new) ++ .m_178330_(ClientboundSetBorderCenterPacket.class, ClientboundSetBorderCenterPacket::new) ++ .m_178330_(ClientboundSetBorderLerpSizePacket.class, ClientboundSetBorderLerpSizePacket::new) ++ .m_178330_(ClientboundSetBorderSizePacket.class, ClientboundSetBorderSizePacket::new) ++ .m_178330_(ClientboundSetBorderWarningDelayPacket.class, ClientboundSetBorderWarningDelayPacket::new) ++ .m_178330_(ClientboundSetBorderWarningDistancePacket.class, ClientboundSetBorderWarningDistancePacket::new) ++ .m_178330_(ClientboundSetCameraPacket.class, ClientboundSetCameraPacket::new) ++ .m_178330_(ClientboundSetCarriedItemPacket.class, ClientboundSetCarriedItemPacket::new) ++ .m_178330_(ClientboundSetChunkCacheCenterPacket.class, ClientboundSetChunkCacheCenterPacket::new) ++ .m_178330_(ClientboundSetChunkCacheRadiusPacket.class, ClientboundSetChunkCacheRadiusPacket::new) ++ .m_178330_(ClientboundSetDefaultSpawnPositionPacket.class, ClientboundSetDefaultSpawnPositionPacket::new) ++ .m_178330_(ClientboundSetDisplayObjectivePacket.class, ClientboundSetDisplayObjectivePacket::new) ++ .m_178330_(ClientboundSetEntityDataPacket.class, ClientboundSetEntityDataPacket::new) ++ .m_178330_(ClientboundSetEntityLinkPacket.class, ClientboundSetEntityLinkPacket::new) ++ .m_178330_(ClientboundSetEntityMotionPacket.class, ClientboundSetEntityMotionPacket::new) ++ .m_178330_(ClientboundSetEquipmentPacket.class, ClientboundSetEquipmentPacket::new) ++ .m_178330_(ClientboundSetExperiencePacket.class, ClientboundSetExperiencePacket::new) ++ .m_178330_(ClientboundSetHealthPacket.class, ClientboundSetHealthPacket::new) ++ .m_178330_(ClientboundSetObjectivePacket.class, ClientboundSetObjectivePacket::new) ++ .m_178330_(ClientboundSetPassengersPacket.class, ClientboundSetPassengersPacket::new) ++ .m_178330_(ClientboundSetPlayerTeamPacket.class, ClientboundSetPlayerTeamPacket::new) ++ .m_178330_(ClientboundSetScorePacket.class, ClientboundSetScorePacket::new) ++ .m_178330_(ClientboundSetSimulationDistancePacket.class, ClientboundSetSimulationDistancePacket::new) ++ .m_178330_(ClientboundSetSubtitleTextPacket.class, ClientboundSetSubtitleTextPacket::new) ++ .m_178330_(ClientboundSetTimePacket.class, ClientboundSetTimePacket::new) ++ .m_178330_(ClientboundSetTitleTextPacket.class, ClientboundSetTitleTextPacket::new) ++ .m_178330_(ClientboundSetTitlesAnimationPacket.class, ClientboundSetTitlesAnimationPacket::new) ++ .m_178330_(ClientboundSoundEntityPacket.class, ClientboundSoundEntityPacket::new) ++ .m_178330_(ClientboundSoundPacket.class, ClientboundSoundPacket::new) ++ .m_178330_(ClientboundStartConfigurationPacket.class, ClientboundStartConfigurationPacket::new) ++ .m_178330_(ClientboundStopSoundPacket.class, ClientboundStopSoundPacket::new) ++ .m_178330_(ClientboundSystemChatPacket.class, ClientboundSystemChatPacket::new) ++ .m_178330_(ClientboundTabListPacket.class, ClientboundTabListPacket::new) ++ .m_178330_(ClientboundTagQueryPacket.class, ClientboundTagQueryPacket::new) ++ .m_178330_(ClientboundTakeItemEntityPacket.class, ClientboundTakeItemEntityPacket::new) ++ .m_178330_(ClientboundTeleportEntityPacket.class, ClientboundTeleportEntityPacket::new) ++ .m_178330_(ClientboundUpdateAdvancementsPacket.class, ClientboundUpdateAdvancementsPacket::new) ++ .m_178330_(ClientboundUpdateAttributesPacket.class, ClientboundUpdateAttributesPacket::new) ++ .m_178330_(ClientboundUpdateMobEffectPacket.class, ClientboundUpdateMobEffectPacket::new) ++ .m_178330_(ClientboundUpdateRecipesPacket.class, ClientboundUpdateRecipesPacket::new) ++ .m_178330_(ClientboundUpdateTagsPacket.class, ClientboundUpdateTagsPacket::new) ++ ) ++ .m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()) ++ .m_178330_(ServerboundAcceptTeleportationPacket.class, ServerboundAcceptTeleportationPacket::new) ++ .m_178330_(ServerboundBlockEntityTagQuery.class, ServerboundBlockEntityTagQuery::new) ++ .m_178330_(ServerboundChangeDifficultyPacket.class, ServerboundChangeDifficultyPacket::new) ++ .m_178330_(ServerboundChatAckPacket.class, ServerboundChatAckPacket::new) ++ .m_178330_(ServerboundChatCommandPacket.class, ServerboundChatCommandPacket::new) ++ .m_178330_(ServerboundChatPacket.class, ServerboundChatPacket::new) ++ .m_178330_(ServerboundChatSessionUpdatePacket.class, ServerboundChatSessionUpdatePacket::new) ++ .m_178330_(ServerboundChunkBatchReceivedPacket.class, ServerboundChunkBatchReceivedPacket::new) ++ .m_178330_(ServerboundClientCommandPacket.class, ServerboundClientCommandPacket::new) ++ .m_178330_(ServerboundClientInformationPacket.class, ServerboundClientInformationPacket::new) ++ .m_178330_(ServerboundCommandSuggestionPacket.class, ServerboundCommandSuggestionPacket::new) ++ .m_178330_(ServerboundConfigurationAcknowledgedPacket.class, ServerboundConfigurationAcknowledgedPacket::new) ++ .m_178330_(ServerboundContainerButtonClickPacket.class, ServerboundContainerButtonClickPacket::new) ++ .m_178330_(ServerboundContainerClickPacket.class, ServerboundContainerClickPacket::new) ++ .m_178330_(ServerboundContainerClosePacket.class, ServerboundContainerClosePacket::new) ++ .m_178330_(ServerboundCustomPayloadPacket.class, ServerboundCustomPayloadPacket::new) ++ .m_178330_(ServerboundEditBookPacket.class, ServerboundEditBookPacket::new) ++ .m_178330_(ServerboundEntityTagQuery.class, ServerboundEntityTagQuery::new) ++ .m_178330_(ServerboundInteractPacket.class, ServerboundInteractPacket::new) ++ .m_178330_(ServerboundJigsawGeneratePacket.class, ServerboundJigsawGeneratePacket::new) ++ .m_178330_(ServerboundKeepAlivePacket.class, ServerboundKeepAlivePacket::new) ++ .m_178330_(ServerboundLockDifficultyPacket.class, ServerboundLockDifficultyPacket::new) ++ .m_178330_(ServerboundMovePlayerPacket.Pos.class, ServerboundMovePlayerPacket.Pos::m_179685_) ++ .m_178330_(ServerboundMovePlayerPacket.PosRot.class, ServerboundMovePlayerPacket.PosRot::m_179687_) ++ .m_178330_(ServerboundMovePlayerPacket.Rot.class, ServerboundMovePlayerPacket.Rot::m_179689_) ++ .m_178330_(ServerboundMovePlayerPacket.StatusOnly.class, ServerboundMovePlayerPacket.StatusOnly::m_179697_) ++ .m_178330_(ServerboundMoveVehiclePacket.class, ServerboundMoveVehiclePacket::new) ++ .m_178330_(ServerboundPaddleBoatPacket.class, ServerboundPaddleBoatPacket::new) ++ .m_178330_(ServerboundPickItemPacket.class, ServerboundPickItemPacket::new) ++ .m_178330_(ServerboundPingRequestPacket.class, ServerboundPingRequestPacket::new) ++ .m_178330_(ServerboundPlaceRecipePacket.class, ServerboundPlaceRecipePacket::new) ++ .m_178330_(ServerboundPlayerAbilitiesPacket.class, ServerboundPlayerAbilitiesPacket::new) ++ .m_178330_(ServerboundPlayerActionPacket.class, ServerboundPlayerActionPacket::new) ++ .m_178330_(ServerboundPlayerCommandPacket.class, ServerboundPlayerCommandPacket::new) ++ .m_178330_(ServerboundPlayerInputPacket.class, ServerboundPlayerInputPacket::new) ++ .m_178330_(ServerboundPongPacket.class, ServerboundPongPacket::new) ++ .m_178330_(ServerboundRecipeBookChangeSettingsPacket.class, ServerboundRecipeBookChangeSettingsPacket::new) ++ .m_178330_(ServerboundRecipeBookSeenRecipePacket.class, ServerboundRecipeBookSeenRecipePacket::new) ++ .m_178330_(ServerboundRenameItemPacket.class, ServerboundRenameItemPacket::new) ++ .m_178330_(ServerboundResourcePackPacket.class, ServerboundResourcePackPacket::new) ++ .m_178330_(ServerboundSeenAdvancementsPacket.class, ServerboundSeenAdvancementsPacket::new) ++ .m_178330_(ServerboundSelectTradePacket.class, ServerboundSelectTradePacket::new) ++ .m_178330_(ServerboundSetBeaconPacket.class, ServerboundSetBeaconPacket::new) ++ .m_178330_(ServerboundSetCarriedItemPacket.class, ServerboundSetCarriedItemPacket::new) ++ .m_178330_(ServerboundSetCommandBlockPacket.class, ServerboundSetCommandBlockPacket::new) ++ .m_178330_(ServerboundSetCommandMinecartPacket.class, ServerboundSetCommandMinecartPacket::new) ++ .m_178330_(ServerboundSetCreativeModeSlotPacket.class, ServerboundSetCreativeModeSlotPacket::new) ++ .m_178330_(ServerboundSetJigsawBlockPacket.class, ServerboundSetJigsawBlockPacket::new) ++ .m_178330_(ServerboundSetStructureBlockPacket.class, ServerboundSetStructureBlockPacket::new) ++ .m_178330_(ServerboundSignUpdatePacket.class, ServerboundSignUpdatePacket::new) ++ .m_178330_(ServerboundSwingPacket.class, ServerboundSwingPacket::new) ++ .m_178330_(ServerboundTeleportToEntityPacket.class, ServerboundTeleportToEntityPacket::new) ++ .m_178330_(ServerboundUseItemOnPacket.class, ServerboundUseItemOnPacket::new) ++ .m_178330_(ServerboundUseItemPacket.class, ServerboundUseItemPacket::new) ++ ) ++ ), ++ STATUS("status", m_129600_() ++ .m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()) ++ .m_178330_(ServerboundStatusRequestPacket.class, ServerboundStatusRequestPacket::new) ++ .m_178330_(ServerboundPingRequestPacket.class, ServerboundPingRequestPacket::new) ++ ) ++ .m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()) ++ .m_178330_(ClientboundStatusResponsePacket.class, ClientboundStatusResponsePacket::new) ++ .m_178330_(ClientboundPongResponsePacket.class, ClientboundPongResponsePacket::new) ++ ) ++ ), ++ LOGIN("login", m_129600_() ++ .m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()) ++ .m_178330_(ClientboundLoginDisconnectPacket.class, ClientboundLoginDisconnectPacket::new) ++ .m_178330_(ClientboundHelloPacket.class, ClientboundHelloPacket::new) ++ .m_178330_(ClientboundGameProfilePacket.class, ClientboundGameProfilePacket::new) ++ .m_178330_(ClientboundLoginCompressionPacket.class, ClientboundLoginCompressionPacket::new) ++ .m_178330_(ClientboundCustomQueryPacket.class, ClientboundCustomQueryPacket::new) ++ ) ++ .m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()) ++ .m_178330_(ServerboundHelloPacket.class, ServerboundHelloPacket::new) ++ .m_178330_(ServerboundKeyPacket.class, ServerboundKeyPacket::new) ++ .m_178330_(ServerboundCustomQueryAnswerPacket.class, ServerboundCustomQueryAnswerPacket::m_294367_) ++ .m_178330_(ServerboundLoginAcknowledgedPacket.class, ServerboundLoginAcknowledgedPacket::new) ++ ) ++ ), ++ CONFIGURATION("configuration", m_129600_() ++ .m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()) ++ .m_178330_(ClientboundCustomPayloadPacket.class, ClientboundCustomPayloadPacket::new) ++ .m_178330_(ClientboundDisconnectPacket.class, ClientboundDisconnectPacket::new) ++ .m_178330_(ClientboundFinishConfigurationPacket.class, ClientboundFinishConfigurationPacket::new) ++ .m_178330_(ClientboundKeepAlivePacket.class, ClientboundKeepAlivePacket::new) ++ .m_178330_(ClientboundPingPacket.class, ClientboundPingPacket::new) ++ .m_178330_(ClientboundRegistryDataPacket.class, ClientboundRegistryDataPacket::new) ++ .m_178330_(ClientboundResourcePackPacket.class, ClientboundResourcePackPacket::new) ++ .m_178330_(ClientboundUpdateEnabledFeaturesPacket.class, ClientboundUpdateEnabledFeaturesPacket::new) ++ .m_178330_(ClientboundUpdateTagsPacket.class, ClientboundUpdateTagsPacket::new) ++ ) ++ .m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()) ++ .m_178330_(ServerboundClientInformationPacket.class, ServerboundClientInformationPacket::new) ++ .m_178330_(ServerboundCustomPayloadPacket.class, ServerboundCustomPayloadPacket::new) ++ .m_178330_(ServerboundFinishConfigurationPacket.class, ServerboundFinishConfigurationPacket::new) ++ .m_178330_(ServerboundKeepAlivePacket.class, ServerboundKeepAlivePacket::new) ++ .m_178330_(ServerboundPongPacket.class, ServerboundPongPacket::new) ++ .m_178330_(ServerboundResourcePackPacket.class, ServerboundResourcePackPacket::new) ++ ) ++ ); + + public static final int f_263799_ = -1; + private final String f_129573_; diff --git a/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch index d598b4f56d..dad0e933a1 100644 --- a/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch @@ -15,7 +15,7 @@ if (i >= 0 && i <= 1048576) { - p_297545_.skipBytes(i); - return new DiscardedPayload(p_299265_); -+ return new DiscardedPayload(p_299265_, p_297545_); ++ return new DiscardedPayload(p_299265_, new FriendlyByteBuf(p_297545_.readBytes(i))); } else { throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes"); } diff --git a/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch index dd02c51dba..b96e87ccdd 100644 --- a/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch @@ -15,7 +15,7 @@ if (i >= 0 && i <= 32767) { - p_299925_.skipBytes(i); - return new DiscardedPayload(p_300234_); -+ return new DiscardedPayload(p_300234_, p_299925_); ++ return new DiscardedPayload(p_300234_, new FriendlyByteBuf(p_299925_.readBytes(i))); } else { throw new IllegalArgumentException("Payload may not be larger than 32767 bytes"); } diff --git a/patches/minecraft/net/minecraft/network/protocol/handshake/ClientIntentionPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/handshake/ClientIntentionPacket.java.patch deleted file mode 100644 index 2fd8a71fa7..0000000000 --- a/patches/minecraft/net/minecraft/network/protocol/handshake/ClientIntentionPacket.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/network/protocol/handshake/ClientIntentionPacket.java -+++ b/net/minecraft/network/protocol/handshake/ClientIntentionPacket.java -@@ -13,7 +_,7 @@ - - public void m_5779_(FriendlyByteBuf p_134737_) { - p_134737_.m_130130_(this.f_134720_); -- p_134737_.m_130070_(this.f_134721_); -+ p_134737_.m_130070_(this.f_134721_ + "\0" + net.minecraftforge.network.NetworkConstants.NETVERSION + "\0"); - p_134737_.writeShort(this.f_134722_); - p_134737_.m_130130_(this.f_134723_.m_293527_()); - } 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 ec3b545754..0aa34ba0ed 100644 --- a/patches/minecraft/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java.patch @@ -15,7 +15,7 @@ if (i >= 0 && i <= 1048576) { - p_297706_.skipBytes(i); - return new DiscardedQueryPayload(p_299981_); -+ return new DiscardedQueryPayload(p_299981_, p_297706_); ++ return new DiscardedQueryPayload(p_299981_, new FriendlyByteBuf(p_297706_.readBytes(i))); } 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 39d55ef85c..911b2352ed 100644 --- a/patches/minecraft/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java.patch @@ -15,7 +15,7 @@ if (i >= 0 && i <= 1048576) { - p_299934_.skipBytes(i); - return DiscardedQueryAnswerPayload.f_290582_; -+ return new DiscardedQueryAnswerPayload(p_299934_); ++ return new DiscardedQueryAnswerPayload(new FriendlyByteBuf(p_299934_.readBytes(i))); } else { throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes"); } @@ -24,7 +24,7 @@ p_298492_.m_10044_(this); } + ++ @Nullable @Override public FriendlyByteBuf getInternalData() { return this.f_290461_ instanceof DiscardedQueryAnswerPayload dc ? dc.data() : null; } ++ @Override public net.minecraft.resources.ResourceLocation getName() { return net.minecraftforge.network.NetworkInitialization.LOGIN_NAME; } + @Override public int getIndex() { return f_290801_(); } -+ @Override public net.minecraft.resources.ResourceLocation getName() { return net.minecraftforge.network.LoginWrapper.WRAPPER; } -+ @Nullable @Override public FriendlyByteBuf getInternalData() { return this.f_290461_ == null ? null : ((DiscardedQueryAnswerPayload)this.f_290461_).data(); } } diff --git a/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch b/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch index e7307b909d..f558197393 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch @@ -1,5 +1,14 @@ --- a/net/minecraft/server/level/ServerPlayer.java +++ b/net/minecraft/server/level/ServerPlayer.java +@@ -149,7 +_,7 @@ + import net.minecraft.world.scores.criteria.ObjectiveCriteria; + import org.slf4j.Logger; + +-public class ServerPlayer extends Player { ++public class ServerPlayer extends Player implements net.minecraftforge.common.extensions.IForgeServerPlayer { + private static final Logger f_8907_ = LogUtils.getLogger(); + private static final int f_143381_ = 32; + private static final int f_143382_ = 10; @@ -571,6 +_,7 @@ public void m_6667_(DamageSource p_9035_) { diff --git a/patches/minecraft/net/minecraft/server/network/ConfigurationTask.java.patch b/patches/minecraft/net/minecraft/server/network/ConfigurationTask.java.patch new file mode 100644 index 0000000000..1b99bb8b9c --- /dev/null +++ b/patches/minecraft/net/minecraft/server/network/ConfigurationTask.java.patch @@ -0,0 +1,13 @@ +--- a/net/minecraft/server/network/ConfigurationTask.java ++++ b/net/minecraft/server/network/ConfigurationTask.java +@@ -4,6 +_,10 @@ + import net.minecraft.network.protocol.Packet; + + public interface ConfigurationTask { ++ default void start(net.minecraftforge.network.config.ConfigurationTaskContext ctx) { ++ m_293075_(ctx::send); ++ } ++ + void m_293075_(Consumer> p_299398_); + + ConfigurationTask.Type m_293172_(); diff --git a/patches/minecraft/net/minecraft/server/network/ServerCommonPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerCommonPacketListenerImpl.java.patch index 3c71309ff8..ccc7398e6a 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerCommonPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerCommonPacketListenerImpl.java.patch @@ -4,7 +4,7 @@ } public void m_293234_(ServerboundCustomPayloadPacket p_300164_) { -+ net.minecraftforge.network.NetworkHooks.onCustomPayload(p_300164_, this.f_291338_); ++ net.minecraftforge.common.ForgeHooks.onCustomPayload(p_300164_, this.f_291338_); } public void m_293248_(ServerboundResourcePackPacket p_300656_) { diff --git a/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch new file mode 100644 index 0000000000..272c9268c4 --- /dev/null +++ b/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch @@ -0,0 +1,50 @@ +--- a/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java ++++ b/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java +@@ -36,16 +_,19 @@ + public class ServerConfigurationPacketListenerImpl extends ServerCommonPacketListenerImpl implements TickablePacketListener, ServerConfigurationPacketListener { + private static final Logger f_291519_ = LogUtils.getLogger(); + private static final Component f_291657_ = Component.m_237115_("multiplayer.disconnect.invalid_player_data"); ++ private static final ConfigurationTask.Type VANILLA_START = new ConfigurationTask.Type("vanilla_start"); + private final GameProfile f_291596_; + private final Queue f_290691_ = new ConcurrentLinkedQueue<>(); + @Nullable + private ConfigurationTask f_291862_; + private ClientInformation f_290851_; ++ private final net.minecraftforge.network.config.ConfigurationTaskContext taskContext; + + public ServerConfigurationPacketListenerImpl(MinecraftServer p_301415_, Connection p_298106_, CommonListenerCookie p_301309_) { + super(p_301415_, p_298106_, p_301309_); + this.f_291596_ = p_301309_.f_290628_(); + this.f_290851_ = p_301309_.f_290565_(); ++ this.taskContext = new net.minecraftforge.network.config.ConfigurationTaskContext(p_298106_, this::m_141995_, this::m_293514_); + } + + protected GameProfile m_293343_() { +@@ -61,12 +_,17 @@ + return this.f_291338_.m_129536_(); + } + +- public void m_294295_() { ++ private void vanillaStart() { + this.m_141995_(new ClientboundCustomPayloadPacket(new BrandPayload(this.f_291389_.getServerModName()))); + LayeredRegistryAccess layeredregistryaccess = this.f_291389_.m_247573_(); + this.m_141995_(new ClientboundUpdateEnabledFeaturesPacket(FeatureFlags.f_244280_.m_245829_(this.f_291389_.m_129910_().m_247623_()))); + this.m_141995_(new ClientboundRegistryDataPacket((new RegistryAccess.ImmutableRegistryAccess(RegistrySynchronization.m_257599_(layeredregistryaccess))).m_203557_())); + this.m_141995_(new ClientboundUpdateTagsPacket(TagNetworkSerialization.m_245799_(layeredregistryaccess))); ++ } ++ ++ public void m_294295_() { ++ net.minecraftforge.event.ForgeEventFactory.gatherLoginConfigTasks(this.f_291338_, this.f_290691_::add); ++ this.f_290691_.add(new net.minecraftforge.network.config.SimpleConfigurationTask(VANILLA_START, this::vanillaStart)); + this.m_295612_(); + this.f_290691_.add(new JoinWorldTask()); + this.m_295676_(); +@@ -135,7 +_,7 @@ + ConfigurationTask configurationtask = this.f_290691_.poll(); + if (configurationtask != null) { + this.f_291862_ = configurationtask; +- configurationtask.m_293075_(this::m_141995_); ++ configurationtask.start(this.taskContext); + } + + } diff --git a/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch index e4efd7b764..822cfadaa5 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch @@ -1,42 +1,5 @@ --- a/net/minecraft/server/network/ServerLoginPacketListenerImpl.java +++ b/net/minecraft/server/network/ServerLoginPacketListenerImpl.java -@@ -62,7 +_,10 @@ - } - - public void m_9933_() { -- if (this.f_10019_ == ServerLoginPacketListenerImpl.State.VERIFYING) { -+ if (this.f_10019_ == State.NEGOTIATING) { //TODO: Redesign with new protocol switching Mojang added -+ if (net.minecraftforge.network.NetworkHooks.tickNegotiation(this.f_10013_)) -+ this.f_10019_ = State.VERIFYING; -+ } else if (this.f_10019_ == ServerLoginPacketListenerImpl.State.VERIFYING) { - this.m_294778_(Objects.requireNonNull(this.f_291112_)); - } - -@@ -101,7 +_,7 @@ - - public String m_10056_() { - String s = this.f_10013_.m_295656_(this.f_10018_.m_292975_()); -- return this.f_291165_ != null ? this.f_291165_ + " (" + s + ")" : s; -+ return this.f_291112_ != null ? this.f_291112_ + " (" + s + ")" : s; - } - - public void m_5990_(ServerboundHelloPacket p_10047_) { -@@ -110,13 +_,13 @@ - this.f_291165_ = p_10047_.f_238040_(); - GameProfile gameprofile = this.f_10018_.m_236731_(); - if (gameprofile != null && this.f_291165_.equalsIgnoreCase(gameprofile.getName())) { -- this.m_294008_(gameprofile); -+ this.f_10019_ = ServerLoginPacketListenerImpl.State.NEGOTIATING; // FORGE: continue NEGOTIATING, we move to READY_TO_ACCEPT after Forge is ready - } else { - if (this.f_10018_.m_129797_() && !this.f_10013_.m_129531_()) { - this.f_10019_ = ServerLoginPacketListenerImpl.State.KEY; - this.f_10013_.m_129512_(new ClientboundHelloPacket("", this.f_10018_.m_129790_().getPublic().getEncoded(), this.f_252396_)); - } else { -- this.m_294008_(m_295545_(this.f_291165_)); -+ this.f_10019_ = ServerLoginPacketListenerImpl.State.NEGOTIATING; // FORGE: continue NEGOTIATING, we move to READY_TO_ACCEPT after Forge is ready - } - - } @@ -180,7 +_,7 @@ throw new IllegalStateException("Protocol error", cryptexception); } @@ -46,20 +9,11 @@ public void run() { String s1 = Objects.requireNonNull(ServerLoginPacketListenerImpl.this.f_291165_, "Player name not initialized"); -@@ -200,7 +_,7 @@ - } catch (AuthenticationUnavailableException authenticationunavailableexception) { - if (ServerLoginPacketListenerImpl.this.f_10018_.m_129792_()) { - ServerLoginPacketListenerImpl.f_10015_.warn("Authentication servers are down but will let them in anyway!"); -- ServerLoginPacketListenerImpl.this.m_294008_(ServerLoginPacketListenerImpl.m_295545_(s1)); -+ ServerLoginPacketListenerImpl.this.f_10019_ = ServerLoginPacketListenerImpl.State.NEGOTIATING; // FORGE: continue NEGOTIATING, we move to READY_TO_ACCEPT after Forge is ready - } else { - ServerLoginPacketListenerImpl.this.m_10053_(Component.m_237115_("multiplayer.disconnect.authservers_down")); - ServerLoginPacketListenerImpl.f_10015_.error("Couldn't verify username because servers are unavailable"); @@ -220,6 +_,7 @@ } public void m_10044_(ServerboundCustomQueryAnswerPacket p_297965_) { -+ if (!net.minecraftforge.network.NetworkHooks.onCustomPayload(p_297965_, this.f_10013_)) ++ if (!net.minecraftforge.common.ForgeHooks.onCustomPayload(p_297965_, this.f_10013_)) this.m_10053_(f_291075_); } diff --git a/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch b/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch index 88f263d740..9bac5c2a30 100644 --- a/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch +++ b/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch @@ -8,14 +8,6 @@ public PlayerList(MinecraftServer p_203842_, LayeredRegistryAccess p_251844_, PlayerDataStorage p_203844_, int p_203845_) { this.f_11195_ = p_203842_; -@@ -163,6 +_,7 @@ - LevelData leveldata = serverlevel1.m_6106_(); - p_11263_.m_143427_(compoundtag); - ServerGamePacketListenerImpl servergamepacketlistenerimpl = new ServerGamePacketListenerImpl(this.f_11195_, p_11262_, p_11263_, p_297215_); -+ net.minecraftforge.network.NetworkHooks.sendMCRegistryPackets(p_11262_, "PLAY_TO_CLIENT"); - GameRules gamerules = serverlevel1.m_46469_(); - boolean flag = gamerules.m_46207_(GameRules.f_46156_); - boolean flag1 = gamerules.m_46207_(GameRules.f_46145_); @@ -171,6 +_,7 @@ servergamepacketlistenerimpl.m_141995_(new ClientboundChangeDifficultyPacket(leveldata.m_5472_(), leveldata.m_5474_())); servergamepacketlistenerimpl.m_141995_(new ClientboundPlayerAbilitiesPacket(p_11263_.m_150110_())); diff --git a/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch b/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch index 613416b95d..dee3529d78 100644 --- a/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch @@ -7,7 +7,7 @@ + private final java.util.function.Predicate> velocityUpdateSupplier; + private final java.util.function.ToIntFunction> trackingRangeSupplier; + private final java.util.function.ToIntFunction> updateIntervalSupplier; -+ private final java.util.function.BiFunction customClientFactory; ++ private final java.util.function.BiFunction customClientFactory; + private static EntityType m_20634_(String p_20635_, EntityType.Builder p_20636_) { return Registry.m_122961_(BuiltInRegistries.f_256780_, p_20635_, p_20636_.m_20712_(p_20635_)); @@ -29,7 +29,7 @@ - this.f_244139_ = p_273518_; + this(p_273268_, p_272918_, p_273417_, p_273389_, p_273556_, p_272654_, p_273631_, p_272946_, p_272895_, p_273451_, p_273518_, EntityType::defaultVelocitySupplier, EntityType::defaultTrackingRangeSupplier, EntityType::defaultUpdateIntervalSupplier, null); + } -+ public EntityType(EntityType.EntityFactory p_251402_, MobCategory p_251431_, boolean p_251439_, boolean p_251973_, boolean p_252007_, boolean p_250908_, ImmutableSet p_250201_, EntityDimensions p_251742_, int p_250479_, int p_249249_, FeatureFlagSet p_250427_, final java.util.function.Predicate> velocityUpdateSupplier, final java.util.function.ToIntFunction> trackingRangeSupplier, final java.util.function.ToIntFunction> updateIntervalSupplier, final java.util.function.BiFunction customClientFactory) { ++ public EntityType(EntityType.EntityFactory p_251402_, MobCategory p_251431_, boolean p_251439_, boolean p_251973_, boolean p_252007_, boolean p_250908_, ImmutableSet p_250201_, EntityDimensions p_251742_, int p_250479_, int p_249249_, FeatureFlagSet p_250427_, final java.util.function.Predicate> velocityUpdateSupplier, final java.util.function.ToIntFunction> trackingRangeSupplier, final java.util.function.ToIntFunction> updateIntervalSupplier, final java.util.function.BiFunction customClientFactory) { + this.f_20535_ = p_251402_; + this.f_20536_ = p_251431_; + this.f_20541_ = p_250908_; @@ -76,7 +76,7 @@ return this.f_204038_; } -+ public T customClientSpawn(net.minecraftforge.network.PlayMessages.SpawnEntity packet, Level world) { ++ public T customClientSpawn(net.minecraftforge.network.packets.SpawnEntity packet, Level world) { + if (customClientFactory == null) return this.m_20615_(world); + return customClientFactory.apply(packet, world); + } @@ -92,7 +92,7 @@ + private java.util.function.Predicate> velocityUpdateSupplier = EntityType::defaultVelocitySupplier; + private java.util.function.ToIntFunction> trackingRangeSupplier = EntityType::defaultTrackingRangeSupplier; + private java.util.function.ToIntFunction> updateIntervalSupplier = EntityType::defaultUpdateIntervalSupplier; -+ private java.util.function.BiFunction customClientFactory; ++ private java.util.function.BiFunction customClientFactory; + private Builder(EntityType.EntityFactory p_20696_, MobCategory p_20697_) { this.f_20685_ = p_20696_; @@ -120,7 +120,7 @@ + * By default, entities are spawned clientside via {@link EntityType#create(Level)}}. + * If you need finer control over the spawning process, use this to get read access to the spawn packet. + */ -+ public EntityType.Builder setCustomClientFactory(java.util.function.BiFunction customClientFactory) { ++ public EntityType.Builder setCustomClientFactory(java.util.function.BiFunction customClientFactory) { + this.customClientFactory = customClientFactory; + return this; + } diff --git a/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch index b27169de71..a99083f603 100644 --- a/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch @@ -31,7 +31,7 @@ public static AttributeSupplier.Builder m_21183_() { - return AttributeSupplier.m_22244_().m_22266_(Attributes.f_22276_).m_22266_(Attributes.f_22278_).m_22266_(Attributes.f_22279_).m_22266_(Attributes.f_22284_).m_22266_(Attributes.f_22285_).m_22266_(Attributes.f_290864_); -+ return AttributeSupplier.m_22244_().m_22266_(Attributes.f_22276_).m_22266_(Attributes.f_22278_).m_22266_(Attributes.f_22279_).m_22266_(Attributes.f_22284_).m_22266_(Attributes.f_22285_).m_22266_(net.minecraftforge.common.ForgeMod.SWIM_SPEED.get()).m_22266_(net.minecraftforge.common.ForgeMod.NAMETAG_DISTANCE.get()).m_22266_(net.minecraftforge.common.ForgeMod.ENTITY_GRAVITY.get()).m_22266_(net.minecraftforge.common.ForgeMod.STEP_HEIGHT_ADDITION.get()); ++ return AttributeSupplier.m_22244_().m_22266_(Attributes.f_22276_).m_22266_(Attributes.f_22278_).m_22266_(Attributes.f_22279_).m_22266_(Attributes.f_22284_).m_22266_(Attributes.f_22285_).m_22266_(Attributes.f_290864_).m_22266_(net.minecraftforge.common.ForgeMod.SWIM_SPEED.get()).m_22266_(net.minecraftforge.common.ForgeMod.NAMETAG_DISTANCE.get()).m_22266_(net.minecraftforge.common.ForgeMod.ENTITY_GRAVITY.get()).m_22266_(net.minecraftforge.common.ForgeMod.STEP_HEIGHT_ADDITION.get()); } protected void m_7840_(double p_20990_, boolean p_20991_, BlockState p_20992_, BlockPos p_20993_) { diff --git a/patches/minecraft/net/minecraft/world/inventory/MenuType.java.patch b/patches/minecraft/net/minecraft/world/inventory/MenuType.java.patch index 939dc5f2b4..5060610832 100644 --- a/patches/minecraft/net/minecraft/world/inventory/MenuType.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/MenuType.java.patch @@ -17,8 +17,8 @@ + + @Override + public T create(int windowId, Inventory playerInv, net.minecraft.network.FriendlyByteBuf extraData) { -+ if (this.f_39981_ instanceof net.minecraftforge.network.IContainerFactory) { -+ return ((net.minecraftforge.network.IContainerFactory) this.f_39981_).create(windowId, playerInv, extraData); ++ if (this.f_39981_ instanceof net.minecraftforge.network.IContainerFactory ctr) { ++ return ctr.create(windowId, playerInv, extraData); + } + return m_39985_(windowId, playerInv); } diff --git a/src/main/java/net/minecraftforge/client/ForgeHooksClient.java b/src/main/java/net/minecraftforge/client/ForgeHooksClient.java index 7768c68244..a826efb21e 100644 --- a/src/main/java/net/minecraftforge/client/ForgeHooksClient.java +++ b/src/main/java/net/minecraftforge/client/ForgeHooksClient.java @@ -145,6 +145,7 @@ import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; import net.minecraftforge.client.extensions.common.IClientItemExtensions; import net.minecraftforge.client.extensions.common.IClientMobEffectExtensions; import net.minecraftforge.client.gui.ClientTooltipComponentManager; +import net.minecraftforge.client.gui.ModMismatchDisconnectedScreen; import net.minecraftforge.client.gui.overlay.GuiOverlayManager; import net.minecraftforge.client.model.data.ModelData; import net.minecraftforge.client.textures.ForgeTextureMetadata; @@ -165,7 +166,8 @@ import net.minecraftforge.fml.VersionChecker; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.forge.snapshots.ForgeSnapshotsModClient; import net.minecraftforge.gametest.ForgeGameTestHooks; -import net.minecraftforge.network.NetworkConstants; +import net.minecraftforge.network.NetworkContext; +import net.minecraftforge.network.NetworkInitialization; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.ServerStatusPing; import net.minecraftforge.registries.GameData; @@ -201,8 +203,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; @ApiStatus.Internal -public class ForgeHooksClient -{ +public class ForgeHooksClient { private static final Logger LOGGER = LogManager.getLogger(); private static final Marker CLIENTHOOKS = MarkerManager.getMarker("CLIENTHOOKS"); @@ -218,21 +219,18 @@ public class ForgeHooksClient guiLayers.forEach(screen -> screen.resize(minecraft, width, height)); } - public static void clearGuiLayers(Minecraft minecraft) - { + public static void clearGuiLayers(Minecraft minecraft) { while(guiLayers.size() > 0) popGuiLayerInternal(minecraft); } - private static void popGuiLayerInternal(Minecraft minecraft) - { + private static void popGuiLayerInternal(Minecraft minecraft) { if (minecraft.screen != null) minecraft.screen.removed(); minecraft.screen = guiLayers.pop(); } - public static void pushGuiLayer(Minecraft minecraft, Screen screen) - { + public static void pushGuiLayer(Minecraft minecraft, Screen screen) { if (minecraft.screen != null) guiLayers.push(minecraft.screen); minecraft.screen = Objects.requireNonNull(screen); @@ -240,10 +238,8 @@ public class ForgeHooksClient minecraft.getNarrator().sayNow(screen.getNarrationMessage()); } - public static void popGuiLayer(Minecraft minecraft) - { - if (guiLayers.size() == 0) - { + public static void popGuiLayer(Minecraft minecraft) { + if (guiLayers.size() == 0) { minecraft.setScreen(null); return; } @@ -253,22 +249,19 @@ public class ForgeHooksClient minecraft.getNarrator().sayNow(minecraft.screen.getNarrationMessage()); } - public static float getGuiFarPlane() - { + public static float getGuiFarPlane() { // 1000 units for the overlay background, // and 10000 units for each layered Screen, return 1000.0F + 10000.0F * (1 + guiLayers.size()); } - public static String getArmorTexture(Entity entity, ItemStack armor, String _default, EquipmentSlot slot, String type) - { + public static String getArmorTexture(Entity entity, ItemStack armor, String _default, EquipmentSlot slot, String type) { String result = armor.getItem().getArmorTexture(armor, entity, slot, type); return result != null ? result : _default; } - public static boolean onDrawHighlight(LevelRenderer context, Camera camera, HitResult target, float partialTick, PoseStack poseStack, MultiBufferSource bufferSource) - { + public static boolean onDrawHighlight(LevelRenderer context, Camera camera, HitResult target, float partialTick, PoseStack poseStack, MultiBufferSource bufferSource) { switch (target.getType()) { case BLOCK: if (!(target instanceof BlockHitResult blockTarget)) return false; @@ -287,40 +280,33 @@ public class ForgeHooksClient stage.dispatch(levelRenderer, poseStack, projectionMatrix, renderTick, camera, frustum); } - public static boolean renderSpecificFirstPersonHand(InteractionHand hand, PoseStack poseStack, MultiBufferSource bufferSource, int packedLight, float partialTick, float interpPitch, float swingProgress, float equipProgress, ItemStack stack) - { + public static boolean renderSpecificFirstPersonHand(InteractionHand hand, PoseStack poseStack, MultiBufferSource bufferSource, int packedLight, float partialTick, float interpPitch, float swingProgress, float equipProgress, ItemStack stack) { return MinecraftForge.EVENT_BUS.post(new RenderHandEvent(hand, poseStack, bufferSource, packedLight, partialTick, interpPitch, swingProgress, equipProgress, stack)); } - public static boolean renderSpecificFirstPersonArm(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm) - { + public static boolean renderSpecificFirstPersonArm(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm) { return MinecraftForge.EVENT_BUS.post(new RenderArmEvent(poseStack, multiBufferSource, packedLight, player, arm)); } - public static void onTextureStitchedPost(TextureAtlas map) - { + public static void onTextureStitchedPost(TextureAtlas map) { ModLoader.get().postEvent(new TextureStitchEvent.Post(map)); } - public static void onBlockColorsInit(BlockColors blockColors) - { + public static void onBlockColorsInit(BlockColors blockColors) { ModLoader.get().postEvent(new RegisterColorHandlersEvent.Block(blockColors)); } - public static void onItemColorsInit(ItemColors itemColors, BlockColors blockColors) - { + public static void onItemColorsInit(ItemColors itemColors, BlockColors blockColors) { ModLoader.get().postEvent(new RegisterColorHandlersEvent.Item(itemColors, blockColors)); } - public static Model getArmorModel(LivingEntity entityLiving, ItemStack itemStack, EquipmentSlot slot, HumanoidModel _default) - { + public static Model getArmorModel(LivingEntity entityLiving, ItemStack itemStack, EquipmentSlot slot, HumanoidModel _default) { return IClientItemExtensions.of(itemStack).getGenericArmorModel(entityLiving, itemStack, slot, _default); } /** Copies humanoid model properties from the original model to another, used for armor models */ @SuppressWarnings("unchecked") - public static void copyModelProperties(HumanoidModel original, HumanoidModel replacement) - { + public static void copyModelProperties(HumanoidModel original, HumanoidModel replacement) { // this function does not make use of the generic, so the unchecked cast should be safe original.copyPropertiesTo((HumanoidModel)replacement); replacement.head.visible = original.head.visible; @@ -333,35 +319,27 @@ public class ForgeHooksClient } //This properly moves the domain, if provided, to the front of the string before concatenating - public static String fixDomain(String base, String complex) - { + public static String fixDomain(String base, String complex) { int idx = complex.indexOf(':'); if (idx == -1) - { return base + complex; - } String name = complex.substring(idx + 1, complex.length()); - if (idx > 1) - { + if (idx > 1) { String domain = complex.substring(0, idx); return domain + ':' + base + name; - } - else - { + } else { return base + name; } } - public static float getFieldOfViewModifier(Player entity, float fovModifier) - { + public static float getFieldOfViewModifier(Player entity, float fovModifier) { ComputeFovModifierEvent fovModifierEvent = new ComputeFovModifierEvent(entity, fovModifier); MinecraftForge.EVENT_BUS.post(fovModifierEvent); return fovModifierEvent.getNewFovModifier(); } - public static double getFieldOfView(GameRenderer renderer, Camera camera, double partialTick, double fov, boolean usedConfiguredFov) - { + public static double getFieldOfView(GameRenderer renderer, Camera camera, double partialTick, double fov, boolean usedConfiguredFov) { ViewportEvent.ComputeFov event = new ViewportEvent.ComputeFov(renderer, camera, partialTick, fov, usedConfiguredFov); MinecraftForge.EVENT_BUS.post(event); return event.getFOV(); @@ -370,19 +348,16 @@ public class ForgeHooksClient /** * Initialization of Forge Renderers. */ - static - { + static { //FluidRegistry.renderIdFluid = RenderingRegistry.getNextAvailableRenderId(); //RenderingRegistry.registerBlockHandler(RenderBlockFluid.instance); } - public static void renderMainMenu(TitleScreen gui, GuiGraphics guiGraphics, Font font, int width, int height, int alpha) - { + public static void renderMainMenu(TitleScreen gui, GuiGraphics guiGraphics, Font font, int width, int height, int alpha) { VersionChecker.Status status = ForgeVersion.getStatus(); ForgeSnapshotsModClient.renderMainMenuWarning(status, gui, guiGraphics, font, width, height, alpha); - forgeStatusLine = switch(status) - { + forgeStatusLine = switch(status) { // case FAILED -> " Version check failed"; // case UP_TO_DATE -> "Forge up to date"; // case AHEAD -> "Using non-recommended Forge build, issues may arise."; @@ -393,15 +368,13 @@ public class ForgeHooksClient public static String forgeStatusLine; @Nullable - public static SoundInstance playSound(SoundEngine manager, SoundInstance sound) - { + public static SoundInstance playSound(SoundEngine manager, SoundInstance sound) { PlaySoundEvent e = new PlaySoundEvent(manager, sound); MinecraftForge.EVENT_BUS.post(e); return e.getSound(); } - public static void drawScreen(Screen screen, GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) - { + public static void drawScreen(Screen screen, GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) { guiGraphics.pose().pushPose(); guiLayers.forEach(layer -> { // Prevent the background layers from thinking the mouse is over their controls and showing them as highlighted. @@ -412,15 +385,13 @@ public class ForgeHooksClient guiGraphics.pose().popPose(); } - private static void drawScreenInternal(Screen screen, GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) - { + private static void drawScreenInternal(Screen screen, GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) { if (!MinecraftForge.EVENT_BUS.post(new ScreenEvent.Render.Pre(screen, guiGraphics, mouseX, mouseY, partialTick))) screen.renderWithTooltip(guiGraphics, mouseX, mouseY, partialTick); MinecraftForge.EVENT_BUS.post(new ScreenEvent.Render.Post(screen, guiGraphics, mouseX, mouseY, partialTick)); } - public static Vector3f getFogColor(Camera camera, float partialTick, ClientLevel level, int renderDistance, float darkenWorldAmount, float fogRed, float fogGreen, float fogBlue) - { + public static Vector3f getFogColor(Camera camera, float partialTick, ClientLevel level, int renderDistance, float darkenWorldAmount, float fogRed, float fogGreen, float fogBlue) { // Modify fog color depending on the fluid FluidState state = level.getFluidState(camera.getBlockPosition()); Vector3f fluidFogColor = new Vector3f(fogRed, fogGreen, fogBlue); @@ -434,48 +405,41 @@ public class ForgeHooksClient return fluidFogColor; } - public static void onFogRender(FogRenderer.FogMode mode, FogType type, Camera camera, float partialTick, float renderDistance, float nearDistance, float farDistance, FogShape shape) - { + public static void onFogRender(FogRenderer.FogMode mode, FogType type, Camera camera, float partialTick, float renderDistance, float nearDistance, float farDistance, FogShape shape) { // Modify fog rendering depending on the fluid FluidState state = camera.getEntity().level().getFluidState(camera.getBlockPosition()); if (camera.getPosition().y < (double)((float)camera.getBlockPosition().getY() + state.getHeight(camera.getEntity().level(), camera.getBlockPosition()))) IClientFluidTypeExtensions.of(state).modifyFogRender(camera, mode, renderDistance, partialTick, nearDistance, farDistance, shape); ViewportEvent.RenderFog event = new ViewportEvent.RenderFog(mode, type, camera, partialTick, nearDistance, farDistance, shape); - if (MinecraftForge.EVENT_BUS.post(event)) - { + if (MinecraftForge.EVENT_BUS.post(event)) { RenderSystem.setShaderFogStart(event.getNearPlaneDistance()); RenderSystem.setShaderFogEnd(event.getFarPlaneDistance()); RenderSystem.setShaderFogShape(event.getFogShape()); } } - public static ViewportEvent.ComputeCameraAngles onCameraSetup(GameRenderer renderer, Camera camera, float partial) - { + public static ViewportEvent.ComputeCameraAngles onCameraSetup(GameRenderer renderer, Camera camera, float partial) { ViewportEvent.ComputeCameraAngles event = new ViewportEvent.ComputeCameraAngles(renderer, camera, partial, camera.getYRot(), camera.getXRot(), 0); MinecraftForge.EVENT_BUS.post(event); return event; } - public static void onModifyBakingResult(Map models, ModelBakery modelBakery) - { + public static void onModifyBakingResult(Map models, ModelBakery modelBakery) { ModLoader.get().postEvent(new ModelEvent.ModifyBakingResult(models, modelBakery)); } - public static void onModelBake(ModelManager modelManager, Map models, ModelBakery modelBakery) - { + public static void onModelBake(ModelManager modelManager, Map models, ModelBakery modelBakery) { ModLoader.get().postEvent(new ModelEvent.BakingCompleted(modelManager, Collections.unmodifiableMap(models), modelBakery)); } - public static BakedModel handleCameraTransforms(PoseStack poseStack, BakedModel model, ItemDisplayContext cameraTransformType, boolean applyLeftHandTransform) - { + public static BakedModel handleCameraTransforms(PoseStack poseStack, BakedModel model, ItemDisplayContext cameraTransformType, boolean applyLeftHandTransform) { model = model.applyTransform(cameraTransformType, poseStack, applyLeftHandTransform); return model; } @SuppressWarnings("deprecation") - public static TextureAtlasSprite[] getFluidSprites(BlockAndTintGetter level, BlockPos pos, FluidState fluidStateIn) - { + public static TextureAtlasSprite[] getFluidSprites(BlockAndTintGetter level, BlockPos pos, FluidState fluidStateIn) { IClientFluidTypeExtensions props = IClientFluidTypeExtensions.of(fluidStateIn); ResourceLocation overlayTexture = props.getOverlayTexture(fluidStateIn, level, pos); return new TextureAtlasSprite[] { @@ -486,13 +450,11 @@ public class ForgeHooksClient } @SuppressWarnings("deprecation") - public static Material getBlockMaterial(ResourceLocation loc) - { + public static Material getBlockMaterial(ResourceLocation loc) { return new Material(TextureAtlas.LOCATION_BLOCKS, loc); } - public static void fillNormal(int[] faceData, Direction facing) - { + public static void fillNormal(int[] faceData, Direction facing) { fillNormal(faceData, facing, false); } @@ -500,8 +462,7 @@ public class ForgeHooksClient * internal, relies on fixed format of FaceBakery */ // TODO Do we need this? - public static void fillNormal(int[] faceData, Direction facing, boolean calculateNormals) - { + public static void fillNormal(int[] faceData, Direction facing, boolean calculateNormals) { Vector3f v2; if (calculateNormals || ForgeConfig.CLIENT.calculateAllNormals.get()) { Vector3f v1 = getVertexPos(faceData, 3); @@ -512,9 +473,8 @@ public class ForgeHooksClient v2.sub(t2); v2.cross(v1); v2.normalize(); - } else { + } else v2 = new Vector3f(facing.getNormal().getX(), facing.getNormal().getY(), facing.getNormal().getZ()); - } int x = ((byte) Math.round(v2.x() * 127)) & 0xFF; int y = ((byte) Math.round(v2.y() * 127)) & 0xFF; int z = ((byte) Math.round(v2.z() * 127)) & 0xFF; @@ -522,13 +482,10 @@ public class ForgeHooksClient int normal = x | (y << 0x08) | (z << 0x10); for(int i = 0; i < 4; i++) - { faceData[i * 8 + 7] = normal; - } } - private static Vector3f getVertexPos(int[] data, int vertex) - { + private static Vector3f getVertexPos(int[] data, int vertex) { int idx = vertex * 8; float x = Float.intBitsToFloat(data[idx]); @@ -538,8 +495,7 @@ public class ForgeHooksClient return new Vector3f(x, y, z); } - public static boolean calculateFaceWithoutAO(BlockAndTintGetter getter, BlockState state, BlockPos pos, BakedQuad quad, boolean isFaceCubic, float[] brightness, int[] lightmap) - { + public static boolean calculateFaceWithoutAO(BlockAndTintGetter getter, BlockState state, BlockPos pos, BakedQuad quad, boolean isFaceCubic, float[] brightness, int[] lightmap) { if (quad.hasAmbientOcclusion()) return false; @@ -550,22 +506,17 @@ public class ForgeHooksClient return true; } - public static void loadEntityShader(Entity entity, GameRenderer entityRenderer) - { - if (entity != null) - { + public static void loadEntityShader(Entity entity, GameRenderer entityRenderer) { + if (entity != null) { ResourceLocation shader = EntitySpectatorShaderManager.get(entity.getType()); if (shader != null) - { entityRenderer.loadEffect(shader); - } } } private static int slotMainHand = 0; - public static boolean shouldCauseReequipAnimation(@NotNull ItemStack from, @NotNull ItemStack to, int slot) - { + public static boolean shouldCauseReequipAnimation(@NotNull ItemStack from, @NotNull ItemStack to, int slot) { boolean fromInvalid = from.isEmpty(); boolean toInvalid = to.isEmpty(); @@ -573,92 +524,77 @@ public class ForgeHooksClient if (fromInvalid || toInvalid) return true; boolean changed = false; - if (slot != -1) - { + if (slot != -1) { changed = slot != slotMainHand; slotMainHand = slot; } return from.getItem().shouldCauseReequipAnimation(from, to, changed); } - public static CustomizeGuiOverlayEvent.BossEventProgress onCustomizeBossEventProgress(GuiGraphics guiGraphics, Window window, LerpingBossEvent bossInfo, int x, int y, int increment) - { + public static CustomizeGuiOverlayEvent.BossEventProgress onCustomizeBossEventProgress(GuiGraphics guiGraphics, Window window, LerpingBossEvent bossInfo, int x, int y, int increment) { CustomizeGuiOverlayEvent.BossEventProgress evt = new CustomizeGuiOverlayEvent.BossEventProgress(window, guiGraphics, Minecraft.getInstance().getPartialTick(), bossInfo, x, y, increment); MinecraftForge.EVENT_BUS.post(evt); return evt; } - public static ScreenshotEvent onScreenshot(NativeImage image, File screenshotFile) - { + public static ScreenshotEvent onScreenshot(NativeImage image, File screenshotFile) { ScreenshotEvent event = new ScreenshotEvent(image, screenshotFile); MinecraftForge.EVENT_BUS.post(event); return event; } - public static void onClientChangeGameType(PlayerInfo info, GameType currentGameMode, GameType newGameMode) - { - if (currentGameMode != newGameMode) - { + public static void onClientChangeGameType(PlayerInfo info, GameType currentGameMode, GameType newGameMode) { + if (currentGameMode != newGameMode) { ClientPlayerChangeGameTypeEvent evt = new ClientPlayerChangeGameTypeEvent(info, currentGameMode, newGameMode); MinecraftForge.EVENT_BUS.post(evt); } } - public static void onMovementInputUpdate(Player player, Input movementInput) - { + public static void onMovementInputUpdate(Player player, Input movementInput) { MinecraftForge.EVENT_BUS.post(new MovementInputUpdateEvent(player, movementInput)); } - public static boolean onScreenKeyPressedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers) - { + public static boolean onScreenKeyPressedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers) { Event event = new ScreenEvent.KeyPressed.Pre(guiScreen, keyCode, scanCode, modifiers); return MinecraftForge.EVENT_BUS.post(event); } - public static boolean onScreenKeyPressedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers) - { + public static boolean onScreenKeyPressedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers) { Event event = new ScreenEvent.KeyPressed.Post(guiScreen, keyCode, scanCode, modifiers); return MinecraftForge.EVENT_BUS.post(event); } - public static boolean onScreenKeyReleasedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers) - { + public static boolean onScreenKeyReleasedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers) { Event event = new ScreenEvent.KeyReleased.Pre(guiScreen, keyCode, scanCode, modifiers); return MinecraftForge.EVENT_BUS.post(event); } - public static boolean onScreenKeyReleasedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers) - { + public static boolean onScreenKeyReleasedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers) { Event event = new ScreenEvent.KeyReleased.Post(guiScreen, keyCode, scanCode, modifiers); return MinecraftForge.EVENT_BUS.post(event); } - public static boolean onScreenCharTypedPre(Screen guiScreen, char codePoint, int modifiers) - { + public static boolean onScreenCharTypedPre(Screen guiScreen, char codePoint, int modifiers) { Event event = new ScreenEvent.CharacterTyped.Pre(guiScreen, codePoint, modifiers); return MinecraftForge.EVENT_BUS.post(event); } - public static void onScreenCharTypedPost(Screen guiScreen, char codePoint, int modifiers) - { + public static void onScreenCharTypedPost(Screen guiScreen, char codePoint, int modifiers) { Event event = new ScreenEvent.CharacterTyped.Post(guiScreen, codePoint, modifiers); MinecraftForge.EVENT_BUS.post(event); } - public static void onRecipesUpdated(RecipeManager mgr) - { + public static void onRecipesUpdated(RecipeManager mgr) { Event event = new RecipesUpdatedEvent(mgr); MinecraftForge.EVENT_BUS.post(event); } - public static void onKeyInput(int key, int scanCode, int action, int modifiers) - { + public static void onKeyInput(int key, int scanCode, int action, int modifiers) { MinecraftForge.EVENT_BUS.post(new InputEvent.Key(key, scanCode, action, modifiers)); } - public static InputEvent.InteractionKeyMappingTriggered onClickInput(int button, KeyMapping keyBinding, InteractionHand hand) - { + public static InputEvent.InteractionKeyMappingTriggered onClickInput(int button, KeyMapping keyBinding, InteractionHand hand) { InputEvent.InteractionKeyMappingTriggered event = new InputEvent.InteractionKeyMappingTriggered(button, keyBinding, hand); MinecraftForge.EVENT_BUS.post(event); return event; @@ -676,15 +612,13 @@ public class ForgeHooksClient public static void renderPistonMovedBlocks(BlockPos pos, BlockState state, PoseStack stack, MultiBufferSource bufferSource, Level level, boolean checkSides, int packedOverlay, BlockRenderDispatcher blockRenderer) { var model = blockRenderer.getBlockModel(state); - for (var renderType : model.getRenderTypes(state, RandomSource.create(state.getSeed(pos)), ModelData.EMPTY)) - { + for (var renderType : model.getRenderTypes(state, RandomSource.create(state.getSeed(pos)), ModelData.EMPTY)) { VertexConsumer vertexConsumer = bufferSource.getBuffer(RenderTypeHelper.getMovingBlockRenderType(renderType)); blockRenderer.getModelRenderer().tesselateBlock(level, model, state, pos, stack, vertexConsumer, checkSides, RandomSource.create(), state.getSeed(pos), packedOverlay, ModelData.EMPTY, renderType); } } - public static boolean shouldRenderEffect(MobEffectInstance effectInstance) - { + public static boolean shouldRenderEffect(MobEffectInstance effectInstance) { return IClientMobEffectExtensions.of(effectInstance).isVisibleInInventory(effectInstance); } @@ -701,24 +635,16 @@ public class ForgeHooksClient } @Nullable - public static TextureAtlasSprite loadTextureAtlasSprite( - ResourceLocation atlasName, - SpriteContents contents, - int atlasWidth, int atlasHeight, - int spriteX, int spriteY, int mipmapLevel - ) - { + public static TextureAtlasSprite loadTextureAtlasSprite(ResourceLocation atlasName, SpriteContents contents, int atlasWidth, int atlasHeight, int spriteX, int spriteY, int mipmapLevel) { if (contents.forgeMeta == null || contents.forgeMeta.getLoader() == null) return null; return contents.forgeMeta.getLoader().makeSprite(atlasName, contents, atlasWidth, atlasHeight, spriteX, spriteY, mipmapLevel); } - private static final Map> layerDefinitions = new HashMap<>(); - public static void registerLayerDefinition(ModelLayerLocation layerLocation, Supplier supplier) - { + public static void registerLayerDefinition(ModelLayerLocation layerLocation, Supplier supplier) { layerDefinitions.put(layerLocation, supplier); } @@ -726,15 +652,14 @@ public class ForgeHooksClient layerDefinitions.forEach((k, v) -> builder.put(k, v.get())); } - public static void processForgeListPingData(ServerStatus packet, ServerData target) - { - packet.forgeData().ifPresentOrElse(forgeData -> - { + public static void processForgeListPingData(ServerStatus packet, ServerData target) { + packet.forgeData().ifPresentOrElse(forgeData -> { final Map mods = forgeData.getRemoteModData(); final Map remoteChannels = forgeData.getRemoteChannels(); final int fmlver = forgeData.getFMLNetworkVersion(); - boolean fmlNetMatches = fmlver == NetworkConstants.FMLNETVERSION; + int wantedVer = NetworkInitialization.getVersion(); + boolean fmlNetMatches = fmlver == wantedVer; boolean channelsMatch = NetworkRegistry.checkListPingCompatibilityForClient(remoteChannels); AtomicBoolean result = new AtomicBoolean(true); final List extraClientMods = new ArrayList<>(); @@ -742,15 +667,14 @@ public class ForgeHooksClient mc.getCustomExtension(IExtensionPoint.DisplayTest.class).ifPresent(ext-> { boolean foundModOnServer = ext.remoteVersionTest().test(mods.get(modid), true); result.compareAndSet(true, foundModOnServer); - if (!foundModOnServer) { + if (!foundModOnServer) extraClientMods.add(modid); - } }) ); boolean modsMatch = result.get(); final Map extraServerMods = mods.entrySet().stream(). - filter(e -> !Objects.equals(NetworkConstants.IGNORESERVERONLY, e.getValue())). + filter(e -> !Objects.equals(IExtensionPoint.DisplayTest.IGNORESERVERONLY, e.getValue())). filter(e -> !ModList.get().isLoaded(e.getKey())). collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); @@ -764,20 +688,19 @@ public class ForgeHooksClient .map(e -> e.getKey() + "@" + e.getValue()) .collect(Collectors.joining(", "))); } + if (!modsMatch) { extraReason = "fml.menu.multiplayer.modsincompatible"; LOGGER.info(CLIENTHOOKS, "Client has mods that are missing on server: {}", extraClientMods); } - if (!channelsMatch) { - extraReason = "fml.menu.multiplayer.networkincompatible"; - } - if (fmlver < NetworkConstants.FMLNETVERSION) { + if (!channelsMatch) + extraReason = "fml.menu.multiplayer.networkincompatible"; + if (fmlver < wantedVer) extraReason = "fml.menu.multiplayer.serveroutdated"; - } - if (fmlver > NetworkConstants.FMLNETVERSION) { + if (fmlver > wantedVer) extraReason = "fml.menu.multiplayer.clientoutdated"; - } + target.forgeData = new ExtendedServerListData("FML", extraServerMods.isEmpty() && fmlNetMatches && channelsMatch && modsMatch, mods.size(), extraReason, forgeData.isTruncated()); }, () -> target.forgeData = new ExtendedServerListData("VANILLA", NetworkRegistry.canConnectToVanillaServer(),0, null)); } @@ -803,9 +726,7 @@ public class ForgeHooksClient } } if (target.forgeData.truncated()) - { tooltip += "\n" + ForgeI18n.parseMessage("fml.menu.multiplayer.truncated"); - } break; case "VANILLA": if (target.forgeData.isCompatible()) { @@ -830,19 +751,15 @@ public class ForgeHooksClient } } - private static Connection getClientConnection() - { + private static Connection getClientConnection() { return Minecraft.getInstance().getConnection()!=null ? Minecraft.getInstance().getConnection().getConnection() : null; } - public static void handleClientLevelClosing(ClientLevel level) - { + public static void handleClientLevelClosing(ClientLevel level) { Connection client = getClientConnection(); // ONLY revert a non-local connection if (client != null && !client.isMemoryConnection()) - { GameData.revertToFrozen(); - } } public static void firePlayerLogin(MultiPlayerGameMode pc, LocalPlayer player, Connection networkManager) { @@ -870,15 +787,13 @@ public class ForgeHooksClient } @Nullable - public static Component onClientChat(ChatType.Bound boundChatType, Component message, UUID sender) - { + public static Component onClientChat(ChatType.Bound boundChatType, Component message, UUID sender) { ClientChatReceivedEvent event = new ClientChatReceivedEvent(boundChatType, message, sender); return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage(); } @Nullable - public static Component onClientPlayerChat(ChatType.Bound boundChatType, Component message, PlayerChatMessage playerChatMessage, UUID sender) - { + public static Component onClientPlayerChat(ChatType.Bound boundChatType, Component message, PlayerChatMessage playerChatMessage, UUID sender) { ClientChatReceivedEvent.Player event = new ClientChatReceivedEvent.Player(boundChatType, message, playerChatMessage, sender); return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage(); } @@ -888,15 +803,13 @@ public class ForgeHooksClient private static final ChatType.Bound SYSTEM_CHAT_TYPE_BOUND = SYSTEM_CHAT_TYPE.bind(Component.literal("System")); @Nullable - public static Component onClientSystemChat(Component message, boolean overlay) - { + public static Component onClientSystemChat(Component message, boolean overlay) { ClientChatReceivedEvent.System event = new ClientChatReceivedEvent.System(SYSTEM_CHAT_TYPE_BOUND, message, overlay); return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage(); } @NotNull - public static String onClientSendMessage(String message) - { + public static String onClientSendMessage(String message) { ClientChatEvent event = new ClientChatEvent(message); return MinecraftForge.EVENT_BUS.post(event) ? "" : event.getMessage(); } @@ -906,58 +819,49 @@ public class ForgeHooksClient * for the input {@link RenderType}. */ @NotNull - public static RenderType getEntityRenderType(RenderType chunkRenderType, boolean cull) - { + public static RenderType getEntityRenderType(RenderType chunkRenderType, boolean cull) { return RenderTypeHelper.getEntityRenderType(chunkRenderType, cull); } @Mod.EventBusSubscriber(value = Dist.CLIENT, modid="forge", bus= Mod.EventBusSubscriber.Bus.MOD) - public static class ClientEvents - { + public static class ClientEvents { @Nullable private static ShaderInstance rendertypeEntityTranslucentUnlitShader; - public static ShaderInstance getEntityTranslucentUnlitShader() - { + public static ShaderInstance getEntityTranslucentUnlitShader() { return Objects.requireNonNull(rendertypeEntityTranslucentUnlitShader, "Attempted to call getEntityTranslucentUnlitShader before shaders have finished loading."); } @SubscribeEvent - public static void registerShaders(RegisterShadersEvent event) throws IOException - { + public static void registerShaders(RegisterShadersEvent event) throws IOException { event.registerShader(new ShaderInstance(event.getResourceProvider(), new ResourceLocation("forge","rendertype_entity_unlit_translucent"), DefaultVertexFormat.NEW_ENTITY), (p_172645_) -> { rendertypeEntityTranslucentUnlitShader = p_172645_; }); } } - public static Font getTooltipFont(@NotNull ItemStack stack, Font fallbackFont) - { + public static Font getTooltipFont(@NotNull ItemStack stack, Font fallbackFont) { Font stackFont = IClientItemExtensions.of(stack).getFont(stack, IClientItemExtensions.FontContext.TOOLTIP); return stackFont == null ? fallbackFont : stackFont; } - public static RenderTooltipEvent.Pre onRenderTooltipPre(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, int screenWidth, int screenHeight, @NotNull List components, @NotNull Font fallbackFont, @NotNull ClientTooltipPositioner positioner) - { + public static RenderTooltipEvent.Pre onRenderTooltipPre(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, int screenWidth, int screenHeight, @NotNull List components, @NotNull Font fallbackFont, @NotNull ClientTooltipPositioner positioner) { var preEvent = new RenderTooltipEvent.Pre(stack, graphics, x, y, screenWidth, screenHeight, getTooltipFont(stack, fallbackFont), components, positioner); MinecraftForge.EVENT_BUS.post(preEvent); return preEvent; } - public static RenderTooltipEvent.Color onRenderTooltipColor(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, @NotNull Font font, @NotNull List components) - { + public static RenderTooltipEvent.Color onRenderTooltipColor(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, @NotNull Font font, @NotNull List components) { var colorEvent = new RenderTooltipEvent.Color(stack, graphics, x, y, font, 0xf0100010, 0x505000FF, 0x5028007f, components); MinecraftForge.EVENT_BUS.post(colorEvent); return colorEvent; } - public static List gatherTooltipComponents(ItemStack stack, List textElements, int mouseX, int screenWidth, int screenHeight, Font fallbackFont) - { + public static List gatherTooltipComponents(ItemStack stack, List textElements, int mouseX, int screenWidth, int screenHeight, Font fallbackFont) { return gatherTooltipComponents(stack, textElements, Optional.empty(), mouseX, screenWidth, screenHeight, fallbackFont); } - public static List gatherTooltipComponents(ItemStack stack, List textElements, Optional itemComponent, int mouseX, int screenWidth, int screenHeight, Font fallbackFont) - { + public static List gatherTooltipComponents(ItemStack stack, List textElements, Optional itemComponent, int mouseX, int screenWidth, int screenHeight, Font fallbackFont) { Font font = getTooltipFont(stack, fallbackFont); List> elements = textElements.stream() .map((Function>) Either::left) @@ -977,11 +881,9 @@ public class ForgeHooksClient boolean needsWrap = false; int tooltipX = mouseX + 12; - if (tooltipX + tooltipTextWidth + 4 > screenWidth) - { + if (tooltipX + tooltipTextWidth + 4 > screenWidth) { tooltipX = mouseX - 16 - tooltipTextWidth; - if (tooltipX < 4) // if the tooltip doesn't fit on the screen - { + if (tooltipX < 4) { // if the tooltip doesn't fit on the screen if (mouseX > screenWidth / 2) tooltipTextWidth = mouseX - 12 - 8; else @@ -990,15 +892,13 @@ public class ForgeHooksClient } } - if (event.getMaxWidth() > 0 && tooltipTextWidth > event.getMaxWidth()) - { + if (event.getMaxWidth() > 0 && tooltipTextWidth > event.getMaxWidth()) { tooltipTextWidth = event.getMaxWidth(); needsWrap = true; } int tooltipTextWidthF = tooltipTextWidth; - if (needsWrap) - { + if (needsWrap) { return event.getTooltipElements().stream() .flatMap(either -> either.map( text -> splitLine(text, font, tooltipTextWidthF), @@ -1014,115 +914,83 @@ public class ForgeHooksClient .toList(); } - private static Stream splitLine(FormattedText text, Font font, int maxWidth) - { + private static Stream splitLine(FormattedText text, Font font, int maxWidth) { if (text instanceof Component component && component.getString().isEmpty()) - { return Stream.of(component.getVisualOrderText()).map(ClientTooltipComponent::create); - } return font.split(text, maxWidth).stream().map(ClientTooltipComponent::create); } - public static Comparator makeParticleRenderTypeComparator(List renderOrder) - { + public static Comparator makeParticleRenderTypeComparator(List renderOrder) { Comparator vanillaComparator = Comparator.comparingInt(renderOrder::indexOf); - return (typeOne, typeTwo) -> - { + return (typeOne, typeTwo) -> { boolean vanillaOne = renderOrder.contains(typeOne); boolean vanillaTwo = renderOrder.contains(typeTwo); if (vanillaOne && vanillaTwo) - { return vanillaComparator.compare(typeOne, typeTwo); - } if (!vanillaOne && !vanillaTwo) - { return Integer.compare(System.identityHashCode(typeOne), System.identityHashCode(typeTwo)); - } return vanillaOne ? -1 : 1; }; } - public static ScreenEvent.RenderInventoryMobEffects onScreenPotionSize(Screen screen, int availableSpace, boolean compact, int horizontalOffset) - { + public static ScreenEvent.RenderInventoryMobEffects onScreenPotionSize(Screen screen, int availableSpace, boolean compact, int horizontalOffset) { final ScreenEvent.RenderInventoryMobEffects event = new ScreenEvent.RenderInventoryMobEffects(screen, availableSpace, compact, horizontalOffset); MinecraftForge.EVENT_BUS.post(event); return event; } - public static boolean onToastAdd(Toast toast) - { + public static boolean onToastAdd(Toast toast) { return MinecraftForge.EVENT_BUS.post(new ToastAddEvent(toast)); } - public static boolean isBlockInSolidLayer(BlockState state) - { + public static boolean isBlockInSolidLayer(BlockState state) { var model = Minecraft.getInstance().getBlockRenderer().getBlockModel(state); return model.getRenderTypes(state, RandomSource.create(), ModelData.EMPTY).contains(RenderType.solid()); } - public static void createWorldConfirmationScreen(Runnable doConfirmedWorldLoad) - { + public static void createWorldConfirmationScreen(Runnable doConfirmedWorldLoad) { Component title = Component.translatable("selectWorld.backupQuestion.experimental"); Component msg = Component.translatable("selectWorld.backupWarning.experimental") .append("\n\n") .append(Component.translatable("forge.selectWorld.backupWarning.experimental.additional")); - Screen screen = new ConfirmScreen(confirmed -> - { + Screen screen = new ConfirmScreen(confirmed -> { if (confirmed) - { doConfirmedWorldLoad.run(); - } else - { Minecraft.getInstance().setScreen(null); - } }, title, msg, CommonComponents.GUI_PROCEED, CommonComponents.GUI_CANCEL); Minecraft.getInstance().setScreen(screen); } - public static boolean renderFireOverlay(Player player, PoseStack mat) - { + public static boolean renderFireOverlay(Player player, PoseStack mat) { return renderBlockOverlay(player, mat, RenderBlockScreenEffectEvent.OverlayType.FIRE, Blocks.FIRE.defaultBlockState(), player.blockPosition()); } - public static boolean renderWaterOverlay(Player player, PoseStack mat) - { + public static boolean renderWaterOverlay(Player player, PoseStack mat) { return renderBlockOverlay(player, mat, RenderBlockScreenEffectEvent.OverlayType.WATER, Blocks.WATER.defaultBlockState(), player.blockPosition()); } - public static boolean renderBlockOverlay(Player player, PoseStack mat, RenderBlockScreenEffectEvent.OverlayType type, BlockState block, BlockPos pos) - { + public static boolean renderBlockOverlay(Player player, PoseStack mat, RenderBlockScreenEffectEvent.OverlayType type, BlockState block, BlockPos pos) { return MinecraftForge.EVENT_BUS.post(new RenderBlockScreenEffectEvent(player, mat, type, block, pos)); } - public static int getMaxMipmapLevel(int width, int height) - { + public static int getMaxMipmapLevel(int width, int height) { return Math.min( Mth.log2(Math.max(1, width)), Mth.log2(Math.max(1, height)) ); } - public static ResourceLocation getShaderImportLocation(String basePath, boolean isRelative, String importPath) - { + public static ResourceLocation getShaderImportLocation(String basePath, boolean isRelative, String importPath) { final var loc = new ResourceLocation(importPath); final var normalised = FileUtil.normalizeResourcePath( (isRelative ? basePath : "shaders/include/") + loc.getPath()); return new ResourceLocation(loc.getNamespace(), normalised); } - // Use ForgeHooks.onCreativeModeTabBuildContents() - // since calling this will crash if called on server - @Deprecated(forRemoval = true, since = "1.20.1") - public static void onCreativeModeTabBuildContents(CreativeModeTab tab, ResourceKey tabKey, CreativeModeTab.DisplayItemsGenerator originalGenerator, CreativeModeTab.ItemDisplayParameters params, CreativeModeTab.Output output) - { - // Bounce to ForgeHooks.onCreativeModeBuildContents(...) - ForgeHooks.onCreativeModeTabBuildContents(tab, tabKey, originalGenerator, params, output); - } - /** * This function is a clone of {@link Direction#getNearest(float, float, float)} designed to return a consistent * direction when the normal is at an inflection point (ie 45 degrees) rounding errors @@ -1138,8 +1006,7 @@ public class ForgeHooksClient * @param nZ Z component of the normal * @return the nearest Direction to the passed in normal, biased slightly in favor of the order of declaration */ - public static Direction getNearestStable(float nX, float nY, float nZ) - { + public static Direction getNearestStable(float nX, float nY, float nZ) { if (ForgeConfig.CLIENT.stabilizeDirectionGetNearest.get()) { Direction ret = Direction.NORTH; float sum = Float.MIN_VALUE; @@ -1151,21 +1018,17 @@ public class ForgeHooksClient } } return ret; - } else { + } else return Direction.getNearest(nX, nY, nZ); - } } // Make sure the below method is only ever called once (by forge). private static boolean initializedClientHooks = false; // Runs during Minecraft construction, before initial resource loading. @ApiStatus.Internal - public static void initClientHooks(Minecraft mc, ReloadableResourceManager resourceManager) - { + public static void initClientHooks(Minecraft mc, ReloadableResourceManager resourceManager) { if (initializedClientHooks) - { throw new IllegalStateException("Client hooks initialized more than once"); - } initializedClientHooks = true; ForgeGameTestHooks.registerGametests(); @@ -1184,4 +1047,12 @@ public class ForgeHooksClient ItemDecoratorHandler.init(); PresetEditorManager.init(); } + + public static boolean onClientDisconnect(Connection connection, Minecraft mc, Screen parent, Component message) { + var mismatch = NetworkContext.get(connection).getMismatchs(); + if (mismatch == null) + return false; + mc.setScreen(new ModMismatchDisconnectedScreen(parent, CommonComponents.CONNECT_FAILED, message, mismatch)); + return true; + } } diff --git a/src/main/java/net/minecraftforge/client/event/ForgeEventFactoryClient.java b/src/main/java/net/minecraftforge/client/event/ForgeEventFactoryClient.java new file mode 100644 index 0000000000..b186e01c18 --- /dev/null +++ b/src/main/java/net/minecraftforge/client/event/ForgeEventFactoryClient.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.client.event; + +import java.util.Map; + +import org.jetbrains.annotations.Nullable; + +import net.minecraft.client.MouseHandler; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.renderer.entity.EntityRenderer; +import net.minecraft.client.renderer.entity.EntityRendererProvider.Context; +import net.minecraft.client.resources.PlayerSkin.Model; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.player.Player; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.fml.ModLoader; + +public class ForgeEventFactoryClient { + private static boolean post(Event e) { + return MinecraftForge.EVENT_BUS.post(e); + } + + private static E fire(E e) { + MinecraftForge.EVENT_BUS.post(e); + return e; + } + + public static void gatherLayers(Map, EntityRenderer> renderers, Map> playerRenderers, Context context) { + // TODO: Why is this a ModLoader event... + ModLoader.get().postEvent(new EntityRenderersEvent.AddLayers(renderers, playerRenderers, context)); + } + + public static boolean onScreenMouseReleasedPre(Screen guiScreen, double mouseX, double mouseY, int button) { + return post(new ScreenEvent.MouseButtonReleased.Pre(guiScreen, mouseX, mouseY, button)); + } + + public static boolean onScreenMouseReleasedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled) { + var result = fire(new ScreenEvent.MouseButtonReleased.Post(guiScreen, mouseX, mouseY, button, handled)).getResult(); + return result == Event.Result.DEFAULT ? handled : result == Event.Result.ALLOW; + } + + public static boolean onScreenMouseClickedPre(Screen guiScreen, double mouseX, double mouseY, int button) { + return post(new ScreenEvent.MouseButtonPressed.Pre(guiScreen, mouseX, mouseY, button)); + } + + public static boolean onScreenMouseClickedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled) { + var result = fire(new ScreenEvent.MouseButtonPressed.Post(guiScreen, mouseX, mouseY, button, handled)).getResult(); + return result == Event.Result.DEFAULT ? handled : result == Event.Result.ALLOW; + } + + public static boolean onMouseButtonPre(int button, int action, int mods) { + return post(new InputEvent.MouseButton.Pre(button, action, mods)); + } + + public static void onMouseButtonPost(int button, int action, int mods) { + post(new InputEvent.MouseButton.Post(button, action, mods)); + } + + public static boolean onScreenMouseScrollPre(Screen guiScreen, double mouseX, double mouseY, double deltaX, double deltaY) { + return post(new ScreenEvent.MouseScrolled.Pre(guiScreen, mouseX, mouseY, deltaX, deltaY)); + } + + public static void onScreenMouseScrollPost(Screen guiScreen, double mouseX, double mouseY, double deltaX, double deltaY) { + post(new ScreenEvent.MouseScrolled.Post(guiScreen, mouseX, mouseY, deltaX, deltaY)); + } + + public static boolean onMouseScroll(MouseHandler mouseHelper, double deltaX, double deltaY) { + return post(new InputEvent.MouseScrollingEvent(deltaX, deltaY, mouseHelper.isLeftPressed(), mouseHelper.isMiddlePressed(), mouseHelper.isRightPressed(), mouseHelper.xpos(), mouseHelper.ypos())); + } + + public static boolean onScreenMouseDragPre(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) { + return post(new ScreenEvent.MouseDragged.Pre(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY)); + } + + public static void onScreenMouseDragPost(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) { + post(new ScreenEvent.MouseDragged.Post(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY)); + } + + public static @Nullable Screen onScreenOpening(Screen old, Screen screen) { + var event = new ScreenEvent.Opening(old, screen); + if (post(event)) + return null; + return event.getNewScreen(); + } + + public static void onScreenClose(Screen screen) { + post(new ScreenEvent.Closing(screen)); + } +} diff --git a/src/main/java/net/minecraftforge/client/gui/ModMismatchDisconnectedScreen.java b/src/main/java/net/minecraftforge/client/gui/ModMismatchDisconnectedScreen.java index f07aabd80e..3d4d19fa6e 100644 --- a/src/main/java/net/minecraftforge/client/gui/ModMismatchDisconnectedScreen.java +++ b/src/main/java/net/minecraftforge/client/gui/ModMismatchDisconnectedScreen.java @@ -10,7 +10,6 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Optional; import java.util.stream.Collectors; @@ -39,46 +38,43 @@ import net.minecraft.util.FormattedCharSequence; import net.minecraftforge.common.ForgeI18n; import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.loading.FMLPaths; -import net.minecraftforge.network.ConnectionData.ModMismatchData; -import net.minecraftforge.network.NetworkRegistry; +import net.minecraftforge.network.NetworkContext.NetworkMismatchData; +import net.minecraftforge.network.packets.ModVersions; -public class ModMismatchDisconnectedScreen extends Screen -{ +//TODO: Oh god... Whoever wrote this was on something very very strong. +public class ModMismatchDisconnectedScreen extends Screen { private final Component reason; private MultiLineLabel message = MultiLineLabel.EMPTY; private final Screen parent; private int textHeight; - private final ModMismatchData modMismatchData; private final Path modsDir; private final Path logFile; private final int listHeight; - private final Map> presentModData; - private final List missingModData; - private final Map mismatchedModData; + private final NetworkMismatchData data; + private final boolean hasMismatches; + private final List allModIds; private final Map presentModUrls; - private final boolean mismatchedDataFromServer; - public ModMismatchDisconnectedScreen(Screen parentScreen, Component title, Component reason, ModMismatchData modMismatchData) - { + public ModMismatchDisconnectedScreen(Screen parentScreen, Component title, Component reason, NetworkMismatchData data) { super(title); this.parent = parentScreen; this.reason = reason; - this.modMismatchData = modMismatchData; this.modsDir = FMLPaths.MODSDIR.get(); this.logFile = FMLPaths.GAMEDIR.get().resolve(Paths.get("logs","latest.log")); - this.listHeight = modMismatchData.containsMismatches() ? 140 : 0; - this.mismatchedDataFromServer = modMismatchData.mismatchedDataFromServer(); - this.presentModData = modMismatchData.presentModData(); - this.missingModData = modMismatchData.mismatchedModData().entrySet().stream().filter(e -> e.getValue().equals(NetworkRegistry.ABSENT.version())).map(Entry::getKey).collect(Collectors.toList()); - this.mismatchedModData = modMismatchData.mismatchedModData().entrySet().stream().filter(e -> !e.getValue().equals(NetworkRegistry.ABSENT.version())).collect(Collectors.toMap(Entry::getKey, Entry::getValue)); - this.allModIds = presentModData.keySet().stream().map(ResourceLocation::getNamespace).distinct().collect(Collectors.toList()); - this.presentModUrls = ModList.get().getMods().stream().filter(info -> allModIds.contains(info.getModId())).map(info -> Pair.of(info.getModId(), (String)info.getConfig().getConfigElement("displayURL").orElse(""))).collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); + this.data = data; + this.hasMismatches = !data.mismatched().isEmpty() || !data.missing().isEmpty(); + this.listHeight = hasMismatches ? 140 : 0; + + this.allModIds = data.mods().keySet().stream().distinct().collect(Collectors.toList()); + this.presentModUrls = ModList.get().getMods().stream() + .filter(info -> allModIds.contains(info.getModId())) + .map(info -> Pair.of(info.getModId(), (String)info.getConfig().getConfigElement("displayURL").orElse(""))) + .collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); } @Override - protected void init() - { + protected void init() { this.message = MultiLineLabel.create(this.font, this.reason, this.width - 50); this.textHeight = this.message.getLineCount() * 9; @@ -86,7 +82,7 @@ public class ModMismatchDisconnectedScreen extends Screen int listWidth = Math.min(440, this.width - 16); int upperButtonHeight = Math.min((this.height + this.listHeight + this.textHeight) / 2 + 10, this.height - 50); int lowerButtonHeight = Math.min((this.height + this.listHeight + this.textHeight) / 2 + 35, this.height - 25); - if (modMismatchData.containsMismatches()) + if (hasMismatches) this.addRenderableWidget(new MismatchInfoPanel(minecraft, listWidth, listHeight, (this.height - this.listHeight) / 2, listLeft)); int buttonWidth = Math.min(210, this.width / 2 - 20); @@ -102,17 +98,15 @@ public class ModMismatchDisconnectedScreen extends Screen } @Override - public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) - { + public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) { this.renderBackground(guiGraphics, mouseX, mouseY, partialTicks); - int textYOffset = modMismatchData.containsMismatches() ? 18 : 0; + int textYOffset = hasMismatches ? 18 : 0; guiGraphics.drawCenteredString(this.font, this.title, this.width / 2, (this.height - this.listHeight - this.textHeight) / 2 - textYOffset - 9 * 2, 0xAAAAAA); this.message.renderCentered(guiGraphics, this.width / 2, (this.height - this.listHeight - this.textHeight) / 2 - textYOffset); super.render(guiGraphics, mouseX, mouseY, partialTicks); } - class MismatchInfoPanel extends ScrollPanel - { + class MismatchInfoPanel extends ScrollPanel { private final List>> lineTable; private final int contentSize; private final int nameIndent = 10; @@ -120,41 +114,69 @@ public class ModMismatchDisconnectedScreen extends Screen private final int nameWidth = tableWidth * 3 / 5; private final int versionWidth = (tableWidth - nameWidth) / 2; - public MismatchInfoPanel(Minecraft client, int width, int height, int top, int left) - { + public MismatchInfoPanel(Minecraft client, int width, int height, int top, int left) { super(client, width, height, top, left); //The raw list of the strings in a table row, the components may still be too long for the final table and will be split up later. The first row element may have a style assigned to it that will be used for the whole content row. List>> rawTable = new ArrayList<>(); - if (!missingModData.isEmpty()) - { + if (!data.missing().isEmpty()) { //The header of the section, colored in gray - rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage(mismatchedDataFromServer ? "fml.modmismatchscreen.missingmods.server" : "fml.modmismatchscreen.missingmods.client")).withStyle(ChatFormatting.GRAY), null)); + rawTable.add(Pair.of( + Component.literal(ForgeI18n.parseMessage(data.fromServer() ? "fml.modmismatchscreen.missingmods.server" : "fml.modmismatchscreen.missingmods.client")).withStyle(ChatFormatting.GRAY), + null + )); //This table section contains the mod name and mod version of each mod that has a missing remote counterpart (if the mod is missing on the server, the client mod version is displayed, and vice versa) - rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.table.modname")).withStyle(ChatFormatting.UNDERLINE), Pair.of("", ForgeI18n.parseMessage(mismatchedDataFromServer ? "fml.modmismatchscreen.table.youhave" : "fml.modmismatchscreen.table.youneed")))); + rawTable.add(Pair.of( + Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.table.modname")).withStyle(ChatFormatting.UNDERLINE), + Pair.of( + "", + ForgeI18n.parseMessage(data.fromServer() ? "fml.modmismatchscreen.table.youhave" : "fml.modmismatchscreen.table.youneed") + ) + )); int i = 0; - for (ResourceLocation mod : missingModData) { - rawTable.add(Pair.of(toModNameComponent(mod, presentModData.get(mod).getLeft(), i), Pair.of("", presentModData.getOrDefault(mod, Pair.of("", "")).getRight()))); + for (ResourceLocation mod : data.missing()) { + rawTable.add(Pair.of( + toModNameComponent(mod, data.mods().get(mod.getNamespace()).name(), i), + Pair.of( + "", + data.mods().getOrDefault(mod, new ModVersions.Info("", "")).version() + ) + )); if (++i >= 10) { //If too many missing mod entries are present, append a line referencing how to see the full list and stop rendering any more entries - rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.additional", missingModData.size() - i)).withStyle(ChatFormatting.ITALIC), Pair.of("", ""))); + rawTable.add(Pair.of( + Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.additional", data.missing().size() - i)).withStyle(ChatFormatting.ITALIC), + Pair.of("", "") + )); break; } } rawTable.add(Pair.of(Component.literal(" "), null)); //padding } - if (!mismatchedModData.isEmpty()) - { + + if (!data.mismatched().isEmpty()) { //The header of the table section, colored in gray rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.mismatchedmods")).withStyle(ChatFormatting.GRAY), null)); //This table section contains the mod name and both mod versions of each mod that has a mismatching client and server version - rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.table.modname")).withStyle(ChatFormatting.UNDERLINE), Pair.of(ForgeI18n.parseMessage(mismatchedDataFromServer ? "fml.modmismatchscreen.table.youhave" : "fml.modmismatchscreen.table.serverhas"), ForgeI18n.parseMessage(mismatchedDataFromServer ? "fml.modmismatchscreen.table.serverhas" : "fml.modmismatchscreen.table.youhave")))); + rawTable.add(Pair.of( + Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.table.modname")).withStyle(ChatFormatting.UNDERLINE), + Pair.of( + ForgeI18n.parseMessage(data.fromServer() ? "fml.modmismatchscreen.table.youhave" : "fml.modmismatchscreen.table.serverhas"), + ForgeI18n.parseMessage(data.fromServer() ? "fml.modmismatchscreen.table.serverhas" : "fml.modmismatchscreen.table.youhave") + ) + )); int i = 0; - for (Map.Entry modData : mismatchedModData.entrySet()) { - rawTable.add(Pair.of(toModNameComponent(modData.getKey(), presentModData.get(modData.getKey()).getLeft(), i), Pair.of(presentModData.getOrDefault(modData.getKey(), Pair.of("", "")).getRight(), modData.getValue()))); + for (var modData : data.mismatched().entrySet()) { + rawTable.add(Pair.of( + toModNameComponent(modData.getKey(), data.mods().get(modData.getKey().getNamespace()).name(), i), + Pair.of( + data.mods().getOrDefault(modData.getKey(), new ModVersions.Info("", "")).version(), + modData.getValue().received() + ) + )); if (++i >= 10) { //If too many mismatched mod entries are present, append a line referencing how to see the full list and stop rendering any more entries - rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.additional", mismatchedModData.size() - i)).withStyle(ChatFormatting.ITALIC), Pair.of("", ""))); + rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.additional", data.mismatched().size() - i)).withStyle(ChatFormatting.ITALIC), Pair.of("", ""))); break; } } @@ -172,8 +194,7 @@ public class ModMismatchDisconnectedScreen extends Screen * @param versions The last two elements of the content row, usually representing the mod versions. If either one or both of them are not given, the first element may take up more space within the table. * @return A list of table rows consisting of 3 elements each which consist of the same content as was given by the parameters, but split up to fit within the table dimensions. */ - private List>> splitLineToWidth(MutableComponent name, Pair versions) - { + private List>> splitLineToWidth(MutableComponent name, Pair versions) { Style style = name.getStyle(); int versionColumns = versions == null ? 0 : (versions.getLeft().isEmpty() ? (versions.getRight().isEmpty() ? 0 : 1) : 2); int adaptedNameWidth = nameWidth + versionWidth * (2 - versionColumns) - 4; //the name width may be expanded when the version column string is missing @@ -183,7 +204,13 @@ public class ModMismatchDisconnectedScreen extends Screen List>> splitLines = new ArrayList<>(); int rowsOccupied = Math.max(nameLines.size(), Math.max(clientVersionLines.size(), serverVersionLines.size())); for (int i = 0; i < rowsOccupied; i++) { - splitLines.add(Pair.of(i < nameLines.size() ? nameLines.get(i) : FormattedCharSequence.EMPTY, versions == null ? null : Pair.of(i < clientVersionLines.size() ? clientVersionLines.get(i) : FormattedCharSequence.EMPTY, i < serverVersionLines.size() ? serverVersionLines.get(i) : FormattedCharSequence.EMPTY))); + splitLines.add(Pair.of( + i < nameLines.size() ? nameLines.get(i) : FormattedCharSequence.EMPTY, + versions == null ? null : Pair.of( + i < clientVersionLines.size() ? clientVersionLines.get(i) : FormattedCharSequence.EMPTY, + i < serverVersionLines.size() ? serverVersionLines.get(i) : FormattedCharSequence.EMPTY + ) + )); } return splitLines; } @@ -196,8 +223,7 @@ public class ModMismatchDisconnectedScreen extends Screen * @param color Defines the color of the returned style information. An odd number will result in a yellow, an even one in a gold color. This color variation makes it easier for users to distinguish different mod entries. * @return A component with the mod name as the main text component, and an assigned style which will be used for the whole content row. */ - private MutableComponent toModNameComponent(ResourceLocation id, String modName, int color) - { + private MutableComponent toModNameComponent(ResourceLocation id, String modName, int color) { String modId = id.getNamespace(); String tooltipId = id.getPath().isEmpty() ? id.getNamespace() : id.toString(); return Component.literal(modName).withStyle(color % 2 == 0 ? ChatFormatting.GOLD : ChatFormatting.YELLOW) @@ -206,8 +232,7 @@ public class ModMismatchDisconnectedScreen extends Screen } @Override - protected int getContentHeight() - { + protected int getContentHeight() { int height = contentSize * (font.lineHeight + 3); if (height < bottom - top - 4) @@ -217,8 +242,7 @@ public class ModMismatchDisconnectedScreen extends Screen } @Override - protected void drawPanel(GuiGraphics guiGraphics, int entryRight, int relativeY, Tesselator tess, int mouseX, int mouseY) - { + protected void drawPanel(GuiGraphics guiGraphics, int entryRight, int relativeY, Tesselator tess, int mouseX, int mouseY) { int i = 0; for (Pair> line : lineTable) { @@ -229,8 +253,7 @@ public class ModMismatchDisconnectedScreen extends Screen //Only indent the given name if a version string is present. This makes it easier to distinguish table section headers and mod entries int nameLeft = left + border + (versions == null ? 0 : nameIndent); guiGraphics.drawString(font, name, nameLeft, relativeY + i * 12, color, false); - if (versions != null) - { + if (versions != null) { guiGraphics.drawString(font, versions.getLeft(), left + border + nameIndent + nameWidth, relativeY + i * 12, color, false); guiGraphics.drawString(font, versions.getRight(), left + border + nameIndent + nameWidth + versionWidth, relativeY + i * 12, color, false); } @@ -240,24 +263,18 @@ public class ModMismatchDisconnectedScreen extends Screen } @Override - public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) - { + public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) { super.render(guiGraphics, mouseX, mouseY, partialTicks); Style style = getComponentStyleAt(mouseX, mouseY); if (style != null && style.getHoverEvent() != null) - { guiGraphics.renderComponentHoverEffect(font, style, mouseX, mouseY); - } } - public Style getComponentStyleAt(double x, double y) - { - if (this.isMouseOver(x, y)) - { + public Style getComponentStyleAt(double x, double y) { + if (this.isMouseOver(x, y)) { double relativeY = y - this.top + this.scrollDistance - border; int slotIndex = (int)(relativeY + (border / 2)) / 12; - if (slotIndex < contentSize) - { + if (slotIndex < contentSize) { //The relative x needs to take the potentially missing indent of the row into account. It does that by checking if the line has a version associated to it double relativeX = x - left - border - (lineTable.get(slotIndex).getRight() == null ? 0 : nameIndent); if (relativeX >= 0) @@ -269,8 +286,7 @@ public class ModMismatchDisconnectedScreen extends Screen } @Override - public boolean mouseClicked(final double mouseX, final double mouseY, final int button) - { + public boolean mouseClicked(final double mouseX, final double mouseY, final int button) { Style style = getComponentStyleAt(mouseX, mouseY); if (style != null) { handleComponentClicked(style); @@ -280,8 +296,7 @@ public class ModMismatchDisconnectedScreen extends Screen } @Override - public NarrationPriority narrationPriority() - { + public NarrationPriority narrationPriority() { return NarrationPriority.NONE; } diff --git a/src/main/java/net/minecraftforge/common/ForgeHooks.java b/src/main/java/net/minecraftforge/common/ForgeHooks.java index 7976993c76..f6592705fa 100644 --- a/src/main/java/net/minecraftforge/common/ForgeHooks.java +++ b/src/main/java/net/minecraftforge/common/ForgeHooks.java @@ -5,41 +5,26 @@ package net.minecraftforge.common; -import com.google.common.collect.Queues; import java.net.URI; import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.Deque; import java.util.HashMap; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; -import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; -import com.google.common.collect.Sets; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; import com.mojang.serialization.Dynamic; import com.mojang.serialization.Lifecycle; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import net.minecraft.ResourceLocationException; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.commands.SharedSuggestionProvider; @@ -50,28 +35,21 @@ import net.minecraft.core.HolderLookup; import net.minecraft.core.HolderSet; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.core.registries.Registries; -import net.minecraft.network.chat.ChatDecorator; +import net.minecraft.network.Connection; import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.TextColor; import net.minecraft.network.chat.contents.LiteralContents; import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.packs.PackType; -import net.minecraft.server.packs.metadata.pack.PackMetadataSection; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.tags.BlockTags; -import net.minecraft.tags.TagEntry; import net.minecraft.tags.TagKey; import net.minecraft.util.CrudeIncrementalIntIdentityHashBiMap; -import net.minecraft.util.GsonHelper; import net.minecraft.util.Mth; import net.minecraft.util.datafix.fixes.StructuresBecomeConfiguredFix; import net.minecraft.world.Difficulty; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; -import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectUtil; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; @@ -98,14 +76,11 @@ import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.WorldData; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.LootTable; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.network.FilteredText; import net.minecraft.world.inventory.AnvilMenu; import net.minecraft.world.Container; import net.minecraft.world.item.context.UseOnContext; @@ -147,7 +122,6 @@ import net.minecraftforge.event.VanillaGameEvent; import net.minecraftforge.event.entity.EntityAttributeCreationEvent; import net.minecraftforge.event.entity.EntityAttributeModificationEvent; import net.minecraftforge.event.entity.EntityEvent; -import net.minecraftforge.event.entity.EntityTravelToDimensionEvent; import net.minecraftforge.event.entity.item.ItemTossEvent; import net.minecraftforge.event.entity.living.EnderManAngerEvent; import net.minecraftforge.event.entity.living.LivingAttackEvent; @@ -177,9 +151,17 @@ import net.minecraftforge.event.entity.living.LivingGetProjectileEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.level.BlockEvent; 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.ModList; import net.minecraftforge.fml.ModLoader; +import net.minecraftforge.fml.config.ConfigTracker; +import net.minecraftforge.fml.util.thread.EffectiveSide; +import net.minecraftforge.network.ConnectionType; +import net.minecraftforge.network.ICustomPacket; +import net.minecraftforge.network.NetworkContext; +import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.resource.ResourcePackLoader; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.ForgeRegistry; @@ -187,7 +169,6 @@ import net.minecraftforge.registries.GameData; import net.minecraftforge.registries.RegistryManager; import net.minecraftforge.server.permission.PermissionAPI; -import org.apache.commons.lang3.function.TriFunction; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; @@ -207,124 +188,103 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public class ForgeHooks -{ +public class ForgeHooks { private static final Logger LOGGER = LogManager.getLogger(); @SuppressWarnings("unused") private static final Marker FORGEHOOKS = MarkerManager.getMarker("FORGEHOOKS"); private static final Marker WORLDPERSISTENCE = MarkerManager.getMarker("WP"); - public static boolean canContinueUsing(@NotNull ItemStack from, @NotNull ItemStack to) - { + public static boolean canContinueUsing(@NotNull ItemStack from, @NotNull ItemStack to) { if (!from.isEmpty() && !to.isEmpty()) - { return from.getItem().canContinueUsing(from, to); - } return false; } - public static boolean isCorrectToolForDrops(@NotNull BlockState state, @NotNull Player player) - { + public static boolean isCorrectToolForDrops(@NotNull BlockState state, @NotNull Player player) { if (!state.requiresCorrectToolForDrops()) return ForgeEventFactory.doPlayerHarvestCheck(player, state, true); return player.hasCorrectToolForDrops(state); } - public static boolean onItemStackedOn(ItemStack carriedItem, ItemStack stackedOnItem, Slot slot, ClickAction action, Player player, SlotAccess carriedSlotAccess) - { + public static boolean onItemStackedOn(ItemStack carriedItem, ItemStack stackedOnItem, Slot slot, ClickAction action, Player player, SlotAccess carriedSlotAccess) { return MinecraftForge.EVENT_BUS.post(new ItemStackedOnOtherEvent(carriedItem, stackedOnItem, slot, action, player, carriedSlotAccess)); } - public static void onDifficultyChange(Difficulty difficulty, Difficulty oldDifficulty) - { + public static void onDifficultyChange(Difficulty difficulty, Difficulty oldDifficulty) { MinecraftForge.EVENT_BUS.post(new DifficultyChangeEvent(difficulty, oldDifficulty)); } - public static LivingChangeTargetEvent onLivingChangeTarget(LivingEntity entity, LivingEntity originalTarget, ILivingTargetType targetType) - { + public static LivingChangeTargetEvent onLivingChangeTarget(LivingEntity entity, LivingEntity originalTarget, ILivingTargetType targetType) { LivingChangeTargetEvent event = new LivingChangeTargetEvent(entity, originalTarget, targetType); MinecraftForge.EVENT_BUS.post(event); return event; } - public static Brain onLivingMakeBrain(LivingEntity entity, Brain originalBrain, Dynamic dynamic) - { + public static Brain onLivingMakeBrain(LivingEntity entity, Brain originalBrain, Dynamic dynamic) { BrainBuilder brainBuilder = originalBrain.createBuilder(); LivingMakeBrainEvent event = new LivingMakeBrainEvent(entity, brainBuilder); MinecraftForge.EVENT_BUS.post(event); return brainBuilder.makeBrain(dynamic); } - public static boolean onLivingTick(LivingEntity entity) - { + public static boolean onLivingTick(LivingEntity entity) { return MinecraftForge.EVENT_BUS.post(new LivingTickEvent(entity)); } - public static boolean onLivingAttack(LivingEntity entity, DamageSource src, float amount) - { + public static boolean onLivingAttack(LivingEntity entity, DamageSource src, float amount) { return entity instanceof Player || !MinecraftForge.EVENT_BUS.post(new LivingAttackEvent(entity, src, amount)); } - public static boolean onPlayerAttack(LivingEntity entity, DamageSource src, float amount) - { + public static boolean onPlayerAttack(LivingEntity entity, DamageSource src, float amount) { return !MinecraftForge.EVENT_BUS.post(new LivingAttackEvent(entity, src, amount)); } - public static LivingKnockBackEvent onLivingKnockBack(LivingEntity target, float strength, double ratioX, double ratioZ) - { + public static LivingKnockBackEvent onLivingKnockBack(LivingEntity target, float strength, double ratioX, double ratioZ) { LivingKnockBackEvent event = new LivingKnockBackEvent(target, strength, ratioX, ratioZ); MinecraftForge.EVENT_BUS.post(event); return event; } - public static boolean onLivingUseTotem(LivingEntity entity, DamageSource damageSource, ItemStack totem, InteractionHand hand) - { + public static boolean onLivingUseTotem(LivingEntity entity, DamageSource damageSource, ItemStack totem, InteractionHand hand) { return !MinecraftForge.EVENT_BUS.post(new LivingUseTotemEvent(entity, damageSource, totem, hand)); } - public static float onLivingHurt(LivingEntity entity, DamageSource src, float amount) - { + public static float onLivingHurt(LivingEntity entity, DamageSource src, float amount) { LivingHurtEvent event = new LivingHurtEvent(entity, src, amount); return (MinecraftForge.EVENT_BUS.post(event) ? 0 : event.getAmount()); } - public static float onLivingDamage(LivingEntity entity, DamageSource src, float amount) - { + public static float onLivingDamage(LivingEntity entity, DamageSource src, float amount) { LivingDamageEvent event = new LivingDamageEvent(entity, src, amount); return (MinecraftForge.EVENT_BUS.post(event) ? 0 : event.getAmount()); } - public static boolean onLivingDeath(LivingEntity entity, DamageSource src) - { + public static boolean onLivingDeath(LivingEntity entity, DamageSource src) { return MinecraftForge.EVENT_BUS.post(new LivingDeathEvent(entity, src)); } - public static boolean onLivingDrops(LivingEntity entity, DamageSource source, Collection drops, int lootingLevel, boolean recentlyHit) - { + public static boolean onLivingDrops(LivingEntity entity, DamageSource source, Collection drops, int lootingLevel, boolean recentlyHit) { return MinecraftForge.EVENT_BUS.post(new LivingDropsEvent(entity, source, drops, lootingLevel, recentlyHit)); } @Nullable - public static float[] onLivingFall(LivingEntity entity, float distance, float damageMultiplier) - { + public static float[] onLivingFall(LivingEntity entity, float distance, float damageMultiplier) { LivingFallEvent event = new LivingFallEvent(entity, distance, damageMultiplier); return (MinecraftForge.EVENT_BUS.post(event) ? null : new float[]{event.getDistance(), event.getDamageMultiplier()}); } - public static int getLootingLevel(Entity target, @Nullable Entity killer, @Nullable DamageSource cause) - { + public static int getLootingLevel(Entity target, @Nullable Entity killer, @Nullable DamageSource cause) { int looting = 0; - if (killer instanceof LivingEntity) - looting = EnchantmentHelper.getMobLooting((LivingEntity)killer); - if (target instanceof LivingEntity) - looting = getLootingLevel((LivingEntity)target, cause, looting); + if (killer instanceof LivingEntity living) + looting = EnchantmentHelper.getMobLooting(living); + if (target instanceof LivingEntity living) + looting = getLootingLevel(living, cause, looting); return looting; } - public static int getLootingLevel(LivingEntity target, @Nullable DamageSource cause, int level) - { + public static int getLootingLevel(LivingEntity target, @Nullable DamageSource cause, int level) { LootingLevelEvent event = new LootingLevelEvent(target, cause, level); MinecraftForge.EVENT_BUS.post(event); return event.getLootingLevel(); @@ -336,32 +296,23 @@ public class ForgeHooks return Math.max(0,event.getVisibilityModifier()); } - public static Optional isLivingOnLadder(@NotNull BlockState state, @NotNull Level level, @NotNull BlockPos pos, @NotNull LivingEntity entity) - { + public static Optional isLivingOnLadder(@NotNull BlockState state, @NotNull Level level, @NotNull BlockPos pos, @NotNull LivingEntity entity) { boolean isSpectator = (entity instanceof Player && entity.isSpectator()); if (isSpectator) return Optional.empty(); if (!ForgeConfig.SERVER.fullBoundingBoxLadders.get()) - { return state.isLadder(level, pos, entity) ? Optional.of(pos) : Optional.empty(); - } - else - { + else { AABB bb = entity.getBoundingBox(); int mX = Mth.floor(bb.minX); int mY = Mth.floor(bb.minY); int mZ = Mth.floor(bb.minZ); - for (int y2 = mY; y2 < bb.maxY; y2++) - { - for (int x2 = mX; x2 < bb.maxX; x2++) - { - for (int z2 = mZ; z2 < bb.maxZ; z2++) - { + for (int y2 = mY; y2 < bb.maxY; y2++) { + for (int x2 = mX; x2 < bb.maxX; x2++) { + for (int z2 = mZ; z2 < bb.maxZ; z2++) { BlockPos tmp = new BlockPos(x2, y2, z2); state = level.getBlockState(tmp); if (state.isLadder(level, tmp, entity)) - { return Optional.of(tmp); - } } } } @@ -369,14 +320,13 @@ public class ForgeHooks } } - public static void onLivingJump(LivingEntity entity) - { + public static void onLivingJump(LivingEntity entity) { MinecraftForge.EVENT_BUS.post(new LivingJumpEvent(entity)); } + @SuppressWarnings("resource") @Nullable - public static ItemEntity onPlayerTossEvent(@NotNull Player player, @NotNull ItemStack item, boolean includeName) - { + public static ItemEntity onPlayerTossEvent(@NotNull Player player, @NotNull ItemStack item, boolean includeName) { player.captureDrops(Lists.newArrayList()); ItemEntity ret = player.drop(item, false, includeName); player.captureDrops(null); @@ -393,8 +343,7 @@ public class ForgeHooks return event.getEntity(); } - public static boolean onVanillaGameEvent(Level level, GameEvent vanillaEvent, Vec3 pos, GameEvent.Context context) - { + public static boolean onVanillaGameEvent(Level level, GameEvent vanillaEvent, Vec3 pos, GameEvent.Context context) { return !MinecraftForge.EVENT_BUS.post(new VanillaGameEvent(level, vanillaEvent, pos, context)); } @@ -412,8 +361,7 @@ public class ForgeHooks Pattern.CASE_INSENSITIVE); public static Component newChatWithLinks(String string){ return newChatWithLinks(string, true); } - public static Component newChatWithLinks(String string, boolean allowMissingHeader) - { + public static Component newChatWithLinks(String string, boolean allowMissingHeader) { // Includes ipv4 and domain pattern // Matches an ip (xx.xxx.xx.xxx) or a domain (something.com) with or // without a protocol or path. @@ -422,15 +370,13 @@ public class ForgeHooks int lastEnd = 0; // Find all urls - while (matcher.find()) - { + while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); // Append the previous left overs. String part = string.substring(lastEnd, start); - if (part.length() > 0) - { + if (part.length() > 0) { if (ichat == null) ichat = Component.literal(part); else @@ -440,13 +386,10 @@ public class ForgeHooks String url = string.substring(start, end); MutableComponent link = Component.literal(url); - try - { + try { // Add schema so client doesn't crash. - if ((new URI(url)).getScheme() == null) - { - if (!allowMissingHeader) - { + if ((new URI(url)).getScheme() == null) { + if (!allowMissingHeader) { if (ichat == null) ichat = Component.literal(url); else @@ -455,9 +398,7 @@ public class ForgeHooks } url = "http://" + url; } - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { // Bad syntax bail out! if (ichat == null) ichat = Component.literal(url); else ichat.append(url); @@ -481,8 +422,7 @@ public class ForgeHooks return ichat; } - public static void dropXpForBlock(BlockState state, ServerLevel level, BlockPos pos, ItemStack stack) - { + public static void dropXpForBlock(BlockState state, ServerLevel level, BlockPos pos, ItemStack stack) { int fortuneLevel = stack.getEnchantmentLevel(Enchantments.BLOCK_FORTUNE); int silkTouchLevel = stack.getEnchantmentLevel(Enchantments.SILK_TOUCH); int exp = state.getExpDrop(level, level.random, pos, fortuneLevel, silkTouchLevel); @@ -490,23 +430,18 @@ public class ForgeHooks state.getBlock().popExperience(level, pos, exp); } - public static int onBlockBreakEvent(Level level, GameType gameType, ServerPlayer entityPlayer, BlockPos pos) - { + public static int onBlockBreakEvent(Level level, GameType gameType, ServerPlayer entityPlayer, BlockPos pos) { // Logic from tryHarvestBlock for pre-canceling the event boolean preCancelEvent = false; ItemStack itemstack = entityPlayer.getMainHandItem(); if (!itemstack.isEmpty() && !itemstack.getItem().canAttackBlock(level.getBlockState(pos), level, pos, entityPlayer)) - { preCancelEvent = true; - } - if (gameType.isBlockPlacingRestricted()) - { + if (gameType.isBlockPlacingRestricted()) { if (gameType == GameType.SPECTATOR) preCancelEvent = true; - if (!entityPlayer.mayBuild()) - { + if (!entityPlayer.mayBuild()) { if (itemstack.isEmpty() || !itemstack.hasAdventureModeBreakTagForBlock(level.registryAccess().registryOrThrow(Registries.BLOCK), new BlockInWorld(level, pos, false))) preCancelEvent = true; } @@ -514,9 +449,7 @@ public class ForgeHooks // Tell client the block is gone immediately then process events if (level.getBlockEntity(pos) == null) - { entityPlayer.connection.send(new ClientboundBlockUpdatePacket(pos, level.getFluidState(pos).createLegacyBlock())); - } // Post the block break event BlockState state = level.getBlockState(pos); @@ -525,27 +458,22 @@ public class ForgeHooks MinecraftForge.EVENT_BUS.post(event); // Handle if the event is canceled - if (event.isCanceled()) - { + if (event.isCanceled()) { // Let the client know the block still exists entityPlayer.connection.send(new ClientboundBlockUpdatePacket(level, pos)); // Update any tile entity data for this block BlockEntity blockEntity = level.getBlockEntity(pos); - if (blockEntity != null) - { + if (blockEntity != null) { Packet pkt = blockEntity.getUpdatePacket(); if (pkt != null) - { entityPlayer.connection.send(pkt); - } } } return event.isCanceled() ? -1 : event.getExpToDrop(); } - public static InteractionResult onPlaceItemIntoWorld(@NotNull UseOnContext context) - { + public static InteractionResult onPlaceItemIntoWorld(@NotNull UseOnContext context) { ItemStack itemstack = context.getItemInHand(); Level level = context.getLevel(); @@ -570,15 +498,12 @@ public class ForgeHooks level.captureBlockSnapshots = false; - if (ret.consumesAction()) - { + if (ret.consumesAction()) { // save new item data int newSize = itemstack.getCount(); CompoundTag newNBT = null; if (itemstack.getTag() != null) - { newNBT = itemstack.getTag().copy(); - } @SuppressWarnings("unchecked") List blockSnapshots = (List)level.capturedBlockSnapshots.clone(); level.capturedBlockSnapshots.clear(); @@ -591,33 +516,24 @@ public class ForgeHooks boolean eventResult = false; if (blockSnapshots.size() > 1) - { eventResult = ForgeEventFactory.onMultiBlockPlace(player, blockSnapshots, side); - } else if (blockSnapshots.size() == 1) - { eventResult = ForgeEventFactory.onBlockPlace(player, blockSnapshots.get(0), side); - } - if (eventResult) - { + if (eventResult) { ret = InteractionResult.FAIL; // cancel placement // revert back all captured blocks - for (BlockSnapshot blocksnapshot : Lists.reverse(blockSnapshots)) - { + for (BlockSnapshot blocksnapshot : Lists.reverse(blockSnapshots)) { level.restoringBlockSnapshots = true; blocksnapshot.restore(true, false); level.restoringBlockSnapshots = false; } - } - else - { + } else { // Change the stack to its new content itemstack.setCount(newSize); itemstack.setTag(newNBT); - for (BlockSnapshot snap : blockSnapshots) - { + for (BlockSnapshot snap : blockSnapshots) { int updateFlag = snap.getFlag(); BlockState oldBlock = snap.getReplacedBlock(); BlockState newBlock = level.getBlockState(snap.getPos()); @@ -634,8 +550,7 @@ public class ForgeHooks return ret; } - public static boolean onAnvilChange(AnvilMenu container, @NotNull ItemStack left, @NotNull ItemStack right, Container outputSlot, String name, int baseCost, Player player) - { + public static boolean onAnvilChange(AnvilMenu container, @NotNull ItemStack left, @NotNull ItemStack right, Container outputSlot, String name, int baseCost, Player player) { AnvilUpdateEvent e = new AnvilUpdateEvent(left, right, name, baseCost, player); if (MinecraftForge.EVENT_BUS.post(e)) return false; if (e.getOutput().isEmpty()) return true; @@ -646,18 +561,15 @@ public class ForgeHooks return false; } - public static float onAnvilRepair(Player player, @NotNull ItemStack output, @NotNull ItemStack left, @NotNull ItemStack right) - { + public static float onAnvilRepair(Player player, @NotNull ItemStack output, @NotNull ItemStack left, @NotNull ItemStack right) { AnvilRepairEvent e = new AnvilRepairEvent(player, left, right, output); MinecraftForge.EVENT_BUS.post(e); return e.getBreakChance(); } - public static int onGrindstoneChange(@NotNull ItemStack top, @NotNull ItemStack bottom, Container outputSlot, int xp) - { + public static int onGrindstoneChange(@NotNull ItemStack top, @NotNull ItemStack bottom, Container outputSlot, int xp) { GrindstoneEvent.OnPlaceItem e = new GrindstoneEvent.OnPlaceItem(top, bottom, xp); - if (MinecraftForge.EVENT_BUS.post(e)) - { + if (MinecraftForge.EVENT_BUS.post(e)) { outputSlot.setItem(0, ItemStack.EMPTY); return -1; } @@ -667,19 +579,16 @@ public class ForgeHooks return e.getXp(); } - public static boolean onGrindstoneTake(Container inputSlots, ContainerLevelAccess access, Function xpFunction) - { + public static boolean onGrindstoneTake(Container inputSlots, ContainerLevelAccess access, Function xpFunction) { access.execute((l,p) -> { int xp = xpFunction.apply(l); GrindstoneEvent.OnTakeItem e = new GrindstoneEvent.OnTakeItem(inputSlots.getItem(0), inputSlots.getItem(1), xp); if (MinecraftForge.EVENT_BUS.post(e)) - { return; - } - if (l instanceof ServerLevel) - { - ExperienceOrb.award((ServerLevel)l, Vec3.atCenterOf(p), e.getXp()); - } + + if (l instanceof ServerLevel server) + ExperienceOrb.award(server, Vec3.atCenterOf(p), e.getXp()); + l.levelEvent(1042, p, 0); inputSlots.setItem(0, e.getNewTopItem()); inputSlots.setItem(1, e.getNewBottomItem()); @@ -689,22 +598,19 @@ public class ForgeHooks } private static ThreadLocal craftingPlayer = new ThreadLocal(); - public static void setCraftingPlayer(Player player) - { + public static void setCraftingPlayer(Player player) { craftingPlayer.set(player); } - public static Player getCraftingPlayer() - { + + public static Player getCraftingPlayer() { return craftingPlayer.get(); } + @NotNull - public static ItemStack getCraftingRemainingItem(@NotNull ItemStack stack) - { - if (stack.getItem().hasCraftingRemainingItem(stack)) - { + public static ItemStack getCraftingRemainingItem(@NotNull ItemStack stack) { + if (stack.getItem().hasCraftingRemainingItem(stack)) { stack = stack.getItem().getCraftingRemainingItem(stack); - if (!stack.isEmpty() && stack.isDamageableItem() && stack.getDamageValue() > stack.getMaxDamage()) - { + if (!stack.isEmpty() && stack.isDamageableItem() && stack.getDamageValue() > stack.getMaxDamage()) { ForgeEventFactory.onPlayerDestroyItem(craftingPlayer.get(), stack, null); return ItemStack.EMPTY; } @@ -713,35 +619,30 @@ public class ForgeHooks return ItemStack.EMPTY; } - public static boolean onPlayerAttackTarget(Player player, Entity target) - { + public static boolean onPlayerAttackTarget(Player player, Entity target) { if (MinecraftForge.EVENT_BUS.post(new AttackEntityEvent(player, target))) return false; ItemStack stack = player.getMainHandItem(); return stack.isEmpty() || !stack.getItem().onLeftClickEntity(stack, player, target); } - public static InteractionResult onInteractEntityAt(Player player, Entity entity, HitResult ray, InteractionHand hand) - { + public static InteractionResult onInteractEntityAt(Player player, Entity entity, HitResult ray, InteractionHand hand) { Vec3 vec3d = ray.getLocation().subtract(entity.position()); return onInteractEntityAt(player, entity, vec3d, hand); } - public static InteractionResult onInteractEntityAt(Player player, Entity entity, Vec3 vec3d, InteractionHand hand) - { + public static InteractionResult onInteractEntityAt(Player player, Entity entity, Vec3 vec3d, InteractionHand hand) { PlayerInteractEvent.EntityInteractSpecific evt = new PlayerInteractEvent.EntityInteractSpecific(player, hand, entity, vec3d); MinecraftForge.EVENT_BUS.post(evt); return evt.isCanceled() ? evt.getCancellationResult() : null; } - public static InteractionResult onInteractEntity(Player player, Entity entity, InteractionHand hand) - { + public static InteractionResult onInteractEntity(Player player, Entity entity, InteractionHand hand) { PlayerInteractEvent.EntityInteract evt = new PlayerInteractEvent.EntityInteract(player, hand, entity); MinecraftForge.EVENT_BUS.post(evt); return evt.isCanceled() ? evt.getCancellationResult() : null; } - public static InteractionResult onItemRightClick(Player player, InteractionHand hand) - { + public static InteractionResult onItemRightClick(Player player, InteractionHand hand) { PlayerInteractEvent.RightClickItem evt = new PlayerInteractEvent.RightClickItem(player, hand); MinecraftForge.EVENT_BUS.post(evt); return evt.isCanceled() ? evt.getCancellationResult() : null; @@ -751,39 +652,33 @@ public class ForgeHooks * @deprecated Use {@link #onLeftClickBlock(Player, BlockPos, Direction, ServerboundPlayerActionPacket.Action)} instead */ @Deprecated(since = "1.20.1", forRemoval = true) - public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face) - { + public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face) { return onLeftClickBlock(player, pos, face, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK); } - public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face, ServerboundPlayerActionPacket.Action action) - { + public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face, ServerboundPlayerActionPacket.Action action) { PlayerInteractEvent.LeftClickBlock evt = new PlayerInteractEvent.LeftClickBlock(player, pos, face, PlayerInteractEvent.LeftClickBlock.Action.convert(action)); MinecraftForge.EVENT_BUS.post(evt); return evt; } - public static PlayerInteractEvent.LeftClickBlock onClientMineHold(Player player, BlockPos pos, Direction face) - { + public static PlayerInteractEvent.LeftClickBlock onClientMineHold(Player player, BlockPos pos, Direction face) { PlayerInteractEvent.LeftClickBlock evt = new PlayerInteractEvent.LeftClickBlock(player, pos, face, PlayerInteractEvent.LeftClickBlock.Action.CLIENT_HOLD); MinecraftForge.EVENT_BUS.post(evt); return evt; } - public static PlayerInteractEvent.RightClickBlock onRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult hitVec) - { + public static PlayerInteractEvent.RightClickBlock onRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult hitVec) { PlayerInteractEvent.RightClickBlock evt = new PlayerInteractEvent.RightClickBlock(player, hand, pos, hitVec); MinecraftForge.EVENT_BUS.post(evt); return evt; } - public static void onEmptyClick(Player player, InteractionHand hand) - { + public static void onEmptyClick(Player player, InteractionHand hand) { MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.RightClickEmpty(player, hand)); } - public static void onEmptyLeftClick(Player player) - { + public static void onEmptyLeftClick(Player player) { MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.LeftClickEmpty(player)); } @@ -800,8 +695,7 @@ public class ForgeHooks /* TODO: GLM private static final ThreadLocal> lootContext = new ThreadLocal<>(); - private static LootTableContext getLootTableContext() - { + private static LootTableContext getLootTableContext() { LootTableContext ctx = lootContext.get().peek(); if (ctx == null) @@ -810,45 +704,34 @@ public class ForgeHooks return ctx; } - public static TriFunction> getLootTableDeserializer(Gson gson, String directory) - { + public static TriFunction> getLootTableDeserializer(Gson gson, String directory) { return (location, data, resourceManager) -> { - try - { + try { Resource resource = resourceManager.getResource(location.withPath(directory + "/" + location.getPath() + ".json")).orElse(null); boolean custom = resource == null || !resource.isBuiltin(); return Optional.ofNullable(loadLootTable(gson, location, data, custom)); - } - catch (Exception exception) - { + } catch (Exception exception) { LOGGER.error("Couldn't parse element {}:{}", directory, location, exception); return Optional.empty(); } }; } - public static LootTable loadLootTable(Gson gson, ResourceLocation name, JsonElement data, boolean custom) - { + public static LootTable loadLootTable(Gson gson, ResourceLocation name, JsonElement data, boolean custom) { Deque que = lootContext.get(); - if (que == null) - { + if (que == null) { que = Queues.newArrayDeque(); lootContext.set(que); } LootTable ret; - try - { + try { que.push(new LootTableContext(name, custom)); ret = gson.fromJson(data, LootTable.class); ret.setLootTableId(name); - } - catch (JsonParseException e) - { + } catch (JsonParseException e) { throw e; - } - finally - { + } finally { que.pop(); } @@ -861,23 +744,20 @@ public class ForgeHooks return ret; } - private static class LootTableContext - { + private static class LootTableContext { public final ResourceLocation name; public final boolean vanilla; public final boolean custom; public int poolCount = 0; - private LootTableContext(ResourceLocation name, boolean custom) - { + private LootTableContext(ResourceLocation name, boolean custom) { this.name = name; this.custom = custom; this.vanilla = "minecraft".equals(this.name.getNamespace()); } } - public static String readPoolName(JsonObject json) - { + public static String readPoolName(JsonObject json) { LootTableContext ctx = getLootTableContext(); if (json.has("name")) @@ -899,8 +779,7 @@ public class ForgeHooks * @return the type of the fluid if vanilla * @throws RuntimeException if the fluid is not a vanilla one */ - public static FluidType getVanillaFluidType(Fluid fluid) - { + public static FluidType getVanillaFluidType(Fluid fluid) { if (fluid == Fluids.EMPTY) return ForgeMod.EMPTY_TYPE.get(); if (fluid == Fluids.WATER || fluid == Fluids.FLOWING_WATER) @@ -912,59 +791,45 @@ public class ForgeHooks throw new RuntimeException("Mod fluids must override getFluidType."); } - public static TagKey getTagFromVanillaTier(Tiers tier) - { - return switch(tier) - { - case WOOD -> Tags.Blocks.NEEDS_WOOD_TOOL; - case GOLD -> Tags.Blocks.NEEDS_GOLD_TOOL; - case STONE -> BlockTags.NEEDS_STONE_TOOL; - case IRON -> BlockTags.NEEDS_IRON_TOOL; - case DIAMOND -> BlockTags.NEEDS_DIAMOND_TOOL; - case NETHERITE -> Tags.Blocks.NEEDS_NETHERITE_TOOL; - }; - } - - public static Collection onCheckCreativeTabs(CreativeModeTab... vanillaTabs) { - final List tabs = new ArrayList<>(Arrays.asList(vanillaTabs)); - return tabs; + public static TagKey getTagFromVanillaTier(Tiers tier) { + return switch(tier) { + case WOOD -> Tags.Blocks.NEEDS_WOOD_TOOL; + case GOLD -> Tags.Blocks.NEEDS_GOLD_TOOL; + case STONE -> BlockTags.NEEDS_STONE_TOOL; + case IRON -> BlockTags.NEEDS_IRON_TOOL; + case DIAMOND -> BlockTags.NEEDS_DIAMOND_TOOL; + case NETHERITE -> Tags.Blocks.NEEDS_NETHERITE_TOOL; + }; } @FunctionalInterface - public interface BiomeCallbackFunction - { + public interface BiomeCallbackFunction { Biome apply(final Biome.ClimateSettings climate, final BiomeSpecialEffects effects, final BiomeGenerationSettings gen, final MobSpawnSettings spawns); } - public static boolean onCropsGrowPre(Level level, BlockPos pos, BlockState state, boolean def) - { + public static boolean onCropsGrowPre(Level level, BlockPos pos, BlockState state, boolean def) { BlockEvent ev = new BlockEvent.CropGrowEvent.Pre(level,pos,state); MinecraftForge.EVENT_BUS.post(ev); - return (ev.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || (ev.getResult() == net.minecraftforge.eventbus.api.Event.Result.DEFAULT && def)); + return (ev.getResult() == Event.Result.ALLOW || (ev.getResult() == Event.Result.DEFAULT && def)); } - public static void onCropsGrowPost(Level level, BlockPos pos, BlockState state) - { + public static void onCropsGrowPost(Level level, BlockPos pos, BlockState state) { MinecraftForge.EVENT_BUS.post(new BlockEvent.CropGrowEvent.Post(level, pos, state, level.getBlockState(pos))); } @Nullable - public static CriticalHitEvent getCriticalHit(Player player, Entity target, boolean vanillaCritical, float damageModifier) - { + public static CriticalHitEvent getCriticalHit(Player player, Entity target, boolean vanillaCritical, float damageModifier) { CriticalHitEvent hitResult = new CriticalHitEvent(player, target, damageModifier, vanillaCritical); MinecraftForge.EVENT_BUS.post(hitResult); - if (hitResult.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || (vanillaCritical && hitResult.getResult() == net.minecraftforge.eventbus.api.Event.Result.DEFAULT)) - { + if (hitResult.getResult() == Event.Result.ALLOW || (vanillaCritical && hitResult.getResult() == Event.Result.DEFAULT)) return hitResult; - } return null; } /** * Hook to fire {@link ItemAttributeModifierEvent}. Modders should use {@link ItemStack#getAttributeModifiers(EquipmentSlot)} instead. */ - public static Multimap getAttributeModifiers(ItemStack stack, EquipmentSlot equipmentSlot, Multimap attributes) - { + public static Multimap getAttributeModifiers(ItemStack stack, EquipmentSlot equipmentSlot, Multimap attributes) { ItemAttributeModifierEvent event = new ItemAttributeModifierEvent(stack, equipmentSlot, attributes); MinecraftForge.EVENT_BUS.post(event); return event.getModifiers(); @@ -973,8 +838,7 @@ public class ForgeHooks /** * Hook to fire {@link LivingGetProjectileEvent}. Returns the ammo to be used. */ - public static ItemStack getProjectile(LivingEntity entity, ItemStack projectileWeaponItem, ItemStack projectile) - { + public static ItemStack getProjectile(LivingEntity entity, ItemStack projectileWeaponItem, ItemStack projectile) { LivingGetProjectileEvent event = new LivingGetProjectileEvent(entity, projectileWeaponItem, projectile); MinecraftForge.EVENT_BUS.post(event); return event.getProjectileItemStack(); @@ -984,51 +848,35 @@ public class ForgeHooks * Used as the default implementation of {@link Item#getCreatorModId}. Call that method instead. */ @Nullable - public static String getDefaultCreatorModId(@NotNull ItemStack itemStack) - { + public static String getDefaultCreatorModId(@NotNull ItemStack itemStack) { Item item = itemStack.getItem(); ResourceLocation registryName = ForgeRegistries.ITEMS.getKey(item); String modId = registryName == null ? null : registryName.getNamespace(); - if ("minecraft".equals(modId)) - { - if (item instanceof EnchantedBookItem) - { + if ("minecraft".equals(modId)) { + if (item instanceof EnchantedBookItem) { ListTag enchantmentsNbt = EnchantedBookItem.getEnchantments(itemStack); - if (enchantmentsNbt.size() == 1) - { + if (enchantmentsNbt.size() == 1) { CompoundTag nbttagcompound = enchantmentsNbt.getCompound(0); ResourceLocation resourceLocation = ResourceLocation.tryParse(nbttagcompound.getString("id")); if (resourceLocation != null && ForgeRegistries.ENCHANTMENTS.containsKey(resourceLocation)) - { return resourceLocation.getNamespace(); - } } - } - else if (item instanceof PotionItem || item instanceof TippedArrowItem) - { + } else if (item instanceof PotionItem || item instanceof TippedArrowItem) { Potion potionType = PotionUtils.getPotion(itemStack); ResourceLocation resourceLocation = ForgeRegistries.POTIONS.getKey(potionType); if (resourceLocation != null) - { return resourceLocation.getNamespace(); - } - } - else if (item instanceof SpawnEggItem) - { - ResourceLocation resourceLocation = ForgeRegistries.ENTITY_TYPES.getKey(((SpawnEggItem) item).getType(null)); + } else if (item instanceof SpawnEggItem egg) { + ResourceLocation resourceLocation = ForgeRegistries.ENTITY_TYPES.getKey(egg.getType(null)); if (resourceLocation != null) - { return resourceLocation.getNamespace(); - } } } return modId; } - public static boolean onFarmlandTrample(Level level, BlockPos pos, BlockState state, float fallDistance, Entity entity) - { - if (entity.canTrample(state, pos, fallDistance)) - { + public static boolean onFarmlandTrample(Level level, BlockPos pos, BlockState state, float fallDistance, Entity entity) { + if (entity.canTrample(state, pos, fallDistance)) { BlockEvent.FarmlandTrampleEvent event = new BlockEvent.FarmlandTrampleEvent(level, pos, state, fallDistance, entity); MinecraftForge.EVENT_BUS.post(event); return !event.isCanceled(); @@ -1043,12 +891,10 @@ public class ForgeHooks return event.getVanillaNoteId(); } - public static boolean hasNoElements(Ingredient ingredient) - { + public static boolean hasNoElements(Ingredient ingredient) { ItemStack[] items = ingredient.getItems(); if (items.length == 0) return true; - if (items.length == 1) - { + if (items.length == 1) { //If we potentially added a barrier due to the ingredient being an empty tag, try and check if it is the stack we added ItemStack item = items[0]; return item.getItem() == Items.BARRIER && item.getHoverName() instanceof MutableComponent hoverName && hoverName.getString().startsWith("Empty Tag: "); @@ -1056,15 +902,10 @@ public class ForgeHooks return false; } - @Deprecated(forRemoval = true, since = "1.20.1") // Tags use a codec now This was never used in 1.20 - public static void deserializeTagAdditions(List list, JsonObject json, List allList) {} - @Nullable - public static EntityDataSerializer getSerializer(int id, CrudeIncrementalIntIdentityHashBiMap> vanilla) - { + public static EntityDataSerializer getSerializer(int id, CrudeIncrementalIntIdentityHashBiMap> vanilla) { EntityDataSerializer serializer = vanilla.byId(id); - if (serializer == null) - { + if (serializer == null) { // ForgeRegistries.DATA_SERIALIZERS is a deferred register now, so if this method is called too early, the registry will be null ForgeRegistry> registry = (ForgeRegistry>) ForgeRegistries.ENTITY_DATA_SERIALIZERS.get(); if (registry != null) @@ -1073,11 +914,9 @@ public class ForgeHooks return serializer; } - public static int getSerializerId(EntityDataSerializer serializer, CrudeIncrementalIntIdentityHashBiMap> vanilla) - { + public static int getSerializerId(EntityDataSerializer serializer, CrudeIncrementalIntIdentityHashBiMap> vanilla) { int id = vanilla.getId(serializer); - if (id < 0) - { + if (id < 0) { // ForgeRegistries.DATA_SERIALIZERS is a deferred register now, so if this method is called too early, the registry will be null ForgeRegistry> registry = (ForgeRegistry>) ForgeRegistries.ENTITY_DATA_SERIALIZERS.get(); if (registry != null) @@ -1086,8 +925,7 @@ public class ForgeHooks return id; } - public static boolean canEntityDestroy(Level level, BlockPos pos, LivingEntity entity) - { + public static boolean canEntityDestroy(Level level, BlockPos pos, LivingEntity entity) { if (!level.isLoaded(pos)) return false; BlockState state = level.getBlockState(pos); @@ -1099,14 +937,10 @@ public class ForgeHooks /** * Gets the burn time of this itemstack. */ - public static int getBurnTime(ItemStack stack, @Nullable RecipeType recipeType) - { + public static int getBurnTime(ItemStack stack, @Nullable RecipeType recipeType) { if (stack.isEmpty()) - { return 0; - } - else - { + else { Item item = stack.getItem(); int ret = stack.getBurnTime(recipeType); return ForgeEventFactory.getItemBurnTime(stack, ret == -1 ? VANILLA_BURNS.getOrDefault(ForgeRegistries.ITEMS.getDelegateOrThrow(item), 0) : ret, recipeType); @@ -1114,31 +948,12 @@ public class ForgeHooks } @SuppressWarnings("deprecation") - public static synchronized void updateBurns() - { + public static synchronized void updateBurns() { VANILLA_BURNS.clear(); FurnaceBlockEntity.getFuel().entrySet().forEach(e -> VANILLA_BURNS.put(ForgeRegistries.ITEMS.getDelegateOrThrow(e.getKey()), e.getValue())); } // TODO: GLM - /** - * All loot table drops should be passed to this function so that mod added effects - * (e.g. smelting enchantments) can be processed. - * - * @param list The loot generated - * @param context The loot context that generated that loot - * @return The modified list - * - * @deprecated Use {@link #modifyLoot(ResourceLocation, ObjectArrayList, LootContext)} instead. - * - * @implNote This method will use the {@linkplain LootTableIdCondition#UNKNOWN_LOOT_TABLE - * unknown loot table marker} when redirecting. - * / - @Deprecated - public static List modifyLoot(List list, LootContext context) { - return modifyLoot(LootTableIdCondition.UNKNOWN_LOOT_TABLE, ObjectArrayList.wrap((ItemStack[]) list.toArray()), context); - } - /** * Handles the modification of loot table drops via the registered Global Loot Modifiers, * so that custom effects can be processed. @@ -1163,43 +978,34 @@ public class ForgeHooks } */ - public static List getModPacks() - { + public static List getModPacks() { List modpacks = ResourcePackLoader.getPackNames(); if(modpacks.isEmpty()) throw new IllegalStateException("Attempted to retrieve mod packs before they were loaded in!"); return modpacks; } - public static List getModPacksWithVanilla() - { + public static List getModPacksWithVanilla() { List modpacks = getModPacks(); modpacks.add("vanilla"); return modpacks; } - private static final Set VANILLA_DIMS = Sets.newHashSet("minecraft:overworld", "minecraft:the_nether", "minecraft:the_end"); - private static final String DIMENSIONS_KEY = "dimensions"; - private static final String SEED_KEY = "seed"; - private static final Map, AttributeSupplier> FORGE_ATTRIBUTES = new HashMap<>(); /** FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY */ @Deprecated - public static Map, AttributeSupplier> getAttributesView() - { + public static Map, AttributeSupplier> getAttributesView() { return Collections.unmodifiableMap(FORGE_ATTRIBUTES); } /** FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY */ @Deprecated - public static void modifyAttributes() - { + public static void modifyAttributes() { ModLoader.get().postEvent(new EntityAttributeCreationEvent(FORGE_ATTRIBUTES)); Map, AttributeSupplier.Builder> finalMap = new HashMap<>(); ModLoader.get().postEvent(new EntityAttributeModificationEvent(finalMap)); - finalMap.forEach((k, v) -> - { + finalMap.forEach((k, v) -> { AttributeSupplier supplier = DefaultAttributes.getSupplier(k); AttributeSupplier.Builder newBuilder = supplier != null ? new AttributeSupplier.Builder(supplier) : new AttributeSupplier.Builder(); newBuilder.combine(v); @@ -1207,31 +1013,26 @@ public class ForgeHooks }); } - public static void onEntityEnterSection(Entity entity, long packedOldPos, long packedNewPos) - { + public static void onEntityEnterSection(Entity entity, long packedOldPos, long packedNewPos) { MinecraftForge.EVENT_BUS.post(new EntityEvent.EnteringSection(entity, packedOldPos, packedNewPos)); } - public static ShieldBlockEvent onShieldBlock(LivingEntity blocker, DamageSource source, float blocked) - { + public static ShieldBlockEvent onShieldBlock(LivingEntity blocker, DamageSource source, float blocked) { ShieldBlockEvent e = new ShieldBlockEvent(blocker, source, blocked); MinecraftForge.EVENT_BUS.post(e); return e; } - public static LivingSwapItemsEvent.Hands onLivingSwapHandItems(LivingEntity livingEntity) - { + public static LivingSwapItemsEvent.Hands onLivingSwapHandItems(LivingEntity livingEntity) { LivingSwapItemsEvent.Hands event = new LivingSwapItemsEvent.Hands(livingEntity); MinecraftForge.EVENT_BUS.post(event); return event; } - public static void writeAdditionalLevelSaveData(WorldData worldData, CompoundTag levelTag) - { + public static void writeAdditionalLevelSaveData(WorldData worldData, CompoundTag levelTag) { CompoundTag fmlData = new CompoundTag(); ListTag modList = new ListTag(); - ModList.get().getMods().forEach(mi -> - { + ModList.get().getMods().forEach(mi -> { final CompoundTag mod = new CompoundTag(); mod.putString("ModId", mi.getModId()); mod.putString("ModVersion", MavenVersionStringHelper.artifactVersionToString(mi.getVersion())); @@ -1244,42 +1045,29 @@ public class ForgeHooks LOGGER.debug(WORLDPERSISTENCE, "Gathering id map for writing to world save {}", worldData.getLevelName()); for (Map.Entry e : RegistryManager.ACTIVE.takeSnapshot(true).entrySet()) - { registries.put(e.getKey().toString(), e.getValue().write()); - } LOGGER.debug(WORLDPERSISTENCE, "ID Map collection complete {}", worldData.getLevelName()); levelTag.put("fml", fmlData); } - /** - * @param rootTag Level data file contents. - * @param levelDirectory Level currently being loaded. - */ @ApiStatus.Internal - public static void readAdditionalLevelSaveData(CompoundTag rootTag, LevelStorageSource.LevelDirectory levelDirectory) - { + public static void readAdditionalLevelSaveData(CompoundTag rootTag, LevelStorageSource.LevelDirectory levelDirectory) { CompoundTag tag = rootTag.getCompound("fml"); - if (tag.contains("LoadingModList")) - { + if (tag.contains("LoadingModList")) { ListTag modList = tag.getList("LoadingModList", net.minecraft.nbt.Tag.TAG_COMPOUND); Map mismatchedVersions = new HashMap<>(modList.size()); Map missingVersions = new HashMap<>(modList.size()); - for (int i = 0; i < modList.size(); i++) - { + for (int i = 0; i < modList.size(); i++) { CompoundTag mod = modList.getCompound(i); String modId = mod.getString("ModId"); if (Objects.equals("minecraft", modId)) - { continue; - } String modVersion = mod.getString("ModVersion"); final var previousVersion = new DefaultArtifactVersion(modVersion); - ModList.get().getModContainerById(modId).ifPresentOrElse(container -> - { + ModList.get().getModContainerById(modId).ifPresentOrElse(container -> { final var loadingVersion = container.getModInfo().getVersion(); - if (!loadingVersion.equals(previousVersion)) - { + if (!loadingVersion.equals(previousVersion)) { // Enqueue mismatched versions for bulk event mismatchedVersions.put(modId, previousVersion); } @@ -1293,49 +1081,42 @@ public class ForgeHooks StringBuilder unresolved = new StringBuilder("The following mods have version differences that were not resolved:"); // For mods that were marked resolved, log the version resolution and the mod that resolved the mismatch - mismatchEvent.getResolved().forEachOrdered((res) -> - { + mismatchEvent.getResolved().forEachOrdered((res) -> { final var modid = res.modid(); final var diff = res.versionDifference(); - if (res.wasSelfResolved()) - { + if (res.wasSelfResolved()) { resolved.append(System.lineSeparator()) - .append(diff.isMissing() - ? "%s (version %s -> MISSING, self-resolved)".formatted(modid, diff.oldVersion()) - : "%s (version %s -> %s, self-resolved)".formatted(modid, diff.oldVersion(), diff.newVersion()) - ); - } - else - { + .append(diff.isMissing() + ? "%s (version %s -> MISSING, self-resolved)".formatted(modid, diff.oldVersion()) + : "%s (version %s -> %s, self-resolved)".formatted(modid, diff.oldVersion(), diff.newVersion()) + ); + } else { final var resolver = res.resolver().getModId(); resolved.append(System.lineSeparator()) - .append(diff.isMissing() - ? "%s (version %s -> MISSING, resolved by %s)".formatted(modid, diff.oldVersion(), resolver) - : "%s (version %s -> %s, resolved by %s)".formatted(modid, diff.oldVersion(), diff.newVersion(), resolver) - ); + .append(diff.isMissing() + ? "%s (version %s -> MISSING, resolved by %s)".formatted(modid, diff.oldVersion(), resolver) + : "%s (version %s -> %s, resolved by %s)".formatted(modid, diff.oldVersion(), diff.newVersion(), resolver) + ); } }); // For mods that did not specify handling, show a warning to users that errors may occur - mismatchEvent.getUnresolved().forEachOrdered((unres) -> - { + mismatchEvent.getUnresolved().forEachOrdered((unres) -> { final var modid = unres.modid(); final var diff = unres.versionDifference(); unresolved.append(System.lineSeparator()) - .append(diff.isMissing() - ? "%s (version %s -> MISSING)".formatted(modid, diff.oldVersion()) - : "%s (version %s -> %s)".formatted(modid, diff.oldVersion(), diff.newVersion()) - ); + .append(diff.isMissing() + ? "%s (version %s -> MISSING)".formatted(modid, diff.oldVersion()) + : "%s (version %s -> %s)".formatted(modid, diff.oldVersion(), diff.newVersion()) + ); }); - if (mismatchEvent.anyResolved()) - { + if (mismatchEvent.anyResolved()) { resolved.append(System.lineSeparator()).append("Things may not work well."); LOGGER.debug(WORLDPERSISTENCE, resolved.toString()); } - if (mismatchEvent.anyUnresolved()) - { + if (mismatchEvent.anyUnresolved()) { unresolved.append(System.lineSeparator()).append("Things may not work well."); LOGGER.warn(WORLDPERSISTENCE, unresolved.toString()); } @@ -1343,26 +1124,21 @@ public class ForgeHooks Multimap failedElements = null; - if (tag.contains("Registries")) - { + if (tag.contains("Registries")) { Map snapshot = new HashMap<>(); CompoundTag regs = tag.getCompound("Registries"); for (String key : regs.getAllKeys()) - { snapshot.put(new ResourceLocation(key), ForgeRegistry.Snapshot.read(regs.getCompound(key))); - } failedElements = GameData.injectSnapshot(snapshot, true, true); } - if (failedElements != null && !failedElements.isEmpty()) - { + if (failedElements != null && !failedElements.isEmpty()) { StringBuilder buf = new StringBuilder(); buf.append("Forge Mod Loader could not load this save.\n\n") .append("There are ").append(failedElements.size()).append(" unassigned registry entries in this save.\n") .append("You will not be able to load until they are present again.\n\n"); - failedElements.asMap().forEach((name, entries) -> - { + failedElements.asMap().forEach((name, entries) -> { buf.append("Missing ").append(name).append(":\n"); entries.forEach(rl -> buf.append(" ").append(rl).append("\n")); }); @@ -1370,8 +1146,7 @@ public class ForgeHooks } } - public static String encodeLifecycle(Lifecycle lifecycle) - { + public static String encodeLifecycle(Lifecycle lifecycle) { if (lifecycle == Lifecycle.stable()) return "stable"; if (lifecycle == Lifecycle.experimental()) @@ -1381,8 +1156,7 @@ public class ForgeHooks throw new IllegalArgumentException("Unknown lifecycle."); } - public static Lifecycle parseLifecycle(String lifecycle) - { + public static Lifecycle parseLifecycle(String lifecycle) { if (lifecycle.equals("stable")) return Lifecycle.stable(); if (lifecycle.equals("experimental")) @@ -1392,8 +1166,7 @@ public class ForgeHooks throw new IllegalArgumentException("Unknown lifecycle."); } - public static boolean shouldSuppressEnderManAnger(EnderMan enderMan, Player player, ItemStack mask) - { + public static boolean shouldSuppressEnderManAnger(EnderMan enderMan, Player player, ItemStack mask) { return mask.isEnderMask(player, enderMan) || MinecraftForge.EVENT_BUS.post(new EnderManAngerEvent(enderMan, player)); } @@ -1408,16 +1181,14 @@ public class ForgeHooks * @hidden For internal use only. */ @Nullable - public static StructuresBecomeConfiguredFix.Conversion getStructureConversion(String originalBiome) - { + public static StructuresBecomeConfiguredFix.Conversion getStructureConversion(String originalBiome) { return FORGE_CONVERSION_MAP.get().get(originalBiome); } /** * @hidden For internal use only. */ - public static boolean checkStructureNamespace(String biome) - { + public static boolean checkStructureNamespace(String biome) { @Nullable ResourceLocation biomeLocation = ResourceLocation.tryParse(biome); return biomeLocation != null && !biomeLocation.getNamespace().equals(ResourceLocation.DEFAULT_NAMESPACE); } @@ -1442,31 +1213,24 @@ public class ForgeHooks * @param registryKey key of the registry * @return path of the registry key. Prefixed with the namespace if it is not "minecraft" */ - public static String prefixNamespace(ResourceLocation registryKey) - { + public static String prefixNamespace(ResourceLocation registryKey) { return registryKey.getNamespace().equals("minecraft") ? registryKey.getPath() : registryKey.getNamespace() + "/" + registryKey.getPath(); } - public static boolean canUseEntitySelectors(SharedSuggestionProvider provider) - { + public static boolean canUseEntitySelectors(SharedSuggestionProvider provider) { if (provider.hasPermission(Commands.LEVEL_GAMEMASTERS)) - { return true; - } else if (provider instanceof CommandSourceStack source && source.source instanceof ServerPlayer player) - { return PermissionAPI.getPermission(player, ForgeMod.USE_SELECTORS_PERMISSION); - } return false; } @ApiStatus.Internal - public static HolderLookup.RegistryLookup wrapRegistryLookup(final HolderLookup.RegistryLookup lookup) - { - return new HolderLookup.RegistryLookup.Delegate<>() - { + public static HolderLookup.RegistryLookup wrapRegistryLookup(final HolderLookup.RegistryLookup lookup) { + return new HolderLookup.RegistryLookup.Delegate<>() { @Override protected RegistryLookup parent() { return lookup; } @Override public Stream> listTags() { return Stream.empty(); } + @SuppressWarnings("deprecation") @Override public Optional> get(TagKey key) { return Optional.of(HolderSet.emptyNamed(lookup, key)); } }; } @@ -1481,36 +1245,26 @@ public class ForgeHooks * @param refillAirAmount The amount of air to refill when the entity is able to breathe * @implNote This method needs to closely replicate the logic found right after the call site in {@link LivingEntity#baseTick()} as it overrides it. */ - public static void onLivingBreathe(LivingEntity entity, int consumeAirAmount, int refillAirAmount) - { + public static void onLivingBreathe(LivingEntity entity, int consumeAirAmount, int refillAirAmount) { // Check things that vanilla considers to be air - these will cause the air supply to be increased. boolean isAir = entity.getEyeInFluidType().isAir() || entity.level().getBlockState(BlockPos.containing(entity.getX(), entity.getEyeY(), entity.getZ())).is(Blocks.BUBBLE_COLUMN); // The following effects cause the entity to not drown, but do not cause the air supply to be increased. boolean canBreathe = !entity.canDrownInFluidType(entity.getEyeInFluidType()) || MobEffectUtil.hasWaterBreathing(entity) || (entity instanceof Player && ((Player) entity).getAbilities().invulnerable); LivingBreatheEvent breatheEvent = new LivingBreatheEvent(entity, isAir || canBreathe, consumeAirAmount, refillAirAmount, isAir); MinecraftForge.EVENT_BUS.post(breatheEvent); - if (breatheEvent.canBreathe()) - { + if (breatheEvent.canBreathe()) { if (breatheEvent.canRefillAir()) - { entity.setAirSupply(Math.min(entity.getAirSupply() + breatheEvent.getRefillAirAmount(), entity.getMaxAirSupply())); - } - } - else - { + } else entity.setAirSupply(entity.getAirSupply() - breatheEvent.getConsumeAirAmount()); - } - if (entity.getAirSupply() <= 0) - { + if (entity.getAirSupply() <= 0) { LivingDrownEvent drownEvent = new LivingDrownEvent(entity, entity.getAirSupply() <= -20, 2.0F, 8); - if (!MinecraftForge.EVENT_BUS.post(drownEvent) && drownEvent.isDrowning()) - { + if (!MinecraftForge.EVENT_BUS.post(drownEvent) && drownEvent.isDrowning()) { entity.setAirSupply(0); Vec3 vec3 = entity.getDeltaMovement(); - for (int i = 0; i < drownEvent.getBubbleCount(); ++i) - { + for (int i = 0; i < drownEvent.getBubbleCount(); ++i) { double d2 = entity.getRandom().nextDouble() - entity.getRandom().nextDouble(); double d3 = entity.getRandom().nextDouble() - entity.getRandom().nextDouble(); double d4 = entity.getRandom().nextDouble() - entity.getRandom().nextDouble(); @@ -1522,20 +1276,17 @@ public class ForgeHooks } if (!isAir && !entity.level().isClientSide && entity.isPassenger() && entity.getVehicle() != null && !entity.getVehicle().canBeRiddenUnderFluidType(entity.getEyeInFluidType(), entity)) - { entity.stopRiding(); - } } - public static void onCreativeModeTabBuildContents(CreativeModeTab tab, ResourceKey tabKey, CreativeModeTab.DisplayItemsGenerator originalGenerator, CreativeModeTab.ItemDisplayParameters params, CreativeModeTab.Output output) - { + public static void onCreativeModeTabBuildContents(CreativeModeTab tab, ResourceKey tabKey, CreativeModeTab.DisplayItemsGenerator originalGenerator, CreativeModeTab.ItemDisplayParameters params, CreativeModeTab.Output output) { final var entries = new MutableHashedLinkedMap(ItemStackLinkedSet.TYPE_AND_TAG, - (key, left, right) -> { - //throw new IllegalStateException("Accidentally adding the same item stack twice " + key.getDisplayName().getString() + " to a Creative Mode Tab: " + tab.getDisplayName().getString()); - // Vanilla adds enchanting books twice in both visibilities. - // This is just code cleanliness for them. For us lets just increase the visibility and merge the entries. - return CreativeModeTab.TabVisibility.PARENT_AND_SEARCH_TABS; - } + (key, left, right) -> { + //throw new IllegalStateException("Accidentally adding the same item stack twice " + key.getDisplayName().getString() + " to a Creative Mode Tab: " + tab.getDisplayName().getString()); + // Vanilla adds enchanting books twice in both visibilities. + // This is just code cleanliness for them. For us lets just increase the visibility and merge the entries. + return CreativeModeTab.TabVisibility.PARENT_AND_SEARCH_TABS; + } ); originalGenerator.accept(params, (stack, vis) -> { @@ -1549,4 +1300,40 @@ public class ForgeHooks for (var entry : entries) output.accept(entry.getKey(), entry.getValue()); } + + @ApiStatus.Internal + public static boolean onCustomPayload(final ICustomPacket packet, final Connection connection) { + if (packet.getDirection().getReceptionSide() != EffectiveSide.get()) { + connection.disconnect(Component.literal("Illegal packet received, terminating connection")); + return false; + } + + var context = new CustomPayloadEvent.Context(connection, packet.getDirection()); + return onCustomPayload(new CustomPayloadEvent(packet, context)); + } + + @ApiStatus.Internal + public static boolean onCustomPayload(CustomPayloadEvent event) { + var channel = NetworkRegistry.findTarget(event.getChannel()); + if (channel != null && channel.dispatch(event)) + return true; + + // Should we always fire this, even if the channel consumed the packet? + if (!event.getSource().getPacketHandled()) { + MinecraftForge.EVENT_BUS.post(event); + return event.getSource().getPacketHandled(); + } + + return false; + } + + @ApiStatus.Internal + public static void handleClientConfigurationComplete(Connection connection) { + if (NetworkContext.get(connection).getType() == ConnectionType.VANILLA) { + LOGGER.info("Connected to a vanilla server. Catching up missing behaviour."); + ConfigTracker.INSTANCE.loadDefaultServerConfigs(); + } else + LOGGER.info("Connected to a modded server."); + } + } \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java b/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java index 1618b4b5c3..ad0e5b5fa5 100644 --- a/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java +++ b/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java @@ -19,6 +19,7 @@ import net.minecraftforge.event.entity.EntityJoinLevelEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.level.ChunkEvent; import net.minecraftforge.event.level.LevelEvent; +import net.minecraftforge.event.network.ConnectionStartEvent; import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.event.TagsUpdatedEvent; @@ -26,27 +27,24 @@ import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.TickEvent.ClientTickEvent; import net.minecraftforge.event.TickEvent.ServerTickEvent; import net.minecraftforge.fml.LogicalSide; +import net.minecraftforge.network.filters.NetworkFilters; import net.minecraftforge.common.util.LogicalSidedProvider; import net.minecraftforge.server.command.ForgeCommand; import net.minecraftforge.server.command.ConfigCommand; -public class ForgeInternalHandler -{ +public class ForgeInternalHandler { @SubscribeEvent(priority = EventPriority.HIGH) - public void onEntityJoinWorld(EntityJoinLevelEvent event) - { + public void onEntityJoinWorld(EntityJoinLevelEvent event) { Entity entity = event.getEntity(); - if (entity.getClass().equals(ItemEntity.class)) - { + if (entity.getClass().equals(ItemEntity.class)) { ItemStack stack = ((ItemEntity)entity).getItem(); Item item = stack.getItem(); - if (item.hasCustomEntity(stack)) - { + if (item.hasCustomEntity(stack)) { Entity newEntity = item.createEntity(event.getLevel(), entity, stack); - if (newEntity != null) - { + if (newEntity != null) { entity.discard(); event.setCanceled(true); + @SuppressWarnings("resource") var executor = LogicalSidedProvider.WORKQUEUE.get(event.getLevel().isClientSide ? LogicalSide.CLIENT : LogicalSide.SERVER); executor.tell(new TickTask(0, () -> event.getLevel().addFreshEntity(newEntity))); } @@ -56,59 +54,49 @@ public class ForgeInternalHandler @SubscribeEvent(priority = EventPriority.HIGHEST) - public void onDimensionUnload(LevelEvent.Unload event) - { + public void onDimensionUnload(LevelEvent.Unload event) { if (event.getLevel() instanceof ServerLevel) FakePlayerFactory.unloadLevel((ServerLevel) event.getLevel()); } @SubscribeEvent - public void onServerTick(ServerTickEvent event) - { + public void onServerTick(ServerTickEvent event) { WorldWorkerManager.tick(event.phase == TickEvent.Phase.START); } @SubscribeEvent - public void checkSettings(ClientTickEvent event) - { + public void checkSettings(ClientTickEvent event) { //if (event.phase == Phase.END) // CloudRenderer.updateCloudSettings(); } @SubscribeEvent - public void onChunkUnload(ChunkEvent.Unload event) - { + public void onChunkUnload(ChunkEvent.Unload event) { if (!event.getLevel().isClientSide()) FarmlandWaterManager.removeTickets(event.getChunk()); } /* @SubscribeEvent - public void playerChangeDimension(PlayerEvent.PlayerChangedDimensionEvent event) - { + public void playerChangeDimension(PlayerEvent.PlayerChangedDimensionEvent event) { if (event.getPlayer() instanceof ServerPlayerEntity) DimensionManager.rebuildPlayerMap(((ServerPlayerEntity)event.getPlayer()).server.getPlayerList(), true); } */ @SubscribeEvent - public void playerLogin(PlayerEvent.PlayerLoggedInEvent event) - { + public void playerLogin(PlayerEvent.PlayerLoggedInEvent event) { UsernameCache.setUsername(event.getEntity().getUUID(), event.getEntity().getGameProfile().getName()); } @SubscribeEvent - public void tagsUpdated(TagsUpdatedEvent event) - { + public void tagsUpdated(TagsUpdatedEvent event) { if (event.shouldUpdateStaticData()) - { ForgeHooks.updateBurns(); - } } @SubscribeEvent - public void onCommandsRegister(RegisterCommandsEvent event) - { + public void onCommandsRegister(RegisterCommandsEvent event) { new ForgeCommand(event.getDispatcher()); ConfigCommand.register(event.getDispatcher()); } @@ -117,14 +105,12 @@ public class ForgeInternalHandler private static LootModifierManager INSTANCE; @SubscribeEvent - public void onResourceReload(AddReloadListenerEvent event) - { + public void onResourceReload(AddReloadListenerEvent event) { INSTANCE = new LootModifierManager(); event.addListener(INSTANCE); } - static LootModifierManager getLootModifierManager() - { + static LootModifierManager getLootModifierManager() { if(INSTANCE == null) throw new IllegalStateException("Can not retrieve LootModifierManager until resources have loaded once."); return INSTANCE; @@ -132,19 +118,20 @@ public class ForgeInternalHandler */ @SubscribeEvent - public void resourceReloadListeners(AddReloadListenerEvent event) - { + public void resourceReloadListeners(AddReloadListenerEvent event) { event.addListener(TierSortingRegistry.getReloadListener()); event.addListener(CreativeModeTabRegistry.getReloadListener()); } @SubscribeEvent(priority = EventPriority.HIGHEST) - public void builtinMobSpawnBlocker(EntityJoinLevelEvent event) - { + public void builtinMobSpawnBlocker(EntityJoinLevelEvent event) { if(event.getEntity() instanceof Mob mob && mob.isSpawnCancelled()) - { event.setCanceled(true); - } + } + + @SubscribeEvent + public void onConnectionStart(ConnectionStartEvent event) { + NetworkFilters.injectIfNecessary(event.getConnection()); } } diff --git a/src/main/java/net/minecraftforge/common/ForgeMod.java b/src/main/java/net/minecraftforge/common/ForgeMod.java index 1129d504cb..b14373f339 100644 --- a/src/main/java/net/minecraftforge/common/ForgeMod.java +++ b/src/main/java/net/minecraftforge/common/ForgeMod.java @@ -71,7 +71,8 @@ import net.minecraftforge.registries.holdersets.AnyHolderSet; import net.minecraftforge.registries.holdersets.HolderSetType; import net.minecraftforge.registries.holdersets.NotHolderSet; import net.minecraftforge.registries.holdersets.OrHolderSet; -import net.minecraftforge.network.NetworkConstants; +import net.minecraftforge.network.NetworkInitialization; +import net.minecraftforge.network.tasks.ForgeNetworkConfigurationHandler; import net.minecraftforge.event.server.ServerStoppingEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.data.event.GatherDataEvent; @@ -115,11 +116,9 @@ import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; -import java.util.stream.Collectors; @Mod("forge") -public class ForgeMod -{ +public class ForgeMod { public static final String VERSION_CHECK_CAT = "version_checking"; private static final Logger LOGGER = LogManager.getLogger(); private static final Marker FORGEMOD = MarkerManager.getMarker("FORGEMOD"); @@ -260,9 +259,9 @@ public class ForgeMod .viscosity(0)) { @Override - public void setItemMovement(ItemEntity entity) - { - if (!entity.isNoGravity()) entity.setDeltaMovement(entity.getDeltaMovement().add(0.0D, -0.04D, 0.0D)); + public void setItemMovement(ItemEntity entity) { + if (!entity.isNoGravity()) + entity.setDeltaMovement(entity.getDeltaMovement().add(0.0D, -0.04D, 0.0D)); } }); public static final RegistryObject WATER_TYPE = VANILLA_FLUID_TYPES.register("water", () -> @@ -278,60 +277,52 @@ public class ForgeMod .canHydrate(true)) { @Override - public @Nullable BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) - { + public @Nullable BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) { return canFluidLog ? super.getBlockPathType(state, level, pos, mob, true) : null; } @Override - public void initializeClient(Consumer consumer) - { - consumer.accept(new IClientFluidTypeExtensions() - { + public void initializeClient(Consumer consumer) { + consumer.accept(new IClientFluidTypeExtensions() { private static final ResourceLocation UNDERWATER_LOCATION = new ResourceLocation("textures/misc/underwater.png"), WATER_STILL = new ResourceLocation("block/water_still"), WATER_FLOW = new ResourceLocation("block/water_flow"), WATER_OVERLAY = new ResourceLocation("block/water_overlay"); @Override - public ResourceLocation getStillTexture() - { + public ResourceLocation getStillTexture() { return WATER_STILL; } @Override - public ResourceLocation getFlowingTexture() - { + public ResourceLocation getFlowingTexture() { return WATER_FLOW; } @Nullable @Override - public ResourceLocation getOverlayTexture() - { + public ResourceLocation getOverlayTexture() { return WATER_OVERLAY; } @Override - public ResourceLocation getRenderOverlayTexture(Minecraft mc) - { + public ResourceLocation getRenderOverlayTexture(Minecraft mc) { return UNDERWATER_LOCATION; } @Override - public int getTintColor() - { + public int getTintColor() { return 0xFF3F76E4; } @Override - public int getTintColor(FluidState state, BlockAndTintGetter getter, BlockPos pos) - { + public int getTintColor(FluidState state, BlockAndTintGetter getter, BlockPos pos) { return BiomeColors.getAverageWaterColor(getter, pos) | 0xFF000000; } }); } }); + public static final RegistryObject LAVA_TYPE = VANILLA_FLUID_TYPES.register("lava", () -> new FluidType(FluidType.Properties.create() .descriptionId("block.minecraft.lava") @@ -347,35 +338,29 @@ public class ForgeMod .temperature(1300)) { @Override - public double motionScale(Entity entity) - { + public double motionScale(Entity entity) { return entity.level().dimensionType().ultraWarm() ? 0.007D : 0.0023333333333333335D; } @Override - public void setItemMovement(ItemEntity entity) - { + public void setItemMovement(ItemEntity entity) { Vec3 vec3 = entity.getDeltaMovement(); entity.setDeltaMovement(vec3.x * (double)0.95F, vec3.y + (double)(vec3.y < (double)0.06F ? 5.0E-4F : 0.0F), vec3.z * (double)0.95F); } @Override - public void initializeClient(Consumer consumer) - { - consumer.accept(new IClientFluidTypeExtensions() - { + public void initializeClient(Consumer consumer) { + consumer.accept(new IClientFluidTypeExtensions() { private static final ResourceLocation LAVA_STILL = new ResourceLocation("block/lava_still"), LAVA_FLOW = new ResourceLocation("block/lava_flow"); @Override - public ResourceLocation getStillTexture() - { + public ResourceLocation getStillTexture() { return LAVA_STILL; } @Override - public ResourceLocation getFlowingTexture() - { + public ResourceLocation getFlowingTexture() { return LAVA_FLOW; } }); @@ -390,21 +375,18 @@ public class ForgeMod public static final RegistryObject FLOWING_MILK = RegistryObject.create(new ResourceLocation("flowing_milk"), ForgeRegistries.FLUIDS); private static ForgeMod INSTANCE; - public static ForgeMod getInstance() - { + public static ForgeMod getInstance() { return INSTANCE; } /** * Run this method during mod constructor to enable milk and add it to the Minecraft milk bucket */ - public static void enableMilkFluid() - { + public static void enableMilkFluid() { enableMilkFluid = true; } - public ForgeMod() - { + public ForgeMod() { LOGGER.info(FORGEMOD,"Forge mod loading, version {}, for MC {} with MCP {}", ForgeVersion.getVersion(), MCPVersion.getMCVersion(), MCPVersion.getMCPVersion()); ForgeSnapshotsMod.logStartupWarning(); INSTANCE = this; @@ -415,7 +397,8 @@ public class ForgeMod return uuid.toString(); }); - LOGGER.debug(FORGEMOD, "Loading Network data for FML net version: {}", NetworkConstants.init()); + NetworkInitialization.init(); + CrashReportCallables.registerCrashCallable("FML", ForgeVersion::getSpec); CrashReportCallables.registerCrashCallable("Forge", ()->ForgeVersion.getGroup()+":"+ForgeVersion.getVersion()); @@ -440,7 +423,6 @@ public class ForgeMod HOLDER_SET_TYPES.register(modEventBus); VANILLA_FLUID_TYPES.register(modEventBus); MinecraftForge.EVENT_BUS.addListener(this::serverStopping); - MinecraftForge.EVENT_BUS.addListener(this::missingSoundMapping); ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, ForgeConfig.clientSpec); ModLoadingContext.get().registerConfig(ModConfig.Type.SERVER, ForgeConfig.serverSpec); ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, ForgeConfig.commonSpec); @@ -454,6 +436,7 @@ public class ForgeMod MinecraftForge.EVENT_BUS.register(MinecraftForge.INTERNAL_HANDLER); MinecraftForge.EVENT_BUS.addListener(this::mappingChanged); MinecraftForge.EVENT_BUS.addListener(this::registerPermissionNodes); + MinecraftForge.EVENT_BUS.register(new ForgeNetworkConfigurationHandler()); ForgeRegistries.ITEMS.tags().addOptionalTagDefaults(Tags.Items.ENCHANTING_FUELS, Set.of(ForgeRegistries.ITEMS.getDelegateOrThrow(Items.LAPIS_LAZULI))); @@ -462,28 +445,23 @@ public class ForgeMod addAlias(ForgeRegistries.ATTRIBUTES, new ResourceLocation("forge", "attack_range"), new ResourceLocation("forge", "entity_reach")); } - public void preInit(FMLCommonSetupEvent evt) - { + public void preInit(FMLCommonSetupEvent evt) { VersionChecker.startVersionCheck(); //VanillaPacketSplitter.register(); } - public void loadComplete(FMLLoadCompleteEvent event) - { + public void loadComplete(FMLLoadCompleteEvent event) { } - public void serverStopping(ServerStoppingEvent evt) - { + public void serverStopping(ServerStoppingEvent evt) { WorldWorkerManager.clear(); } - public void mappingChanged(IdMappingEvent evt) - { + public void mappingChanged(IdMappingEvent evt) { Ingredient.invalidateAll(); } - public void gatherData(GatherDataEvent event) - { + public void gatherData(GatherDataEvent event) { DataGenerator gen = event.getGenerator(); PackOutput packOutput = gen.getPackOutput(); CompletableFuture lookupProvider = event.getLookupProvider(); @@ -509,33 +487,9 @@ public class ForgeMod gen.addProvider(event.includeClient(), new VanillaSoundDefinitionsProvider(packOutput, existingFileHelper)); } - public void missingSoundMapping(MissingMappingsEvent event) - { - if (event.getKey() != ForgeRegistries.Keys.SOUND_EVENTS) - return; - - //Removed in 1.15, see https://minecraft.gamepedia.com/Parrot#History - List removedSounds = Arrays.asList("entity.parrot.imitate.panda", "entity.parrot.imitate.zombie_pigman", "entity.parrot.imitate.enderman", "entity.parrot.imitate.polar_bear", "entity.parrot.imitate.wolf"); - for (MissingMappingsEvent.Mapping mapping : event.getAllMappings(ForgeRegistries.Keys.SOUND_EVENTS)) - { - ResourceLocation regName = mapping.getKey(); - if (regName != null && regName.getNamespace().equals("minecraft")) - { - String path = regName.getPath(); - if (removedSounds.stream().anyMatch(s -> s.equals(path))) - { - LOGGER.info("Ignoring removed minecraft sound {}", regName); - mapping.ignore(); - } - } - } - } - // done in an event instead of deferred to only enable if a mod requests it - public void registerFluids(RegisterEvent event) - { - if (enableMilkFluid) - { + public void registerFluids(RegisterEvent event) { + if (enableMilkFluid) { // register milk fill, empty sounds (delegates to water fill, empty sounds) event.register(ForgeRegistries.Keys.SOUND_EVENTS, helper -> { helper.register(BUCKET_EMPTY_MILK.getId(), SoundEvent.createVariableRangeEvent(BUCKET_EMPTY_MILK.getId())); @@ -544,28 +498,23 @@ public class ForgeMod // register fluid type event.register(ForgeRegistries.Keys.FLUID_TYPES, helper -> helper.register(MILK_TYPE.getId(), new FluidType( - FluidType.Properties.create().density(1024).viscosity(1024) - .sound(SoundActions.BUCKET_FILL, BUCKET_FILL_MILK.get()) - .sound(SoundActions.BUCKET_EMPTY, BUCKET_EMPTY_MILK.get()) - ) - { + FluidType.Properties.create().density(1024).viscosity(1024) + .sound(SoundActions.BUCKET_FILL, BUCKET_FILL_MILK.get()) + .sound(SoundActions.BUCKET_EMPTY, BUCKET_EMPTY_MILK.get()) + ) { @Override - public void initializeClient(Consumer consumer) - { - consumer.accept(new IClientFluidTypeExtensions() - { - private static final ResourceLocation MILK_STILL = new ResourceLocation("forge", "block/milk_still"), - MILK_FLOW = new ResourceLocation("forge", "block/milk_flowing"); + public void initializeClient(Consumer consumer) { + consumer.accept(new IClientFluidTypeExtensions() { + private static final ResourceLocation MILK_STILL = new ResourceLocation("forge", "block/milk_still"); + private static final ResourceLocation MILK_FLOW = new ResourceLocation("forge", "block/milk_flowing"); @Override - public ResourceLocation getStillTexture() - { + public ResourceLocation getStillTexture() { return MILK_STILL; } @Override - public ResourceLocation getFlowingTexture() - { + public ResourceLocation getFlowingTexture() { return MILK_FLOW; } }); @@ -583,24 +532,20 @@ public class ForgeMod } } - public void registerVanillaDisplayContexts(RegisterEvent event) - { - if (event.getRegistryKey().equals(ForgeRegistries.Keys.DISPLAY_CONTEXTS)) - { + public void registerVanillaDisplayContexts(RegisterEvent event) { + if (event.getRegistryKey().equals(ForgeRegistries.Keys.DISPLAY_CONTEXTS)) { IForgeRegistryInternal forgeRegistry = (IForgeRegistryInternal) event.getForgeRegistry(); if (forgeRegistry == null) throw new IllegalStateException("Item display context was not a forge registry, wtf???"); Arrays.stream(ItemDisplayContext.values()) - .filter(Predicate.not(ItemDisplayContext::isModded)) - .forEach(ctx -> forgeRegistry.register(ctx.getId(), new ResourceLocation("minecraft", ctx.getSerializedName()), ctx)); + .filter(Predicate.not(ItemDisplayContext::isModded)) + .forEach(ctx -> forgeRegistry.register(ctx.getId(), new ResourceLocation("minecraft", ctx.getSerializedName()), ctx)); } } - public void registerRecipeSerializers(RegisterEvent event) - { - if (event.getRegistryKey().equals(ForgeRegistries.Keys.RECIPE_SERIALIZERS)) - { + public void registerRecipeSerializers(RegisterEvent event) { + if (event.getRegistryKey().equals(ForgeRegistries.Keys.RECIPE_SERIALIZERS)) { CraftingHelper.register(AndCondition.Serializer.INSTANCE); CraftingHelper.register(FalseCondition.Serializer.INSTANCE); CraftingHelper.register(ItemExistsCondition.Serializer.INSTANCE); @@ -623,8 +568,7 @@ public class ForgeMod } } - public void registerLootData(RegisterEvent event) - { + public void registerLootData(RegisterEvent event) { if (!event.getRegistryKey().equals(Registries.LOOT_CONDITION_TYPE)) return; @@ -635,8 +579,7 @@ public class ForgeMod public static final PermissionNode USE_SELECTORS_PERMISSION = new PermissionNode<>("forge", "use_entity_selectors", PermissionTypes.BOOLEAN, (player, uuid, contexts) -> player != null && player.hasPermissions(Commands.LEVEL_GAMEMASTERS)); - public void registerPermissionNodes(PermissionGatherEvent.Nodes event) - { + public void registerPermissionNodes(PermissionGatherEvent.Nodes event) { event.addNodes(USE_SELECTORS_PERMISSION); } @@ -644,8 +587,7 @@ public class ForgeMod * TODO: Remove when {@link ForgeRegistry#addAlias(ResourceLocation, ResourceLocation)} is elevated to {@link IForgeRegistry}. */ @Deprecated(forRemoval = true, since = "1.20") - private static void addAlias(IForgeRegistry registry, ResourceLocation from, ResourceLocation to) - { + private static void addAlias(IForgeRegistry registry, ResourceLocation from, ResourceLocation to) { ForgeRegistry fReg = (ForgeRegistry) registry; fReg.addAlias(from, to); } diff --git a/src/main/java/net/minecraftforge/common/TierSortingRegistry.java b/src/main/java/net/minecraftforge/common/TierSortingRegistry.java index 75679eaa7b..28b679189b 100644 --- a/src/main/java/net/minecraftforge/common/TierSortingRegistry.java +++ b/src/main/java/net/minecraftforge/common/TierSortingRegistry.java @@ -31,26 +31,28 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ClientPlayerNetworkEvent; import net.minecraftforge.event.entity.player.PlayerEvent; +import net.minecraftforge.event.network.CustomPayloadEvent; import net.minecraftforge.fml.loading.FMLEnvironment; import net.minecraftforge.fml.loading.toposort.TopologicalSort; +import net.minecraftforge.network.ChannelBuilder; import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.NetworkEvent; -import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.PacketDistributor; -import net.minecraftforge.network.simple.SimpleChannel; +import net.minecraftforge.network.SimpleChannel; import net.minecraftforge.server.ServerLifecycleHooks; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.*; -import java.util.*; -import java.util.function.Supplier; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; import java.util.stream.Collectors; -public class TierSortingRegistry -{ +public class TierSortingRegistry { private static final Logger LOGGER = LogManager.getLogger(); private static final ResourceLocation ITEM_TIER_ORDERING_JSON = new ResourceLocation("forge", "item_tier_ordering.json"); @@ -61,8 +63,7 @@ public class TierSortingRegistry * @param after List of tiers to place this tier after (the tiers in the list will be considered lesser tiers) * @param before List of tiers to place this tier before (the tiers in the list will be considered better tiers) */ - public static synchronized Tier registerTier(Tier tier, ResourceLocation name, List after, List before) - { + public static synchronized Tier registerTier(Tier tier, ResourceLocation name, List after, List before) { if (tiers.containsKey(name)) throw new IllegalStateException("Duplicate tier name " + name); @@ -77,8 +78,7 @@ public class TierSortingRegistry * This list will remain valid * @return An unmodifiable list of tiers ordered lesser to greater */ - public static List getSortedTiers() - { + public static List getSortedTiers() { return sortedTiersUnmodifiable; } @@ -88,8 +88,7 @@ public class TierSortingRegistry * @return The tier, or null if not registered */ @Nullable - public static Tier byName(ResourceLocation name) - { + public static Tier byName(ResourceLocation name) { return tiers.get(name); } @@ -99,8 +98,7 @@ public class TierSortingRegistry * @return The name for the tier, or null if not registered */ @Nullable - public static ResourceLocation getName(Tier tier) - { + public static ResourceLocation getName(Tier tier) { return tiers.inverse().get(tier); } @@ -109,8 +107,7 @@ public class TierSortingRegistry * @param tier The tier to query * @return True if isCorrectTierForDrops should be called for the tier */ - public static boolean isTierSorted(Tier tier) - { + public static boolean isTierSorted(Tier tier) { return getName(tier) != null; } @@ -120,8 +117,7 @@ public class TierSortingRegistry * @param state The state to test against * @return True if the tier is good enough */ - public static boolean isCorrectTierForDrops(Tier tier, BlockState state) - { + public static boolean isCorrectTierForDrops(Tier tier, BlockState state) { if (!isTierSorted(tier)) return isCorrectTierVanilla(tier, state); @@ -138,8 +134,7 @@ public class TierSortingRegistry * @param tier The tier * @return All the lower tiers */ - public static List getTiersLowerThan(Tier tier) - { + public static List getTiersLowerThan(Tier tier) { if (!isTierSorted(tier)) return List.of(); return sortedTiers.stream().takeWhile(t -> t != tier).toList(); } @@ -149,41 +144,27 @@ public class TierSortingRegistry /** * Fallback for when a tier isn't in the registry, copy of the logic in {@link DiggerItem#isCorrectToolForDrops} */ - private static boolean isCorrectTierVanilla(Tier tier, BlockState state) - { + private static boolean isCorrectTierVanilla(Tier tier, BlockState state) { + @SuppressWarnings("deprecation") int i = tier.getLevel(); if (i < 3 && state.is(BlockTags.NEEDS_DIAMOND_TOOL)) - { return false; - } else if (i < 2 && state.is(BlockTags.NEEDS_IRON_TOOL)) - { return false; - } else if (i < 1 && state.is(BlockTags.NEEDS_STONE_TOOL)) - { return false; - } return true; } - private static void processTier(Tier tier, ResourceLocation name, List afters, List befores) - { + private static void processTier(Tier tier, ResourceLocation name, List afters, List befores) { tiers.put(name, tier); for(Object after : afters) - { - ResourceLocation other = getTierName(after); - edges.put(other, name); - } + edges.put(getTierName(after), name); for(Object before : befores) - { - ResourceLocation other = getTierName(before); - edges.put(name, other); - } + edges.put(name, getTierName(before)); } - private static ResourceLocation getTierName(Object entry) - { + private static ResourceLocation getTierName(Object entry) { if (entry instanceof String s) return new ResourceLocation(s); if (entry instanceof ResourceLocation rl) @@ -218,63 +199,55 @@ public class TierSortingRegistry private static final List sortedTiersUnmodifiable = Collections.unmodifiableList(sortedTiers); private static final ResourceLocation CHANNEL_NAME = new ResourceLocation("forge:tier_sorting"); - private static final String PROTOCOL_VERSION = "1.0"; - private static final SimpleChannel SYNC_CHANNEL = NetworkRegistry.newSimpleChannel( - CHANNEL_NAME, () -> "1.0", - versionFromServer -> PROTOCOL_VERSION.equals(versionFromServer) || (allowVanilla() && NetworkRegistry.ACCEPTVANILLA.equals(versionFromServer)), - versionFromClient -> PROTOCOL_VERSION.equals(versionFromClient) || (allowVanilla() && NetworkRegistry.ACCEPTVANILLA.equals(versionFromClient)) - ); + private static final SimpleChannel SYNC_CHANNEL = ChannelBuilder + .named(CHANNEL_NAME) + .networkProtocolVersion(1) + .acceptedVersions((s, v) -> v == 1 || allowVanilla()) // Accepts vanilla unless we've got custom tiers + .simpleChannel() + .messageBuilder(SyncPacket.class, NetworkDirection.PLAY_TO_CLIENT) + .encoder(SyncPacket::encode) + .decoder(TierSortingRegistry::receive) + .consumerNetworkThread(TierSortingRegistry::handle) + .add(); - static boolean allowVanilla() - { + static boolean allowVanilla() { return !hasCustomTiers; } /*package private*/ - static void init() - { - SYNC_CHANNEL.registerMessage(0, SyncPacket.class, SyncPacket::encode, TierSortingRegistry::receive, TierSortingRegistry::handle, Optional.of(NetworkDirection.PLAY_TO_CLIENT)); + static void init() { MinecraftForge.EVENT_BUS.addListener(TierSortingRegistry::playerLoggedIn); - if (FMLEnvironment.dist == Dist.CLIENT) ClientEvents.init(); + if (FMLEnvironment.dist == Dist.CLIENT) + ClientEvents.init(); } /*package private*/ - static PreparableReloadListener getReloadListener() - { - return new SimplePreparableReloadListener() - { + static PreparableReloadListener getReloadListener() { + return new SimplePreparableReloadListener() { final Gson gson = (new GsonBuilder()).create(); @NotNull @Override - protected JsonObject prepare(@NotNull ResourceManager resourceManager, ProfilerFiller p) - { + protected JsonObject prepare(@NotNull ResourceManager resourceManager, ProfilerFiller p) { Optional res = resourceManager.getResource(ITEM_TIER_ORDERING_JSON); if (res.isEmpty()) return new JsonObject(); - try (Reader reader = res.get().openAsReader()) - { + try (var reader = res.get().openAsReader()) { return gson.fromJson(reader, JsonObject.class); - } - catch (IOException e) - { + } catch (IOException e) { LOGGER.error("Could not read Tier sorting file " + ITEM_TIER_ORDERING_JSON, e); return new JsonObject(); } } @Override - protected void apply(@NotNull JsonObject data, @NotNull ResourceManager resourceManager, ProfilerFiller p) - { - try - { - if (data.size() > 0) - { + protected void apply(@NotNull JsonObject data, @NotNull ResourceManager resourceManager, ProfilerFiller p) { + try { + if (data.size() > 0) { JsonArray order = GsonHelper.getAsJsonArray(data, "order"); List customOrder = new ArrayList<>(); - for (JsonElement entry : order) - { + for (JsonElement entry : order) { ResourceLocation id = new ResourceLocation(entry.getAsString()); Tier tier = byName(id); if (tier == null) throw new IllegalStateException("Tier not found with name " + id); @@ -288,9 +261,7 @@ public class TierSortingRegistry setTierOrder(customOrder); return; } - } - catch(Exception e) - { + } catch(Exception e) { LOGGER.error("Error parsing Tier sorting file " + ITEM_TIER_ORDERING_JSON, e); } @@ -299,15 +270,12 @@ public class TierSortingRegistry }; } - @SuppressWarnings("UnstableApiUsage") - private static void recalculateItemTiers() - { + private static void recalculateItemTiers() { final MutableGraph graph = GraphBuilder.directed().nodeOrder(ElementOrder.insertion()).build(); for(Tier tier : tiers.values()) - { graph.addNode(tier); - } + edges.forEach((key, value) -> { if (tiers.containsKey(key) && tiers.containsKey(value)) graph.putEdge(tiers.get(key), tiers.get(value)); @@ -317,80 +285,65 @@ public class TierSortingRegistry setTierOrder(tierList); } - private static void setTierOrder(List tierList) - { + private static void setTierOrder(List tierList) { runInServerThreadIfPossible(hasServer -> { sortedTiers.clear(); sortedTiers.addAll(tierList); - if(hasServer) syncToAll(); + if (hasServer) + syncToAll(); }); } - private static void runInServerThreadIfPossible(BooleanConsumer runnable) - { + private static void runInServerThreadIfPossible(BooleanConsumer runnable) { MinecraftServer server = ServerLifecycleHooks.getCurrentServer(); - if (server != null) server.execute(() -> runnable.accept(true)); - else runnable.accept(false); + if (server != null) + server.execute(() -> runnable.accept(true)); + else + runnable.accept(false); } - private static void syncToAll() - { - for(ServerPlayer serverPlayer : ServerLifecycleHooks.getCurrentServer().getPlayerList().getPlayers()) - { + private static void syncToAll() { + for (ServerPlayer serverPlayer : ServerLifecycleHooks.getCurrentServer().getPlayerList().getPlayers()) syncToPlayer(serverPlayer); - } } - private static void playerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) - { + private static void playerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { if (event.getEntity() instanceof ServerPlayer serverPlayer) - { syncToPlayer(serverPlayer); - } } - private static void syncToPlayer(ServerPlayer serverPlayer) - { + private static void syncToPlayer(ServerPlayer serverPlayer) { if (SYNC_CHANNEL.isRemotePresent(serverPlayer.connection.getConnection()) && !serverPlayer.connection.getConnection().isMemoryConnection()) - { - SYNC_CHANNEL.send(PacketDistributor.PLAYER.with(() -> serverPlayer), new SyncPacket(sortedTiers.stream().map(TierSortingRegistry::getName).toList())); - } + SYNC_CHANNEL.send(new SyncPacket(sortedTiers.stream().map(TierSortingRegistry::getName).toList()), PacketDistributor.PLAYER.with(serverPlayer)); } - private static SyncPacket receive(FriendlyByteBuf buffer) - { + private static SyncPacket receive(FriendlyByteBuf buffer) { int count = buffer.readVarInt(); List list = new ArrayList<>(); - for(int i=0;i context) - { + private static void handle(SyncPacket packet, CustomPayloadEvent.Context context) { setTierOrder(packet.tiers.stream().map(TierSortingRegistry::byName).toList()); - context.get().setPacketHandled(true); + context.setPacketHandled(true); } - private record SyncPacket(List tiers) - { - private void encode(FriendlyByteBuf buffer) - { + private record SyncPacket(List tiers) { + private void encode(FriendlyByteBuf buffer) { buffer.writeVarInt(tiers.size()); for(ResourceLocation loc : tiers) buffer.writeResourceLocation(loc); } } - private static class ClientEvents - { - public static void init() - { + private static class ClientEvents { + public static void init() { MinecraftForge.EVENT_BUS.addListener(ClientEvents::clientLogInToServer); } - private static void clientLogInToServer(ClientPlayerNetworkEvent.LoggingIn event) - { + private static void clientLogInToServer(ClientPlayerNetworkEvent.LoggingIn event) { if (event.getConnection() == null || !event.getConnection().isMemoryConnection()) recalculateItemTiers(); } diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeFriendlyByteBuf.java b/src/main/java/net/minecraftforge/common/extensions/IForgeFriendlyByteBuf.java index aa77125848..9eeb131a34 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeFriendlyByteBuf.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeFriendlyByteBuf.java @@ -19,11 +19,9 @@ import java.util.Objects; /** * Extension-Interface providing methods for writing registry-id's instead of their registry-names. */ -public interface IForgeFriendlyByteBuf -{ - private FriendlyByteBuf self() - { - return (FriendlyByteBuf) this; +public interface IForgeFriendlyByteBuf { + private FriendlyByteBuf self() { + return (FriendlyByteBuf)this; } /** @@ -33,8 +31,7 @@ public interface IForgeFriendlyByteBuf * @param entry The entry who's registryName is to be written * @param The type of the entry. */ - default void writeRegistryIdUnsafe(@NotNull IForgeRegistry registry, @NotNull T entry) - { + default void writeRegistryIdUnsafe(@NotNull IForgeRegistry registry, @NotNull T entry) { ForgeRegistry forgeRegistry = (ForgeRegistry) registry; int id = forgeRegistry.getID(entry); self().writeVarInt(id); @@ -46,8 +43,7 @@ public interface IForgeFriendlyByteBuf * @param registry The registry containing the entry represented by this key * @param entryKey The registry-name of an entry in this {@link IForgeRegistry} */ - default void writeRegistryIdUnsafe(@NotNull IForgeRegistry registry, @NotNull ResourceLocation entryKey) - { + default void writeRegistryIdUnsafe(@NotNull IForgeRegistry registry, @NotNull ResourceLocation entryKey) { ForgeRegistry forgeRegistry = (ForgeRegistry) registry; int id = forgeRegistry.getID(entryKey); self().writeVarInt(id); @@ -58,8 +54,7 @@ public interface IForgeFriendlyByteBuf * read id, that the registry's default value will be returned. * @param registry The registry containing the entry */ - default T readRegistryIdUnsafe(@NotNull IForgeRegistry registry) - { + default T readRegistryIdUnsafe(@NotNull IForgeRegistry registry) { ForgeRegistry forgeRegistry = (ForgeRegistry) registry; int id = self().readVarInt(); return forgeRegistry.getValue(id); @@ -77,8 +72,7 @@ public interface IForgeFriendlyByteBuf * @throws NullPointerException if the registry or entry was null * @throws IllegalArgumentException if the registry does not contain the specified value */ - default void writeRegistryId(@NotNull IForgeRegistry registry, @NotNull T entry) - { + default void writeRegistryId(@NotNull IForgeRegistry registry, @NotNull T entry) { Objects.requireNonNull(registry, "Cannot write a null registry key!"); Objects.requireNonNull(entry,"Cannot write a null registry entry!"); ResourceLocation name = registry.getRegistryName(); @@ -94,8 +88,7 @@ public interface IForgeFriendlyByteBuf * @param The type of the registry-entry. Notice that this should match the actual type written to the buffer. * @throws NullPointerException if the registry could not be found. */ - default T readRegistryId() - { + default T readRegistryId() { ResourceLocation location = self().readResourceLocation(); //TODO change to reading a varInt once registries use id's ForgeRegistry registry = RegistryManager.ACTIVE.getRegistry(location); return registry.getValue(self().readVarInt()); @@ -107,8 +100,7 @@ public interface IForgeFriendlyByteBuf * @throws IllegalArgumentException if the retrieved entries registryType doesn't match the one passed in. * @throws NullPointerException if the registry could not be found. */ - default T readRegistryIdSafe(Class registrySuperType) - { + default T readRegistryIdSafe(Class registrySuperType) { T value = readRegistryId(); if (!registrySuperType.isAssignableFrom(value.getClass())) throw new IllegalArgumentException("Attempted to read an registryValue of the wrong type from the Buffer!"); @@ -121,11 +113,10 @@ public interface IForgeFriendlyByteBuf * * @param stack FluidStack to be written to the packet buffer. */ - default void writeFluidStack(FluidStack stack) - { - if (stack.isEmpty()) { + default void writeFluidStack(FluidStack stack) { + if (stack.isEmpty()) self().writeBoolean(false); - } else { + else { self().writeBoolean(true); stack.writeToPacket(self()); } @@ -134,8 +125,7 @@ public interface IForgeFriendlyByteBuf /** * Reads a FluidStack from this buffer. */ - default FluidStack readFluidStack() - { + default FluidStack readFluidStack() { return !self().readBoolean() ? FluidStack.EMPTY : FluidStack.readFromPacket(self()); } } diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeMenuType.java b/src/main/java/net/minecraftforge/common/extensions/IForgeMenuType.java index 8c624b3216..c42b51983f 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeMenuType.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeMenuType.java @@ -12,12 +12,10 @@ import net.minecraft.world.inventory.MenuType; import net.minecraft.network.FriendlyByteBuf; import net.minecraftforge.network.IContainerFactory; -public interface IForgeMenuType -{ - static MenuType create(IContainerFactory factory) - { +public interface IForgeMenuType { + static MenuType create(IContainerFactory factory) { return new MenuType<>(factory, FeatureFlags.DEFAULT_FLAGS); } - + T create(int windowId, Inventory playerInv, FriendlyByteBuf extraData); } diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeServerPlayer.java b/src/main/java/net/minecraftforge/common/extensions/IForgeServerPlayer.java new file mode 100644 index 0000000000..b963110e9f --- /dev/null +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeServerPlayer.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.common.extensions; + +import java.util.function.Consumer; + +import io.netty.buffer.Unpooled; +import net.minecraft.core.BlockPos; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.MenuProvider; +import net.minecraftforge.client.ConfigScreenHandler; +import net.minecraftforge.event.ForgeEventFactory; +import net.minecraftforge.network.NetworkInitialization; +import net.minecraftforge.network.packets.OpenContainer; + +public interface IForgeServerPlayer { + private ServerPlayer self() { + return (ServerPlayer)this; + } + + /** + * Request to open a GUI on the client, from the server + * + * Refer to {@link ConfigScreenHandler.ConfigScreenFactory} for how to provide a function to consume + * these GUI requests on the client. + * + * @param player The player to open the GUI for + * @param containerSupplier A supplier of container properties including the registry name of the container + * @param pos A block pos, which will be encoded into the auxillary data for this request + */ + default void openMenu(MenuProvider containerSupplier, BlockPos pos) { + openMenu(containerSupplier, buf -> buf.writeBlockPos(pos)); + } + + /** + * Request to open a GUI on the client, from the server + * + * Refer to {@link ConfigScreenHandler.ConfigScreenFactory} for how to provide a function to consume + * these GUI requests on the client. + * + * The maximum size for #extraDataWriter is 32600 bytes. + * + * @param player The player to open the GUI for + * @param containerSupplier A supplier of container properties including the registry name of the container + * @param extraDataWriter Consumer to write any additional data the GUI needs + */ + @SuppressWarnings("resource") + default void openMenu(MenuProvider containerSupplier, Consumer extraDataWriter) { + var player = self(); + if (player.level().isClientSide) return; + player.doCloseContainer(); + player.nextContainerCounter(); + int openContainerId = player.containerCounter; + FriendlyByteBuf extraData = new FriendlyByteBuf(Unpooled.buffer()); + extraDataWriter.accept(extraData); + extraData.readerIndex(0); // reset to beginning in case modders read for whatever reason + + FriendlyByteBuf output = new FriendlyByteBuf(Unpooled.buffer()); + output.writeVarInt(extraData.readableBytes()); + output.writeBytes(extraData); + + if (output.readableBytes() > 32600 || output.readableBytes() < 1) + throw new IllegalArgumentException("Invalid PacketBuffer for openGui, found "+ output.readableBytes()+ " bytes"); + var c = containerSupplier.createMenu(openContainerId, player.getInventory(), player); + if (c == null) + return; + var msg = new OpenContainer(c.getType(), openContainerId, containerSupplier.getDisplayName(), output); + NetworkInitialization.PLAY.send(msg, player.connection.getConnection()); + + player.containerMenu = c; + player.initMenu(player.containerMenu); + ForgeEventFactory.onPlayerOpenContainer(player, c); + } + +} diff --git a/src/main/java/net/minecraftforge/common/util/HexDumper.java b/src/main/java/net/minecraftforge/common/util/HexDumper.java index 75837416c8..0857fbf9e1 100644 --- a/src/main/java/net/minecraftforge/common/util/HexDumper.java +++ b/src/main/java/net/minecraftforge/common/util/HexDumper.java @@ -18,11 +18,8 @@ import io.netty.buffer.ByteBuf; * Length: 34 * */ -public class HexDumper -{ - - public static String dump(ByteBuf data) - { +public class HexDumper { + public static String dump(ByteBuf data) { int current = data.readerIndex(); data.readerIndex(0); Instance inst = new Instance(current, data.readableBytes()); @@ -34,29 +31,25 @@ public class HexDumper return inst.finish(); } - public static String dump(byte[] data) - { + public static String dump(byte[] data) { return dump(data, -1); } - public static String dump(byte[] data, int marker) - { + public static String dump(byte[] data, int marker) { Instance inst = new Instance(marker, data.length); for (int x = 0; x < data.length; x++) inst.add(data[x]); return inst.finish(); } - private static class Instance - { + private static class Instance { private static final String HEX = "0123456789ABCDEF"; private final int marked; private final StringBuilder buf; private char[] ascii = new char[16]; private int index = 0; - private Instance(int marked, int size) - { + private Instance(int marked, int size) { this.marked = marked; int lines = ((size + 15) / 16); this.buf = new StringBuilder((size * 3) //Hex @@ -68,16 +61,13 @@ public class HexDumper ascii[x] = ' '; } - public void add(byte data) - { + public void add(byte data) { if (index == 0 && marked != -1) buf.append(index == marked ? '<' : ' '); - if (index != 0 && index % 16 == 0) - { + if (index != 0 && index % 16 == 0) { buf.append('\t'); - for (int x = 0; x < 16; x++) - { + for (int x = 0; x < 16; x++) { buf.append(ascii[x]); ascii[x] = ' '; } @@ -96,11 +86,9 @@ public class HexDumper index++; } - public String finish() - { + public String finish() { int padding = 16 - (index % 16); - if (padding > 0) - { + if (padding > 0) { for (int x = 0; x < padding * 3; x++) buf.append(' '); buf.append('\t'); diff --git a/src/main/java/net/minecraftforge/common/util/PacketLogger.java b/src/main/java/net/minecraftforge/common/util/PacketLogger.java new file mode 100644 index 0000000000..94eb632a94 --- /dev/null +++ b/src/main/java/net/minecraftforge/common/util/PacketLogger.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.common.util; + +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 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; +import net.minecraftforge.network.ICustomPacket; + +/* + * This is a utility class that just dumps packets to the logger. + * If people care I can make this a public API. Makes life a lot easier + * when debugging network things. But it doesn't have a proper API cuz I haven't felt like designing one. + */ +public class PacketLogger { + private static final Logger LOGGER = LogManager.getLogger(); + private static final Marker MARKER = MarkerManager.getMarker("PACKETLOG"); + + private final Connection connection; + public boolean enabled = false; + + public PacketLogger(Connection connection) { + this.connection = connection; + } + + public void send(Packet packet) { + common(connection.getReceiving(), connection.getSending(), packet); + } + + public void recv( Packet packet) { + common(connection.getReceiving(), connection.getReceiving(), packet); + } + + private void common(PacketFlow side, PacketFlow flow, Packet packet) { + if (!enabled) return; + if (packet instanceof ClientboundFinishConfigurationPacket) + enabled = false; + + if (packet instanceof ICustomPacket) { + var data = new FriendlyByteBuf(Unpooled.buffer()); + + packet.write(data); + LOGGER.info(MARKER, "{} {} {}\n{}", side, dir(flow), packet.getClass().getName(), HexDumper.dump(data)); + } else { + LOGGER.info(MARKER, "{} {} {}", side, dir(flow), packet.getClass().getName()); + } + } + + private static String dir(PacketFlow flow) { + return flow == PacketFlow.CLIENTBOUND ? "S->C" : "C->S"; + } +} diff --git a/src/main/java/net/minecraftforge/event/ForgeEventFactory.java b/src/main/java/net/minecraftforge/event/ForgeEventFactory.java index f09ae09731..4a7750d0a2 100644 --- a/src/main/java/net/minecraftforge/event/ForgeEventFactory.java +++ b/src/main/java/net/minecraftforge/event/ForgeEventFactory.java @@ -6,21 +6,18 @@ package net.minecraftforge.event; import java.io.File; -import java.util.*; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import com.mojang.authlib.GameProfile; -import com.mojang.blaze3d.platform.Window; import com.mojang.brigadier.CommandDispatcher; import net.minecraft.advancements.AdvancementHolder; import net.minecraft.advancements.AdvancementProgress; -import net.minecraft.client.MouseHandler; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.renderer.entity.EntityRenderer; -import net.minecraft.client.renderer.entity.EntityRendererProvider.Context; -import net.minecraft.client.resources.PlayerSkin.Model; import net.minecraft.commands.CommandBuildContext; import net.minecraft.core.Holder; import net.minecraft.core.RegistryAccess; @@ -58,6 +55,7 @@ import net.minecraft.world.entity.monster.Zombie; import net.minecraft.world.entity.animal.Animal; import net.minecraft.world.entity.player.Player; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ConfigurationTask; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.item.crafting.RecipeType; @@ -77,6 +75,7 @@ import net.minecraft.sounds.SoundEvent; import net.minecraft.core.BlockPos; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.phys.HitResult; +import net.minecraft.network.Connection; import net.minecraft.network.chat.Component; import net.minecraft.world.level.Explosion; import net.minecraft.world.level.GameRules; @@ -88,9 +87,6 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.storage.ServerLevelData; import net.minecraft.world.level.storage.PlayerDataStorage; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.client.event.EntityRenderersEvent; -import net.minecraftforge.client.event.InputEvent; -import net.minecraftforge.client.event.ScreenEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.ToolAction; import net.minecraftforge.common.capabilities.CapabilityDispatcher; @@ -153,12 +149,13 @@ import net.minecraftforge.event.level.ExplosionEvent; import net.minecraftforge.event.level.PistonEvent; import net.minecraftforge.event.level.SaplingGrowTreeEvent; import net.minecraftforge.event.level.SleepFinishedTimeEvent; +import net.minecraftforge.event.network.ChannelRegistrationChangeEvent; +import net.minecraftforge.event.network.ConnectionStartEvent; +import net.minecraftforge.event.network.GatherLoginConfigurationTasksEvent; import net.minecraftforge.event.level.LevelEvent; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.Event.Result; import net.minecraftforge.fml.LogicalSide; -import net.minecraftforge.fml.ModLoader; - import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -799,70 +796,19 @@ public class ForgeEventFactory { public static void onChunkDataSave(ChunkAccess chunk, LevelAccessor world, CompoundTag data) { post(new ChunkDataEvent.Save(chunk, world, data)); } - - public static void gatherLayers(Map, EntityRenderer> renderers, Map> playerRenderers, Context context) { - // TODO: Why is this a ModLoader event... - ModLoader.get().postEvent(new EntityRenderersEvent.AddLayers(renderers, playerRenderers, context)); - } - - public static boolean onScreenMouseReleasedPre(Screen guiScreen, double mouseX, double mouseY, int button) { - return post(new ScreenEvent.MouseButtonReleased.Pre(guiScreen, mouseX, mouseY, button)); - } - - public static boolean onScreenMouseReleasedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled) { - var result = fire(new ScreenEvent.MouseButtonReleased.Post(guiScreen, mouseX, mouseY, button, handled)).getResult(); - return result == Event.Result.DEFAULT ? handled : result == Event.Result.ALLOW; - } - - public static boolean onScreenMouseClickedPre(Screen guiScreen, double mouseX, double mouseY, int button) { - return post(new ScreenEvent.MouseButtonPressed.Pre(guiScreen, mouseX, mouseY, button)); - } - - public static boolean onScreenMouseClickedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled) { - var result = fire(new ScreenEvent.MouseButtonPressed.Post(guiScreen, mouseX, mouseY, button, handled)).getResult(); - return result == Event.Result.DEFAULT ? handled : result == Event.Result.ALLOW; - } - - public static boolean onMouseButtonPre(int button, int action, int mods) { - return post(new InputEvent.MouseButton.Pre(button, action, mods)); - } - - public static void onMouseButtonPost(int button, int action, int mods) { - post(new InputEvent.MouseButton.Post(button, action, mods)); - } - - public static boolean onScreenMouseScrollPre(Screen guiScreen, double mouseX, double mouseY, double deltaX, double deltaY) { - return post(new ScreenEvent.MouseScrolled.Pre(guiScreen, mouseX, mouseY, deltaX, deltaY)); - } - - public static void onScreenMouseScrollPost(Screen guiScreen, double mouseX, double mouseY, double deltaX, double deltaY) { - post(new ScreenEvent.MouseScrolled.Post(guiScreen, mouseX, mouseY, deltaX, deltaY)); - } - - public static boolean onMouseScroll(MouseHandler mouseHelper, double deltaX, double deltaY) { - return post(new InputEvent.MouseScrollingEvent(deltaX, deltaY, mouseHelper.isLeftPressed(), mouseHelper.isMiddlePressed(), mouseHelper.isRightPressed(), mouseHelper.xpos(), mouseHelper.ypos())); - } - - public static boolean onScreenMouseDragPre(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) { - return post(new ScreenEvent.MouseDragged.Pre(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY)); - } - - public static void onScreenMouseDragPost(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) { - post(new ScreenEvent.MouseDragged.Post(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY)); - } - - public static @Nullable Screen onScreenOpening(Screen old, Screen screen) { - var event = new ScreenEvent.Opening(old, screen); - if (post(event)) - return null; - return event.getNewScreen(); - } - - public static void onScreenClose(Screen screen) { - post(new ScreenEvent.Closing(screen)); - } - public static void onGameShuttingDown() { post(new GameShuttingDownEvent()); } + + public static void gatherLoginConfigTasks(Connection connection, Consumer add) { + post(new GatherLoginConfigurationTasksEvent(connection, add)); + } + + public static void onConnectionStart(Connection connection) { + post(new ConnectionStartEvent(connection)); + } + + public static void onChannelRegistrationChange(Connection connection, ChannelRegistrationChangeEvent.Type changeType, HashSet changed) { + post(new ChannelRegistrationChangeEvent(connection, changeType, changed)); + } } diff --git a/src/main/java/net/minecraftforge/event/entity/player/PlayerNegotiationEvent.java b/src/main/java/net/minecraftforge/event/entity/player/PlayerNegotiationEvent.java deleted file mode 100644 index d1940a9828..0000000000 --- a/src/main/java/net/minecraftforge/event/entity/player/PlayerNegotiationEvent.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.event.entity.player; - -import com.mojang.authlib.GameProfile; -import net.minecraft.network.Connection; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.eventbus.api.Event; - -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Future; - -/** - * This event is fired on the server when a connection has started the Forge handshake, - * Forge will wait for all enqueued work to be completed before proceeding further with the login process. - *
- * This event can be used to delay the player login until any necessary work such as preloading user data has completed. - *
- * This event is fired on the {@link MinecraftForge#EVENT_BUS}. - */ -public class PlayerNegotiationEvent extends Event -{ - - private final Connection connection; - private final GameProfile profile; - private final List> futures; - - public PlayerNegotiationEvent(Connection connection, GameProfile profile, List> futures) - { - this.connection = connection; - this.profile = profile; - this.futures = futures; - } - - /** - * Enqueue work to be completed asynchronously before the login proceeds. - */ - public void enqueueWork(Runnable runnable) - { - enqueueWork(CompletableFuture.runAsync(runnable)); - } - - /** - * Enqueue work to be completed asynchronously before the login proceeds. - */ - public void enqueueWork(Future future) - { - futures.add(future); - } - - public Connection getConnection() - { - return connection; - } - - public GameProfile getProfile() - { - return profile; - } -} diff --git a/src/main/java/net/minecraftforge/event/network/ChannelRegistrationChangeEvent.java b/src/main/java/net/minecraftforge/event/network/ChannelRegistrationChangeEvent.java new file mode 100644 index 0000000000..4b739cf2d3 --- /dev/null +++ b/src/main/java/net/minecraftforge/event/network/ChannelRegistrationChangeEvent.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.event.network; + +import java.util.Collections; +import java.util.Set; + +import net.minecraft.network.Connection; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.eventbus.api.Event; + +/** + * Fired when the channel registration (see minecraft custom channel documentation) changes. + * + * It seems plausible that this will fire multiple times for the same state, depending on what the server is doing. + * It just directly dispatches upon receipt. + */ +public class ChannelRegistrationChangeEvent extends Event { + public enum Type { + REGISTER, UNREGISTER; + } + + private final Connection source; + private final Type changeType; + private final Set channels; + + public ChannelRegistrationChangeEvent(Connection source, Type changeType, Set channels) { + this.source = source; + this.changeType = changeType; + this.channels = Collections.unmodifiableSet(channels); + } + + public Type getType() { + return changeType; + } + + public Connection getSource() { + return source; + } + + public Set getChannels() { + return channels; + } +} \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/event/network/ConnectionStartEvent.java b/src/main/java/net/minecraftforge/event/network/ConnectionStartEvent.java new file mode 100644 index 0000000000..6865b4b41b --- /dev/null +++ b/src/main/java/net/minecraftforge/event/network/ConnectionStartEvent.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.event.network; + +import org.jetbrains.annotations.ApiStatus; + +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.PacketFlow; +import net.minecraftforge.eventbus.api.Event; + +/** + * Fired when a network connection is started, either on the server when it receives the + * ClientIntentionPacket or on the client when the channel is first activated. This is + * intended to allow modders to attach things to the channel that can be used in the future. + * + * As this is a blocking event modders can also do things like load data. Need some example uses. + */ +public class ConnectionStartEvent extends Event { + private final Connection connection; + + @ApiStatus.Internal + public ConnectionStartEvent(Connection connection) { + this.connection = connection; + } + + public Connection getConnection() { + return this.connection; + } + + public boolean isClient() { + return this.connection.getSending() == PacketFlow.SERVERBOUND; + } +} diff --git a/src/main/java/net/minecraftforge/event/network/CustomPayloadEvent.java b/src/main/java/net/minecraftforge/event/network/CustomPayloadEvent.java new file mode 100644 index 0000000000..058ad83490 --- /dev/null +++ b/src/main/java/net/minecraftforge/event/network/CustomPayloadEvent.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.event.network; + +import io.netty.util.Attribute; +import io.netty.util.AttributeKey; + +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.PacketFlow; +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; + +import java.util.concurrent.CompletableFuture; + +// TODO make this not an event, and instead move it to a callback in the Channel itself. +// But also expose it as a generic listener event for anyone who cares about it but is outside out channel control system. +public class CustomPayloadEvent extends Event { + private final ResourceLocation channel; + private final FriendlyByteBuf payload; + private final Context source; + private final int loginIndex; + + public CustomPayloadEvent(ResourceLocation channel, FriendlyByteBuf payload, Context source, int loginIndex) { + this.channel = channel; + this.payload = payload; + this.source = source; + this.loginIndex = loginIndex; + } + + public CustomPayloadEvent(ICustomPacket payload, Context source) { + this(payload.getName(), payload.getInternalData(), source, payload.getIndex()); + } + + public ResourceLocation getChannel() { + return this.channel; + } + + public FriendlyByteBuf getPayload() { + return payload; + } + + public int getLoginIndex() { + return loginIndex; + } + + public Context getSource() { + return source; + } + + /** + * Context for {@link CustomPayloadEvent} + */ + public static class Context { + /** + * The {@link Connection} for this message. + */ + private final Connection connection; + + /** + * The {@link NetworkDirection} this message has been received on. + */ + private final NetworkDirection networkDirection; + + private boolean packetHandled; + + public Context(Connection connection, NetworkDirection networkDirection) { + this.connection = connection; + this.networkDirection = networkDirection; + } + + public boolean isClientSide() { + return getConnection().getReceiving() == PacketFlow.CLIENTBOUND; + } + + public boolean isServerSide() { + return !isClientSide(); + } + + public NetworkDirection getDirection() { + return networkDirection; + } + + public Connection getConnection() { + return connection; + } + + public Attribute attr(AttributeKey key) { + return connection.channel().attr(key); + } + + public void setPacketHandled(boolean packetHandled) { + this.packetHandled = packetHandled; + } + + public boolean getPacketHandled() { + return packetHandled; + } + + public CompletableFuture enqueueWork(Runnable runnable) { + BlockableEventLoop executor = LogicalSidedProvider.WORKQUEUE.get(getDirection().getReceptionSide()); + // 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()) + return executor.submitAsync(runnable); // Use the internal method so thread check isn't done twice + else { + runnable.run(); + return CompletableFuture.completedFuture(null); + } + } + + /** + * When available, gets the sender for packets that are sent from a client to the server. + */ + @Nullable + public ServerPlayer getSender() { + PacketListener netHandler = connection.getPacketListener(); + if (netHandler instanceof ServerGamePacketListenerImpl handler) + return handler.player; + return null; + } + } +} diff --git a/src/main/java/net/minecraftforge/event/network/GatherLoginConfigurationTasksEvent.java b/src/main/java/net/minecraftforge/event/network/GatherLoginConfigurationTasksEvent.java new file mode 100644 index 0000000000..212a909b40 --- /dev/null +++ b/src/main/java/net/minecraftforge/event/network/GatherLoginConfigurationTasksEvent.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.event.network; + +import java.util.function.Consumer; + +import net.minecraft.network.Connection; +import net.minecraft.server.network.ConfigurationTask; +import net.minecraftforge.eventbus.api.Event; + +/** + * Gathers tasks that need to be run during the initial login configuration. + * @see net.minecraft.server.network.ServerConfigurationPacketListenerImpl#startConfiguration() startConfiguration + */ +public class GatherLoginConfigurationTasksEvent extends Event { + private final Connection connection; + private final Consumer add; + + public GatherLoginConfigurationTasksEvent(Connection connection, Consumer add) { + this.connection = connection; + this.add = add; + } + + public Connection getConnection() { + return this.connection; + } + + public void addTask(ConfigurationTask task) { + this.add.accept(task); + } +} diff --git a/src/main/java/net/minecraftforge/logging/PacketDump.java b/src/main/java/net/minecraftforge/logging/PacketDump.java deleted file mode 100644 index cfcd394351..0000000000 --- a/src/main/java/net/minecraftforge/logging/PacketDump.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.logging; - -import io.netty.buffer.ByteBuf; - -public class PacketDump -{ - - public static String getContentDump(ByteBuf buffer) - { - int currentLength = buffer.readableBytes(); - StringBuffer returnString = new StringBuffer((currentLength * 3) + // The - // hex - (currentLength) + // The ascii - (currentLength / 4) + // The tabs/\n's - 30); // The text - - // returnString.append("Buffer contents:\n"); - int i, j; // Loop variables - for (i = 0; i < currentLength; i++) - { - if ((i != 0) && (i % 16 == 0)) - { - // If it's a multiple of 16 and i isn't null, show the ascii - returnString.append('\t'); - for (j = i - 16; j < i; j++) - { - if (buffer.getByte(j) < 0x20 || buffer.getByte(j) > 0x7F) - returnString.append('.'); - else - returnString.append((char) buffer.getByte(j)); - } - // Add a linefeed after the string - returnString.append("\n"); - } - - returnString.append(Integer.toString((buffer.getByte(i) & 0xF0) >> 4, 16) + Integer.toString((buffer.getByte(i) & 0x0F) >> 0, 16)); - returnString.append(' '); - } - - // Add padding spaces if it's not a multiple of 16 - if (i != 0 && i % 16 != 0) - { - for (j = 0; j < ((16 - (i % 16)) * 3); j++) - { - returnString.append(' '); - } - } - // Add the tab for alignment - returnString.append('\t'); - - // Add final characters at right, after padding - - // If it was at the end of a line, print out the full line - if (i > 0 && (i % 16) == 0) - { - j = i - 16; - } else - { - j = (i - (i % 16)); - } - - for (; i >= 0 && j < i; j++) - { - if (buffer.getByte(j) < 0x20 || buffer.getByte(j) > 0x7F) - returnString.append('.'); - else - returnString.append((char) buffer.getByte(j)); - } - - // Finally, tidy it all up with a newline - returnString.append('\n'); - returnString.append("Length: " + currentLength); - - return returnString.toString(); - - } -} diff --git a/src/main/java/net/minecraftforge/network/Channel.java b/src/main/java/net/minecraftforge/network/Channel.java new file mode 100644 index 0000000000..877428da3a --- /dev/null +++ b/src/main/java/net/minecraftforge/network/Channel.java @@ -0,0 +1,163 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network; + +import java.util.Objects; +import java.util.function.IntPredicate; + +import net.minecraft.network.Connection; +import net.minecraft.network.ConnectionProtocol; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketFlow; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.event.network.CustomPayloadEvent; +import net.minecraftforge.network.packets.LoginWrapper; + +public abstract class Channel { + protected final NetworkInstance instance; + + protected Channel(NetworkInstance instance) { + this.instance = instance; + } + + public ResourceLocation getName() { + return instance.getChannelName(); + } + + public int getProtocolVersion() { + return instance.getNetworkProtocolVersion(); + } + + /** + * Returns true if the channel is present in the given connection. + */ + public boolean isRemotePresent(Connection connection) { + return NetworkContext.get(connection).getRemoteChannels().contains(getName()); + } + + protected abstract FriendlyByteBuf toBuffer(MSG message); + + // Package private so we can call from ourselves. + Packet toVanillaPacket(Connection connection, MSG message) { + var protocol = connection.getProtocol(); + var serverbound = connection.getSending() == PacketFlow.SERVERBOUND; + var data = toBuffer(message); + + 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(toBuffer(message), getName()).getThis(); + } else + throw new IllegalStateException("Unsupported protocol " + protocol.name() + " in Forge Networking Channel"); + } + + public void send(MSG msg, Connection connection) { + connection.send(toVanillaPacket(connection, msg)); + } + + /** + * Send a message to the {@link PacketDistributor.PacketTarget} from a {@link PacketDistributor} instance. + * + *
+     *     channel.send(message, PacketDistributor.PLAYER.with(()->player))
+     * 
+ * + * @param target The curried target from a PacketDistributor + * @param message The message to send + * @param The type of the message + */ + public void send(MSG msg, PacketDistributor.PacketTarget target) { + target.send(target.direction().buildPacket(toBuffer(msg), getName()).getThis()); + } + + public void reply(MSG msg, CustomPayloadEvent.Context context) { + send(msg, context.getConnection()); + } + + @FunctionalInterface + public static interface VersionTest { + public static final VersionTest ACCEPT_MISSING = (status, version) -> status == Status.MISSING; + public static final VersionTest ACCEPT_VANILLA = (status, version) -> status == Status.VANILLA; + public static VersionTest exact(int version) { + return (status, remoteVersion) -> status == Status.PRESENT && version == remoteVersion; + } + + public enum Status { + /** + * This value is used when the connection has not specified that it is modded, + * and has not sent a channel list. So we must assume that it is a unmodified vanilla environment. + */ + VANILLA, + /** + * This is used when we are on a modded connection that has sent a channel version + * list, but that list does not contain this channel. + */ + MISSING, + /** + * This is used when we are on a modded connection, the channel version list has been received + * and this channel is in the list. This is the only time that the version parameter of accept + * is valid. + */ + PRESENT; + } + + /** + * Tests is the specified version is compatible with this channel. + * This determines if a we can communicate with a remote end. + * + * The status parameter specifies wither or not the remote knows about + * out channel or not. If the value is {@link Status#MISSING MISSING} + * or {@link Status#VANILLA VANILLA} then the version parameter is meaningless. + * + * If the status is {@link Status#PRESSENT PRESSENT} then the version + * parameter is the version presented by the remote connection. + * + * @return true if we should allow the connection + */ + boolean accepts(Status status, int version); + + + /** + * Returns a instance that represents the logical negation of this + * instance. + */ + default VersionTest negate() { + return (status, version) -> !accepts(status, version); + } + + /** + * Returns a composed instance that represents a short-circuiting logical + * AND of this instance and another. When evaluating the composed + * instance, if this instance is {@code false}, then the {@code other} + * instance is not evaluated. + */ + default VersionTest and(VersionTest other) { + Objects.requireNonNull(other); + return (status, version) -> accepts(status, version) && other.accepts(status, version); + } + + /** + * Returns a composed instance that represents a short-circuiting logical + * OR of this instance and another. When evaluating the composed + * instance, if this instance is {@code true}, then the {@code other} + * instance is not evaluated. + */ + default VersionTest or(VersionTest other) { + Objects.requireNonNull(other); + return (status, version) -> accepts(status, version) || other.accepts(status, version); + } + } +} diff --git a/src/main/java/net/minecraftforge/network/ChannelBuilder.java b/src/main/java/net/minecraftforge/network/ChannelBuilder.java new file mode 100644 index 0000000000..768df10af5 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/ChannelBuilder.java @@ -0,0 +1,216 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; + +import io.netty.util.AttributeKey; +import net.minecraft.network.Connection; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.network.Channel.VersionTest; + +/** + * Builder for constructing impl channels using a builder style API. + */ +public class ChannelBuilder { + private final ResourceLocation name; + private int networkProtocolVersion = 0; + private Channel.VersionTest clientAcceptedVersions; + private Channel.VersionTest serverAcceptedVersions; + private Map, Function> attributes = new HashMap<>(); + private Consumer connectionHandler; + + /** + * Creates a new channel builder, The name of the channel must be unique. + * @param channelName The name of the channel + */ + public static ChannelBuilder named(String channelName) { + return named(new ResourceLocation(channelName)); + } + + /** + * Creates a new channel builder, The name of the channel must be unique. + * @param channelName The name of the channel + */ + public static ChannelBuilder named(ResourceLocation channelName) { + return new ChannelBuilder(channelName); + } + + private ChannelBuilder(ResourceLocation name) { + this.name = name; + } + + /** + * The impl protocol version for this channel. This will be gathered during login and sent to + * the remote partner, where it will be tested with against the relevant predicate. + *
+ * Defaults to 0 + * + * @see #serverAcceptedVersions(Predicate) + * @see #clientAcceptedVersions(Predicate) + * + * @throws IllegalArgumentException if version is < 0 + * + */ + public ChannelBuilder networkProtocolVersion(int version) { + if (version < 0) + throw new IllegalArgumentException("Invalid network protocol: " + version); + this.networkProtocolVersion = version; + return this; + } + + /** + * A predicate run on both sides, with the {@link #networkProtocolVersion(int)} from + * the server, the channel on the remote side. + *
+ * Defaults to only accepting current version and requiring it to be present. + * + * @param test A predicate for testing + * @see VersionTest#accepts(VersionTest.Status, int) + */ + public ChannelBuilder acceptedVersions(VersionTest test) { + return clientAcceptedVersions(test).serverAcceptedVersions(test); + } + + /** + * A predicate run on the client, with the {@link #networkProtocolVersion(int)} from + * the server, the channel on the remote side. + *
+ * Defaults to only accepting current version. + * + * @param test A predicate for testing + * @see VersionTest#accepts(VersionTest.Status, int) + */ + public ChannelBuilder clientAcceptedVersions(VersionTest test) { + this.clientAcceptedVersions = test; + return this; + } + + /** + * A predicate run on the server, with the {@link #networkProtocolVersion(int)} from + * the server, the channel on the remote side. + *
+ * Defaults to only accepting current version. + * + * @param test A predicate for testing + * @see VersionTest#accepts(VersionTest.Status, int) + */ + public ChannelBuilder serverAcceptedVersions(VersionTest test) { + this.serverAcceptedVersions = test; + return this; + } + + /** + * Allows a client to connect to a server that is missing this channel. + * And allows a server to accept a client missing this channel. + * + * This includes vanilla connections. + */ + public ChannelBuilder optional() { + return optionalServer().optionalClient(); + } + + /** + * Allows a client to connect to a server that is missing this channel. + */ + public ChannelBuilder optionalServer() { + return clientAcceptedVersions(VersionTest.ACCEPT_VANILLA.or(VersionTest.ACCEPT_MISSING.or(this.getClientAcceptedVersions()))); + } + + /** + * Tells the server to accept clients that are missing this channel. + */ + public ChannelBuilder optionalClient() { + return serverAcceptedVersions(VersionTest.ACCEPT_VANILLA.or(VersionTest.ACCEPT_MISSING.or(this.getServerAcceptedVersions()))); + } + + /** + * Registers a AttributeKey to be filled when a new connection is created. + * This is meant as a simple way to attach data on a per-connection bases. + * + * @param key The key to assign + * @param factory A factory that creates a new instance of the context data + */ + public ChannelBuilder attribute(AttributeKey key, Supplier factory) { + return this.attribute(key, con -> factory.get()); + } + + /** + * Registers a AttributeKey to be filled when a new connection is created. + * This is meant as a simple way to attach data on a per-connection bases. + * + * @param key The key to assign + * @param factory A factory that creates a new instance of the context data + */ + public ChannelBuilder attribute(AttributeKey key, Function factory) { + this.attributes.put(key, factory); + return this; + } + + + /** + * Registers a function that will be called when a new connection is established. + * This is meant to allow you to do basic configuration and add context objects. + * This is equivalent to the {@link net.minecraftforge.event.network.ConnectionStartEvent ConnectionStartEvent} + */ + public ChannelBuilder connectionHandler(Consumer handler) { + this.connectionHandler = handler; + return this; + } + + /** + * Create the impl instance + * @return the {@link NetworkInstance} + */ + private NetworkInstance createNetworkInstance() { + if (NetworkRegistry.lock) { + NetworkRegistry.LOGGER.error(NetworkRegistry.NETREGISTRY, "Attempted to register channel {} even though registry phase is over", name); + throw new IllegalArgumentException("Registration of impl channels is locked"); + } + if (NetworkRegistry.instances.containsKey(name)) { + NetworkRegistry.LOGGER.error(NetworkRegistry.NETREGISTRY, "NetworkDirection channel {} already registered.", name); + throw new IllegalArgumentException("NetworkDirection Channel {"+ name +"} already registered"); + } + + var networkInstance = new NetworkInstance(name, networkProtocolVersion, + getClientAcceptedVersions(), getServerAcceptedVersions(), + attributes, connectionHandler + ); + NetworkRegistry.instances.put(name, networkInstance); + return networkInstance; + + } + + private VersionTest getClientAcceptedVersions() { + return this.clientAcceptedVersions == null ? VersionTest.exact(this.networkProtocolVersion) : this.clientAcceptedVersions; + } + + private VersionTest getServerAcceptedVersions() { + return this.serverAcceptedVersions == null ? VersionTest.exact(this.networkProtocolVersion) : this.serverAcceptedVersions; + } + + /** + * Build a new {@link SimpleChannel} with this builder's configuration. + * + * @return A new {@link SimpleChannel} + */ + public SimpleChannel simpleChannel() { + return new SimpleChannel(createNetworkInstance()); + } + + /** + * Build a new {@link EventNetworkChannel} with this builder's configuration. + * @return A new {@link EventNetworkChannel} + */ + public EventNetworkChannel eventNetworkChannel() { + return new EventNetworkChannel(createNetworkInstance()); + } +} \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/network/ChannelListManager.java b/src/main/java/net/minecraftforge/network/ChannelListManager.java new file mode 100644 index 0000000000..5d6843619c --- /dev/null +++ b/src/main/java/net/minecraftforge/network/ChannelListManager.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network; + +import com.mojang.logging.LogUtils; +import io.netty.buffer.Unpooled; +import net.minecraft.ResourceLocationException; +import net.minecraft.network.Connection; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.event.ForgeEventFactory; +import net.minecraftforge.event.network.ChannelRegistrationChangeEvent; +import net.minecraftforge.event.network.CustomPayloadEvent; + +import org.jetbrains.annotations.ApiStatus; +import org.slf4j.Logger; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; + +@ApiStatus.Internal // TODO: Decide what I want to have public, Right now it should just be add/remove channels. +public class ChannelListManager { + private static final Logger LOGGER = LogUtils.getLogger(); + static final EventNetworkChannel REGISTER = ChannelBuilder + .named("minecraft:register") + .optional() + .eventNetworkChannel() + .addListener(ChannelListManager::registerListener); + static final EventNetworkChannel UNREGISTER = ChannelBuilder + .named("minecraft:unregister") + .optional() + .eventNetworkChannel() + .addListener(ChannelListManager::unregisterListener); + + private static void registerListener(CustomPayloadEvent evt) { + var ctx = evt.getSource(); + updateFrom(ctx, evt.getPayload(), ChannelRegistrationChangeEvent.Type.REGISTER); + ctx.setPacketHandled(true); + } + + private static void unregisterListener(CustomPayloadEvent evt) { + var ctx = evt.getSource(); + updateFrom(ctx, evt.getPayload(), ChannelRegistrationChangeEvent.Type.UNREGISTER); + ctx.setPacketHandled(true); + } + + public static void addChannels(Connection connection) { + addChannels(connection, NetworkRegistry.buildChannelVersions().keySet().stream() + .filter(rl -> !"minecraft".equals(rl.getNamespace())) + .toList() + ); + } + + public static void addChannels(Connection connection, ResourceLocation... channels) { + addChannels(connection, Arrays.asList(channels)); + } + + public static void addChannels(Connection connection, Collection channels) { + var list = NetworkContext.get(connection); + var toSend = new HashSet(); + for (var channel : channels) { + if (list.sentChannels.add(channel)) + toSend.add(channel); + } + sendChannels(REGISTER, connection, toSend); + } + + public static void removeChannels(Connection connection, ResourceLocation... channels) { + removeChannels(connection, Arrays.asList(channels)); + } + + public static void removeChannels(Connection connection, Collection channels) { + var list = NetworkContext.get(connection); + var toSend = new HashSet(); + for (var channel : channels) { + if (list.sentChannels.remove(channel)) + toSend.add(channel); + } + sendChannels(UNREGISTER, connection, toSend); + } + + private static void sendChannels(EventNetworkChannel channel, Connection connection, Collection channels) { + var buf = new FriendlyByteBuf(Unpooled.buffer()); + for (var c : channels) { + buf.writeBytes(c.toString().getBytes(StandardCharsets.UTF_8)); + buf.writeByte(0); + } + + channel.send(buf, connection); + } + + private static void updateFrom(CustomPayloadEvent.Context source, FriendlyByteBuf buffer, final ChannelRegistrationChangeEvent.Type changeType) { + byte[] data = new byte[Math.max(buffer.readableBytes(), 0)]; + buffer.readBytes(data); + var changed = new HashSet(); + + int last = 0; + for (int cur = 0; cur < data.length; cur++) { + if (data[cur] == '\0') { + var channel = new String(data, last, cur - last, StandardCharsets.UTF_8); + try { + changed.add(new ResourceLocation(channel)); + } catch (ResourceLocationException ex) { + // Vanilla packet deserializers now force this to be a resource location, so we should never get this, but just in case. + LOGGER.warn("Invalid channel name received: {}. Ignoring", channel); + } + last = cur + 1; + } + } + + ForgeEventFactory.onChannelRegistrationChange(source.getConnection(), changeType, changed); + + var list = NetworkContext.get(source.getConnection()); + for (var channel : changed) { + boolean fire = changeType == ChannelRegistrationChangeEvent.Type.UNREGISTER + ? list.remoteChannels.remove(channel) + : list.remoteChannels.add(channel); + + if (fire) { + var target = NetworkRegistry.findTarget(channel); + if (target != null) + target.registrationChange(changeType == ChannelRegistrationChangeEvent.Type.REGISTER); + } + } + } +} diff --git a/src/main/java/net/minecraftforge/network/ConfigSync.java b/src/main/java/net/minecraftforge/network/ConfigSync.java deleted file mode 100644 index 0471acbabf..0000000000 --- a/src/main/java/net/minecraftforge/network/ConfigSync.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.network; - -import net.minecraft.client.Minecraft; -import net.minecraftforge.fml.config.ConfigTracker; -import net.minecraftforge.fml.config.ModConfig; -import org.apache.commons.lang3.tuple.Pair; - -import java.io.IOException; -import java.nio.file.Files; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.Supplier; -import java.util.stream.Collectors; - -public class ConfigSync { - public static final ConfigSync INSTANCE = new ConfigSync(ConfigTracker.INSTANCE); - private final ConfigTracker tracker; - - private ConfigSync(final ConfigTracker tracker) { - this.tracker = tracker; - } - - public List> syncConfigs(boolean isLocal) { - final Map configData = tracker.configSets().get(ModConfig.Type.SERVER).stream().collect(Collectors.toMap(ModConfig::getFileName, mc -> { - try { - return Files.readAllBytes(mc.getFullPath()); - } catch (IOException e) { - throw new RuntimeException(e); - } - })); - return configData.entrySet().stream().map(e->Pair.of("Config "+e.getKey(), new HandshakeMessages.S2CConfigData(e.getKey(), e.getValue()))).collect(Collectors.toList()); - } - - public void receiveSyncedConfig(final HandshakeMessages.S2CConfigData s2CConfigData, final Supplier contextSupplier) { - if (!Minecraft.getInstance().isLocalServer()) { - Optional.ofNullable(tracker.fileMap().get(s2CConfigData.getFileName())).ifPresent(mc-> mc.acceptSyncedConfig(s2CConfigData.getBytes())); - } - } -} diff --git a/src/main/java/net/minecraftforge/network/ConnectionData.java b/src/main/java/net/minecraftforge/network/ConnectionData.java deleted file mode 100644 index 2a44df3487..0000000000 --- a/src/main/java/net/minecraftforge/network/ConnectionData.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.network; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Multimap; - -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.fml.ModList; - -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.tuple.Pair; - -public class ConnectionData -{ - private ImmutableMap> modData; - private ImmutableMap channels; - - /* package private */ ConnectionData(Map> modData, Map channels) - { - this.modData = ImmutableMap.copyOf(modData); - this.channels = ImmutableMap.copyOf(channels); - } - - /** - * Returns the list of mods present in the remote. - * WARNING: This list is not authoritative. - * A mod missing from the list does not mean the mod isn't there, - * and similarly a mod present in the list does not mean it is there. - * People using hacked clients WILL hack the mod lists to make them look correct. - * Do not use this as an anti-cheat feature! - * - * @return An immutable list of MODIDs - */ - public ImmutableList getModList() - { - return modData.keySet().asList(); - } - - /** - * Returns a map of mods and respective mod names and versions present in the remote. - * WARNING: This list is not authoritative. - * A mod missing from the list does not mean the mod isn't there, - * and similarly a mod present in the list does not mean it is there. - * People using hacked clients WILL hack the mod lists to make them look correct. - * Do not use this as an anti-cheat feature! - * - * @return An immutable map of MODIDs and their respective mod versions - */ - public ImmutableMap> getModData() - { - return modData; - } - - /** - * Returns the list of impl channels present in the remote. - * WARNING: This list is not authoritative. - * A channel missing from the list does not mean the remote won't accept packets with that channel ID, - * and similarly a channel present in the list does not mean the remote won't ignore it. - * People using hacked clients WILL hack the channel list to make it look correct. - * Do not use this as an anti-cheat feature! - * - * @return An immutable map of channel IDs and their respective protocol versions. - */ - public ImmutableMap getChannels() - { - return channels; - } - - /** - * A class for holding the mod mismatch data of a failed handshake. - * Contains a list of mismatched channels, the channels present on the side the handshake failed on, the mods with mismatching registries (if available) and the information of whether the mismatching data's origin is the server. - * @param mismatchedModData The data of the mismatched or missing mods/channels, consisting of the mod or channel id and the version of the respective mod. If the mod version is absent, the entry is assumed to be missing on either side. If it is present, the entry gets treated as a mismatch. - * @param presentModData The data of the channels/mods from the side the mismatch data doesn't originate from, consisting of the mod or channel id and the name and version of the respective mod. This data is useful for a proper comparison against the mismatched channel data. The data is stored like this: [id -> [modName, modVersion]] - * @param mismatchedDataFromServer Whether the mismatched data originates from the server. Note, that the mismatched data origin does not tell us if the actual mismatch check happened on the client or the server. - */ - public record ModMismatchData(Map mismatchedModData, Map> presentModData, boolean mismatchedDataFromServer) - { - /** - * Creates a ModMismatchData instance from given channel mismatch data, which is processed side-aware depending on the value of mismatchedDataFromServer - * @param mismatchedChannels The list of channels that were listed as mismatches, either because they are missing on one side or because their versions mismatched - * @param connectionData The connection data instance responsible for collecting the server mod data. - * @param mismatchedDataFromServer Whether the mismatched data originates from the server. - */ - public static ModMismatchData channel(Map mismatchedChannels, ConnectionData connectionData, boolean mismatchedDataFromServer) - { - Map mismatchedChannelData = enhanceWithModVersion(mismatchedChannels, connectionData, mismatchedDataFromServer); - Map> presentChannelData = getPresentChannelData(mismatchedChannels.keySet(), connectionData, mismatchedDataFromServer); - - return new ModMismatchData(mismatchedChannelData, presentChannelData, mismatchedDataFromServer); - } - - /** - * Creates a ModMismatchData instance from given mismatched registry entries. In this case, the mismatched data is always treated as originating from the client because registry entries missing on the server never cause the handshake to fail. - * @param mismatchedRegistryData The list of mismatched registries and the associated mismatched registry entries. The data is stored like this: "registryNamespace:registryPath" -> "entryNamespace:entryPath" - * @param connectionData The connection data instance responsible for collecting the server mod data. - */ - public static ModMismatchData registry(Multimap mismatchedRegistryData, ConnectionData connectionData) - { - List mismatchedRegistryMods = mismatchedRegistryData.values().stream().map(ResourceLocation::getNamespace).distinct().map(id -> new ResourceLocation(id, "")).toList(); - Map mismatchedRegistryModData = mismatchedRegistryMods.stream().map(id -> ModList.get().getModContainerById(id.getNamespace()).map(modContainer -> Pair.of(id, modContainer.getModInfo().getVersion().toString())).orElse(Pair.of(id, NetworkRegistry.ABSENT.version()))).collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); - Map> presentModData = getServerSidePresentModData(mismatchedRegistryModData.keySet(), connectionData); - - return new ModMismatchData(mismatchedRegistryModData, presentModData, false); - } - - /** - * @return true if this ModMismatchData instance contains channel or registry mismatches - */ - public boolean containsMismatches() - { - return mismatchedModData != null && !mismatchedModData.isEmpty(); - } - - /** - * Enhances a map of mismatched channels with the corresponding mod version. - * @param mismatchedChannels The original mismatched channel list, containing the id and version of the mismatched channel. - * @param connectionData The connection data instance responsible for collecting the server mod data. - * @param mismatchedDataFromServer Whether the mismatched data originates from the server. The given mismatched channel list gets processed side-aware depending on the value of this parameter. - * @return A map containing the id of the channel and the version of the corresponding mod, or NetworkRegistry.ABSENT if the channel is missing. - */ - private static Map enhanceWithModVersion(Map mismatchedChannels, ConnectionData connectionData, boolean mismatchedDataFromServer) - { - Map mismatchedModVersions; - - if (mismatchedDataFromServer) //enhance with data from the server - { - mismatchedModVersions = connectionData != null ? connectionData.getModData().entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> e.getValue().getRight())) : Map.of(); - } - else //enhance with data from the client - { - mismatchedModVersions = ModList.get().getMods().stream().map(info -> Pair.of(info.getModId(), info.getVersion().toString())).collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); - } - return mismatchedChannels.keySet().stream().map(channel -> Pair.of(channel, mismatchedChannels.get(channel).equals(NetworkRegistry.ABSENT.version()) ? NetworkRegistry.ABSENT.version() : mismatchedModVersions.getOrDefault(channel.getNamespace(), NetworkRegistry.ABSENT.version()))).collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); - } - - - /** - * Queries the channel data from the side the mismatched data isn't from, in order to provide a map of all the present channels for a proper comparison against the mismatched channel data. - * @param mismatchedChannelsFilter A filter that gets used in order to only query the data of mismatched mods, because that's the only one we need for a proper comparison between mismatched and present mods. - * @param connectionData The connection data instance responsible for collecting the server mod data. - * @param mismatchedDataFromServer Whether the mismatched data originates from the server. The data gets queried from the side that the mismatch data does not originate from. - * @return The data of all relevant present channels, containing the channel id and the name and version of the corresponding mod. - */ - private static Map> getPresentChannelData(Set mismatchedChannelsFilter, ConnectionData connectionData, boolean mismatchedDataFromServer) - { - Map channelData; - - if (mismatchedDataFromServer) //mismatch data comes from the server, use client channel data - { - channelData = NetworkRegistry.buildChannelVersions(); - } - else //mismatch data comes from the client, use server channel data - { - channelData = connectionData != null ? connectionData.getChannels() : Map.of(); - } - return channelData.keySet().stream().filter(mismatchedChannelsFilter::contains).map(id -> getPresentModDataFromChannel(id, connectionData, mismatchedDataFromServer)).collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); - } - - /** - * Queries the mod data from a given channel id from the side the mismatched data isn't from. - * @param channel The id of the channel the mod data should be queried for. - * @param connectionData The connection data instance responsible for collecting the server mod data. - * @param mismatchedDataFromServer Whether the mismatched data originates from the server. The data gets queried from the side that the mismatch data does not originate from. - * @return The mod data corresponding to the channel id, containing the channel id and the name and version of the corresponding mod. - */ - private static Pair> getPresentModDataFromChannel(ResourceLocation channel, ConnectionData connectionData, boolean mismatchedDataFromServer) - { - if (mismatchedDataFromServer) - { - return ModList.get().getModContainerById(channel.getNamespace()).map(modContainer -> Pair.of(channel, Pair.of(modContainer.getModInfo().getDisplayName(), modContainer.getModInfo().getVersion().toString()))).orElse(Pair.of(channel, Pair.of(channel.getNamespace(), ""))); - } - else - { - Map> modData = connectionData != null ? connectionData.getModData() : Map.of(); - Pair modDataFromChannel = modData.getOrDefault(channel.getNamespace(), Pair.of(channel.getNamespace(), "")); - return Pair.of(channel, modDataFromChannel.getLeft().isEmpty() ? Pair.of(channel.getNamespace(), modDataFromChannel.getRight()) : modDataFromChannel); - } - } - - /** - * Queries the mod data from the server side. Useful in case of a registry mismatch, which always gets detected on the client. - * @param mismatchedModsFilter A filter that gets used in order to only query the data of mismatched mods, because that's the only one we need for a proper comparison between mismatched and present mods. - * @param connectionData The connection data instance responsible for collecting the server mod data. - * @return The mod data from the server, containing the channel id and the name and version of the corresponding mod. - */ - private static Map> getServerSidePresentModData(Set mismatchedModsFilter, ConnectionData connectionData) - { - Map> serverModData = connectionData != null ? connectionData.getModData() : Map.of(); - Set modIdFilter = mismatchedModsFilter.stream().map(ResourceLocation::getNamespace).collect(Collectors.toSet()); - return serverModData.entrySet().stream().filter(e -> modIdFilter.contains(e.getKey())).collect(Collectors.toMap(e -> new ResourceLocation(e.getKey(), ""), Entry::getValue)); - } - } -} diff --git a/src/main/java/net/minecraftforge/network/ConnectionType.java b/src/main/java/net/minecraftforge/network/ConnectionType.java index 32a2c995ff..0c1fe25bde 100644 --- a/src/main/java/net/minecraftforge/network/ConnectionType.java +++ b/src/main/java/net/minecraftforge/network/ConnectionType.java @@ -5,30 +5,7 @@ package net.minecraftforge.network; -import java.util.function.Function; - -import org.jetbrains.annotations.ApiStatus; - -@SuppressWarnings("unused") public enum ConnectionType { - MODDED(s -> Integer.valueOf(s.substring(NetworkConstants.FMLNETMARKER.length()))), - VANILLA(s ->0); - - private final Function versionExtractor; - - ConnectionType(Function versionExtractor) { - this.versionExtractor = versionExtractor; - } - - public static ConnectionType forVersionFlag(String vers) { - return vers.startsWith(NetworkConstants.FMLNETMARKER) ? MODDED : VANILLA; - } - - public int getFMLVersionNumber(final String fmlVersion) { - return versionExtractor.apply(fmlVersion); - } - - public boolean isVanilla() { - return this == VANILLA; - } + MODDED, + VANILLA; } diff --git a/src/main/java/net/minecraftforge/network/DualStackUtils.java b/src/main/java/net/minecraftforge/network/DualStackUtils.java index e9c867f60d..22f292e80c 100644 --- a/src/main/java/net/minecraftforge/network/DualStackUtils.java +++ b/src/main/java/net/minecraftforge/network/DualStackUtils.java @@ -16,18 +16,13 @@ import org.slf4j.Logger; import javax.annotation.Nullable; import java.net.Inet4Address; -import net.minecraftforge.common.ForgeConfig; - -import javax.annotation.Nullable; import java.net.SocketAddress; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; -import java.util.Optional; -public class DualStackUtils -{ +public class DualStackUtils { private static final String INITIAL_PREFER_IPv4_STACK = System.getProperty("java.net.preferIPv4Stack") == null ? "false" : System.getProperty("java.net.preferIPv4Stack"); private static final String INITIAL_PREFER_IPv6_ADDRESSES = System.getProperty("java.net.preferIPv6Addresses") == null ? "false" : System.getProperty("java.net.preferIPv6Addresses"); @@ -48,12 +43,10 @@ public class DualStackUtils * @param hostAddress The address you want to check * @return true if IPv6, false if IPv4 */ - public static boolean checkIPv6(final String hostAddress) - { - final Optional hostAddr = - ServerNameResolver.DEFAULT - .resolveAddress(ServerAddress.parseString(hostAddress)) - .map(ResolvedServerAddress::asInetSocketAddress); + public static boolean checkIPv6(final String hostAddress) { + var hostAddr = ServerNameResolver.DEFAULT + .resolveAddress(ServerAddress.parseString(hostAddress)) + .map(ResolvedServerAddress::asInetSocketAddress); if (hostAddr.isPresent()) return checkIPv6(hostAddr.get().getAddress()); else return false; @@ -65,57 +58,45 @@ public class DualStackUtils * @param inetAddress The address you want to check * @return true if IPv6, false if IPv4 */ - public static boolean checkIPv6(final InetAddress inetAddress) - { + public static boolean checkIPv6(final InetAddress inetAddress) { // only log debug messages if we're not in the server pinger thread, as otherwise it's unclear which IP // corresponds to which server as soon as you have more than one server in the multiplayer server list - final String currentThreadName = Thread.currentThread().getName(); - final boolean shouldLogDebug = !currentThreadName.contains("Server Pinger #"); + boolean thread = !Thread.currentThread().getName().contains("Server Pinger #"); - if (inetAddress instanceof Inet6Address addr) - { - if (shouldLogDebug) - LOGGER.debug("Detected IPv6 address: \"" + addr.getHostAddress() + "\""); + if (inetAddress instanceof Inet6Address addr) { + debug(thread, "Detected IPv6 address: \"" + addr.getHostAddress() + "\""); System.setProperty("java.net.preferIPv4Stack", "false"); System.setProperty("java.net.preferIPv6Addresses", "true"); return true; - } - else if (inetAddress instanceof Inet4Address addr) - { - if (shouldLogDebug) - LOGGER.debug("Detected IPv4 address: \"" + addr.getHostAddress() + "\""); + } else if (inetAddress instanceof Inet4Address addr) { + debug(thread, "Detected IPv4 address: \"" + addr.getHostAddress() + "\""); System.setProperty("java.net.preferIPv4Stack", "true"); System.setProperty("java.net.preferIPv6Addresses", "false"); return false; - } - else - { - if (shouldLogDebug) { - final String addr = inetAddress == null ? "null" : "\"" + inetAddress.getHostAddress() + "\""; - LOGGER.debug("Unable to determine IP version of address: " + addr); - } - - if (INITIAL_PREFER_IPv4_STACK.equalsIgnoreCase("false") && INITIAL_PREFER_IPv6_ADDRESSES.equalsIgnoreCase("true")) - { - if (shouldLogDebug) - LOGGER.debug("Assuming IPv6 as Java was explicitly told to prefer it..."); + } else { + debug(thread, "Unable to determine IP version of address: " + (inetAddress == null ? "null" : "\"" + inetAddress.getHostAddress() + "\"")); + if (INITIAL_PREFER_IPv4_STACK.equalsIgnoreCase("false") && INITIAL_PREFER_IPv6_ADDRESSES.equalsIgnoreCase("true")) { + debug(thread, "Assuming IPv6 as Java was explicitly told to prefer it..."); System.setProperty("java.net.preferIPv4Stack", "false"); System.setProperty("java.net.preferIPv6Addresses", "true"); return true; } - if (shouldLogDebug) - LOGGER.debug("Assuming IPv4..."); - + debug(thread, "Assuming IPv4..."); System.setProperty("java.net.preferIPv4Stack", "true"); System.setProperty("java.net.preferIPv6Addresses", "false"); return false; } } + private static void debug(boolean shouldLogDebug, String message) { + if (shouldLogDebug) + LOGGER.debug(message); + } + /** * Get the device's local IP address, taking into account scenarios where the client's network adapter * supports IPv6 and has it enabled but the router's LAN does not. @@ -123,17 +104,13 @@ public class DualStackUtils * @return the client's local IP address or {@code null} if unable to determine it */ @Nullable - public static InetAddress getLocalAddress() - { + public static InetAddress getLocalAddress() { final InetAddress localAddr = new InetSocketAddress(HttpUtil.getAvailablePort()).getAddress(); if (localAddr.isAnyLocalAddress()) return localAddr; - try - { + try { return InetAddress.getByName("localhost"); - } - catch (final UnknownHostException e) - { + } catch (final UnknownHostException e) { return null; } } @@ -143,8 +120,7 @@ public class DualStackUtils * @return The multicast group to use for LAN discovery - IPv6 if available, IPv4 otherwise. */ public static String getMulticastGroup() { - if (checkIPv6(getLocalAddress())) return "FF75:230::60"; - else return "224.0.2.60"; + return checkIPv6(getLocalAddress()) ? "FF75:230::60" : "224.0.2.60"; } /** @@ -162,9 +138,9 @@ public class DualStackUtils public static String getAddressString(final SocketAddress address) { if (address instanceof final InetSocketAddress inetAddress) { String formatted; - if (inetAddress.isUnresolved()) { + if (inetAddress.isUnresolved()) formatted = inetAddress.getHostName() + "/"; - } else { + else { formatted = InetAddresses.toAddrString(inetAddress.getAddress()); if (inetAddress.getAddress() instanceof Inet6Address) formatted = '[' + formatted + ']'; diff --git a/src/main/java/net/minecraftforge/network/EventNetworkChannel.java b/src/main/java/net/minecraftforge/network/EventNetworkChannel.java new file mode 100644 index 0000000000..e9bdcd9bec --- /dev/null +++ b/src/main/java/net/minecraftforge/network/EventNetworkChannel.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.event.network.CustomPayloadEvent; + +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.function.Supplier; + +/** + * An event-bus like object on which {@link CustomPayloadEvent}s are posted. + * + * These events are fired from 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. + * + * @see ChannelBuilder#newEventChannel(ResourceLocation, Supplier, Predicate, Predicate) + */ +public class EventNetworkChannel extends Channel { + EventNetworkChannel(NetworkInstance instance) { + super(instance); + } + + public EventNetworkChannel addListener(Consumer eventListener) { + instance.addListener(eventListener); + return this; + } + + public EventNetworkChannel registerObject(Object object) { + instance.registerObject(object); + return this; + } + + public void unregisterObject(Object object) { + instance.unregisterObject(object); + } + + @Override + protected FriendlyByteBuf toBuffer(FriendlyByteBuf message) { + return message; + } +} diff --git a/src/main/java/net/minecraftforge/network/ForgePacketHandler.java b/src/main/java/net/minecraftforge/network/ForgePacketHandler.java new file mode 100644 index 0000000000..6263fd21fd --- /dev/null +++ b/src/main/java/net/minecraftforge/network/ForgePacketHandler.java @@ -0,0 +1,261 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network; + +import net.minecraft.network.Connection; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.common.ForgeHooks; +import net.minecraftforge.common.util.LogMessageAdapter; +import net.minecraftforge.event.network.CustomPayloadEvent; +import net.minecraftforge.fml.ModList; +import net.minecraftforge.fml.config.ConfigTracker; +import net.minecraftforge.network.NetworkContext.NetworkMismatchData; +import net.minecraftforge.network.packets.Acknowledge; +import net.minecraftforge.network.packets.ChannelVersions; +import net.minecraftforge.network.packets.LoginWrapper; +import net.minecraftforge.network.packets.ModVersions; +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.tasks.ChannelVersionsTask; +import net.minecraftforge.network.tasks.ModVersionsTask; +import net.minecraftforge.registries.DataPackRegistriesHooks; +import net.minecraftforge.registries.ForgeRegistry; +import net.minecraftforge.registries.GameData; + +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 it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiConsumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * TODO: Gathered Payloads + *

During client to server initiation, on the server, the {@link CustomPayloadEvent.GatherLoginPayloadsEvent} is fired, + * which solicits all registered channels at the {@link NetworkRegistry} for any + * {@link NetworkRegistry.LoginPayload} they wish to supply. + */ +public class ForgePacketHandler { + private static final Logger LOGGER = LogManager.getLogger(); + private static final Marker MARKER = MarkerManager.getMarker("FORGE_PACKET_HANDLER"); + + private Set registriesToReceive; + private Map registrySnapshots = new HashMap<>(); + private int nextAckId = 0; + private Int2ObjectMap> pendingAcknowledgments = new Int2ObjectOpenHashMap<>(); + + ForgePacketHandler(Connection connection) { + } + + public int expectAck(BiConsumer consumer) { + int id = this.nextAckId++; + this.pendingAcknowledgments.put(id, consumer); + return id; + } + + void handleLoginWrapper(LoginWrapper msg, CustomPayloadEvent.Context ctx) { + ForgeHooks.onCustomPayload(new CustomPayloadEvent(msg.channel(), msg.data(), ctx, -1)); + } + + void handleClientAck(Acknowledge msg, CustomPayloadEvent.Context ctx) { + ctx.setPacketHandled(true); + var consumer = this.pendingAcknowledgments.remove(msg.token()); + if (consumer != null) { + LOGGER.debug(MARKER, "Received acknowledgement {} from client", msg.token()); + consumer.accept(msg, ctx); + } else { + LOGGER.error(MARKER, "Received unknown acknowledgement {} from client", msg.token()); + ctx.getConnection().disconnect(Component.literal("Illegal Acknowledge packet received, unknown token: " + Integer.toHexString(msg.token()))); + } + } + + void handleModVersions(ModVersions list, CustomPayloadEvent.Context ctx) { + ctx.setPacketHandled(true); + LOGGER.debug(MARKER, "Received {} connection with modlist [{}]", ctx.isClientSide() ? "server" : "client", list.mods().keySet().stream().sorted().collect(Collectors.joining(", "))); + var nctx = NetworkContext.get(ctx.getConnection()); + nctx.modList.clear(); + nctx.modList.putAll(list.mods()); + + if (ctx.isClientSide()) { + NetworkInitialization.PLAY.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 + * Or make the marker in Intention packet a generic 'we are modded, negotiate what type' identifier? + */ + LOGGER.debug(MARKER, "Accepted server connection"); + nctx.setConnectionType(ConnectionType.MODDED); + } else + nctx.finishTask(ModVersionsTask.TYPE); + } + + void handleChannelVersions(ChannelVersions list, CustomPayloadEvent.Context ctx) { + ctx.setPacketHandled(true); + LOGGER.debug(MARKER, "Received {} connection with channels [{}]", ctx.isClientSide() ? "server" : "client", list.channels().keySet().stream().map(ResourceLocation::toString).sorted().collect(Collectors.joining(", "))); + var nctx = NetworkContext.get(ctx.getConnection()); + nctx.channelList.clear(); + nctx.channelList.putAll(list.channels()); + + var invalid = NetworkRegistry.validateChannels(list.channels(), ctx.isServerSide()); + if (invalid != null) { + LOGGER.error(MARKER, "Terminating connection with {}, mismatched channel list", ctx.isClientSide() ? "server" : "client"); + nctx.mismatchData = new NetworkMismatchData(invalid.mismatched(), invalid.missing(), invalid.fromServer(), nctx.getModList()); + + if (ctx.isServerSide()) + NetworkInitialization.PLAY.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()); + else + nctx.finishTask(ChannelVersionsTask.TYPE); + + } + + void handleModMismatchData(MismatchData data, CustomPayloadEvent.Context ctx) { + ctx.setPacketHandled(true); + var nctx = NetworkContext.get(ctx.getConnection()); + nctx.mismatchData = new NetworkMismatchData(data.mismatched(), data.missing(), true, nctx.getModList()); + LOGGER.error(MARKER, "Channels [{}] rejected their client side version number", + Stream.concat(data.missing().stream(), data.mismatched().keySet().stream()).map(Object::toString).collect(Collectors.joining(", "))); + LOGGER.error(MARKER, "Terminating connection with server, mismatched mod list"); + ctx.getConnection().disconnect(Component.literal("Connection closed - mismatched mod channel list")); + } + + void handleRegistryList(RegistryList list, CustomPayloadEvent.Context ctx) { + ctx.setPacketHandled(true); + + // Validate synced custom datapack registries, client cannot be missing any present on the server. + List missing = new ArrayList<>(); + var clientDataPackRegistries = DataPackRegistriesHooks.getSyncedCustomRegistries(); + for (var key : list.datapacks()) { + if (!clientDataPackRegistries.contains(key)) { + LOGGER.error(MARKER, "Missing required datapack registry: {}", key.location()); + missing.add(key.location().toString()); + } + } + + if (!missing.isEmpty()) { + ctx.getConnection().disconnect(Component.translatable("fml.menu.multiplayer.missingdatapackregistries", String.join(", ", missing))); + return; + } + + NetworkInitialization.PLAY.reply(new Acknowledge(list.token()), ctx); + + this.registriesToReceive = new HashSet<>(list.normal()); + this.registrySnapshots.clear(); + LOGGER.debug(MARKER, "Expecting {} registries: {}", this.registriesToReceive.size(), this.registriesToReceive.stream().map(Object::toString).collect(Collectors.joining(", "))); + } + + void handleRegistryData(RegistryData msg, CustomPayloadEvent.Context ctx) { + ctx.setPacketHandled(true); + + LOGGER.debug(MARKER,"Received registry data packet for {} token {}", msg.name(), msg.token()); + if (!this.registriesToReceive.remove(msg.name())) { + LOGGER.error(MARKER, "Received unexpected registry data packet for {}", msg.name()); + ctx.getConnection().disconnect(Component.literal("Illegal Registry Data packet received, unexpected regitry: " + msg.name())); + return; + } + this.registrySnapshots.put(msg.name(), msg.data()); + + boolean continueHandshake = true; + if (this.registriesToReceive.isEmpty()) + continueHandshake = handleRegistryLoading(ctx); + + if (!continueHandshake) + LOGGER.error(MARKER, "Connection closed, not continuing handshake"); + else + NetworkInitialization.PLAY.reply(new Acknowledge(msg.token()), ctx); + } + + private boolean handleRegistryLoading(CustomPayloadEvent.Context ctx) { + var nctx = NetworkContext.get(ctx.getConnection()); + // We use a countdown latch to suspend the impl thread pending the client thread processing the registry data + var block = new CountDownLatch(1); + + AtomicReference errorData = new AtomicReference<>(); + ctx.enqueueWork(() -> { + LOGGER.debug(MARKER, "Injecting registry snapshot from server."); + var missingData = GameData.injectSnapshot(registrySnapshots, false, false); + + LOGGER.debug(MARKER, "Snapshot injected."); + if (!missingData.isEmpty()) { + LOGGER.error(MARKER, "Missing registry data for connection:\n{}", LogMessageAdapter.adapt(sb -> + missingData.forEach((k, v) -> sb.append("\t").append(k).append(": ").append(v).append('\n')) + )); + + // The error screen just wants mods, so lets guess based on registry entry namespaces + // TODO: Make this sane... and fully test + var missingMods = missingData.values().stream() + .map(ResourceLocation::getNamespace) + .distinct() + .toList(); + var mismatched = new HashMap(); + var missing = new HashSet(); + for (var id : missingMods) { + var key = new ResourceLocation(id, ""); + var container = ModList.get().getModContainerById(id).get(); + if (container != null) + mismatched.put(key, new NetworkMismatchData.Version(container.getModInfo().getVersion().toString(), "")); + else + missing.add(key); + } + errorData.set(new NetworkMismatchData(mismatched, missing, true, nctx.getModList())); + } + + block.countDown(); + }); + + LOGGER.debug(MARKER, "Waiting for registries to load."); + try { + block.await(); + } catch (InterruptedException e) { + Thread.interrupted(); + } + + var mismatchData = errorData.get(); + if (mismatchData != null) { + LOGGER.error(MARKER, "Failed to load registry, closing connection."); + //Populate the mod mismatch attribute with a new mismatch data instance to indicate that the disconnect happened due to a mod mismatch + nctx.mismatchData = mismatchData; + ctx.getConnection().disconnect(Component.literal("Failed to synchronize registry data from server, closing connection")); + return false; + } + + LOGGER.debug(MARKER, "Registry load complete, continuing handshake."); + return true; + } + + void handleConfigSync(ConfigData msg, CustomPayloadEvent.Context ctx) { + ctx.setPacketHandled(true); + LOGGER.debug(MARKER, "Received config sync from server for {}", msg.name()); + + if (!ctx.getConnection().isMemoryConnection()) { + var cfg = ConfigTracker.INSTANCE.fileMap().get(msg.name()); + if (cfg != null) + cfg.acceptSyncedConfig(msg.data()); + } + } +} diff --git a/src/main/java/net/minecraftforge/network/HandshakeHandler.java b/src/main/java/net/minecraftforge/network/HandshakeHandler.java deleted file mode 100644 index 921632e19e..0000000000 --- a/src/main/java/net/minecraftforge/network/HandshakeHandler.java +++ /dev/null @@ -1,400 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.network; - -import com.google.common.collect.Multimap; -import com.mojang.authlib.GameProfile; - -import net.minecraft.core.Registry; -import net.minecraft.network.Connection; -import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.handshake.ClientIntentionPacket; -import net.minecraft.network.protocol.login.ClientboundCustomQueryPacket; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.network.ServerLoginPacketListenerImpl; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.util.LogMessageAdapter; -import net.minecraftforge.event.entity.player.PlayerNegotiationEvent; -import net.minecraftforge.network.ConnectionData.ModMismatchData; -import net.minecraftforge.network.simple.SimpleChannel; -import net.minecraftforge.registries.DataPackRegistriesHooks; -import net.minecraftforge.registries.ForgeRegistry; -import net.minecraftforge.registries.GameData; -import org.apache.commons.lang3.tuple.Pair; -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 com.google.common.collect.Maps; - -import java.util.*; -import java.util.concurrent.CancellationException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiConsumer; -import java.util.function.Function; -import java.util.function.IntSupplier; -import java.util.function.Supplier; -import java.util.stream.Collectors; - -/** - * Instance responsible for handling the overall FML impl handshake. - * - *

An instance is created during {@link ClientIntentionPacket} handling, and attached - * to the {@link Connection#channel()} via {@link NetworkConstants#FML_HANDSHAKE_HANDLER}. - * - *

The {@link NetworkConstants#handshakeChannel} is a {@link SimpleChannel} with standard messages flowing in both directions. - * - *

The {@link #loginWrapper} transforms these messages into {@link ServerboundCustomQueryPacket} - * and {@link ClientboundCustomQueryPacket} compatible messages, by means of wrapping. - * - *

The handshake is ticked {@code #tickLogin(NetworkManager)} from the {@link ServerLoginPacketListenerImpl#tick()} method, - * utilizing the {@code ServerLoginPacketListenerImpl.State#NEGOTIATING} state, which is otherwise unused in vanilla code. - * - *

During client to server initiation, on the server, the {@link NetworkEvent.GatherLoginPayloadsEvent} is fired, - * which solicits all registered channels at the {@link NetworkRegistry} for any - * {@link NetworkRegistry.LoginPayload} they wish to supply. - * - *

The collected {@link NetworkRegistry.LoginPayload} are sent, one per tick, via - * the {@code FMLLoginWrapper#wrapPacket(ResourceLocation, net.minecraft.impl.FriendlyByteBuf)} mechanism to the incoming client connection. Each - * packet is indexed via {@link ServerboundCustomQueryPacket#getTransactionId()}, which is - * the only mechanism available for tracking request/response pairs. - * - *

Each packet sent from the server should be replied by the client, though not necessarily in sent order. The reply - * should contain the index of the server's packet it is replying to. The {@link LoginWrapper} class handles indexing - * replies correctly automatically. - * - *

Once all packets have been dispatched, we wait for all replies to be received. Once all replies are received, the - * final login phase will commence. - */ -public class HandshakeHandler -{ - static final Marker FMLHSMARKER = MarkerManager.getMarker("FMLHANDSHAKE").setParents(NetworkConstants.NETWORK); - private static final Logger LOGGER = LogManager.getLogger(); - - private static final LoginWrapper loginWrapper = new LoginWrapper(); - - static { - } - - /** - * Create a new handshake instance. Called when connection is first created during the {@link ClientIntentionPacket} - * handling. - * - * @param manager The impl manager for this connection - * @param direction The {@link NetworkDirection} for this connection: {@link NetworkDirection#LOGIN_TO_SERVER} or {@link NetworkDirection#LOGIN_TO_CLIENT} - */ - static void registerHandshake(Connection manager, NetworkDirection direction) { - manager.channel().attr(NetworkConstants.FML_HANDSHAKE_HANDLER).compareAndSet(null, new HandshakeHandler(manager, direction)); - } - - static boolean tickLogin(Connection networkManager) - { - return networkManager.channel().attr(NetworkConstants.FML_HANDSHAKE_HANDLER).get().tickServer(); - } - - private List messageList; - - private List sentMessages = new ArrayList<>(); - - private final NetworkDirection direction; - private final Connection manager; - private int packetPosition; - private Map registrySnapshots; - private Set registriesToReceive; - private Map registryHashes; - private boolean negotiationStarted = false; - private final List> pendingFutures = new ArrayList<>(); - - private HandshakeHandler(Connection networkManager, NetworkDirection side) - { - this.direction = side; - this.manager = networkManager; - if (networkManager.isMemoryConnection()) { - this.messageList = NetworkRegistry.gatherLoginPayloads(this.direction, true); - LOGGER.debug(FMLHSMARKER, "Starting local connection."); - } else if (NetworkHooks.getConnectionType(()->this.manager)== ConnectionType.VANILLA) { - this.messageList = Collections.emptyList(); - LOGGER.debug(FMLHSMARKER, "Starting new vanilla impl connection."); - } else { - this.messageList = NetworkRegistry.gatherLoginPayloads(this.direction, false); - LOGGER.debug(FMLHSMARKER, "Starting new modded impl connection. Found {} messages to dispatch.", this.messageList.size()); - } - } - - @FunctionalInterface - public interface HandshakeConsumer - { - void accept(HandshakeHandler handler, MSG msg, Supplier context); - } - - /** - * Transforms a two-argument instance method reference into a {@link BiConsumer} based on the {@link #getHandshake(Supplier)} function. - * - * This should only be used for login message types. - * - * @param consumer A two argument instance method reference - * @param message type - * @return A {@link BiConsumer} for use in message handling - */ - public static BiConsumer> biConsumerFor(HandshakeConsumer consumer) - { - return (m, c) -> consumer.accept(getHandshake(c), m, c); - } - - /** - * Transforms a two-argument instance method reference into a {@link BiConsumer} {@link #biConsumerFor(HandshakeConsumer)}, first calling the {@link #handleIndexedMessage(IntSupplier, Supplier)} - * method to handle index tracking. Used for client to server replies. - * - * This should only be used for login messages. - * - * @param next The method reference to call after index handling - * @param message type - * @return A {@link BiConsumer} for use in message handling - */ - public static BiConsumer> indexFirst(HandshakeConsumer next) - { - final BiConsumer> loginIndexedMessageSupplierBiConsumer = biConsumerFor(HandshakeHandler::handleIndexedMessage); - return loginIndexedMessageSupplierBiConsumer.andThen(biConsumerFor(next)); - } - - /** - * Retrieve the handshake from the {@link NetworkEvent.Context} - * - * @param contextSupplier the {@link NetworkEvent.Context} - * @return The handshake handler for the connection - */ - private static HandshakeHandler getHandshake(Supplier contextSupplier) { - return contextSupplier.get().attr(NetworkConstants.FML_HANDSHAKE_HANDLER).get(); - } - - void handleServerModListOnClient(HandshakeMessages.S2CModList serverModList, Supplier c) - { - LOGGER.debug(FMLHSMARKER, "Logging into server with mod list [{}]", String.join(", ", serverModList.getModList())); - Map mismatchedChannels = NetworkRegistry.validateClientChannels(serverModList.getChannels()); - c.get().setPacketHandled(true); - //The connection data needs to be modified before a new ModMismatchData instance could be constructed - NetworkHooks.appendConnectionData(c.get().getNetworkManager(), serverModList.getModList().stream().collect(Collectors.toMap(Function.identity(), s -> Pair.of("", ""))), serverModList.getChannels()); - if (!mismatchedChannels.isEmpty()) { - LOGGER.error(FMLHSMARKER, "Terminating connection with server, mismatched mod list"); - //Populate the mod mismatch attribute with a new mismatch data instance to indicate that the disconnect happened due to a mod mismatch - c.get().getNetworkManager().channel().attr(NetworkConstants.FML_MOD_MISMATCH_DATA).set(ModMismatchData.channel(mismatchedChannels, NetworkHooks.getConnectionData(c.get().getNetworkManager()), true)); - c.get().getNetworkManager().disconnect(Component.literal("Connection closed - mismatched mod channel list")); - return; - } - // Validate synced custom datapack registries, client cannot be missing any present on the server. - List missingDataPackRegistries = new ArrayList<>(); - Set>> clientDataPackRegistries = DataPackRegistriesHooks.getSyncedCustomRegistries(); - for (ResourceKey> key : serverModList.getCustomDataPackRegistries()) - { - if (!clientDataPackRegistries.contains(key)) - { - ResourceLocation location = key.location(); - LOGGER.error(FMLHSMARKER, "Missing required datapack registry: {}", location); - missingDataPackRegistries.add(key.location().toString()); - } - } - if (!missingDataPackRegistries.isEmpty()) - { - c.get().getNetworkManager().disconnect(Component.translatable("fml.menu.multiplayer.missingdatapackregistries", String.join(", ", missingDataPackRegistries))); - return; - } - NetworkConstants.handshakeChannel.reply(new HandshakeMessages.C2SModListReply(), c.get()); - - LOGGER.debug(FMLHSMARKER, "Accepted server connection"); - // Set the modded marker on the channel so we know we got packets - c.get().getNetworkManager().channel().attr(NetworkConstants.FML_NETVERSION).set(NetworkConstants.NETVERSION); - - this.registriesToReceive = new HashSet<>(serverModList.getRegistries()); - this.registrySnapshots = Maps.newHashMap(); - LOGGER.debug(ForgeRegistry.REGISTRIES, "Expecting {} registries: {}", ()->this.registriesToReceive.size(), ()->this.registriesToReceive); - } - - void handleModData(HandshakeMessages.S2CModData serverModData, Supplier c) - { - c.get().getNetworkManager().channel().attr(NetworkConstants.FML_CONNECTION_DATA).set(new ConnectionData(serverModData.getMods(), new HashMap<>())); - c.get().setPacketHandled(true); - } - - void handleIndexedMessage(MSG message, Supplier c) - { - LOGGER.debug(FMLHSMARKER, "Received client indexed reply {} of type {}", message.getAsInt(), message.getClass().getName()); - boolean removed = this.sentMessages.removeIf(i-> i == message.getAsInt()); - if (!removed) { - LOGGER.error(FMLHSMARKER, "Recieved unexpected index {} in client reply", message.getAsInt()); - } - } - - void handleClientModListOnServer(HandshakeMessages.C2SModListReply clientModList, Supplier c) - { - LOGGER.debug(FMLHSMARKER, "Received client connection with modlist [{}]", String.join(", ", clientModList.getModList())); - Map mismatchedChannels = NetworkRegistry.validateServerChannels(clientModList.getChannels()); - c.get().getNetworkManager().channel().attr(NetworkConstants.FML_CONNECTION_DATA) - .set(new ConnectionData(clientModList.getModList().stream().collect(Collectors.toMap(Function.identity(), s -> Pair.of("", ""))), clientModList.getChannels())); - c.get().setPacketHandled(true); - if (!mismatchedChannels.isEmpty()) { - LOGGER.error(FMLHSMARKER, "Terminating connection with client, mismatched mod list"); - NetworkConstants.handshakeChannel.reply(new HandshakeMessages.S2CChannelMismatchData(mismatchedChannels), c.get()); - c.get().getNetworkManager().disconnect(Component.literal("Connection closed - mismatched mod channel list")); - return; - } - LOGGER.debug(FMLHSMARKER, "Accepted client connection mod list"); - } - - void handleModMismatchData(HandshakeMessages.S2CChannelMismatchData modMismatchData, Supplier c) - { - if (!modMismatchData.getMismatchedChannelData().isEmpty()) - { - LOGGER.error(FMLHSMARKER, "Channels [{}] rejected their client side version number", - modMismatchData.getMismatchedChannelData().keySet().stream().map(Object::toString).collect(Collectors.joining(","))); - LOGGER.error(FMLHSMARKER, "Terminating connection with server, mismatched mod list"); - c.get().setPacketHandled(true); - //Populate the mod mismatch attribute with a new mismatch data instance to indicate that the disconnect happened due to a mod mismatch - c.get().getNetworkManager().channel().attr(NetworkConstants.FML_MOD_MISMATCH_DATA).set(ModMismatchData.channel(modMismatchData.getMismatchedChannelData(), NetworkHooks.getConnectionData(c.get().getNetworkManager()), false)); - c.get().getNetworkManager().disconnect(Component.literal("Connection closed - mismatched mod channel list")); - } - } - - void handleRegistryMessage(final HandshakeMessages.S2CRegistry registryPacket, final Supplier contextSupplier){ - LOGGER.debug(FMLHSMARKER,"Received registry packet for {}", registryPacket.getRegistryName()); - this.registriesToReceive.remove(registryPacket.getRegistryName()); - this.registrySnapshots.put(registryPacket.getRegistryName(), registryPacket.getSnapshot()); - - boolean continueHandshake = true; - if (this.registriesToReceive.isEmpty()) { - continueHandshake = handleRegistryLoading(contextSupplier); - } - // The handshake reply isn't sent until we have processed the message - contextSupplier.get().setPacketHandled(true); - if (!continueHandshake) { - LOGGER.error(FMLHSMARKER, "Connection closed, not continuing handshake"); - } else { - NetworkConstants.handshakeChannel.reply(new HandshakeMessages.C2SAcknowledge(), contextSupplier.get()); - } - } - - private boolean handleRegistryLoading(final Supplier contextSupplier) { - // We use a countdown latch to suspend the impl thread pending the client thread processing the registry data - AtomicBoolean successfulConnection = new AtomicBoolean(false); - AtomicReference> registryMismatches = new AtomicReference<>(); - CountDownLatch block = new CountDownLatch(1); - contextSupplier.get().enqueueWork(() -> { - LOGGER.debug(FMLHSMARKER, "Injecting registry snapshot from server."); - final Multimap missingData = GameData.injectSnapshot(registrySnapshots, false, false); - LOGGER.debug(FMLHSMARKER, "Snapshot injected."); - if (!missingData.isEmpty()) { - LOGGER.error(FMLHSMARKER, "Missing registry data for impl connection:\n{}", LogMessageAdapter.adapt(sb-> - missingData.forEach((reg, entry)-> sb.append("\t").append(reg).append(": ").append(entry).append('\n')))); - } - successfulConnection.set(missingData.isEmpty()); - registryMismatches.set(missingData); - block.countDown(); - }); - LOGGER.debug(FMLHSMARKER, "Waiting for registries to load."); - try { - block.await(); - } catch (InterruptedException e) { - Thread.interrupted(); - } - if (successfulConnection.get()) { - LOGGER.debug(FMLHSMARKER, "Registry load complete, continuing handshake."); - } else { - LOGGER.error(FMLHSMARKER, "Failed to load registry, closing connection."); - //Populate the mod mismatch attribute with a new mismatch data instance to indicate that the disconnect happened due to a mod mismatch - this.manager.channel().attr(NetworkConstants.FML_MOD_MISMATCH_DATA).set(ModMismatchData.registry(registryMismatches.get(), NetworkHooks.getConnectionData(contextSupplier.get().getNetworkManager()))); - this.manager.disconnect(Component.literal("Failed to synchronize registry data from server, closing connection")); - } - return successfulConnection.get(); - } - - void handleClientAck(final HandshakeMessages.C2SAcknowledge msg, final Supplier contextSupplier) { - LOGGER.debug(FMLHSMARKER, "Received acknowledgement from client"); - contextSupplier.get().setPacketHandled(true); - } - - void handleConfigSync(final HandshakeMessages.S2CConfigData msg, final Supplier contextSupplier) { - LOGGER.debug(FMLHSMARKER, "Received config sync from server"); - ConfigSync.INSTANCE.receiveSyncedConfig(msg, contextSupplier); - contextSupplier.get().setPacketHandled(true); - NetworkConstants.handshakeChannel.reply(new HandshakeMessages.C2SAcknowledge(), contextSupplier.get()); - } - /** - * FML will send packets, from Server to Client, from the messages queue until the queue is drained. Each message - * will be indexed, and placed into the "pending acknowledgement" queue. - * - * As indexed packets are received at the server, they will be removed from the "pending acknowledgement" queue. - * - * Once the pending queue is drained, this method returns true - indicating that login processing can proceed to - * the next step. - * - * @return true if there is no more need to tick this login connection. - */ - public boolean tickServer() - { - if (!negotiationStarted) { - GameProfile profile = ((ServerLoginPacketListenerImpl) manager.getPacketListener()).getAuthenticatedProfile(); - PlayerNegotiationEvent event = new PlayerNegotiationEvent(manager, profile, pendingFutures); - MinecraftForge.EVENT_BUS.post(event); - negotiationStarted = true; - } - - if (packetPosition < messageList.size()) { - NetworkRegistry.LoginPayload message = messageList.get(packetPosition); - - LOGGER.debug(FMLHSMARKER, "Sending ticking packet info '{}' to '{}' sequence {}", message.getMessageContext(), message.getChannelName(), packetPosition); - if (message.needsResponse()) - sentMessages.add(packetPosition); - loginWrapper.sendServerToClientLoginPacket(message.getChannelName(), message.getData(), packetPosition, this.manager); - packetPosition++; - } - - pendingFutures.removeIf(future -> { - if (!future.isDone()) { - return false; - } - - try { - future.get(); - } catch (ExecutionException ex) { - LOGGER.error("Error during negotiation", ex.getCause()); - } catch (CancellationException | InterruptedException ex) { - // no-op - } - - return true; - }); - - // we're done when sentMessages is empty - if (sentMessages.isEmpty() && packetPosition >= messageList.size()-1 && pendingFutures.isEmpty()) { - // clear ourselves - we're done! - this.manager.channel().attr(NetworkConstants.FML_HANDSHAKE_HANDLER).set(null); - LOGGER.debug(FMLHSMARKER, "Handshake complete!"); - return true; - } - return false; - } - - /** - * Helper method to determine if the S2C packet at the given packet position needs a response in form of a packet handled in {@link HandshakeHandler#handleIndexedMessage} for the handshake to progress. - * @param mgr The impl manager for this connection - * @param packetPosition The packet position of the packet that the status is queried of - * @return true if the packet at the given packet position needs a response and thus may stop the handshake from progressing - */ - public static boolean packetNeedsResponse(Connection mgr, int packetPosition) - { - HandshakeHandler handler = mgr.channel().attr(NetworkConstants.FML_HANDSHAKE_HANDLER).get(); - if (handler != null) - { - return handler.sentMessages.contains(packetPosition); - } - return false; - } -} diff --git a/src/main/java/net/minecraftforge/network/HandshakeMessages.java b/src/main/java/net/minecraftforge/network/HandshakeMessages.java deleted file mode 100644 index 5d9a2048a1..0000000000 --- a/src/main/java/net/minecraftforge/network/HandshakeMessages.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.network; - -import net.minecraft.core.Registry; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.fml.ModList; -import net.minecraftforge.forgespi.language.IModInfo; -import net.minecraftforge.registries.DataPackRegistriesHooks; -import net.minecraftforge.registries.ForgeRegistry; -import net.minecraftforge.registries.RegistryManager; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.IntSupplier; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.tuple.Pair; - -import com.google.common.collect.Maps; -import org.jetbrains.annotations.Nullable; - -public class HandshakeMessages -{ - static class LoginIndexedMessage implements IntSupplier - { - private int loginIndex; - - void setLoginIndex(final int loginIndex) { - this.loginIndex = loginIndex; - } - - int getLoginIndex() { - return loginIndex; - } - - @Override - public int getAsInt() { - return getLoginIndex(); - } - } - /** - * Server to client "list of mods". Always first handshake message after the data sent by S2CModData. - */ - public static class S2CModList extends LoginIndexedMessage - { - private List mods; - private Map channels; - private List registries; - private final List>> dataPackRegistries; - - public S2CModList() - { - this.mods = ModList.get().getMods().stream().map(IModInfo::getModId).collect(Collectors.toList()); - this.channels = NetworkRegistry.buildChannelVersions(); - this.registries = RegistryManager.getRegistryNamesForSyncToClient(); - this.dataPackRegistries = List.copyOf(DataPackRegistriesHooks.getSyncedCustomRegistries()); - } - - private S2CModList(List mods, Map channels, List registries, List>> dataPackRegistries) - { - this.mods = mods; - this.channels = channels; - this.registries = registries; - this.dataPackRegistries = dataPackRegistries; - } - - public static S2CModList decode(FriendlyByteBuf input) - { - List mods = new ArrayList<>(); - int len = input.readVarInt(); - for (int x = 0; x < len; x++) - mods.add(input.readUtf(0x100)); - - Map channels = new HashMap<>(); - len = input.readVarInt(); - for (int x = 0; x < len; x++) - channels.put(input.readResourceLocation(), input.readUtf(0x100)); - - List registries = new ArrayList<>(); - len = input.readVarInt(); - for (int x = 0; x < len; x++) - registries.add(input.readResourceLocation()); - - List>> dataPackRegistries = input.readCollection(ArrayList::new, buf -> ResourceKey.createRegistryKey(buf.readResourceLocation())); - return new S2CModList(mods, channels, registries, dataPackRegistries); - } - - public void encode(FriendlyByteBuf output) - { - output.writeVarInt(mods.size()); - mods.forEach(m -> output.writeUtf(m, 0x100)); - - output.writeVarInt(channels.size()); - channels.forEach((k, v) -> { - output.writeResourceLocation(k); - output.writeUtf(v, 0x100); - }); - - output.writeVarInt(registries.size()); - registries.forEach(output::writeResourceLocation); - - Set>> dataPackRegistries = DataPackRegistriesHooks.getSyncedCustomRegistries(); - output.writeCollection(dataPackRegistries, (buf, key) -> buf.writeResourceLocation(key.location())); - } - - public List getModList() { - return mods; - } - - public List getRegistries() { - return this.registries; - } - - public Map getChannels() { - return this.channels; - } - - /** - * @return list of ids of non-vanilla syncable datapack registries on the server. - */ - public List>> getCustomDataPackRegistries() { - return this.dataPackRegistries; - } - } - - /** - * Prefixes S2CModList by sending additional data about the mods installed on the server to the client - * The mod data is stored as follows: [modId -> [modName, modVersion]] - */ - public static class S2CModData extends LoginIndexedMessage - { - private final Map> mods; - - public S2CModData() - { - this.mods = ModList.get().getMods().stream().collect(Collectors.toMap(IModInfo::getModId, info -> Pair.of(info.getDisplayName(), info.getVersion().toString()))); - } - - private S2CModData(Map> mods) - { - this.mods = mods; - } - - public static S2CModData decode(FriendlyByteBuf input) - { - Map> mods = input.readMap(o -> o.readUtf(0x100), o -> Pair.of(o.readUtf(0x100), o.readUtf(0x100))); - return new S2CModData(mods); - } - - public void encode(FriendlyByteBuf output) - { - output.writeMap(mods, (o, s) -> o.writeUtf(s, 0x100), (o, p) -> { - o.writeUtf(p.getLeft(), 0x100); - o.writeUtf(p.getRight(), 0x100); - }); - } - - public Map> getMods() - { - return mods; - } - } - - public static class C2SModListReply extends LoginIndexedMessage - { - private List mods; - private Map channels; - private Map registries; - - public C2SModListReply() - { - this.mods = ModList.get().getMods().stream().map(IModInfo::getModId).collect(Collectors.toList()); - this.channels = NetworkRegistry.buildChannelVersions(); - this.registries = Maps.newHashMap(); //TODO: Fill with known hashes, which requires keeping a file cache - } - - private C2SModListReply(List mods, Map channels, Map registries) - { - this.mods = mods; - this.channels = channels; - this.registries = registries; - } - - public static C2SModListReply decode(FriendlyByteBuf input) - { - List mods = new ArrayList<>(); - int len = input.readVarInt(); - for (int x = 0; x < len; x++) - mods.add(input.readUtf(0x100)); - - Map channels = new HashMap<>(); - len = input.readVarInt(); - for (int x = 0; x < len; x++) - channels.put(input.readResourceLocation(), input.readUtf(0x100)); - - Map registries = new HashMap<>(); - len = input.readVarInt(); - for (int x = 0; x < len; x++) - registries.put(input.readResourceLocation(), input.readUtf(0x100)); - - return new C2SModListReply(mods, channels, registries); - } - - public void encode(FriendlyByteBuf output) - { - output.writeVarInt(mods.size()); - mods.forEach(m -> output.writeUtf(m, 0x100)); - - output.writeVarInt(channels.size()); - channels.forEach((k, v) -> { - output.writeResourceLocation(k); - output.writeUtf(v, 0x100); - }); - - output.writeVarInt(registries.size()); - registries.forEach((k, v) -> { - output.writeResourceLocation(k); - output.writeUtf(v, 0x100); - }); - } - - public List getModList() { - return mods; - } - - public Map getRegistries() { - return this.registries; - } - - public Map getChannels() { - return this.channels; - } - } - - public static class C2SAcknowledge extends LoginIndexedMessage { - public void encode(FriendlyByteBuf buf) { - - } - - public static C2SAcknowledge decode(FriendlyByteBuf buf) { - return new C2SAcknowledge(); - } - } - - public static class S2CRegistry extends LoginIndexedMessage { - private ResourceLocation registryName; - @Nullable - private ForgeRegistry.Snapshot snapshot; - - public S2CRegistry(final ResourceLocation name, @Nullable ForgeRegistry.Snapshot snapshot) { - this.registryName = name; - this.snapshot = snapshot; - } - - void encode(final FriendlyByteBuf buffer) { - buffer.writeResourceLocation(registryName); - buffer.writeBoolean(hasSnapshot()); - if (hasSnapshot()) - buffer.writeBytes(snapshot.getPacketData()); - } - - public static S2CRegistry decode(final FriendlyByteBuf buffer) { - ResourceLocation name = buffer.readResourceLocation(); - ForgeRegistry.Snapshot snapshot = null; - if (buffer.readBoolean()) - snapshot = ForgeRegistry.Snapshot.read(buffer); - return new S2CRegistry(name, snapshot); - } - - public ResourceLocation getRegistryName() { - return registryName; - } - - public boolean hasSnapshot() { - return snapshot != null; - } - - @Nullable - public ForgeRegistry.Snapshot getSnapshot() { - return snapshot; - } - } - - - public static class S2CConfigData extends LoginIndexedMessage { - private final String fileName; - private final byte[] fileData; - - public S2CConfigData(final String configFileName, final byte[] configFileData) { - this.fileName = configFileName; - this.fileData = configFileData; - } - - void encode(final FriendlyByteBuf buffer) { - buffer.writeUtf(this.fileName); - buffer.writeByteArray(this.fileData); - } - - public static S2CConfigData decode(final FriendlyByteBuf buffer) { - return new S2CConfigData(buffer.readUtf(32767), buffer.readByteArray()); - } - - public String getFileName() { - return fileName; - } - - public byte[] getBytes() { - return fileData; - } - } - - /** - * Notifies the client of a channel mismatch on the server, so a {@link net.minecraftforge.client.gui.ModMismatchDisconnectedScreen} is used to notify the user of the disconnection. - * This packet also sends the data of a channel mismatch (currently, the ids and versions of the mismatched channels) to the client for it to display the correct information in said screen. - */ - public static class S2CChannelMismatchData extends LoginIndexedMessage - { - private final Map mismatchedChannelData; - - public S2CChannelMismatchData(Map mismatchedChannelData) - { - this.mismatchedChannelData = mismatchedChannelData; - } - - public static S2CChannelMismatchData decode(FriendlyByteBuf input) - { - Map mismatchedMods = input.readMap(i -> new ResourceLocation(i.readUtf(0x100)), i -> i.readUtf(0x100)); - - return new S2CChannelMismatchData(mismatchedMods); - } - - public void encode(FriendlyByteBuf output) - { - output.writeMap(mismatchedChannelData, (o, r) -> o.writeUtf(r.toString(), 0x100), (o, v) -> o.writeUtf(v, 0x100)); - } - - public Map getMismatchedChannelData() - { - return mismatchedChannelData; - } - } -} diff --git a/src/main/java/net/minecraftforge/network/IContainerFactory.java b/src/main/java/net/minecraftforge/network/IContainerFactory.java index 3c5bd12d2c..35fc4c77db 100644 --- a/src/main/java/net/minecraftforge/network/IContainerFactory.java +++ b/src/main/java/net/minecraftforge/network/IContainerFactory.java @@ -10,13 +10,11 @@ import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.MenuType; import net.minecraft.network.FriendlyByteBuf; -public interface IContainerFactory extends MenuType.MenuSupplier -{ +public interface IContainerFactory extends MenuType.MenuSupplier { T create(int windowId, Inventory inv, FriendlyByteBuf data); - + @Override - default T create(int p_create_1_, Inventory p_create_2_) - { - return create(p_create_1_, p_create_2_, null); + default T create(int id, Inventory inv) { + return create(id, inv, null); } } diff --git a/src/main/java/net/minecraftforge/network/LoginWrapper.java b/src/main/java/net/minecraftforge/network/LoginWrapper.java deleted file mode 100644 index 54106ad1c7..0000000000 --- a/src/main/java/net/minecraftforge/network/LoginWrapper.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.network; - -import io.netty.buffer.Unpooled; -import net.minecraft.network.Connection; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.network.event.EventNetworkChannel; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.ApiStatus; - -/** - * Wrapper for custom login packets. Transforms unnamed login channel messages into channels dispatched the same - * as regular custom packets. - */ -public class LoginWrapper -{ - private static final Logger LOGGER = LogManager.getLogger(); - @ApiStatus.Internal - public static final ResourceLocation WRAPPER = new ResourceLocation("fml:loginwrapper"); - private EventNetworkChannel wrapperChannel; - - LoginWrapper() { - wrapperChannel = NetworkRegistry.ChannelBuilder.named(LoginWrapper.WRAPPER). - clientAcceptedVersions(a->true). - serverAcceptedVersions(a->true). - networkProtocolVersion(()-> NetworkConstants.NETVERSION) - .eventNetworkChannel(); - wrapperChannel.addListener(this::wrapperReceived); - } - - private void wrapperReceived(final T packet) { - // we don't care about channel registration change events on this channel - if (packet instanceof NetworkEvent.ChannelRegistrationChangeEvent) return; - final NetworkEvent.Context wrappedContext = packet.getSource().get(); - final FriendlyByteBuf payload = packet.getPayload(); - ResourceLocation targetNetworkReceiver = NetworkConstants.FML_HANDSHAKE_RESOURCE; - FriendlyByteBuf data = null; - if (payload != null) { - targetNetworkReceiver = payload.readResourceLocation(); - final int payloadLength = payload.readVarInt(); - data = new FriendlyByteBuf(payload.readBytes(payloadLength)); - } - final int loginSequence = packet.getLoginIndex(); - LOGGER.debug(HandshakeHandler.FMLHSMARKER, "Recieved login wrapper packet event for channel {} with index {}", targetNetworkReceiver, loginSequence); - final NetworkEvent.Context context = new NetworkEvent.Context(wrappedContext.getNetworkManager(), wrappedContext.getDirection(), (rl, buf) -> { - LOGGER.debug(HandshakeHandler.FMLHSMARKER, "Dispatching wrapped packet reply for channel {} with index {}", rl, loginSequence); - wrappedContext.getPacketDispatcher().sendPacket(WRAPPER, this.wrapPacket(rl, buf)); - }); - final NetworkEvent.LoginPayloadEvent loginPayloadEvent = new NetworkEvent.LoginPayloadEvent(data, () -> context, loginSequence); - NetworkRegistry.findTarget(targetNetworkReceiver).ifPresent(ni -> { - ni.dispatchLoginPacket(loginPayloadEvent); - wrappedContext.setPacketHandled(context.getPacketHandled()); - }); - } - - private FriendlyByteBuf wrapPacket(final ResourceLocation rl, final FriendlyByteBuf buf) { - FriendlyByteBuf pb = new FriendlyByteBuf(Unpooled.buffer(buf.capacity())); - pb.writeResourceLocation(rl); - pb.writeVarInt(buf.readableBytes()); - pb.writeBytes(buf); - return pb; - } - - void sendServerToClientLoginPacket(final ResourceLocation resourceLocation, final FriendlyByteBuf buffer, final int index, final Connection manager) { - FriendlyByteBuf pb = wrapPacket(resourceLocation, buffer); - manager.send(NetworkDirection.LOGIN_TO_CLIENT.buildPacket(Pair.of(pb, index), WRAPPER).getThis()); - } -} diff --git a/src/main/java/net/minecraftforge/network/MCRegisterPacketHandler.java b/src/main/java/net/minecraftforge/network/MCRegisterPacketHandler.java deleted file mode 100644 index ea46d4d524..0000000000 --- a/src/main/java/net/minecraftforge/network/MCRegisterPacketHandler.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.network; - -import com.mojang.logging.LogUtils; -import io.netty.buffer.Unpooled; -import io.netty.util.Attribute; -import net.minecraft.ResourceLocationException; -import net.minecraft.network.protocol.Packet; -import net.minecraft.network.Connection; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; - -import org.apache.commons.lang3.tuple.Pair; -import org.slf4j.Logger; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; -import java.util.function.Supplier; - -public class MCRegisterPacketHandler -{ - private static final Logger LOGGER = LogUtils.getLogger(); - public static final MCRegisterPacketHandler INSTANCE = new MCRegisterPacketHandler(); - - public static class ChannelList { - private Set locations = new HashSet<>(); - private Set remoteLocations = Set.of(); - - public void updateFrom(final Supplier source, FriendlyByteBuf buffer, final NetworkEvent.RegistrationChangeType changeType) { - byte[] data = new byte[Math.max(buffer.readableBytes(), 0)]; - buffer.readBytes(data); - Set oldLocations = this.locations; - this.locations = bytesToResLocation(data); - this.remoteLocations = Set.copyOf(this.locations); - // ensure all locations receive updates, old and new. - oldLocations.addAll(this.locations); - oldLocations.stream() - .map(NetworkRegistry::findTarget) - .filter(Optional::isPresent) - .map(Optional::get) - .forEach(t->t.dispatchEvent(new NetworkEvent.ChannelRegistrationChangeEvent(source, changeType))); - } - - byte[] toByteArray() { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - for (ResourceLocation rl : locations) { - try { - bos.write(rl.toString().getBytes(StandardCharsets.UTF_8)); - bos.write(0); - } catch (IOException e) { - // fake IOE - } - } - return bos.toByteArray(); - } - - private Set bytesToResLocation(byte[] all) { - HashSet rl = new HashSet<>(); - int last = 0; - for (int cur = 0; cur < all.length; cur++) { - if (all[cur] == '\0') { - String s = new String(all, last, cur - last, StandardCharsets.UTF_8); - try { - rl.add(new ResourceLocation(s)); - } catch (ResourceLocationException ex) { - LOGGER.warn("Invalid channel name received: {}. Ignoring", s); - } - last = cur + 1; - } - } - return rl; - } - - /** - * {@return the unmodifiable set of channel locations sent by the remote side} - * This is useful for interacting with other modloaders via the network to inspect registered network channel IDs. - */ - public Set getRemoteLocations() { - return this.remoteLocations; - } - } - - public void addChannels(Set locations, Connection manager) { - getFrom(manager).locations.addAll(locations); - } - - void registerListener(NetworkEvent evt) { - final ChannelList channelList = getFrom(evt); - channelList.updateFrom(evt.getSource(), evt.getPayload(), NetworkEvent.RegistrationChangeType.REGISTER); - evt.getSource().get().setPacketHandled(true); - } - - void unregisterListener(NetworkEvent evt) { - final ChannelList channelList = getFrom(evt); - channelList.updateFrom(evt.getSource(), evt.getPayload(), NetworkEvent.RegistrationChangeType.UNREGISTER); - evt.getSource().get().setPacketHandled(true); - } - - private static ChannelList getFrom(Connection manager) { - return fromAttr(manager.channel().attr(NetworkConstants.FML_MC_REGISTRY)); - } - - private static ChannelList getFrom(NetworkEvent event) { - return fromAttr(event.getSource().get().attr(NetworkConstants.FML_MC_REGISTRY)); - } - - private static ChannelList fromAttr(Attribute attr) { - attr.setIfAbsent(new ChannelList()); - return attr.get(); - } - - public void sendRegistry(Connection manager, final NetworkDirection dir) { - FriendlyByteBuf pb = new FriendlyByteBuf(Unpooled.buffer()); - pb.writeBytes(getFrom(manager).toByteArray()); - final ICustomPacket> iPacketICustomPacket = dir.buildPacket(Pair.of(pb, 0), NetworkConstants.MC_REGISTER_RESOURCE); - manager.send(iPacketICustomPacket.getThis()); - } -} diff --git a/src/main/java/net/minecraftforge/network/NetworkConstants.java b/src/main/java/net/minecraftforge/network/NetworkConstants.java deleted file mode 100644 index 41381f2807..0000000000 --- a/src/main/java/net/minecraftforge/network/NetworkConstants.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.network; - -import io.netty.util.AttributeKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.fml.IExtensionPoint; -import net.minecraftforge.fml.IExtensionPoint.DisplayTest; -import net.minecraftforge.network.ConnectionData.ModMismatchData; -import net.minecraftforge.network.HandshakeMessages.S2CModList; -import net.minecraftforge.network.event.EventNetworkChannel; -import net.minecraftforge.network.simple.SimpleChannel; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; - -import java.util.List; -/** - * Constants related to networking - */ -public class NetworkConstants -{ - public static final String FMLNETMARKER = "FML"; - /** - * Netversion 3: {@link S2CModList} packet may include a list of non-vanilla synced datapack registry ids. - */ - public static final int FMLNETVERSION = 3; - public static final String NETVERSION = FMLNETMARKER + FMLNETVERSION; - public static final String NOVERSION = "NONE"; - - static final Marker NETWORK = MarkerManager.getMarker("FMLNETWORK"); - static final AttributeKey FML_NETVERSION = AttributeKey.valueOf("fml:netversion"); - static final AttributeKey FML_HANDSHAKE_HANDLER = AttributeKey.valueOf("fml:handshake"); - static final AttributeKey FML_MC_REGISTRY = AttributeKey.valueOf("minecraft:netregistry"); - static final AttributeKey FML_CONNECTION_DATA = AttributeKey.valueOf("fml:conndata"); - static final AttributeKey FML_MOD_MISMATCH_DATA = AttributeKey.valueOf("fml:mismatchdata"); - static final ResourceLocation FML_HANDSHAKE_RESOURCE = new ResourceLocation("fml:handshake"); - static final ResourceLocation FML_PLAY_RESOURCE = new ResourceLocation("fml:play"); - static final ResourceLocation MC_REGISTER_RESOURCE = new ResourceLocation("minecraft:register"); - static final ResourceLocation MC_UNREGISTER_RESOURCE = new ResourceLocation("minecraft:unregister"); - static final SimpleChannel handshakeChannel = NetworkInitialization.getHandshakeChannel(); - static final SimpleChannel playChannel = NetworkInitialization.getPlayChannel(); - static final List mcRegChannels = NetworkInitialization.buildMCRegistrationChannels(); - /** - * Return this value in your {@link DisplayTest} function to be ignored. - */ - public static final String IGNORESERVERONLY = DisplayTest.IGNORESERVERONLY; - - public static String init() { - return NetworkConstants.NETVERSION; - } -} diff --git a/src/main/java/net/minecraftforge/network/NetworkContext.java b/src/main/java/net/minecraftforge/network/NetworkContext.java new file mode 100644 index 0000000000..77ddef410e --- /dev/null +++ b/src/main/java/net/minecraftforge/network/NetworkContext.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.jetbrains.annotations.ApiStatus; + +import io.netty.util.AttributeKey; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import net.minecraft.network.Connection; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.network.ConfigurationTask; +import net.minecraft.server.network.ServerConfigurationPacketListenerImpl; +import net.minecraftforge.network.packets.ModVersions; + +public class NetworkContext { + private static final String MARKER = "FORGE"; + public static final int NET_VERSION = 0; + private static final AttributeKey CHANNEL_KEY = AttributeKey.valueOf("forge:netcontext"); + + /** + * Gets the associated NetworkContext from the connection, creating a new instance if necessary. + */ + public static NetworkContext get(Connection connection) { + var attr = connection.channel().attr(CHANNEL_KEY); + var ret = attr.get(); + if (ret == null) { + synchronized(connection.channel()) { + ret = attr.get(); + if (ret == null) { + ret = new NetworkContext(connection); + attr.set(ret); + } + } + } + return ret; + } + + private final Connection connection; + private ConnectionType type = ConnectionType.VANILLA; + private int netVersion = 0; + + private NetworkContext(Connection connection) { + this.connection = connection; + } + + public ConnectionType getType() { + return this.type; + } + + public int getNetVersion() { + return this.netVersion; + } + + public Set getRemoteChannels() { + return this.remoteChannelsView; + } + + /** + * A list of mods and their verisons reported by the other side of the connection. + * The remote side can and does lie about this, so not rely on it for any anti-cheat system. + */ + public Map getModList() { + return this.modListView; + } + + /* =================================================================================== + * INTERNAL BELOW THIS + * =================================================================================== + */ + + /** + * This is a hint that we are a modded client, This is sent in the first packet the client sends to the server. + * Unfortunately we do not have a modder facing value in this packet, so we have a long standing tradition of + * encoding it on the hostName field, which is a UTF string. + * Forge treats this string a null terminated list. With our value being anywhere in the list. + * Our identifier is currently FORGE, Optionally followed by a number indicating the network version. + * If the version is missing, we assume 0. + * + * TODO: Move out of the Intention packet and into a immediately sent Login custom payload? Which should arrive before we get to config stage? + */ + @ApiStatus.Internal + public static String enhanceHostName(String hostName) { + return String.join("\0", hostName, MARKER); + } + + @ApiStatus.Internal + public void processIntention(String hostName) { + this.type = ConnectionType.VANILLA; + this.netVersion = 0; + + int idx = hostName.indexOf('\0'); + if (idx != -1) { + for (var pt : hostName.split("\0")) { + if (pt.startsWith(MARKER)) { + this.type = ConnectionType.MODDED; + if (pt.length() > MARKER.length()) + this.netVersion = Integer.valueOf(pt.substring(MARKER.length())); + } + } + } + } + + @ApiStatus.Internal + Set remoteChannels = new HashSet<>(); + private Set remoteChannelsView = Collections.unmodifiableSet(this.remoteChannels); + + @ApiStatus.Internal + Set sentChannels = new HashSet<>(); + + @ApiStatus.Internal + Map modList = new HashMap<>(); + private Map modListView = Collections.unmodifiableMap(modList); + + @ApiStatus.Internal + Map channelList = new Object2IntOpenHashMap<>(); + + // TODO Make this official API? This is to allow us to finish a task in the packet handlers and not the task function itself. + @ApiStatus.Internal + public void finishTask(ConfigurationTask.Type task) { + if (this.connection.getPacketListener() instanceof ServerConfigurationPacketListenerImpl cfg) + cfg.finishCurrentTask(task); + else + throw new IllegalStateException("Attempted to finish task " + task + " when packet listener was " + this.connection.getPacketListener().getClass().getName()); + } + + @ApiStatus.Internal + NetworkMismatchData mismatchData = null; + + @ApiStatus.Internal + public NetworkMismatchData getMismatchs() { + return mismatchData; + } + + @ApiStatus.Internal + void setConnectionType(ConnectionType type) { + this.type = type; + } + + @ApiStatus.Internal + public record NetworkMismatchData( + Map mismatched, + Set missing, + boolean fromServer, + Map mods + ) { + public record Version(String received, String had) {} + } +} diff --git a/src/main/java/net/minecraftforge/network/NetworkDirection.java b/src/main/java/net/minecraftforge/network/NetworkDirection.java index 574e48043f..7c53dc0ebe 100644 --- a/src/main/java/net/minecraftforge/network/NetworkDirection.java +++ b/src/main/java/net/minecraftforge/network/NetworkDirection.java @@ -17,35 +17,28 @@ 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 org.apache.commons.lang3.tuple.Pair; - -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.stream.Collectors; -import java.util.stream.Stream; +@SuppressWarnings("rawtypes") public enum NetworkDirection { - PLAY_TO_SERVER(NetworkEvent.ClientCustomPayloadEvent::new, LogicalSide.CLIENT, ServerboundCustomPayloadPacket.class, 1, NetworkDirection::playServerbound), - PLAY_TO_CLIENT(NetworkEvent.ServerCustomPayloadEvent::new, LogicalSide.SERVER, ClientboundCustomPayloadPacket.class, 0, NetworkDirection::playClientbound), - LOGIN_TO_SERVER(NetworkEvent.ClientCustomPayloadLoginEvent::new, LogicalSide.CLIENT, ServerboundCustomQueryAnswerPacket.class, 3, NetworkDirection::loginServerbound), - LOGIN_TO_CLIENT(NetworkEvent.ServerCustomPayloadLoginEvent::new, LogicalSide.SERVER, ClientboundCustomQueryPacket.class, 2, NetworkDirection::loginClientbound); + 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); - private final BiFunction, Supplier, NetworkEvent> eventSupplier; private final LogicalSide logicalSide; private final Class packetClass; private final int otherWay; private final Factory factory; - private static final Reference2ReferenceArrayMap, NetworkDirection> packetLookup; + private static final Reference2ReferenceArrayMap, NetworkDirection> packetLookup = new Reference2ReferenceArrayMap<>(); + private static final NetworkDirection[] values = values(); static { - packetLookup = Stream.of(values()). - collect(Collectors.toMap(NetworkDirection::getPacketClass, Function.identity(), (m1,m2)->m1, Reference2ReferenceArrayMap::new)); + for (var value : values) + packetLookup.put(value.getPacketClass(), value); } - private NetworkDirection(BiFunction, Supplier, NetworkEvent> eventSupplier, LogicalSide logicalSide, Class clazz, int i, Factory factory) { - this.eventSupplier = eventSupplier; + private NetworkDirection(LogicalSide logicalSide, Class clazz, int i, Factory factory) { this.logicalSide = logicalSide; this.packetClass = clazz; this.otherWay = i; @@ -61,22 +54,20 @@ public enum NetworkDirection { } public NetworkDirection reply() { - return NetworkDirection.values()[this.otherWay]; - } - - public NetworkEvent getEvent(final ICustomPacket buffer, final Supplier manager) { - return this.eventSupplier.apply(buffer, manager); + return values[this.otherWay]; } public LogicalSide getOriginationSide() { return logicalSide; } - public LogicalSide getReceptionSide() { return reply().logicalSide; }; + public LogicalSide getReceptionSide() { + return reply().logicalSide; + } @SuppressWarnings("unchecked") - public > ICustomPacket buildPacket(Pair packetData, ResourceLocation channelName) { - return this.factory.create(packetData.getLeft(), packetData.getRight(), channelName); + public > ICustomPacket buildPacket(FriendlyByteBuf data, ResourceLocation channelName) { + return this.factory.create(data, 0, channelName); } private interface Factory> { diff --git a/src/main/java/net/minecraftforge/network/NetworkEvent.java b/src/main/java/net/minecraftforge/network/NetworkEvent.java deleted file mode 100644 index 08761f4a66..0000000000 --- a/src/main/java/net/minecraftforge/network/NetworkEvent.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.network; - -import io.netty.util.Attribute; -import io.netty.util.AttributeKey; - -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.network.PacketListener; -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import net.minecraft.network.Connection; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.thread.BlockableEventLoop; -import net.minecraftforge.eventbus.api.Event; -import net.minecraftforge.common.util.LogicalSidedProvider; -import org.apache.commons.lang3.tuple.Pair; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.function.BiConsumer; -import java.util.function.BiFunction; -import java.util.function.Supplier; - -public class NetworkEvent extends Event -{ - private final FriendlyByteBuf payload; - private final Supplier source; - private final int loginIndex; - - private NetworkEvent(final ICustomPacket payload, final Supplier source) - { - this.payload = payload.getInternalData(); - this.source = source; - this.loginIndex = payload.getIndex(); - } - - private NetworkEvent(final FriendlyByteBuf payload, final Supplier source, final int loginIndex) - { - this.payload = payload; - this.source = source; - this.loginIndex = loginIndex; - } - - public NetworkEvent(final Supplier source) { - this.source = source; - this.payload = null; - this.loginIndex = -1; - } - - public FriendlyByteBuf getPayload() - { - return payload; - } - - public Supplier getSource() - { - return source; - } - - public int getLoginIndex() - { - return loginIndex; - } - - public static class ServerCustomPayloadEvent extends NetworkEvent - { - ServerCustomPayloadEvent(final ICustomPacket payload, final Supplier source) { - super(payload, source); - } - } - public static class ClientCustomPayloadEvent extends NetworkEvent - { - ClientCustomPayloadEvent(final ICustomPacket payload, final Supplier source) { - super(payload, source); - } - } - public static class ServerCustomPayloadLoginEvent extends ServerCustomPayloadEvent { - ServerCustomPayloadLoginEvent(ICustomPacket payload, Supplier source) - { - super(payload, source); - } - } - - public static class ClientCustomPayloadLoginEvent extends ClientCustomPayloadEvent { - ClientCustomPayloadLoginEvent(ICustomPacket payload, Supplier source) - { - super(payload, source); - } - } - - public static class GatherLoginPayloadsEvent extends Event { - private final List collected; - private final boolean isLocal; - - public GatherLoginPayloadsEvent(final List loginPayloadList, boolean isLocal) { - this.collected = loginPayloadList; - this.isLocal = isLocal; - } - - public void add(FriendlyByteBuf buffer, ResourceLocation channelName, String context) { - collected.add(new NetworkRegistry.LoginPayload(buffer, channelName, context)); - } - - public void add(FriendlyByteBuf buffer, ResourceLocation channelName, String context, boolean needsResponse) - { - collected.add(new NetworkRegistry.LoginPayload(buffer, channelName, context, needsResponse)); - } - - public boolean isLocal() { - return isLocal; - } - } - - public static class LoginPayloadEvent extends NetworkEvent { - LoginPayloadEvent(final FriendlyByteBuf payload, final Supplier source, final int loginIndex) { - super(payload, source, loginIndex); - } - } - - public enum RegistrationChangeType { - REGISTER, UNREGISTER; - } - - /** - * Fired when the channel registration (see minecraft custom channel documentation) changes. Note the payload - * is not exposed. This fires to the resource location that owns the channel, when it's registration changes state. - * - * It seems plausible that this will fire multiple times for the same state, depending on what the server is doing. - * It just directly dispatches upon receipt. - */ - public static class ChannelRegistrationChangeEvent extends NetworkEvent { - private final RegistrationChangeType changeType; - - ChannelRegistrationChangeEvent(final Supplier source, RegistrationChangeType changeType) { - super(source); - this.changeType = changeType; - } - - public RegistrationChangeType getRegistrationChangeType() { - return this.changeType; - } - } - /** - * Context for {@link NetworkEvent} - */ - public static class Context - { - /** - * The {@link Connection} for this message. - */ - private final Connection networkManager; - - /** - * The {@link NetworkDirection} this message has been received on. - */ - private final NetworkDirection networkDirection; - - /** - * The packet dispatcher for this event. Sends back to the origin. - */ - private final PacketDispatcher packetDispatcher; - private boolean packetHandled; - - Context(Connection netHandler, NetworkDirection networkDirection, int index) - { - this(netHandler, networkDirection, new PacketDispatcher.NetworkManagerDispatcher(netHandler, index, networkDirection.reply()::buildPacket)); - } - - Context(Connection networkManager, NetworkDirection networkDirection, final BiConsumer packetSink) { - this(networkManager, networkDirection, new PacketDispatcher(packetSink)); - } - - Context(Connection networkManager, NetworkDirection networkDirection, PacketDispatcher dispatcher) { - this.networkManager = networkManager; - this.networkDirection = networkDirection; - this.packetDispatcher = dispatcher; - } - - public NetworkDirection getDirection() { - return networkDirection; - } - - public PacketDispatcher getPacketDispatcher() { - return packetDispatcher; - } - - public Attribute attr(AttributeKey key) { - return networkManager.channel().attr(key); - } - - public void setPacketHandled(boolean packetHandled) { - this.packetHandled = packetHandled; - } - - public boolean getPacketHandled() - { - return packetHandled; - } - - public CompletableFuture enqueueWork(Runnable runnable) { - BlockableEventLoop executor = LogicalSidedProvider.WORKQUEUE.get(getDirection().getReceptionSide()); - // 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()) { - return executor.submitAsync(runnable); // Use the internal method so thread check isn't done twice - } else { - runnable.run(); - return CompletableFuture.completedFuture(null); - } - } - - /** - * When available, gets the sender for packets that are sent from a client to the server. - */ - @Nullable - public ServerPlayer getSender() - { - PacketListener netHandler = networkManager.getPacketListener(); - if (netHandler instanceof ServerGamePacketListenerImpl) - { - ServerGamePacketListenerImpl netHandlerPlayServer = (ServerGamePacketListenerImpl) netHandler; - return netHandlerPlayServer.player; - } - return null; - } - - public Connection getNetworkManager() { - return networkManager; - } - } - - /** - * Dispatcher for sending packets in response to a received packet. Abstracts out the difference between wrapped packets - * and unwrapped packets. - */ - public static class PacketDispatcher { - BiConsumer packetSink; - - PacketDispatcher(final BiConsumer packetSink) { - this.packetSink = packetSink; - } - - private PacketDispatcher() { - - } - - public void sendPacket(ResourceLocation resourceLocation, FriendlyByteBuf buffer) { - packetSink.accept(resourceLocation, buffer); - } - - static class NetworkManagerDispatcher extends PacketDispatcher - { - private final Connection manager; - private final int packetIndex; - private final BiFunction, ResourceLocation, ICustomPacket> customPacketSupplier; - - NetworkManagerDispatcher(Connection manager, int packetIndex, BiFunction, ResourceLocation, ICustomPacket> customPacketSupplier) { - super(); - this.packetSink = this::dispatchPacket; - this.manager = manager; - this.packetIndex = packetIndex; - this.customPacketSupplier = customPacketSupplier; - } - - private void dispatchPacket(final ResourceLocation resourceLocation, final FriendlyByteBuf buffer) { - final ICustomPacket packet = this.customPacketSupplier.apply(Pair.of(buffer, packetIndex), resourceLocation); - this.manager.send(packet.getThis()); - } - } - } -} diff --git a/src/main/java/net/minecraftforge/network/NetworkHooks.java b/src/main/java/net/minecraftforge/network/NetworkHooks.java deleted file mode 100644 index 8639d094d2..0000000000 --- a/src/main/java/net/minecraftforge/network/NetworkHooks.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.network; - -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.function.Consumer; -import java.util.function.Supplier; -import java.util.stream.Collectors; - -import io.netty.channel.Channel; -import io.netty.channel.ChannelHandlerContext; -import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.game.ClientGamePacketListener; -import net.minecraftforge.client.ConfigScreenHandler; -import net.minecraftforge.fml.util.thread.EffectiveSide; -import net.minecraftforge.network.ConnectionData.ModMismatchData; -import net.minecraftforge.network.filters.NetworkFilters; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import io.netty.buffer.Unpooled; -import net.minecraft.world.entity.Entity; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; -import net.minecraft.world.MenuProvider; -import net.minecraft.network.protocol.Packet; -import net.minecraft.network.Connection; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.protocol.handshake.ClientIntentionPacket; -import net.minecraft.server.network.ServerLoginPacketListenerImpl; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.core.BlockPos; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.entity.player.PlayerContainerEvent; -import net.minecraftforge.fml.config.ConfigTracker; - -import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.Nullable; - -@ApiStatus.Internal -public class NetworkHooks { - private static final Logger LOGGER = LogManager.getLogger(); - - public static String getFMLVersion(final String ip) { - int idx = ip.indexOf('\0'); - if (idx == -1) - return NetworkConstants.NOVERSION; - - for (var pt : ip.split("\0")) { - if (pt.startsWith("FML")) - return pt; - } - - return NetworkConstants.NOVERSION; - } - - public static ConnectionType getConnectionType(final Supplier connection) { - return getConnectionType(connection.get().channel()); - } - - public static ConnectionType getConnectionType(ChannelHandlerContext context) { - return getConnectionType(context.channel()); - } - - private static ConnectionType getConnectionType(Channel channel) { - return ConnectionType.forVersionFlag(channel.attr(NetworkConstants.FML_NETVERSION).get()); - } - - @SuppressWarnings("unchecked") - public static Packet getEntitySpawningPacket(Entity entity) { - // ClientboundCustomPayloadPacket is an instance of Packet - return (Packet) NetworkConstants.playChannel.toVanillaPacket(new PlayMessages.SpawnEntity(entity), NetworkDirection.PLAY_TO_CLIENT); - } - - public static boolean onCustomPayload(final ICustomPacket packet, final Connection manager) { - return NetworkRegistry.findTarget(packet.getName()). - filter(ni->validateSideForProcessing(packet, ni, manager)). - map(ni->ni.dispatch(packet.getDirection(), packet, manager)).orElse(Boolean.FALSE); - } - - private static boolean validateSideForProcessing(final ICustomPacket packet, final NetworkInstance ni, final Connection manager) { - if (packet.getDirection().getReceptionSide() != EffectiveSide.get()) { - manager.disconnect(Component.literal("Illegal packet received, terminating connection")); - return false; - } - return true; - } - - public static void validatePacketDirection(final NetworkDirection packetDirection, final Optional expectedDirection, final Connection connection) { - if (packetDirection != expectedDirection.orElse(packetDirection)) { - connection.disconnect(Component.literal("Illegal packet received, terminating connection")); - throw new IllegalStateException("Invalid packet received, aborting connection"); - } - } - - public static void registerServerLoginChannel(Connection manager, ClientIntentionPacket packet) { - manager.channel().attr(NetworkConstants.FML_NETVERSION).set(NetworkHooks.getFMLVersion(packet.hostName())); - HandshakeHandler.registerHandshake(manager, NetworkDirection.LOGIN_TO_CLIENT); - } - - public synchronized static void registerClientLoginChannel(Connection manager) { - manager.channel().attr(NetworkConstants.FML_NETVERSION).set(NetworkConstants.NOVERSION); - HandshakeHandler.registerHandshake(manager, NetworkDirection.LOGIN_TO_SERVER); - } - - public synchronized static void sendMCRegistryPackets(Connection manager, String direction) { - NetworkFilters.injectIfNecessary(manager); - final Set resourceLocations = NetworkRegistry.buildChannelVersions().keySet().stream(). - filter(rl -> !Objects.equals(rl.getNamespace(), "minecraft")). - collect(Collectors.toSet()); - MCRegisterPacketHandler.INSTANCE.addChannels(resourceLocations, manager); - MCRegisterPacketHandler.INSTANCE.sendRegistry(manager, NetworkDirection.valueOf(direction)); - } - - public static boolean isVanillaConnection(Connection manager) { - if (manager == null || manager.channel() == null) throw new NullPointerException("ARGH! Network Manager is null (" + manager != null ? "CHANNEL" : "MANAGER"+")" ); - return getConnectionType(() -> manager) == ConnectionType.VANILLA; - } - - public static void handleClientLoginSuccess(Connection manager) { - if (isVanillaConnection(manager)) { - LOGGER.info("Connected to a vanilla server. Catching up missing behaviour."); - ConfigTracker.INSTANCE.loadDefaultServerConfigs(); - } else { - LOGGER.info("Connected to a modded server."); - } - } - - public static boolean tickNegotiation(Connection manager) { - return HandshakeHandler.tickLogin(manager); - } - - /** - * Request to open a GUI on the client, from the server - * - * Refer to {@link ConfigScreenHandler.ConfigScreenFactory} for how to provide a function to consume - * these GUI requests on the client. - * - * @param player The player to open the GUI for - * @param containerSupplier A supplier of container properties including the registry name of the container - */ - public static void openScreen(ServerPlayer player, MenuProvider containerSupplier) { - openScreen(player, containerSupplier, buf -> {}); - } - - /** - * Request to open a GUI on the client, from the server - * - * Refer to {@link ConfigScreenHandler.ConfigScreenFactory} for how to provide a function to consume - * these GUI requests on the client. - * - * @param player The player to open the GUI for - * @param containerSupplier A supplier of container properties including the registry name of the container - * @param pos A block pos, which will be encoded into the auxillary data for this request - */ - public static void openScreen(ServerPlayer player, MenuProvider containerSupplier, BlockPos pos) { - openScreen(player, containerSupplier, buf -> buf.writeBlockPos(pos)); - } - - /** - * Request to open a GUI on the client, from the server - * - * Refer to {@link ConfigScreenHandler.ConfigScreenFactory} for how to provide a function to consume - * these GUI requests on the client. - * - * The maximum size for #extraDataWriter is 32600 bytes. - * - * @param player The player to open the GUI for - * @param containerSupplier A supplier of container properties including the registry name of the container - * @param extraDataWriter Consumer to write any additional data the GUI needs - */ - public static void openScreen(ServerPlayer player, MenuProvider containerSupplier, Consumer extraDataWriter) { - if (player.level().isClientSide) return; - player.doCloseContainer(); - player.nextContainerCounter(); - int openContainerId = player.containerCounter; - FriendlyByteBuf extraData = new FriendlyByteBuf(Unpooled.buffer()); - extraDataWriter.accept(extraData); - extraData.readerIndex(0); // reset to beginning in case modders read for whatever reason - - FriendlyByteBuf output = new FriendlyByteBuf(Unpooled.buffer()); - output.writeVarInt(extraData.readableBytes()); - output.writeBytes(extraData); - - if (output.readableBytes() > 32600 || output.readableBytes() < 1) { - throw new IllegalArgumentException("Invalid PacketBuffer for openGui, found "+ output.readableBytes()+ " bytes"); - } - var c = containerSupplier.createMenu(openContainerId, player.getInventory(), player); - if (c == null) - return; - MenuType type = c.getType(); - PlayMessages.OpenContainer msg = new PlayMessages.OpenContainer(type, openContainerId, containerSupplier.getDisplayName(), output); - NetworkConstants.playChannel.sendTo(msg, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); - - player.containerMenu = c; - player.initMenu(player.containerMenu); - MinecraftForge.EVENT_BUS.post(new PlayerContainerEvent.Open(player, c)); - } - - /** - * Updates the current ConnectionData instance with new mod or channel data if the old instance did not have either of these yet, - * or creates a new ConnectionData instance with the new data if the current ConnectionData instance doesn't exist yet. - */ - static void appendConnectionData(Connection mgr, Map> modData, Map channels) { - ConnectionData oldData = mgr.channel().attr(NetworkConstants.FML_CONNECTION_DATA).get(); - - oldData = oldData != null ? new ConnectionData(oldData.getModData().isEmpty() ? modData : oldData.getModData(), oldData.getChannels().isEmpty() ? channels : oldData.getChannels()) : new ConnectionData(modData, channels); - mgr.channel().attr(NetworkConstants.FML_CONNECTION_DATA).set(oldData); - } - - @Nullable - public static ConnectionData getConnectionData(Connection mgr) { - return mgr.channel().attr(NetworkConstants.FML_CONNECTION_DATA).get(); - } - - @Nullable - public static ModMismatchData getModMismatchData(Connection mgr) { - return mgr.channel().attr(NetworkConstants.FML_MOD_MISMATCH_DATA).get(); - } - - @Nullable - public static MCRegisterPacketHandler.ChannelList getChannelList(Connection mgr) { - return mgr.channel().attr(NetworkConstants.FML_MC_REGISTRY).get(); - } -} diff --git a/src/main/java/net/minecraftforge/network/NetworkInitialization.java b/src/main/java/net/minecraftforge/network/NetworkInitialization.java index e1500f655d..6370890c8c 100644 --- a/src/main/java/net/minecraftforge/network/NetworkInitialization.java +++ b/src/main/java/net/minecraftforge/network/NetworkInitialization.java @@ -5,118 +5,113 @@ package net.minecraftforge.network; -import net.minecraftforge.network.event.EventNetworkChannel; -import net.minecraftforge.network.simple.SimpleChannel; -import net.minecraftforge.registries.RegistryManager; +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 java.util.Arrays; -import java.util.List; +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; -class NetworkInitialization { +@ApiStatus.Internal +public 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"); + public static final AttributeKey CONTEXT = AttributeKey.newInstance(HANDSHAKE_NAME.toString()); - public static SimpleChannel getHandshakeChannel() { - SimpleChannel handshakeChannel = NetworkRegistry.ChannelBuilder. - named(NetworkConstants.FML_HANDSHAKE_RESOURCE). - clientAcceptedVersions(a -> true). - serverAcceptedVersions(a -> true). - networkProtocolVersion(() -> NetworkConstants.NETVERSION). - simpleChannel(); + public static SimpleChannel LOGIN = ChannelBuilder + .named(LOGIN_NAME) + .optional() + .networkProtocolVersion(0) + .simpleChannel() - handshakeChannel.messageBuilder(HandshakeMessages.C2SAcknowledge.class, 99, NetworkDirection.LOGIN_TO_SERVER). - loginIndex(HandshakeMessages.LoginIndexedMessage::getLoginIndex, HandshakeMessages.LoginIndexedMessage::setLoginIndex). - decoder(HandshakeMessages.C2SAcknowledge::decode). - encoder(HandshakeMessages.C2SAcknowledge::encode). - consumerNetworkThread(HandshakeHandler.indexFirst(HandshakeHandler::handleClientAck)). - add(); + .messageBuilder(LoginWrapper.class) + .decoder(LoginWrapper::decode) + .encoder(LoginWrapper::encode) + .consumerNetworkThread(CONTEXT, ForgePacketHandler::handleLoginWrapper) + .add(); - handshakeChannel.messageBuilder(HandshakeMessages.S2CModData.class, 5, NetworkDirection.LOGIN_TO_CLIENT). - loginIndex(HandshakeMessages.LoginIndexedMessage::getLoginIndex, HandshakeMessages.LoginIndexedMessage::setLoginIndex). - decoder(HandshakeMessages.S2CModData::decode). - encoder(HandshakeMessages.S2CModData::encode). - markAsLoginPacket(). - noResponse(). - consumerNetworkThread(HandshakeHandler.biConsumerFor(HandshakeHandler::handleModData)). - add(); + public static SimpleChannel PLAY = ChannelBuilder + .named(HANDSHAKE_NAME) + .optional() + .networkProtocolVersion(0) + .attribute(CONTEXT, ForgePacketHandler::new) + .simpleChannel() - handshakeChannel.messageBuilder(HandshakeMessages.S2CModList.class, 1, NetworkDirection.LOGIN_TO_CLIENT). - loginIndex(HandshakeMessages.LoginIndexedMessage::getLoginIndex, HandshakeMessages.LoginIndexedMessage::setLoginIndex). - decoder(HandshakeMessages.S2CModList::decode). - encoder(HandshakeMessages.S2CModList::encode). - markAsLoginPacket(). - consumerNetworkThread(HandshakeHandler.biConsumerFor(HandshakeHandler::handleServerModListOnClient)). - add(); + .messageBuilder(Acknowledge.class, NetworkDirection.PLAY_TO_SERVER) + .decoder(Acknowledge::decode) + .encoder(Acknowledge::encode) + .consumerNetworkThread(CONTEXT, ForgePacketHandler::handleClientAck) + .add() - handshakeChannel.messageBuilder(HandshakeMessages.C2SModListReply.class, 2, NetworkDirection.LOGIN_TO_SERVER). - loginIndex(HandshakeMessages.LoginIndexedMessage::getLoginIndex, HandshakeMessages.LoginIndexedMessage::setLoginIndex). - decoder(HandshakeMessages.C2SModListReply::decode). - encoder(HandshakeMessages.C2SModListReply::encode). - consumerNetworkThread(HandshakeHandler.indexFirst(HandshakeHandler::handleClientModListOnServer)). - add(); + .messageBuilder(ModVersions.class) + .decoder(ModVersions::decode) + .encoder(ModVersions::encode) + .consumerNetworkThread(CONTEXT, ForgePacketHandler::handleModVersions) + .add() - handshakeChannel.messageBuilder(HandshakeMessages.S2CRegistry.class, 3, NetworkDirection.LOGIN_TO_CLIENT). - loginIndex(HandshakeMessages.LoginIndexedMessage::getLoginIndex, HandshakeMessages.LoginIndexedMessage::setLoginIndex). - decoder(HandshakeMessages.S2CRegistry::decode). - encoder(HandshakeMessages.S2CRegistry::encode). - buildLoginPacketList(RegistryManager::generateRegistryPackets). //TODO: Make this non-static, and store a cache on the client. - consumerNetworkThread(HandshakeHandler.biConsumerFor(HandshakeHandler::handleRegistryMessage)). - add(); + .messageBuilder(ChannelVersions.class) + .decoder(ChannelVersions::decode) + .encoder(ChannelVersions::encode) + .consumerNetworkThread(CONTEXT, ForgePacketHandler::handleChannelVersions) + .add() - handshakeChannel.messageBuilder(HandshakeMessages.S2CConfigData.class, 4, NetworkDirection.LOGIN_TO_CLIENT). - loginIndex(HandshakeMessages.LoginIndexedMessage::getLoginIndex, HandshakeMessages.LoginIndexedMessage::setLoginIndex). - decoder(HandshakeMessages.S2CConfigData::decode). - encoder(HandshakeMessages.S2CConfigData::encode). - buildLoginPacketList(ConfigSync.INSTANCE::syncConfigs). - consumerNetworkThread(HandshakeHandler.biConsumerFor(HandshakeHandler::handleConfigSync)). - add(); + .messageBuilder(RegistryList.class, NetworkDirection.PLAY_TO_CLIENT) + .decoder(RegistryList::decode) + .encoder(RegistryList::encode) + .consumerNetworkThread(CONTEXT, ForgePacketHandler::handleRegistryList) + .add() - handshakeChannel.messageBuilder(HandshakeMessages.S2CChannelMismatchData.class, 6, NetworkDirection.LOGIN_TO_CLIENT). - loginIndex(HandshakeMessages.LoginIndexedMessage::getLoginIndex, HandshakeMessages.LoginIndexedMessage::setLoginIndex). - decoder(HandshakeMessages.S2CChannelMismatchData::decode). - encoder(HandshakeMessages.S2CChannelMismatchData::encode). - consumerNetworkThread(HandshakeHandler.biConsumerFor(HandshakeHandler::handleModMismatchData)). - add(); + .messageBuilder(RegistryData.class, NetworkDirection.PLAY_TO_CLIENT) + .decoder(RegistryData::decode) + .encoder(RegistryData::encode) + .consumerNetworkThread(CONTEXT, ForgePacketHandler::handleRegistryData) + .add() - return handshakeChannel; + .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) + .decoder(SpawnEntity::decode) + .encoder(SpawnEntity::encode) + .consumerNetworkThread(SpawnEntity::handle) + .add() + + .messageBuilder(OpenContainer.class) + .decoder(OpenContainer::decode) + .encoder(OpenContainer::encode) + .consumerNetworkThread(OpenContainer::handle) + .add(); + + public static void init() { + for (var channel : new Channel[]{ LOGIN, PLAY, ChannelListManager.REGISTER, ChannelListManager.UNREGISTER}) + LOGGER.debug(MARKER, "Registering Network {} v{}", channel.getName(), channel.getProtocolVersion()); } - public static SimpleChannel getPlayChannel() { - SimpleChannel playChannel = NetworkRegistry.ChannelBuilder. - named(NetworkConstants.FML_PLAY_RESOURCE). - clientAcceptedVersions(a -> true). - serverAcceptedVersions(a -> true). - networkProtocolVersion(() -> NetworkConstants.NETVERSION). - simpleChannel(); - - playChannel.messageBuilder(PlayMessages.SpawnEntity.class, 0). - decoder(PlayMessages.SpawnEntity::decode). - encoder(PlayMessages.SpawnEntity::encode). - consumerNetworkThread(PlayMessages.SpawnEntity::handle). - add(); - - playChannel.messageBuilder(PlayMessages.OpenContainer.class,1). - decoder(PlayMessages.OpenContainer::decode). - encoder(PlayMessages.OpenContainer::encode). - consumerNetworkThread(PlayMessages.OpenContainer::handle). - add(); - - return playChannel; - } - - public static List buildMCRegistrationChannels() { - final EventNetworkChannel mcRegChannel = NetworkRegistry.ChannelBuilder. - named(NetworkConstants.MC_REGISTER_RESOURCE). - clientAcceptedVersions(a -> true). - serverAcceptedVersions(a -> true). - networkProtocolVersion(() -> NetworkConstants.NETVERSION). - eventNetworkChannel(); - mcRegChannel.addListener(MCRegisterPacketHandler.INSTANCE::registerListener); - final EventNetworkChannel mcUnregChannel = NetworkRegistry.ChannelBuilder. - named(NetworkConstants.MC_UNREGISTER_RESOURCE). - clientAcceptedVersions(a -> true). - serverAcceptedVersions(a -> true). - networkProtocolVersion(() -> NetworkConstants.NETVERSION). - eventNetworkChannel(); - mcUnregChannel.addListener(MCRegisterPacketHandler.INSTANCE::unregisterListener); - return Arrays.asList(mcRegChannel, mcUnregChannel); + public static int getVersion() { + return PLAY.getProtocolVersion(); } } diff --git a/src/main/java/net/minecraftforge/network/NetworkInstance.java b/src/main/java/net/minecraftforge/network/NetworkInstance.java index 7d962b6ff7..d0d7ec3e0b 100644 --- a/src/main/java/net/minecraftforge/network/NetworkInstance.java +++ b/src/main/java/net/minecraftforge/network/NetworkInstance.java @@ -7,50 +7,54 @@ package net.minecraftforge.network; import net.minecraft.network.Connection; import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.event.network.CustomPayloadEvent; import net.minecraftforge.eventbus.api.BusBuilder; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.eventbus.api.IEventListener; +import net.minecraftforge.network.Channel.VersionTest; -import java.util.List; +import java.util.Map; import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.function.Supplier; +import java.util.function.Function; +import org.jetbrains.annotations.ApiStatus; -public class NetworkInstance -{ - public ResourceLocation getChannelName() - { - return channelName; - } +import io.netty.util.AttributeKey; +/** + * This is essentially the shared common class for {@link SimpleChannel} and {@link EventNetworkChannel}. + * I've now introduced {@link Channel} as that common modder facing base class. I am basically using this + * 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... private final ResourceLocation channelName; - private final String networkProtocolVersion; - private final Predicate clientAcceptedVersions; - private final Predicate serverAcceptedVersions; - private final IEventBus networkEventBus; + private final int networkProtocolVersion; + final VersionTest clientAcceptedVersions; + final VersionTest serverAcceptedVersions; + final Map, Function> attributes; + final Consumer channelHandler; + final ServerStatusPing.ChannelData pingData; - NetworkInstance(ResourceLocation channelName, Supplier networkProtocolVersion, Predicate clientAcceptedVersions, Predicate serverAcceptedVersions) - { + NetworkInstance(ResourceLocation channelName, int networkProtocolVersion, + VersionTest clientAcceptedVersions, VersionTest serverAcceptedVersions, + Map, Function> attributes, Consumer channelHandler + ) { this.channelName = channelName; - this.networkProtocolVersion = networkProtocolVersion.get(); + this.networkProtocolVersion = networkProtocolVersion; this.clientAcceptedVersions = clientAcceptedVersions; this.serverAcceptedVersions = serverAcceptedVersions; + this.attributes = attributes; + this.channelHandler = channelHandler; this.networkEventBus = BusBuilder.builder().setExceptionHandler(this::handleError).useModLauncher().build(); + this.pingData = new ServerStatusPing.ChannelData(channelName, networkProtocolVersion, this.clientAcceptedVersions.accepts(VersionTest.Status.MISSING, -1)); } - private void handleError(IEventBus iEventBus, Event event, IEventListener[] iEventListeners, int i, Throwable throwable) - { - + private void handleError(IEventBus iEventBus, Event event, IEventListener[] iEventListeners, int i, Throwable throwable) { } - public void addListener(Consumer eventListener) - { - this.networkEventBus.addListener(eventListener); - } - - public void addGatherListener(Consumer eventListener) - { + public void addListener(Consumer eventListener) { this.networkEventBus.addListener(eventListener); } @@ -62,42 +66,20 @@ public class NetworkInstance this.networkEventBus.unregister(object); } - boolean dispatch(final NetworkDirection side, final ICustomPacket packet, final Connection manager) - { - final NetworkEvent.Context context = new NetworkEvent.Context(manager, side, packet.getIndex()); - this.networkEventBus.post(side.getEvent(packet, () -> context)); - return context.getPacketHandled(); + public boolean dispatch(CustomPayloadEvent event) { + this.networkEventBus.post(event); + return event.getSource().getPacketHandled(); } - String getNetworkProtocolVersion() { + ResourceLocation getChannelName() { + return channelName; + } + + int getNetworkProtocolVersion() { return networkProtocolVersion; } - boolean tryServerVersionOnClient(final String serverVersion) { - return this.clientAcceptedVersions.test(serverVersion); - } - - boolean tryClientVersionOnServer(final String clientVersion) { - return this.serverAcceptedVersions.test(clientVersion); - } - - void dispatchGatherLogin(final List loginPayloadList, boolean isLocal) { - this.networkEventBus.post(new NetworkEvent.GatherLoginPayloadsEvent(loginPayloadList, isLocal)); - } - - void dispatchLoginPacket(final NetworkEvent.LoginPayloadEvent loginPayloadEvent) { - this.networkEventBus.post(loginPayloadEvent); - } - - void dispatchEvent(final NetworkEvent networkEvent) { - this.networkEventBus.post(networkEvent); - } - - public boolean isRemotePresent(Connection manager) { - ConnectionData connectionData = NetworkHooks.getConnectionData(manager); - MCRegisterPacketHandler.ChannelList channelList = NetworkHooks.getChannelList(manager); - return (connectionData != null && connectionData.getChannels().containsKey(channelName)) - // if it's not in the fml connection data, let's check if it's sent by another modloader. - || (channelList != null && channelList.getRemoteLocations().contains(channelName)); + void registrationChange(boolean registered) { + // TODO: Expose to listeners? } } diff --git a/src/main/java/net/minecraftforge/network/NetworkRegistry.java b/src/main/java/net/minecraftforge/network/NetworkRegistry.java index 3dfabbc892..6361bcce72 100644 --- a/src/main/java/net/minecraftforge/network/NetworkRegistry.java +++ b/src/main/java/net/minecraftforge/network/NetworkRegistry.java @@ -6,435 +6,177 @@ package net.minecraftforge.network; import net.minecraft.network.Connection; -import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.network.event.EventNetworkChannel; -import net.minecraftforge.network.simple.SimpleChannel; +import net.minecraftforge.event.ForgeEventFactory; +import net.minecraftforge.network.Channel.VersionTest; +import net.minecraftforge.network.NetworkContext.NetworkMismatchData; import net.minecraftforge.registries.DataPackRegistriesHooks; -import org.apache.commons.lang3.tuple.Pair; 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 org.jetbrains.annotations.Nullable; + +import io.netty.util.Attribute; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import java.util.HashSet; -import java.util.function.BiFunction; -import java.util.function.Predicate; -import java.util.function.Supplier; +import java.util.function.Function; import java.util.stream.Collectors; +import java.util.stream.Stream; /** - * The impl registry. Tracks channels on behalf of mods. + * Tracks channels created by {@link ChannelBuilder}. This class is not intended for use by modders. */ -public class NetworkRegistry -{ - private static final Logger LOGGER = LogManager.getLogger(); - private static final Marker NETREGISTRY = MarkerManager.getMarker("NETREGISTRY"); +@ApiStatus.Internal +public class NetworkRegistry { + static final Logger LOGGER = LogManager.getLogger(); + static final Marker NETREGISTRY = MarkerManager.getMarker("NETREGISTRY"); - private static Map instances = Collections.synchronizedMap(new HashMap<>()); - - /** - * Special value for clientAcceptedVersions and serverAcceptedVersions predicates indicating the other side lacks - * this channel. - */ - public static ServerStatusPing.ChannelData ABSENT = new ServerStatusPing.ChannelData(new ResourceLocation("absent"), "ABSENT \uD83E\uDD14", false); - - public static String ACCEPTVANILLA = new String("ALLOWVANILLA \uD83D\uDC93\uD83D\uDC93\uD83D\uDC93"); - - /** - * Makes a version predicate that accepts connections to vanilla or without the channel. - * @param protocolVersion The protocol version, which will be matched exactly. - * @return A new predicate with the new conditions. - */ - public static Predicate acceptMissingOr(final String protocolVersion) - { - return acceptMissingOr(protocolVersion::equals); - } - - /** - * Makes a version predicate that accepts connections to vanilla or without the channel. - * @param versionCheck The main version predicate, which should check the version number of the protocol. - * @return A new predicate with the new conditions. - */ - public static Predicate acceptMissingOr(Predicate versionCheck) - { - return versionCheck.or(ABSENT.version()::equals).or(ACCEPTVANILLA::equals); - } - - public static List getServerNonVanillaNetworkMods() - { - return listRejectedVanillaMods(NetworkInstance::tryClientVersionOnServer); - } - - public static List getClientNonVanillaNetworkMods() - { - return listRejectedVanillaMods(NetworkInstance::tryServerVersionOnClient); - } + static Map instances = Collections.synchronizedMap(new HashMap<>()); public static boolean acceptsVanillaClientConnections() { - return (instances.isEmpty() || getServerNonVanillaNetworkMods().isEmpty()) && DataPackRegistriesHooks.getSyncedCustomRegistries().isEmpty(); + return (instances.isEmpty() || listRejectedVanillaMods(n -> n.clientAcceptedVersions).isEmpty()) && DataPackRegistriesHooks.getSyncedCustomRegistries().isEmpty(); } public static boolean canConnectToVanillaServer() { - return instances.isEmpty() || getClientNonVanillaNetworkMods().isEmpty(); + return instances.isEmpty() || listRejectedVanillaMods(n -> n.serverAcceptedVersions).isEmpty(); } - - /** - * Create a new {@link SimpleChannel}. - * - * @param name The registry name for this channel. Must be unique - * @param networkProtocolVersion The impl protocol version string that will be offered to the remote side {@link ChannelBuilder#networkProtocolVersion(Supplier)} - * @param clientAcceptedVersions Called on the client with the networkProtocolVersion string from the server {@link ChannelBuilder#clientAcceptedVersions(Predicate)} - * @param serverAcceptedVersions Called on the server with the networkProtocolVersion string from the client {@link ChannelBuilder#serverAcceptedVersions(Predicate)} - * @return A new {@link SimpleChannel} - * - * @see ChannelBuilder#newSimpleChannel(ResourceLocation, Supplier, Predicate, Predicate) - */ - public static SimpleChannel newSimpleChannel(final ResourceLocation name, Supplier networkProtocolVersion, Predicate clientAcceptedVersions, Predicate serverAcceptedVersions) { - return new SimpleChannel(createInstance(name, networkProtocolVersion, clientAcceptedVersions, serverAcceptedVersions)); + @Nullable + public static NetworkInstance findTarget(ResourceLocation resourceLocation) { + return instances.get(resourceLocation); } - /** - * Create a new {@link EventNetworkChannel}. - * - * @param name The registry name for this channel. Must be unique - * @param networkProtocolVersion The impl protocol version string that will be offered to the remote side {@link ChannelBuilder#networkProtocolVersion(Supplier)} - * @param clientAcceptedVersions Called on the client with the networkProtocolVersion string from the server {@link ChannelBuilder#clientAcceptedVersions(Predicate)} - * @param serverAcceptedVersions Called on the server with the networkProtocolVersion string from the client {@link ChannelBuilder#serverAcceptedVersions(Predicate)} - - * @return A new {@link EventNetworkChannel} - * - * @see ChannelBuilder#newEventChannel(ResourceLocation, Supplier, Predicate, Predicate) - */ - public static EventNetworkChannel newEventChannel(final ResourceLocation name, Supplier networkProtocolVersion, Predicate clientAcceptedVersions, Predicate serverAcceptedVersions) { - return new EventNetworkChannel(createInstance(name, networkProtocolVersion, clientAcceptedVersions, serverAcceptedVersions)); - } - - /** - * Creates the internal {@link NetworkInstance} that tracks the channel data. - * @param name registry name - * @param networkProtocolVersion The protocol version string - * @param clientAcceptedVersions The client accepted predicate - * @param serverAcceptedVersions The server accepted predicate - * @return The {@link NetworkInstance} - * @throws IllegalArgumentException if the name already exists - */ - private static NetworkInstance createInstance(ResourceLocation name, Supplier networkProtocolVersion, Predicate clientAcceptedVersions, Predicate serverAcceptedVersions) - { - if(lock) { - LOGGER.error(NETREGISTRY, "Attempted to register channel {} even though registry phase is over", name); - throw new IllegalArgumentException("Registration of impl channels is locked"); - } - if (instances.containsKey(name)) { - LOGGER.error(NETREGISTRY, "NetworkDirection channel {} already registered.", name); - throw new IllegalArgumentException("NetworkDirection Channel {"+ name +"} already registered"); - } - final NetworkInstance networkInstance = new NetworkInstance(name, networkProtocolVersion, clientAcceptedVersions, serverAcceptedVersions); - instances.put(name, networkInstance); - return networkInstance; - } - - /** - * Find the {@link NetworkInstance}, if possible - * - * @param resourceLocation The impl instance to lookup - * @return The {@link Optional} {@link NetworkInstance} - */ - static Optional findTarget(ResourceLocation resourceLocation) - { - return Optional.ofNullable(instances.get(resourceLocation)); - } - - /** - * Construct the Map representation of the channel list, for use during login handshaking - * - * @see HandshakeMessages.S2CModList - * @see HandshakeMessages.C2SModListReply - */ - static Map buildChannelVersions() { - return instances.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getNetworkProtocolVersion())); - } - - /** - * Construct the Map representation of the channel list, for the client to check against during list ping - * - * @see HandshakeMessages.S2CModList - * @see HandshakeMessages.C2SModListReply - */ static Map buildChannelVersionsForListPing() { - return instances.entrySet().stream(). - filter(p -> !p.getKey().getNamespace().equals("fml")). - collect(Collectors.toMap(Map.Entry::getKey, val -> new ServerStatusPing.ChannelData(val.getKey(), val.getValue().getNetworkProtocolVersion(), val.getValue().tryClientVersionOnServer(ABSENT.version())))); + return instances.entrySet().stream() + .filter(p -> !p.getKey().getNamespace().equals("forge")) + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().pingData)); } - static List listRejectedVanillaMods(BiFunction testFunction) { - final List> results = instances.values().stream(). - map(ni -> { - final String incomingVersion = ACCEPTVANILLA; - final boolean test = testFunction.apply(ni, incomingVersion); - LOGGER.debug(NETREGISTRY, "Channel '{}' : Vanilla acceptance test: {}", ni.getChannelName(), test ? "ACCEPTED" : "REJECTED"); - return Pair.of(ni.getChannelName(), test); - }).filter(p->!p.getRight()).toList(); + static List listRejectedVanillaMods(Function testFunction) { + var results = new ArrayList(); + for (var net : instances.values()) { + boolean test = testFunction.apply(net).accepts(VersionTest.Status.VANILLA, -1); + LOGGER.debug(NETREGISTRY, "Channel '{}' : Vanilla acceptance test: {}", net.getChannelName(), test ? "ACCEPTED" : "REJECTED"); + if (!test) + results.add(net.getChannelName().toString()); + } if (!results.isEmpty()) { - LOGGER.error(NETREGISTRY, "Channels [{}] rejected vanilla connections", - results.stream().map(Pair::getLeft).map(Object::toString).collect(Collectors.joining(","))); - return results.stream().map(Pair::getLeft).map(Object::toString).collect(Collectors.toList()); + LOGGER.error(NETREGISTRY, "Channels [{}] rejected vanilla connections", String.join(", ", results)); + return results; } + LOGGER.debug(NETREGISTRY, "Accepting channel list from vanilla"); return Collections.emptyList(); } - /** - * Validate the channels from the server on the client. Tests the client predicates against the server - * supplied impl protocol version. - * - * @param channels An @{@link Map} of name->version pairs for testing - * @return a map of mismatched channel ids and versions, or an empty map if all channels accept themselves - */ - static Map validateClientChannels(final Map channels) { - return validateChannels(channels, "server", NetworkInstance::tryServerVersionOnClient); - } - /** - * Validate the channels from the client on the server. Tests the server predicates against the client - * supplied impl protocol version. - * @param channels An @{@link Map} of name->version pairs for testing - * @return a map of mismatched channel ids and versions, or an empty map if all channels accept themselves - */ - static Map validateServerChannels(final Map channels) { - return validateChannels(channels, "client", NetworkInstance::tryClientVersionOnServer); - } + @Nullable + public static NetworkMismatchData validateChannels(Map incoming, boolean fromClient) { + var originName = fromClient ? "client" : "server"; - /** - * Tests if the map matches with the supplied predicate tester - * - * @param incoming An @{@link Map} of name->version pairs for testing - * @param originName A label for use in logging (where the version pairs came from) - * @param testFunction The test function to use for testing - * @return a map of mismatched channel ids and versions, or an empty map if all channels accept themselves - */ - private static Map validateChannels(final Map incoming, final String originName, BiFunction testFunction) { - final Map results = instances.values().stream(). - map(ni -> { - final String incomingVersion = incoming.getOrDefault(ni.getChannelName(), ABSENT.version()); - final boolean test = testFunction.apply(ni, incomingVersion); - LOGGER.debug(NETREGISTRY, "Channel '{}' : Version test of '{}' from {} : {}", ni.getChannelName(), incomingVersion, originName, test ? "ACCEPTED" : "REJECTED"); - return Pair.of(Pair.of(ni.getChannelName(), incomingVersion), test); - }).filter(p->!p.getRight()).map(Pair::getLeft).collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); + Set missing = new HashSet<>(); + Map results = new HashMap<>(); + instances.forEach((name, net) -> { + VersionTest test = fromClient ? net.clientAcceptedVersions : net.serverAcceptedVersions; - if (!results.isEmpty()) { + var status = VersionTest.Status.MISSING; + var version = 0; + if (incoming.containsKey(net.getChannelName())) { + status = VersionTest.Status.PRESENT; + version = incoming.get(net.getChannelName()); + } + + boolean accepted = test.accepts(status, version); + LOGGER.debug(NETREGISTRY, "Channel '{}' : Version test of '{} {}' from {} : {}", name, status, version, originName, accepted ? "ACCEPTED" : "REJECTED"); + + if (!accepted) { + if (status == VersionTest.Status.MISSING) + missing.add(name); + else + results.put(name, new NetworkMismatchData.Version(Integer.toString(version), Integer.toString(net.getNetworkProtocolVersion()))); + } + }); + + if (!results.isEmpty() || !missing.isEmpty()) { LOGGER.error(NETREGISTRY, "Channels [{}] rejected their {} side version number", - results.keySet().stream().map(Object::toString).collect(Collectors.joining(",")), - originName); - return results; + Stream.concat(missing.stream(), results.keySet().stream()).map(Object::toString).collect(Collectors.joining(",")), originName); + return new NetworkMismatchData(results, missing, !fromClient, null); } - LOGGER.debug(NETREGISTRY, "Accepting channel list from {}", originName); - return results; - } - /** - * Retrieve the {@link LoginPayload} list for dispatch during {@link HandshakeHandler#tickLogin(Connection)} handling. - * Dispatches {@link NetworkEvent.GatherLoginPayloadsEvent} to each {@link NetworkInstance}. - * - * @return The {@link LoginPayload} list - * @param direction the impl direction for the request - only gathers for LOGIN_TO_CLIENT - */ - static List gatherLoginPayloads(final NetworkDirection direction, boolean isLocal) { - if (direction!=NetworkDirection.LOGIN_TO_CLIENT) return Collections.emptyList(); - List gatheredPayloads = new ArrayList<>(); - instances.values().forEach(ni->ni.dispatchGatherLogin(gatheredPayloads, isLocal)); - return gatheredPayloads; + LOGGER.debug(NETREGISTRY, "Accepting channel list from {}", originName); + return null; } public static boolean checkListPingCompatibilityForClient(Map incoming) { Set handled = new HashSet<>(); - final List> results = instances.values().stream(). - filter(p -> !p.getChannelName().getNamespace().equals("fml")). - map(ni -> { - final ServerStatusPing.ChannelData incomingVersion = incoming.getOrDefault(ni.getChannelName(), ABSENT); - final boolean test = ni.tryServerVersionOnClient(incomingVersion.version()); - handled.add(ni.getChannelName()); - LOGGER.debug(NETREGISTRY, "Channel '{}' : Version test of '{}' during listping : {}", ni.getChannelName(), incomingVersion, test ? "ACCEPTED" : "REJECTED"); - return Pair.of(ni.getChannelName(), test); - }).filter(p->!p.getRight()).collect(Collectors.toList()); - final List missingButRequired = incoming.entrySet().stream(). - filter(p -> !p.getKey().getNamespace().equals("fml")). - filter(p -> !p.getValue().required()). - filter(p -> !handled.contains(p.getKey())). - map(Map.Entry::getKey). - collect(Collectors.toList()); + var rejected = new ArrayList(); - if (!results.isEmpty()) { - LOGGER.error(NETREGISTRY, "Channels [{}] rejected their server side version number during listping", - results.stream().map(Pair::getLeft).map(Object::toString).collect(Collectors.joining(","))); + for (var net : instances.values()) { + var status = VersionTest.Status.MISSING; + var version = 0; + if (incoming.containsKey(net.getChannelName())) { + status = VersionTest.Status.PRESENT; + version = incoming.get(net.getChannelName()).version(); + } + + boolean accepted = net.serverAcceptedVersions.accepts(status, version); + LOGGER.debug(NETREGISTRY, "Channel '{}' : Version test of '{} {}' during listping : {}", net.getChannelName(), status, version, accepted ? "ACCEPTED" : "REJECTED"); + + if (!accepted) + rejected.add(net.getChannelName().toString()); + handled.add(net.getChannelName()); + } + + var missingButRequired = new ArrayList(); + incoming.forEach((name, data) -> { + if (data.required() && !handled.contains(name)) + missingButRequired.add(name.toString()); + }); + + if (!rejected.isEmpty()) { + LOGGER.error(NETREGISTRY, "Channels [{}] rejected their server side version number during listping", String.join(", ", rejected)); return false; } - if(!missingButRequired.isEmpty()){ - LOGGER.error(NETREGISTRY, "The server is likely to require channel [{}] to be present, yet we don't have it", - missingButRequired); + + if (!missingButRequired.isEmpty()) { + LOGGER.error(NETREGISTRY, "The server is likely to require channel [{}] to be present, yet we don't have it", String.join(", ", missingButRequired)); return false; } + LOGGER.debug(NETREGISTRY, "Accepting channel list during listping"); return true; } - private static boolean lock = false; - public boolean isLocked(){ - return lock; - } - + static boolean lock = false; public static void lock() { - lock=true; + lock = true; } - /** - * Tracks individual outbound messages for dispatch to clients during login handling. Gathered by dispatching - * {@link NetworkEvent.GatherLoginPayloadsEvent} during early connection handling. - */ - public static class LoginPayload { - /** - * The data for sending - */ - private final FriendlyByteBuf data; - /** - * A channel which will receive a {@link NetworkEvent.LoginPayloadEvent} from the {@link LoginWrapper} - */ - private final ResourceLocation channelName; - - /** - * Some context for logging purposes - */ - private final String messageContext; - - /** - * If the connection should await a response to this packet to continue with the handshake - */ - private final boolean needsResponse; - - public LoginPayload(final FriendlyByteBuf buffer, final ResourceLocation channelName, final String messageContext) { - this(buffer, channelName, messageContext, true); - } - - public LoginPayload(final FriendlyByteBuf buffer, final ResourceLocation channelName, final String messageContext, final boolean needsResponse) - { - this.data = buffer; - this.channelName = channelName; - this.messageContext = messageContext; - this.needsResponse = needsResponse; - } - - public FriendlyByteBuf getData() { - return data; - } - - public ResourceLocation getChannelName() { - return channelName; - } - - public String getMessageContext() { - return messageContext; - } - - public boolean needsResponse() - { - return needsResponse; + @SuppressWarnings("unchecked") + public static void onConnectionStart(Connection connection) { + ForgeEventFactory.onConnectionStart(connection); + var channel = connection.channel(); + for (var inst : instances.values()) { + if (inst.attributes != null) + inst.attributes.forEach((k, v) -> ((Attribute)channel.attr(k)).compareAndSet(null, (Object)v.apply(connection))); + if (inst.channelHandler != null) + inst.channelHandler.accept(connection); } } - /** - * Builder for constructing impl channels using a builder style API. - */ - public static class ChannelBuilder { - private ResourceLocation channelName; - private Supplier networkProtocolVersion; - private Predicate clientAcceptedVersions; - private Predicate serverAcceptedVersions; - - /** - * The name of the channel. Must be unique. - * @param channelName The name of the channel - * @return the channel builder - */ - public static ChannelBuilder named(ResourceLocation channelName) - { - ChannelBuilder builder = new ChannelBuilder(); - builder.channelName = channelName; - return builder; - } - - /** - * The impl protocol string for this channel. This will be gathered during login and sent to - * the remote partner, where it will be tested with against the relevant predicate. - * - * @see #serverAcceptedVersions(Predicate) - * @see #clientAcceptedVersions(Predicate) - * @param networkProtocolVersion A supplier of strings for impl protocol version testing - * @return the channel builder - */ - public ChannelBuilder networkProtocolVersion(Supplier networkProtocolVersion) - { - this.networkProtocolVersion = networkProtocolVersion; - return this; - } - - /** - * A predicate run on the client, with the {@link #networkProtocolVersion(Supplier)} string from - * the server, or the special value {@link NetworkRegistry#ABSENT} indicating the absence of - * the channel on the remote side. - * @param clientAcceptedVersions A predicate for testing - * @return the channel builder - */ - public ChannelBuilder clientAcceptedVersions(Predicate clientAcceptedVersions) - { - this.clientAcceptedVersions = clientAcceptedVersions; - return this; - } - - /** - * A predicate run on the server, with the {@link #networkProtocolVersion(Supplier)} string from - * the server, or the special value {@link NetworkRegistry#ABSENT} indicating the absence of - * the channel on the remote side. - * @param serverAcceptedVersions A predicate for testing - * @return the channel builder - */ - public ChannelBuilder serverAcceptedVersions(Predicate serverAcceptedVersions) - { - this.serverAcceptedVersions = serverAcceptedVersions; - return this; - } - - /** - * Create the impl instance - * @return the {@link NetworkInstance} - */ - private NetworkInstance createNetworkInstance() { - return createInstance(channelName, networkProtocolVersion, clientAcceptedVersions, serverAcceptedVersions); - } - - /** - * Build a new {@link SimpleChannel} with this builder's configuration. - * - * @return A new {@link SimpleChannel} - */ - public SimpleChannel simpleChannel() { - return new SimpleChannel(createNetworkInstance()); - } - - /** - * Build a new {@link EventNetworkChannel} with this builder's configuration. - * @return A new {@link EventNetworkChannel} - */ - public EventNetworkChannel eventNetworkChannel() { - return new EventNetworkChannel(createNetworkInstance()); - } + public static Map buildChannelVersions() { + var ret = new Object2IntOpenHashMap(instances.size()); + instances.forEach((k, v) -> ret.put(k, v.getNetworkProtocolVersion())); + return ret; } } diff --git a/src/main/java/net/minecraftforge/network/PacketDistributor.java b/src/main/java/net/minecraftforge/network/PacketDistributor.java index b6874491d0..0deb9ee8f2 100644 --- a/src/main/java/net/minecraftforge/network/PacketDistributor.java +++ b/src/main/java/net/minecraftforge/network/PacketDistributor.java @@ -15,46 +15,45 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.Level; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.server.level.ServerChunkCache; -import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.server.ServerLifecycleHooks; import java.util.List; import java.util.function.BiFunction; import java.util.function.Consumer; -import java.util.function.Supplier; +import org.jetbrains.annotations.Nullable; /** * Means to distribute packets in various ways * - * @see SimpleChannel#send(PacketTarget, Object) + * @see Channel#send(Object, PacketTarget) * * @param */ -public class PacketDistributor { +public record PacketDistributor(BiFunction, T, Consumer>> functor, NetworkDirection direction) { /** * Send to the player specified in the Supplier *
- * {@link #with(Supplier)} Player + * {@link #with(T)} Player */ - public static final PacketDistributor PLAYER = new PacketDistributor<>(PacketDistributor::playerConsumer, NetworkDirection.PLAY_TO_CLIENT); + public static final PacketDistributor PLAYER = new PacketDistributor<>(PacketDistributor::playerConsumer); /** * Send to everyone in the dimension specified in the Supplier *
- * {@link #with(Supplier)} DimensionType + * {@link #with(T)} DimensionType */ - public static final PacketDistributor> DIMENSION = new PacketDistributor<>(PacketDistributor::playerListDimConsumer, NetworkDirection.PLAY_TO_CLIENT); + public static final PacketDistributor> DIMENSION = new PacketDistributor<>(PacketDistributor::playerListDimConsumer); /** * Send to everyone near the {@link TargetPoint} specified in the Supplier *
- * {@link #with(Supplier)} TargetPoint + * {@link #with(T)} TargetPoint */ - public static final PacketDistributor NEAR = new PacketDistributor<>(PacketDistributor::playerListPointConsumer, NetworkDirection.PLAY_TO_CLIENT); + public static final PacketDistributor NEAR = new PacketDistributor<>(PacketDistributor::playerListPointConsumer); /** * Send to everyone *
* {@link #noArg()} */ - public static final PacketDistributor ALL = new PacketDistributor<>(PacketDistributor::playerListAll, NetworkDirection.PLAY_TO_CLIENT); + public static final PacketDistributor ALL = new PacketDistributor<>(PacketDistributor::playerListAll); /** * Send to the server (CLIENT to SERVER) *
@@ -64,119 +63,50 @@ public class PacketDistributor { /** * Send to all tracking the Entity in the Supplier *
- * {@link #with(Supplier)} Entity + * {@link #with(T)} Entity */ - public static final PacketDistributor TRACKING_ENTITY = new PacketDistributor<>(PacketDistributor::trackingEntity, NetworkDirection.PLAY_TO_CLIENT); + public static final PacketDistributor TRACKING_ENTITY = new PacketDistributor<>(PacketDistributor::trackingEntity); /** * Send to all tracking the Entity and Player in the Supplier *
- * {@link #with(Supplier)} Entity + * {@link #with(T)} Entity */ - public static final PacketDistributor TRACKING_ENTITY_AND_SELF = new PacketDistributor<>(PacketDistributor::trackingEntityAndSelf, NetworkDirection.PLAY_TO_CLIENT); + public static final PacketDistributor TRACKING_ENTITY_AND_SELF = new PacketDistributor<>(PacketDistributor::trackingEntityAndSelf); /** * Send to all tracking the Chunk in the Supplier *
- * {@link #with(Supplier)} Chunk + * {@link #with(T)} Chunk */ - public static final PacketDistributor TRACKING_CHUNK = new PacketDistributor<>(PacketDistributor::trackingChunk, NetworkDirection.PLAY_TO_CLIENT); + public static final PacketDistributor TRACKING_CHUNK = new PacketDistributor<>(PacketDistributor::trackingChunk); /** * Send to the supplied list of NetworkManager instances in the Supplier *
- * {@link #with(Supplier)} List of NetworkManager + * {@link #with(T)} List of NetworkManager */ - public static final PacketDistributor> NMLIST = new PacketDistributor<>(PacketDistributor::networkManagerList, NetworkDirection.PLAY_TO_CLIENT); - - public static final class TargetPoint { - - private final ServerPlayer excluded; - private final double x; - private final double y; - private final double z; - private final double r2; - private final ResourceKey dim; - - /** - * A target point with excluded entity - * - * @param excluded Entity to exclude - * @param x X - * @param y Y - * @param z Z - * @param r2 Radius - * @param dim DimensionType - */ - public TargetPoint(final ServerPlayer excluded, final double x, final double y, final double z, final double r2, final ResourceKey dim) { - this.excluded = excluded; - this.x = x; - this.y = y; - this.z = z; - this.r2 = r2; - this.dim = dim; - } + public static final PacketDistributor> NMLIST = new PacketDistributor<>(PacketDistributor::networkManagerList); + public static record TargetPoint(@Nullable ServerPlayer excluded, double x, double y, double z, double r2, ResourceKey dim) { /** * A target point without excluded entity - * @param x X - * @param y Y - * @param z Z - * @param r2 Radius - * @param dim DimensionType */ - public TargetPoint(final double x, final double y, final double z, final double r2, final ResourceKey dim) { - this.excluded = null; - this.x = x; - this.y = y; - this.z = z; - this.r2 = r2; - this.dim = dim; + public TargetPoint(double x, double y, double z, double r2, ResourceKey dim) { + this(null, x, y, z, r2, dim); } - - /** - * Helper to build a TargetPoint without excluded Entity - * @param x X - * @param y Y - * @param z Z - * @param r2 Radius - * @param dim DimensionType - * @return A TargetPoint supplier - */ - public static Supplier p(double x, double y, double z, double r2, ResourceKey dim) { - TargetPoint tp = new TargetPoint(x, y, z, r2, dim); - return ()->tp; - } - } /** * A Distributor curried with a specific value instance, for actual dispatch * - * @see SimpleChannel#send(PacketTarget, Object) - * + * @see Channel#send(Object, PacketTarget) */ - public static class PacketTarget { - private final Consumer> packetConsumer; - private final PacketDistributor distributor; - PacketTarget(final Consumer> packetConsumer, final PacketDistributor distributor) { - this.packetConsumer = packetConsumer; - this.distributor = distributor; - } - + public record PacketTarget(Consumer> packetConsumer, NetworkDirection direction) { public void send(Packet packet) { packetConsumer.accept(packet); } - - public NetworkDirection getDirection() { - return distributor.direction; - } - } - private final BiFunction, Supplier, Consumer>> functor; - private final NetworkDirection direction; - - public PacketDistributor(BiFunction, Supplier, Consumer>> functor, NetworkDirection direction) { - this.functor = functor; - this.direction = direction; + public PacketDistributor(BiFunction, T, Consumer>> functor) { + this(functor, NetworkDirection.PLAY_TO_CLIENT); } /** @@ -184,8 +114,8 @@ public class PacketDistributor { * @param input The input to apply * @return A curried instance */ - public PacketTarget with(Supplier input) { - return new PacketTarget(functor.apply(this, input), this); + public PacketTarget with(T input) { + return new PacketTarget(functor.apply(this, input), this.direction()); } /** @@ -196,54 +126,43 @@ public class PacketDistributor { * @return A curried instance */ public PacketTarget noArg() { - return new PacketTarget(functor.apply(this, ()->null), this); + return new PacketTarget(functor.apply(this, null), this.direction()); } - private Consumer> playerConsumer(final Supplier entityPlayerMPSupplier) { - return p -> entityPlayerMPSupplier.get().connection.getConnection().send(p); - } - private Consumer> playerListDimConsumer(final Supplier> dimensionTypeSupplier) { - return p->getServer().getPlayerList().broadcastAll(p, dimensionTypeSupplier.get()); + private Consumer> playerConsumer(ServerPlayer player) { + return p -> player.connection.getConnection().send(p); } - private Consumer> playerListAll(final Supplier voidSupplier) { + private Consumer> playerListDimConsumer(ResourceKey dimension) { + return p -> getServer().getPlayerList().broadcastAll(p, dimension); + } + + private Consumer> playerListAll(Void ignored) { return p -> getServer().getPlayerList().broadcastAll(p); } - private Consumer> clientToServer(final Supplier voidSupplier) { + private Consumer> clientToServer(Void ignored) { return p -> Minecraft.getInstance().getConnection().send(p); } - private Consumer> playerListPointConsumer(final Supplier targetPointSupplier) { - return p -> { - final TargetPoint tp = targetPointSupplier.get(); - getServer().getPlayerList().broadcast(tp.excluded, tp.x, tp.y, tp.z, tp.r2, tp.dim, p); - }; + private Consumer> playerListPointConsumer(TargetPoint tp) { + return p -> getServer().getPlayerList().broadcast(tp.excluded, tp.x, tp.y, tp.z, tp.r2, tp.dim, p); } - private Consumer> trackingEntity(final Supplier entitySupplier) { - return p-> { - final Entity entity = entitySupplier.get(); - ((ServerChunkCache)entity.getCommandSenderWorld().getChunkSource()).broadcast(entity, p); - }; + private Consumer> trackingEntity(Entity entity) { + return p -> ((ServerChunkCache)entity.getCommandSenderWorld().getChunkSource()).broadcast(entity, p); } - private Consumer> trackingEntityAndSelf(final Supplier entitySupplier) { - return p-> { - final Entity entity = entitySupplier.get(); - ((ServerChunkCache)entity.getCommandSenderWorld().getChunkSource()).broadcastAndSend(entity, p); - }; + private Consumer> trackingEntityAndSelf(Entity entity) { + return p -> ((ServerChunkCache)entity.getCommandSenderWorld().getChunkSource()).broadcastAndSend(entity, p); } - private Consumer> trackingChunk(final Supplier chunkPosSupplier) { - return p -> { - final LevelChunk chunk = chunkPosSupplier.get(); - ((ServerChunkCache)chunk.getLevel().getChunkSource()).chunkMap.getPlayers(chunk.getPos(), false).forEach(e -> e.connection.send(p)); - }; + private Consumer> trackingChunk(LevelChunk chunk) { + return p -> ((ServerChunkCache)chunk.getLevel().getChunkSource()).chunkMap.getPlayers(chunk.getPos(), false).forEach(e -> e.connection.send(p)); } - private Consumer> networkManagerList(final Supplier> nmListSupplier) { - return p -> nmListSupplier.get().forEach(nm->nm.send(p)); + private Consumer> networkManagerList(List connections) { + return p -> connections.forEach(nm->nm.send(p)); } private MinecraftServer getServer() { diff --git a/src/main/java/net/minecraftforge/network/PlayMessages.java b/src/main/java/net/minecraftforge/network/PlayMessages.java deleted file mode 100644 index f10c8e1cec..0000000000 --- a/src/main/java/net/minecraftforge/network/PlayMessages.java +++ /dev/null @@ -1,326 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.network; - -import io.netty.buffer.Unpooled; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.screens.MenuScreens; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.inventory.MenuAccess; -import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.core.Registry; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.chat.Component; -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.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; -import net.minecraft.world.level.Level; -import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.util.LogicalSidedProvider; -import net.minecraftforge.entity.IEntityAdditionalSpawnData; - -import java.util.Optional; -import java.util.UUID; -import java.util.function.Supplier; - -public class PlayMessages -{ - /** - * Used to spawn a custom entity without the same restrictions as - * {@link ClientboundAddEntityPacket} - *

- * To customize how your entity is created clientside (instead of using the default factory provided to the - * {@link EntityType}) - * see {@link EntityType.Builder#setCustomClientFactory}. - */ - public static class SpawnEntity - { - private final Entity entity; - private final int typeId; - private final int entityId; - private final UUID uuid; - private final double posX, posY, posZ; - private final byte pitch, yaw, headYaw; - private final int velX, velY, velZ; - private final FriendlyByteBuf buf; - - SpawnEntity(Entity e) - { - this.entity = e; - this.typeId = BuiltInRegistries.ENTITY_TYPE.getId(e.getType()); //TODO: Codecs - this.entityId = e.getId(); - this.uuid = e.getUUID(); - this.posX = e.getX(); - this.posY = e.getY(); - this.posZ = e.getZ(); - this.pitch = (byte) Mth.floor(e.getXRot() * 256.0F / 360.0F); - this.yaw = (byte) Mth.floor(e.getYRot() * 256.0F / 360.0F); - this.headYaw = (byte) (e.getYHeadRot() * 256.0F / 360.0F); - Vec3 vec3d = e.getDeltaMovement(); - double d1 = Mth.clamp(vec3d.x, -3.9D, 3.9D); - double d2 = Mth.clamp(vec3d.y, -3.9D, 3.9D); - double d3 = Mth.clamp(vec3d.z, -3.9D, 3.9D); - this.velX = (int) (d1 * 8000.0D); - this.velY = (int) (d2 * 8000.0D); - this.velZ = (int) (d3 * 8000.0D); - this.buf = null; - } - - private SpawnEntity(int typeId, int entityId, UUID uuid, double posX, double posY, double posZ, byte pitch, byte yaw, byte headYaw, int velX, int velY, int velZ, FriendlyByteBuf buf) - { - this.entity = null; - this.typeId = typeId; - this.entityId = entityId; - this.uuid = uuid; - this.posX = posX; - this.posY = posY; - this.posZ = posZ; - this.pitch = pitch; - this.yaw = yaw; - this.headYaw = headYaw; - this.velX = velX; - this.velY = velY; - this.velZ = velZ; - this.buf = buf; - } - - public static void encode(SpawnEntity msg, FriendlyByteBuf buf) - { - buf.writeVarInt(msg.typeId); - buf.writeInt(msg.entityId); - buf.writeLong(msg.uuid.getMostSignificantBits()); - buf.writeLong(msg.uuid.getLeastSignificantBits()); - buf.writeDouble(msg.posX); - buf.writeDouble(msg.posY); - buf.writeDouble(msg.posZ); - buf.writeByte(msg.pitch); - buf.writeByte(msg.yaw); - buf.writeByte(msg.headYaw); - buf.writeShort(msg.velX); - buf.writeShort(msg.velY); - buf.writeShort(msg.velZ); - if (msg.entity instanceof IEntityAdditionalSpawnData entityAdditionalSpawnData) - { - final FriendlyByteBuf spawnDataBuffer = new FriendlyByteBuf(Unpooled.buffer()); - - entityAdditionalSpawnData.writeSpawnData(spawnDataBuffer); - - buf.writeVarInt(spawnDataBuffer.readableBytes()); - buf.writeBytes(spawnDataBuffer); - - spawnDataBuffer.release(); - } else - { - buf.writeVarInt(0); - } - } - - public static SpawnEntity decode(FriendlyByteBuf buf) - { - return new SpawnEntity(buf.readVarInt(), buf.readInt(), new UUID(buf.readLong(), buf.readLong()), buf.readDouble(), buf.readDouble(), buf.readDouble(), buf.readByte(), buf.readByte(), buf.readByte(), buf.readShort(), buf.readShort(), buf.readShort(), readSpawnDataPacket(buf)); - } - - private static FriendlyByteBuf readSpawnDataPacket(FriendlyByteBuf buf) - { - final int count = buf.readVarInt(); - if (count > 0) - { - final FriendlyByteBuf spawnDataBuffer = new FriendlyByteBuf(Unpooled.buffer()); - spawnDataBuffer.writeBytes(buf, count); - return spawnDataBuffer; - } - - return new FriendlyByteBuf(Unpooled.buffer()); - } - - public static void handle(SpawnEntity msg, Supplier ctx) - { - ctx.get().enqueueWork(() -> { - try - { - EntityType type = BuiltInRegistries.ENTITY_TYPE.byId(msg.typeId); - Optional world = LogicalSidedProvider.CLIENTWORLD.get(ctx.get().getDirection().getReceptionSide()); - Entity e = world.map(w -> type.customClientSpawn(msg, w)).orElse(null); - if (e == null) - { - return; - } - - /* - * Sets the postiion on the client, Mirrors what - * Entity#recreateFromPacket and LivingEntity#recreateFromPacket does. - */ - e.syncPacketPositionCodec(msg.posX, msg.posY, msg.posZ); - e.absMoveTo(msg.posX, msg.posY, msg.posZ, (msg.yaw * 360) / 256.0F, (msg.pitch * 360) / 256.0F); - e.setYHeadRot((msg.headYaw * 360) / 256.0F); - e.setYBodyRot((msg.headYaw * 360) / 256.0F); - - e.setId(msg.entityId); - e.setUUID(msg.uuid); - world.filter(ClientLevel.class::isInstance).ifPresent(w -> ((ClientLevel) w).putNonPlayerEntity(msg.entityId, e)); - e.lerpMotion(msg.velX / 8000.0, msg.velY / 8000.0, msg.velZ / 8000.0); - if (e instanceof IEntityAdditionalSpawnData entityAdditionalSpawnData) - { - entityAdditionalSpawnData.readSpawnData(msg.buf); - } - } finally - { - msg.buf.release(); - } - }); - ctx.get().setPacketHandled(true); - } - - public Entity getEntity() - { - return entity; - } - - public int getTypeId() - { - return typeId; - } - - public int getEntityId() - { - return entityId; - } - - public UUID getUuid() - { - return uuid; - } - - public double getPosX() - { - return posX; - } - - public double getPosY() - { - return posY; - } - - public double getPosZ() - { - return posZ; - } - - public byte getPitch() - { - return pitch; - } - - public byte getYaw() - { - return yaw; - } - - public byte getHeadYaw() - { - return headYaw; - } - - public int getVelX() - { - return velX; - } - - public int getVelY() - { - return velY; - } - - public int getVelZ() - { - return velZ; - } - - public FriendlyByteBuf getAdditionalData() - { - return buf; - } - } - - public static class OpenContainer - { - private final int id; - private final int windowId; - private final Component name; - private final FriendlyByteBuf additionalData; - - OpenContainer(MenuType id, int windowId, Component name, FriendlyByteBuf additionalData) - { - this(BuiltInRegistries.MENU.getId(id), windowId, name, additionalData); - } - - private OpenContainer(int id, int windowId, Component name, FriendlyByteBuf additionalData) - { - this.id = id; - this.windowId = windowId; - this.name = name; - this.additionalData = additionalData; - } - - public static void encode(OpenContainer msg, FriendlyByteBuf buf) - { - buf.writeVarInt(msg.id); - buf.writeVarInt(msg.windowId); - buf.writeComponent(msg.name); - buf.writeByteArray(msg.additionalData.readByteArray()); - } - - public static OpenContainer decode(FriendlyByteBuf buf) - { - return new OpenContainer(buf.readVarInt(), buf.readVarInt(), buf.readComponent(), new FriendlyByteBuf(Unpooled.wrappedBuffer(buf.readByteArray(32600)))); - } - - public static void handle(OpenContainer msg, Supplier ctx) - { - ctx.get().enqueueWork(() -> { - try - { - MenuScreens.getScreenFactory(msg.getType(), Minecraft.getInstance(), msg.getWindowId(), msg.getName()).ifPresent(f -> { - AbstractContainerMenu c = msg.getType().create(msg.getWindowId(), Minecraft.getInstance().player.getInventory(), msg.getAdditionalData()); - - @SuppressWarnings("unchecked") Screen s = ((MenuScreens.ScreenConstructor) f).create(c, Minecraft.getInstance().player.getInventory(), msg.getName()); - Minecraft.getInstance().player.containerMenu = ((MenuAccess) s).getMenu(); - Minecraft.getInstance().setScreen(s); - }); - } finally - { - msg.getAdditionalData().release(); - } - - }); - ctx.get().setPacketHandled(true); - } - - public final MenuType getType() - { - return BuiltInRegistries.MENU.byId(this.id); - } - - public int getWindowId() - { - return windowId; - } - - public Component getName() - { - return name; - } - - public FriendlyByteBuf getAdditionalData() - { - return additionalData; - } - } -} diff --git a/src/main/java/net/minecraftforge/network/ServerStatusPing.java b/src/main/java/net/minecraftforge/network/ServerStatusPing.java index df2e4a843e..d462904318 100644 --- a/src/main/java/net/minecraftforge/network/ServerStatusPing.java +++ b/src/main/java/net/minecraftforge/network/ServerStatusPing.java @@ -71,13 +71,14 @@ import java.util.stream.Collectors; * } * */ + +// TODO: Rewrite to a simpler format And/Or remove when I rewrite DisplayTest public record ServerStatusPing( Map channels, Map mods, int fmlNetworkVer, boolean truncated -) -{ +) { private static final Codec BYTE_BUF_CODEC = Codec.STRING .xmap(ServerStatusPing::decodeOptimized, ServerStatusPing::encodeOptimized); @@ -99,43 +100,38 @@ public record ServerStatusPing( )))); - public ServerStatusPing() - { + public ServerStatusPing() { this( - NetworkRegistry.buildChannelVersionsForListPing(), - Util.make(new HashMap<>(), map -> ModList.get().forEachModContainer((modid, mc) -> - map.put(modid, mc.getCustomExtension(IExtensionPoint.DisplayTest.class) - .map(IExtensionPoint.DisplayTest::suppliedVersion) - .map(Supplier::get) - .orElse(NetworkConstants.IGNORESERVERONLY)))), - NetworkConstants.FMLNETVERSION, - false + NetworkRegistry.buildChannelVersionsForListPing(), + Util.make(new HashMap<>(), map -> ModList.get().forEachModContainer((modid, mc) -> + map.put(modid, mc.getCustomExtension(IExtensionPoint.DisplayTest.class) + .map(IExtensionPoint.DisplayTest::suppliedVersion) + .map(Supplier::get) + .orElse(IExtensionPoint.DisplayTest.IGNORESERVERONLY)))), + NetworkContext.NET_VERSION, + false ); } @Override // Don't compare the truncated flag as it is irrelevant - public boolean equals(Object o) - { + public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ServerStatusPing that)) return false; return fmlNetworkVer == that.fmlNetworkVer && channels.equals(that.channels) && mods.equals(that.mods); } @Override - public int hashCode() - { + public int hashCode() { return Objects.hash(channels, mods, fmlNetworkVer); } - private List> getChannelsForMod(String modId) - { + private List> getChannelsForMod(String modId) { return channels.entrySet().stream() .filter(c -> c.getKey().getNamespace().equals(modId)) .toList(); } - private List> getNonModChannels() - { + private List> getNonModChannels() { return channels.entrySet().stream() .filter(c -> !mods.containsKey(c.getKey().getNamespace())) .toList(); @@ -161,55 +157,45 @@ public record ServerStatusPing( buf.writeBoolean(false); // placeholder for whether we are truncating buf.writeShort(mods.size()); // short so that we can replace it later in case of truncation int writtenCount = 0; - for (var modEntry : mods.entrySet()) - { - var isIgnoreServerOnly = modEntry.getValue().equals(NetworkConstants.IGNORESERVERONLY); + for (var modEntry : mods.entrySet()) { + var isIgnoreServerOnly = modEntry.getValue().equals(IExtensionPoint.DisplayTest.IGNORESERVERONLY); var channelsForMod = getChannelsForMod(modEntry.getKey()); var channelSizeAndVersionFlag = channelsForMod.size() << 1; if (isIgnoreServerOnly) - { channelSizeAndVersionFlag |= VERSION_FLAG_IGNORESERVERONLY; - } buf.writeVarInt(channelSizeAndVersionFlag); buf.writeUtf(modEntry.getKey()); if (!isIgnoreServerOnly) - { buf.writeUtf(modEntry.getValue()); - } // write the channels for this mod, if any - for (var entry : channelsForMod) - { + for (var entry : channelsForMod) { buf.writeUtf(entry.getKey().getPath()); - buf.writeUtf(entry.getValue().version()); + buf.writeVarInt(entry.getValue().version()); buf.writeBoolean(entry.getValue().required()); } writtenCount++; - if (buf.readableBytes() >= 60000) - { + if (buf.readableBytes() >= 60000) { reachedSizeLimit = true; break; } } - if (!reachedSizeLimit) - { + if (!reachedSizeLimit) { // write any channels that don't match up with a ModID. var nonModChannels = getNonModChannels(); buf.writeVarInt(nonModChannels.size()); for (var entry : nonModChannels) { buf.writeResourceLocation(entry.getKey()); - buf.writeUtf(entry.getValue().version()); + buf.writeVarInt(entry.getValue().version()); buf.writeBoolean(entry.getValue().required()); } - } - else - { + } else { buf.setShort(1, writtenCount); buf.writeVarInt(0); } @@ -226,8 +212,7 @@ public record ServerStatusPing( Map channels; Map mods; - try - { + try { truncated = buf.readBoolean(); var modsSize = buf.readUnsignedShort(); mods = new HashMap<>(); @@ -237,10 +222,10 @@ public record ServerStatusPing( var channelSize = channelSizeAndVersionFlag >>> 1; var isIgnoreServerOnly = (channelSizeAndVersionFlag & VERSION_FLAG_IGNORESERVERONLY) != 0; var modId = buf.readUtf(); - var modVersion = isIgnoreServerOnly ? NetworkConstants.IGNORESERVERONLY : buf.readUtf(); + var modVersion = isIgnoreServerOnly ? IExtensionPoint.DisplayTest.IGNORESERVERONLY : buf.readUtf(); for (var i1 = 0; i1 < channelSize; i1++) { var channelName = buf.readUtf(); - var channelVersion = buf.readUtf(); + var channelVersion = buf.readVarInt(); var requiredOnClient = buf.readBoolean(); final ResourceLocation id = new ResourceLocation(modId, channelName); channels.put(id, new ChannelData(id, channelVersion, requiredOnClient)); @@ -252,13 +237,11 @@ public record ServerStatusPing( var nonModChannelCount = buf.readVarInt(); for (var i = 0; i < nonModChannelCount; i++) { var channelName = buf.readResourceLocation(); - var channelVersion = buf.readUtf(); + var channelVersion = buf.readVarInt(); var requiredOnClient = buf.readBoolean(); channels.put(channelName, new ChannelData(channelName, channelVersion, requiredOnClient)); } - } - finally - { + } finally { buf.release(); } @@ -269,8 +252,7 @@ public record ServerStatusPing( * Encode given ByteBuf to a String. This is optimized for UTF-16 Code-Point count. * Supports at most 2^30 bytes in length */ - private static String encodeOptimized(ByteBuf buf) - { + private static String encodeOptimized(ByteBuf buf) { var byteLength = buf.readableBytes(); var sb = new StringBuilder(); sb.append((char) (byteLength & 0x7FFF)); @@ -278,10 +260,8 @@ public record ServerStatusPing( int buffer = 0; // we will need at most 8 + 14 = 22 bits of buffer, so an int is enough int bitsInBuf = 0; - while (buf.isReadable()) - { - if (bitsInBuf >= 15) - { + while (buf.isReadable()) { + if (bitsInBuf >= 15) { char c = (char) (buffer & 0x7FFF); sb.append(c); buffer >>>= 15; @@ -293,8 +273,7 @@ public record ServerStatusPing( } buf.release(); - if (bitsInBuf > 0) - { + if (bitsInBuf > 0) { char c = (char) (buffer & 0x7FFF); sb.append(c); } @@ -304,8 +283,7 @@ public record ServerStatusPing( /** * Decode binary data encoded by {@link #encodeOptimized} */ - private static ByteBuf decodeOptimized(String s) - { + private static ByteBuf decodeOptimized(String s) { var size0 = ((int) s.charAt(0)); var size1 = ((int) s.charAt(1)); var size = size0 | (size1 << 15); @@ -315,10 +293,8 @@ public record ServerStatusPing( int stringIndex = 2; int buffer = 0; // we will need at most 8 + 14 = 22 bits of buffer, so an int is enough int bitsInBuf = 0; - while (stringIndex < s.length()) - { - while (bitsInBuf >= 8) - { + while (stringIndex < s.length()) { + while (bitsInBuf >= 8) { buf.writeByte(buffer); buffer >>>= 8; bitsInBuf -= 8; @@ -331,8 +307,7 @@ public record ServerStatusPing( } // write any leftovers - while (buf.readableBytes() < size) - { + while (buf.readableBytes() < size) { buf.writeByte(buffer); buffer >>>= 8; bitsInBuf -= 8; @@ -340,38 +315,34 @@ public record ServerStatusPing( return buf; } - public Map getRemoteChannels() - { + public Map getRemoteChannels() { return this.channels; } - public Map getRemoteModData() - { + public Map getRemoteModData() { return mods; } - public int getFMLNetworkVersion() - { + public int getFMLNetworkVersion() { return fmlNetworkVer; } - public boolean isTruncated() - { + public boolean isTruncated() { return truncated; } public record ModInfo(String modId, String modmarker) { public static final Codec CODEC = RecordCodecBuilder.create(in -> in.group( - Codec.STRING.fieldOf("modId").forGetter(ModInfo::modId), - Codec.STRING.fieldOf("modmarker").forGetter(ModInfo::modmarker) + Codec.STRING.fieldOf("modId").forGetter(ModInfo::modId), + Codec.STRING.fieldOf("modmarker").forGetter(ModInfo::modmarker) ).apply(in, ModInfo::new)); } - public record ChannelData(ResourceLocation res, String version, boolean required) { + public record ChannelData(ResourceLocation res, int version, boolean required) { public static final Codec CODEC = RecordCodecBuilder.create(in -> in.group( - ResourceLocation.CODEC.fieldOf("res").forGetter(ChannelData::res), - Codec.STRING.fieldOf("version").forGetter(ChannelData::version), - Codec.BOOL.fieldOf("required").forGetter(ChannelData::required) + ResourceLocation.CODEC.fieldOf("res").forGetter(ChannelData::res), + Codec.INT.fieldOf("version").forGetter(ChannelData::version), + Codec.BOOL.fieldOf("required").forGetter(ChannelData::required) ).apply(in, ChannelData::new)); } } diff --git a/src/main/java/net/minecraftforge/network/SimpleChannel.java b/src/main/java/net/minecraftforge/network/SimpleChannel.java new file mode 100644 index 0000000000..c43b19cac2 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/SimpleChannel.java @@ -0,0 +1,347 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraftforge.event.network.CustomPayloadEvent; + +import org.apache.commons.lang3.function.TriConsumer; +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 org.jetbrains.annotations.Nullable; + +import io.netty.buffer.Unpooled; +import io.netty.util.AttributeKey; +import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import it.unimi.dsi.fastutil.shorts.Short2ObjectArrayMap; +import it.unimi.dsi.fastutil.shorts.Short2ObjectMap; + +import java.util.*; +import java.util.function.*; + +public class SimpleChannel extends Channel { + private static final Logger LOGGER = LogManager.getLogger(); + private static final Marker MARKER = MarkerManager.getMarker("SIMPLE_CHANNEL"); + + @ApiStatus.Internal + SimpleChannel(NetworkInstance instance) { + super(instance); + instance.addListener(this::networkEventListener); + } + + /** + * Build a new MessageBuilder, using the next available discriminator. + * + * @param type Type of message + * @param Type of type + */ + public MessageBuilder messageBuilder(final Class type) { + return messageBuilder(type, nextIndex()); + } + + /** + * Build a new MessageBuilder. + * + * @param type Type of message + * @param discriminator Manually configured discriminator, Must be between 0 and 255 inclusive. + * @param Type of type + */ + public MessageBuilder messageBuilder(final Class type, short discriminator) { + return messageBuilder(type, discriminator, null); + } + + /** + * Build a new MessageBuilder, using the next available discriminator. + * + * @param type Type of message + * @param direction a impl direction which will be asserted before any processing of this message occurs. Use to + * enforce strict sided handling to prevent spoofing. + * @param Type of type + */ + public MessageBuilder messageBuilder(final Class type, NetworkDirection direction) { + return messageBuilder(type, nextIndex(), direction); + } + + /** + * Build a new MessageBuilder. + * + * @param type Type of message + * @param discriminator Manually configured discriminator, Must be between 0 and 255 inclusive. + * @param direction a impl direction which will be asserted before any processing of this message occurs. Use to + * enforce strict sided handling to prevent spoofing. + * @param Type of type + */ + public MessageBuilder messageBuilder(final Class type, short discriminator, NetworkDirection direction) { + return new MessageBuilder<>(this, type, discriminator, direction); + } + + public static class MessageBuilder { + private final SimpleChannel channel; + private final Class type; + private final short id; + private final Optional direction; + + private BiConsumer encoder; + private Function decoder; + private BiConsumer consumer; + + private MessageBuilder(final SimpleChannel channel, final Class type, short id, @Nullable NetworkDirection networkDirection) { + this.channel = channel; + this.type = type; + this.id = id; + this.direction = Optional.ofNullable(networkDirection); + } + + /** + * Set the message encoder, which writes this message to a {@link FriendlyByteBuf}. + *

+ * The encoder is called immediately {@linkplain #send(PacketDistributor.PacketTarget, Object) 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 + * interact with the current game state. + * + * @param encoder The message encoder. + * @return This message builder, for chaining. + */ + public MessageBuilder encoder(BiConsumer encoder) { + this.encoder = encoder; + return this; + } + + /** + * 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 + * message is handled}. + * + * @param decoder The message decoder. + * @return The message builder, for chaining. + */ + public MessageBuilder decoder(Function decoder) { + this.decoder = decoder; + 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. + *

+ * 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 consumerNetworkThread(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. The instance will be retrieved from the associated AttributeKey on the + * 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 + * main thread. + * + * @param consumer The message consumer. + * @return The message builder, for chaining. + * + * @see #consumerMainThread(BiConsumer) + */ + public MessageBuilder consumerNetworkThread(AttributeKey key, TriConsumer consumer) { + return consumerNetworkThread((msg, ctx) -> { + var inst = ctx.getConnection().channel().attr(key).get(); + consumer.accept(inst, msg, ctx); + }); + } + + /** + * Function returning a boolean "packet handled" indication, for simpler channel building. + * + * @see #consumerNetworkThread(BiConsumer) + */ + public MessageBuilder consumerNetworkThread(ToBooleanBiFunction handler) { + this.consumer = (msg, ctx) -> ctx.setPacketHandled(handler.applyAsBool(msg, ctx)); + return this; + } + + /** + * Function returning a boolean "packet handled" indication, for simpler channel building. + * + * @see #consumerNetworkThread(AttributeKey,TriConsumer) + */ + 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); + }); + } + + /** + * Set the message consumer, which is called once a message has been decoded. This accepts the decoded message + * object and the message's context. + *

+ * Unlike {@link #consumerNetworkThread(BiConsumer)}, the consumer is called on the main thread, and so can + * interact with most game state by default. + * + * @param consumer The message consumer. + * @return The message builder, for chaining. + * + * @see #consumerNetworkThread(BiConsumer) + */ + public MessageBuilder consumerMainThread(BiConsumer consumer) { + this.consumer = (msg, context) -> { + var ctx = context; + ctx.enqueueWork(() -> consumer.accept(msg, context)); + ctx.setPacketHandled(true); + }; + 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. The instance will be retrieved from the associated AttributeKey on the + * channel. + *

+ * Unlike {@link #consumerNetworkThread(AttributeKey,TriConsumer)}, the consumer is called on the main thread, + * and so can interact with most game state by default. + * + * @param consumer The message consumer. + * @return The message builder, for chaining. + * + * @see #consumerNetworkThread(BiConsumer) + */ + public MessageBuilder consumerMainThread(AttributeKey key, TriConsumer consumer) { + this.consumer = (msg, ctx) -> { + ctx.enqueueWork(() -> { + var inst = ctx.getConnection().channel().attr(key).get(); + consumer.accept(inst, msg, ctx); + }); + ctx.setPacketHandled(true); + }; + return this; + } + + // TODO: Move out to full classes? + @FunctionalInterface + public interface ToBooleanBiFunction { + boolean applyAsBool(T first, U second); + } + @FunctionalInterface + public interface ToBooleanTriFunction { + boolean applyAsBool(T first, U second, V third); + } + + /** + * Finishes building this packet. + * @return The attached SimpleChannel to facilitate chaining. + */ + public SimpleChannel add() { + var msg = new Message<>(this.id, this.type, 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()); + if (channel.byType.containsKey(msg.type())) + throw new IllegalStateException("Failed to register SimpleChannel message, Class " + msg.type().getName() + " already registered"); + + channel.byId.put(msg.index(), msg); + channel.byType.put(msg.type(), msg); + return this.channel; + } + } + + /* =================================================================================== + * INTERNAL BELOW THIS + * =================================================================================== + */ + private short lastIndex = 0; + private Short2ObjectMap> byId = new Short2ObjectArrayMap<>(); + private Object2ObjectMap, Message> byType = new Object2ObjectArrayMap<>(); + + private record Message( + short index, + Class type, + Optional direction, + BiConsumer encoder, + Function decoder, + BiConsumer consumer + ){ }; + + private short nextIndex() { + while (byId.containsKey(lastIndex)) { + lastIndex++; + if (lastIndex > 0xFF) + throw new IllegalStateException("Ran out of discriminator, only 255 are allowed"); + } + return lastIndex++; + } + + private void networkEventListener(CustomPayloadEvent event) { + var data = event.getPayload(); + if (data == null || !data.isReadable()) { + LOGGER.error(MARKER, "Received empty payload on channel {} login index {}", getName(), event.getLoginIndex()); + return; + } + + short id = data.readUnsignedByte(); + var msg = byId.get(id); + if (msg == null) { + LOGGER.error(MARKER, "Received invalid discriminator byte {} on channel {}", id, getName()); + return; + } + + var con = event.getSource().getConnection(); + var dir = event.getSource().getDirection(); + + 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); + } + + decodeAndDispatch(data, event.getSource(), msg); + } + + // Yay generics + 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 + protected FriendlyByteBuf toBuffer(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.writeByte(msg.index() & 0xFF); + if (msg.encoder() != null) + ((BiConsumer)msg.encoder()).accept(message, ret); + + return ret; + } +} diff --git a/src/main/java/net/minecraftforge/network/config/ConfigurationTaskContext.java b/src/main/java/net/minecraftforge/network/config/ConfigurationTaskContext.java new file mode 100644 index 0000000000..81876cd541 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/config/ConfigurationTaskContext.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.config; + +import java.util.function.Consumer; + +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.server.network.ConfigurationTask.Type; + +public class ConfigurationTaskContext { + private final Connection connection; + private final Consumer> send; + private final Consumer finish; + + public ConfigurationTaskContext(Connection connection, Consumer> send, Consumer finish) { + this.connection = connection; + this.send = send; + this.finish = finish; + } + + public Connection getConnection() { + return connection; + } + + public void send(Packet packet) { + this.send.accept(packet); + } + + public void finish(Type task) { + this.finish.accept(task); + } +} diff --git a/src/main/java/net/minecraftforge/network/config/SimpleConfigurationTask.java b/src/main/java/net/minecraftforge/network/config/SimpleConfigurationTask.java new file mode 100644 index 0000000000..a92b980ff0 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/config/SimpleConfigurationTask.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.config; + +import java.util.function.Consumer; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.server.network.ConfigurationTask; + +/** + * A simple ConfigurationTask that will run a block of code and then mark itself as finished. + */ +public class SimpleConfigurationTask implements ConfigurationTask { + private final Type type; + private final Consumer task; + + public SimpleConfigurationTask(Type type, Consumer task) { + this.type = type; + this.task = task; + } + + public SimpleConfigurationTask(Type type, Runnable task) { + this(type, c -> task.run()); + } + + @Override + public void start(ConfigurationTaskContext ctx) { + this.task.accept(ctx); + ctx.finish(type()); + } + + @Override + public void start(Consumer> send) { + throw new IllegalStateException("This should never be called"); + } + + @Override + public Type type() { + return this.type; + } +} diff --git a/src/main/java/net/minecraftforge/network/event/EventNetworkChannel.java b/src/main/java/net/minecraftforge/network/event/EventNetworkChannel.java deleted file mode 100644 index 2070d4bdcf..0000000000 --- a/src/main/java/net/minecraftforge/network/event/EventNetworkChannel.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.network.event; - -import net.minecraft.network.Connection; -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.network.NetworkEvent; -import net.minecraftforge.network.NetworkInstance; -import net.minecraftforge.network.NetworkRegistry; - -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.function.Supplier; - -/** - * An event-bus like object on which {@link NetworkEvent}s are posted. - * - * These events are fired from the network thread, and so should not interact with most game state by default. - * {@link NetworkEvent.Context#enqueueWork(Runnable)} can be used to handle the message on the main server or client - * thread. - * - * @see NetworkRegistry#newEventChannel(ResourceLocation, Supplier, Predicate, Predicate) - * @see NetworkRegistry.ChannelBuilder#newEventChannel(ResourceLocation, Supplier, Predicate, Predicate) - */ -public class EventNetworkChannel -{ - private final NetworkInstance instance; - - public EventNetworkChannel(NetworkInstance instance) - { - this.instance = instance; - } - - public void addListener(Consumer eventListener) - { - instance.addListener(eventListener); - } - - public void registerObject(Object object) - { - instance.registerObject(object); - } - - public void unregisterObject(Object object) - { - instance.unregisterObject(object); - } - - public boolean isRemotePresent(Connection manager) { - return instance.isRemotePresent(manager); - } -} diff --git a/src/main/java/net/minecraftforge/network/filters/NetworkFilters.java b/src/main/java/net/minecraftforge/network/filters/NetworkFilters.java index d215281a14..a70e4959c3 100644 --- a/src/main/java/net/minecraftforge/network/filters/NetworkFilters.java +++ b/src/main/java/net/minecraftforge/network/filters/NetworkFilters.java @@ -16,34 +16,27 @@ import org.apache.logging.log4j.Logger; import com.google.common.collect.ImmutableMap; -public class NetworkFilters -{ - +public class NetworkFilters { private static final Logger LOGGER = LogManager.getLogger(); private static final Map> instances = ImmutableMap.of( - "forge:vanilla_filter", manager -> new VanillaConnectionNetworkFilter()/*, - "forge:forge_fixes", ForgeConnectionNetworkFilter::new*/ + "forge:vanilla_filter", manager -> new VanillaConnectionNetworkFilter()/*, + "forge:forge_fixes", ForgeConnectionNetworkFilter::new*/ ); - public static void injectIfNecessary(Connection manager) - { + public static void injectIfNecessary(Connection manager) { ChannelPipeline pipeline = manager.channel().pipeline(); if (pipeline.get("packet_handler") == null) return; // Realistically this can only ever be null if the connection was prematurely closed due to an error. We return early here to reduce further log spam. instances.forEach((key, filterFactory) -> { VanillaPacketFilter filter = filterFactory.apply(manager); - if (filter.isNecessary(manager)) - { + if (filter.isNecessary(manager)) { pipeline.addBefore("packet_handler", key, filter); LOGGER.debug("Injected {} into {}", filter, manager); } }); } - private NetworkFilters() - { - } - + private NetworkFilters() {} } diff --git a/src/main/java/net/minecraftforge/network/filters/VanillaConnectionNetworkFilter.java b/src/main/java/net/minecraftforge/network/filters/VanillaConnectionNetworkFilter.java index 4b97b25c55..bc6b000996 100644 --- a/src/main/java/net/minecraftforge/network/filters/VanillaConnectionNetworkFilter.java +++ b/src/main/java/net/minecraftforge/network/filters/VanillaConnectionNetworkFilter.java @@ -23,42 +23,34 @@ import net.minecraft.network.Connection; import net.minecraft.network.protocol.game.ClientboundCommandsPacket; import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.network.NetworkHooks; +import net.minecraftforge.network.ConnectionType; +import net.minecraftforge.network.NetworkContext; import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryManager; import org.jetbrains.annotations.NotNull; -import org.slf4j.Logger; - import com.google.common.collect.ImmutableMap; import com.mojang.brigadier.tree.RootCommandNode; -import com.mojang.logging.LogUtils; /** * A filter for impl packets, used to filter/modify parts of vanilla impl messages that * will cause errors or warnings on vanilla clients, for example entity attributes that are added by Forge or mods. */ @ChannelHandler.Sharable -public class VanillaConnectionNetworkFilter extends VanillaPacketFilter -{ - private static final Logger LOGGER = LogUtils.getLogger(); - - public VanillaConnectionNetworkFilter() - { +public class VanillaConnectionNetworkFilter extends VanillaPacketFilter { + public VanillaConnectionNetworkFilter() { super( - ImmutableMap.>, BiConsumer, List>>>builder() - .put(handler(ClientboundUpdateAttributesPacket.class, VanillaConnectionNetworkFilter::filterEntityProperties)) - .put(handler(ClientboundCommandsPacket.class, VanillaConnectionNetworkFilter::filterCommandList)) - // TODO Filter tags - //.put(handler(ClientboundUpdateTagsPacket.class, VanillaConnectionNetworkFilter::filterCustomTagTypes)) - .build() + ImmutableMap.>, BiConsumer, List>>>builder() + .put(handler(ClientboundUpdateAttributesPacket.class, VanillaConnectionNetworkFilter::filterEntityProperties)) + .put(handler(ClientboundCommandsPacket.class, VanillaConnectionNetworkFilter::filterCommandList)) + // TODO Filter tags + //.put(handler(ClientboundUpdateTagsPacket.class, VanillaConnectionNetworkFilter::filterCustomTagTypes)) + .build() ); } @Override - protected boolean isNecessary(Connection manager) - { - return NetworkHooks.isVanillaConnection(manager); + protected boolean isNecessary(Connection connection) { + return NetworkContext.get(connection).getType() == ConnectionType.VANILLA; } /** @@ -66,8 +58,7 @@ public class VanillaConnectionNetworkFilter extends VanillaPacketFilter * A vanilla client would ignore these with an error log. */ @NotNull - private static ClientboundUpdateAttributesPacket filterEntityProperties(ClientboundUpdateAttributesPacket msg) - { + private static ClientboundUpdateAttributesPacket filterEntityProperties(ClientboundUpdateAttributesPacket msg) { ClientboundUpdateAttributesPacket newPacket = new ClientboundUpdateAttributesPacket(msg.getEntityId(), Collections.emptyList()); msg.getValues().stream() .filter(snapshot -> { @@ -83,8 +74,7 @@ public class VanillaConnectionNetworkFilter extends VanillaPacketFilter * A vanilla client would fail to deserialize the packet and disconnect with an error message if these were sent. */ @NotNull - private static ClientboundCommandsPacket filterCommandList(ClientboundCommandsPacket packet) - { + private static ClientboundCommandsPacket filterCommandList(ClientboundCommandsPacket packet) { CommandBuildContext commandBuildContext = Commands.createValidationContext(VanillaRegistries.createLookup()); RootCommandNode root = packet.getRoot(commandBuildContext); RootCommandNode newRoot = CommandTreeCleaner.cleanArgumentTypes(root, argType -> { @@ -109,12 +99,11 @@ public class VanillaConnectionNetworkFilter extends VanillaPacketFilter .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return new ClientboundUpdateTagsPacket(tags); } - */ - private static boolean isVanillaRegistry(ResourceLocation location) - { + private static boolean isVanillaRegistry(ResourceLocation location) { // Checks if the registry name is contained within the static view of both BuiltInRegistries and VanillaRegistries return RegistryManager.getVanillaRegistryKeys().contains(location) || VanillaRegistries.DATAPACK_REGISTRY_KEYS.stream().anyMatch(k -> k.location().equals(location)); } + */ } diff --git a/src/main/java/net/minecraftforge/network/packets/Acknowledge.java b/src/main/java/net/minecraftforge/network/packets/Acknowledge.java new file mode 100644 index 0000000000..2951f4e406 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/packets/Acknowledge.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.packets; + +import net.minecraft.network.FriendlyByteBuf; + +/* + * 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 void encode(FriendlyByteBuf buf) { + buf.writeVarInt(token); + } + + public static Acknowledge decode(FriendlyByteBuf buf) { + return new Acknowledge(buf.readVarInt()); + } +} \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/network/packets/ChannelVersions.java b/src/main/java/net/minecraftforge/network/packets/ChannelVersions.java new file mode 100644 index 0000000000..74a8fcb851 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/packets/ChannelVersions.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.packets; + +import java.util.HashMap; +import java.util.Map; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.network.NetworkRegistry; + +public record ChannelVersions(Map channels) { + public ChannelVersions() { + this(NetworkRegistry.buildChannelVersions()); + } + + public static ChannelVersions decode(FriendlyByteBuf buf) { + Map channels = new HashMap<>(); + int len = buf.readVarInt(); + for (int x = 0; x < len; x++) + channels.put(buf.readResourceLocation(), buf.readVarInt()); + + return new ChannelVersions(channels); + } + + public void encode(FriendlyByteBuf buf) { + buf.writeVarInt(channels.size()); + channels.forEach((k, v) -> { + buf.writeResourceLocation(k); + buf.writeVarInt(v); + }); + } +} \ 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 new file mode 100644 index 0000000000..8392a1845e --- /dev/null +++ b/src/main/java/net/minecraftforge/network/packets/ConfigData.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.packets; + +import net.minecraft.network.FriendlyByteBuf; + +public record ConfigData(String name, byte[] data) { + public void encode(final FriendlyByteBuf buf) { + buf.writeUtf(this.name()); + buf.writeByteArray(this.data()); + } + + public static ConfigData decode(FriendlyByteBuf buf) { + return new ConfigData(buf.readUtf(), buf.readByteArray()); + } +} \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/network/packets/LoginWrapper.java b/src/main/java/net/minecraftforge/network/packets/LoginWrapper.java new file mode 100644 index 0000000000..e4a32c2708 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/packets/LoginWrapper.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.packets; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; + +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 void encode(FriendlyByteBuf buf) { + buf.writeResourceLocation(channel); + buf.writeVarInt(data.readableBytes()); + buf.writeBytes(data.slice()); + } +} diff --git a/src/main/java/net/minecraftforge/network/packets/MismatchData.java b/src/main/java/net/minecraftforge/network/packets/MismatchData.java new file mode 100644 index 0000000000..ec16c4d04a --- /dev/null +++ b/src/main/java/net/minecraftforge/network/packets/MismatchData.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.packets; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.network.NetworkContext.NetworkMismatchData; +import net.minecraftforge.network.NetworkContext.NetworkMismatchData.Version; + +/** + * Notifies the client of a channel mismatch on the server, so a {@link net.minecraftforge.client.gui.ModMismatchDisconnectedScreen} is used to notify the user of the disconnection. + * This packet also sends the data of a channel mismatch (currently, the ids and versions of the mismatched channels) to the client for it to display the correct information in said screen. + */ +public record MismatchData( + Map mismatched, + Set missing +) { + private static final int MAX_LENGTH = 0x100; + + public MismatchData(NetworkMismatchData data) { + this(data.mismatched(), data.missing()); + } + + public static MismatchData decode(FriendlyByteBuf buf) { + var mismatched = buf.readMap( + i -> new ResourceLocation(i.readUtf(MAX_LENGTH)), + i -> new Version( + i.readUtf(MAX_LENGTH), + i.readUtf(MAX_LENGTH) + ) + ); + var missing = buf.readCollection(HashSet::new, + i -> new ResourceLocation(i.readUtf(MAX_LENGTH)) + ); + return new MismatchData(mismatched, missing); + } + + public void encode(FriendlyByteBuf buf) { + buf.writeMap(mismatched, + (o, k) -> o.writeUtf(k.toString(), MAX_LENGTH), + (o, v) -> { + o.writeUtf(v.received(), MAX_LENGTH); + o.writeUtf(v.had(), MAX_LENGTH); + } + ); + buf.writeCollection(missing, + (o, k) -> o.writeUtf(k.toString(), MAX_LENGTH) + ); + } +} \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/network/packets/ModVersions.java b/src/main/java/net/minecraftforge/network/packets/ModVersions.java new file mode 100644 index 0000000000..161b5eaae4 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/packets/ModVersions.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.packets; + +import java.util.HashMap; +import java.util.Map; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraftforge.fml.ModList; + +/** + * Prefixes S2CModList by sending additional data about the mods installed on the server to the client + * The mod data is stored as follows: [modId -> [modName, modVersion]] + */ +public record ModVersions(Map mods) { + private static final int MAX_LENGTH = 0x100; + + public static ModVersions create() { + Map mods = new HashMap<>(); + ModList.get().getMods().stream().forEach(mod -> + mods.put( + mod.getModId(), + new Info(mod.getDisplayName(), mod.getVersion().toString()) + ) + ); + return new ModVersions(mods); + } + + public static ModVersions decode(FriendlyByteBuf buf) { + var mods = buf.readMap( + o -> o.readUtf(MAX_LENGTH), + o -> new Info( + o.readUtf(MAX_LENGTH), + o.readUtf(MAX_LENGTH) + ) + ); + return new ModVersions(mods); + } + + public void encode(FriendlyByteBuf output) { + output.writeMap(mods, + (o, s) -> o.writeUtf(s, MAX_LENGTH), + (o, p) -> { + o.writeUtf(p.name(), MAX_LENGTH); + o.writeUtf(p.version(), MAX_LENGTH); + } + ); + } + + public record Info(String name, String version) {} +} \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/network/packets/OpenContainer.java b/src/main/java/net/minecraftforge/network/packets/OpenContainer.java new file mode 100644 index 0000000000..1ca37a09f9 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/packets/OpenContainer.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.packets; + +import org.jetbrains.annotations.ApiStatus; + +import io.netty.buffer.Unpooled; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.MenuScreens; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.inventory.MenuAccess; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +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 { + private final int id; + private final int windowId; + private final Component name; + private final FriendlyByteBuf additionalData; + + /** 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); + } + + private OpenContainer(int id, int windowId, Component name, FriendlyByteBuf additionalData) { + this.id = id; + this.windowId = windowId; + this.name = name; + this.additionalData = additionalData; + } + + public static void encode(OpenContainer msg, FriendlyByteBuf buf) { + buf.writeVarInt(msg.id); + buf.writeVarInt(msg.windowId); + buf.writeComponent(msg.name); + buf.writeByteArray(msg.additionalData.readByteArray()); + } + + public static OpenContainer decode(FriendlyByteBuf buf) { + return new OpenContainer(buf.readVarInt(), buf.readVarInt(), buf.readComponent(), new FriendlyByteBuf(Unpooled.wrappedBuffer(buf.readByteArray(32600)))); + } + + @SuppressWarnings("unchecked") + public static void handle(OpenContainer msg, CustomPayloadEvent.Context ctx) { + ctx.enqueueWork(() -> { + try { + var mc = Minecraft.getInstance(); + var inv = mc.player.getInventory(); + MenuScreens.getScreenFactory(msg.getType(), mc, msg.getWindowId(), msg.getName()).ifPresent(f -> { + AbstractContainerMenu c = msg.getType().create(msg.getWindowId(), inv, msg.getAdditionalData()); + + Screen s = ((MenuScreens.ScreenConstructor)f).create(c, inv, msg.getName()); + mc.player.containerMenu = ((MenuAccess)s).getMenu(); + mc.setScreen(s); + }); + } finally { + msg.getAdditionalData().release(); + } + + }); + ctx.setPacketHandled(true); + } + + @SuppressWarnings("deprecation") + public final MenuType getType() { + return BuiltInRegistries.MENU.byId(this.id); + } + + public int getWindowId() { + return windowId; + } + + public Component getName() { + return name; + } + + public FriendlyByteBuf getAdditionalData() { + return additionalData; + } +} \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/network/packets/RegistryData.java b/src/main/java/net/minecraftforge/network/packets/RegistryData.java new file mode 100644 index 0000000000..e5444b1e30 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/packets/RegistryData.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.packets; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.registries.ForgeRegistry.Snapshot; + +public record RegistryData(int token, ResourceLocation name, Snapshot data) { + public void encode(FriendlyByteBuf buf) { + buf.writeVarInt(token); + buf.writeResourceLocation(name); + buf.writeBytes(data.getPacketData()); + } + + public static RegistryData decode(FriendlyByteBuf buf) { + return new RegistryData(buf.readVarInt(), buf.readResourceLocation(), Snapshot.read(buf)); + } +} \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/network/packets/RegistryList.java b/src/main/java/net/minecraftforge/network/packets/RegistryList.java new file mode 100644 index 0000000000..f13f655d07 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/packets/RegistryList.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.packets; + +import java.util.List; +import net.minecraft.core.Registry; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.registries.DataPackRegistriesHooks; +import net.minecraftforge.registries.RegistryManager; + +public record RegistryList( + int token, + List normal, + List>> datapacks) { + + public RegistryList(int token) { + this(token, RegistryManager.getRegistryNamesForSyncToClient(), List.copyOf(DataPackRegistriesHooks.getSyncedCustomRegistries())); + } + + public static RegistryList decode(FriendlyByteBuf buf) { + var token = buf.readVarInt(); + var normal = buf.readList(FriendlyByteBuf::readResourceLocation); + List>> datapacks = buf.readList(b -> ResourceKey.createRegistryKey(buf.readResourceLocation())); + return new RegistryList(token, normal, datapacks); + } + + public void encode(FriendlyByteBuf buf) { + buf.writeVarInt(token()); + buf.writeCollection(normal(), FriendlyByteBuf::writeResourceLocation); + buf.writeCollection(datapacks(), FriendlyByteBuf::writeResourceKey); + } +} \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/network/packets/SpawnEntity.java b/src/main/java/net/minecraftforge/network/packets/SpawnEntity.java new file mode 100644 index 0000000000..de442cd331 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/packets/SpawnEntity.java @@ -0,0 +1,211 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.packets; + +import java.util.Optional; +import java.util.UUID; + +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.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; +import net.minecraftforge.event.network.CustomPayloadEvent; +import net.minecraftforge.event.network.CustomPayloadEvent.Context; + +/** + * Used to spawn a custom entity without the same restrictions as + * {@link ClientboundAddEntityPacket} + *

+ * To customize how your entity is created clientside (instead of using the default factory provided to the + * {@link EntityType}) + * see {@link EntityType.Builder#setCustomClientFactory}. + */ +public class SpawnEntity { + private final Entity entity; + private final int typeId; + private final int entityId; + private final UUID uuid; + private final double posX, posY, posZ; + private final byte pitch, yaw, headYaw; + private final int velX, velY, velZ; + private final FriendlyByteBuf buf; + + SpawnEntity(Entity e) { + this.entity = e; + this.typeId = BuiltInRegistries.ENTITY_TYPE.getId(e.getType()); //TODO: Codecs + this.entityId = e.getId(); + this.uuid = e.getUUID(); + this.posX = e.getX(); + this.posY = e.getY(); + this.posZ = e.getZ(); + this.pitch = (byte) Mth.floor(e.getXRot() * 256.0F / 360.0F); + this.yaw = (byte) Mth.floor(e.getYRot() * 256.0F / 360.0F); + this.headYaw = (byte) (e.getYHeadRot() * 256.0F / 360.0F); + Vec3 vec3d = e.getDeltaMovement(); + double d1 = Mth.clamp(vec3d.x, -3.9D, 3.9D); + double d2 = Mth.clamp(vec3d.y, -3.9D, 3.9D); + double d3 = Mth.clamp(vec3d.z, -3.9D, 3.9D); + this.velX = (int) (d1 * 8000.0D); + this.velY = (int) (d2 * 8000.0D); + this.velZ = (int) (d3 * 8000.0D); + this.buf = null; + } + + private SpawnEntity(int typeId, int entityId, UUID uuid, double posX, double posY, double posZ, byte pitch, byte yaw, byte headYaw, int velX, int velY, int velZ, FriendlyByteBuf buf) { + this.entity = null; + this.typeId = typeId; + this.entityId = entityId; + this.uuid = uuid; + this.posX = posX; + this.posY = posY; + this.posZ = posZ; + this.pitch = pitch; + this.yaw = yaw; + this.headYaw = headYaw; + this.velX = velX; + this.velY = velY; + this.velZ = velZ; + this.buf = buf; + } + + public static void encode(SpawnEntity msg, FriendlyByteBuf buf) { + buf.writeVarInt(msg.typeId); + buf.writeInt(msg.entityId); + buf.writeLong(msg.uuid.getMostSignificantBits()); + buf.writeLong(msg.uuid.getLeastSignificantBits()); + buf.writeDouble(msg.posX); + buf.writeDouble(msg.posY); + buf.writeDouble(msg.posZ); + buf.writeByte(msg.pitch); + buf.writeByte(msg.yaw); + buf.writeByte(msg.headYaw); + buf.writeShort(msg.velX); + buf.writeShort(msg.velY); + buf.writeShort(msg.velZ); + if (msg.entity instanceof IEntityAdditionalSpawnData entityAdditionalSpawnData) { + final FriendlyByteBuf spawnDataBuffer = new FriendlyByteBuf(Unpooled.buffer()); + + entityAdditionalSpawnData.writeSpawnData(spawnDataBuffer); + + buf.writeVarInt(spawnDataBuffer.readableBytes()); + buf.writeBytes(spawnDataBuffer); + + spawnDataBuffer.release(); + } else { + buf.writeVarInt(0); + } + } + + public static SpawnEntity decode(FriendlyByteBuf buf) { + return new SpawnEntity(buf.readVarInt(), buf.readInt(), new UUID(buf.readLong(), buf.readLong()), buf.readDouble(), buf.readDouble(), buf.readDouble(), buf.readByte(), buf.readByte(), buf.readByte(), buf.readShort(), buf.readShort(), buf.readShort(), readSpawnDataPacket(buf)); + } + + private static FriendlyByteBuf readSpawnDataPacket(FriendlyByteBuf buf) { + final int count = buf.readVarInt(); + if (count > 0) { + final FriendlyByteBuf spawnDataBuffer = new FriendlyByteBuf(Unpooled.buffer()); + spawnDataBuffer.writeBytes(buf, count); + return spawnDataBuffer; + } + + return new FriendlyByteBuf(Unpooled.buffer()); + } + + public static void handle(SpawnEntity msg, CustomPayloadEvent.Context ctx) { + ctx.enqueueWork(() -> { + try { + EntityType type = BuiltInRegistries.ENTITY_TYPE.byId(msg.typeId); + Optional world = LogicalSidedProvider.CLIENTWORLD.get(ctx.getDirection().getReceptionSide()); + Entity e = world.map(w -> type.customClientSpawn(msg, w)).orElse(null); + if (e == null) + return; + + /* + * Sets the postiion on the client, Mirrors what + * Entity#recreateFromPacket and LivingEntity#recreateFromPacket does. + */ + e.syncPacketPositionCodec(msg.posX, msg.posY, msg.posZ); + e.absMoveTo(msg.posX, msg.posY, msg.posZ, (msg.yaw * 360) / 256.0F, (msg.pitch * 360) / 256.0F); + e.setYHeadRot((msg.headYaw * 360) / 256.0F); + e.setYBodyRot((msg.headYaw * 360) / 256.0F); + + e.setId(msg.entityId); + e.setUUID(msg.uuid); + world.filter(ClientLevel.class::isInstance).ifPresent(w -> ((ClientLevel) w).putNonPlayerEntity(msg.entityId, e)); + e.lerpMotion(msg.velX / 8000.0, msg.velY / 8000.0, msg.velZ / 8000.0); + if (e instanceof IEntityAdditionalSpawnData entityAdditionalSpawnData) + entityAdditionalSpawnData.readSpawnData(msg.buf); + } finally { + msg.buf.release(); + } + }); + ctx.setPacketHandled(true); + } + + public Entity getEntity() { + return entity; + } + + public int getTypeId() { + return typeId; + } + + public int getEntityId() { + return entityId; + } + + public UUID getUuid() { + return uuid; + } + + public double getPosX() { + return posX; + } + + public double getPosY() { + return posY; + } + + public double getPosZ() { + return posZ; + } + + public byte getPitch() { + return pitch; + } + + public byte getYaw() { + return yaw; + } + + public byte getHeadYaw() { + return headYaw; + } + + public int getVelX() { + return velX; + } + + public int getVelY() { + return velY; + } + + public int getVelZ() { + return velZ; + } + + public FriendlyByteBuf getAdditionalData() { + return buf; + } +} \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/network/simple/IndexedMessageCodec.java b/src/main/java/net/minecraftforge/network/simple/IndexedMessageCodec.java deleted file mode 100644 index efaf40641e..0000000000 --- a/src/main/java/net/minecraftforge/network/simple/IndexedMessageCodec.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.network.simple; - -import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; -import it.unimi.dsi.fastutil.shorts.Short2ObjectArrayMap; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.network.HandshakeHandler; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.NetworkEvent; -import net.minecraftforge.network.NetworkHooks; -import net.minecraftforge.network.NetworkInstance; -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 java.util.Objects; -import java.util.Optional; -import java.util.function.BiConsumer; -import java.util.function.Function; -import java.util.function.Supplier; - -public class IndexedMessageCodec -{ - private static final Logger LOGGER = LogManager.getLogger(); - private static final Marker SIMPLENET = MarkerManager.getMarker("SIMPLENET"); - private final Short2ObjectArrayMap> indicies = new Short2ObjectArrayMap<>(); - private final Object2ObjectArrayMap, MessageHandler> types = new Object2ObjectArrayMap<>(); - private final NetworkInstance networkInstance; - - public IndexedMessageCodec() { - this(null); - } - public IndexedMessageCodec(final NetworkInstance instance) { - this.networkInstance = instance; - } - - @SuppressWarnings("unchecked") - public MessageHandler findMessageType(final MSG msgToReply) { - return (MessageHandler) types.get(msgToReply.getClass()); - } - - @SuppressWarnings("unchecked") - MessageHandler findIndex(final short i) { - return (MessageHandler) indicies.get(i); - } - - @SuppressWarnings("OptionalUsedAsFieldOrParameterType") - class MessageHandler - { - private final Optional> encoder; - private final Optional> decoder; - private final int index; - private final BiConsumer> messageConsumer; - private final Class messageType; - private final Optional networkDirection; - private Optional> loginIndexSetter; - private Optional> loginIndexGetter; - - public MessageHandler(int index, Class messageType, BiConsumer encoder, Function decoder, BiConsumer> messageConsumer, final Optional networkDirection) - { - this.index = index; - this.messageType = messageType; - this.encoder = Optional.ofNullable(encoder); - this.decoder = Optional.ofNullable(decoder); - this.messageConsumer = messageConsumer; - this.networkDirection = networkDirection; - this.loginIndexGetter = Optional.empty(); - this.loginIndexSetter = Optional.empty(); - indicies.put((short)(index & 0xff), this); - types.put(messageType, this); - } - - void setLoginIndexSetter(BiConsumer loginIndexSetter) - { - this.loginIndexSetter = Optional.of(loginIndexSetter); - } - - Optional> getLoginIndexSetter() { - return this.loginIndexSetter; - } - - void setLoginIndexGetter(Function loginIndexGetter) { - this.loginIndexGetter = Optional.of(loginIndexGetter); - } - - public Optional> getLoginIndexGetter() { - return this.loginIndexGetter; - } - - MSG newInstance() { - try { - return messageType.newInstance(); - } catch (InstantiationException | IllegalAccessException e) { - LOGGER.error("Invalid login message", e); - throw new RuntimeException(e); - } - } - } - - private static void tryDecode(FriendlyByteBuf payload, Supplier context, int payloadIndex, MessageHandler codec) - { - codec.decoder.map(d->d.apply(payload)). - map(p->{ - // Only run the loginIndex function for payloadIndexed packets (login) - if (payloadIndex != Integer.MIN_VALUE) - { - codec.getLoginIndexSetter().ifPresent(f-> f.accept(p, payloadIndex)); - } - return p; - }).ifPresent(m->codec.messageConsumer.accept(m, context)); - } - - private static int tryEncode(FriendlyByteBuf target, M message, MessageHandler codec) { - codec.encoder.ifPresent(encoder->{ - target.writeByte(codec.index & 0xff); - encoder.accept(message, target); - }); - return codec.loginIndexGetter.orElse(m -> Integer.MIN_VALUE).apply(message); - } - - public int build(MSG message, FriendlyByteBuf target) - { - @SuppressWarnings("unchecked") - MessageHandler messageHandler = (MessageHandler)types.get(message.getClass()); - if (messageHandler == null) { - LOGGER.error(SIMPLENET, "Received invalid message {} on channel {}", message.getClass().getName(), Optional.ofNullable(networkInstance).map(NetworkInstance::getChannelName).map(Objects::toString).orElse("MISSING CHANNEL")); - throw new IllegalArgumentException("Invalid message "+message.getClass().getName()); - } - return tryEncode(target, message, messageHandler); - } - - void consume(FriendlyByteBuf payload, int payloadIndex, Supplier context) { - if (payload == null || !payload.isReadable()) { - LOGGER.error(SIMPLENET, "Received empty payload on channel {}", Optional.ofNullable(networkInstance).map(NetworkInstance::getChannelName).map(Objects::toString).orElse("MISSING CHANNEL")); - if (!HandshakeHandler.packetNeedsResponse(context.get().getNetworkManager(), payloadIndex)) - { - context.get().setPacketHandled(true); //don't disconnect if the corresponding S2C packet that was not recognized on the client doesn't require a proper response - } - return; - } - short discriminator = payload.readUnsignedByte(); - final MessageHandler messageHandler = indicies.get(discriminator); - if (messageHandler == null) { - LOGGER.error(SIMPLENET, "Received invalid discriminator byte {} on channel {}", discriminator, Optional.ofNullable(networkInstance).map(NetworkInstance::getChannelName).map(Objects::toString).orElse("MISSING CHANNEL")); - return; - } - NetworkHooks.validatePacketDirection(context.get().getDirection(), messageHandler.networkDirection, context.get().getNetworkManager()); - tryDecode(payload, context, payloadIndex, messageHandler); - } - - MessageHandler addCodecIndex(int index, Class messageType, BiConsumer encoder, Function decoder, BiConsumer> messageConsumer, final Optional networkDirection) { - return new MessageHandler<>(index, messageType, encoder, decoder, messageConsumer, networkDirection); - } -} diff --git a/src/main/java/net/minecraftforge/network/simple/SimpleChannel.java b/src/main/java/net/minecraftforge/network/simple/SimpleChannel.java deleted file mode 100644 index 7ebac94637..0000000000 --- a/src/main/java/net/minecraftforge/network/simple/SimpleChannel.java +++ /dev/null @@ -1,313 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.network.simple; - -import io.netty.buffer.Unpooled; -import net.minecraft.client.Minecraft; -import net.minecraft.network.Connection; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.protocol.Packet; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.NetworkEvent; -import net.minecraftforge.network.NetworkInstance; -import net.minecraftforge.network.PacketDistributor; -import org.apache.commons.lang3.tuple.Pair; - -import java.util.*; -import java.util.function.*; - -@SuppressWarnings("OptionalUsedAsFieldOrParameterType") -public class SimpleChannel -{ - private final NetworkInstance instance; - private final IndexedMessageCodec indexedCodec; - private final Optional> registryChangeConsumer; - private List>>> loginPackets; - private Map, Boolean> packetsNeedResponse; - - public SimpleChannel(NetworkInstance instance) { - this(instance, Optional.empty()); - } - - private SimpleChannel(NetworkInstance instance, Optional> registryChangeNotify) { - this.instance = instance; - this.indexedCodec = new IndexedMessageCodec(instance); - this.loginPackets = new ArrayList<>(); - this.packetsNeedResponse = new HashMap<>(); - instance.addListener(this::networkEventListener); - instance.addGatherListener(this::networkLoginGather); - this.registryChangeConsumer = registryChangeNotify; - } - - public SimpleChannel(NetworkInstance instance, Consumer registryChangeNotify) { - this(instance, Optional.of(registryChangeNotify)); - } - - private void networkLoginGather(final NetworkEvent.GatherLoginPayloadsEvent gatherEvent) { - loginPackets.forEach(packetGenerator->{ - packetGenerator.apply(gatherEvent.isLocal()).forEach(p->{ - FriendlyByteBuf pb = new FriendlyByteBuf(Unpooled.buffer()); - this.indexedCodec.build(p.getRight(), pb); - gatherEvent.add(pb, this.instance.getChannelName(), p.getLeft(), packetsNeedResponse.getOrDefault(p.getRight().getClass(), true)); - }); - }); - } - private void networkEventListener(final NetworkEvent networkEvent) - { - if (networkEvent instanceof NetworkEvent.ChannelRegistrationChangeEvent) { - this.registryChangeConsumer.ifPresent(l->l.accept(((NetworkEvent.ChannelRegistrationChangeEvent) networkEvent))); - } else { - this.indexedCodec.consume(networkEvent.getPayload(), networkEvent.getLoginIndex(), networkEvent.getSource()); - } - } - - public int encodeMessage(MSG message, final FriendlyByteBuf target) { - return this.indexedCodec.build(message, target); - } - - public IndexedMessageCodec.MessageHandler registerMessage(int index, Class messageType, BiConsumer encoder, Function decoder, BiConsumer> messageConsumer) { - return registerMessage(index, messageType, encoder, decoder, messageConsumer, Optional.empty()); - } - - public IndexedMessageCodec.MessageHandler registerMessage(int index, Class messageType, BiConsumer encoder, Function decoder, BiConsumer> messageConsumer, final Optional networkDirection) { - return this.indexedCodec.addCodecIndex(index, messageType, encoder, decoder, messageConsumer, networkDirection); - } - - private Pair toBuffer(MSG msg) { - final FriendlyByteBuf bufIn = new FriendlyByteBuf(Unpooled.buffer()); - int index = encodeMessage(msg, bufIn); - return Pair.of(bufIn, index); - } - - public void sendToServer(MSG message) - { - sendTo(message, Minecraft.getInstance().getConnection().getConnection(), NetworkDirection.PLAY_TO_SERVER); - } - - public void sendTo(MSG message, Connection manager, NetworkDirection direction) - { - manager.send(toVanillaPacket(message, direction)); - } - - /** - * Send a message to the {@link PacketDistributor.PacketTarget} from a {@link PacketDistributor} instance. - * - *

-     *     channel.send(PacketDistributor.PLAYER.with(()->player), message)
-     * 
- * - * @param target The curried target from a PacketDistributor - * @param message The message to send - * @param The type of the message - */ - public void send(PacketDistributor.PacketTarget target, MSG message) { - target.send(toVanillaPacket(message, target.getDirection())); - } - - public Packet toVanillaPacket(MSG message, NetworkDirection direction) - { - return direction.buildPacket(toBuffer(message), instance.getChannelName()).getThis(); - } - - public void reply(MSG msgToReply, NetworkEvent.Context context) - { - context.getPacketDispatcher().sendPacket(instance.getChannelName(), toBuffer(msgToReply).getLeft()); - } - - /** - * Returns true if the channel is present in the given connection. - */ - public boolean isRemotePresent(Connection manager) { - return instance.isRemotePresent(manager); - } - - /** - * Build a new MessageBuilder. The type should implement {@link java.util.function.IntSupplier} if it is a login - * packet. - * @param type Type of message - * @param id id in the indexed codec - * @param Type of type - * @return a MessageBuilder - */ - public MessageBuilder messageBuilder(final Class type, int id) { - return MessageBuilder.forType(this, type, id, null); - } - - /** - * Build a new MessageBuilder. The type should implement {@link java.util.function.IntSupplier} if it is a login - * packet. - * @param type Type of message - * @param id id in the indexed codec - * @param direction a impl direction which will be asserted before any processing of this message occurs. Use to - * enforce strict sided handling to prevent spoofing. - * @param Type of type - * @return a MessageBuilder - */ - public MessageBuilder messageBuilder(final Class type, int id, NetworkDirection direction) { - return MessageBuilder.forType(this, type, id, direction); - } - - public static class MessageBuilder { - private SimpleChannel channel; - private Class type; - private int id; - private BiConsumer encoder; - private Function decoder; - private BiConsumer> consumer; - private Function loginIndexGetter; - private BiConsumer loginIndexSetter; - private Function>> loginPacketGenerators; - private Optional networkDirection; - private boolean needsResponse = true; - - private static MessageBuilder forType(final SimpleChannel channel, final Class type, int id, NetworkDirection networkDirection) { - MessageBuilder builder = new MessageBuilder<>(); - builder.channel = channel; - builder.id = id; - builder.type = type; - builder.networkDirection = Optional.ofNullable(networkDirection); - return builder; - } - - /** - * Set the message encoder, which writes this message to a {@link FriendlyByteBuf}. - *

- * The encoder is called immediately {@linkplain #send(PacketDistributor.PacketTarget, Object) 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 - * interact with the current game state. - * - * @param encoder The message encoder. - * @return This message builder, for chaining. - */ - public MessageBuilder encoder(BiConsumer encoder) { - this.encoder = encoder; - return this; - } - - /** - * 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 - * message is handled}. - * - * @param decoder The message decoder. - * @return The message builder, for chaining. - */ - public MessageBuilder decoder(Function decoder) { - this.decoder = decoder; - return this; - } - - public MessageBuilder loginIndex(Function loginIndexGetter, BiConsumer loginIndexSetter) { - this.loginIndexGetter = loginIndexGetter; - this.loginIndexSetter = loginIndexSetter; - return this; - } - - public MessageBuilder buildLoginPacketList(Function>> loginPacketGenerators) { - this.loginPacketGenerators = loginPacketGenerators; - return this; - } - - public MessageBuilder markAsLoginPacket() - { - this.loginPacketGenerators = (isLocal) -> { - try { - return Collections.singletonList(Pair.of(type.getName(), type.newInstance())); - } catch (InstantiationException | IllegalAccessException e) { - throw new RuntimeException("Inaccessible no-arg constructor for message "+type.getName(), e); - } - }; - return this; - } - - /** - * Marks this packet as not needing a response when sent to the client - */ - public MessageBuilder noResponse() - { - this.needsResponse = false; - 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. - *

- * The consumer is called on the network thread, and so should not interact with most game state by default. - * {@link NetworkEvent.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 consumerNetworkThread(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. - *

- * Unlike {@link #consumerNetworkThread(BiConsumer)}, the consumer is called on the main thread, and so can - * interact with most game state by default. - * - * @param consumer The message consumer. - * @return The message builder, for chaining. - * @see #consumerNetworkThread(BiConsumer) - */ - public MessageBuilder consumerMainThread(BiConsumer> consumer) { - this.consumer = (msg, context) -> { - var ctx = context.get(); - ctx.enqueueWork(() -> consumer.accept(msg, context)); - ctx.setPacketHandled(true); - }; - return this; - } - - public interface ToBooleanBiFunction { - boolean applyAsBool(T first, U second); - } - - /** - * Function returning a boolean "packet handled" indication, for simpler channel building. - * @param handler a handler - * @return this - * @see #consumerNetworkThread(BiConsumer) - */ - public MessageBuilder consumerNetworkThread(ToBooleanBiFunction> handler) { - this.consumer = (msg, ctx) -> { - boolean handled = handler.applyAsBool(msg, ctx); - ctx.get().setPacketHandled(handled); - }; - return this; - } - - public void add() { - final IndexedMessageCodec.MessageHandler message = this.channel.registerMessage(this.id, this.type, this.encoder, this.decoder, this.consumer, this.networkDirection); - if (this.loginIndexSetter != null) { - message.setLoginIndexSetter(this.loginIndexSetter); - } - if (this.loginIndexGetter != null) { - if (!IntSupplier.class.isAssignableFrom(this.type)) { - throw new IllegalArgumentException("Login packet type that does not supply an index as an IntSupplier"); - } - message.setLoginIndexGetter(this.loginIndexGetter); - } - if (this.loginPacketGenerators != null) { - this.channel.loginPackets.add(this.loginPacketGenerators); - } - this.channel.packetsNeedResponse.put(this.type, this.needsResponse); - } - } -} diff --git a/src/main/java/net/minecraftforge/network/tasks/ChannelVersionsTask.java b/src/main/java/net/minecraftforge/network/tasks/ChannelVersionsTask.java new file mode 100644 index 0000000000..245529a13e --- /dev/null +++ b/src/main/java/net/minecraftforge/network/tasks/ChannelVersionsTask.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.tasks; + +import java.util.function.Consumer; +import org.jetbrains.annotations.ApiStatus; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.server.network.ConfigurationTask; +import net.minecraftforge.network.NetworkInitialization; +import net.minecraftforge.network.config.ConfigurationTaskContext; +import net.minecraftforge.network.packets.ChannelVersions; + +/** + * Sends the list of known channels to the client as well as their specific versions. + * Allows the client to do compatibility checking. + */ +@ApiStatus.Internal +public class ChannelVersionsTask implements ConfigurationTask { + public static final Type TYPE = new Type("forge:channel_list"); + + @Override + public void start(ConfigurationTaskContext ctx) { + NetworkInitialization.PLAY.send(new ChannelVersions(), ctx.getConnection()); + } + + @Override + public void start(Consumer> send) { + throw new IllegalStateException("This should never be called"); + } + + @Override + public Type type() { + return TYPE; + } +} diff --git a/src/main/java/net/minecraftforge/network/tasks/ForgeNetworkConfigurationHandler.java b/src/main/java/net/minecraftforge/network/tasks/ForgeNetworkConfigurationHandler.java new file mode 100644 index 0000000000..125c393394 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/tasks/ForgeNetworkConfigurationHandler.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.tasks; + +import org.jetbrains.annotations.ApiStatus; + +import net.minecraftforge.event.network.GatherLoginConfigurationTasksEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.network.ConnectionType; +import net.minecraftforge.network.NetworkContext; + +@ApiStatus.Internal +public class ForgeNetworkConfigurationHandler { + @SubscribeEvent + public void gatherInit(GatherLoginConfigurationTasksEvent event) { + var ctx = NetworkContext.get(event.getConnection()); + if (ctx.getType() != ConnectionType.MODDED) + return; + + // Send minecraft:register packet for all known channels. This allows the other side to know what we can talk about. + event.addTask(new RegisterChannelsTask()); + // Send the mod version and display name to the client so that it can check for compatibility, Currently doesn't really do anything + // We expect a response from the client + event.addTask(new ModVersionsTask()); + // Send the channel list to the client, which is checked on the client to make sure it knows how to talk to the server. + // We expect a Response from the client + event.addTask(new ChannelVersionsTask()); + // Sync all of our registry mappings + event.addTask(new SyncRegistriesTask()); + // Lastly sync raw mod config files. We send raw file bytes, which is very inefficient, but we can change it later. //TODO: Compress/Optimize config file data + event.addTask(new SyncConfigTask()); + } +} diff --git a/src/main/java/net/minecraftforge/network/tasks/ModVersionsTask.java b/src/main/java/net/minecraftforge/network/tasks/ModVersionsTask.java new file mode 100644 index 0000000000..cc00121695 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/tasks/ModVersionsTask.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.tasks; + +import java.util.function.Consumer; +import org.jetbrains.annotations.ApiStatus; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.server.network.ConfigurationTask; +import net.minecraftforge.network.NetworkInitialization; +import net.minecraftforge.network.config.ConfigurationTaskContext; +import net.minecraftforge.network.packets.ModVersions; + +/** + * Sends the list of known channels to the client using the + * Plugin Channel + * register messages. + */ +@ApiStatus.Internal +public class ModVersionsTask implements ConfigurationTask { + public static final Type TYPE = new Type("forge:channel_list"); + + @Override + public void start(ConfigurationTaskContext ctx) { + NetworkInitialization.PLAY.send(ModVersions.create(), ctx.getConnection()); + } + + @Override + public void start(Consumer> send) { + throw new IllegalStateException("This should never be called"); + } + + @Override + public Type type() { + return TYPE; + } +} diff --git a/src/main/java/net/minecraftforge/network/tasks/RegisterChannelsTask.java b/src/main/java/net/minecraftforge/network/tasks/RegisterChannelsTask.java new file mode 100644 index 0000000000..cf764040f4 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/tasks/RegisterChannelsTask.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.tasks; + +import java.util.function.Consumer; + +import org.jetbrains.annotations.ApiStatus; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.server.network.ConfigurationTask; +import net.minecraftforge.network.ChannelListManager; +import net.minecraftforge.network.config.ConfigurationTaskContext; + +/** + * Sends the list of known channels to the client using the + * Plugin Channel + * register messages. + */ +@ApiStatus.Internal +class RegisterChannelsTask implements ConfigurationTask { + private static final Type TYPE = new Type("forge:send_vanilla_channel_list"); + + @Override + public void start(ConfigurationTaskContext ctx) { + ChannelListManager.addChannels(ctx.getConnection()); + ctx.finish(type()); + } + + @Override + public void start(Consumer> send) { + throw new IllegalStateException("This should never be called"); + } + + @Override + public Type type() { + return TYPE; + } +} diff --git a/src/main/java/net/minecraftforge/network/tasks/SyncConfigTask.java b/src/main/java/net/minecraftforge/network/tasks/SyncConfigTask.java new file mode 100644 index 0000000000..9f680f5abb --- /dev/null +++ b/src/main/java/net/minecraftforge/network/tasks/SyncConfigTask.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.network.tasks; + +import java.io.IOException; +import java.nio.file.Files; +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 net.minecraft.network.chat.Component; +import net.minecraftforge.fml.config.ConfigTracker; +import net.minecraftforge.fml.config.ModConfig; +import net.minecraftforge.network.NetworkInitialization; +import net.minecraftforge.network.config.ConfigurationTaskContext; +import net.minecraftforge.network.config.SimpleConfigurationTask; +import net.minecraftforge.network.packets.ConfigData; + +@ApiStatus.Internal +class SyncConfigTask extends SimpleConfigurationTask { + static final Type TYPE = new Type("forge:sync_configs"); + private static final Logger LOGGER = LogManager.getLogger(); + private static final Marker MARKER = MarkerManager.getMarker("FORGE_SYNC_CONFIG"); + + SyncConfigTask() { + super(TYPE, SyncConfigTask::run); + } + + private static void run(ConfigurationTaskContext ctx) { + 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()); + } 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 new file mode 100644 index 0000000000..9d020e47f6 --- /dev/null +++ b/src/main/java/net/minecraftforge/network/tasks/SyncRegistriesTask.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +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; + +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 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; +import net.minecraft.server.network.ConfigurationTask; +import net.minecraftforge.event.network.CustomPayloadEvent; +import net.minecraftforge.network.ForgePacketHandler; +import net.minecraftforge.network.NetworkInitialization; +import net.minecraftforge.network.config.ConfigurationTaskContext; +import net.minecraftforge.network.packets.Acknowledge; +import net.minecraftforge.network.packets.RegistryData; +import net.minecraftforge.network.packets.RegistryList; +import net.minecraftforge.registries.ForgeRegistry.Snapshot; +import net.minecraftforge.registries.RegistryManager; + +/** + * Sends the list of known channels to the client as well as their specific versions. + * Allows the client to do compatibility checking. + */ +@ApiStatus.Internal +public class SyncRegistriesTask implements ConfigurationTask { + private static final Logger LOGGER = LogManager.getLogger(); + private static final Marker MARKER = MarkerManager.getMarker("SYNC_REGISTRIES_TASK"); + public static final Type TYPE = new Type("forge:sync_registries"); + + private ConfigurationTaskContext taskCtx; + private Map snapshot; + private ForgePacketHandler handler; + private int expectedToken; + + @Override + public void start(ConfigurationTaskContext ctx) { + this.taskCtx = ctx; + var con = ctx.getConnection(); + handler = con.channel().attr(NetworkInitialization.CONTEXT).get(); + + // If we're in memory, then don't actually sync the registries. + if (!ctx.getConnection().isMemoryConnection()) + this.snapshot = RegistryManager.ACTIVE.takeSnapshot(false); + + expectedToken = handler.expectAck(this::sendRegistries); + NetworkInitialization.PLAY.send(new RegistryList(expectedToken), con); + } + + private void sendRegistries(Acknowledge msg, CustomPayloadEvent.Context ctx) { + if (msg.token() != expectedToken) { + LOGGER.error(MARKER, "Received unknown acknowledgement received {} exptected {}", msg.token(), expectedToken); + ctx.getConnection().disconnect(Component.literal("Illegal Acknowledge packet received, unknown token: " + msg.token())); + return; + } + + // We've got no more to send, so finish this task! + if (this.snapshot == null || this.snapshot.isEmpty()) { + taskCtx.finish(type()); + return; + } + + // Send the next registry! + 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); + } + + @Override + public void start(Consumer> send) { + throw new IllegalStateException("This should never be called"); + } + + @Override + public Type type() { + return TYPE; + } +} diff --git a/src/main/java/net/minecraftforge/registries/DataPackRegistriesHooks.java b/src/main/java/net/minecraftforge/registries/DataPackRegistriesHooks.java index 360cb39ac7..3138464131 100644 --- a/src/main/java/net/minecraftforge/registries/DataPackRegistriesHooks.java +++ b/src/main/java/net/minecraftforge/registries/DataPackRegistriesHooks.java @@ -14,7 +14,6 @@ import org.jetbrains.annotations.ApiStatus; import java.util.ArrayList; import java.util.Collections; -import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; @@ -23,8 +22,7 @@ import java.util.Set; import java.util.stream.Stream; @ApiStatus.Internal -public final class DataPackRegistriesHooks -{ +public final class DataPackRegistriesHooks { private DataPackRegistriesHooks() {} // utility class private static final Map>, RegistrySynchronization.NetworkedRegistryData> NETWORKABLE_REGISTRIES = new LinkedHashMap<>(); @@ -34,8 +32,7 @@ public final class DataPackRegistriesHooks private static final Set>> SYNCED_CUSTOM_REGISTRIES_VIEW = Collections.unmodifiableSet(SYNCED_CUSTOM_REGISTRIES); /* Internal forge hook for retaining mutable access to RegistryAccess's codec registry when it bootstraps. */ - public static Map>, RegistrySynchronization.NetworkedRegistryData> grabNetworkableRegistries(ImmutableMap.Builder>, RegistrySynchronization.NetworkedRegistryData> builder) - { + public static Map>, RegistrySynchronization.NetworkedRegistryData> grabNetworkableRegistries(ImmutableMap.Builder>, RegistrySynchronization.NetworkedRegistryData> builder) { if (!StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).getCallerClass().equals(RegistrySynchronization.class)) throw new IllegalCallerException("Attempted to call DataPackRegistriesHooks#grabNetworkableRegistries!"); NETWORKABLE_REGISTRIES.forEach(builder::put); @@ -45,12 +42,10 @@ public final class DataPackRegistriesHooks } /* Internal forge method, registers a datapack registry codec and folder. */ - static void addRegistryCodec(DataPackRegistryEvent.DataPackRegistryData data) - { + static void addRegistryCodec(DataPackRegistryEvent.DataPackRegistryData data) { RegistryDataLoader.RegistryData loaderData = data.loaderData(); DATA_PACK_REGISTRIES.add(loaderData); - if (data.networkCodec() != null) - { + if (data.networkCodec() != null) { SYNCED_CUSTOM_REGISTRIES.add(loaderData.key()); NETWORKABLE_REGISTRIES.put(loaderData.key(), new RegistrySynchronization.NetworkedRegistryData<>(loaderData.key(), data.networkCodec())); } @@ -60,8 +55,7 @@ public final class DataPackRegistriesHooks * {@return An unmodifiable view of the list of datapack registries}. * These registries are loaded from per-world datapacks on server startup. */ - public static List> getDataPackRegistries() - { + public static List> getDataPackRegistries() { return DATA_PACK_REGISTRIES_VIEW; } @@ -74,8 +68,7 @@ public final class DataPackRegistriesHooks * Clients must have each of a server's synced datapack registries to be able to connect to that server; * vanilla clients therefore cannot connect if this list is non-empty on the server. */ - public static Set>> getSyncedCustomRegistries() - { + public static Set>> getSyncedCustomRegistries() { return SYNCED_CUSTOM_REGISTRIES_VIEW; } } diff --git a/src/main/java/net/minecraftforge/registries/ForgeRegistry.java b/src/main/java/net/minecraftforge/registries/ForgeRegistry.java index a1a0d7caf3..121229e9d9 100644 --- a/src/main/java/net/minecraftforge/registries/ForgeRegistry.java +++ b/src/main/java/net/minecraftforge/registries/ForgeRegistry.java @@ -946,8 +946,7 @@ public class ForgeRegistry implements IForgeRegistryInternal, IForgeRegist } } - public static class Snapshot - { + public static class Snapshot { private static final Comparator sorter = (a,b) -> a.compareNamespaced(b); public final Map ids = Maps.newTreeMap(sorter); public final Map aliases = Maps.newTreeMap(sorter); @@ -955,13 +954,11 @@ public class ForgeRegistry implements IForgeRegistryInternal, IForgeRegist public final Map overrides = Maps.newTreeMap(sorter); private FriendlyByteBuf binary = null; - public CompoundTag write() - { + public CompoundTag write() { CompoundTag data = new CompoundTag(); ListTag ids = new ListTag(); - this.ids.entrySet().stream().forEach(e -> - { + this.ids.entrySet().stream().forEach(e -> { CompoundTag tag = new CompoundTag(); tag.putString("K", e.getKey().toString()); tag.putInt("V", e.getValue()); @@ -970,8 +967,7 @@ public class ForgeRegistry implements IForgeRegistryInternal, IForgeRegist data.put("ids", ids); ListTag aliases = new ListTag(); - this.aliases.entrySet().stream().forEach(e -> - { + this.aliases.entrySet().stream().forEach(e -> { CompoundTag tag = new CompoundTag(); tag.putString("K", e.getKey().toString()); tag.putString("V", e.getValue().toString()); @@ -980,8 +976,7 @@ public class ForgeRegistry implements IForgeRegistryInternal, IForgeRegist data.put("aliases", aliases); ListTag overrides = new ListTag(); - this.overrides.entrySet().stream().forEach(e -> - { + this.overrides.entrySet().stream().forEach(e -> { CompoundTag tag = new CompoundTag(); tag.putString("K", e.getKey().toString()); tag.putString("V", e.getValue()); @@ -995,99 +990,58 @@ public class ForgeRegistry implements IForgeRegistryInternal, IForgeRegist return data; } - public static Snapshot read(CompoundTag nbt) - { + public static Snapshot read(CompoundTag nbt) { Snapshot ret = new Snapshot(); if (nbt == null) - { return ret; - } ListTag list = nbt.getList("ids", 10); - list.forEach(e -> - { + list.forEach(e -> { CompoundTag comp = (CompoundTag)e; ret.ids.put(new ResourceLocation(comp.getString("K")), comp.getInt("V")); }); list = nbt.getList("aliases", 10); - list.forEach(e -> - { + list.forEach(e -> { CompoundTag comp = (CompoundTag)e; ret.aliases.put(new ResourceLocation(comp.getString("K")), new ResourceLocation(comp.getString("V"))); }); list = nbt.getList("overrides", 10); - list.forEach(e -> - { + list.forEach(e -> { CompoundTag comp = (CompoundTag)e; ret.overrides.put(new ResourceLocation(comp.getString("K")), comp.getString("V")); }); int[] blocked = nbt.getIntArray("blocked"); for (int i : blocked) - { ret.blocked.add(i); - } return ret; } - public synchronized FriendlyByteBuf getPacketData() - { + public synchronized FriendlyByteBuf getPacketData() { if (binary == null) { FriendlyByteBuf pkt = new FriendlyByteBuf(Unpooled.buffer()); - - pkt.writeVarInt(this.ids.size()); - this.ids.forEach((k,v) -> { - pkt.writeResourceLocation(k); - pkt.writeVarInt(v); - }); - - pkt.writeVarInt(this.aliases.size()); - this.aliases.forEach((k, v) -> { - pkt.writeResourceLocation(k); - pkt.writeResourceLocation(v); - }); - - pkt.writeVarInt(this.overrides.size()); - this.overrides.forEach((k, v) -> { - pkt.writeResourceLocation(k); - pkt.writeUtf(v, 0x100); - }); - - pkt.writeVarInt(this.blocked.size()); - this.blocked.forEach(pkt::writeVarInt); - + pkt.writeMap(this.ids, FriendlyByteBuf::writeResourceLocation, FriendlyByteBuf::writeVarInt); + pkt.writeMap(this.aliases, FriendlyByteBuf::writeResourceLocation, FriendlyByteBuf::writeResourceLocation); + pkt.writeMap(this.overrides, FriendlyByteBuf::writeResourceLocation, (b,v) -> b.writeUtf(v, 0x100)); + pkt.writeCollection(this.blocked, FriendlyByteBuf::writeVarInt); this.binary = pkt; } return new FriendlyByteBuf(binary.slice()); } - public static Snapshot read(FriendlyByteBuf buff) - { - if (buff == null) + public static Snapshot read(FriendlyByteBuf buf) { + if (buf == null) return new Snapshot(); - Snapshot ret = new Snapshot(); - - int len = buff.readVarInt(); - for (int x = 0; x < len; x++) - ret.ids.put(buff.readResourceLocation(), buff.readVarInt()); - - len = buff.readVarInt(); - for (int x = 0; x < len; x++) - ret.aliases.put(buff.readResourceLocation(), buff.readResourceLocation()); - - len = buff.readVarInt(); - for (int x = 0; x < len; x++) - ret.overrides.put(buff.readResourceLocation(), buff.readUtf(0x100)); - - len = buff.readVarInt(); - for (int x = 0; x < len; x++) - ret.blocked.add(buff.readVarInt()); - + var ret = new Snapshot(); + ret.ids.putAll(buf.readMap(FriendlyByteBuf::readResourceLocation, FriendlyByteBuf::readVarInt)); + ret.aliases.putAll(buf.readMap(FriendlyByteBuf::readResourceLocation, FriendlyByteBuf::readResourceLocation)); + ret.overrides.putAll(buf.readMap(FriendlyByteBuf::readResourceLocation, b -> b.readUtf(0x100))); + ret.blocked.addAll(buf.readList(FriendlyByteBuf::readVarInt)); return ret; } } diff --git a/src/main/java/net/minecraftforge/registries/RegistryManager.java b/src/main/java/net/minecraftforge/registries/RegistryManager.java index da1670b626..fa8163bc32 100644 --- a/src/main/java/net/minecraftforge/registries/RegistryManager.java +++ b/src/main/java/net/minecraftforge/registries/RegistryManager.java @@ -10,11 +10,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.stream.Collectors; - import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; -import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.mojang.serialization.Lifecycle; @@ -24,14 +21,12 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.core.Registry; import net.minecraftforge.fml.ModLoader; -import net.minecraftforge.network.HandshakeMessages; import net.minecraftforge.registries.ForgeRegistry.Snapshot; -import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.ApiStatus; -public class RegistryManager -{ +public class RegistryManager { private static final Logger LOGGER = LogManager.getLogger(); public static final RegistryManager ACTIVE = new RegistryManager("ACTIVE"); public static final RegistryManager VANILLA = new RegistryManager("VANILLA"); @@ -39,65 +34,61 @@ public class RegistryManager private static Set vanillaRegistryKeys = Set.of(); BiMap> registries = HashBiMap.create(); + private Map> registryView = Collections.unmodifiableMap(registries); private Set persisted = Sets.newHashSet(); private Set synced = Sets.newHashSet(); private Map legacyNames = new HashMap<>(); private final String name; - RegistryManager() - { + RegistryManager() { this("STAGING"); } - public RegistryManager(String name) - { + public RegistryManager(String name) { this.name = name; } - public String getName() - { + public String getName() { return this.name; } - boolean isStaging() - { + boolean isStaging() { return "STAGING".equals(this.name); } @SuppressWarnings("unchecked") - public ForgeRegistry getRegistry(ResourceLocation key) - { + public ForgeRegistry getRegistry(ResourceLocation key) { return (ForgeRegistry)this.registries.get(key); } - public ForgeRegistry getRegistry(ResourceKey> key) - { + public ForgeRegistry getRegistry(ResourceKey> key) { return getRegistry(key.location()); } - public ResourceLocation getName(IForgeRegistry reg) - { + public ResourceLocation getName(IForgeRegistry reg) { return this.registries.inverse().get(reg); } - public ResourceLocation updateLegacyName(ResourceLocation legacyName) - { + public Map> getRegistries() { + return this.registryView; + } + + public static Set getVanillaRegistryKeys() { + return vanillaRegistryKeys; + } + + public ResourceLocation updateLegacyName(ResourceLocation legacyName) { ResourceLocation originalName = legacyName; - while (getRegistry(legacyName) == null) - { + while (getRegistry(legacyName) == null) { legacyName = legacyNames.get(legacyName); if (legacyName == null) - { return originalName; - } } return legacyName; } - public ForgeRegistry getRegistry(ResourceLocation key, RegistryManager other) - { - if (!this.registries.containsKey(key)) - { + public ForgeRegistry getRegistry(ResourceLocation key, RegistryManager other) { + if (!this.registries.containsKey(key)) { ForgeRegistry ot = other.getRegistry(key); if (ot == null) return null; @@ -113,8 +104,7 @@ public class RegistryManager return getRegistry(key); } - ForgeRegistry createRegistry(ResourceLocation name, RegistryBuilder builder) - { + ForgeRegistry createRegistry(ResourceLocation name, RegistryBuilder builder) { if (registries.containsKey(name)) throw new IllegalArgumentException("Attempted to register a registry for " + name + " but it already exists"); ForgeRegistry reg = new ForgeRegistry(this, name, builder); @@ -128,22 +118,19 @@ public class RegistryManager return getRegistry(name); } - static void registerToRootRegistry(ForgeRegistry forgeReg) - { + static void registerToRootRegistry(ForgeRegistry forgeReg) { injectForgeRegistry(forgeReg, BuiltInRegistries.REGISTRY); } @SuppressWarnings("unchecked") - private static void injectForgeRegistry(ForgeRegistry forgeReg, Registry> rootRegistry) - { + private static void injectForgeRegistry(ForgeRegistry forgeReg, Registry> rootRegistry) { WritableRegistry> registry = (WritableRegistry>) rootRegistry; Registry wrapper = forgeReg.getWrapper(); if (wrapper != null) registry.register(forgeReg.getRegistryKey(), wrapper, Lifecycle.experimental()); } - public static void postNewRegistryEvent() - { + public static void postNewRegistryEvent() { NewRegistryEvent event = new NewRegistryEvent(); DataPackRegistryEvent.NewRegistry dataPackEvent = new DataPackRegistryEvent.NewRegistry(); vanillaRegistryKeys = Set.copyOf(BuiltInRegistries.REGISTRY.keySet()); @@ -155,61 +142,29 @@ public class RegistryManager dataPackEvent.process(); } - private void addLegacyName(ResourceLocation legacyName, ResourceLocation name) - { + private void addLegacyName(ResourceLocation legacyName, ResourceLocation name) { if (this.legacyNames.containsKey(legacyName)) - { throw new IllegalArgumentException("Legacy name conflict for registry " + name + ", upgrade path must be linear: " + legacyName); - } this.legacyNames.put(legacyName, name); } - private void findSuperTypes(Class type, Set> types) - { - if (type == null || type == Object.class) - { - return; - } - types.add(type); - for (Class interfac : type.getInterfaces()) - { - findSuperTypes(interfac, types); - } - findSuperTypes(type.getSuperclass(), types); - } - - public Map takeSnapshot(boolean savingToDisc) - { - Map ret = Maps.newHashMap(); - Set keys = savingToDisc ? this.persisted : this.synced; + public Map takeSnapshot(boolean savingToDisc) { + Map ret = new HashMap<>(); + var keys = savingToDisc ? this.persisted : this.synced; keys.forEach(name -> ret.put(name, getRegistry(name).makeSnapshot())); return ret; } //Public for testing only - public void clean() - { + @ApiStatus.Internal + public void clean() { this.persisted.clear(); this.synced.clear(); this.registries.clear(); } - public static List> generateRegistryPackets(boolean isLocal) - { - return !isLocal ? ACTIVE.takeSnapshot(false).entrySet().stream(). - map(e->Pair.of("Registry " + e.getKey(), new HandshakeMessages.S2CRegistry(e.getKey(), e.getValue()))). - collect(Collectors.toList()) : Collections.emptyList(); - } - - public static List getRegistryNamesForSyncToClient() - { - return ACTIVE.registries.keySet().stream(). - filter(resloc -> ACTIVE.synced.contains(resloc)). - collect(Collectors.toList()); - } - - public static Set getVanillaRegistryKeys() - { - return vanillaRegistryKeys; + @ApiStatus.Internal + public static List getRegistryNamesForSyncToClient() { + return ACTIVE.registries.keySet().stream().filter(ACTIVE.synced::contains).toList(); } } diff --git a/src/main/java/net/minecraftforge/server/ServerLifecycleHooks.java b/src/main/java/net/minecraftforge/server/ServerLifecycleHooks.java index 96f410d546..ae793a88bf 100644 --- a/src/main/java/net/minecraftforge/server/ServerLifecycleHooks.java +++ b/src/main/java/net/minecraftforge/server/ServerLifecycleHooks.java @@ -20,8 +20,13 @@ import net.minecraft.core.Holder; import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.Registries; import net.minecraft.gametest.framework.GameTestServer; +import net.minecraft.network.Connection; +import net.minecraft.network.ConnectionProtocol; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.protocol.handshake.ClientIntent; +import net.minecraft.network.protocol.handshake.ClientIntentionPacket; +import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket; import net.minecraft.server.packs.PackResources; import net.minecraft.server.packs.PackType; import net.minecraft.server.packs.repository.PackSource; @@ -35,11 +40,10 @@ import net.minecraftforge.common.world.BiomeModifier; import net.minecraftforge.fml.ModLoader; import net.minecraftforge.fml.ModLoadingStage; import net.minecraftforge.fml.ModLoadingWarning; -import net.minecraftforge.network.ConnectionType; -import net.minecraftforge.network.NetworkConstants; -import net.minecraftforge.network.NetworkHooks; -import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.forgespi.locating.IModFile; +import net.minecraftforge.network.ConnectionType; +import net.minecraftforge.network.NetworkContext; +import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.registries.ForgeRegistries.Keys; import net.minecraftforge.resource.PathPackResources; import net.minecraftforge.server.permission.PermissionAPI; @@ -48,10 +52,6 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; -import net.minecraft.network.Connection; -import net.minecraft.network.ConnectionProtocol; -import net.minecraft.network.protocol.handshake.ClientIntentionPacket; -import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket; import net.minecraft.server.packs.repository.Pack; import net.minecraft.server.packs.repository.Pack.Info; import net.minecraft.server.MinecraftServer; @@ -69,16 +69,17 @@ import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.GameData; import org.jetbrains.annotations.ApiStatus; -public class ServerLifecycleHooks -{ +@SuppressWarnings("deprecation") +@ApiStatus.Internal +public class ServerLifecycleHooks { private static final Logger LOGGER = LogManager.getLogger(); private static final Marker SERVERHOOKS = MarkerManager.getMarker("SERVERHOOKS"); private static final LevelResource SERVERCONFIG = new LevelResource("serverconfig"); + private static final AtomicBoolean allowLogins = new AtomicBoolean(false); private static volatile CountDownLatch exitLatch = null; private static MinecraftServer currentServer; - private static Path getServerConfigPath(final MinecraftServer server) - { + private static Path getServerConfigPath(final MinecraftServer server) { final Path serverConfig = server.getWorldPath(SERVERCONFIG); if (!Files.isDirectory(serverConfig)) { try { @@ -90,8 +91,7 @@ public class ServerLifecycleHooks return serverConfig; } - public static boolean handleServerAboutToStart(final MinecraftServer server) - { + public static boolean handleServerAboutToStart(final MinecraftServer server) { currentServer = server; // on the dedi server we need to force the stuff to setup properly LogicalSidedProvider.setServer(()->server); @@ -100,8 +100,7 @@ public class ServerLifecycleHooks return !MinecraftForge.EVENT_BUS.post(new ServerAboutToStartEvent(server)); } - public static boolean handleServerStarting(final MinecraftServer server) - { + public static boolean handleServerStarting(final MinecraftServer server) { DistExecutor.runWhenOn(Dist.DEDICATED_SERVER, ()->()->{ LanguageHook.loadLanguagesOnServer(server); // GameTestServer requires the gametests to be registered earlier, so it is done in main and should not be done twice. @@ -112,90 +111,28 @@ public class ServerLifecycleHooks return !MinecraftForge.EVENT_BUS.post(new ServerStartingEvent(server)); } - public static void handleServerStarted(final MinecraftServer server) - { - MinecraftForge.EVENT_BUS.post(new ServerStartedEvent(server)); - allowLogins.set(true); - } - public static void handleServerStopping(final MinecraftServer server) - { - allowLogins.set(false); - MinecraftForge.EVENT_BUS.post(new ServerStoppingEvent(server)); - } - - public static void expectServerStopped() - { + public static void expectServerStopped() { exitLatch = new CountDownLatch(1); } - public static void handleServerStopped(final MinecraftServer server) - { + public static void handleServerStopped(final MinecraftServer server) { if (!server.isDedicatedServer()) GameData.revertToFrozen(); MinecraftForge.EVENT_BUS.post(new ServerStoppedEvent(server)); currentServer = null; LogicalSidedProvider.setServer(null); CountDownLatch latch = exitLatch; - if (latch != null) - { + if (latch != null) { latch.countDown(); exitLatch = null; } ConfigTracker.INSTANCE.unloadConfigs(ModConfig.Type.SERVER, getServerConfigPath(server)); } - public static MinecraftServer getCurrentServer() - { + public static MinecraftServer getCurrentServer() { return currentServer; } - private static AtomicBoolean allowLogins = new AtomicBoolean(false); - - public static boolean handleServerLogin(final ClientIntentionPacket packet, final Connection manager) { - if (!allowLogins.get()) - { - MutableComponent text = Component.literal("Server is still starting! Please wait before reconnecting."); - LOGGER.info(SERVERHOOKS,"Disconnecting Player (server is still starting): {}", text.getContents()); - manager.send(new ClientboundLoginDisconnectPacket(text)); - manager.disconnect(text); - return false; - } - - if (packet.nextProtocol() == ConnectionProtocol.LOGIN) { - var fmlVersion = NetworkHooks.getFMLVersion(packet.hostName()); - final ConnectionType connectionType = ConnectionType.forVersionFlag(fmlVersion); - final int versionNumber = connectionType.getFMLVersionNumber(fmlVersion); - - if (connectionType == ConnectionType.MODDED && versionNumber != NetworkConstants.FMLNETVERSION) { - rejectConnection(manager, connectionType, "This modded server is not impl compatible with your modded client. Please verify your Forge version closely matches the server. Got net version " + versionNumber + " this server is net version " + NetworkConstants.FMLNETVERSION); - return false; - } - - if (connectionType == ConnectionType.VANILLA && !NetworkRegistry.acceptsVanillaClientConnections()) { - rejectConnection(manager, connectionType, "This server has mods that require Forge to be installed on the client. Contact your server admin for more details."); - return false; - } - } - - if (packet.nextProtocol() == ConnectionProtocol.STATUS) return true; - - NetworkHooks.registerServerLoginChannel(manager, packet); - return true; - - } - - private static void rejectConnection(final Connection manager, ConnectionType type, String message) { - //manager.setProtocol(ConnectionProtocol.LOGIN); Pretty sure things auto swap in ProtocolSwapHandler - LOGGER.info(SERVERHOOKS, "[{}] Disconnecting {} connection attempt: {}", manager.getLoggableAddress(true), type, message); // TODO: Respect logIP setting - MutableComponent text = Component.literal(message); - manager.send(new ClientboundLoginDisconnectPacket(text)); - manager.disconnect(text); - } - - public static void handleExit(int retVal) - { - System.exit(retVal); - } @ApiStatus.Internal public static RepositorySource buildPackFinder(Map modResourcePacks) { @@ -203,8 +140,7 @@ public class ServerLifecycleHooks } private static void serverPackFinder(Map modResourcePacks, Consumer packAcceptor) { - for (Entry e : modResourcePacks.entrySet()) - { + for (Entry e : modResourcePacks.entrySet()) { IModInfo mod = e.getKey().getModInfos().get(0); if (Objects.equals(mod.getModId(), "minecraft")) continue; // skip the minecraft "mod" final String name = "mod:" + mod.getModId(); @@ -233,8 +169,7 @@ public class ServerLifecycleHooks } } - private static void runModifiers(final MinecraftServer server) - { + private static void runModifiers(final MinecraftServer server) { final RegistryAccess registries = server.registryAccess(); // The order of holders() is the order modifiers were loaded in. @@ -249,13 +184,57 @@ public class ServerLifecycleHooks // Apply sorted biome modifiers to each biome. registries.registryOrThrow(Registries.BIOME).holders().forEach(biomeHolder -> - { - biomeHolder.value().modifiableBiomeInfo().applyBiomeModifiers(biomeHolder, biomeModifiers); - }); + biomeHolder.value().modifiableBiomeInfo().applyBiomeModifiers(biomeHolder, biomeModifiers) + ); // Apply sorted structure modifiers to each structure. registries.registryOrThrow(Registries.STRUCTURE).holders().forEach(structureHolder -> - { - structureHolder.value().modifiableStructureInfo().applyStructureModifiers(structureHolder, structureModifiers); - }); + structureHolder.value().modifiableStructureInfo().applyStructureModifiers(structureHolder, structureModifiers) + ); + } + + //================================================================================================================================================================================== + //================================================================================================================================================================================== + //================================================================================================================================================================================== + //================================================================================================================================================================================== + //================================================================================================================================================================================== + //================================================================================================================================================================================== + + public static void handleServerStarted(final MinecraftServer server) { + MinecraftForge.EVENT_BUS.post(new ServerStartedEvent(server)); + allowLogins.set(true); + } + + public static void handleServerStopping(final MinecraftServer server) { + allowLogins.set(false); + MinecraftForge.EVENT_BUS.post(new ServerStoppingEvent(server)); + } + + public static boolean handleServerLogin(final ClientIntentionPacket packet, final Connection connection) { + var ctx = NetworkContext.get(connection); + ctx.processIntention(packet.hostName()); + + if (!allowLogins.get()) + return rejectConnection(connection, ctx.getType(), "Server is still starting! Please wait before reconnecting."); + + if (packet.nextProtocol() != ConnectionProtocol.LOGIN) + return true; + + if (ctx.getType() == ConnectionType.MODDED && ctx.getNetVersion() != NetworkContext.NET_VERSION) + return rejectConnection(connection, ctx.getType(), "This modded server is not impl compatible with your modded client. Please verify your Forge version closely matches the server. Got net version " + ctx.getNetVersion() + " this server is net version " + NetworkContext.NET_VERSION); + + if (ctx.getType() == ConnectionType.VANILLA && !NetworkRegistry.acceptsVanillaClientConnections()) + return rejectConnection(connection, ctx.getType(), "This server has mods that require Forge to be installed on the client. Contact your server admin for more details."); + + NetworkRegistry.onConnectionStart(connection); + return true; + } + + private static boolean rejectConnection(final Connection connection, ConnectionType type, String message) { + connection.setClientboundProtocolAfterHandshake(ClientIntent.LOGIN); + LOGGER.info(SERVERHOOKS, "[{}] Disconnecting {} connection attempt: {}", connection.getLoggableAddress(true), type, message); // TODO: Respect logIP setting + var text = Component.literal(message); + connection.send(new ClientboundLoginDisconnectPacket(text)); + connection.disconnect(text); + return false; } } diff --git a/src/main/java/net/minecraftforge/server/command/TextComponentHelper.java b/src/main/java/net/minecraftforge/server/command/TextComponentHelper.java index 557ad55d2b..333dedb433 100644 --- a/src/main/java/net/minecraftforge/server/command/TextComponentHelper.java +++ b/src/main/java/net/minecraftforge/server/command/TextComponentHelper.java @@ -9,10 +9,9 @@ import net.minecraft.commands.CommandSource; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.locale.Language; import net.minecraftforge.network.ConnectionType; -import net.minecraftforge.network.NetworkHooks; +import net.minecraftforge.network.NetworkContext; import java.util.Locale; public class TextComponentHelper { @@ -29,10 +28,8 @@ public class TextComponentHelper { } private static boolean isVanillaClient(CommandSource sender) { - if (sender instanceof ServerPlayer playerMP) { - ServerGamePacketListenerImpl channel = playerMP.connection; - return NetworkHooks.getConnectionType(channel::getConnection) == ConnectionType.VANILLA; - } + if (sender instanceof ServerPlayer playerMP) + return NetworkContext.get(playerMP.connection.getConnection()).getType() == ConnectionType.VANILLA; return false; } } diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index cb6e4cf848..290934c70a 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -234,6 +234,7 @@ public net.minecraft.server.level.ServerLevel m_142646_()Lnet/minecraft/world/le public net.minecraft.server.level.ServerPlayer f_8940_ # containerCounter public net.minecraft.server.level.ServerPlayer m_143399_(Lnet/minecraft/world/inventory/AbstractContainerMenu;)V # initMenu public net.minecraft.server.level.ServerPlayer m_9217_()V # nextContainerCounter +public net.minecraft.server.network.ServerConfigurationPacketListenerImpl m_293514_(Lnet/minecraft/server/network/ConfigurationTask$Type;)V # finishCurrentTask public net.minecraft.server.packs.repository.ServerPacksSource m_246173_()Lnet/minecraft/server/packs/VanillaPackResources; # createVanillaPackSource public net.minecraft.server.packs.resources.FallbackResourceManager f_10599_ # fallbacks public net.minecraft.util.ExtraCodecs$EitherCodec diff --git a/src/test/java/net/minecraftforge/debug/entity/player/PlayerNegotiationEventTest.java b/src/test/java/net/minecraftforge/debug/entity/player/PlayerNegotiationEventTest.java deleted file mode 100644 index 0ff420de13..0000000000 --- a/src/test/java/net/minecraftforge/debug/entity/player/PlayerNegotiationEventTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.debug.entity.player; - -import net.minecraftforge.event.entity.player.PlayerNegotiationEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - * Tests {@link PlayerNegotiationEvent} by listening for and then enqueuing work to be done asynchronously, - * details regarding the work execution is printed out and exceptions are thrown to ensure proper handling. - */ -@Mod("player_negotiation_event_test") -@Mod.EventBusSubscriber() -public class PlayerNegotiationEventTest -{ - private static final boolean ENABLE = false; - private static final Logger LOGGER = LogManager.getLogger(PlayerNegotiationEventTest.class); - - @SubscribeEvent - public static void onPlayerNegotiation(PlayerNegotiationEvent event) - { - if (!ENABLE) return; - LOGGER.info("{} ({})[{}] started negotiation", event.getProfile().getName(), event.getProfile().getId(), event.getConnection().getRemoteAddress()); - event.enqueueWork(() -> { - // This log message should be printed on the fork-join-pool. - LOGGER.info("Hello from {}", Thread.currentThread().getName()); - }); - event.enqueueWork(() -> { - // This exception should be logged by Forge. - throw new RuntimeException("Test Exception from PlayerNegotiationEventTest"); - }); - } -} diff --git a/src/test/java/net/minecraftforge/debug/misc/ContainerTypeTest.java b/src/test/java/net/minecraftforge/debug/misc/ContainerTypeTest.java index 4f741ed72f..9670471cb0 100644 --- a/src/test/java/net/minecraftforge/debug/misc/ContainerTypeTest.java +++ b/src/test/java/net/minecraftforge/debug/misc/ContainerTypeTest.java @@ -5,7 +5,6 @@ package net.minecraftforge.debug.misc; -import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.world.level.block.Blocks; import net.minecraft.client.gui.screens.MenuScreens; @@ -29,107 +28,85 @@ import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; -import net.minecraftforge.network.NetworkHooks; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.ObjectHolder; import net.minecraftforge.registries.RegisterEvent; @Mod("containertypetest") -public class ContainerTypeTest -{ +public class ContainerTypeTest { @ObjectHolder(registryName = "menu", value = "containertypetest:container") public static final MenuType TYPE = null; - public class TestContainer extends AbstractContainerMenu - { + public class TestContainer extends AbstractContainerMenu { private final String text; - protected TestContainer(int windowId, Inventory playerInv, FriendlyByteBuf extraData) - { + protected TestContainer(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { this(windowId, new SimpleContainer(9), extraData.readUtf(128)); } - public TestContainer(int windowId, SimpleContainer inv, String text) - { + public TestContainer(int windowId, SimpleContainer inv, String text) { super(TYPE, windowId); this.text = text; for (int i = 0; i < 9; i++) - { this.addSlot(new Slot(inv, i, (i % 3) * 18, (i / 3) * 18)); - } } @Override - public ItemStack quickMoveStack(Player p_38941_, int p_38942_) - { + public ItemStack quickMoveStack(Player p_38941_, int p_38942_) { return ItemStack.EMPTY; } @Override - public boolean stillValid(Player playerIn) - { + public boolean stillValid(Player playerIn) { return true; } } - public class TestGui extends AbstractContainerScreen - { - public TestGui(TestContainer container, Inventory inv, Component name) - { + public class TestGui extends AbstractContainerScreen { + public TestGui(TestContainer container, Inventory inv, Component name) { super(container, inv, name); } @Override - protected void renderBg(GuiGraphics graphics, float partialTick, int mouseX, int mouseY) - { + protected void renderBg(GuiGraphics graphics, float partialTick, int mouseX, int mouseY) { graphics.drawString(this.font, getMenu().text, mouseX, mouseY, -1); } } - public ContainerTypeTest() - { + public ContainerTypeTest() { FMLJavaModLoadingContext.get().getModEventBus().addListener(this::registerContainers); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); MinecraftForge.EVENT_BUS.addListener(this::onRightClick); } - private void registerContainers(final RegisterEvent event) - { + private void registerContainers(final RegisterEvent event) { event.register(ForgeRegistries.Keys.MENU_TYPES, helper -> helper.register("container", IForgeMenuType.create(TestContainer::new))); } - private void setup(FMLClientSetupEvent event) - { + private void setup(FMLClientSetupEvent event) { MenuScreens.register(TYPE, TestGui::new); } - private void onRightClick(PlayerInteractEvent.RightClickBlock event) - { - if (!event.getLevel().isClientSide && event.getHand() == InteractionHand.MAIN_HAND) - { - if (event.getLevel().getBlockState(event.getPos()).getBlock() == Blocks.SPONGE) - { + @SuppressWarnings("resource") + private void onRightClick(PlayerInteractEvent.RightClickBlock event) { + if (!event.getLevel().isClientSide && event.getHand() == InteractionHand.MAIN_HAND) { + if (event.getLevel().getBlockState(event.getPos()).getBlock() == Blocks.SPONGE) { String text = "Hello World!"; - NetworkHooks.openScreen((ServerPlayer) event.getEntity(), new MenuProvider() - { - @Override - public AbstractContainerMenu createMenu(int p_createMenu_1_, Inventory p_createMenu_2_, Player p_createMenu_3_) - { - SimpleContainer inv = new SimpleContainer(9); - for (int i = 0; i < inv.getContainerSize(); i++) - { - inv.setItem(i, new ItemStack(Items.DIAMOND)); + ((ServerPlayer)event.getEntity()).openMenu(new MenuProvider() { + @Override + public AbstractContainerMenu createMenu(int id, Inventory inventor, Player player) { + SimpleContainer inv = new SimpleContainer(9); + for (int i = 0; i < inv.getContainerSize(); i++) + inv.setItem(i, new ItemStack(Items.DIAMOND)); + return new TestContainer(id, inv, text); } - return new TestContainer(p_createMenu_1_, inv, text); - } - @Override - public Component getDisplayName() - { - return Component.literal("Test"); - } - }, extraData -> { - extraData.writeUtf(text); - }); + @Override + public Component getDisplayName() { + return Component.literal("Test"); + } + }, + extraData -> extraData.writeUtf(text) + ); } } } diff --git a/src/test/java/net/minecraftforge/debug/misc/ModMismatchTest.java b/src/test/java/net/minecraftforge/debug/misc/ModMismatchTest.java index ede181f52c..a78ae4c3e6 100644 --- a/src/test/java/net/minecraftforge/debug/misc/ModMismatchTest.java +++ b/src/test/java/net/minecraftforge/debug/misc/ModMismatchTest.java @@ -13,8 +13,8 @@ import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.loading.FMLEnvironment; -import net.minecraftforge.network.NetworkRegistry; -import net.minecraftforge.network.simple.SimpleChannel; +import net.minecraftforge.network.ChannelBuilder; +import net.minecraftforge.network.SimpleChannel; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; @@ -27,8 +27,7 @@ import net.minecraftforge.registries.ForgeRegistries; * This test mod is disabled by default to ensure that users can join test servers without needing to specifically disable this test mod. */ @Mod(ModMismatchTest.MOD_ID) -public class ModMismatchTest -{ +public class ModMismatchTest { public static final String MOD_ID = "mod_mismatch_test"; private static final boolean ENABLED = false; @@ -42,15 +41,15 @@ public class ModMismatchTest private static final boolean REGISTER_REGISTRY_ENTRY = false; private static final DeferredRegister SOUND_EVENTS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, MOD_ID); - private static final String CHANNEL_PROTOCOL_VERSION = FMLEnvironment.dist == Dist.CLIENT ? "V1" : "V2"; + private static final int CHANNEL_PROTOCOL_VERSION = FMLEnvironment.dist == Dist.CLIENT ? 1 : 2; - public ModMismatchTest() - { - if (ENABLED) - { - if ((FMLEnvironment.dist == Dist.DEDICATED_SERVER && REGISTER_FOR_SERVER) || (FMLEnvironment.dist == Dist.CLIENT && REGISTER_FOR_CLIENT)) - { - NetworkRegistry.newSimpleChannel(new ResourceLocation(MOD_ID, "channel"), () -> CHANNEL_PROTOCOL_VERSION, p -> p.equals(CHANNEL_PROTOCOL_VERSION), (p) -> p.equals(CHANNEL_PROTOCOL_VERSION)); + public ModMismatchTest() { + if (ENABLED) { + if ((FMLEnvironment.dist == Dist.DEDICATED_SERVER && REGISTER_FOR_SERVER) || (FMLEnvironment.dist == Dist.CLIENT && REGISTER_FOR_CLIENT)) { + var channel = ChannelBuilder + .named(new ResourceLocation(MOD_ID, "channel")) + .networkProtocolVersion(CHANNEL_PROTOCOL_VERSION) + .simpleChannel(); } if (REGISTER_REGISTRY_ENTRY && FMLEnvironment.dist == Dist.DEDICATED_SERVER) {