Minestom/src/main/java/net/minestom/server/utils/PacketUtils.java

188 lines
9.0 KiB
Java
Raw Normal View History

2020-04-24 03:25:58 +02:00
package net.minestom.server.utils;
2019-08-22 14:52:32 +02:00
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.minestom.server.MinecraftServer;
2021-06-11 17:19:11 +02:00
import net.minestom.server.adventure.MinestomAdventure;
import net.minestom.server.adventure.audience.PacketGroupingAudience;
import net.minestom.server.entity.Player;
import net.minestom.server.listener.manager.PacketListenerManager;
2021-08-04 04:00:42 +02:00
import net.minestom.server.network.packet.FramedPacket;
2021-03-12 16:33:19 +01:00
import net.minestom.server.network.packet.server.ComponentHoldingServerPacket;
2020-04-24 03:25:58 +02:00
import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.player.NettyPlayerConnection;
import net.minestom.server.network.player.PlayerConnection;
2021-08-04 12:41:15 +02:00
import net.minestom.server.network.socket.Server;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.callback.validator.PlayerValidator;
2020-11-05 22:20:51 +01:00
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
2019-08-22 14:52:32 +02:00
2021-08-04 12:41:15 +02:00
import java.nio.BufferOverflowException;
2021-06-20 20:59:53 +02:00
import java.nio.ByteBuffer;
import java.util.Collection;
2021-06-20 20:59:53 +02:00
import java.util.zip.Deflater;
2020-08-15 04:05:15 +02:00
/**
* Utils class for packets. Including writing a {@link ServerPacket} into a {@link ByteBuffer}
2020-11-13 09:17:53 +01:00
* for network processing.
2020-08-15 04:05:15 +02:00
*/
public final class PacketUtils {
private static final PacketListenerManager PACKET_LISTENER_MANAGER = MinecraftServer.getPacketListenerManager();
2021-06-20 20:59:53 +02:00
private static final ThreadLocal<Deflater> COMPRESSOR = ThreadLocal.withInitial(Deflater::new);
2021-08-04 12:41:15 +02:00
private static final ThreadLocal<ByteBuffer> BUFFER = ThreadLocal.withInitial(() -> ByteBuffer.allocateDirect(Server.SOCKET_BUFFER_SIZE));
private PacketUtils() {
}
2019-08-22 14:52:32 +02:00
/**
* Sends a packet to an audience. This method performs the following steps in the
* following order:
* <ol>
* <li>If {@code audience} is a {@link Player}, send the packet to them.</li>
* <li>Otherwise, if {@code audience} is a {@link PacketGroupingAudience}, call
* {@link #sendGroupedPacket(Collection, ServerPacket)} on the players that the
* grouping audience contains.</li>
* <li>Otherwise, if {@code audience} is a {@link ForwardingAudience.Single},
* call this method on the single audience inside the forwarding audience.</li>
* <li>Otherwise, if {@code audience} is a {@link ForwardingAudience}, call this
* method for each audience member of the forwarding audience.</li>
* <li>Otherwise, do nothing.</li>
* </ol>
*
* @param audience the audience
* @param packet the packet
*/
@SuppressWarnings("OverrideOnly") // we need to access the audiences inside ForwardingAudience
public static void sendPacket(@NotNull Audience audience, @NotNull ServerPacket packet) {
if (audience instanceof Player) {
((Player) audience).getPlayerConnection().sendPacket(packet);
} else if (audience instanceof PacketGroupingAudience) {
PacketUtils.sendGroupedPacket(((PacketGroupingAudience) audience).getPlayers(), packet);
} else if (audience instanceof ForwardingAudience.Single) {
PacketUtils.sendPacket(((ForwardingAudience.Single) audience).audience(), packet);
} else if (audience instanceof ForwardingAudience) {
for (Audience member : ((ForwardingAudience) audience).audiences()) {
PacketUtils.sendPacket(member, packet);
}
}
}
2020-11-13 09:17:53 +01:00
/**
* Sends a {@link ServerPacket} to multiple players.
2020-11-13 09:17:53 +01:00
* <p>
* Can drastically improve performance since the packet will not have to be processed as much.
2020-11-13 09:17:53 +01:00
*
* @param players the players to send the packet to
* @param packet the packet to send to the players
* @param playerValidator optional callback to check if a specify player of {@code players} should receive the packet
2020-11-13 09:17:53 +01:00
*/
public static void sendGroupedPacket(@NotNull Collection<Player> players, @NotNull ServerPacket packet,
@Nullable PlayerValidator playerValidator) {
2020-11-20 14:14:55 +01:00
if (players.isEmpty())
return;
2021-03-12 16:33:19 +01:00
// work out if the packet needs to be sent individually due to server-side translating
boolean needsTranslating = false;
2021-06-11 17:19:11 +02:00
if (MinestomAdventure.AUTOMATIC_COMPONENT_TRANSLATION && packet instanceof ComponentHoldingServerPacket) {
needsTranslating = ComponentUtils.areAnyTranslatable(((ComponentHoldingServerPacket) packet).components());
2021-03-12 16:33:19 +01:00
}
if (MinecraftServer.hasGroupedPacket() && !needsTranslating) {
// Send grouped packet...
final boolean success = PACKET_LISTENER_MANAGER.processServerPacket(packet, players);
if (success) {
2021-08-04 12:41:15 +02:00
ByteBuffer finalBuffer = createFramedPacket(packet);
2021-08-04 04:00:42 +02:00
final FramedPacket framedPacket = new FramedPacket(packet.getId(), finalBuffer);
// Send packet to all players
for (Player player : players) {
if (!player.isOnline())
continue;
// Verify if the player should receive the packet
if (playerValidator != null && !playerValidator.isValid(player))
continue;
final PlayerConnection playerConnection = player.getPlayerConnection();
if (playerConnection instanceof NettyPlayerConnection) {
2021-08-04 05:15:40 +02:00
((NettyPlayerConnection) playerConnection).write(framedPacket);
} else {
playerConnection.sendPacket(packet);
}
}
2021-08-04 12:41:15 +02:00
finalBuffer.clear(); // Clear packet to be reused
}
} else {
// Write the same packet for each individual players
for (Player player : players) {
// Verify if the player should receive the packet
if (playerValidator != null && !playerValidator.isValid(player))
continue;
player.getPlayerConnection().sendPacket(packet, false);
}
}
}
/**
* Same as {@link #sendGroupedPacket(Collection, ServerPacket, PlayerValidator)}
* but with the player validator sets to null.
*
* @see #sendGroupedPacket(Collection, ServerPacket, PlayerValidator)
*/
public static void sendGroupedPacket(@NotNull Collection<Player> players, @NotNull ServerPacket packet) {
sendGroupedPacket(players, packet, null);
}
public static void writeFramedPacket(@NotNull ByteBuffer buffer,
@NotNull ServerPacket packet,
boolean compression) {
if (!compression) {
// Length + payload
final int lengthIndex = Utils.writeEmptyVarIntHeader(buffer);
Utils.writeVarInt(buffer, packet.getId());
packet.write(new BinaryWriter(buffer));
final int finalSize = buffer.position() - (lengthIndex + 3);
Utils.writeVarIntHeader(buffer, lengthIndex, finalSize);
return;
}
// Compressed format
final int compressedIndex = Utils.writeEmptyVarIntHeader(buffer);
final int uncompressedIndex = Utils.writeEmptyVarIntHeader(buffer);
final int contentStart = buffer.position();
Utils.writeVarInt(buffer, packet.getId());
packet.write(new BinaryWriter(buffer));
final int packetSize = buffer.position() - contentStart;
if (packetSize >= MinecraftServer.getCompressionThreshold()) {
// Packet large enough, compress
final int limitCache = buffer.limit();
buffer.position(contentStart).limit(contentStart + packetSize);
var uncompressedCopy = ByteBuffer.allocate(packetSize).put(buffer).flip();
buffer.position(contentStart).limit(limitCache);
var deflater = COMPRESSOR.get();
deflater.setInput(uncompressedCopy);
deflater.finish();
deflater.deflate(buffer);
deflater.reset();
Utils.writeVarIntHeader(buffer, compressedIndex, (buffer.position() - contentStart) + 3);
Utils.writeVarIntHeader(buffer, uncompressedIndex, packetSize);
} else {
Utils.writeVarIntHeader(buffer, compressedIndex, packetSize + 3);
Utils.writeVarIntHeader(buffer, uncompressedIndex, 0);
2021-03-26 13:08:05 +01:00
}
}
2021-08-04 12:41:15 +02:00
public static ByteBuffer createFramedPacket(@NotNull ServerPacket packet) {
var buffer = BUFFER.get();
try {
writeFramedPacket(buffer, packet, MinecraftServer.getCompressionThreshold() > 0);
} catch (BufferOverflowException e) {
// In the unlikely case where the packet is bigger than the default buffer size,
// increase to the highest authorized buffer size using heap (for cheap allocation)
buffer = ByteBuffer.allocate(Server.MAX_PACKET_SIZE);
writeFramedPacket(buffer, packet, MinecraftServer.getCompressionThreshold() > 0);
}
return buffer;
}
2019-08-22 14:52:32 +02:00
}