Use NetworkBuffer in packets (#1487)

This commit is contained in:
TheMode 2022-10-29 11:02:22 +02:00 committed by GitHub
parent ba2816fc74
commit 993af51556
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
209 changed files with 2869 additions and 2344 deletions

View File

@ -9,7 +9,7 @@ import java.util.UUID;
*/ */
public class AttributeModifier { public class AttributeModifier {
private final float amount; private final double amount;
private final String name; private final String name;
private final AttributeOperation operation; private final AttributeOperation operation;
private final UUID id; private final UUID id;
@ -21,7 +21,7 @@ public class AttributeModifier {
* @param amount the value of this modifier * @param amount the value of this modifier
* @param operation the operation to apply this modifier with * @param operation the operation to apply this modifier with
*/ */
public AttributeModifier(@NotNull String name, float amount, @NotNull AttributeOperation operation) { public AttributeModifier(@NotNull String name, double amount, @NotNull AttributeOperation operation) {
this(UUID.randomUUID(), name, amount, operation); this(UUID.randomUUID(), name, amount, operation);
} }
@ -33,7 +33,7 @@ public class AttributeModifier {
* @param amount the value of this modifier * @param amount the value of this modifier
* @param operation the operation to apply this modifier with * @param operation the operation to apply this modifier with
*/ */
public AttributeModifier(@NotNull UUID id, @NotNull String name, float amount, @NotNull AttributeOperation operation) { public AttributeModifier(@NotNull UUID id, @NotNull String name, double amount, @NotNull AttributeOperation operation) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.amount = amount; this.amount = amount;
@ -65,7 +65,7 @@ public class AttributeModifier {
* *
* @return the value of this modifier * @return the value of this modifier
*/ */
public float getAmount() { public double getAmount() {
return amount; return amount;
} }

View File

@ -1,34 +1,34 @@
package net.minestom.server.crypto; package net.minestom.server.crypto;
import net.minestom.server.utils.binary.BinaryReader; import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.binary.Writeable;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
public record ArgumentSignatures(@NotNull List<@NotNull Entry> entries) implements Writeable { import static net.minestom.server.network.NetworkBuffer.STRING;
public record ArgumentSignatures(@NotNull List<@NotNull Entry> entries) implements NetworkBuffer.Writer {
public ArgumentSignatures { public ArgumentSignatures {
entries = List.copyOf(entries); entries = List.copyOf(entries);
} }
public ArgumentSignatures(BinaryReader reader) { public ArgumentSignatures(@NotNull NetworkBuffer reader) {
this(reader.readVarIntList(Entry::new)); this(reader.readCollection(Entry::new));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarIntList(entries, BinaryWriter::write); writer.writeCollection(entries);
} }
public record Entry(@NotNull String name, @NotNull MessageSignature signature) implements Writeable { public record Entry(@NotNull String name, @NotNull MessageSignature signature) implements NetworkBuffer.Writer {
public Entry(BinaryReader reader) { public Entry(@NotNull NetworkBuffer reader) {
this(reader.readSizedString(), new MessageSignature(reader)); this(reader.read(STRING), new MessageSignature(reader));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeSizedString(name); writer.write(STRING, name);
writer.write(signature); writer.write(signature);
} }
} }

View File

@ -1,50 +1,46 @@
package net.minestom.server.crypto; package net.minestom.server.crypto;
import net.minestom.server.utils.binary.BinaryReader; import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.binary.Writeable;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
public record LastSeenMessages(@NotNull List<@NotNull Entry> entries) implements Writeable { public record LastSeenMessages(@NotNull List<@NotNull Entry> entries) implements NetworkBuffer.Writer {
public LastSeenMessages { public LastSeenMessages {
entries = List.copyOf(entries); entries = List.copyOf(entries);
} }
public LastSeenMessages(BinaryReader reader) { public LastSeenMessages(@NotNull NetworkBuffer reader) {
this(reader.readVarIntList(Entry::new)); this(reader.readCollection(Entry::new));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
} }
public record Entry(UUID from, MessageSignature lastSignature) implements Writeable { public record Entry(UUID from, MessageSignature lastSignature) implements NetworkBuffer.Writer {
public Entry(BinaryReader reader) { public Entry(@NotNull NetworkBuffer reader) {
this(reader.readUuid(), new MessageSignature(reader)); this(reader.read(NetworkBuffer.UUID), new MessageSignature(reader));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeUuid(from); writer.write(NetworkBuffer.UUID, from);
writer.write(lastSignature); writer.write(lastSignature);
} }
} }
public record Update(LastSeenMessages lastSeen, @Nullable Entry lastReceived) implements Writeable { public record Update(LastSeenMessages lastSeen, @Nullable Entry lastReceived) implements NetworkBuffer.Writer {
public Update(BinaryReader reader) { public Update(@NotNull NetworkBuffer reader) {
this(new LastSeenMessages(reader), reader.readBoolean() ? new Entry(reader) : null); this(new LastSeenMessages(reader), reader.readOptional(Entry::new));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.write(lastSeen); writer.write(lastSeen);
writer.writeBoolean(lastReceived != null); writer.writeOptional(lastReceived);
if (lastReceived != null) writer.write(lastReceived);
} }
} }
} }

View File

@ -1,17 +1,17 @@
package net.minestom.server.crypto; package net.minestom.server.crypto;
import net.minestom.server.utils.binary.BinaryReader; import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.binary.Writeable;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public record MessageSignature(byte @NotNull [] signature) implements Writeable { import static net.minestom.server.network.NetworkBuffer.BYTE_ARRAY;
public MessageSignature(BinaryReader reader) {
this(reader.readByteArray()); public record MessageSignature(byte @NotNull [] signature) implements NetworkBuffer.Writer {
public MessageSignature(@NotNull NetworkBuffer reader) {
this(reader.read(BYTE_ARRAY));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeByteArray(signature); writer.write(BYTE_ARRAY, signature);
} }
} }

View File

@ -1,28 +1,31 @@
package net.minestom.server.crypto; package net.minestom.server.crypto;
import net.minestom.server.utils.binary.BinaryReader; import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.binary.Writeable;
import net.minestom.server.utils.crypto.KeyUtils; import net.minestom.server.utils.crypto.KeyUtils;
import org.jetbrains.annotations.NotNull;
import java.security.PublicKey; import java.security.PublicKey;
import java.time.Instant; import java.time.Instant;
import java.util.Arrays; import java.util.Arrays;
import static net.minestom.server.network.NetworkBuffer.BYTE_ARRAY;
import static net.minestom.server.network.NetworkBuffer.LONG;
/** /**
* Player's public key used to sign chat messages * Player's public key used to sign chat messages
*/ */
public record PlayerPublicKey(Instant expiresAt, PublicKey publicKey, byte[] signature) implements Writeable { public record PlayerPublicKey(Instant expiresAt, PublicKey publicKey,
public PlayerPublicKey(BinaryReader reader) { byte[] signature) implements NetworkBuffer.Writer {
this(Instant.ofEpochMilli(reader.readLong()), public PlayerPublicKey(@NotNull NetworkBuffer reader) {
KeyUtils.publicRSAKeyFrom(reader.readByteArray()), reader.readByteArray()); this(Instant.ofEpochMilli(reader.read(LONG)),
KeyUtils.publicRSAKeyFrom(reader.read(BYTE_ARRAY)), reader.read(BYTE_ARRAY));
} }
@Override @Override
public void write(BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeLong(expiresAt().toEpochMilli()); writer.write(LONG, expiresAt().toEpochMilli());
writer.writeByteArray(publicKey.getEncoded()); writer.write(BYTE_ARRAY, publicKey.getEncoded());
writer.writeByteArray(signature()); writer.write(BYTE_ARRAY, signature());
} }
@Override @Override

View File

@ -1,18 +1,19 @@
package net.minestom.server.crypto; package net.minestom.server.crypto;
import net.minestom.server.utils.binary.BinaryReader; import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.binary.Writeable;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public record SaltSignaturePair(long salt, byte[] signature) implements Writeable { import static net.minestom.server.network.NetworkBuffer.BYTE_ARRAY;
public SaltSignaturePair(BinaryReader reader) { import static net.minestom.server.network.NetworkBuffer.LONG;
this(reader.readLong(), reader.readByteArray());
public record SaltSignaturePair(long salt, byte[] signature) implements NetworkBuffer.Writer {
public SaltSignaturePair(@NotNull NetworkBuffer reader) {
this(reader.read(LONG), reader.read(BYTE_ARRAY));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeLong(salt); writer.write(LONG, salt);
writer.writeByteArray(signature); writer.write(BYTE_ARRAY, signature);
} }
} }

View File

@ -2,7 +2,7 @@ package net.minestom.server.crypto;
import net.minestom.server.MinecraftServer; import net.minestom.server.MinecraftServer;
import net.minestom.server.entity.Player; import net.minestom.server.entity.Player;
import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.utils.crypto.KeyUtils; import net.minestom.server.utils.crypto.KeyUtils;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -36,8 +36,8 @@ public interface SignatureValidator {
*/ */
boolean validate(byte[] payload, byte[] signature); boolean validate(byte[] payload, byte[] signature);
default boolean validate(Consumer<BinaryWriter> payload, byte[] signature) { default boolean validate(Consumer<NetworkBuffer> payload, byte[] signature) {
return validate(BinaryWriter.makeArray(payload), signature); return validate(NetworkBuffer.makeArray(payload), signature);
} }
static SignatureValidator from(PublicKey publicKey, KeyUtils.SignatureAlgorithm algorithm) { static SignatureValidator from(PublicKey publicKey, KeyUtils.SignatureAlgorithm algorithm) {

View File

@ -1,22 +1,20 @@
package net.minestom.server.crypto; package net.minestom.server.crypto;
import net.minestom.server.utils.binary.BinaryReader; import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.binary.Writeable;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.UUID; import java.util.UUID;
public record SignedMessageHeader(@Nullable MessageSignature previousSignature, UUID sender) implements Writeable { public record SignedMessageHeader(@Nullable MessageSignature previousSignature,
public SignedMessageHeader(BinaryReader reader) { @NotNull UUID sender) implements NetworkBuffer.Writer {
this(reader.readBoolean() ? new MessageSignature(reader) : null, reader.readUuid()); public SignedMessageHeader(@NotNull NetworkBuffer reader) {
this(reader.readOptional(MessageSignature::new), reader.read(NetworkBuffer.UUID));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBoolean(previousSignature != null); writer.writeOptional(previousSignature);
if (previousSignature != null) writer.write(previousSignature); writer.write(NetworkBuffer.UUID, sender);
writer.writeUuid(sender);
} }
} }

View File

@ -2,13 +2,10 @@ package net.minestom.server.entity;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.coordinate.Vec;
import net.minestom.server.item.ItemStack; import net.minestom.server.item.ItemStack;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.play.EntityMetaDataPacket; import net.minestom.server.network.packet.server.play.EntityMetaDataPacket;
import net.minestom.server.utils.Direction; import net.minestom.server.utils.Direction;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.binary.Writeable;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -24,104 +21,78 @@ import java.util.UUID;
public final class Metadata { public final class Metadata {
public static Entry<Byte> Byte(byte value) { public static Entry<Byte> Byte(byte value) {
return new MetadataImpl.EntryImpl<>(TYPE_BYTE, value, BinaryWriter::writeByte, BinaryReader::readByte); return new MetadataImpl.EntryImpl<>(TYPE_BYTE, value, NetworkBuffer.BYTE);
} }
public static Entry<Integer> VarInt(int value) { public static Entry<Integer> VarInt(int value) {
return new MetadataImpl.EntryImpl<>(TYPE_VARINT, value, BinaryWriter::writeVarInt, BinaryReader::readVarInt); return new MetadataImpl.EntryImpl<>(TYPE_VARINT, value, NetworkBuffer.VAR_INT);
} }
public static Entry<Float> Float(float value) { public static Entry<Float> Float(float value) {
return new MetadataImpl.EntryImpl<>(TYPE_FLOAT, value, BinaryWriter::writeFloat, BinaryReader::readFloat); return new MetadataImpl.EntryImpl<>(TYPE_FLOAT, value, NetworkBuffer.FLOAT);
} }
public static Entry<String> String(@NotNull String value) { public static Entry<String> String(@NotNull String value) {
return new MetadataImpl.EntryImpl<>(TYPE_STRING, value, BinaryWriter::writeSizedString, BinaryReader::readSizedString); return new MetadataImpl.EntryImpl<>(TYPE_STRING, value, NetworkBuffer.STRING);
} }
public static Entry<Component> Chat(@NotNull Component value) { public static Entry<Component> Chat(@NotNull Component value) {
return new MetadataImpl.EntryImpl<>(TYPE_CHAT, value, BinaryWriter::writeComponent, BinaryReader::readComponent); return new MetadataImpl.EntryImpl<>(TYPE_CHAT, value, NetworkBuffer.COMPONENT);
} }
public static Entry<Component> OptChat(@Nullable Component value) { public static Entry<Component> OptChat(@Nullable Component value) {
return new MetadataImpl.EntryImpl<>(TYPE_OPTCHAT, value, (writer, v) -> { return new MetadataImpl.EntryImpl<>(TYPE_OPTCHAT, value, NetworkBuffer.OPT_CHAT);
writer.writeBoolean(v != null);
if (v != null) writer.writeComponent(v);
}, reader -> reader.readBoolean() ? reader.readComponent() : null);
} }
public static Entry<ItemStack> Slot(@NotNull ItemStack value) { public static Entry<ItemStack> Slot(@NotNull ItemStack value) {
return new MetadataImpl.EntryImpl<>(TYPE_SLOT, value, BinaryWriter::writeItemStack, BinaryReader::readItemStack); return new MetadataImpl.EntryImpl<>(TYPE_SLOT, value, NetworkBuffer.ITEM);
} }
public static Entry<Boolean> Boolean(boolean value) { public static Entry<Boolean> Boolean(boolean value) {
return new MetadataImpl.EntryImpl<>(TYPE_BOOLEAN, value, BinaryWriter::writeBoolean, BinaryReader::readBoolean); return new MetadataImpl.EntryImpl<>(TYPE_BOOLEAN, value, NetworkBuffer.BOOLEAN);
} }
public static Entry<Point> Rotation(@NotNull Point value) { public static Entry<Point> Rotation(@NotNull Point value) {
return new MetadataImpl.EntryImpl<>(TYPE_ROTATION, value, (writer, v) -> { return new MetadataImpl.EntryImpl<>(TYPE_ROTATION, value, NetworkBuffer.ROTATION);
writer.writeFloat((float) v.x());
writer.writeFloat((float) v.y());
writer.writeFloat((float) v.z());
}, reader -> new Vec(reader.readFloat(), reader.readFloat(), reader.readFloat()));
} }
public static Entry<Point> Position(@NotNull Point value) { public static Entry<Point> Position(@NotNull Point value) {
return new MetadataImpl.EntryImpl<>(TYPE_POSITION, value, BinaryWriter::writeBlockPosition, BinaryReader::readBlockPosition); return new MetadataImpl.EntryImpl<>(TYPE_POSITION, value, NetworkBuffer.BLOCK_POSITION);
} }
public static Entry<Point> OptPosition(@Nullable Point value) { public static Entry<Point> OptPosition(@Nullable Point value) {
return new MetadataImpl.EntryImpl<>(TYPE_OPTPOSITION, value, (writer, v) -> { return new MetadataImpl.EntryImpl<>(TYPE_OPTPOSITION, value, NetworkBuffer.OPT_BLOCK_POSITION);
writer.writeBoolean(v != null);
if (v != null) writer.writeBlockPosition(v);
}, reader -> reader.readBoolean() ? reader.readBlockPosition() : null);
} }
public static Entry<Direction> Direction(@NotNull Direction value) { public static Entry<Direction> Direction(@NotNull Direction value) {
return new MetadataImpl.EntryImpl<>(TYPE_DIRECTION, value, return new MetadataImpl.EntryImpl<>(TYPE_DIRECTION, value, NetworkBuffer.DIRECTION);
(writer, v) -> writer.writeVarInt(v.ordinal()),
reader -> Direction.values()[reader.readVarInt()]);
} }
public static Entry<UUID> OptUUID(@Nullable UUID value) { public static Entry<UUID> OptUUID(@Nullable UUID value) {
return new MetadataImpl.EntryImpl<>(TYPE_OPTUUID, value, (writer, v) -> { return new MetadataImpl.EntryImpl<>(TYPE_OPTUUID, value, NetworkBuffer.OPT_UUID);
writer.writeBoolean(v != null);
if (v != null) writer.writeUuid(v);
}, reader -> reader.readBoolean() ? reader.readUuid() : null);
} }
public static Entry<Integer> OptBlockID(@Nullable Integer value) { public static Entry<Integer> OptBlockID(@Nullable Integer value) {
return new MetadataImpl.EntryImpl<>(TYPE_OPTBLOCKID, value, return new MetadataImpl.EntryImpl<>(TYPE_OPTBLOCKID, value, NetworkBuffer.OPT_BLOCK_ID);
(writer, v) -> writer.writeVarInt(v != null ? v : 0),
reader -> reader.readBoolean() ? reader.readVarInt() : null);
} }
public static Entry<NBT> NBT(@NotNull NBT nbt) { public static Entry<NBT> NBT(@NotNull NBT nbt) {
return new MetadataImpl.EntryImpl<>(TYPE_NBT, nbt, (writer, v) -> writer.writeNBT("", v), BinaryReader::readTag); return new MetadataImpl.EntryImpl<>(TYPE_NBT, nbt, NetworkBuffer.NBT);
} }
public static Entry<int[]> VillagerData(int villagerType, public static Entry<int[]> VillagerData(int villagerType,
int villagerProfession, int villagerProfession,
int level) { int level) {
return new MetadataImpl.EntryImpl<>(TYPE_VILLAGERDATA, new int[]{villagerType, villagerProfession, level}, return new MetadataImpl.EntryImpl<>(TYPE_VILLAGERDATA, new int[]{villagerType, villagerProfession, level},
(writer, v) -> { NetworkBuffer.VILLAGER_DATA);
writer.writeVarInt(v[0]);
writer.writeVarInt(v[1]);
writer.writeVarInt(v[2]);
},
reader -> new int[]{reader.readVarInt(), reader.readVarInt(), reader.readVarInt()});
} }
public static Entry<Integer> OptVarInt(@Nullable Integer value) { public static Entry<Integer> OptVarInt(@Nullable Integer value) {
return new MetadataImpl.EntryImpl<>(TYPE_OPTVARINT, return new MetadataImpl.EntryImpl<>(TYPE_OPTVARINT, value, NetworkBuffer.OPT_VAR_INT);
value, (writer, v) -> writer.writeVarInt(v != null ? v + 1 : 0),
reader -> reader.readBoolean() ? reader.readVarInt() : null);
} }
public static Entry<Entity.Pose> Pose(@NotNull Entity.Pose value) { public static Entry<Entity.Pose> Pose(@NotNull Entity.Pose value) {
return new MetadataImpl.EntryImpl<>(TYPE_POSE, value, return new MetadataImpl.EntryImpl<>(TYPE_POSE, value, NetworkBuffer.POSE);
(writer, v) -> writer.writeVarInt(v.ordinal()),
reader -> Entity.Pose.values()[reader.readVarInt()]);
} }
public static final byte TYPE_BYTE = 0; public static final byte TYPE_BYTE = 0;
@ -229,14 +200,14 @@ public final class Metadata {
return map; return map;
} }
public sealed interface Entry<T> extends Writeable public sealed interface Entry<T> extends NetworkBuffer.Writer
permits MetadataImpl.EntryImpl { permits MetadataImpl.EntryImpl {
int type(); int type();
@UnknownNullability T value(); @UnknownNullability T value();
@ApiStatus.Internal @ApiStatus.Internal
static @NotNull Entry<?> read(int type, @NotNull BinaryReader reader) { static @NotNull Entry<?> read(int type, @NotNull NetworkBuffer reader) {
return MetadataImpl.EntryImpl.read(type, reader); return MetadataImpl.EntryImpl.read(type, reader);
} }
} }

View File

@ -3,22 +3,19 @@ package net.minestom.server.entity;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.minestom.server.coordinate.Vec; import net.minestom.server.coordinate.Vec;
import net.minestom.server.item.ItemStack; import net.minestom.server.item.ItemStack;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.utils.Direction; import net.minestom.server.utils.Direction;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.collection.ObjectArray; import net.minestom.server.utils.collection.ObjectArray;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.UnknownNullability; import org.jetbrains.annotations.UnknownNullability;
import org.jglrxavpok.hephaistos.nbt.NBTEnd; import org.jglrxavpok.hephaistos.nbt.NBTEnd;
import java.util.function.BiConsumer;
import java.util.function.Function;
import static net.minestom.server.entity.Metadata.Boolean; import static net.minestom.server.entity.Metadata.Boolean;
import static net.minestom.server.entity.Metadata.Byte; import static net.minestom.server.entity.Metadata.Byte;
import static net.minestom.server.entity.Metadata.Float; import static net.minestom.server.entity.Metadata.Float;
import static net.minestom.server.entity.Metadata.String; import static net.minestom.server.entity.Metadata.String;
import static net.minestom.server.entity.Metadata.*; import static net.minestom.server.entity.Metadata.*;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
final class MetadataImpl { final class MetadataImpl {
static final ObjectArray<Metadata.Entry<?>> EMPTY_VALUES = ObjectArray.singleThread(20); static final ObjectArray<Metadata.Entry<?>> EMPTY_VALUES = ObjectArray.singleThread(20);
@ -47,22 +44,21 @@ final class MetadataImpl {
} }
record EntryImpl<T>(int type, @UnknownNullability T value, record EntryImpl<T>(int type, @UnknownNullability T value,
@NotNull BiConsumer<BinaryWriter, T> writer, @NotNull NetworkBuffer.Type<T> serializer) implements Metadata.Entry<T> {
@NotNull Function<BinaryReader, T> reader) implements Metadata.Entry<T> { static Entry<?> read(int type, @NotNull NetworkBuffer reader) {
static Entry<?> read(int type, @NotNull BinaryReader reader) {
final EntryImpl<?> value = (EntryImpl<?>) EMPTY_VALUES.get(type); final EntryImpl<?> value = (EntryImpl<?>) EMPTY_VALUES.get(type);
if (value == null) throw new UnsupportedOperationException("Unknown value type: " + type); if (value == null) throw new UnsupportedOperationException("Unknown value type: " + type);
return value.withValue(reader); return value.withValue(reader);
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(type); writer.write(VAR_INT, type);
this.writer.accept(writer, value); writer.write(serializer, value);
} }
private EntryImpl<T> withValue(@NotNull BinaryReader reader) { private EntryImpl<T> withValue(@NotNull NetworkBuffer reader) {
return new EntryImpl<>(type, this.reader.apply(reader), writer, this.reader); return new EntryImpl<>(type, reader.read(serializer), serializer);
} }
} }
} }

View File

@ -45,7 +45,7 @@ public final class VelocityProxy {
return enabled; return enabled;
} }
public static boolean checkIntegrity(NetworkBuffer buffer) { public static boolean checkIntegrity(@NotNull NetworkBuffer buffer) {
final byte[] signature = new byte[32]; final byte[] signature = new byte[32];
for (int i = 0; i < signature.length; i++) { for (int i = 0; i < signature.length; i++) {
signature[i] = buffer.read(BYTE); signature[i] = buffer.read(BYTE);

View File

@ -9,6 +9,7 @@ import net.minestom.server.entity.Player;
import net.minestom.server.entity.pathfinding.PFBlock; import net.minestom.server.entity.pathfinding.PFBlock;
import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.Block;
import net.minestom.server.instance.block.BlockHandler; import net.minestom.server.instance.block.BlockHandler;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.CachedPacket; import net.minestom.server.network.packet.server.CachedPacket;
import net.minestom.server.network.packet.server.play.ChunkDataPacket; import net.minestom.server.network.packet.server.play.ChunkDataPacket;
import net.minestom.server.network.packet.server.play.UpdateLightPacket; import net.minestom.server.network.packet.server.play.UpdateLightPacket;
@ -20,7 +21,6 @@ import net.minestom.server.snapshot.SnapshotUpdater;
import net.minestom.server.utils.ArrayUtils; import net.minestom.server.utils.ArrayUtils;
import net.minestom.server.utils.MathUtils; import net.minestom.server.utils.MathUtils;
import net.minestom.server.utils.ObjectPool; import net.minestom.server.utils.ObjectPool;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.chunk.ChunkUtils; import net.minestom.server.utils.chunk.ChunkUtils;
import net.minestom.server.world.biomes.Biome; import net.minestom.server.world.biomes.Biome;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -203,11 +203,10 @@ public class DynamicChunk extends Chunk {
"WORLD_SURFACE", NBT.LongArray(encodeBlocks(worldSurface, bitsForHeight)))); "WORLD_SURFACE", NBT.LongArray(encodeBlocks(worldSurface, bitsForHeight))));
} }
// Data // Data
final byte[] data = ObjectPool.PACKET_POOL.use(buffer -> { final byte[] data = ObjectPool.PACKET_POOL.use(buffer ->
final BinaryWriter writer = new BinaryWriter(buffer); NetworkBuffer.makeArray(networkBuffer -> {
for (Section section : sections) writer.write(section); for (Section section : sections) networkBuffer.write(section);
return writer.toByteArray(); }));
});
return new ChunkDataPacket(chunkX, chunkZ, return new ChunkDataPacket(chunkX, chunkZ,
new ChunkData(heightmapsNBT, data, entries), new ChunkData(heightmapsNBT, data, entries),
createLightData()); createLightData());

View File

@ -1,11 +1,12 @@
package net.minestom.server.instance; package net.minestom.server.instance;
import net.minestom.server.instance.palette.Palette; import net.minestom.server.instance.palette.Palette;
import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.utils.binary.Writeable;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public final class Section implements Writeable { import static net.minestom.server.network.NetworkBuffer.SHORT;
public final class Section implements NetworkBuffer.Writer {
private Palette blockPalette; private Palette blockPalette;
private Palette biomePalette; private Palette biomePalette;
private byte[] skyLight; private byte[] skyLight;
@ -62,8 +63,8 @@ public final class Section implements Writeable {
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeShort((short) blockPalette.count()); writer.write(SHORT, (short) blockPalette.count());
writer.write(blockPalette); writer.write(blockPalette);
writer.write(biomePalette); writer.write(biomePalette);
} }

View File

@ -2,8 +2,8 @@ package net.minestom.server.instance.palette;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet; import it.unimi.dsi.fastutil.ints.IntSet;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.utils.MathUtils; import net.minestom.server.utils.MathUtils;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.function.IntUnaryOperator; import java.util.function.IntUnaryOperator;
@ -106,7 +106,7 @@ final class AdaptivePalette implements Palette, Cloneable {
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
final SpecializedPalette optimized = optimizedPalette(); final SpecializedPalette optimized = optimizedPalette();
this.palette = optimized; this.palette = optimized;
optimized.write(writer); optimized.write(writer);

View File

@ -1,8 +1,11 @@
package net.minestom.server.instance.palette; package net.minestom.server.instance.palette;
import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.network.NetworkBuffer;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BYTE;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
/** /**
* Palette containing a single value. Useful for both empty and full palettes. * Palette containing a single value. Useful for both empty and full palettes.
*/ */
@ -43,9 +46,9 @@ record FilledPalette(byte dim, int value) implements SpecializedPalette.Immutabl
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeByte((byte) 0); writer.write(BYTE, (byte) 0);
writer.writeVarInt(value); writer.write(VAR_INT, value);
writer.writeVarInt(0); writer.write(VAR_INT, 0);
} }
} }

View File

@ -3,14 +3,16 @@ package net.minestom.server.instance.palette;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntArrayList;
import net.minestom.server.MinecraftServer; import net.minestom.server.MinecraftServer;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.utils.MathUtils; import net.minestom.server.utils.MathUtils;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Arrays; import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator; import java.util.function.IntUnaryOperator;
import static net.minestom.server.network.NetworkBuffer.*;
/** /**
* Palette able to take any value anywhere. May consume more memory than required. * Palette able to take any value anywhere. May consume more memory than required.
*/ */
@ -207,12 +209,12 @@ final class FlexiblePalette implements SpecializedPalette, Cloneable {
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeByte(bitsPerEntry); writer.write(BYTE, bitsPerEntry);
if (bitsPerEntry <= maxBitsPerEntry()) { // Palette index if (bitsPerEntry <= maxBitsPerEntry()) { // Palette index
writer.writeVarIntList(paletteToValueList, BinaryWriter::writeVarInt); writer.writeCollection(VAR_INT, paletteToValueList);
} }
writer.writeLongArray(values); writer.write(LONG_ARRAY, values);
} }
private void retrieveAll(@NotNull EntryConsumer consumer, boolean consumeEmpty) { private void retrieveAll(@NotNull EntryConsumer consumer, boolean consumeEmpty) {

View File

@ -1,6 +1,6 @@
package net.minestom.server.instance.palette; package net.minestom.server.instance.palette;
import net.minestom.server.utils.binary.Writeable; import net.minestom.server.network.NetworkBuffer;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.function.IntUnaryOperator; import java.util.function.IntUnaryOperator;
@ -10,7 +10,7 @@ import java.util.function.IntUnaryOperator;
* <p> * <p>
* 0 is the default value. * 0 is the default value.
*/ */
public interface Palette extends Writeable { public interface Palette extends NetworkBuffer.Writer {
static Palette blocks() { static Palette blocks() {
return newPalette(16, 8, 4); return newPalette(16, 8, 4);
} }

View File

@ -3,11 +3,11 @@ package net.minestom.server.item;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.Block;
import net.minestom.server.item.attribute.ItemAttribute; import net.minestom.server.item.attribute.ItemAttribute;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.registry.ProtocolObject; import net.minestom.server.registry.ProtocolObject;
import net.minestom.server.tag.Tag; import net.minestom.server.tag.Tag;
import net.minestom.server.tag.TagReadable; import net.minestom.server.tag.TagReadable;
import net.minestom.server.tag.Taggable; import net.minestom.server.tag.Taggable;
import net.minestom.server.utils.binary.Writeable;
import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -17,7 +17,7 @@ import org.jglrxavpok.hephaistos.nbt.NBTCompound;
import java.util.*; import java.util.*;
import java.util.function.Consumer; import java.util.function.Consumer;
public sealed interface ItemMeta extends TagReadable, Writeable public sealed interface ItemMeta extends TagReadable, NetworkBuffer.Writer
permits ItemMetaImpl { permits ItemMetaImpl {
@Override @Override

View File

@ -1,8 +1,8 @@
package net.minestom.server.item; package net.minestom.server.item;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.tag.Tag; import net.minestom.server.tag.Tag;
import net.minestom.server.tag.TagHandler; import net.minestom.server.tag.TagHandler;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.UnknownNullability; import org.jetbrains.annotations.UnknownNullability;
import org.jglrxavpok.hephaistos.nbt.NBTCompound; import org.jglrxavpok.hephaistos.nbt.NBTCompound;
@ -10,6 +10,9 @@ import org.jglrxavpok.hephaistos.nbt.NBTCompound;
import java.util.Objects; import java.util.Objects;
import java.util.function.Consumer; import java.util.function.Consumer;
import static net.minestom.server.network.NetworkBuffer.BYTE;
import static net.minestom.server.network.NetworkBuffer.NBT;
record ItemMetaImpl(TagHandler tagHandler) implements ItemMeta { record ItemMetaImpl(TagHandler tagHandler) implements ItemMeta {
static final ItemMetaImpl EMPTY = new ItemMetaImpl(TagHandler.newHandler()); static final ItemMetaImpl EMPTY = new ItemMetaImpl(TagHandler.newHandler());
@ -36,13 +39,13 @@ record ItemMetaImpl(TagHandler tagHandler) implements ItemMeta {
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
final NBTCompound nbt = toNBT(); final NBTCompound nbt = toNBT();
if (nbt.isEmpty()) { if (nbt.isEmpty()) {
writer.writeByte((byte) 0); writer.write(BYTE, (byte) 0);
return; return;
} }
writer.writeNBT("", nbt); writer.write(NBT, nbt);
} }
@Override @Override

View File

@ -2,7 +2,10 @@ package net.minestom.server.network;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.entity.Entity;
import net.minestom.server.item.ItemStack; import net.minestom.server.item.ItemStack;
import net.minestom.server.utils.Direction;
import net.minestom.server.utils.Either;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -15,12 +18,16 @@ import java.nio.ByteOrder;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
@ApiStatus.Experimental @ApiStatus.Experimental
public final class NetworkBuffer { public final class NetworkBuffer {
public static final Type<Boolean> BOOLEAN = NetworkBufferTypes.BOOLEAN; public static final Type<Boolean> BOOLEAN = NetworkBufferTypes.BOOLEAN;
public static final Type<Byte> BYTE = NetworkBufferTypes.BYTE; public static final Type<Byte> BYTE = NetworkBufferTypes.BYTE;
public static final Type<Short> SHORT = NetworkBufferTypes.SHORT; public static final Type<Short> SHORT = NetworkBufferTypes.SHORT;
public static final Type<Integer> UNSIGNED_SHORT = NetworkBufferTypes.UNSIGNED_SHORT;
public static final Type<Integer> INT = NetworkBufferTypes.INT; public static final Type<Integer> INT = NetworkBufferTypes.INT;
public static final Type<Long> LONG = NetworkBufferTypes.LONG; public static final Type<Long> LONG = NetworkBufferTypes.LONG;
public static final Type<Float> FLOAT = NetworkBufferTypes.FLOAT; public static final Type<Float> FLOAT = NetworkBufferTypes.FLOAT;
@ -35,6 +42,22 @@ public final class NetworkBuffer {
public static final Type<UUID> UUID = NetworkBufferTypes.UUID; public static final Type<UUID> UUID = NetworkBufferTypes.UUID;
public static final Type<ItemStack> ITEM = NetworkBufferTypes.ITEM; public static final Type<ItemStack> ITEM = NetworkBufferTypes.ITEM;
public static final Type<byte[]> BYTE_ARRAY = NetworkBufferTypes.BYTE_ARRAY;
public static final Type<long[]> LONG_ARRAY = NetworkBufferTypes.LONG_ARRAY;
public static final Type<int[]> VAR_INT_ARRAY = NetworkBufferTypes.VAR_INT_ARRAY;
public static final Type<long[]> VAR_LONG_ARRAY = NetworkBufferTypes.VAR_LONG_ARRAY;
// METADATA
public static final Type<Component> OPT_CHAT = NetworkBufferTypes.OPT_CHAT;
public static final Type<Point> ROTATION = NetworkBufferTypes.ROTATION;
public static final Type<Point> OPT_BLOCK_POSITION = NetworkBufferTypes.OPT_BLOCK_POSITION;
public static final Type<Direction> DIRECTION = NetworkBufferTypes.DIRECTION;
public static final Type<UUID> OPT_UUID = NetworkBufferTypes.OPT_UUID;
public static final Type<Integer> OPT_BLOCK_ID = NetworkBufferTypes.OPT_BLOCK_ID;
public static final Type<int[]> VILLAGER_DATA = NetworkBufferTypes.VILLAGER_DATA;
public static final Type<Integer> OPT_VAR_INT = NetworkBufferTypes.OPT_VAR_INT;
public static final Type<Entity.Pose> POSE = NetworkBufferTypes.POSE;
ByteBuffer nioBuffer; ByteBuffer nioBuffer;
final boolean resizable; final boolean resizable;
int writeIndex; int writeIndex;
@ -69,6 +92,10 @@ public final class NetworkBuffer {
if (length != -1) this.writeIndex += length; if (length != -1) this.writeIndex += length;
} }
public <T> void write(@NotNull Writer writer) {
writer.write(this);
}
public <T> @NotNull T read(@NotNull Type<T> type) { public <T> @NotNull T read(@NotNull Type<T> type) {
var impl = (NetworkBufferTypes.TypeImpl<T>) type; var impl = (NetworkBufferTypes.TypeImpl<T>) type;
return impl.reader().read(this); return impl.reader().read(this);
@ -79,10 +106,19 @@ public final class NetworkBuffer {
if (value != null) write(type, value); if (value != null) write(type, value);
} }
public void writeOptional(@Nullable Writer writer) {
write(BOOLEAN, writer != null);
if (writer != null) write(writer);
}
public <T> @Nullable T readOptional(@NotNull Type<T> type) { public <T> @Nullable T readOptional(@NotNull Type<T> type) {
return read(BOOLEAN) ? read(type) : null; return read(BOOLEAN) ? read(type) : null;
} }
public <T> @Nullable T readOptional(@NotNull Function<@NotNull NetworkBuffer, @NotNull T> function) {
return read(BOOLEAN) ? function.apply(this) : null;
}
public <T> void writeCollection(@NotNull Type<T> type, @Nullable Collection<@NotNull T> values) { public <T> void writeCollection(@NotNull Type<T> type, @Nullable Collection<@NotNull T> values) {
if (values == null) { if (values == null) {
write(BYTE, (byte) 0); write(BYTE, (byte) 0);
@ -99,19 +135,93 @@ public final class NetworkBuffer {
writeCollection(type, values == null ? null : List.of(values)); writeCollection(type, values == null ? null : List.of(values));
} }
public <T> @NotNull Collection<@NotNull T> readCollection(@NotNull Type<T> type) { public <T extends Writer> void writeCollection(@Nullable Collection<@NotNull T> values) {
if (values == null) {
write(BYTE, (byte) 0);
return;
}
write(VAR_INT, values.size());
for (T value : values) {
write(value);
}
}
public <T> void writeCollection(@Nullable Collection<@NotNull T> values,
@NotNull BiConsumer<@NotNull NetworkBuffer, @NotNull T> consumer) {
if (values == null) {
write(BYTE, (byte) 0);
return;
}
write(VAR_INT, values.size());
for (T value : values) {
consumer.accept(this, value);
}
}
public <T> @NotNull List<@NotNull T> readCollection(@NotNull Type<T> type) {
final int size = read(VAR_INT); final int size = read(VAR_INT);
final Collection<T> values = new java.util.ArrayList<>(size); final List<T> values = new java.util.ArrayList<>(size);
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
values.add(read(type)); values.add(read(type));
} }
return values; return values;
} }
public <T> @NotNull List<@NotNull T> readCollection(@NotNull Function<@NotNull NetworkBuffer, @NotNull T> function) {
final int size = read(VAR_INT);
final List<T> values = new java.util.ArrayList<>(size);
for (int i = 0; i < size; i++) {
values.add(function.apply(this));
}
return values;
}
public <L, R> void writeEither(Either<L, R> either, BiConsumer<NetworkBuffer, L> leftWriter, BiConsumer<NetworkBuffer, R> rightWriter) {
if (either.isLeft()) {
write(BOOLEAN, true);
leftWriter.accept(this, either.left());
} else {
write(BOOLEAN, false);
rightWriter.accept(this, either.right());
}
}
public <L, R> @NotNull Either<L, R> readEither(@NotNull Function<NetworkBuffer, L> leftReader, Function<NetworkBuffer, R> rightReader) {
if (read(BOOLEAN)) {
return Either.left(leftReader.apply(this));
} else {
return Either.right(rightReader.apply(this));
}
}
public <E extends Enum<?>> void writeEnum(@NotNull Class<E> enumClass, @NotNull E value) {
write(VAR_INT, value.ordinal());
}
public <E extends Enum<?>> @NotNull E readEnum(@NotNull Class<@NotNull E> enumClass) {
return enumClass.getEnumConstants()[read(VAR_INT)];
}
public byte[] readBytes(int length) {
byte[] bytes = new byte[length];
nioBuffer.get(readIndex, bytes, 0, length);
readIndex += length;
return bytes;
}
public void copyTo(int srcOffset, byte @NotNull [] dest, int destOffset, int length) { public void copyTo(int srcOffset, byte @NotNull [] dest, int destOffset, int length) {
this.nioBuffer.get(srcOffset, dest, destOffset, length); this.nioBuffer.get(srcOffset, dest, destOffset, length);
} }
public byte @NotNull [] extractBytes(@NotNull Consumer<@NotNull NetworkBuffer> extractor) {
final int startingPosition = readIndex();
extractor.accept(this);
final int endingPosition = readIndex();
byte[] output = new byte[endingPosition - startingPosition];
copyTo(startingPosition, output, 0, output.length);
return output;
}
public void clear() { public void clear() {
this.writeIndex = 0; this.writeIndex = 0;
this.readIndex = 0; this.readIndex = 0;
@ -153,6 +263,20 @@ public final class NetworkBuffer {
} }
} }
public sealed interface Type<T> permits NetworkBufferTypes.TypeImpl { public sealed interface Type<T> permits NetworkBufferTypes.TypeImpl {
} }
@FunctionalInterface
public interface Writer {
void write(@NotNull NetworkBuffer writer);
}
public static byte[] makeArray(@NotNull Consumer<@NotNull NetworkBuffer> writing) {
NetworkBuffer writer = new NetworkBuffer();
writing.accept(writer);
byte[] bytes = new byte[writer.writeIndex];
writer.copyTo(0, bytes, 0, bytes.length);
return bytes;
}
} }

View File

@ -4,9 +4,12 @@ import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.coordinate.Vec; import net.minestom.server.coordinate.Vec;
import net.minestom.server.entity.Entity;
import net.minestom.server.item.ItemStack; import net.minestom.server.item.ItemStack;
import net.minestom.server.item.Material; import net.minestom.server.item.Material;
import net.minestom.server.utils.Direction;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.UnknownNullability;
import org.jglrxavpok.hephaistos.nbt.*; import org.jglrxavpok.hephaistos.nbt.*;
import java.io.IOException; import java.io.IOException;
@ -52,6 +55,17 @@ final class NetworkBufferTypes {
buffer.readIndex += 2; buffer.readIndex += 2;
return value; return value;
}); });
static final TypeImpl<Integer> UNSIGNED_SHORT = new TypeImpl<>(Integer.class,
(buffer, value) -> {
buffer.ensureSize(2);
buffer.nioBuffer.putShort(buffer.writeIndex(), (short) (value & 0xFFFF));
return 2;
},
buffer -> {
final short value = buffer.nioBuffer.getShort(buffer.readIndex());
buffer.readIndex += 2;
return value & 0xFFFF;
});
static final TypeImpl<Integer> INT = new TypeImpl<>(Integer.class, static final TypeImpl<Integer> INT = new TypeImpl<>(Integer.class,
(buffer, value) -> { (buffer, value) -> {
buffer.ensureSize(4); buffer.ensureSize(4);
@ -306,6 +320,184 @@ final class NetworkBufferTypes {
return ItemStack.fromNBT(material, compound, amount); return ItemStack.fromNBT(material, compound, amount);
}); });
static final TypeImpl<byte[]> BYTE_ARRAY = new TypeImpl<>(byte[].class,
(buffer, value) -> {
buffer.write(VAR_INT, value.length);
buffer.write(RAW_BYTES, value);
return -1;
},
buffer -> {
final int length = buffer.read(VAR_INT);
final byte[] bytes = new byte[length];
buffer.nioBuffer.get(buffer.readIndex(), bytes);
buffer.readIndex += length;
return bytes;
});
static final TypeImpl<long[]> LONG_ARRAY = new TypeImpl<>(long[].class,
(buffer, value) -> {
buffer.write(VAR_INT, value.length);
for (long l : value) {
buffer.write(LONG, l);
}
return -1;
},
buffer -> {
final int length = buffer.read(VAR_INT);
final long[] longs = new long[length];
for (int i = 0; i < length; i++) {
longs[i] = buffer.read(LONG);
}
return longs;
});
static final TypeImpl<int[]> VAR_INT_ARRAY = new TypeImpl<>(int[].class,
(buffer, value) -> {
buffer.write(VAR_INT, value.length);
for (int i : value) {
buffer.write(VAR_INT, i);
}
return -1;
},
buffer -> {
final int length = buffer.read(VAR_INT);
final int[] ints = new int[length];
for (int i = 0; i < length; i++) {
ints[i] = buffer.read(VAR_INT);
}
return ints;
});
static final TypeImpl<long[]> VAR_LONG_ARRAY = new TypeImpl<>(long[].class,
(buffer, value) -> {
buffer.write(VAR_INT, value.length);
for (long l : value) {
buffer.write(VAR_LONG, l);
}
return -1;
},
buffer -> {
final int length = buffer.read(VAR_INT);
final long[] longs = new long[length];
for (int i = 0; i < length; i++) {
longs[i] = buffer.read(VAR_LONG);
}
return longs;
});
// METADATA
static final TypeImpl<Component> OPT_CHAT = new TypeImpl<>(Component.class,
(buffer, value) -> {
if (value == null) {
buffer.write(BOOLEAN, false);
return -1;
}
buffer.write(BOOLEAN, true);
buffer.write(COMPONENT, value);
return -1;
},
buffer -> {
final boolean present = buffer.read(BOOLEAN);
if (!present) return null;
return buffer.read(COMPONENT);
});
static final TypeImpl<Point> ROTATION = new TypeImpl<>(Point.class,
(buffer, value) -> {
buffer.write(FLOAT, (float) value.x());
buffer.write(FLOAT, (float) value.y());
buffer.write(FLOAT, (float) value.z());
return -1;
},
buffer -> {
final float x = buffer.read(FLOAT);
final float y = buffer.read(FLOAT);
final float z = buffer.read(FLOAT);
return new Vec(x, y, z);
});
static final TypeImpl<Point> OPT_BLOCK_POSITION = new TypeImpl<>(Point.class,
(buffer, value) -> {
if (value == null) {
buffer.write(BOOLEAN, false);
return -1;
}
buffer.write(BOOLEAN, true);
buffer.write(BLOCK_POSITION, value);
return -1;
},
buffer -> {
final boolean present = buffer.read(BOOLEAN);
if (!present) return null;
return buffer.read(BLOCK_POSITION);
});
static final TypeImpl<Direction> DIRECTION = new TypeImpl<>(Direction.class,
(buffer, value) -> {
buffer.write(VAR_INT, value.ordinal());
return -1;
},
buffer -> {
final int ordinal = buffer.read(VAR_INT);
return Direction.values()[ordinal];
});
static final TypeImpl<UUID> OPT_UUID = new TypeImpl<>(UUID.class,
(buffer, value) -> {
if (value == null) {
buffer.write(BOOLEAN, false);
return -1;
}
buffer.write(BOOLEAN, true);
buffer.write(UUID, value);
return -1;
},
buffer -> {
final boolean present = buffer.read(BOOLEAN);
if (!present) return null;
return buffer.read(UUID);
});
static final TypeImpl<Integer> OPT_BLOCK_ID = new TypeImpl<>(Integer.class,
(buffer, value) -> {
if (value == null) {
buffer.write(NetworkBuffer.VAR_INT, 0);
return -1;
}
buffer.write(VAR_INT, value);
return -1;
},
buffer -> {
final int value = buffer.read(VAR_INT);
return value == 0 ? null : value;
});
static final TypeImpl<int[]> VILLAGER_DATA = new TypeImpl<>(int[].class,
(buffer, value) -> {
buffer.write(VAR_INT, value[0]);
buffer.write(VAR_INT, value[1]);
buffer.write(VAR_INT, value[2]);
return -1;
},
buffer -> {
final int[] value = new int[3];
value[0] = buffer.read(VAR_INT);
value[1] = buffer.read(VAR_INT);
value[2] = buffer.read(VAR_INT);
return value;
});
static final TypeImpl<Integer> OPT_VAR_INT = new TypeImpl<>(int.class,
(buffer, value) -> {
if (value == null) {
buffer.write(VAR_INT, 0);
return -1;
}
buffer.write(VAR_INT, value + 1);
return -1;
},
buffer -> {
final int value = buffer.read(VAR_INT);
return value == 0 ? null : value - 1;
});
static final TypeImpl<Entity.Pose> POSE = new TypeImpl<>(Entity.Pose.class,
(buffer, value) -> {
buffer.write(VAR_INT, value.ordinal());
return -1;
},
buffer -> {
final int ordinal = buffer.read(VAR_INT);
return Entity.Pose.values()[ordinal];
});
record TypeImpl<T>(@NotNull Class<T> type, record TypeImpl<T>(@NotNull Class<T> type,
@NotNull TypeWriter<T> writer, @NotNull TypeWriter<T> writer,
@ -313,10 +505,10 @@ final class NetworkBufferTypes {
} }
interface TypeWriter<T> { interface TypeWriter<T> {
long write(@NotNull NetworkBuffer buffer, @NotNull T value); long write(@NotNull NetworkBuffer buffer, @UnknownNullability T value);
} }
interface TypeReader<T> { interface TypeReader<T> {
@NotNull T read(@NotNull NetworkBuffer buffer); @UnknownNullability T read(@NotNull NetworkBuffer buffer);
} }
} }

View File

@ -27,18 +27,17 @@ public record PacketProcessor(@NotNull ClientPacketsHandler statusHandler,
} }
public @NotNull ClientPacket create(@NotNull ConnectionState connectionState, int packetId, ByteBuffer body) { public @NotNull ClientPacket create(@NotNull ConnectionState connectionState, int packetId, ByteBuffer body) {
NetworkBuffer networkBuffer = new NetworkBuffer(body); NetworkBuffer buffer = new NetworkBuffer(body);
BinaryReader reader = new BinaryReader(networkBuffer);
final ClientPacket clientPacket = switch (connectionState) { final ClientPacket clientPacket = switch (connectionState) {
case PLAY -> playHandler.create(packetId, reader); case PLAY -> playHandler.create(packetId, buffer);
case LOGIN -> loginHandler.create(packetId, reader); case LOGIN -> loginHandler.create(packetId, buffer);
case STATUS -> statusHandler.create(packetId, reader); case STATUS -> statusHandler.create(packetId, buffer);
case UNKNOWN -> { case UNKNOWN -> {
assert packetId == 0; assert packetId == 0;
yield new HandshakePacket(reader); yield new HandshakePacket(buffer);
} }
}; };
body.position(networkBuffer.readIndex()); body.position(buffer.readIndex());
return clientPacket; return clientPacket;
} }

View File

@ -1,11 +1,11 @@
package net.minestom.server.network.packet.client; package net.minestom.server.network.packet.client;
import net.minestom.server.utils.binary.Writeable; import net.minestom.server.network.NetworkBuffer;
/** /**
* Represents a packet received from a client. * Represents a packet received from a client.
* <p> * <p>
* Packets are value-based, and should therefore be reliant on identity. * Packets are value-based, and should therefore not be reliant on identity.
*/ */
public interface ClientPacket extends Writeable { public interface ClientPacket extends NetworkBuffer.Writer {
} }

View File

@ -1,12 +1,12 @@
package net.minestom.server.network.packet.client; package net.minestom.server.network.packet.client;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.login.EncryptionResponsePacket; import net.minestom.server.network.packet.client.login.EncryptionResponsePacket;
import net.minestom.server.network.packet.client.login.LoginPluginResponsePacket; import net.minestom.server.network.packet.client.login.LoginPluginResponsePacket;
import net.minestom.server.network.packet.client.login.LoginStartPacket; import net.minestom.server.network.packet.client.login.LoginStartPacket;
import net.minestom.server.network.packet.client.play.*; import net.minestom.server.network.packet.client.play.*;
import net.minestom.server.network.packet.client.status.PingPacket; import net.minestom.server.network.packet.client.status.PingPacket;
import net.minestom.server.network.packet.client.status.StatusRequestPacket; import net.minestom.server.network.packet.client.status.StatusRequestPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.collection.ObjectArray; import net.minestom.server.utils.collection.ObjectArray;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.UnknownNullability; import org.jetbrains.annotations.UnknownNullability;
@ -16,20 +16,20 @@ import java.util.function.Function;
/** /**
* Contains registered packets and a way to instantiate them. * Contains registered packets and a way to instantiate them.
* <p> * <p>
* Packets are registered using {@link #register(int, Function)} and created using {@link #create(int, BinaryReader)}. * Packets are registered using {@link #register(int, Function)} and created using {@link #create(int, NetworkBuffer)}.
*/ */
public sealed class ClientPacketsHandler permits ClientPacketsHandler.Status, ClientPacketsHandler.Login, ClientPacketsHandler.Play { public sealed class ClientPacketsHandler permits ClientPacketsHandler.Status, ClientPacketsHandler.Login, ClientPacketsHandler.Play {
private final ObjectArray<Function<BinaryReader, ClientPacket>> suppliers = ObjectArray.singleThread(0x10); private final ObjectArray<Function<NetworkBuffer, ClientPacket>> suppliers = ObjectArray.singleThread(0x10);
private ClientPacketsHandler() { private ClientPacketsHandler() {
} }
public void register(int id, @NotNull Function<@NotNull BinaryReader, @NotNull ClientPacket> packetSupplier) { public void register(int id, @NotNull Function<@NotNull NetworkBuffer, @NotNull ClientPacket> packetSupplier) {
this.suppliers.set(id, packetSupplier); this.suppliers.set(id, packetSupplier);
} }
public @UnknownNullability ClientPacket create(int packetId, @NotNull BinaryReader reader) { public @UnknownNullability ClientPacket create(int packetId, @NotNull NetworkBuffer reader) {
final Function<BinaryReader, ClientPacket> supplier = suppliers.get(packetId); final Function<NetworkBuffer, ClientPacket> supplier = suppliers.get(packetId);
if (supplier == null) if (supplier == null)
throw new IllegalStateException("Packet id 0x" + Integer.toHexString(packetId) + " isn't registered!"); throw new IllegalStateException("Packet id 0x" + Integer.toHexString(packetId) + " isn't registered!");
return supplier.apply(reader); return supplier.apply(reader);

View File

@ -9,13 +9,12 @@ import net.kyori.adventure.text.format.NamedTextColor;
import net.minestom.server.MinecraftServer; import net.minestom.server.MinecraftServer;
import net.minestom.server.extras.bungee.BungeeCordProxy; import net.minestom.server.extras.bungee.BungeeCordProxy;
import net.minestom.server.network.ConnectionState; import net.minestom.server.network.ConnectionState;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPreplayPacket; import net.minestom.server.network.packet.client.ClientPreplayPacket;
import net.minestom.server.network.packet.server.login.LoginDisconnectPacket; import net.minestom.server.network.packet.server.login.LoginDisconnectPacket;
import net.minestom.server.network.player.GameProfile; import net.minestom.server.network.player.GameProfile;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.network.player.PlayerSocketConnection; import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.net.SocketAddress; import java.net.SocketAddress;
@ -23,6 +22,8 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import static net.minestom.server.network.NetworkBuffer.*;
public record HandshakePacket(int protocolVersion, @NotNull String serverAddress, public record HandshakePacket(int protocolVersion, @NotNull String serverAddress,
int serverPort, int nextState) implements ClientPreplayPacket { int serverPort, int nextState) implements ClientPreplayPacket {
@ -32,21 +33,27 @@ public record HandshakePacket(int protocolVersion, @NotNull String serverAddress
private static final Component INVALID_VERSION_TEXT = Component.text("Invalid Version, please use " + MinecraftServer.VERSION_NAME, NamedTextColor.RED); private static final Component INVALID_VERSION_TEXT = Component.text("Invalid Version, please use " + MinecraftServer.VERSION_NAME, NamedTextColor.RED);
private static final Component INVALID_BUNGEE_FORWARDING = Component.text("If you wish to use IP forwarding, please enable it in your BungeeCord config as well!", NamedTextColor.RED); private static final Component INVALID_BUNGEE_FORWARDING = Component.text("If you wish to use IP forwarding, please enable it in your BungeeCord config as well!", NamedTextColor.RED);
public HandshakePacket(BinaryReader reader) { public HandshakePacket {
this(reader.readVarInt(), reader.readSizedString(BungeeCordProxy.isEnabled() ? Short.MAX_VALUE : 255), if (serverAddress.length() > (BungeeCordProxy.isEnabled() ? Short.MAX_VALUE : 255)) {
reader.readUnsignedShort(), reader.readVarInt()); throw new IllegalArgumentException("Server address too long: " + serverAddress.length());
}
}
public HandshakePacket(@NotNull NetworkBuffer reader) {
this(reader.read(VAR_INT), reader.read(STRING),
reader.read(UNSIGNED_SHORT), reader.read(VAR_INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(protocolVersion); writer.write(VAR_INT, protocolVersion);
int maxLength = BungeeCordProxy.isEnabled() ? Short.MAX_VALUE : 255; int maxLength = BungeeCordProxy.isEnabled() ? Short.MAX_VALUE : 255;
if (serverAddress.length() > maxLength) { if (serverAddress.length() > maxLength) {
throw new IllegalArgumentException("serverAddress is " + serverAddress.length() + " characters long, maximum allowed is " + maxLength); throw new IllegalArgumentException("serverAddress is " + serverAddress.length() + " characters long, maximum allowed is " + maxLength);
} }
writer.writeSizedString(serverAddress); writer.write(STRING, serverAddress);
writer.writeUnsignedShort(serverPort); writer.write(UNSIGNED_SHORT, serverPort);
writer.writeVarInt(nextState); writer.write(VAR_INT, nextState);
} }
@Override @Override
@ -63,7 +70,7 @@ public record HandshakePacket(int protocolVersion, @NotNull String serverAddress
((java.net.InetSocketAddress) connection.getRemoteAddress()).getPort()); ((java.net.InetSocketAddress) connection.getRemoteAddress()).getPort());
socketConnection.setRemoteAddress(socketAddress); socketConnection.setRemoteAddress(socketAddress);
UUID playerUuid = UUID.fromString( UUID playerUuid = java.util.UUID.fromString(
split[2] split[2]
.replaceFirst( .replaceFirst(
"(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5" "(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5"

View File

@ -7,14 +7,13 @@ import net.minestom.server.crypto.SaltSignaturePair;
import net.minestom.server.crypto.SignatureValidator; import net.minestom.server.crypto.SignatureValidator;
import net.minestom.server.extras.MojangAuth; import net.minestom.server.extras.MojangAuth;
import net.minestom.server.extras.mojangAuth.MojangCrypt; import net.minestom.server.extras.mojangAuth.MojangCrypt;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPreplayPacket; import net.minestom.server.network.packet.client.ClientPreplayPacket;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.network.player.PlayerSocketConnection; import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.utils.Either; import net.minestom.server.utils.Either;
import net.minestom.server.utils.InterfaceUtils; import net.minestom.server.utils.InterfaceUtils;
import net.minestom.server.utils.async.AsyncUtils; import net.minestom.server.utils.async.AsyncUtils;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.crypto.KeyUtils; import net.minestom.server.utils.crypto.KeyUtils;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -29,11 +28,14 @@ import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.UUID; import java.util.UUID;
public record EncryptionResponsePacket(byte[] sharedSecret, Either<byte[], SaltSignaturePair> nonceOrSignature) implements ClientPreplayPacket { import static net.minestom.server.network.NetworkBuffer.*;
public record EncryptionResponsePacket(byte[] sharedSecret,
Either<byte[], SaltSignaturePair> nonceOrSignature) implements ClientPreplayPacket {
private static final Gson GSON = new Gson(); private static final Gson GSON = new Gson();
public EncryptionResponsePacket(BinaryReader reader) { public EncryptionResponsePacket(@NotNull NetworkBuffer reader) {
this(reader.readByteArray(), reader.readEither(BinaryReader::readByteArray, SaltSignaturePair::new)); this(reader.read(BYTE_ARRAY), reader.readEither(networkBuffer -> networkBuffer.read(BYTE_ARRAY), SaltSignaturePair::new));
} }
@Override @Override
@ -54,8 +56,8 @@ public record EncryptionResponsePacket(byte[] sharedSecret, Either<byte[], SaltS
signature -> !hasPublicKey || !SignatureValidator signature -> !hasPublicKey || !SignatureValidator
.from(connection.playerPublicKey().publicKey(), KeyUtils.SignatureAlgorithm.SHA256withRSA) .from(connection.playerPublicKey().publicKey(), KeyUtils.SignatureAlgorithm.SHA256withRSA)
.validate(binaryWriter -> { .validate(binaryWriter -> {
binaryWriter.writeBytes(socketConnection.getNonce()); binaryWriter.write(RAW_BYTES, socketConnection.getNonce());
binaryWriter.writeLong(signature.salt()); binaryWriter.write(LONG, signature.salt());
}, signature.signature())); }, signature.signature()));
if (verificationFailed) { if (verificationFailed) {
@ -93,7 +95,7 @@ public record EncryptionResponsePacket(byte[] sharedSecret, Either<byte[], SaltS
return; return;
} }
socketConnection.setEncryptionKey(getSecretKey()); socketConnection.setEncryptionKey(getSecretKey());
UUID profileUUID = UUID.fromString(gameProfile.get("id").getAsString() UUID profileUUID = java.util.UUID.fromString(gameProfile.get("id").getAsString()
.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); .replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5"));
final String profileName = gameProfile.get("name").getAsString(); final String profileName = gameProfile.get("name").getAsString();
@ -107,9 +109,10 @@ public record EncryptionResponsePacket(byte[] sharedSecret, Either<byte[], SaltS
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeByteArray(sharedSecret); writer.write(BYTE_ARRAY, sharedSecret);
writer.writeEither(nonceOrSignature, BinaryWriter::writeByteArray, InterfaceUtils.flipBiConsumer(SaltSignaturePair::write)); writer.writeEither(nonceOrSignature, (networkBuffer, bytes) -> networkBuffer.write(BYTE_ARRAY, bytes),
InterfaceUtils.flipBiConsumer(SaltSignaturePair::write));
} }
private SecretKey getSecretKey() { private SecretKey getSecretKey() {

View File

@ -11,8 +11,6 @@ import net.minestom.server.network.packet.server.login.LoginDisconnectPacket;
import net.minestom.server.network.player.GameProfile; import net.minestom.server.network.player.GameProfile;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.network.player.PlayerSocketConnection; import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -22,14 +20,14 @@ import java.net.SocketAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import static net.minestom.server.network.NetworkBuffer.STRING; import static net.minestom.server.network.NetworkBuffer.*;
public record LoginPluginResponsePacket(int messageId, byte @Nullable [] data) implements ClientPreplayPacket { public record LoginPluginResponsePacket(int messageId, byte @Nullable [] data) implements ClientPreplayPacket {
private final static ConnectionManager CONNECTION_MANAGER = MinecraftServer.getConnectionManager(); private final static ConnectionManager CONNECTION_MANAGER = MinecraftServer.getConnectionManager();
public static final Component INVALID_PROXY_RESPONSE = Component.text("Invalid proxy response!", NamedTextColor.RED); public static final Component INVALID_PROXY_RESPONSE = Component.text("Invalid proxy response!", NamedTextColor.RED);
public LoginPluginResponsePacket(BinaryReader reader) { public LoginPluginResponsePacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt(), reader.readBoolean() ? reader.readRemainingBytes() : null); this(reader.read(VAR_INT), reader.readOptional(RAW_BYTES));
} }
@Override @Override
@ -59,7 +57,7 @@ public record LoginPluginResponsePacket(int messageId, byte @Nullable [] data) i
} }
final int port = ((java.net.InetSocketAddress) connection.getRemoteAddress()).getPort(); final int port = ((java.net.InetSocketAddress) connection.getRemoteAddress()).getPort();
socketAddress = new InetSocketAddress(address, port); socketAddress = new InetSocketAddress(address, port);
gameProfile = new GameProfile(new BinaryReader(buffer)); gameProfile = new GameProfile(buffer);
} }
} }
} }
@ -77,9 +75,8 @@ public record LoginPluginResponsePacket(int messageId, byte @Nullable [] data) i
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(messageId); writer.write(VAR_INT, messageId);
writer.writeBoolean(data != null); writer.writeOptional(RAW_BYTES, data);
if (data != null) writer.writeBytes(data);
} }
} }

View File

@ -9,14 +9,13 @@ import net.minestom.server.extras.MojangAuth;
import net.minestom.server.extras.bungee.BungeeCordProxy; import net.minestom.server.extras.bungee.BungeeCordProxy;
import net.minestom.server.extras.velocity.VelocityProxy; import net.minestom.server.extras.velocity.VelocityProxy;
import net.minestom.server.network.ConnectionState; import net.minestom.server.network.ConnectionState;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPreplayPacket; import net.minestom.server.network.packet.client.ClientPreplayPacket;
import net.minestom.server.network.packet.server.login.EncryptionRequestPacket; import net.minestom.server.network.packet.server.login.EncryptionRequestPacket;
import net.minestom.server.network.packet.server.login.LoginDisconnectPacket; import net.minestom.server.network.packet.server.login.LoginDisconnectPacket;
import net.minestom.server.network.packet.server.login.LoginPluginRequestPacket; import net.minestom.server.network.packet.server.login.LoginPluginRequestPacket;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.network.player.PlayerSocketConnection; import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -24,15 +23,15 @@ import java.time.Instant;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import static net.minestom.server.network.NetworkBuffer.*;
public record LoginStartPacket(@NotNull String username, public record LoginStartPacket(@NotNull String username,
@Nullable PlayerPublicKey publicKey, @Nullable PlayerPublicKey publicKey,
@Nullable UUID profileId) implements ClientPreplayPacket { @Nullable UUID profileId) implements ClientPreplayPacket {
private static final Component ALREADY_CONNECTED = Component.text("You are already on this server", NamedTextColor.RED); private static final Component ALREADY_CONNECTED = Component.text("You are already on this server", NamedTextColor.RED);
public LoginStartPacket(BinaryReader reader) { public LoginStartPacket(@NotNull NetworkBuffer reader) {
this(reader.readSizedString(16), this(reader.read(STRING), reader.readOptional(PlayerPublicKey::new), reader.readOptional(UUID));
reader.readBoolean() ? new PlayerPublicKey(reader) : null,
reader.readBoolean() ? reader.readUuid() : null);
} }
@Override @Override
@ -42,13 +41,13 @@ public record LoginStartPacket(@NotNull String username,
if (publicKey != null) { if (publicKey != null) {
if (!SignatureValidator.YGGDRASIL.validate(binaryWriter -> { if (!SignatureValidator.YGGDRASIL.validate(binaryWriter -> {
if (profileId != null) { if (profileId != null) {
binaryWriter.writeLong(profileId.getMostSignificantBits()); binaryWriter.write(LONG, profileId.getMostSignificantBits());
binaryWriter.writeLong(profileId.getLeastSignificantBits()); binaryWriter.write(LONG, profileId.getLeastSignificantBits());
} else { } else {
MinecraftServer.LOGGER.warn("Profile ID was null for player {}, signature will not match!", username); MinecraftServer.LOGGER.warn("Profile ID was null for player {}, signature will not match!", username);
} }
binaryWriter.writeLong(publicKey.expiresAt().toEpochMilli()); binaryWriter.write(LONG, publicKey.expiresAt().toEpochMilli());
binaryWriter.writeBytes(publicKey.publicKey().getEncoded()); binaryWriter.write(RAW_BYTES, publicKey.publicKey().getEncoded());
}, publicKey.signature())) { }, publicKey.signature())) {
connection.sendPacket(new LoginDisconnectPacket(Component.text("Invalid Profile Public Key!"))); connection.sendPacket(new LoginDisconnectPacket(Component.text("Invalid Profile Public Key!")));
connection.disconnect(); connection.disconnect();
@ -101,9 +100,9 @@ public record LoginStartPacket(@NotNull String username,
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
if (username.length() > 16) if (username.length() > 16)
throw new IllegalArgumentException("Username is not allowed to be longer than 16 characters"); throw new IllegalArgumentException("Username is not allowed to be longer than 16 characters");
writer.writeSizedString(username); writer.write(STRING, username);
} }
} }

View File

@ -1,15 +1,22 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.advancements.AdvancementAction; import net.minestom.server.advancements.AdvancementAction;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import static net.minestom.server.network.NetworkBuffer.STRING;
public record ClientAdvancementTabPacket(@NotNull AdvancementAction action, public record ClientAdvancementTabPacket(@NotNull AdvancementAction action,
@Nullable String tabIdentifier) implements ClientPacket { @Nullable String tabIdentifier) implements ClientPacket {
public ClientAdvancementTabPacket(BinaryReader reader) { public ClientAdvancementTabPacket {
if (tabIdentifier != null && tabIdentifier.length() > 256) {
throw new IllegalArgumentException("Tab identifier too long: " + tabIdentifier.length());
}
}
public ClientAdvancementTabPacket(@NotNull NetworkBuffer reader) {
this(read(reader)); this(read(reader));
} }
@ -17,21 +24,21 @@ public record ClientAdvancementTabPacket(@NotNull AdvancementAction action,
this(packet.action, packet.tabIdentifier); this(packet.action, packet.tabIdentifier);
} }
private static ClientAdvancementTabPacket read(BinaryReader reader) { private static ClientAdvancementTabPacket read(@NotNull NetworkBuffer reader) {
var action = AdvancementAction.values()[reader.readVarInt()]; var action = reader.readEnum(AdvancementAction.class);
var tabIdentifier = action == AdvancementAction.OPENED_TAB ? reader.readSizedString(256) : null; var tabIdentifier = action == AdvancementAction.OPENED_TAB ? reader.read(STRING) : null;
return new ClientAdvancementTabPacket(action, tabIdentifier); return new ClientAdvancementTabPacket(action, tabIdentifier);
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(action.ordinal()); writer.writeEnum(AdvancementAction.class, action);
if (action == AdvancementAction.OPENED_TAB) { if (action == AdvancementAction.OPENED_TAB) {
assert tabIdentifier != null; assert tabIdentifier != null;
if (tabIdentifier.length() > 256) { if (tabIdentifier.length() > 256) {
throw new IllegalArgumentException("Tab identifier cannot be longer than 256 characters."); throw new IllegalArgumentException("Tab identifier cannot be longer than 256 characters.");
} }
writer.writeSizedString(tabIdentifier); writer.write(STRING, tabIdentifier);
} }
} }
} }

View File

@ -1,18 +1,17 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.entity.Player; import net.minestom.server.entity.Player;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public record ClientAnimationPacket(@NotNull Player.Hand hand) implements ClientPacket { public record ClientAnimationPacket(@NotNull Player.Hand hand) implements ClientPacket {
public ClientAnimationPacket(BinaryReader reader) { public ClientAnimationPacket(@NotNull NetworkBuffer reader) {
this(Player.Hand.values()[reader.readVarInt()]); this(reader.readEnum(Player.Hand.class));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(hand.ordinal()); writer.writeEnum(Player.Hand.class, hand);
} }
} }

View File

@ -1,18 +1,17 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.crypto.LastSeenMessages; import net.minestom.server.crypto.LastSeenMessages;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public record ClientChatAckPacket(@NotNull LastSeenMessages.Update update) implements ClientPacket { public record ClientChatAckPacket(@NotNull LastSeenMessages.Update update) implements ClientPacket {
public ClientChatAckPacket(BinaryReader reader) { public ClientChatAckPacket(@NotNull NetworkBuffer reader) {
this(new LastSeenMessages.Update(reader)); this(new LastSeenMessages.Update(reader));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.write(update); writer.write(update);
} }
} }

View File

@ -2,11 +2,12 @@ package net.minestom.server.network.packet.client.play;
import net.minestom.server.crypto.LastSeenMessages; import net.minestom.server.crypto.LastSeenMessages;
import net.minestom.server.crypto.MessageSignature; import net.minestom.server.crypto.MessageSignature;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.*;
public record ClientChatMessagePacket(@NotNull String message, public record ClientChatMessagePacket(@NotNull String message,
long timestamp, long salt, @NotNull MessageSignature signature, long timestamp, long salt, @NotNull MessageSignature signature,
boolean signedPreview, boolean signedPreview,
@ -17,20 +18,20 @@ public record ClientChatMessagePacket(@NotNull String message,
} }
} }
public ClientChatMessagePacket(BinaryReader reader) { public ClientChatMessagePacket(@NotNull NetworkBuffer reader) {
this(reader.readSizedString(256), this(reader.read(STRING),
reader.readLong(), reader.readLong(), new MessageSignature(reader), reader.read(LONG), reader.read(LONG), new MessageSignature(reader),
reader.readBoolean(), reader.read(BOOLEAN),
new LastSeenMessages.Update(reader)); new LastSeenMessages.Update(reader));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeSizedString(message); writer.write(STRING, message);
writer.writeLong(timestamp); writer.write(LONG, timestamp);
writer.writeLong(salt); writer.write(LONG, salt);
writer.write(signature); writer.write(signature);
writer.writeBoolean(signedPreview); writer.write(BOOLEAN, signedPreview);
writer.write(lastSeenMessages); writer.write(lastSeenMessages);
} }
} }

View File

@ -1,18 +1,26 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.INT;
import static net.minestom.server.network.NetworkBuffer.STRING;
public record ClientChatPreviewPacket(int queryId, @NotNull String query) implements ClientPacket { public record ClientChatPreviewPacket(int queryId, @NotNull String query) implements ClientPacket {
public ClientChatPreviewPacket(BinaryReader reader) { public ClientChatPreviewPacket {
this(reader.readInt(), reader.readSizedString(256)); if (query.length() > 256) {
throw new IllegalArgumentException("Query length cannot be greater than 256");
}
}
public ClientChatPreviewPacket(@NotNull NetworkBuffer reader) {
this(reader.read(INT), reader.read(STRING));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeInt(queryId); writer.write(INT, queryId);
writer.writeSizedString(query); writer.write(STRING, query);
} }
} }

View File

@ -1,18 +1,19 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BYTE;
public record ClientClickWindowButtonPacket(byte windowId, byte buttonId) implements ClientPacket { public record ClientClickWindowButtonPacket(byte windowId, byte buttonId) implements ClientPacket {
public ClientClickWindowButtonPacket(BinaryReader reader) { public ClientClickWindowButtonPacket(@NotNull NetworkBuffer reader) {
this(reader.readByte(), reader.readByte()); this(reader.read(BYTE), reader.read(BYTE));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeByte(windowId); writer.write(BYTE, windowId);
writer.writeByte(buttonId); writer.write(BYTE, buttonId);
} }
} }

View File

@ -1,14 +1,14 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.item.ItemStack; import net.minestom.server.item.ItemStack;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.binary.Writeable;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
import static net.minestom.server.network.NetworkBuffer.*;
public record ClientClickWindowPacket(byte windowId, int stateId, public record ClientClickWindowPacket(byte windowId, int stateId,
short slot, byte button, @NotNull ClickType clickType, short slot, byte button, @NotNull ClickType clickType,
@NotNull List<ChangedSlot> changedSlots, @NotNull List<ChangedSlot> changedSlots,
@ -17,32 +17,32 @@ public record ClientClickWindowPacket(byte windowId, int stateId,
changedSlots = List.copyOf(changedSlots); changedSlots = List.copyOf(changedSlots);
} }
public ClientClickWindowPacket(BinaryReader reader) { public ClientClickWindowPacket(@NotNull NetworkBuffer reader) {
this(reader.readByte(), reader.readVarInt(), this(reader.read(BYTE), reader.read(VAR_INT),
reader.readShort(), reader.readByte(), ClickType.values()[reader.readVarInt()], reader.read(SHORT), reader.read(BYTE), reader.readEnum(ClickType.class),
reader.readVarIntList(ChangedSlot::new), reader.readItemStack()); reader.readCollection(ChangedSlot::new), reader.read(ITEM));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeByte(windowId); writer.write(BYTE, windowId);
writer.writeVarInt(stateId); writer.write(VAR_INT, stateId);
writer.writeShort(slot); writer.write(SHORT, slot);
writer.writeByte(button); writer.write(BYTE, button);
writer.writeVarInt(clickType.ordinal()); writer.write(VAR_INT, clickType.ordinal());
writer.writeVarIntList(changedSlots, BinaryWriter::write); writer.writeCollection(changedSlots);
writer.writeItemStack(clickedItem); writer.write(ITEM, clickedItem);
} }
public record ChangedSlot(short slot, @NotNull ItemStack item) implements Writeable { public record ChangedSlot(short slot, @NotNull ItemStack item) implements NetworkBuffer.Writer {
public ChangedSlot(BinaryReader reader) { public ChangedSlot(@NotNull NetworkBuffer reader) {
this(reader.readShort(), reader.readItemStack()); this(reader.read(SHORT), reader.read(ITEM));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeShort(slot); writer.write(SHORT, slot);
writer.writeItemStack(item); writer.write(ITEM, item);
} }
} }

View File

@ -1,17 +1,18 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BYTE;
public record ClientCloseWindowPacket(byte windowId) implements ClientPacket { public record ClientCloseWindowPacket(byte windowId) implements ClientPacket {
public ClientCloseWindowPacket(BinaryReader reader) { public ClientCloseWindowPacket(@NotNull NetworkBuffer reader) {
this(reader.readByte()); this(reader.read(BYTE));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeByte(windowId); writer.write(BYTE, windowId);
} }
} }

View File

@ -2,28 +2,34 @@ package net.minestom.server.network.packet.client.play;
import net.minestom.server.crypto.ArgumentSignatures; import net.minestom.server.crypto.ArgumentSignatures;
import net.minestom.server.crypto.LastSeenMessages; import net.minestom.server.crypto.LastSeenMessages;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.*;
public record ClientCommandChatPacket(@NotNull String message, long timestamp, public record ClientCommandChatPacket(@NotNull String message, long timestamp,
long salt, @NotNull ArgumentSignatures signatures, long salt, @NotNull ArgumentSignatures signatures,
boolean signedPreview, boolean signedPreview,
LastSeenMessages.@NotNull Update lastSeenMessages) implements ClientPacket { LastSeenMessages.@NotNull Update lastSeenMessages) implements ClientPacket {
public ClientCommandChatPacket {
if (message.length() > 256) {
throw new IllegalArgumentException("Message length cannot be greater than 256");
}
}
public ClientCommandChatPacket(BinaryReader reader) { public ClientCommandChatPacket(@NotNull NetworkBuffer reader) {
this(reader.readSizedString(256), reader.readLong(), this(reader.read(STRING), reader.read(LONG),
reader.readLong(), new ArgumentSignatures(reader), reader.readBoolean(), new LastSeenMessages.Update(reader)); reader.read(LONG), new ArgumentSignatures(reader), reader.read(BOOLEAN), new LastSeenMessages.Update(reader));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeSizedString(message); writer.write(STRING, message);
writer.writeLong(timestamp); writer.write(LONG, timestamp);
writer.writeLong(salt); writer.write(LONG, salt);
writer.write(signatures); writer.write(signatures);
writer.writeBoolean(signedPreview); writer.write(BOOLEAN, signedPreview);
writer.write(lastSeenMessages); writer.write(lastSeenMessages);
} }
} }

View File

@ -1,10 +1,11 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.*;
public record ClientCraftRecipeRequest(byte windowId, String recipe, boolean makeAll) implements ClientPacket { public record ClientCraftRecipeRequest(byte windowId, String recipe, boolean makeAll) implements ClientPacket {
public ClientCraftRecipeRequest { public ClientCraftRecipeRequest {
if (recipe.length() > 256) { if (recipe.length() > 256) {
@ -12,14 +13,14 @@ public record ClientCraftRecipeRequest(byte windowId, String recipe, boolean mak
} }
} }
public ClientCraftRecipeRequest(BinaryReader reader) { public ClientCraftRecipeRequest(@NotNull NetworkBuffer reader) {
this(reader.readByte(), reader.readSizedString(256), reader.readBoolean()); this(reader.read(BYTE), reader.read(STRING), reader.read(BOOLEAN));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeByte(windowId); writer.write(BYTE, windowId);
writer.writeSizedString(recipe); writer.write(STRING, recipe);
writer.writeBoolean(makeAll); writer.write(BOOLEAN, makeAll);
} }
} }

View File

@ -1,19 +1,21 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.item.ItemStack; import net.minestom.server.item.ItemStack;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.ITEM;
import static net.minestom.server.network.NetworkBuffer.SHORT;
public record ClientCreativeInventoryActionPacket(short slot, @NotNull ItemStack item) implements ClientPacket { public record ClientCreativeInventoryActionPacket(short slot, @NotNull ItemStack item) implements ClientPacket {
public ClientCreativeInventoryActionPacket(BinaryReader reader) { public ClientCreativeInventoryActionPacket(@NotNull NetworkBuffer reader) {
this(reader.readShort(), reader.readItemStack()); this(reader.read(SHORT), reader.read(ITEM));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeShort(slot); writer.write(SHORT, slot);
writer.writeItemStack(item); writer.write(ITEM, item);
} }
} }

View File

@ -1,29 +1,33 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.List; import java.util.List;
import static net.minestom.server.network.NetworkBuffer.STRING;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record ClientEditBookPacket(int slot, @NotNull List<String> pages, public record ClientEditBookPacket(int slot, @NotNull List<String> pages,
@Nullable String title) implements ClientPacket { @Nullable String title) implements ClientPacket {
public ClientEditBookPacket { public ClientEditBookPacket {
pages = List.copyOf(pages); pages = List.copyOf(pages);
if (title != null && title.length() > 128) {
throw new IllegalArgumentException("Title length cannot be greater than 128");
}
} }
public ClientEditBookPacket(BinaryReader reader) { public ClientEditBookPacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt(), reader.readVarIntList(BinaryReader::readSizedString), this(reader.read(VAR_INT), reader.readCollection(STRING),
reader.readBoolean() ? reader.readSizedString(128) : null); reader.readOptional(STRING));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(slot); writer.write(VAR_INT, slot);
writer.writeVarIntList(pages, BinaryWriter::writeSizedString); writer.writeCollection(STRING, pages);
writer.writeBoolean(title != null); writer.writeOptional(STRING, title);
if (title != null) writer.writeSizedString(title);
} }
} }

View File

@ -1,22 +1,23 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record ClientEntityActionPacket(int playerId, @NotNull Action action, public record ClientEntityActionPacket(int playerId, @NotNull Action action,
int horseJumpBoost) implements ClientPacket { int horseJumpBoost) implements ClientPacket {
public ClientEntityActionPacket(BinaryReader reader) { public ClientEntityActionPacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt(), Action.values()[reader.readVarInt()], this(reader.read(VAR_INT), reader.readEnum(Action.class),
reader.readVarInt()); reader.read(VAR_INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(playerId); writer.write(VAR_INT, playerId);
writer.writeVarInt(action.ordinal()); writer.writeEnum(Action.class, action);
writer.writeVarInt(horseJumpBoost); writer.write(VAR_INT, horseJumpBoost);
} }
public enum Action { public enum Action {

View File

@ -1,21 +1,22 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.*;
public record ClientGenerateStructurePacket(@NotNull Point blockPosition, public record ClientGenerateStructurePacket(@NotNull Point blockPosition,
int level, boolean keepJigsaws) implements ClientPacket { int level, boolean keepJigsaws) implements ClientPacket {
public ClientGenerateStructurePacket(BinaryReader reader) { public ClientGenerateStructurePacket(@NotNull NetworkBuffer reader) {
this(reader.readBlockPosition(), reader.readVarInt(), reader.readBoolean()); this(reader.read(BLOCK_POSITION), reader.read(VAR_INT), reader.read(BOOLEAN));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBlockPosition(blockPosition); writer.write(BLOCK_POSITION, blockPosition);
writer.writeVarInt(level); writer.write(VAR_INT, level);
writer.writeBoolean(keepJigsaws); writer.write(BOOLEAN, keepJigsaws);
} }
} }

View File

@ -1,17 +1,18 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.SHORT;
public record ClientHeldItemChangePacket(short slot) implements ClientPacket { public record ClientHeldItemChangePacket(short slot) implements ClientPacket {
public ClientHeldItemChangePacket(BinaryReader reader) { public ClientHeldItemChangePacket(@NotNull NetworkBuffer reader) {
this(reader.readShort()); this(reader.read(SHORT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeShort(slot); writer.write(SHORT, slot);
} }
} }

View File

@ -1,43 +1,44 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.entity.Player; import net.minestom.server.entity.Player;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.binary.Writeable; import net.minestom.server.utils.binary.Writeable;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.*;
public record ClientInteractEntityPacket(int targetId, @NotNull Type type, boolean sneaking) implements ClientPacket { public record ClientInteractEntityPacket(int targetId, @NotNull Type type, boolean sneaking) implements ClientPacket {
public ClientInteractEntityPacket(BinaryReader reader) { public ClientInteractEntityPacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt(), switch (reader.readVarInt()) { this(reader.read(VAR_INT), switch (reader.read(VAR_INT)) {
case 0 -> new Interact(reader); case 0 -> new Interact(reader);
case 1 -> new Attack(); case 1 -> new Attack();
case 2 -> new InteractAt(reader); case 2 -> new InteractAt(reader);
default -> throw new RuntimeException("Unknown action id"); default -> throw new RuntimeException("Unknown action id");
}, reader.readBoolean()); }, reader.read(BOOLEAN));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(targetId); writer.write(VAR_INT, targetId);
writer.writeVarInt(type.id()); writer.write(VAR_INT, type.id());
writer.write(type); writer.write(type);
writer.writeBoolean(sneaking); writer.write(BOOLEAN, sneaking);
} }
public sealed interface Type extends Writeable public sealed interface Type extends Writer
permits Interact, Attack, InteractAt { permits Interact, Attack, InteractAt {
int id(); int id();
} }
public record Interact(@NotNull Player.Hand hand) implements Type { public record Interact(Player.@NotNull Hand hand) implements Type {
public Interact(BinaryReader reader) { public Interact(@NotNull NetworkBuffer reader) {
this(Player.Hand.values()[reader.readVarInt()]); this(reader.readEnum(Player.Hand.class));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(hand.ordinal()); writer.writeEnum(Player.Hand.class, hand);
} }
@Override @Override
@ -48,7 +49,7 @@ public record ClientInteractEntityPacket(int targetId, @NotNull Type type, boole
public record Attack() implements Type { public record Attack() implements Type {
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
// Empty // Empty
} }
@ -59,18 +60,18 @@ public record ClientInteractEntityPacket(int targetId, @NotNull Type type, boole
} }
public record InteractAt(float targetX, float targetY, float targetZ, public record InteractAt(float targetX, float targetY, float targetZ,
Player.Hand hand) implements Type { Player.@NotNull Hand hand) implements Type {
public InteractAt(BinaryReader reader) { public InteractAt(@NotNull NetworkBuffer reader) {
this(reader.readFloat(), reader.readFloat(), reader.readFloat(), this(reader.read(FLOAT), reader.read(FLOAT), reader.read(FLOAT),
Player.Hand.values()[reader.readVarInt()]); reader.readEnum(Player.Hand.class));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeFloat(targetX); writer.write(FLOAT, targetX);
writer.writeFloat(targetY); writer.write(FLOAT, targetY);
writer.writeFloat(targetZ); writer.write(FLOAT, targetZ);
writer.writeVarInt(hand.ordinal()); writer.writeEnum(Player.Hand.class, hand);
} }
@Override @Override

View File

@ -1,17 +1,18 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.LONG;
public record ClientKeepAlivePacket(long id) implements ClientPacket { public record ClientKeepAlivePacket(long id) implements ClientPacket {
public ClientKeepAlivePacket(BinaryReader reader) { public ClientKeepAlivePacket(@NotNull NetworkBuffer reader) {
this(reader.readLong()); this(reader.read(LONG));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeLong(id); writer.write(LONG, id);
} }
} }

View File

@ -1,10 +1,11 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.STRING;
public record ClientNameItemPacket(@NotNull String itemName) implements ClientPacket { public record ClientNameItemPacket(@NotNull String itemName) implements ClientPacket {
public ClientNameItemPacket { public ClientNameItemPacket {
if (itemName.length() > Short.MAX_VALUE) { if (itemName.length() > Short.MAX_VALUE) {
@ -12,12 +13,12 @@ public record ClientNameItemPacket(@NotNull String itemName) implements ClientPa
} }
} }
public ClientNameItemPacket(BinaryReader reader) { public ClientNameItemPacket(@NotNull NetworkBuffer reader) {
this(reader.readSizedString(Short.MAX_VALUE)); this(reader.read(STRING));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeSizedString(itemName); writer.write(STRING, itemName);
} }
} }

View File

@ -1,17 +1,18 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record ClientPickItemPacket(int slot) implements ClientPacket { public record ClientPickItemPacket(int slot) implements ClientPacket {
public ClientPickItemPacket(BinaryReader reader) { public ClientPickItemPacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt()); this(reader.read(VAR_INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(slot); writer.write(VAR_INT, slot);
} }
} }

View File

@ -1,17 +1,18 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BYTE;
public record ClientPlayerAbilitiesPacket(byte flags) implements ClientPacket { public record ClientPlayerAbilitiesPacket(byte flags) implements ClientPacket {
public ClientPlayerAbilitiesPacket(BinaryReader reader) { public ClientPlayerAbilitiesPacket(@NotNull NetworkBuffer reader) {
this(reader.readByte()); this(reader.read(BYTE));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeByte(flags); writer.write(BYTE, flags);
} }
} }

View File

@ -3,31 +3,32 @@ package net.minestom.server.network.packet.client.play;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.entity.Player; import net.minestom.server.entity.Player;
import net.minestom.server.instance.block.BlockFace; import net.minestom.server.instance.block.BlockFace;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.*;
public record ClientPlayerBlockPlacementPacket(@NotNull Player.Hand hand, @NotNull Point blockPosition, public record ClientPlayerBlockPlacementPacket(@NotNull Player.Hand hand, @NotNull Point blockPosition,
@NotNull BlockFace blockFace, @NotNull BlockFace blockFace,
float cursorPositionX, float cursorPositionY, float cursorPositionZ, float cursorPositionX, float cursorPositionY, float cursorPositionZ,
boolean insideBlock, int sequence) implements ClientPacket { boolean insideBlock, int sequence) implements ClientPacket {
public ClientPlayerBlockPlacementPacket(BinaryReader reader) { public ClientPlayerBlockPlacementPacket(@NotNull NetworkBuffer reader) {
this(Player.Hand.values()[reader.readVarInt()], reader.readBlockPosition(), this(reader.readEnum(Player.Hand.class), reader.read(BLOCK_POSITION),
BlockFace.values()[reader.readVarInt()], reader.readEnum(BlockFace.class),
reader.readFloat(), reader.readFloat(), reader.readFloat(), reader.read(FLOAT), reader.read(FLOAT), reader.read(FLOAT),
reader.readBoolean(), reader.readVarInt()); reader.read(BOOLEAN), reader.read(VAR_INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(hand.ordinal()); writer.writeEnum(Player.Hand.class, hand);
writer.writeBlockPosition(blockPosition); writer.write(BLOCK_POSITION, blockPosition);
writer.writeVarInt(blockFace.ordinal()); writer.writeEnum(BlockFace.class, blockFace);
writer.writeFloat(cursorPositionX); writer.write(FLOAT, cursorPositionX);
writer.writeFloat(cursorPositionY); writer.write(FLOAT, cursorPositionY);
writer.writeFloat(cursorPositionZ); writer.write(FLOAT, cursorPositionZ);
writer.writeBoolean(insideBlock); writer.write(BOOLEAN, insideBlock);
writer.writeVarInt(sequence); writer.write(VAR_INT, sequence);
} }
} }

View File

@ -2,24 +2,25 @@ package net.minestom.server.network.packet.client.play;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.instance.block.BlockFace; import net.minestom.server.instance.block.BlockFace;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.*;
public record ClientPlayerDiggingPacket(@NotNull Status status, @NotNull Point blockPosition, public record ClientPlayerDiggingPacket(@NotNull Status status, @NotNull Point blockPosition,
@NotNull BlockFace blockFace, int sequence) implements ClientPacket { @NotNull BlockFace blockFace, int sequence) implements ClientPacket {
public ClientPlayerDiggingPacket(BinaryReader reader) { public ClientPlayerDiggingPacket(@NotNull NetworkBuffer reader) {
this(Status.values()[reader.readVarInt()], reader.readBlockPosition(), this(reader.readEnum(Status.class), reader.read(BLOCK_POSITION),
BlockFace.values()[reader.readByte()], reader.readVarInt()); BlockFace.values()[reader.read(BYTE)], reader.read(VAR_INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(status.ordinal()); writer.writeEnum(Status.class, status);
writer.writeBlockPosition(blockPosition); writer.write(BLOCK_POSITION, blockPosition);
writer.writeByte((byte) blockFace.ordinal()); writer.write(BYTE, (byte) blockFace.ordinal());
writer.writeVarInt(sequence); writer.write(VAR_INT, sequence);
} }
public enum Status { public enum Status {

View File

@ -1,17 +1,18 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BOOLEAN;
public record ClientPlayerPacket(boolean onGround) implements ClientPacket { public record ClientPlayerPacket(boolean onGround) implements ClientPacket {
public ClientPlayerPacket(BinaryReader reader) { public ClientPlayerPacket(@NotNull NetworkBuffer reader) {
this(reader.readBoolean()); this(reader.read(BOOLEAN));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBoolean(onGround); writer.write(BOOLEAN, onGround);
} }
} }

View File

@ -1,25 +1,26 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Pos;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.*;
public record ClientPlayerPositionAndRotationPacket(@NotNull Pos position, public record ClientPlayerPositionAndRotationPacket(@NotNull Pos position,
boolean onGround) implements ClientPacket { boolean onGround) implements ClientPacket {
public ClientPlayerPositionAndRotationPacket(BinaryReader reader) { public ClientPlayerPositionAndRotationPacket(@NotNull NetworkBuffer reader) {
this(new Pos(reader.readDouble(), reader.readDouble(), reader.readDouble(), this(new Pos(reader.read(DOUBLE), reader.read(DOUBLE), reader.read(DOUBLE),
reader.readFloat(), reader.readFloat()), reader.readBoolean()); reader.read(FLOAT), reader.read(FLOAT)), reader.read(BOOLEAN));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeDouble(position.x()); writer.write(DOUBLE, position.x());
writer.writeDouble(position.y()); writer.write(DOUBLE, position.y());
writer.writeDouble(position.z()); writer.write(DOUBLE, position.z());
writer.writeFloat(position.yaw()); writer.write(FLOAT, position.yaw());
writer.writeFloat(position.pitch()); writer.write(FLOAT, position.pitch());
writer.writeBoolean(onGround); writer.write(BOOLEAN, onGround);
} }
} }

View File

@ -2,23 +2,25 @@ package net.minestom.server.network.packet.client.play;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.coordinate.Vec; import net.minestom.server.coordinate.Vec;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BOOLEAN;
import static net.minestom.server.network.NetworkBuffer.DOUBLE;
public record ClientPlayerPositionPacket(@NotNull Point position, public record ClientPlayerPositionPacket(@NotNull Point position,
boolean onGround) implements ClientPacket { boolean onGround) implements ClientPacket {
public ClientPlayerPositionPacket(BinaryReader reader) { public ClientPlayerPositionPacket(@NotNull NetworkBuffer reader) {
this(new Vec(reader.readDouble(), reader.readDouble(), reader.readDouble()), this(new Vec(reader.read(DOUBLE), reader.read(DOUBLE), reader.read(DOUBLE)),
reader.readBoolean()); reader.read(BOOLEAN));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeDouble(position.x()); writer.write(DOUBLE, position.x());
writer.writeDouble(position.y()); writer.write(DOUBLE, position.y());
writer.writeDouble(position.z()); writer.write(DOUBLE, position.z());
writer.writeBoolean(onGround); writer.write(BOOLEAN, onGround);
} }
} }

View File

@ -1,19 +1,21 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BOOLEAN;
import static net.minestom.server.network.NetworkBuffer.FLOAT;
public record ClientPlayerRotationPacket(float yaw, float pitch, boolean onGround) implements ClientPacket { public record ClientPlayerRotationPacket(float yaw, float pitch, boolean onGround) implements ClientPacket {
public ClientPlayerRotationPacket(BinaryReader reader) { public ClientPlayerRotationPacket(@NotNull NetworkBuffer reader) {
this(reader.readFloat(), reader.readFloat(), reader.readBoolean()); this(reader.read(FLOAT), reader.read(FLOAT), reader.read(BOOLEAN));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeFloat(yaw); writer.write(FLOAT, yaw);
writer.writeFloat(pitch); writer.write(FLOAT, pitch);
writer.writeBoolean(onGround); writer.write(BOOLEAN, onGround);
} }
} }

View File

@ -1,23 +1,25 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.RAW_BYTES;
import static net.minestom.server.network.NetworkBuffer.STRING;
public record ClientPluginMessagePacket(@NotNull String channel, byte[] data) implements ClientPacket { public record ClientPluginMessagePacket(@NotNull String channel, byte[] data) implements ClientPacket {
public ClientPluginMessagePacket { public ClientPluginMessagePacket {
if (channel.length() > 256) if (channel.length() > 256)
throw new IllegalArgumentException("Channel cannot be more than 256 characters long"); throw new IllegalArgumentException("Channel cannot be more than 256 characters long");
} }
public ClientPluginMessagePacket(BinaryReader reader) { public ClientPluginMessagePacket(@NotNull NetworkBuffer reader) {
this(reader.readSizedString(256), reader.readRemainingBytes()); this(reader.read(STRING), reader.read(RAW_BYTES));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeSizedString(channel); writer.write(STRING, channel);
writer.writeBytes(data); writer.write(RAW_BYTES, data);
} }
} }

View File

@ -1,17 +1,18 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.INT;
public record ClientPongPacket(int id) implements ClientPacket { public record ClientPongPacket(int id) implements ClientPacket {
public ClientPongPacket(BinaryReader reader) { public ClientPongPacket(@NotNull NetworkBuffer reader) {
this(reader.readInt()); this(reader.read(INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeInt(id); writer.write(INT, id);
} }
} }

View File

@ -1,19 +1,21 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BLOCK_POSITION;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record ClientQueryBlockNbtPacket(int transactionId, @NotNull Point blockPosition) implements ClientPacket { public record ClientQueryBlockNbtPacket(int transactionId, @NotNull Point blockPosition) implements ClientPacket {
public ClientQueryBlockNbtPacket(BinaryReader reader) { public ClientQueryBlockNbtPacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt(), reader.readBlockPosition()); this(reader.read(VAR_INT), reader.read(BLOCK_POSITION));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(transactionId); writer.write(VAR_INT, transactionId);
writer.writeBlockPosition(blockPosition); writer.write(BLOCK_POSITION, blockPosition);
} }
} }

View File

@ -1,18 +1,19 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record ClientQueryEntityNbtPacket(int transactionId, int entityId) implements ClientPacket { public record ClientQueryEntityNbtPacket(int transactionId, int entityId) implements ClientPacket {
public ClientQueryEntityNbtPacket(BinaryReader reader) { public ClientQueryEntityNbtPacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt(), reader.readVarInt()); this(reader.read(VAR_INT), reader.read(VAR_INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(transactionId); writer.write(VAR_INT, transactionId);
writer.writeVarInt(entityId); writer.write(VAR_INT, entityId);
} }
} }

View File

@ -1,18 +1,17 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.resourcepack.ResourcePackStatus; import net.minestom.server.resourcepack.ResourcePackStatus;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public record ClientResourcePackStatusPacket(@NotNull ResourcePackStatus status) implements ClientPacket { public record ClientResourcePackStatusPacket(@NotNull ResourcePackStatus status) implements ClientPacket {
public ClientResourcePackStatusPacket(BinaryReader reader) { public ClientResourcePackStatusPacket(@NotNull NetworkBuffer reader) {
this(ResourcePackStatus.values()[reader.readVarInt()]); this(reader.readEnum(ResourcePackStatus.class));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(status.ordinal()); writer.writeEnum(ResourcePackStatus.class, status);
} }
} }

View File

@ -1,17 +1,18 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record ClientSelectTradePacket(int selectedSlot) implements ClientPacket { public record ClientSelectTradePacket(int selectedSlot) implements ClientPacket {
public ClientSelectTradePacket(BinaryReader reader) { public ClientSelectTradePacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt()); this(reader.read(VAR_INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(selectedSlot); writer.write(VAR_INT, selectedSlot);
} }
} }

View File

@ -1,24 +1,26 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.potion.PotionType; import net.minestom.server.potion.PotionType;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import static net.minestom.server.network.NetworkBuffer.BOOLEAN;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record ClientSetBeaconEffectPacket(@Nullable PotionType primaryEffect, public record ClientSetBeaconEffectPacket(@Nullable PotionType primaryEffect,
@Nullable PotionType secondaryEffect) implements ClientPacket { @Nullable PotionType secondaryEffect) implements ClientPacket {
public ClientSetBeaconEffectPacket(BinaryReader reader) { public ClientSetBeaconEffectPacket(@NotNull NetworkBuffer reader) {
this(reader.readBoolean() ? PotionType.fromId(reader.readVarInt()) : null, this(reader.read(BOOLEAN) ? PotionType.fromId(reader.read(VAR_INT)) : null,
reader.readBoolean() ? PotionType.fromId(reader.readVarInt()) : null); reader.read(BOOLEAN) ? PotionType.fromId(reader.read(VAR_INT)) : null);
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBoolean(primaryEffect != null); writer.write(BOOLEAN, primaryEffect != null);
if (primaryEffect != null) writer.writeVarInt(primaryEffect.id()); if (primaryEffect != null) writer.write(VAR_INT, primaryEffect.id());
writer.writeBoolean(secondaryEffect != null); writer.write(BOOLEAN, secondaryEffect != null);
if (secondaryEffect != null) writer.writeVarInt(secondaryEffect.id()); if (secondaryEffect != null) writer.write(VAR_INT, secondaryEffect.id());
} }
} }

View File

@ -1,17 +1,24 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.STRING;
public record ClientSetDisplayedRecipePacket(@NotNull String recipeId) implements ClientPacket { public record ClientSetDisplayedRecipePacket(@NotNull String recipeId) implements ClientPacket {
public ClientSetDisplayedRecipePacket(BinaryReader reader) { public ClientSetDisplayedRecipePacket {
this(reader.readSizedString(256)); if (recipeId.length() > 256) {
throw new IllegalArgumentException("'recipeId' cannot be longer than 256 characters.");
}
}
public ClientSetDisplayedRecipePacket(@NotNull NetworkBuffer reader) {
this(reader.read(STRING));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeSizedString(recipeId); writer.write(STRING, recipeId);
} }
} }

View File

@ -1,21 +1,22 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BOOLEAN;
public record ClientSetRecipeBookStatePacket(@NotNull BookType bookType, public record ClientSetRecipeBookStatePacket(@NotNull BookType bookType,
boolean bookOpen, boolean filterActive) implements ClientPacket { boolean bookOpen, boolean filterActive) implements ClientPacket {
public ClientSetRecipeBookStatePacket(BinaryReader reader) { public ClientSetRecipeBookStatePacket(@NotNull NetworkBuffer reader) {
this(BookType.values()[reader.readVarInt()], reader.readBoolean(), reader.readBoolean()); this(reader.readEnum(BookType.class), reader.read(BOOLEAN), reader.read(BOOLEAN));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(bookType.ordinal()); writer.writeEnum(BookType.class, bookType);
writer.writeBoolean(bookOpen); writer.write(BOOLEAN, bookOpen);
writer.writeBoolean(filterActive); writer.write(BOOLEAN, filterActive);
} }
public enum BookType { public enum BookType {

View File

@ -2,11 +2,12 @@ package net.minestom.server.network.packet.client.play;
import net.minestom.server.entity.Player; import net.minestom.server.entity.Player;
import net.minestom.server.message.ChatMessageType; import net.minestom.server.message.ChatMessageType;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.*;
public record ClientSettingsPacket(@NotNull String locale, byte viewDistance, public record ClientSettingsPacket(@NotNull String locale, byte viewDistance,
@NotNull ChatMessageType chatMessageType, boolean chatColors, @NotNull ChatMessageType chatMessageType, boolean chatColors,
byte displayedSkinParts, @NotNull Player.MainHand mainHand, byte displayedSkinParts, @NotNull Player.MainHand mainHand,
@ -16,22 +17,22 @@ public record ClientSettingsPacket(@NotNull String locale, byte viewDistance,
throw new IllegalArgumentException("Locale cannot be longer than 128 characters."); throw new IllegalArgumentException("Locale cannot be longer than 128 characters.");
} }
public ClientSettingsPacket(BinaryReader reader) { public ClientSettingsPacket(@NotNull NetworkBuffer reader) {
this(reader.readSizedString(128), reader.readByte(), this(reader.read(STRING), reader.read(BYTE),
ChatMessageType.fromPacketID(reader.readVarInt()), reader.readBoolean(), ChatMessageType.fromPacketID(reader.read(VAR_INT)), reader.read(BOOLEAN),
reader.readByte(), Player.MainHand.values()[reader.readVarInt()], reader.read(BYTE), reader.readEnum(Player.MainHand.class),
reader.readBoolean(), reader.readBoolean()); reader.read(BOOLEAN), reader.read(BOOLEAN));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeSizedString(locale); writer.write(STRING, locale);
writer.writeByte(viewDistance); writer.write(BYTE, viewDistance);
writer.writeVarInt(chatMessageType.getPacketID()); writer.write(VAR_INT, chatMessageType.getPacketID());
writer.writeBoolean(chatColors); writer.write(BOOLEAN, chatColors);
writer.writeByte(displayedSkinParts); writer.write(BYTE, displayedSkinParts);
writer.writeVarInt(mainHand.ordinal()); writer.write(VAR_INT, mainHand.ordinal());
writer.writeBoolean(enableTextFiltering); writer.write(BOOLEAN, enableTextFiltering);
writer.writeBoolean(allowsListing); writer.write(BOOLEAN, allowsListing);
} }
} }

View File

@ -1,8 +1,7 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.UUID; import java.util.UUID;
@ -13,12 +12,12 @@ import java.util.UUID;
* rather than spectating them. * rather than spectating them.
*/ */
public record ClientSpectatePacket(@NotNull UUID target) implements ClientPacket { public record ClientSpectatePacket(@NotNull UUID target) implements ClientPacket {
public ClientSpectatePacket(BinaryReader reader) { public ClientSpectatePacket(@NotNull NetworkBuffer reader) {
this(reader.readUuid()); this(reader.read(NetworkBuffer.UUID));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeUuid(target); writer.write(NetworkBuffer.UUID, target);
} }
} }

View File

@ -1,18 +1,17 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public record ClientStatusPacket(@NotNull Action action) implements ClientPacket { public record ClientStatusPacket(@NotNull Action action) implements ClientPacket {
public ClientStatusPacket(BinaryReader reader) { public ClientStatusPacket(@NotNull NetworkBuffer reader) {
this(Action.values()[reader.readVarInt()]); this(reader.readEnum(Action.class));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(action.ordinal()); writer.writeEnum(Action.class, action);
} }
public enum Action { public enum Action {

View File

@ -1,18 +1,19 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BOOLEAN;
public record ClientSteerBoatPacket(boolean leftPaddleTurning, boolean rightPaddleTurning) implements ClientPacket { public record ClientSteerBoatPacket(boolean leftPaddleTurning, boolean rightPaddleTurning) implements ClientPacket {
public ClientSteerBoatPacket(BinaryReader reader) { public ClientSteerBoatPacket(@NotNull NetworkBuffer reader) {
this(reader.readBoolean(), reader.readBoolean()); this(reader.read(BOOLEAN), reader.read(BOOLEAN));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBoolean(leftPaddleTurning); writer.write(BOOLEAN, leftPaddleTurning);
writer.writeBoolean(rightPaddleTurning); writer.write(BOOLEAN, rightPaddleTurning);
} }
} }

View File

@ -1,20 +1,22 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BYTE;
import static net.minestom.server.network.NetworkBuffer.FLOAT;
public record ClientSteerVehiclePacket(float sideways, float forward, public record ClientSteerVehiclePacket(float sideways, float forward,
byte flags) implements ClientPacket { byte flags) implements ClientPacket {
public ClientSteerVehiclePacket(BinaryReader reader) { public ClientSteerVehiclePacket(@NotNull NetworkBuffer reader) {
this(reader.readFloat(), reader.readFloat(), reader.readByte()); this(reader.read(FLOAT), reader.read(FLOAT), reader.read(BYTE));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeFloat(sideways); writer.write(FLOAT, sideways);
writer.writeFloat(forward); writer.write(FLOAT, forward);
writer.writeByte(flags); writer.write(BYTE, flags);
} }
} }

View File

@ -1,18 +1,20 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.STRING;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record ClientTabCompletePacket(int transactionId, @NotNull String text) implements ClientPacket { public record ClientTabCompletePacket(int transactionId, @NotNull String text) implements ClientPacket {
public ClientTabCompletePacket(BinaryReader reader) { public ClientTabCompletePacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt(), reader.readSizedString(Short.MAX_VALUE)); this(reader.read(VAR_INT), reader.read(STRING));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(transactionId); writer.write(VAR_INT, transactionId);
writer.writeSizedString(text); writer.write(STRING, text);
} }
} }

View File

@ -1,17 +1,18 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record ClientTeleportConfirmPacket(int teleportId) implements ClientPacket { public record ClientTeleportConfirmPacket(int teleportId) implements ClientPacket {
public ClientTeleportConfirmPacket(BinaryReader reader) { public ClientTeleportConfirmPacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt()); this(reader.read(VAR_INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(teleportId); writer.write(VAR_INT, teleportId);
} }
} }

View File

@ -1,20 +1,21 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.*;
public record ClientUpdateCommandBlockMinecartPacket(int entityId, @NotNull String command, public record ClientUpdateCommandBlockMinecartPacket(int entityId, @NotNull String command,
boolean trackOutput) implements ClientPacket { boolean trackOutput) implements ClientPacket {
public ClientUpdateCommandBlockMinecartPacket(BinaryReader reader) { public ClientUpdateCommandBlockMinecartPacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt(), reader.readSizedString(Short.MAX_VALUE), reader.readBoolean()); this(reader.read(VAR_INT), reader.read(STRING), reader.read(BOOLEAN));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(entityId); writer.write(VAR_INT, entityId);
writer.writeSizedString(command); writer.write(STRING, command);
writer.writeBoolean(trackOutput); writer.write(BOOLEAN, trackOutput);
} }
} }

View File

@ -1,24 +1,25 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.*;
public record ClientUpdateCommandBlockPacket(@NotNull Point blockPosition, @NotNull String command, public record ClientUpdateCommandBlockPacket(@NotNull Point blockPosition, @NotNull String command,
@NotNull Mode mode, byte flags) implements ClientPacket { @NotNull Mode mode, byte flags) implements ClientPacket {
public ClientUpdateCommandBlockPacket(BinaryReader reader) { public ClientUpdateCommandBlockPacket(@NotNull NetworkBuffer reader) {
this(reader.readBlockPosition(), reader.readSizedString(Short.MAX_VALUE), this(reader.read(BLOCK_POSITION), reader.read(STRING),
Mode.values()[reader.readVarInt()], reader.readByte()); Mode.values()[reader.read(VAR_INT)], reader.read(BYTE));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBlockPosition(blockPosition); writer.write(BLOCK_POSITION, blockPosition);
writer.writeSizedString(command); writer.write(STRING, command);
writer.writeVarInt(mode.ordinal()); writer.write(VAR_INT, mode.ordinal());
writer.writeByte(flags); writer.write(BYTE, flags);
} }
public enum Mode { public enum Mode {

View File

@ -1,13 +1,15 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
import static net.minestom.server.network.NetworkBuffer.BLOCK_POSITION;
import static net.minestom.server.network.NetworkBuffer.STRING;
public record ClientUpdateSignPacket(@NotNull Point blockPosition, public record ClientUpdateSignPacket(@NotNull Point blockPosition,
@NotNull List<String> lines) implements ClientPacket { @NotNull List<String> lines) implements ClientPacket {
public ClientUpdateSignPacket { public ClientUpdateSignPacket {
@ -22,21 +24,21 @@ public record ClientUpdateSignPacket(@NotNull Point blockPosition,
} }
} }
public ClientUpdateSignPacket(BinaryReader reader) { public ClientUpdateSignPacket(@NotNull NetworkBuffer reader) {
this(reader.readBlockPosition(), readLines(reader)); this(reader.read(BLOCK_POSITION), readLines(reader));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBlockPosition(blockPosition); writer.write(BLOCK_POSITION, blockPosition);
writer.writeSizedString(lines.get(0)); writer.write(STRING, lines.get(0));
writer.writeSizedString(lines.get(1)); writer.write(STRING, lines.get(1));
writer.writeSizedString(lines.get(2)); writer.write(STRING, lines.get(2));
writer.writeSizedString(lines.get(3)); writer.write(STRING, lines.get(3));
} }
private static List<String> readLines(BinaryReader reader) { private static List<String> readLines(@NotNull NetworkBuffer reader) {
return List.of(reader.readSizedString(384), reader.readSizedString(384), return List.of(reader.read(STRING), reader.read(STRING),
reader.readSizedString(384), reader.readSizedString(384)); reader.read(STRING), reader.read(STRING));
} }
} }

View File

@ -2,25 +2,26 @@ package net.minestom.server.network.packet.client.play;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.coordinate.Vec; import net.minestom.server.coordinate.Vec;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.Rotation; import net.minestom.server.utils.Rotation;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.*;
public record ClientUpdateStructureBlockPacket(Point location, Action action, public record ClientUpdateStructureBlockPacket(Point location, Action action,
Mode mode, String name, Mode mode, String name,
Point offset, Point size, Point offset, Point size,
Mirror mirror, Rotation rotation, Mirror mirror, Rotation rotation,
String metadata, float integrity, String metadata, float integrity,
long seed, byte flags) implements ClientPacket { long seed, byte flags) implements ClientPacket {
public ClientUpdateStructureBlockPacket(BinaryReader reader) { public ClientUpdateStructureBlockPacket(@NotNull NetworkBuffer reader) {
this(reader.readBlockPosition(), Action.values()[reader.readVarInt()], this(reader.read(BLOCK_POSITION), reader.readEnum(Action.class),
Mode.values()[reader.readVarInt()], reader.readSizedString(Short.MAX_VALUE), reader.readEnum(Mode.class), reader.read(STRING),
new Vec(reader.readByte(), reader.readByte(), reader.readByte()), new Vec(reader.readByte(), reader.readByte(), reader.readByte()), new Vec(reader.read(BYTE), reader.read(BYTE), reader.read(BYTE)), new Vec(reader.read(BYTE), reader.read(BYTE), reader.read(BYTE)),
Mirror.values()[reader.readVarInt()], fromRestrictedRotation(reader.readVarInt()), Mirror.values()[reader.read(VAR_INT)], fromRestrictedRotation(reader.read(VAR_INT)),
reader.readSizedString(Short.MAX_VALUE), reader.readFloat(), reader.read(STRING), reader.read(FLOAT),
reader.readVarLong(), reader.readByte()); reader.read(VAR_LONG), reader.read(BYTE));
} }
// Flag values // Flag values
@ -32,23 +33,23 @@ public record ClientUpdateStructureBlockPacket(Point location, Action action,
public static final byte SHOW_BOUNDING_BOX = 0x4; public static final byte SHOW_BOUNDING_BOX = 0x4;
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBlockPosition(location); writer.write(BLOCK_POSITION, location);
writer.writeVarInt(action.ordinal()); writer.writeEnum(Action.class, action);
writer.writeVarInt(mode.ordinal()); writer.writeEnum(Mode.class, mode);
writer.writeSizedString(name); writer.write(STRING, name);
writer.writeByte((byte) offset.x()); writer.write(BYTE, (byte) offset.x());
writer.writeByte((byte) offset.y()); writer.write(BYTE, (byte) offset.y());
writer.writeByte((byte) offset.z()); writer.write(BYTE, (byte) offset.z());
writer.writeByte((byte) size.x()); writer.write(BYTE, (byte) size.x());
writer.writeByte((byte) size.y()); writer.write(BYTE, (byte) size.y());
writer.writeByte((byte) size.z()); writer.write(BYTE, (byte) size.z());
writer.writeVarInt(mirror.ordinal()); writer.write(VAR_INT, mirror.ordinal());
writer.writeVarInt(toRestrictedRotation(rotation)); writer.write(VAR_INT, toRestrictedRotation(rotation));
writer.writeSizedString(metadata); writer.write(STRING, metadata);
writer.writeFloat(integrity); writer.write(FLOAT, integrity);
writer.writeVarLong(seed); writer.write(VAR_LONG, seed);
writer.writeByte(flags); writer.write(BYTE, flags);
} }
/** /**
@ -72,7 +73,8 @@ public record ClientUpdateStructureBlockPacket(Point location, Action action,
case CLOCKWISE -> 1; case CLOCKWISE -> 1;
case FLIPPED -> 2; case FLIPPED -> 2;
case COUNTER_CLOCKWISE -> 3; case COUNTER_CLOCKWISE -> 3;
default -> throw new IllegalArgumentException("ClientUpdateStructurePacket#rotation must be a valid 90-degree rotation."); default ->
throw new IllegalArgumentException("ClientUpdateStructurePacket#rotation must be a valid 90-degree rotation.");
}; };
} }
@ -82,7 +84,8 @@ public record ClientUpdateStructureBlockPacket(Point location, Action action,
case 1 -> Rotation.CLOCKWISE; case 1 -> Rotation.CLOCKWISE;
case 2 -> Rotation.FLIPPED; case 2 -> Rotation.FLIPPED;
case 3 -> Rotation.COUNTER_CLOCKWISE; case 3 -> Rotation.COUNTER_CLOCKWISE;
default -> throw new IllegalArgumentException("ClientUpdateStructurePacket#rotation must be a valid 90-degree rotation."); default ->
throw new IllegalArgumentException("ClientUpdateStructurePacket#rotation must be a valid 90-degree rotation.");
}; };
} }
} }

View File

@ -1,19 +1,20 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.entity.Player; import net.minestom.server.entity.Player;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record ClientUseItemPacket(@NotNull Player.Hand hand, int sequence) implements ClientPacket { public record ClientUseItemPacket(@NotNull Player.Hand hand, int sequence) implements ClientPacket {
public ClientUseItemPacket(BinaryReader reader) { public ClientUseItemPacket(@NotNull NetworkBuffer reader) {
this(Player.Hand.values()[reader.readVarInt()], reader.readVarInt()); this(reader.readEnum(Player.Hand.class), reader.read(VAR_INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(hand.ordinal()); writer.writeEnum(Player.Hand.class, hand);
writer.writeVarInt(sequence); writer.write(VAR_INT, sequence);
} }
} }

View File

@ -1,23 +1,25 @@
package net.minestom.server.network.packet.client.play; package net.minestom.server.network.packet.client.play;
import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Pos;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.DOUBLE;
import static net.minestom.server.network.NetworkBuffer.FLOAT;
public record ClientVehicleMovePacket(@NotNull Pos position) implements ClientPacket { public record ClientVehicleMovePacket(@NotNull Pos position) implements ClientPacket {
public ClientVehicleMovePacket(BinaryReader reader) { public ClientVehicleMovePacket(@NotNull NetworkBuffer reader) {
this(new Pos(reader.readDouble(), reader.readDouble(), reader.readDouble(), this(new Pos(reader.read(DOUBLE), reader.read(DOUBLE), reader.read(DOUBLE),
reader.readFloat(), reader.readFloat())); reader.read(FLOAT), reader.read(FLOAT)));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeDouble(position.x()); writer.write(DOUBLE, position.x());
writer.writeDouble(position.y()); writer.write(DOUBLE, position.y());
writer.writeDouble(position.z()); writer.write(DOUBLE, position.z());
writer.writeFloat(position.yaw()); writer.write(FLOAT, position.yaw());
writer.writeFloat(position.pitch()); writer.write(FLOAT, position.pitch());
} }
} }

View File

@ -1,14 +1,15 @@
package net.minestom.server.network.packet.client.status; package net.minestom.server.network.packet.client.status;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPreplayPacket; import net.minestom.server.network.packet.client.ClientPreplayPacket;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BYTE;
public record LegacyServerListPingPacket(byte payload) implements ClientPreplayPacket { public record LegacyServerListPingPacket(byte payload) implements ClientPreplayPacket {
public LegacyServerListPingPacket(BinaryReader reader) { public LegacyServerListPingPacket(@NotNull NetworkBuffer reader) {
this(reader.readByte()); this(reader.read(BYTE));
} }
@Override @Override
@ -17,7 +18,7 @@ public record LegacyServerListPingPacket(byte payload) implements ClientPreplayP
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeByte(payload); writer.write(BYTE, payload);
} }
} }

View File

@ -3,16 +3,17 @@ package net.minestom.server.network.packet.client.status;
import net.minestom.server.MinecraftServer; import net.minestom.server.MinecraftServer;
import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.EventDispatcher;
import net.minestom.server.event.server.ClientPingServerEvent; import net.minestom.server.event.server.ClientPingServerEvent;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPreplayPacket; import net.minestom.server.network.packet.client.ClientPreplayPacket;
import net.minestom.server.network.packet.server.status.PongPacket; import net.minestom.server.network.packet.server.status.PongPacket;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.LONG;
public record PingPacket(long number) implements ClientPreplayPacket { public record PingPacket(long number) implements ClientPreplayPacket {
public PingPacket(BinaryReader reader) { public PingPacket(@NotNull NetworkBuffer reader) {
this(reader.readLong()); this(reader.read(LONG));
} }
@Override @Override
@ -36,7 +37,7 @@ public record PingPacket(long number) implements ClientPreplayPacket {
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeLong(number); writer.write(LONG, number);
} }
} }

View File

@ -2,16 +2,15 @@ package net.minestom.server.network.packet.client.status;
import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.EventDispatcher;
import net.minestom.server.event.server.ServerListPingEvent; import net.minestom.server.event.server.ServerListPingEvent;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.client.ClientPreplayPacket; import net.minestom.server.network.packet.client.ClientPreplayPacket;
import net.minestom.server.network.packet.server.handshake.ResponsePacket; import net.minestom.server.network.packet.server.handshake.ResponsePacket;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.ping.ServerListPingType; import net.minestom.server.ping.ServerListPingType;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public record StatusRequestPacket() implements ClientPreplayPacket { public record StatusRequestPacket() implements ClientPreplayPacket {
public StatusRequestPacket(BinaryReader reader) { public StatusRequestPacket(@NotNull NetworkBuffer reader) {
this(); this();
} }
@ -24,7 +23,7 @@ public record StatusRequestPacket() implements ClientPreplayPacket {
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
// Empty // Empty
} }
} }

View File

@ -1,14 +1,14 @@
package net.minestom.server.network.packet.server; package net.minestom.server.network.packet.server;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.utils.binary.Writeable;
/** /**
* Represents a packet which can be sent to a player using {@link PlayerConnection#sendPacket(SendablePacket)}. * Represents a packet which can be sent to a player using {@link PlayerConnection#sendPacket(SendablePacket)}.
* <p> * <p>
* Packets are value-based, and should therefore not be reliant on identity. * Packets are value-based, and should therefore not be reliant on identity.
*/ */
public non-sealed interface ServerPacket extends Writeable, SendablePacket { public non-sealed interface ServerPacket extends NetworkBuffer.Writer, SendablePacket {
/** /**
* Gets the id of this packet. * Gets the id of this packet.

View File

@ -1,18 +1,19 @@
package net.minestom.server.network.packet.server.handshake; package net.minestom.server.network.packet.server.handshake;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.STRING;
public record ResponsePacket(@NotNull String jsonResponse) implements ServerPacket { public record ResponsePacket(@NotNull String jsonResponse) implements ServerPacket {
public ResponsePacket(BinaryReader reader) { public ResponsePacket(@NotNull NetworkBuffer reader) {
this(reader.readSizedString()); this(reader.read(STRING));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeSizedString(jsonResponse); writer.write(STRING, jsonResponse);
} }
@Override @Override

View File

@ -1,25 +1,27 @@
package net.minestom.server.network.packet.server.login; package net.minestom.server.network.packet.server.login;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BYTE_ARRAY;
import static net.minestom.server.network.NetworkBuffer.STRING;
public record EncryptionRequestPacket(@NotNull String serverId, public record EncryptionRequestPacket(@NotNull String serverId,
byte @NotNull [] publicKey, byte @NotNull [] publicKey,
byte @NotNull [] verifyToken) implements ServerPacket { byte @NotNull [] verifyToken) implements ServerPacket {
public EncryptionRequestPacket(BinaryReader reader) { public EncryptionRequestPacket(@NotNull NetworkBuffer reader) {
this(reader.readSizedString(), this(reader.read(STRING),
reader.readByteArray(), reader.read(BYTE_ARRAY),
reader.readByteArray()); reader.read(BYTE_ARRAY));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeSizedString(serverId); writer.write(STRING, serverId);
writer.writeByteArray(publicKey); writer.write(BYTE_ARRAY, publicKey);
writer.writeByteArray(verifyToken); writer.write(BYTE_ARRAY, verifyToken);
} }
@Override @Override

View File

@ -1,24 +1,25 @@
package net.minestom.server.network.packet.server.login; package net.minestom.server.network.packet.server.login;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ComponentHoldingServerPacket; import net.minestom.server.network.packet.server.ComponentHoldingServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.function.UnaryOperator; import java.util.function.UnaryOperator;
import static net.minestom.server.network.NetworkBuffer.COMPONENT;
public record LoginDisconnectPacket(@NotNull Component kickMessage) implements ComponentHoldingServerPacket { public record LoginDisconnectPacket(@NotNull Component kickMessage) implements ComponentHoldingServerPacket {
public LoginDisconnectPacket(BinaryReader reader) { public LoginDisconnectPacket(@NotNull NetworkBuffer reader) {
this(reader.readComponent()); this(reader.read(COMPONENT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeComponent(kickMessage); writer.write(COMPONENT, kickMessage);
} }
@Override @Override

View File

@ -1,25 +1,26 @@
package net.minestom.server.network.packet.server.login; package net.minestom.server.network.packet.server.login;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import static net.minestom.server.network.NetworkBuffer.*;
public record LoginPluginRequestPacket(int messageId, @NotNull String channel, public record LoginPluginRequestPacket(int messageId, @NotNull String channel,
byte @Nullable [] data) implements ServerPacket { byte @Nullable [] data) implements ServerPacket {
public LoginPluginRequestPacket(BinaryReader reader) { public LoginPluginRequestPacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt(), reader.readSizedString(), this(reader.read(VAR_INT), reader.read(STRING),
reader.readRemainingBytes()); reader.read(RAW_BYTES));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(messageId); writer.write(VAR_INT, messageId);
writer.writeSizedString(channel); writer.write(STRING, channel);
if (data != null && data.length > 0) { if (data != null && data.length > 0) {
writer.writeBytes(data); writer.write(RAW_BYTES, data);
} }
} }

View File

@ -1,23 +1,25 @@
package net.minestom.server.network.packet.server.login; package net.minestom.server.network.packet.server.login;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.UUID; import java.util.UUID;
import static net.minestom.server.network.NetworkBuffer.STRING;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record LoginSuccessPacket(@NotNull UUID uuid, @NotNull String username, int properties) implements ServerPacket { public record LoginSuccessPacket(@NotNull UUID uuid, @NotNull String username, int properties) implements ServerPacket {
public LoginSuccessPacket(BinaryReader reader) { public LoginSuccessPacket(@NotNull NetworkBuffer reader) {
this(reader.readUuid(), reader.readSizedString(), reader.readVarInt()); this(reader.read(NetworkBuffer.UUID), reader.read(STRING), reader.read(VAR_INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeUuid(uuid); writer.write(NetworkBuffer.UUID, uuid);
writer.writeSizedString(username); writer.write(STRING, username);
writer.writeVarInt(properties); writer.write(VAR_INT, properties);
} }
@Override @Override

View File

@ -1,19 +1,20 @@
package net.minestom.server.network.packet.server.login; package net.minestom.server.network.packet.server.login;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record SetCompressionPacket(int threshold) implements ServerPacket { public record SetCompressionPacket(int threshold) implements ServerPacket {
public SetCompressionPacket(BinaryReader reader) { public SetCompressionPacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt()); this(reader.read(VAR_INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(threshold); writer.write(VAR_INT, threshold);
} }
@Override @Override

View File

@ -1,19 +1,20 @@
package net.minestom.server.network.packet.server.play; package net.minestom.server.network.packet.server.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record AcknowledgeBlockChangePacket(int sequence) implements ServerPacket { public record AcknowledgeBlockChangePacket(int sequence) implements ServerPacket {
public AcknowledgeBlockChangePacket(BinaryReader reader) { public AcknowledgeBlockChangePacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt()); this(reader.read(VAR_INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(sequence); writer.write(VAR_INT, sequence);
} }
@Override @Override

View File

@ -1,25 +1,26 @@
package net.minestom.server.network.packet.server.play; package net.minestom.server.network.packet.server.play;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ComponentHoldingServerPacket; import net.minestom.server.network.packet.server.ComponentHoldingServerPacket;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.function.UnaryOperator; import java.util.function.UnaryOperator;
import static net.minestom.server.network.NetworkBuffer.COMPONENT;
public record ActionBarPacket(@NotNull Component text) implements ComponentHoldingServerPacket { public record ActionBarPacket(@NotNull Component text) implements ComponentHoldingServerPacket {
public ActionBarPacket(BinaryReader reader) { public ActionBarPacket(@NotNull NetworkBuffer reader) {
this(reader.readComponent()); this(reader.read(COMPONENT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeComponent(text); writer.write(COMPONENT, text);
} }
@Override @Override

View File

@ -4,18 +4,21 @@ import net.kyori.adventure.text.Component;
import net.minestom.server.advancements.FrameType; import net.minestom.server.advancements.FrameType;
import net.minestom.server.adventure.ComponentHolder; import net.minestom.server.adventure.ComponentHolder;
import net.minestom.server.item.ItemStack; import net.minestom.server.item.ItemStack;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ComponentHoldingServerPacket; import net.minestom.server.network.packet.server.ComponentHoldingServerPacket;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.binary.Writeable;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.*; import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.UnaryOperator; import java.util.function.UnaryOperator;
import static net.minestom.server.network.NetworkBuffer.*;
public record AdvancementsPacket(boolean reset, @NotNull List<AdvancementMapping> advancementMappings, public record AdvancementsPacket(boolean reset, @NotNull List<AdvancementMapping> advancementMappings,
@NotNull List<String> identifiersToRemove, @NotNull List<String> identifiersToRemove,
@NotNull List<ProgressMapping> progressMappings) implements ComponentHoldingServerPacket { @NotNull List<ProgressMapping> progressMappings) implements ComponentHoldingServerPacket {
@ -25,18 +28,18 @@ public record AdvancementsPacket(boolean reset, @NotNull List<AdvancementMapping
progressMappings = List.copyOf(progressMappings); progressMappings = List.copyOf(progressMappings);
} }
public AdvancementsPacket(BinaryReader reader) { public AdvancementsPacket(@NotNull NetworkBuffer reader) {
this(reader.readBoolean(), reader.readVarIntList(AdvancementMapping::new), this(reader.read(BOOLEAN), reader.readCollection(AdvancementMapping::new),
reader.readVarIntList(BinaryReader::readSizedString), reader.readCollection(STRING),
reader.readVarIntList(ProgressMapping::new)); reader.readCollection(ProgressMapping::new));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBoolean(reset); writer.write(BOOLEAN, reset);
writer.writeVarIntList(advancementMappings, BinaryWriter::write); writer.writeCollection(advancementMappings);
writer.writeVarIntList(identifiersToRemove, BinaryWriter::writeSizedString); writer.writeCollection(STRING, identifiersToRemove);
writer.writeVarIntList(progressMappings, BinaryWriter::write); writer.writeCollection(progressMappings);
} }
@Override @Override
@ -72,14 +75,15 @@ public record AdvancementsPacket(boolean reset, @NotNull List<AdvancementMapping
/** /**
* AdvancementMapping maps the namespaced ID to the Advancement. * AdvancementMapping maps the namespaced ID to the Advancement.
*/ */
public record AdvancementMapping(@NotNull String key, @NotNull Advancement value) implements Writeable, ComponentHolder<AdvancementMapping> { public record AdvancementMapping(@NotNull String key,
public AdvancementMapping(BinaryReader reader) { @NotNull Advancement value) implements NetworkBuffer.Writer, ComponentHolder<AdvancementMapping> {
this(reader.readSizedString(), new Advancement(reader)); public AdvancementMapping(@NotNull NetworkBuffer reader) {
this(reader.read(STRING), new Advancement(reader));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeSizedString(key); writer.write(STRING, key);
writer.write(value); writer.write(value);
} }
@ -96,27 +100,25 @@ public record AdvancementsPacket(boolean reset, @NotNull List<AdvancementMapping
public record Advancement(@Nullable String parentIdentifier, @Nullable DisplayData displayData, public record Advancement(@Nullable String parentIdentifier, @Nullable DisplayData displayData,
@NotNull List<String> criteria, @NotNull List<String> criteria,
@NotNull List<Requirement> requirements) implements Writeable, ComponentHolder<Advancement> { @NotNull List<Requirement> requirements) implements NetworkBuffer.Writer, ComponentHolder<Advancement> {
public Advancement { public Advancement {
criteria = List.copyOf(criteria); criteria = List.copyOf(criteria);
requirements = List.copyOf(requirements); requirements = List.copyOf(requirements);
} }
public Advancement(BinaryReader reader) { public Advancement(@NotNull NetworkBuffer reader) {
this(reader.readBoolean() ? reader.readSizedString() : null, this(reader.read(BOOLEAN) ? reader.read(STRING) : null,
reader.readBoolean() ? new DisplayData(reader) : null, reader.read(BOOLEAN) ? new DisplayData(reader) : null,
reader.readVarIntList(BinaryReader::readSizedString), reader.readCollection(STRING),
reader.readVarIntList(Requirement::new)); reader.readCollection(Requirement::new));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBoolean(parentIdentifier != null); writer.writeOptional(STRING, parentIdentifier);
if (parentIdentifier != null) writer.writeSizedString(parentIdentifier); writer.writeOptional(displayData);
writer.writeBoolean(displayData != null); writer.writeCollection(STRING, criteria);
if (displayData != null) writer.write(displayData); writer.writeCollection(requirements);
writer.writeVarIntList(criteria, BinaryWriter::writeSizedString);
writer.writeVarIntList(requirements, BinaryWriter::write);
} }
@Override @Override
@ -130,26 +132,26 @@ public record AdvancementsPacket(boolean reset, @NotNull List<AdvancementMapping
} }
} }
public record Requirement(@NotNull List<String> requirements) implements Writeable { public record Requirement(@NotNull List<String> requirements) implements NetworkBuffer.Writer {
public Requirement { public Requirement {
requirements = List.copyOf(requirements); requirements = List.copyOf(requirements);
} }
public Requirement(BinaryReader reader) { public Requirement(@NotNull NetworkBuffer reader) {
this(reader.readVarIntList(BinaryReader::readSizedString)); this(reader.readCollection(STRING));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarIntList(requirements, BinaryWriter::writeSizedString); writer.writeCollection(STRING, requirements);
} }
} }
public record DisplayData(@NotNull Component title, @NotNull Component description, public record DisplayData(@NotNull Component title, @NotNull Component description,
@NotNull ItemStack icon, @NotNull FrameType frameType, @NotNull ItemStack icon, @NotNull FrameType frameType,
int flags, @Nullable String backgroundTexture, int flags, @Nullable String backgroundTexture,
float x, float y) implements Writeable, ComponentHolder<DisplayData> { float x, float y) implements NetworkBuffer.Writer, ComponentHolder<DisplayData> {
public DisplayData(BinaryReader reader) { public DisplayData(@NotNull NetworkBuffer reader) {
this(read(reader)); this(read(reader));
} }
@ -160,15 +162,15 @@ public record AdvancementsPacket(boolean reset, @NotNull List<AdvancementMapping
displayData.x, displayData.y); displayData.x, displayData.y);
} }
private static DisplayData read(BinaryReader reader) { private static DisplayData read(@NotNull NetworkBuffer reader) {
var title = reader.readComponent(); var title = reader.read(COMPONENT);
var description = reader.readComponent(); var description = reader.read(COMPONENT);
var icon = reader.readItemStack(); var icon = reader.read(ITEM);
var frameType = FrameType.values()[reader.readVarInt()]; var frameType = FrameType.values()[reader.read(VAR_INT)];
var flags = reader.readInt(); var flags = reader.read(INT);
var backgroundTexture = (flags & 0x1) != 0 ? reader.readSizedString() : null; var backgroundTexture = (flags & 0x1) != 0 ? reader.read(STRING) : null;
var x = reader.readFloat(); var x = reader.read(FLOAT);
var y = reader.readFloat(); var y = reader.read(FLOAT);
return new DisplayData(title, description, return new DisplayData(title, description,
icon, frameType, icon, frameType,
flags, backgroundTexture, flags, backgroundTexture,
@ -176,18 +178,18 @@ public record AdvancementsPacket(boolean reset, @NotNull List<AdvancementMapping
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeComponent(title); writer.write(COMPONENT, title);
writer.writeComponent(description); writer.write(COMPONENT, description);
writer.writeItemStack(icon); writer.write(ITEM, icon);
writer.writeVarInt(frameType.ordinal()); writer.write(VAR_INT, frameType.ordinal());
writer.writeInt(flags); writer.write(INT, flags);
if ((flags & 0x1) != 0) { if ((flags & 0x1) != 0) {
assert backgroundTexture != null; assert backgroundTexture != null;
writer.writeSizedString(backgroundTexture); writer.write(STRING, backgroundTexture);
} }
writer.writeFloat(x); writer.write(FLOAT, x);
writer.writeFloat(y); writer.write(FLOAT, y);
} }
@Override @Override
@ -201,55 +203,55 @@ public record AdvancementsPacket(boolean reset, @NotNull List<AdvancementMapping
} }
} }
public record ProgressMapping(@NotNull String key, @NotNull AdvancementProgress progress) implements Writeable { public record ProgressMapping(@NotNull String key,
public ProgressMapping(BinaryReader reader) { @NotNull AdvancementProgress progress) implements NetworkBuffer.Writer {
this(reader.readSizedString(), new AdvancementProgress(reader)); public ProgressMapping(@NotNull NetworkBuffer reader) {
this(reader.read(STRING), new AdvancementProgress(reader));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeSizedString(key); writer.write(STRING, key);
writer.write(progress); writer.write(progress);
} }
} }
public record AdvancementProgress(@NotNull List<Criteria> criteria) implements Writeable { public record AdvancementProgress(@NotNull List<Criteria> criteria) implements NetworkBuffer.Writer {
public AdvancementProgress { public AdvancementProgress {
criteria = List.copyOf(criteria); criteria = List.copyOf(criteria);
} }
public AdvancementProgress(BinaryReader reader) { public AdvancementProgress(@NotNull NetworkBuffer reader) {
this(reader.readVarIntList(Criteria::new)); this(reader.readCollection(Criteria::new));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarIntList(criteria, BinaryWriter::write); writer.writeCollection(criteria);
} }
} }
public record Criteria(@NotNull String criterionIdentifier, public record Criteria(@NotNull String criterionIdentifier,
@NotNull CriterionProgress criterionProgress) implements Writeable { @NotNull CriterionProgress criterionProgress) implements NetworkBuffer.Writer {
public Criteria(BinaryReader reader) { public Criteria(@NotNull NetworkBuffer reader) {
this(reader.readSizedString(), new CriterionProgress(reader)); this(reader.read(STRING), new CriterionProgress(reader));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeSizedString(criterionIdentifier); writer.write(STRING, criterionIdentifier);
writer.write(criterionProgress); writer.write(criterionProgress);
} }
} }
public record CriterionProgress(@Nullable Long dateOfAchieving) implements Writeable { public record CriterionProgress(@Nullable Long dateOfAchieving) implements NetworkBuffer.Writer {
public CriterionProgress(BinaryReader reader) { public CriterionProgress(@NotNull NetworkBuffer reader) {
this(reader.readBoolean() ? reader.readLong() : null); this(reader.readOptional(LONG));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBoolean(dateOfAchieving != null); writer.writeOptional(LONG, dateOfAchieving);
if (dateOfAchieving != null) writer.writeLong(dateOfAchieving);
} }
} }
} }

View File

@ -1,26 +1,27 @@
package net.minestom.server.network.packet.server.play; package net.minestom.server.network.packet.server.play;
import net.minestom.server.entity.Entity; import net.minestom.server.entity.Entity;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import static net.minestom.server.network.NetworkBuffer.INT;
public record AttachEntityPacket(int attachedEntityId, int holdingEntityId) implements ServerPacket { public record AttachEntityPacket(int attachedEntityId, int holdingEntityId) implements ServerPacket {
public AttachEntityPacket(@NotNull Entity attachedEntity, @Nullable Entity holdingEntity) { public AttachEntityPacket(@NotNull Entity attachedEntity, @Nullable Entity holdingEntity) {
this(attachedEntity.getEntityId(), holdingEntity != null ? holdingEntity.getEntityId() : -1); this(attachedEntity.getEntityId(), holdingEntity != null ? holdingEntity.getEntityId() : -1);
} }
public AttachEntityPacket(BinaryReader reader) { public AttachEntityPacket(@NotNull NetworkBuffer reader) {
this(reader.readInt(), reader.readInt()); this(reader.read(INT), reader.read(INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeInt(attachedEntityId); writer.write(INT, attachedEntityId);
writer.writeInt(holdingEntityId); writer.write(INT, holdingEntityId);
} }
@Override @Override

View File

@ -2,29 +2,30 @@ package net.minestom.server.network.packet.server.play;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.Block;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.*;
public record BlockActionPacket(@NotNull Point blockPosition, byte actionId, public record BlockActionPacket(@NotNull Point blockPosition, byte actionId,
byte actionParam, int blockId) implements ServerPacket { byte actionParam, int blockId) implements ServerPacket {
public BlockActionPacket(Point blockPosition, byte actionId, byte actionParam, Block block) { public BlockActionPacket(Point blockPosition, byte actionId, byte actionParam, Block block) {
this(blockPosition, actionId, actionParam, block.id()); this(blockPosition, actionId, actionParam, block.id());
} }
public BlockActionPacket(BinaryReader reader) { public BlockActionPacket(@NotNull NetworkBuffer reader) {
this(reader.readBlockPosition(), reader.readByte(), this(reader.read(BLOCK_POSITION), reader.read(BYTE),
reader.readByte(), reader.readVarInt()); reader.read(BYTE), reader.read(VAR_INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBlockPosition(blockPosition); writer.write(BLOCK_POSITION, blockPosition);
writer.writeByte(actionId); writer.write(BYTE, actionId);
writer.writeByte(actionParam); writer.write(BYTE, actionParam);
writer.writeVarInt(blockId); writer.write(VAR_INT, blockId);
} }
@Override @Override

View File

@ -1,23 +1,24 @@
package net.minestom.server.network.packet.server.play; package net.minestom.server.network.packet.server.play;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.*;
public record BlockBreakAnimationPacket(int entityId, @NotNull Point blockPosition, public record BlockBreakAnimationPacket(int entityId, @NotNull Point blockPosition,
byte destroyStage) implements ServerPacket { byte destroyStage) implements ServerPacket {
public BlockBreakAnimationPacket(BinaryReader reader) { public BlockBreakAnimationPacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt(), reader.readBlockPosition(), reader.readByte()); this(reader.read(VAR_INT), reader.read(BLOCK_POSITION), reader.read(BYTE));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(entityId); writer.write(VAR_INT, entityId);
writer.writeBlockPosition(blockPosition); writer.write(BLOCK_POSITION, blockPosition);
writer.writeByte(destroyStage); writer.write(BYTE, destroyStage);
} }
@Override @Override

View File

@ -2,25 +2,27 @@ package net.minestom.server.network.packet.server.play;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.Block;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BLOCK_POSITION;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record BlockChangePacket(@NotNull Point blockPosition, int blockStateId) implements ServerPacket { public record BlockChangePacket(@NotNull Point blockPosition, int blockStateId) implements ServerPacket {
public BlockChangePacket(@NotNull Point blockPosition, @NotNull Block block) { public BlockChangePacket(@NotNull Point blockPosition, @NotNull Block block) {
this(blockPosition, block.stateId()); this(blockPosition, block.stateId());
} }
public BlockChangePacket(BinaryReader reader) { public BlockChangePacket(@NotNull NetworkBuffer reader) {
this(reader.readBlockPosition(), reader.readVarInt()); this(reader.read(BLOCK_POSITION), reader.read(VAR_INT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBlockPosition(blockPosition); writer.write(BLOCK_POSITION, blockPosition);
writer.writeVarInt(blockStateId); writer.write(VAR_INT, blockStateId);
} }
@Override @Override

View File

@ -1,29 +1,30 @@
package net.minestom.server.network.packet.server.play; package net.minestom.server.network.packet.server.play;
import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Point;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jglrxavpok.hephaistos.nbt.NBTCompound; import org.jglrxavpok.hephaistos.nbt.NBTCompound;
import static net.minestom.server.network.NetworkBuffer.*;
public record BlockEntityDataPacket(@NotNull Point blockPosition, int action, public record BlockEntityDataPacket(@NotNull Point blockPosition, int action,
@Nullable NBTCompound data) implements ServerPacket { @Nullable NBTCompound data) implements ServerPacket {
public BlockEntityDataPacket(BinaryReader reader) { public BlockEntityDataPacket(@NotNull NetworkBuffer reader) {
this(reader.readBlockPosition(), reader.readVarInt(), (NBTCompound) reader.readTag()); this(reader.read(BLOCK_POSITION), reader.read(VAR_INT), (NBTCompound) reader.read(NBT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBlockPosition(blockPosition); writer.write(BLOCK_POSITION, blockPosition);
writer.writeVarInt(action); writer.write(VAR_INT, action);
if (data != null) { if (data != null) {
writer.writeNBT("", data); writer.write(NBT, data);
} else { } else {
// TAG_End // TAG_End
writer.writeByte((byte) 0x00); writer.write(BYTE, (byte) 0x00);
} }
} }

View File

@ -4,12 +4,10 @@ import net.kyori.adventure.bossbar.BossBar;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.adventure.AdventurePacketConvertor;
import net.minestom.server.adventure.ComponentHolder; import net.minestom.server.adventure.ComponentHolder;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ComponentHoldingServerPacket; import net.minestom.server.network.packet.server.ComponentHoldingServerPacket;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.binary.Writeable;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Collection; import java.util.Collection;
@ -17,9 +15,11 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.function.UnaryOperator; import java.util.function.UnaryOperator;
import static net.minestom.server.network.NetworkBuffer.*;
public record BossBarPacket(@NotNull UUID uuid, @NotNull Action action) implements ComponentHoldingServerPacket { public record BossBarPacket(@NotNull UUID uuid, @NotNull Action action) implements ComponentHoldingServerPacket {
public BossBarPacket(BinaryReader reader) { public BossBarPacket(@NotNull NetworkBuffer reader) {
this(reader.readUuid(), switch (reader.readVarInt()) { this(reader.read(NetworkBuffer.UUID), switch (reader.read(VAR_INT)) {
case 0 -> new AddAction(reader); case 0 -> new AddAction(reader);
case 1 -> new RemoveAction(); case 1 -> new RemoveAction();
case 2 -> new UpdateHealthAction(reader); case 2 -> new UpdateHealthAction(reader);
@ -31,9 +31,9 @@ public record BossBarPacket(@NotNull UUID uuid, @NotNull Action action) implemen
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeUuid(uuid); writer.write(NetworkBuffer.UUID, uuid);
writer.writeVarInt(action.id()); writer.write(VAR_INT, action.id());
writer.write(action); writer.write(action);
} }
@ -51,31 +51,32 @@ public record BossBarPacket(@NotNull UUID uuid, @NotNull Action action) implemen
: this; : this;
} }
public sealed interface Action extends Writeable public sealed interface Action extends NetworkBuffer.Writer
permits AddAction, RemoveAction, UpdateHealthAction, UpdateTitleAction, UpdateStyleAction, UpdateFlagsAction { permits AddAction, RemoveAction, UpdateHealthAction, UpdateTitleAction, UpdateStyleAction, UpdateFlagsAction {
int id(); int id();
} }
public record AddAction(@NotNull Component title, float health, @NotNull BossBar.Color color, public record AddAction(@NotNull Component title, float health, @NotNull BossBar.Color color,
@NotNull BossBar.Overlay overlay, byte flags) implements Action, ComponentHolder<AddAction> { @NotNull BossBar.Overlay overlay,
byte flags) implements Action, ComponentHolder<AddAction> {
public AddAction(@NotNull BossBar bar) { public AddAction(@NotNull BossBar bar) {
this(bar.name(), bar.progress(), bar.color(), bar.overlay(), this(bar.name(), bar.progress(), bar.color(), bar.overlay(),
AdventurePacketConvertor.getBossBarFlagValue(bar.flags())); AdventurePacketConvertor.getBossBarFlagValue(bar.flags()));
} }
public AddAction(BinaryReader reader) { public AddAction(@NotNull NetworkBuffer reader) {
this(reader.readComponent(), reader.readFloat(), this(reader.read(COMPONENT), reader.read(FLOAT),
BossBar.Color.values()[reader.readVarInt()], BossBar.Color.values()[reader.read(VAR_INT)],
BossBar.Overlay.values()[reader.readVarInt()], reader.readByte()); BossBar.Overlay.values()[reader.read(VAR_INT)], reader.read(BYTE));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeComponent(title); writer.write(COMPONENT, title);
writer.writeFloat(health); writer.write(FLOAT, health);
writer.writeVarInt(AdventurePacketConvertor.getBossBarColorValue(color)); writer.write(VAR_INT, AdventurePacketConvertor.getBossBarColorValue(color));
writer.writeVarInt(AdventurePacketConvertor.getBossBarOverlayValue(overlay)); writer.write(VAR_INT, AdventurePacketConvertor.getBossBarOverlayValue(overlay));
writer.writeByte(flags); writer.write(BYTE, flags);
} }
@Override @Override
@ -96,7 +97,7 @@ public record BossBarPacket(@NotNull UUID uuid, @NotNull Action action) implemen
public record RemoveAction() implements Action { public record RemoveAction() implements Action {
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
} }
@Override @Override
@ -110,13 +111,13 @@ public record BossBarPacket(@NotNull UUID uuid, @NotNull Action action) implemen
this(bar.progress()); this(bar.progress());
} }
public UpdateHealthAction(BinaryReader reader) { public UpdateHealthAction(@NotNull NetworkBuffer reader) {
this(reader.readFloat()); this(reader.read(FLOAT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeFloat(health); writer.write(FLOAT, health);
} }
@Override @Override
@ -130,13 +131,13 @@ public record BossBarPacket(@NotNull UUID uuid, @NotNull Action action) implemen
this(bar.name()); this(bar.name());
} }
public UpdateTitleAction(BinaryReader reader) { public UpdateTitleAction(@NotNull NetworkBuffer reader) {
this(reader.readComponent()); this(reader.read(COMPONENT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeComponent(title); writer.write(COMPONENT, title);
} }
@Override @Override
@ -161,14 +162,14 @@ public record BossBarPacket(@NotNull UUID uuid, @NotNull Action action) implemen
this(bar.color(), bar.overlay()); this(bar.color(), bar.overlay());
} }
public UpdateStyleAction(BinaryReader reader) { public UpdateStyleAction(@NotNull NetworkBuffer reader) {
this(BossBar.Color.values()[reader.readVarInt()], BossBar.Overlay.values()[reader.readVarInt()]); this(BossBar.Color.values()[reader.read(VAR_INT)], BossBar.Overlay.values()[reader.read(VAR_INT)]);
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(AdventurePacketConvertor.getBossBarColorValue(color)); writer.write(VAR_INT, AdventurePacketConvertor.getBossBarColorValue(color));
writer.writeVarInt(AdventurePacketConvertor.getBossBarOverlayValue(overlay)); writer.write(VAR_INT, AdventurePacketConvertor.getBossBarOverlayValue(overlay));
} }
@Override @Override
@ -182,13 +183,13 @@ public record BossBarPacket(@NotNull UUID uuid, @NotNull Action action) implemen
this(AdventurePacketConvertor.getBossBarFlagValue(bar.flags())); this(AdventurePacketConvertor.getBossBarFlagValue(bar.flags()));
} }
public UpdateFlagsAction(BinaryReader reader) { public UpdateFlagsAction(@NotNull NetworkBuffer reader) {
this(reader.readByte()); this(reader.read(BYTE));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeByte(flags); writer.write(BYTE, flags);
} }
@Override @Override

View File

@ -1,15 +1,16 @@
package net.minestom.server.network.packet.server.play; package net.minestom.server.network.packet.server.play;
import net.minestom.server.entity.Entity; import net.minestom.server.entity.Entity;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record CameraPacket(int cameraId) implements ServerPacket { public record CameraPacket(int cameraId) implements ServerPacket {
public CameraPacket(BinaryReader reader) { public CameraPacket(@NotNull NetworkBuffer reader) {
this(reader.readVarInt()); this(reader.read(VAR_INT));
} }
public CameraPacket(@NotNull Entity camera) { public CameraPacket(@NotNull Entity camera) {
@ -17,8 +18,8 @@ public record CameraPacket(int cameraId) implements ServerPacket {
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeVarInt(cameraId); writer.write(VAR_INT, cameraId);
} }
@Override @Override

View File

@ -1,20 +1,22 @@
package net.minestom.server.network.packet.server.play; package net.minestom.server.network.packet.server.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BYTE;
import static net.minestom.server.network.NetworkBuffer.FLOAT;
public record ChangeGameStatePacket(@NotNull Reason reason, float value) implements ServerPacket { public record ChangeGameStatePacket(@NotNull Reason reason, float value) implements ServerPacket {
public ChangeGameStatePacket(BinaryReader reader) { public ChangeGameStatePacket(@NotNull NetworkBuffer reader) {
this(Reason.values()[reader.readByte()], reader.readFloat()); this(Reason.values()[reader.read(BYTE)], reader.read(FLOAT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeByte((byte) reason.ordinal()); writer.write(BYTE, (byte) reason.ordinal());
writer.writeFloat(value); writer.write(FLOAT, value);
} }
@Override @Override

View File

@ -1,11 +1,10 @@
package net.minestom.server.network.packet.server.play; package net.minestom.server.network.packet.server.play;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ComponentHoldingServerPacket; import net.minestom.server.network.packet.server.ComponentHoldingServerPacket;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -13,16 +12,17 @@ import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.function.UnaryOperator; import java.util.function.UnaryOperator;
import static net.minestom.server.network.NetworkBuffer.*;
public record ChatPreviewPacket(int queryId, @Nullable Component preview) implements ComponentHoldingServerPacket { public record ChatPreviewPacket(int queryId, @Nullable Component preview) implements ComponentHoldingServerPacket {
public ChatPreviewPacket(BinaryReader reader) { public ChatPreviewPacket(@NotNull NetworkBuffer reader) {
this(reader.readInt(), reader.readBoolean() ? reader.readComponent() : null); this(reader.read(INT), reader.readOptional(COMPONENT));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeInt(queryId); writer.write(INT, queryId);
writer.writeBoolean(preview != null); writer.writeOptional(COMPONENT, preview);
if (preview != null) writer.writeComponent(preview);
} }
@Override @Override

View File

@ -1,26 +1,27 @@
package net.minestom.server.network.packet.server.play; package net.minestom.server.network.packet.server.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.network.packet.server.play.data.ChunkData; import net.minestom.server.network.packet.server.play.data.ChunkData;
import net.minestom.server.network.packet.server.play.data.LightData; import net.minestom.server.network.packet.server.play.data.LightData;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.INT;
public record ChunkDataPacket(int chunkX, int chunkZ, public record ChunkDataPacket(int chunkX, int chunkZ,
@NotNull ChunkData chunkData, @NotNull ChunkData chunkData,
@NotNull LightData lightData) implements ServerPacket { @NotNull LightData lightData) implements ServerPacket {
public ChunkDataPacket(BinaryReader reader) { public ChunkDataPacket(@NotNull NetworkBuffer reader) {
this(reader.readInt(), reader.readInt(), this(reader.read(INT), reader.read(INT),
new ChunkData(reader), new ChunkData(reader),
new LightData(reader)); new LightData(reader));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeInt(chunkX); writer.write(INT, chunkX);
writer.writeInt(chunkZ); writer.write(INT, chunkZ);
writer.write(chunkData); writer.write(chunkData);
writer.write(lightData); writer.write(lightData);
} }

View File

@ -1,19 +1,20 @@
package net.minestom.server.network.packet.server.play; package net.minestom.server.network.packet.server.play;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.minestom.server.network.NetworkBuffer.BOOLEAN;
public record ClearTitlesPacket(boolean reset) implements ServerPacket { public record ClearTitlesPacket(boolean reset) implements ServerPacket {
public ClearTitlesPacket(BinaryReader reader) { public ClearTitlesPacket(@NotNull NetworkBuffer reader) {
this(reader.readBoolean()); this(reader.read(BOOLEAN));
} }
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull NetworkBuffer writer) {
writer.writeBoolean(reset); writer.write(BOOLEAN, reset);
} }
@Override @Override

Some files were not shown because too many files have changed in this diff Show More