Minestom/src/main/java/net/minestom/server/network/packet/server/ServerPacket.java

65 lines
2.4 KiB
Java
Raw Normal View History

2020-04-24 03:25:58 +02:00
package net.minestom.server.network.packet.server;
2024-03-19 17:42:06 +01:00
import net.minestom.server.adventure.ComponentHolder;
import net.minestom.server.network.ConnectionState;
2022-10-29 11:02:22 +02:00
import net.minestom.server.network.NetworkBuffer;
2020-10-15 21:16:31 +02:00
import net.minestom.server.network.player.PlayerConnection;
2024-03-19 17:42:06 +01:00
import net.minestom.server.utils.PacketUtils;
import org.jetbrains.annotations.NotNull;
2024-03-19 17:42:06 +01:00
import java.util.ArrayList;
import java.util.List;
2020-04-24 03:25:58 +02:00
2020-10-15 21:16:31 +02:00
/**
2021-11-17 06:31:24 +01:00
* Represents a packet which can be sent to a player using {@link PlayerConnection#sendPacket(SendablePacket)}.
* <p>
* Packets are value-based, and should therefore not be reliant on identity.
2020-10-15 21:16:31 +02:00
*/
2024-03-19 17:42:06 +01:00
public sealed interface ServerPacket extends NetworkBuffer.Writer, SendablePacket permits
ServerPacket.Configuration, ServerPacket.Status, ServerPacket.Login, ServerPacket.Play {
2020-04-24 03:25:58 +02:00
2020-08-19 20:47:53 +02:00
/**
2020-10-15 21:16:31 +02:00
* Gets the id of this packet.
2020-08-19 20:47:53 +02:00
* <p>
2020-10-15 21:16:31 +02:00
* Written in the final buffer header so it needs to match the client id.
2020-08-19 20:47:53 +02:00
*
* @return the id of this packet
*/
2024-03-19 17:42:06 +01:00
default int getId(@NotNull ConnectionState state) {
final int id = switch (state) {
case HANDSHAKE -> -1;
case CONFIGURATION -> this instanceof Configuration configuration ? configuration.configurationId() : -1;
case STATUS -> this instanceof Status status ? status.statusId() : -1;
case LOGIN -> this instanceof Login login ? login.loginId() : -1;
case PLAY -> this instanceof Play play ? play.playId() : -1;
};
if (id != -1) return id;
// Invalid state, generate error
List<ConnectionState> validStates = new ArrayList<>();
if (this instanceof Configuration) validStates.add(ConnectionState.CONFIGURATION);
if (this instanceof Status) validStates.add(ConnectionState.STATUS);
if (this instanceof Login) validStates.add(ConnectionState.LOGIN);
if (this instanceof Play) validStates.add(ConnectionState.PLAY);
return PacketUtils.invalidPacketState(getClass(), state, validStates.toArray(ConnectionState[]::new));
}
non-sealed interface Configuration extends ServerPacket {
int configurationId();
}
non-sealed interface Status extends ServerPacket {
int statusId();
}
non-sealed interface Login extends ServerPacket {
int loginId();
}
non-sealed interface Play extends ServerPacket {
int playId();
}
2024-03-19 17:42:06 +01:00
interface ComponentHolding extends ComponentHolder<ServerPacket> {
}
2020-04-24 03:25:58 +02:00
}