Cache Event Methods, Polish Last PR

This commit is contained in:
LOOHP 2021-08-19 20:50:45 +08:00
parent a0f592d8fe
commit 7d8208272f
18 changed files with 270 additions and 118 deletions

17
pom.xml
View File

@ -5,7 +5,7 @@
<groupId>com.loohp</groupId> <groupId>com.loohp</groupId>
<artifactId>Limbo</artifactId> <artifactId>Limbo</artifactId>
<name>Limbo</name> <name>Limbo</name>
<version>0.5.3-ALPHA</version> <version>0.6.0-ALPHA</version>
<description>Standalone Limbo Minecraft Server.</description> <description>Standalone Limbo Minecraft Server.</description>
<url>https://github.com/LOOHP/Limbo</url> <url>https://github.com/LOOHP/Limbo</url>
@ -25,6 +25,21 @@
<resource> <resource>
<directory>src/main/resources</directory> <directory>src/main/resources</directory>
<filtering>true</filtering> <filtering>true</filtering>
<excludes>
<exclude>**/*.java</exclude>
<exclude>**/*.ttf</exclude>
<exclude>**/*.jar</exclude>
<exclude>**/*.schem</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>**/*.ttf</include>
<include>**/*.jar</include>
<include>**/*.schem</include>
</includes>
</resource> </resource>
</resources> </resources>
<plugins> <plugins>

View File

@ -5,15 +5,12 @@ import java.awt.image.BufferedImage;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URL; import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.ArrayList; import java.util.ArrayList;
@ -39,13 +36,9 @@ import org.json.simple.parser.ParseException;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.loohp.limbo.events.EventsManager;
import com.loohp.limbo.server.ServerConnection;
import com.loohp.limbo.server.packets.Packet;
import com.loohp.limbo.server.packets.PacketIn;
import com.loohp.limbo.server.packets.PacketOut;
import com.loohp.limbo.commands.CommandSender; import com.loohp.limbo.commands.CommandSender;
import com.loohp.limbo.consolegui.GUI; import com.loohp.limbo.consolegui.GUI;
import com.loohp.limbo.events.EventsManager;
import com.loohp.limbo.file.ServerProperties; import com.loohp.limbo.file.ServerProperties;
import com.loohp.limbo.location.Location; import com.loohp.limbo.location.Location;
import com.loohp.limbo.metrics.Metrics; import com.loohp.limbo.metrics.Metrics;
@ -55,6 +48,10 @@ import com.loohp.limbo.plugins.LimboPlugin;
import com.loohp.limbo.plugins.PluginManager; import com.loohp.limbo.plugins.PluginManager;
import com.loohp.limbo.scheduler.LimboScheduler; import com.loohp.limbo.scheduler.LimboScheduler;
import com.loohp.limbo.scheduler.Tick; import com.loohp.limbo.scheduler.Tick;
import com.loohp.limbo.server.ServerConnection;
import com.loohp.limbo.server.packets.Packet;
import com.loohp.limbo.server.packets.PacketIn;
import com.loohp.limbo.server.packets.PacketOut;
import com.loohp.limbo.utils.CustomStringUtils; import com.loohp.limbo.utils.CustomStringUtils;
import com.loohp.limbo.utils.ImageUtils; import com.loohp.limbo.utils.ImageUtils;
import com.loohp.limbo.utils.NetworkUtils; import com.loohp.limbo.utils.NetworkUtils;
@ -296,11 +293,12 @@ public class Limbo {
File defaultCommandsJar = new File(pluginFolder, "LimboDefaultCmd.jar"); File defaultCommandsJar = new File(pluginFolder, "LimboDefaultCmd.jar");
defaultCommandsJar.delete(); defaultCommandsJar.delete();
console.sendMessage("Downloading limbo default commands module from github..."); console.sendMessage("Loading limbo default commands module...");
ReadableByteChannel rbc = Channels.newChannel(new URL("https://github.com/LOOHP/Limbo/raw/master/modules/LimboDefaultCmd.jar").openStream()); try (InputStream in = Limbo.class.getClassLoader().getResourceAsStream("LimboDefaultCmd.jar")) {
FileOutputStream fos = new FileOutputStream(defaultCommandsJar); Files.copy(in, defaultCommandsJar.toPath());
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (IOException e) {
fos.close(); e.printStackTrace();
}
pluginManager = new PluginManager(pluginFolder); pluginManager = new PluginManager(pluginFolder);
try { try {
@ -372,16 +370,25 @@ public class Limbo {
if (!schem.exists()) { if (!schem.exists()) {
console.sendMessage("Schemetic file " + properties.getSchemFileName() + " for world " + properties.getLevelName() + " not found!"); console.sendMessage("Schemetic file " + properties.getSchemFileName() + " for world " + properties.getLevelName() + " not found!");
console.sendMessage("Creating default world...");
try (InputStream in = Limbo.class.getClassLoader().getResourceAsStream("spawn.schem")) {
Files.copy(in, schem.toPath());
} catch (IOException e) {
e.printStackTrace();
}
}
try {
World world = Schematic.toWorld(properties.getLevelName().getKey(), Environment.fromNamespacedKey(properties.getLevelDimension()), (CompoundTag) NBTUtil.read(schem).getTag());
console.sendMessage("Loaded world " + properties.getLevelName() + "!");
return world;
} catch (Throwable e) {
console.sendMessage("Unable to load world " + properties.getSchemFileName() + "!");
e.printStackTrace();
console.sendMessage("Server will exit!"); console.sendMessage("Server will exit!");
System.exit(1); System.exit(1);
return null; return null;
} }
World world = Schematic.toWorld(properties.getLevelName().getKey(), Environment.fromNamespacedKey(properties.getLevelDimension()), (CompoundTag) NBTUtil.read(schem).getTag());
console.sendMessage("Loaded world " + properties.getLevelName() + "!");
return world;
} }
public void registerWorld(World world) { public void registerWorld(World world) {

View File

@ -10,5 +10,7 @@ import java.lang.annotation.Target;
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface EventHandler { public @interface EventHandler {
EventPriority priority() default EventPriority.NORMAL; EventPriority priority() default EventPriority.NORMAL;
} }

View File

@ -1,6 +1,7 @@
package com.loohp.limbo.events; package com.loohp.limbo.events;
public enum EventPriority { public enum EventPriority {
LOWEST(0), LOWEST(0),
LOW(1), LOW(1),
NORMAL(2), NORMAL(2),
@ -34,4 +35,5 @@ public enum EventPriority {
} }
return array; return array;
} }
} }

View File

@ -3,46 +3,52 @@ package com.loohp.limbo.events;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import com.loohp.limbo.plugins.LimboPlugin; import com.loohp.limbo.plugins.LimboPlugin;
public class EventsManager { public class EventsManager {
private List<ListenerPair> listeners; private List<ListenerPair> listeners;
private Map<Listener, RegisteredCachedListener> cachedListeners;
public EventsManager() { public EventsManager() {
listeners = new ArrayList<>(); listeners = new ArrayList<>();
cachedListeners = new ConcurrentHashMap<>();
} }
public <T extends Event> T callEvent(T event) { public <T extends Event> T callEvent(T event) {
for (EventPriority priority : EventPriority.getPrioritiesInOrder()) { for (EventPriority priority : EventPriority.getPrioritiesInOrder()) {
for (ListenerPair entry : listeners) { for (Entry<Listener, RegisteredCachedListener> entry : cachedListeners.entrySet()) {
Listener listener = entry.listener; for (Method method : entry.getValue().getListeners(event.getClass(), priority)) {
for (Method method : listener.getClass().getMethods()) {
if (method.isAnnotationPresent(EventHandler.class)) {
if (method.getAnnotation(EventHandler.class).priority().equals(priority)) {
if (method.getParameterCount() == 1 && method.getParameterTypes()[0].equals(event.getClass())) {
try { try {
method.invoke(listener, event); method.invoke(entry.getKey(), event);
} catch (Exception e) { } catch (Exception e) {
System.err.println("Error while passing " + event.getClass().getCanonicalName() + " to the plugin \"" + entry.plugin.getName() + "\""); System.err.println("Error while passing " + event.getClass().getCanonicalName() + " to the plugin \"" + entry.getValue().getPlugin().getName() + "\"");
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
} }
}
}
}
return event; return event;
} }
public void registerEvents(LimboPlugin plugin, Listener listener) { public void registerEvents(LimboPlugin plugin, Listener listener) {
listeners.add(new ListenerPair(plugin, listener)); listeners.add(new ListenerPair(plugin, listener));
cachedListeners.put(listener, new RegisteredCachedListener(plugin, listener));
} }
public void unregisterAllListeners(LimboPlugin plugin) { public void unregisterAllListeners(LimboPlugin plugin) {
listeners.removeIf(each -> each.plugin.equals(plugin)); listeners.removeIf(each -> {
if (each.plugin.equals(plugin)) {
cachedListeners.remove(each.listener);
return true;
} else {
return false;
}
});
} }
protected static class ListenerPair { protected static class ListenerPair {

View File

@ -0,0 +1,47 @@
package com.loohp.limbo.events;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.loohp.limbo.plugins.LimboPlugin;
public class RegisteredCachedListener {
private LimboPlugin plugin;
private Map<Class<? extends Event>, Map<EventPriority, List<Method>>> listeners;
@SuppressWarnings("unchecked")
public RegisteredCachedListener(LimboPlugin plugin, Listener listener) {
this.plugin = plugin;
this.listeners = new ConcurrentHashMap<>();
for (Method method : listener.getClass().getMethods()) {
if (method.isAnnotationPresent(EventHandler.class) && method.getParameterCount() == 1 && Event.class.isAssignableFrom(method.getParameterTypes()[0])) {
Class<? extends Event> eventClass = (Class<? extends Event>) method.getParameterTypes()[0];
listeners.putIfAbsent(eventClass, new ConcurrentHashMap<>());
Map<EventPriority, List<Method>> mapping = listeners.get(eventClass);
EventPriority priority = method.getAnnotation(EventHandler.class).priority();
mapping.putIfAbsent(priority, new ArrayList<>());
List<Method> list = mapping.get(priority);
list.add(method);
}
}
}
public LimboPlugin getPlugin() {
return plugin;
}
public List<Method> getListeners(Class<? extends Event> eventClass, EventPriority priority) {
Map<EventPriority, List<Method>> mapping = listeners.get(eventClass);
if (mapping == null) {
return Collections.emptyList();
}
List<Method> list = mapping.get(priority);
return list == null ? Collections.emptyList() : Collections.unmodifiableList(list);
}
}

View File

@ -1,5 +1,21 @@
package com.loohp.limbo.file; package com.loohp.limbo.file;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Properties;
import javax.imageio.ImageIO;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.location.Location; import com.loohp.limbo.location.Location;
@ -7,15 +23,6 @@ import com.loohp.limbo.utils.GameMode;
import com.loohp.limbo.utils.NamespacedKey; import com.loohp.limbo.utils.NamespacedKey;
import com.loohp.limbo.world.World; import com.loohp.limbo.world.World;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Properties;
public class ServerProperties { public class ServerProperties {
public static final String COMMENT = "For explaination of what each of the options does, please visit:\nhttps://github.com/LOOHP/Limbo/blob/master/src/main/resources/server.properties"; public static final String COMMENT = "For explaination of what each of the options does, please visit:\nhttps://github.com/LOOHP/Limbo/blob/master/src/main/resources/server.properties";

View File

@ -4,21 +4,21 @@ import java.io.IOException;
import java.util.UUID; import java.util.UUID;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.commands.CommandSender;
import com.loohp.limbo.entity.DataWatcher;
import com.loohp.limbo.entity.DataWatcher.WatchableField;
import com.loohp.limbo.entity.DataWatcher.WatchableObjectType;
import com.loohp.limbo.entity.EntityType;
import com.loohp.limbo.entity.LivingEntity;
import com.loohp.limbo.events.player.PlayerChatEvent; import com.loohp.limbo.events.player.PlayerChatEvent;
import com.loohp.limbo.events.player.PlayerTeleportEvent; import com.loohp.limbo.events.player.PlayerTeleportEvent;
import com.loohp.limbo.location.Location;
import com.loohp.limbo.server.ClientConnection; import com.loohp.limbo.server.ClientConnection;
import com.loohp.limbo.server.packets.PacketPlayOutChat; import com.loohp.limbo.server.packets.PacketPlayOutChat;
import com.loohp.limbo.server.packets.PacketPlayOutGameState; import com.loohp.limbo.server.packets.PacketPlayOutGameState;
import com.loohp.limbo.server.packets.PacketPlayOutHeldItemChange; import com.loohp.limbo.server.packets.PacketPlayOutHeldItemChange;
import com.loohp.limbo.server.packets.PacketPlayOutPositionAndLook; import com.loohp.limbo.server.packets.PacketPlayOutPositionAndLook;
import com.loohp.limbo.server.packets.PacketPlayOutRespawn; import com.loohp.limbo.server.packets.PacketPlayOutRespawn;
import com.loohp.limbo.commands.CommandSender;
import com.loohp.limbo.entity.DataWatcher;
import com.loohp.limbo.entity.EntityType;
import com.loohp.limbo.entity.LivingEntity;
import com.loohp.limbo.entity.DataWatcher.WatchableField;
import com.loohp.limbo.entity.DataWatcher.WatchableObjectType;
import com.loohp.limbo.location.Location;
import com.loohp.limbo.utils.GameMode; import com.loohp.limbo.utils.GameMode;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;

View File

@ -11,6 +11,8 @@ import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.entity.Entity;
import com.loohp.limbo.location.Location;
import com.loohp.limbo.server.packets.PacketPlayOutEntityDestroy; import com.loohp.limbo.server.packets.PacketPlayOutEntityDestroy;
import com.loohp.limbo.server.packets.PacketPlayOutEntityMetadata; import com.loohp.limbo.server.packets.PacketPlayOutEntityMetadata;
import com.loohp.limbo.server.packets.PacketPlayOutLightUpdate; import com.loohp.limbo.server.packets.PacketPlayOutLightUpdate;
@ -18,8 +20,6 @@ import com.loohp.limbo.server.packets.PacketPlayOutMapChunk;
import com.loohp.limbo.server.packets.PacketPlayOutSpawnEntity; import com.loohp.limbo.server.packets.PacketPlayOutSpawnEntity;
import com.loohp.limbo.server.packets.PacketPlayOutSpawnEntityLiving; import com.loohp.limbo.server.packets.PacketPlayOutSpawnEntityLiving;
import com.loohp.limbo.server.packets.PacketPlayOutUnloadChunk; import com.loohp.limbo.server.packets.PacketPlayOutUnloadChunk;
import com.loohp.limbo.entity.Entity;
import com.loohp.limbo.location.Location;
import com.loohp.limbo.world.World; import com.loohp.limbo.world.World;
import net.querz.mca.Chunk; import net.querz.mca.Chunk;

View File

@ -1,41 +1,90 @@
package com.loohp.limbo.server; package com.loohp.limbo.server;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.loohp.limbo.Limbo;
import com.loohp.limbo.events.player.*;
import com.loohp.limbo.events.status.StatusPingEvent;
import com.loohp.limbo.file.ServerProperties;
import com.loohp.limbo.location.Location;
import com.loohp.limbo.player.Player;
import com.loohp.limbo.player.PlayerInteractManager;
import com.loohp.limbo.server.packets.*;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerAbilities.PlayerAbilityFlags;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo.PlayerInfoAction;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo.PlayerInfoData;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo.PlayerInfoData.PlayerInfoDataAddPlayer.PlayerSkinProperty;
import com.loohp.limbo.server.packets.PacketPlayOutTabComplete.TabCompleteMatches;
import com.loohp.limbo.utils.*;
import com.loohp.limbo.utils.MojangAPIUtils.SkinResponse;
import com.loohp.limbo.world.BlockPosition;
import com.loohp.limbo.world.World;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.Socket; import java.net.Socket;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.loohp.limbo.Limbo;
import com.loohp.limbo.events.player.PlayerJoinEvent;
import com.loohp.limbo.events.player.PlayerLoginEvent;
import com.loohp.limbo.events.player.PlayerMoveEvent;
import com.loohp.limbo.events.player.PlayerQuitEvent;
import com.loohp.limbo.events.player.PlayerSelectedSlotChangeEvent;
import com.loohp.limbo.events.status.StatusPingEvent;
import com.loohp.limbo.file.ServerProperties;
import com.loohp.limbo.location.Location;
import com.loohp.limbo.player.Player;
import com.loohp.limbo.player.PlayerInteractManager;
import com.loohp.limbo.server.packets.Packet;
import com.loohp.limbo.server.packets.PacketHandshakingIn;
import com.loohp.limbo.server.packets.PacketLoginInLoginStart;
import com.loohp.limbo.server.packets.PacketLoginInPluginMessaging;
import com.loohp.limbo.server.packets.PacketLoginOutDisconnect;
import com.loohp.limbo.server.packets.PacketLoginOutLoginSuccess;
import com.loohp.limbo.server.packets.PacketLoginOutPluginMessaging;
import com.loohp.limbo.server.packets.PacketOut;
import com.loohp.limbo.server.packets.PacketPlayInChat;
import com.loohp.limbo.server.packets.PacketPlayInHeldItemChange;
import com.loohp.limbo.server.packets.PacketPlayInKeepAlive;
import com.loohp.limbo.server.packets.PacketPlayInPosition;
import com.loohp.limbo.server.packets.PacketPlayInPositionAndLook;
import com.loohp.limbo.server.packets.PacketPlayInRotation;
import com.loohp.limbo.server.packets.PacketPlayInTabComplete;
import com.loohp.limbo.server.packets.PacketPlayOutDeclareCommands;
import com.loohp.limbo.server.packets.PacketPlayOutDisconnect;
import com.loohp.limbo.server.packets.PacketPlayOutEntityMetadata;
import com.loohp.limbo.server.packets.PacketPlayOutGameState;
import com.loohp.limbo.server.packets.PacketPlayOutHeldItemChange;
import com.loohp.limbo.server.packets.PacketPlayOutLogin;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerAbilities;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerAbilities.PlayerAbilityFlags;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo.PlayerInfoAction;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo.PlayerInfoData;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo.PlayerInfoData.PlayerInfoDataAddPlayer.PlayerSkinProperty;
import com.loohp.limbo.server.packets.PacketPlayOutPositionAndLook;
import com.loohp.limbo.server.packets.PacketPlayOutSpawnPosition;
import com.loohp.limbo.server.packets.PacketPlayOutTabComplete;
import com.loohp.limbo.server.packets.PacketPlayOutTabComplete.TabCompleteMatches;
import com.loohp.limbo.server.packets.PacketPlayOutUpdateViewPosition;
import com.loohp.limbo.server.packets.PacketStatusInPing;
import com.loohp.limbo.server.packets.PacketStatusInRequest;
import com.loohp.limbo.server.packets.PacketStatusOutPong;
import com.loohp.limbo.server.packets.PacketStatusOutResponse;
import com.loohp.limbo.utils.CheckedBiConsumer;
import com.loohp.limbo.utils.CustomStringUtils;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.DeclareCommands;
import com.loohp.limbo.utils.ForwardingUtils;
import com.loohp.limbo.utils.GameMode;
import com.loohp.limbo.utils.MojangAPIUtils;
import com.loohp.limbo.utils.MojangAPIUtils.SkinResponse;
import com.loohp.limbo.utils.NamespacedKey;
import com.loohp.limbo.world.BlockPosition;
import com.loohp.limbo.world.World;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer;
public class ClientConnection extends Thread { public class ClientConnection extends Thread {
public static enum ClientState { public static enum ClientState {
@ -48,7 +97,6 @@ public class ClientConnection extends Thread {
} }
private final Random random = new Random(); private final Random random = new Random();
private final JsonParser jsonParser = new JsonParser();
private final Socket client_socket; private final Socket client_socket;
private boolean running; private boolean running;
@ -212,15 +260,16 @@ public class ClientConnection extends Thread {
boolean bungeeGuardFound = false; boolean bungeeGuardFound = false;
if (data.length > 3) { if (data.length > 3) {
JsonArray skinJson = this.jsonParser.parse(data[3]).getAsJsonArray(); JSONArray skinJson = (JSONArray) new JSONParser().parse(data[3]);
for (JsonElement property : skinJson) { for (Object obj : skinJson) {
if (property.getAsJsonObject().get("name").getAsString().equals("textures")) { JSONObject property = (JSONObject) obj;
String skin = property.getAsJsonObject().get("value").getAsString(); if (property.get("name").toString().equals("textures")) {
String signature = property.getAsJsonObject().get("signature").getAsString(); String skin = property.get("value").toString();
String signature = property.get("signature").toString();
forwardedSkin = new SkinResponse(skin, signature); forwardedSkin = new SkinResponse(skin, signature);
} else if (isBungeeGuard && property.getAsJsonObject().get("name").getAsString().equals("bungeeguard-token")) { } else if (isBungeeGuard && property.get("name").toString().equals("bungeeguard-token")) {
String token = property.getAsJsonObject().get("value").getAsString(); String token = property.get("value").toString();
bungeeGuardFound = Limbo.getInstance().getServerProperties().getForwardingSecrets().contains(token); bungeeGuardFound = Limbo.getInstance().getServerProperties().getForwardingSecrets().contains(token);
} }
} }
@ -272,15 +321,16 @@ public class ClientConnection extends Thread {
disconnectDuringLogin(TextComponent.fromLegacyText("Internal error, messageId did not match")); disconnectDuringLogin(TextComponent.fromLegacyText("Internal error, messageId did not match"));
break; break;
} }
if (response.getData() == null) { if (!response.getData().isPresent()) {
disconnectDuringLogin(TextComponent.fromLegacyText("Unknown login plugin response packet!")); disconnectDuringLogin(TextComponent.fromLegacyText("Unknown login plugin response packet!"));
break; break;
} }
if (!ForwardingUtils.validateVelocityModernResponse(response.getData())) { byte[] responseData = response.getData().get();
if (!ForwardingUtils.validateVelocityModernResponse(responseData)) {
disconnectDuringLogin(TextComponent.fromLegacyText("Invalid playerinfo forwarding!")); disconnectDuringLogin(TextComponent.fromLegacyText("Invalid playerinfo forwarding!"));
break; break;
} }
ForwardingUtils.VelocityModernForwardingData data = ForwardingUtils.getVelocityDataFrom(response.getData()); ForwardingUtils.VelocityModernForwardingData data = ForwardingUtils.getVelocityDataFrom(responseData);
inetAddress = InetAddress.getByName(data.getIpAddress()); inetAddress = InetAddress.getByName(data.getIpAddress());
forwardedSkin = data.getSkinResponse(); forwardedSkin = data.getSkinResponse();
@ -376,8 +426,7 @@ public class ClientConnection extends Thread {
int packetId = DataTypeIO.readVarInt(input); int packetId = DataTypeIO.readVarInt(input);
Class<? extends Packet> packetType = Packet.getPlayIn().get(packetId); Class<? extends Packet> packetType = Packet.getPlayIn().get(packetId);
//Limbo.getInstance().getConsole().sendMessage(packetId + " -> " + packetType); //Limbo.getInstance().getConsole().sendMessage(packetId + " -> " + packetType);
CheckedConsumer<PlayerMoveEvent, IOException> processMoveEvent = event -> { CheckedBiConsumer<PlayerMoveEvent, Location, IOException> processMoveEvent = (event, originalTo) -> {
Location originalTo = event.getTo().clone();
if (event.isCancelled()) { if (event.isCancelled()) {
Location returnTo = event.getFrom(); Location returnTo = event.getFrom();
PacketPlayOutPositionAndLook cancel = new PacketPlayOutPositionAndLook(returnTo.getX(), returnTo.getY(), returnTo.getZ(), returnTo.getYaw(), returnTo.getPitch(), 1, false); PacketPlayOutPositionAndLook cancel = new PacketPlayOutPositionAndLook(returnTo.getX(), returnTo.getY(), returnTo.getZ(), returnTo.getYaw(), returnTo.getPitch(), 1, false);
@ -401,22 +450,28 @@ public class ClientConnection extends Thread {
Location from = player.getLocation(); Location from = player.getLocation();
Location to = new Location(player.getWorld(), pos.getX(), pos.getY(), pos.getZ(), pos.getYaw(), pos.getPitch()); Location to = new Location(player.getWorld(), pos.getX(), pos.getY(), pos.getZ(), pos.getYaw(), pos.getPitch());
if (!from.equals(to)) {
PlayerMoveEvent event = Limbo.getInstance().getEventsManager().callEvent(new PlayerMoveEvent(player, from, to)); PlayerMoveEvent event = Limbo.getInstance().getEventsManager().callEvent(new PlayerMoveEvent(player, from, to));
processMoveEvent.consume(event); processMoveEvent.consume(event, to);
}
} else if (packetType.equals(PacketPlayInPosition.class)) { } else if (packetType.equals(PacketPlayInPosition.class)) {
PacketPlayInPosition pos = new PacketPlayInPosition(input); PacketPlayInPosition pos = new PacketPlayInPosition(input);
Location from = player.getLocation(); Location from = player.getLocation();
Location to = new Location(player.getWorld(), pos.getX(), pos.getY(), pos.getZ(), player.getLocation().getYaw(), player.getLocation().getPitch()); Location to = new Location(player.getWorld(), pos.getX(), pos.getY(), pos.getZ(), player.getLocation().getYaw(), player.getLocation().getPitch());
if (!from.equals(to)) {
PlayerMoveEvent event = Limbo.getInstance().getEventsManager().callEvent(new PlayerMoveEvent(player, from, to)); PlayerMoveEvent event = Limbo.getInstance().getEventsManager().callEvent(new PlayerMoveEvent(player, from, to));
processMoveEvent.consume(event); processMoveEvent.consume(event, to);
}
} else if (packetType.equals(PacketPlayInRotation.class)) { } else if (packetType.equals(PacketPlayInRotation.class)) {
PacketPlayInRotation pos = new PacketPlayInRotation(input); PacketPlayInRotation pos = new PacketPlayInRotation(input);
Location from = player.getLocation(); Location from = player.getLocation();
Location to = new Location(player.getWorld(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), pos.getYaw(), pos.getPitch()); Location to = new Location(player.getWorld(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), pos.getYaw(), pos.getPitch());
if (!from.equals(to)) {
PlayerMoveEvent event = Limbo.getInstance().getEventsManager().callEvent(new PlayerMoveEvent(player, from, to)); PlayerMoveEvent event = Limbo.getInstance().getEventsManager().callEvent(new PlayerMoveEvent(player, from, to));
processMoveEvent.consume(event); processMoveEvent.consume(event, to);
}
} else if (packetType.equals(PacketPlayInKeepAlive.class)) { } else if (packetType.equals(PacketPlayInKeepAlive.class)) {
PacketPlayInKeepAlive alive = new PacketPlayInKeepAlive(input); PacketPlayInKeepAlive alive = new PacketPlayInKeepAlive(input);
if (alive.getPayload() != getLastKeepAlivePayLoad()) { if (alive.getPayload() != getLastKeepAlivePayLoad()) {
@ -486,8 +541,4 @@ public class ClientConnection extends Thread {
running = false; running = false;
} }
@FunctionalInterface
public interface CheckedConsumer<T, TException extends Throwable> {
void consume(T t) throws TException;
}
} }

View File

@ -1,19 +1,21 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Optional;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketLoginInPluginMessaging extends PacketIn { public class PacketLoginInPluginMessaging extends PacketIn {
private int messageId; private int messageId;
private boolean successful; private boolean successful;
private byte[] data = null; private Optional<byte[]> data;
public PacketLoginInPluginMessaging(int messageId, boolean successful, byte[] data) { public PacketLoginInPluginMessaging(int messageId, boolean successful, byte[] data) {
this.messageId = messageId; this.messageId = messageId;
this.data = data; this.successful = successful;
this.data = successful ? Optional.of(data) : Optional.empty();
} }
public PacketLoginInPluginMessaging(DataInputStream in, int packetLength, int packetId) throws IOException { public PacketLoginInPluginMessaging(DataInputStream in, int packetLength, int packetId) throws IOException {
@ -22,9 +24,14 @@ public class PacketLoginInPluginMessaging extends PacketIn {
if (successful) { if (successful) {
int dataLength = packetLength - DataTypeIO.getVarIntLength(packetId) - DataTypeIO.getVarIntLength(messageId) - 1; int dataLength = packetLength - DataTypeIO.getVarIntLength(packetId) - DataTypeIO.getVarIntLength(messageId) - 1;
if (dataLength != 0) { if (dataLength != 0) {
data = new byte[dataLength]; byte[] data = new byte[dataLength];
in.readFully(data); in.readFully(data);
this.data = Optional.of(data);
} else {
this.data = Optional.of(new byte[0]);
} }
} else {
data = Optional.empty();
} }
} }
@ -36,7 +43,7 @@ public class PacketLoginInPluginMessaging extends PacketIn {
return successful; return successful;
} }
public byte[] getData() { public Optional<byte[]> getData() {
return data; return data;
} }

View File

@ -1,13 +1,13 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.NamespacedKey;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.NamespacedKey;
public class PacketLoginOutPluginMessaging extends PacketOut { public class PacketLoginOutPluginMessaging extends PacketOut {
private int messageId; private int messageId;

View File

@ -13,10 +13,10 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.UUID; import java.util.UUID;
import com.loohp.limbo.entity.Entity;
import com.loohp.limbo.entity.Pose;
import com.loohp.limbo.entity.DataWatcher.WatchableObject; import com.loohp.limbo.entity.DataWatcher.WatchableObject;
import com.loohp.limbo.entity.DataWatcher.WatchableObjectType; import com.loohp.limbo.entity.DataWatcher.WatchableObjectType;
import com.loohp.limbo.entity.Entity;
import com.loohp.limbo.entity.Pose;
import com.loohp.limbo.utils.DataTypeIO; import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.Rotation3f; import com.loohp.limbo.utils.Rotation3f;
import com.loohp.limbo.world.BlockPosition; import com.loohp.limbo.world.BlockPosition;

View File

@ -0,0 +1,8 @@
package com.loohp.limbo.utils;
@FunctionalInterface
public interface CheckedBiConsumer<T, U, TException extends Throwable> {
void consume(T t, U u) throws TException;
}

View File

@ -7,8 +7,8 @@ import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.server.packets.PacketPlayOutDeclareCommands;
import com.loohp.limbo.commands.CommandSender; import com.loohp.limbo.commands.CommandSender;
import com.loohp.limbo.server.packets.PacketPlayOutDeclareCommands;
public class DeclareCommands { public class DeclareCommands {

View File

@ -11,15 +11,15 @@ import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.server.packets.PacketPlayOutEntityDestroy;
import com.loohp.limbo.server.packets.PacketPlayOutEntityMetadata;
import com.loohp.limbo.entity.ArmorStand; import com.loohp.limbo.entity.ArmorStand;
import com.loohp.limbo.entity.DataWatcher; import com.loohp.limbo.entity.DataWatcher;
import com.loohp.limbo.entity.DataWatcher.WatchableObject;
import com.loohp.limbo.entity.Entity; import com.loohp.limbo.entity.Entity;
import com.loohp.limbo.entity.EntityType; import com.loohp.limbo.entity.EntityType;
import com.loohp.limbo.entity.DataWatcher.WatchableObject;
import com.loohp.limbo.location.Location; import com.loohp.limbo.location.Location;
import com.loohp.limbo.player.Player; import com.loohp.limbo.player.Player;
import com.loohp.limbo.server.packets.PacketPlayOutEntityDestroy;
import com.loohp.limbo.server.packets.PacketPlayOutEntityMetadata;
import com.loohp.limbo.utils.SchematicConvertionUtils; import com.loohp.limbo.utils.SchematicConvertionUtils;
import net.querz.mca.Chunk; import net.querz.mca.Chunk;

Binary file not shown.