diff --git a/src/main/java/org/dragonet/proxy/commands/Command.java b/src/main/java/org/dragonet/proxy/commands/Command.java index 057f2b461..ddb5ae3a7 100644 --- a/src/main/java/org/dragonet/proxy/commands/Command.java +++ b/src/main/java/org/dragonet/proxy/commands/Command.java @@ -3,32 +3,29 @@ import org.dragonet.proxy.DragonProxy; public abstract class Command { - // vars - private final String name; - protected String description = ""; - private CommandRegister commandMap = null; - // constructor - public Command(String name) { - this(name, ""); - } + private final String name; + protected String description = ""; + private CommandRegister commandMap = null; - public Command(String name, String description) { - this.name = name; - this.description = description; - } + // constructor + public Command(String name) { + this(name, ""); + } - // public - public String getName() { - return name; - } + public Command(String name, String description) { + this.name = name; + this.description = description; + } - public String getDescription() { - return description; - } + public String getName() { + return name; + } - public abstract void execute(DragonProxy proxy, String[] args); + public String getDescription() { + return description; + } - // private + public abstract void execute(DragonProxy proxy, String[] args); } diff --git a/src/main/java/org/dragonet/proxy/commands/CommandRegister.java b/src/main/java/org/dragonet/proxy/commands/CommandRegister.java index 6c0d79783..c5e596d67 100644 --- a/src/main/java/org/dragonet/proxy/commands/CommandRegister.java +++ b/src/main/java/org/dragonet/proxy/commands/CommandRegister.java @@ -21,56 +21,51 @@ import org.dragonet.proxy.commands.defaults.*; public final class CommandRegister { - // vars - private final Map commandMap = Collections.synchronizedMap(new HashMap()); - private final DragonProxy proxy; - // constructor - public CommandRegister(DragonProxy proxy) { - this.proxy = proxy; - registerDefaults(); - } + private final Map commandMap = Collections.synchronizedMap(new HashMap()); + private final DragonProxy proxy; - // public - public void registerDefaults() { - registerCommand("stop", new StopCommand("stop")); - registerCommand("help", new HelpCommand("help")); - registerCommand("kill", new KillCommand("kill")); // Bad things could happen - registerCommand("test", new TestCommand("test")); // FOR TESTING - } + public CommandRegister(DragonProxy proxy) { + this.proxy = proxy; + registerDefaults(); + } - public void registerCommand(String command, Command console) { - commandMap.put(command, console); - } + public void registerDefaults() { + registerCommand("stop", new StopCommand("stop")); + registerCommand("help", new HelpCommand("help")); + registerCommand("kill", new KillCommand("kill")); // Bad things could happen + registerCommand("test", new TestCommand("test")); // FOR TESTING + } - public Map getCommands() { - return commandMap; - } + public void registerCommand(String command, Command console) { + commandMap.put(command, console); + } - public void callCommand(String cmd) { - String trimedCmd = cmd.trim(); - String label = null; - String[] args = null; - if (!cmd.trim().contains(" ")) { - label = trimedCmd.toLowerCase(); - args = new String[0]; - } else { - label = trimedCmd.substring(0, trimedCmd.indexOf(" ")).toLowerCase(); - String argLine = trimedCmd.substring(trimedCmd.indexOf(" ") + 1); - args = argLine.contains(" ") ? argLine.split(" ") : new String[] { argLine }; - } - if (label == null) { - proxy.getLogger().warning(proxy.getLang().get(Lang.COMMAND_NOT_FOUND)); - return; - } - Command command = commandMap.get(label); - if (command == null) { - proxy.getLogger().warning(proxy.getLang().get(Lang.COMMAND_NOT_FOUND)); - return; - } - command.execute(proxy, args); - } - - // private + public Map getCommands() { + return commandMap; + } + public void callCommand(String cmd) { + String trimedCmd = cmd.trim(); + String label = null; + String[] args = null; + if (!cmd.trim().contains(" ")) { + label = trimedCmd.toLowerCase(); + args = new String[0]; + } else { + label = trimedCmd.substring(0, trimedCmd.indexOf(" ")).toLowerCase(); + String argLine = trimedCmd.substring(trimedCmd.indexOf(" ") + 1); + args = argLine.contains(" ") ? argLine.split(" ") : new String[]{argLine}; + } + if (label == null) { + proxy.getLogger().warning(proxy.getLang().get(Lang.COMMAND_NOT_FOUND)); + return; + } + Command command = commandMap.get(label); + if (command == null) { + proxy.getLogger().warning(proxy.getLang().get(Lang.COMMAND_NOT_FOUND)); + return; + } + command.execute(proxy, args); + } } diff --git a/src/main/java/org/dragonet/proxy/commands/IConsoleCommand.java b/src/main/java/org/dragonet/proxy/commands/IConsoleCommand.java index 329e0dc55..f00ca97a0 100644 --- a/src/main/java/org/dragonet/proxy/commands/IConsoleCommand.java +++ b/src/main/java/org/dragonet/proxy/commands/IConsoleCommand.java @@ -15,5 +15,6 @@ import org.dragonet.proxy.DragonProxy; public interface IConsoleCommand { - void execute(DragonProxy proxy, String[] args); + + void execute(DragonProxy proxy, String[] args); } diff --git a/src/main/java/org/dragonet/proxy/commands/defaults/HelpCommand.java b/src/main/java/org/dragonet/proxy/commands/defaults/HelpCommand.java index 043a36983..74c0f2aaf 100644 --- a/src/main/java/org/dragonet/proxy/commands/defaults/HelpCommand.java +++ b/src/main/java/org/dragonet/proxy/commands/defaults/HelpCommand.java @@ -20,28 +20,22 @@ import java.util.TreeMap; public class HelpCommand extends Command { - // vars - // constructor - public HelpCommand(String name) { - super(name, "Displays commands for DragonProxy"); - } + public HelpCommand(String name) { + super(name, "Displays commands for DragonProxy"); + } - // public - public void execute(DragonProxy proxy, String[] args) { - proxy.getLogger().info(MCColor.GREEN + "----[ All commands for DragonProxy ]----"); + public void execute(DragonProxy proxy, String[] args) { + proxy.getLogger().info(MCColor.GREEN + "----[ All commands for DragonProxy ]----"); - Map commands = new TreeMap<>(); - for (Command cmd : proxy.getCommandRegister().getCommands().values()) { - commands.put(cmd.getName(), cmd); - } - - for (Command command1 : commands.values()) { - proxy.getLogger() - .info(MCColor.DARK_GREEN + command1.getName() + ": " + MCColor.WHITE + command1.getDescription()); - } - } - - // private + Map commands = new TreeMap<>(); + for (Command cmd : proxy.getCommandRegister().getCommands().values()) { + commands.put(cmd.getName(), cmd); + } + for (Command command1 : commands.values()) { + proxy.getLogger() + .info(MCColor.DARK_GREEN + command1.getName() + ": " + MCColor.WHITE + command1.getDescription()); + } + } } diff --git a/src/main/java/org/dragonet/proxy/commands/defaults/KillCommand.java b/src/main/java/org/dragonet/proxy/commands/defaults/KillCommand.java index 7ee52d7f8..63a92c85c 100644 --- a/src/main/java/org/dragonet/proxy/commands/defaults/KillCommand.java +++ b/src/main/java/org/dragonet/proxy/commands/defaults/KillCommand.java @@ -17,19 +17,13 @@ // Only use if you have to. Clients will eventually timeout. public class KillCommand extends Command { - // vars - // constructor - public KillCommand(String name) { - super(name, "Forcefully kill the proxy"); - } - - // public - public void execute(DragonProxy proxy, String[] args) { - proxy.getLogger().info("Forcefully killing proxy..."); - System.exit(0); - } - - // private + public KillCommand(String name) { + super(name, "Forcefully kill the proxy"); + } + public void execute(DragonProxy proxy, String[] args) { + proxy.getLogger().info("Forcefully killing proxy..."); + System.exit(0); + } } diff --git a/src/main/java/org/dragonet/proxy/commands/defaults/StopCommand.java b/src/main/java/org/dragonet/proxy/commands/defaults/StopCommand.java index b5ce54f7f..f03bde853 100644 --- a/src/main/java/org/dragonet/proxy/commands/defaults/StopCommand.java +++ b/src/main/java/org/dragonet/proxy/commands/defaults/StopCommand.java @@ -16,18 +16,12 @@ import org.dragonet.proxy.commands.Command; public class StopCommand extends Command { - // vars - // constructor - public StopCommand(String name) { - super(name, "Stop the proxy"); - } - - // public - public void execute(DragonProxy proxy, String[] args) { - proxy.shutdown(); - } - - // private + public StopCommand(String name) { + super(name, "Stop the proxy"); + } + public void execute(DragonProxy proxy, String[] args) { + proxy.shutdown(); + } } diff --git a/src/main/java/org/dragonet/proxy/commands/defaults/TestCommand.java b/src/main/java/org/dragonet/proxy/commands/defaults/TestCommand.java index b13b7db78..604c7eaf0 100644 --- a/src/main/java/org/dragonet/proxy/commands/defaults/TestCommand.java +++ b/src/main/java/org/dragonet/proxy/commands/defaults/TestCommand.java @@ -15,81 +15,75 @@ * Created on 2017/9/13. */ public class TestCommand extends Command { - // vars - // constructor - public TestCommand(String name) { - super(name); - } + public TestCommand(String name) { + super(name); + } - // public - public void execute(DragonProxy proxy, String[] args) { - UpstreamSession player = proxy.getSessionRegister().getAll().values().toArray(new UpstreamSession[1])[0]; - if (args[0].equalsIgnoreCase("status")) { - PlayStatusPacket s = new PlayStatusPacket(); - s.status = PlayStatusPacket.PLAYER_SPAWN; - player.sendPacket(s); - } else if (args[0].equalsIgnoreCase("res")) { - player.sendPacket(new ResourcePacksInfoPacket()); - } else if (args[0].equalsIgnoreCase("pos")) { - player.sendChat("pos at: " + player.getEntityCache().getClientEntity().x + ", " - + player.getEntityCache().getClientEntity().y + ", " + player.getEntityCache().getClientEntity().z); - } else if (args[0].equalsIgnoreCase("respawn")) { - RespawnPacket resp = new RespawnPacket(); - resp.position = new Vector3F(Float.parseFloat(args[1]), Float.parseFloat(args[2]), - Float.parseFloat(args[3])); - player.sendPacket(resp); - } else if (args[0].equalsIgnoreCase("chunkradius")) { - player.sendPacket(new ChunkRadiusUpdatedPacket(8)); - } else if (args[0].equalsIgnoreCase("setspawnpos")) { - SetSpawnPositionPacket packetSetSpawnPosition = new SetSpawnPositionPacket(); - packetSetSpawnPosition.position = new BlockPosition(Integer.parseInt(args[1]), Integer.parseInt(args[2]), Integer.parseInt(args[3])); - player.sendPacket(packetSetSpawnPosition); - } else if (args[0].equalsIgnoreCase("motion")) { - SetEntityMotionPacket mot = new SetEntityMotionPacket(); - mot.rtid = 1L; - mot.motion = new Vector3F(0f, 0f, 0f); - player.sendPacket(mot); - } else if (args[0].equalsIgnoreCase("die")) { - player.sendPacket(new SetHealthPacket(0)); - } else if (args[0].equalsIgnoreCase("tp")) { - Vector3F dest = new Vector3F(Float.parseFloat(args[1]), Float.parseFloat(args[2]), - Float.parseFloat(args[3])); - MovePlayerPacket m = new MovePlayerPacket(); - m.rtid = 1L; - m.mode = (byte) (Integer.parseInt(args[4]) & 0xFF); - m.position = dest; - player.sendPacket(m); - player.sendChat("\u00a7bTeleported to: " + dest.toString()); - } else if (args[0].equalsIgnoreCase("moveentity")) { - Vector3F dest = new Vector3F(Float.parseFloat(args[1]), Float.parseFloat(args[2]), - Float.parseFloat(args[3])); - MoveEntityPacket m = new MoveEntityPacket(); - m.rtid = 1L; - m.teleported = args[4].equalsIgnoreCase("true"); - m.position = dest; - player.sendPacket(m); - player.sendChat("\u00a7bTeleported to: " + dest.toString()); - } else if (args[0].equalsIgnoreCase("chunk")) { - /* + public void execute(DragonProxy proxy, String[] args) { + UpstreamSession player = proxy.getSessionRegister().getAll().values().toArray(new UpstreamSession[1])[0]; + if (args[0].equalsIgnoreCase("status")) { + PlayStatusPacket s = new PlayStatusPacket(); + s.status = PlayStatusPacket.PLAYER_SPAWN; + player.sendPacket(s); + } else if (args[0].equalsIgnoreCase("res")) { + player.sendPacket(new ResourcePacksInfoPacket()); + } else if (args[0].equalsIgnoreCase("pos")) { + player.sendChat("pos at: " + player.getEntityCache().getClientEntity().x + ", " + + player.getEntityCache().getClientEntity().y + ", " + player.getEntityCache().getClientEntity().z); + } else if (args[0].equalsIgnoreCase("respawn")) { + RespawnPacket resp = new RespawnPacket(); + resp.position = new Vector3F(Float.parseFloat(args[1]), Float.parseFloat(args[2]), + Float.parseFloat(args[3])); + player.sendPacket(resp); + } else if (args[0].equalsIgnoreCase("chunkradius")) { + player.sendPacket(new ChunkRadiusUpdatedPacket(8)); + } else if (args[0].equalsIgnoreCase("setspawnpos")) { + SetSpawnPositionPacket packetSetSpawnPosition = new SetSpawnPositionPacket(); + packetSetSpawnPosition.position = new BlockPosition(Integer.parseInt(args[1]), Integer.parseInt(args[2]), Integer.parseInt(args[3])); + player.sendPacket(packetSetSpawnPosition); + } else if (args[0].equalsIgnoreCase("motion")) { + SetEntityMotionPacket mot = new SetEntityMotionPacket(); + mot.rtid = 1L; + mot.motion = new Vector3F(0f, 0f, 0f); + player.sendPacket(mot); + } else if (args[0].equalsIgnoreCase("die")) { + player.sendPacket(new SetHealthPacket(0)); + } else if (args[0].equalsIgnoreCase("tp")) { + Vector3F dest = new Vector3F(Float.parseFloat(args[1]), Float.parseFloat(args[2]), + Float.parseFloat(args[3])); + MovePlayerPacket m = new MovePlayerPacket(); + m.rtid = 1L; + m.mode = (byte) (Integer.parseInt(args[4]) & 0xFF); + m.position = dest; + player.sendPacket(m); + player.sendChat("\u00a7bTeleported to: " + dest.toString()); + } else if (args[0].equalsIgnoreCase("moveentity")) { + Vector3F dest = new Vector3F(Float.parseFloat(args[1]), Float.parseFloat(args[2]), + Float.parseFloat(args[3])); + MoveEntityPacket m = new MoveEntityPacket(); + m.rtid = 1L; + m.teleported = args[4].equalsIgnoreCase("true"); + m.position = dest; + player.sendPacket(m); + player.sendChat("\u00a7bTeleported to: " + dest.toString()); + } else if (args[0].equalsIgnoreCase("chunk")) { + /* * FullChunkData chunk = new FullChunkData(Integer.parseInt(args[1]), * Integer.parseInt(args[2])); Arrays.fill(chunk.ids, (byte)1); - */ - ChunkData data = new ChunkData(); - data.sections = new Section[16]; - for (int cy = 0; cy < 16; cy++) { - data.sections[cy] = new Section(); - Arrays.fill(data.sections[cy].blockIds, (byte) 1); - } - FullChunkDataPacket chunk = new FullChunkDataPacket(); - chunk.x = Integer.parseInt(args[1]); - chunk.z = Integer.parseInt(args[2]); - data.encode(); - chunk.payload = data.getBuffer(); - player.sendPacket(chunk); - } - } - - // private - + */ + ChunkData data = new ChunkData(); + data.sections = new Section[16]; + for (int cy = 0; cy < 16; cy++) { + data.sections[cy] = new Section(); + Arrays.fill(data.sections[cy].blockIds, (byte) 1); + } + FullChunkDataPacket chunk = new FullChunkDataPacket(); + chunk.x = Integer.parseInt(args[1]); + chunk.z = Integer.parseInt(args[2]); + data.encode(); + chunk.payload = data.getBuffer(); + player.sendPacket(chunk); + } + } } diff --git a/src/main/java/org/dragonet/proxy/configuration/IConfigurationSerializable.java b/src/main/java/org/dragonet/proxy/configuration/IConfigurationSerializable.java index 9f7e6d8c9..0690e277f 100644 --- a/src/main/java/org/dragonet/proxy/configuration/IConfigurationSerializable.java +++ b/src/main/java/org/dragonet/proxy/configuration/IConfigurationSerializable.java @@ -3,5 +3,6 @@ import java.util.Map; public interface IConfigurationSerializable { - public Map serialize(); + + public Map serialize(); } diff --git a/src/main/java/org/dragonet/proxy/configuration/Lang.java b/src/main/java/org/dragonet/proxy/configuration/Lang.java index fe8dd7723..27e3b6c8d 100644 --- a/src/main/java/org/dragonet/proxy/configuration/Lang.java +++ b/src/main/java/org/dragonet/proxy/configuration/Lang.java @@ -15,58 +15,53 @@ import java.io.IOException; public class Lang extends PropertiesConfig { - // vars - public static final String INIT_LOADING = "init_loading"; - public static final String INIT_MC_PC_SUPPORT = "init_mc_pc_support"; - public static final String INIT_MC_PE_SUPPORT = "init_mc_pe_support"; - public static final String INIT_CREATING_THREAD_POOL = "init_creating_thread_pool"; - public static final String INIT_BINDING = "init_binding"; - public static final String INIT_DONE = "init_done"; - public static final String BROADCAST_TITLE = "broadcast_title"; - public static final String MESSAGE_CLIENT_CONNECTED = "message_client_connected"; - public static final String MESSAGE_CLS_NOTICE = "message_cls_notice"; - public static final String MESSAGE_SERVER_ERROR = "message_server_error"; - public static final String ERROR_CLS_UNREACHABLE = "error_cls_unreachable"; - public static final String ERROR_CLS_ERROR = "error_cls_error"; - public static final String ERROR_CLS_LOGIN = "error_cls_login"; - public static final String MESSAGE_ONLINE_NOTICE = "message_online_notice"; - public static final String MESSAGE_ONLINE_EMAIL = "message_online_email"; - public static final String MESSAGE_ONLINE_ERROR = "message_online_error"; - public static final String MESSAGE_ONLINE_PASSWORD = "message_online_password"; - public static final String MESSAGE_ONLINE_LOGGIN_IN = "message_online_logging_in"; - public static final String MESSAGE_ONLINE_LOGIN_SUCCESS = "message_online_login_success"; - public static final String MESSAGE_ONLINE_LOGIN_SUCCESS_CONSOLE = "message_online_login_success_console"; - public static final String MESSAGE_TELEPORT_TO_SPAWN = "message_teleport_to_spawn"; - public static final String MESSAGE_ONLINE_USERNAME = "message_online_username"; - public static final String MESSAGE_ONLINE_LOGIN_FAILD = "message_online_login_faild"; - public static final String MESSAGE_REMOTE_CONNECTED = "message_remote_connected"; - public static final String MESSAGE_REMOTE_CONNECT_FAILURE = "message_remote_connect_failure"; - public static final String MESSAGE_JOINED = "message_joined"; - public static final String MESSAGE_KICKED = "message_kicked"; - public static final String MESSAGE_CLIENT_DISCONNECT = "message_client_disconnect"; - public static final String MESSAGE_REMOTE_IS_ONLINE = "message_remote_is_online"; - public static final String MESSAGE_REMOTE_ERROR = "message_remote_error"; - public static final String MESSAGE_REMOTE_DISCONNECTED = "message_remote_disconnected"; - public static final String CLIENT_DISCONNECTED = "client_disconnected"; - public static final String COMMAND_NOT_FOUND = "command_not_found"; - public static final String SHUTTING_DOWN = "shutting_down"; - public static final String MESSAGE_UNSUPPORTED_CLIENT = "message_unsupported_client"; - public static final String QUERY_FAILED = "query_failed"; - // constructor - public Lang(String langFileName) throws IOException { - super("/en_US.properties", langFileName, false); - } + public static final String INIT_LOADING = "init_loading"; + public static final String INIT_MC_PC_SUPPORT = "init_mc_pc_support"; + public static final String INIT_MC_PE_SUPPORT = "init_mc_pe_support"; + public static final String INIT_CREATING_THREAD_POOL = "init_creating_thread_pool"; + public static final String INIT_BINDING = "init_binding"; + public static final String INIT_DONE = "init_done"; + public static final String BROADCAST_TITLE = "broadcast_title"; + public static final String MESSAGE_CLIENT_CONNECTED = "message_client_connected"; + public static final String MESSAGE_CLS_NOTICE = "message_cls_notice"; + public static final String MESSAGE_SERVER_ERROR = "message_server_error"; + public static final String ERROR_CLS_UNREACHABLE = "error_cls_unreachable"; + public static final String ERROR_CLS_ERROR = "error_cls_error"; + public static final String ERROR_CLS_LOGIN = "error_cls_login"; + public static final String MESSAGE_ONLINE_NOTICE = "message_online_notice"; + public static final String MESSAGE_ONLINE_EMAIL = "message_online_email"; + public static final String MESSAGE_ONLINE_ERROR = "message_online_error"; + public static final String MESSAGE_ONLINE_PASSWORD = "message_online_password"; + public static final String MESSAGE_ONLINE_LOGGIN_IN = "message_online_logging_in"; + public static final String MESSAGE_ONLINE_LOGIN_SUCCESS = "message_online_login_success"; + public static final String MESSAGE_ONLINE_LOGIN_SUCCESS_CONSOLE = "message_online_login_success_console"; + public static final String MESSAGE_TELEPORT_TO_SPAWN = "message_teleport_to_spawn"; + public static final String MESSAGE_ONLINE_USERNAME = "message_online_username"; + public static final String MESSAGE_ONLINE_LOGIN_FAILD = "message_online_login_faild"; + public static final String MESSAGE_REMOTE_CONNECTED = "message_remote_connected"; + public static final String MESSAGE_REMOTE_CONNECT_FAILURE = "message_remote_connect_failure"; + public static final String MESSAGE_JOINED = "message_joined"; + public static final String MESSAGE_KICKED = "message_kicked"; + public static final String MESSAGE_CLIENT_DISCONNECT = "message_client_disconnect"; + public static final String MESSAGE_REMOTE_IS_ONLINE = "message_remote_is_online"; + public static final String MESSAGE_REMOTE_ERROR = "message_remote_error"; + public static final String MESSAGE_REMOTE_DISCONNECTED = "message_remote_disconnected"; + public static final String CLIENT_DISCONNECTED = "client_disconnected"; + public static final String COMMAND_NOT_FOUND = "command_not_found"; + public static final String SHUTTING_DOWN = "shutting_down"; + public static final String MESSAGE_UNSUPPORTED_CLIENT = "message_unsupported_client"; + public static final String QUERY_FAILED = "query_failed"; - // public - public String get(String key) { - return getConfig().getProperty(key).replace("[PROJNAME]", getConfig().getProperty("project_name")); - } + public Lang(String langFileName) throws IOException { + super("/en_US.properties", langFileName, false); + } - public String get(String key, Object... repl) { - return String.format(get(key), repl); - } - - // private + public String get(String key) { + return getConfig().getProperty(key).replace("[PROJNAME]", getConfig().getProperty("project_name")); + } + public String get(String key, Object... repl) { + return String.format(get(key), repl); + } } diff --git a/src/main/java/org/dragonet/proxy/configuration/PropertiesConfig.java b/src/main/java/org/dragonet/proxy/configuration/PropertiesConfig.java index 05f7c52e3..9486d8b9d 100644 --- a/src/main/java/org/dragonet/proxy/configuration/PropertiesConfig.java +++ b/src/main/java/org/dragonet/proxy/configuration/PropertiesConfig.java @@ -20,34 +20,29 @@ import java.util.Properties; public class PropertiesConfig { - // vars - private final Properties config; - // constructor - public PropertiesConfig(String defaultResourcePath, String fileName, boolean saveDefault) throws IOException { - Properties defaultConfig = new Properties(); - defaultConfig.load(PropertiesConfig.class.getResourceAsStream(defaultResourcePath)); - config = new Properties(defaultConfig); - File file = new File(fileName); - if (file.exists()) { - config.load(new FileInputStream(fileName)); - } else if (saveDefault) { - FileOutputStream fos = new FileOutputStream(fileName); - InputStream ris = PropertiesConfig.class.getResourceAsStream(defaultResourcePath); - int d = -1; - while ((d = ris.read()) != -1) { - fos.write(d); - } - fos.close(); - ris.close(); - } - } + private final Properties config; - // public - public Properties getConfig() { - return config; - } - - // private + public PropertiesConfig(String defaultResourcePath, String fileName, boolean saveDefault) throws IOException { + Properties defaultConfig = new Properties(); + defaultConfig.load(PropertiesConfig.class.getResourceAsStream(defaultResourcePath)); + config = new Properties(defaultConfig); + File file = new File(fileName); + if (file.exists()) { + config.load(new FileInputStream(fileName)); + } else if (saveDefault) { + FileOutputStream fos = new FileOutputStream(fileName); + InputStream ris = PropertiesConfig.class.getResourceAsStream(defaultResourcePath); + int d = -1; + while ((d = ris.read()) != -1) { + fos.write(d); + } + fos.close(); + ris.close(); + } + } + public Properties getConfig() { + return config; + } } diff --git a/src/main/java/org/dragonet/proxy/configuration/RemoteServer.java b/src/main/java/org/dragonet/proxy/configuration/RemoteServer.java index d20029cd2..5f26282ae 100644 --- a/src/main/java/org/dragonet/proxy/configuration/RemoteServer.java +++ b/src/main/java/org/dragonet/proxy/configuration/RemoteServer.java @@ -16,36 +16,31 @@ import java.util.Map; public abstract class RemoteServer implements IConfigurationSerializable { - // vars - public String remote_addr; - public int remote_port; - // constructor - public RemoteServer() { - super(); - } + public String remote_addr; + public int remote_port; - // public - /** - * Required for deserailization. - * - * @param server - * @param map - * @return - */ - public static RemoteServer delicatedDeserialize(RemoteServer server, Map map) { - server.remote_addr = (String) map.get("remote_addr"); - server.remote_port = ((Number) map.get("remote_port")).intValue(); - return server; - } + public RemoteServer() { + super(); + } - public Map serialize() { - Map map = new LinkedHashMap<>(); - map.put("remote_addr", remote_addr); - map.put("remote_port", remote_port); - return map; - } - - // private + /** + * Required for deserailization. + * + * @param server + * @param map + * @return + */ + public static RemoteServer delicatedDeserialize(RemoteServer server, Map map) { + server.remote_addr = (String) map.get("remote_addr"); + server.remote_port = ((Number) map.get("remote_port")).intValue(); + return server; + } + public Map serialize() { + Map map = new LinkedHashMap<>(); + map.put("remote_addr", remote_addr); + map.put("remote_port", remote_port); + return map; + } } diff --git a/src/main/java/org/dragonet/proxy/configuration/ServerConfig.java b/src/main/java/org/dragonet/proxy/configuration/ServerConfig.java index b53caa276..74c2b122d 100644 --- a/src/main/java/org/dragonet/proxy/configuration/ServerConfig.java +++ b/src/main/java/org/dragonet/proxy/configuration/ServerConfig.java @@ -15,26 +15,20 @@ import java.util.Map; public class ServerConfig { - // vars - public String lang = "default"; - public String udp_bind_ip = "0.0.0.0"; - public int udp_bind_port = 19132; - public String motd = "&aServer by DragonProxy"; - public String default_server = "NONE"; - public Map remote_servers; - public String mode = "cls"; - public String command_prefix = "/"; - public int max_players = -1; - public boolean log_console = true; - public int thread_pool_size; - // constructor - public ServerConfig() { + public String lang = "default"; + public String udp_bind_ip = "0.0.0.0"; + public int udp_bind_port = 19132; + public String motd = "&aServer by DragonProxy"; + public String default_server = "NONE"; + public Map remote_servers; + public String mode = "cls"; + public String command_prefix = "/"; + public int max_players = -1; + public boolean log_console = true; + public int thread_pool_size; - } - - // public - - // private + public ServerConfig() { + } } diff --git a/src/main/java/org/dragonet/proxy/data/PocketPotionEffect.java b/src/main/java/org/dragonet/proxy/data/PocketPotionEffect.java index 909dacf46..66ccc68de 100644 --- a/src/main/java/org/dragonet/proxy/data/PocketPotionEffect.java +++ b/src/main/java/org/dragonet/proxy/data/PocketPotionEffect.java @@ -15,87 +15,88 @@ import java.util.HashMap; public class PocketPotionEffect { - // vars - public static final int SPEED = 1; - public static final int SLOWNESS = 2; - public static final int HASTE = 3; - public static final int SWIFTNESS = 3; - public static final int FATIGUE = 4; - public static final int MINING_FATIGUE = 4; - public static final int STRENGTH = 5; - // TODO: public static final int HEALING = 6; - // TODO: public static final int HARMING = 7; - public static final int JUMP = 8; - public static final int NAUSEA = 9; - public static final int CONFUSION = 9; - public static final int REGENERATION = 10; - public static final int DAMAGE_RESISTANCE = 11; - public static final int FIRE_RESISTANCE = 12; - public static final int WATER_BREATHING = 13; - public static final int INVISIBILITY = 14; - // public static final int BLINDNESS = 15; - // public static final int NIGHT_VISION = 16; - // public static final int HUNGER = 17; - public static final int WEAKNESS = 18; - public static final int POISON = 19; - public static final int WITHER = 20; - public static final int HEALTH_BOOST = 21; - // public static final int ABSORPTION = 22; - // public static final int SATURATION = 23; + // vars - private static final HashMap EFFECTS = new HashMap<>(); + public static final int SPEED = 1; + public static final int SLOWNESS = 2; + public static final int HASTE = 3; + public static final int SWIFTNESS = 3; + public static final int FATIGUE = 4; + public static final int MINING_FATIGUE = 4; + public static final int STRENGTH = 5; + // TODO: public static final int HEALING = 6; + // TODO: public static final int HARMING = 7; + public static final int JUMP = 8; + public static final int NAUSEA = 9; + public static final int CONFUSION = 9; + public static final int REGENERATION = 10; + public static final int DAMAGE_RESISTANCE = 11; + public static final int FIRE_RESISTANCE = 12; + public static final int WATER_BREATHING = 13; + public static final int INVISIBILITY = 14; + // public static final int BLINDNESS = 15; + // public static final int NIGHT_VISION = 16; + // public static final int HUNGER = 17; + public static final int WEAKNESS = 18; + public static final int POISON = 19; + public static final int WITHER = 20; + public static final int HEALTH_BOOST = 21; + // public static final int ABSORPTION = 22; + // public static final int SATURATION = 23; - static { - EFFECTS.put(SPEED, new PocketPotionEffect(SPEED)); - EFFECTS.put(SLOWNESS, new PocketPotionEffect(SLOWNESS)); - EFFECTS.put(HASTE, new PocketPotionEffect(HASTE)); - EFFECTS.put(SWIFTNESS, new PocketPotionEffect(SWIFTNESS)); - EFFECTS.put(FATIGUE, new PocketPotionEffect(FATIGUE)); - EFFECTS.put(MINING_FATIGUE, new PocketPotionEffect(MINING_FATIGUE)); - EFFECTS.put(STRENGTH, new PocketPotionEffect(STRENGTH)); - EFFECTS.put(JUMP, new PocketPotionEffect(JUMP)); - EFFECTS.put(NAUSEA, new PocketPotionEffect(NAUSEA)); - EFFECTS.put(CONFUSION, new PocketPotionEffect(CONFUSION)); - EFFECTS.put(REGENERATION, new PocketPotionEffect(REGENERATION)); - EFFECTS.put(DAMAGE_RESISTANCE, new PocketPotionEffect(DAMAGE_RESISTANCE)); - EFFECTS.put(FIRE_RESISTANCE, new PocketPotionEffect(FIRE_RESISTANCE)); - EFFECTS.put(WATER_BREATHING, new PocketPotionEffect(WATER_BREATHING)); - EFFECTS.put(INVISIBILITY, new PocketPotionEffect(INVISIBILITY)); - EFFECTS.put(WEAKNESS, new PocketPotionEffect(WEAKNESS)); - EFFECTS.put(POISON, new PocketPotionEffect(POISON)); - EFFECTS.put(WITHER, new PocketPotionEffect(WITHER)); - EFFECTS.put(HEALTH_BOOST, new PocketPotionEffect(HEALTH_BOOST)); - } + private static final HashMap EFFECTS = new HashMap<>(); - public int amplifier; - public int duration; - public boolean particles; - private final int effect; + static { + EFFECTS.put(SPEED, new PocketPotionEffect(SPEED)); + EFFECTS.put(SLOWNESS, new PocketPotionEffect(SLOWNESS)); + EFFECTS.put(HASTE, new PocketPotionEffect(HASTE)); + EFFECTS.put(SWIFTNESS, new PocketPotionEffect(SWIFTNESS)); + EFFECTS.put(FATIGUE, new PocketPotionEffect(FATIGUE)); + EFFECTS.put(MINING_FATIGUE, new PocketPotionEffect(MINING_FATIGUE)); + EFFECTS.put(STRENGTH, new PocketPotionEffect(STRENGTH)); + EFFECTS.put(JUMP, new PocketPotionEffect(JUMP)); + EFFECTS.put(NAUSEA, new PocketPotionEffect(NAUSEA)); + EFFECTS.put(CONFUSION, new PocketPotionEffect(CONFUSION)); + EFFECTS.put(REGENERATION, new PocketPotionEffect(REGENERATION)); + EFFECTS.put(DAMAGE_RESISTANCE, new PocketPotionEffect(DAMAGE_RESISTANCE)); + EFFECTS.put(FIRE_RESISTANCE, new PocketPotionEffect(FIRE_RESISTANCE)); + EFFECTS.put(WATER_BREATHING, new PocketPotionEffect(WATER_BREATHING)); + EFFECTS.put(INVISIBILITY, new PocketPotionEffect(INVISIBILITY)); + EFFECTS.put(WEAKNESS, new PocketPotionEffect(WEAKNESS)); + EFFECTS.put(POISON, new PocketPotionEffect(POISON)); + EFFECTS.put(WITHER, new PocketPotionEffect(WITHER)); + EFFECTS.put(HEALTH_BOOST, new PocketPotionEffect(HEALTH_BOOST)); + } - // constructor - public PocketPotionEffect(int effect) { - this.effect = effect; - } + public int amplifier; + public int duration; + public boolean particles; + private final int effect; - // public - public static PocketPotionEffect getByID(int id) { - if (EFFECTS.containsKey(id)) { - return EFFECTS.get((Integer) id).clone(); - } else { - return null; - } - } + // constructor + public PocketPotionEffect(int effect) { + this.effect = effect; + } - public int getEffect() { - return effect; - } + // public + public static PocketPotionEffect getByID(int id) { + if (EFFECTS.containsKey(id)) { + return EFFECTS.get((Integer) id).clone(); + } else { + return null; + } + } - // private - protected PocketPotionEffect clone() { - PocketPotionEffect eff = new PocketPotionEffect(effect); - eff.amplifier = amplifier; - eff.particles = particles; - eff.duration = duration; - return eff; - } + public int getEffect() { + return effect; + } + + // private + protected PocketPotionEffect clone() { + PocketPotionEffect eff = new PocketPotionEffect(effect); + eff.amplifier = amplifier; + eff.particles = particles; + eff.duration = duration; + return eff; + } } diff --git a/src/main/java/org/dragonet/proxy/data/entity/EntityType.java b/src/main/java/org/dragonet/proxy/data/entity/EntityType.java index 86921aadb..03ea44caa 100644 --- a/src/main/java/org/dragonet/proxy/data/entity/EntityType.java +++ b/src/main/java/org/dragonet/proxy/data/entity/EntityType.java @@ -20,7 +20,6 @@ public enum EntityType { NONE(0, 0), - CHICKEN(10, 0), COW(11, 0), PIG(12, 0), diff --git a/src/main/java/org/dragonet/proxy/data/entity/PEEntityAttribute.java b/src/main/java/org/dragonet/proxy/data/entity/PEEntityAttribute.java index 5fb5085c8..7450df755 100644 --- a/src/main/java/org/dragonet/proxy/data/entity/PEEntityAttribute.java +++ b/src/main/java/org/dragonet/proxy/data/entity/PEEntityAttribute.java @@ -6,7 +6,6 @@ * Created on 2017/10/21. */ public class PEEntityAttribute { - // vars public static final int ABSORPTION = 0; public static final int SATURATION = 1; @@ -45,7 +44,6 @@ public class PEEntityAttribute { public float defaultValue; public float currentValue; - // constructor public PEEntityAttribute() { } @@ -89,10 +87,14 @@ public PEEntityAttribute(int id, String name, float min, float max, float defaul this.defaultValue = defaultValue; this.currentValue = currentValue; } + + public PEEntityAttribute setValue(float currentValue) + { + this.currentValue = currentValue; + return this; + } public PEEntityAttribute clone() { return new PEEntityAttribute(id, name, min, max, defaultValue, currentValue); } - - // private } diff --git a/src/main/java/org/dragonet/proxy/data/entity/meta/EntityMetaData.java b/src/main/java/org/dragonet/proxy/data/entity/meta/EntityMetaData.java index 9b8f8761a..87dd458ac 100644 --- a/src/main/java/org/dragonet/proxy/data/entity/meta/EntityMetaData.java +++ b/src/main/java/org/dragonet/proxy/data/entity/meta/EntityMetaData.java @@ -18,9 +18,7 @@ import org.dragonet.proxy.data.entity.meta.type.FloatMeta; import org.dragonet.proxy.data.entity.meta.type.LongMeta; import org.dragonet.proxy.data.entity.meta.type.ShortMeta; - import org.dragonet.proxy.utilities.BinaryStream; -import org.dragonet.proxy.utilities.BlockPosition; public class EntityMetaData extends BinaryStream { diff --git a/src/main/java/org/dragonet/proxy/data/entity/meta/type/BlockPositionMeta.java b/src/main/java/org/dragonet/proxy/data/entity/meta/type/BlockPositionMeta.java index cfed4d83e..19062897c 100644 --- a/src/main/java/org/dragonet/proxy/data/entity/meta/type/BlockPositionMeta.java +++ b/src/main/java/org/dragonet/proxy/data/entity/meta/type/BlockPositionMeta.java @@ -32,7 +32,7 @@ public int type() { public void encode(BinaryStream out) { out.putSignedBlockPosition(position); } - + @Override public String toString() { return "BlockPosition{" + position.toString() + "}"; diff --git a/src/main/java/org/dragonet/proxy/data/entity/meta/type/ByteArrayMeta.java b/src/main/java/org/dragonet/proxy/data/entity/meta/type/ByteArrayMeta.java index 92c5d187c..9679d5962 100644 --- a/src/main/java/org/dragonet/proxy/data/entity/meta/type/ByteArrayMeta.java +++ b/src/main/java/org/dragonet/proxy/data/entity/meta/type/ByteArrayMeta.java @@ -43,8 +43,9 @@ public String toString() { builder.append("["); for (int i = 0; i < data.length; i++) { builder.append(data[i]); - if (i != data.length) - builder.append(", "); + if (i != data.length) { + builder.append(", "); + } } builder.append("] = " + new String(data, StandardCharsets.UTF_8)); return "ByteArrayMeta{" + builder.toString() + "}"; diff --git a/src/main/java/org/dragonet/proxy/data/inventory/ContainerId.java b/src/main/java/org/dragonet/proxy/data/inventory/ContainerId.java index 251e747cc..b082459a3 100644 --- a/src/main/java/org/dragonet/proxy/data/inventory/ContainerId.java +++ b/src/main/java/org/dragonet/proxy/data/inventory/ContainerId.java @@ -4,16 +4,24 @@ * Created on 2017/10/21. */ public enum ContainerId { - NONE(1), INVENTORY(0), FIRST(1), LAST(100), OFFHAND(119), ARMOR(120), CREATIVE(121), HOTBAR(122), FIXED_INVENTORY( - 123), CURSOR(124); + NONE(1), + INVENTORY(0), + FIRST(1), + LAST(100), + OFFHAND(119), + ARMOR(120), + CREATIVE(121), + HOTBAR(122), + FIXED_INVENTORY(123), + CURSOR(124); - private int id; + private int id; - private ContainerId(int id) { - this.id = id; - } + private ContainerId(int id) { + this.id = id; + } - public int getId() { - return id; - } + public int getId() { + return id; + } } diff --git a/src/main/java/org/dragonet/proxy/data/inventory/InventoryType.java b/src/main/java/org/dragonet/proxy/data/inventory/InventoryType.java index 3a5377d4e..7dad71ee8 100644 --- a/src/main/java/org/dragonet/proxy/data/inventory/InventoryType.java +++ b/src/main/java/org/dragonet/proxy/data/inventory/InventoryType.java @@ -13,97 +13,101 @@ package org.dragonet.proxy.data.inventory; public final class InventoryType { - public static final class PEInventory { - public static final byte CHEST = (byte) 0; - public static final byte DOUBLE_CHEST = (byte) 0; - public static final byte PLAYER = (byte) 0; - public static final byte FURNACE = (byte) 2; - public static final byte CRAFTING = (byte) 1; - public static final byte WORKBENCH = (byte) 1; - public static final byte STONECUTTER = (byte) 1; - public static final byte BREWING_STAND = (byte) 5; - public static final byte ANVIL = (byte) 6; - public static final byte ENCHANT_TABLE = (byte) 4; - public static final byte toPEInventory(byte bytePC, int slots) { - switch (bytePC) { - case PCInventory.CHEST: - if (slots > 64) // Large - { - return PEInventory.DOUBLE_CHEST; - } else { - return PEInventory.CHEST; - } - case PCInventory.WORKBENCH: - return PEInventory.WORKBENCH; - case PCInventory.FURNANCE: - return PEInventory.FURNACE; - // case PCInventory.DISPENSER: - // case PCInventory.ENCHANTING_TABLE: - // case PCInventory.BREWING_STAND: - // case PCInventory.NPC_TRADE: - // case PCInventory.BEACON: - // case PCInventory.ANVIL: - // case PCInventory.HOPPER: - // case PCInventory.DROPPER: - // case PCInventory.HORSE: - default: - return (byte) 0xFF; - } - } + public static final class PEInventory { - } + public static final byte CHEST = (byte) 0; + public static final byte DOUBLE_CHEST = (byte) 0; + public static final byte PLAYER = (byte) 0; + public static final byte FURNACE = (byte) 2; + public static final byte CRAFTING = (byte) 1; + public static final byte WORKBENCH = (byte) 1; + public static final byte STONECUTTER = (byte) 1; + public static final byte BREWING_STAND = (byte) 5; + public static final byte ANVIL = (byte) 6; + public static final byte ENCHANT_TABLE = (byte) 4; - public static final class PCInventory { - public static final byte CHEST = (byte) 0x0; - public static final byte WORKBENCH = (byte) 0x1; - public static final byte FURNANCE = (byte) 0x2; - public static final byte DISPENSER = (byte) 0x3; - public static final byte ENCHANTING_TABLE = (byte) 0x4; - public static final byte BREWING_STAND = (byte) 0x5; - public static final byte NPC_TRADE = (byte) 0x6; - public static final byte BEACON = (byte) 0x7; - public static final byte ANVIL = (byte) 0x8; - public static final byte HOPPER = (byte) 0x9; - public static final byte DROPPER = (byte) 0x10; - public static final byte HORSE = (byte) 0xa; + public static final byte toPEInventory(byte bytePC, int slots) { + switch (bytePC) { + case PCInventory.CHEST: + if (slots > 64) // Large + { + return PEInventory.DOUBLE_CHEST; + } else { + return PEInventory.CHEST; + } + case PCInventory.WORKBENCH: + return PEInventory.WORKBENCH; + case PCInventory.FURNANCE: + return PEInventory.FURNACE; + // case PCInventory.DISPENSER: + // case PCInventory.ENCHANTING_TABLE: + // case PCInventory.BREWING_STAND: + // case PCInventory.NPC_TRADE: + // case PCInventory.BEACON: + // case PCInventory.ANVIL: + // case PCInventory.HOPPER: + // case PCInventory.DROPPER: + // case PCInventory.HORSE: + default: + return (byte) 0xFF; + } + } - public static final byte fromString(String str) { - if (str.equals("minecraft:chest")) { - return PCInventory.CHEST; - } else if (str.equals("minecraft:crafting_table")) { - return PCInventory.WORKBENCH; - } else if (str.equals("minecraft:furnance")) { - return PCInventory.FURNANCE; - } else if (str.equals("minecraft:dispenser")) { - return PCInventory.DISPENSER; - } else if (str.equals("minecraft:enchanting_table")) { - return PCInventory.ENCHANTING_TABLE; - } else if (str.equals("minecraft:brewing_stand")) { - return PCInventory.BREWING_STAND; - } else if (str.equals("minecraft:villager")) { - return PCInventory.NPC_TRADE; - } else if (str.equals("minecraft:beacon")) { - return PCInventory.BEACON; - } else if (str.equals("minecraft:hopper")) { - return PCInventory.HOPPER; - } else if (str.equals("minecraft:dropper")) { - return PCInventory.DROPPER; - } else if (str.equals("EntityHorse")) { - return PCInventory.HORSE; - } - return (byte) 0xFF; - } - } + } - public static final class SlotSize { - public static final int CHEST = 27; - public static final int DOUBLE_CHEST = 27 + 27; - public static final int PLAYER = 36; - public static final int FURNACE = 3; - public static final int CRAFTING = 5; - public static final int WORKBENCH = 10; - public static final int STONECUTTER = 10; - public static final int ANVIL = 3; - } + public static final class PCInventory { + + public static final byte CHEST = (byte) 0x0; + public static final byte WORKBENCH = (byte) 0x1; + public static final byte FURNANCE = (byte) 0x2; + public static final byte DISPENSER = (byte) 0x3; + public static final byte ENCHANTING_TABLE = (byte) 0x4; + public static final byte BREWING_STAND = (byte) 0x5; + public static final byte NPC_TRADE = (byte) 0x6; + public static final byte BEACON = (byte) 0x7; + public static final byte ANVIL = (byte) 0x8; + public static final byte HOPPER = (byte) 0x9; + public static final byte DROPPER = (byte) 0x10; + public static final byte HORSE = (byte) 0xa; + + public static final byte fromString(String str) { + if (str.equals("minecraft:chest")) { + return PCInventory.CHEST; + } else if (str.equals("minecraft:crafting_table")) { + return PCInventory.WORKBENCH; + } else if (str.equals("minecraft:furnance")) { + return PCInventory.FURNANCE; + } else if (str.equals("minecraft:dispenser")) { + return PCInventory.DISPENSER; + } else if (str.equals("minecraft:enchanting_table")) { + return PCInventory.ENCHANTING_TABLE; + } else if (str.equals("minecraft:brewing_stand")) { + return PCInventory.BREWING_STAND; + } else if (str.equals("minecraft:villager")) { + return PCInventory.NPC_TRADE; + } else if (str.equals("minecraft:beacon")) { + return PCInventory.BEACON; + } else if (str.equals("minecraft:hopper")) { + return PCInventory.HOPPER; + } else if (str.equals("minecraft:dropper")) { + return PCInventory.DROPPER; + } else if (str.equals("EntityHorse")) { + return PCInventory.HORSE; + } + return (byte) 0xFF; + } + } + + public static final class SlotSize { + + public static final int CHEST = 27; + public static final int DOUBLE_CHEST = 27 + 27; + public static final int PLAYER = 36; + public static final int FURNACE = 3; + public static final int CRAFTING = 5; + public static final int WORKBENCH = 10; + public static final int STONECUTTER = 10; + public static final int ANVIL = 3; + } } diff --git a/src/main/java/org/dragonet/proxy/data/inventory/ItemList.java b/src/main/java/org/dragonet/proxy/data/inventory/ItemList.java index be2a6978a..5d5153528 100644 --- a/src/main/java/org/dragonet/proxy/data/inventory/ItemList.java +++ b/src/main/java/org/dragonet/proxy/data/inventory/ItemList.java @@ -20,76 +20,76 @@ import java.util.List; public class ItemList { - // vars - private List items; + // vars - // constructor - public ItemList() { - this.items = new ArrayList<>(); - } + private List items; - public ItemList(ArrayList items) { - this.items = items; - } + // constructor + public ItemList() { + this.items = new ArrayList<>(); + } - public ItemList(ItemStack[] items) { - this.items = Arrays.asList(items); - } + public ItemList(ArrayList items) { + this.items = items; + } - // public - public boolean tryToRemove(ItemStack item) { - ArrayList original = this.cloneList(); - if (item == null || item.getId() == 0) { - return true; - } - int toRemove = item.getAmount(); - for (int i = 0; i < items.size(); i++) { - if (toRemove == 0) { - break; - } - if (items.get(i) == null) { - continue; - } - int typeID = items.get(i).getId(); - int damage = items.get(i).getData(); - int amount = items.get(i).getAmount(); - CompoundTag nbt = items.get(i).getNBT(); - if (typeID == item.getId() && damage == item.getData()) { - // We found the item - if (amount > toRemove) { - // SUCCESS - items.set(i, new ItemStack(typeID, amount - toRemove, damage, nbt)); - return true; - } else { - items.set(i, null); - toRemove -= amount; - } - } - } - if (toRemove <= 0) { - return true; - } else { - this.items = original; - return false; - } - } + public ItemList(ItemStack[] items) { + this.items = Arrays.asList(items); + } - public List getItems() { - return items; - } + // public + public boolean tryToRemove(ItemStack item) { + ArrayList original = this.cloneList(); + if (item == null || item.getId() == 0) { + return true; + } + int toRemove = item.getAmount(); + for (int i = 0; i < items.size(); i++) { + if (toRemove == 0) { + break; + } + if (items.get(i) == null) { + continue; + } + int typeID = items.get(i).getId(); + int damage = items.get(i).getData(); + int amount = items.get(i).getAmount(); + CompoundTag nbt = items.get(i).getNBT(); + if (typeID == item.getId() && damage == item.getData()) { + // We found the item + if (amount > toRemove) { + // SUCCESS + items.set(i, new ItemStack(typeID, amount - toRemove, damage, nbt)); + return true; + } else { + items.set(i, null); + toRemove -= amount; + } + } + } + if (toRemove <= 0) { + return true; + } else { + this.items = original; + return false; + } + } - public ItemStack[] getContents() { - return this.items.toArray(new ItemStack[0]); - } + public List getItems() { + return items; + } - private ArrayList cloneList() { - ArrayList cloned = new ArrayList<>(); - for (ItemStack item : this.items) { - cloned.add(new ItemStack(item.getId(), item.getAmount(), item.getData(), item.getNBT())); - } - return cloned; - } + public ItemStack[] getContents() { + return this.items.toArray(new ItemStack[0]); + } - // private + private ArrayList cloneList() { + ArrayList cloned = new ArrayList<>(); + for (ItemStack item : this.items) { + cloned.add(new ItemStack(item.getId(), item.getAmount(), item.getData(), item.getNBT())); + } + return cloned; + } + // private } diff --git a/src/main/java/org/dragonet/proxy/data/inventory/PEWindowConstantID.java b/src/main/java/org/dragonet/proxy/data/inventory/PEWindowConstantID.java index 1fe82e88b..0207bbc83 100644 --- a/src/main/java/org/dragonet/proxy/data/inventory/PEWindowConstantID.java +++ b/src/main/java/org/dragonet/proxy/data/inventory/PEWindowConstantID.java @@ -13,15 +13,17 @@ package org.dragonet.proxy.data.inventory; public enum PEWindowConstantID { - PLAYER_INVENTORY(0x00), PLAYER_ARMOR(0x78), PLAYER_CREATIVE(0x79); + PLAYER_INVENTORY(0x00), + PLAYER_ARMOR(0x78), + PLAYER_CREATIVE(0x79); - private final byte id; + private final byte id; - PEWindowConstantID(int id) { - this.id = (byte) id; - } + PEWindowConstantID(int id) { + this.id = (byte) id; + } - public byte getId() { - return id; - } + public byte getId() { + return id; + } } diff --git a/src/main/java/org/dragonet/proxy/data/nbt/NBTIO.java b/src/main/java/org/dragonet/proxy/data/nbt/NBTIO.java index b59af791d..0bf94dcc9 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/NBTIO.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/NBTIO.java @@ -20,13 +20,14 @@ public class NBTIO { /** * A Named Binary Tag library for Nukkit Project */ - public static CompoundTag read(File file) throws IOException { return read(file, ByteOrder.BIG_ENDIAN); } public static CompoundTag read(File file, ByteOrder endianness) throws IOException { - if (!file.exists()) return null; + if (!file.exists()) { + return null; + } return read(new FileInputStream(file), endianness); } diff --git a/src/main/java/org/dragonet/proxy/data/nbt/stream/NBTInputStream.java b/src/main/java/org/dragonet/proxy/data/nbt/stream/NBTInputStream.java index ca0246965..ffb5dafe8 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/stream/NBTInputStream.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/stream/NBTInputStream.java @@ -10,10 +10,10 @@ import java.nio.charset.StandardCharsets; /** - * author: MagicDroidX - * Nukkit Project + * author: MagicDroidX Nukkit Project */ public class NBTInputStream implements DataInput, AutoCloseable { + private final DataInputStream stream; private final ByteOrder endianness; private final boolean network; diff --git a/src/main/java/org/dragonet/proxy/data/nbt/stream/NBTOutputStream.java b/src/main/java/org/dragonet/proxy/data/nbt/stream/NBTOutputStream.java index d43226425..f0688c085 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/stream/NBTOutputStream.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/stream/NBTOutputStream.java @@ -10,10 +10,10 @@ import java.nio.charset.StandardCharsets; /** - * author: MagicDroidX - * Nukkit Project + * author: MagicDroidX Nukkit Project */ public class NBTOutputStream implements DataOutput, AutoCloseable { + private final DataOutputStream stream; private final ByteOrder endianness; private final boolean network; diff --git a/src/main/java/org/dragonet/proxy/data/nbt/tag/ByteArrayTag.java b/src/main/java/org/dragonet/proxy/data/nbt/tag/ByteArrayTag.java index 8f251c149..2bf069292 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/tag/ByteArrayTag.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/tag/ByteArrayTag.java @@ -8,6 +8,7 @@ import java.util.Arrays; public class ByteArrayTag extends Tag { + public byte[] data; public ByteArrayTag(String name) { @@ -40,7 +41,7 @@ void load(NBTInputStream dis) throws IOException { public byte getId() { return TAG_Byte_Array; } - + @Override public Object getValue() { return this.data; diff --git a/src/main/java/org/dragonet/proxy/data/nbt/tag/ByteTag.java b/src/main/java/org/dragonet/proxy/data/nbt/tag/ByteTag.java index d2506d4df..8ae0fb753 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/tag/ByteTag.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/tag/ByteTag.java @@ -6,6 +6,7 @@ import java.io.IOException; public class ByteTag extends NumberTag { + public int data; @Override @@ -41,7 +42,7 @@ void load(NBTInputStream dis) throws IOException { public byte getId() { return TAG_Byte; } - + @Override public Object getValue() { return this.data; diff --git a/src/main/java/org/dragonet/proxy/data/nbt/tag/CompoundTag.java b/src/main/java/org/dragonet/proxy/data/nbt/tag/CompoundTag.java index 1f8034f72..a15a6a594 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/tag/CompoundTag.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/tag/CompoundTag.java @@ -10,6 +10,7 @@ import java.util.Map; public class CompoundTag extends Tag implements Cloneable { + private final Map tags = new HashMap<>(); public CompoundTag() { @@ -125,37 +126,51 @@ public CompoundTag remove(String name) { } public int getByte(String name) { - if (!tags.containsKey(name)) return (byte) 0; + if (!tags.containsKey(name)) { + return (byte) 0; + } return ((NumberTag) tags.get(name)).getData().intValue(); } public int getShort(String name) { - if (!tags.containsKey(name)) return 0; + if (!tags.containsKey(name)) { + return 0; + } return ((NumberTag) tags.get(name)).getData().intValue(); } public int getInt(String name) { - if (!tags.containsKey(name)) return 0; + if (!tags.containsKey(name)) { + return 0; + } return ((NumberTag) tags.get(name)).getData().intValue(); } public long getLong(String name) { - if (!tags.containsKey(name)) return (long) 0; + if (!tags.containsKey(name)) { + return (long) 0; + } return ((NumberTag) tags.get(name)).getData().longValue(); } public float getFloat(String name) { - if (!tags.containsKey(name)) return (float) 0; + if (!tags.containsKey(name)) { + return (float) 0; + } return ((NumberTag) tags.get(name)).getData().floatValue(); } public double getDouble(String name) { - if (!tags.containsKey(name)) return (double) 0; + if (!tags.containsKey(name)) { + return (double) 0; + } return ((NumberTag) tags.get(name)).getData().doubleValue(); } public String getString(String name) { - if (!tags.containsKey(name)) return ""; + if (!tags.containsKey(name)) { + return ""; + } Tag tag = tags.get(name); if (tag instanceof NumberTag) { return String.valueOf(((NumberTag) tag).getData()); @@ -164,23 +179,31 @@ public String getString(String name) { } public byte[] getByteArray(String name) { - if (!tags.containsKey(name)) return new byte[0]; + if (!tags.containsKey(name)) { + return new byte[0]; + } return ((ByteArrayTag) tags.get(name)).data; } public int[] getIntArray(String name) { - if (!tags.containsKey(name)) return new int[0]; + if (!tags.containsKey(name)) { + return new int[0]; + } return ((IntArrayTag) tags.get(name)).data; } public CompoundTag getCompound(String name) { - if (!tags.containsKey(name)) return new CompoundTag(name); + if (!tags.containsKey(name)) { + return new CompoundTag(name); + } return (CompoundTag) tags.get(name); } @SuppressWarnings("unchecked") public ListTag getList(String name) { - if (!tags.containsKey(name)) return new ListTag<>(name); + if (!tags.containsKey(name)) { + return new ListTag<>(name); + } return (ListTag) tags.get(name); } @@ -199,7 +222,7 @@ public Map getTags() { public boolean getBoolean(String name) { return getByte(name) != 0; } - + @Override public Object getValue() { return this.tags; diff --git a/src/main/java/org/dragonet/proxy/data/nbt/tag/DoubleTag.java b/src/main/java/org/dragonet/proxy/data/nbt/tag/DoubleTag.java index 4f91712a7..faa901de2 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/tag/DoubleTag.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/tag/DoubleTag.java @@ -6,6 +6,7 @@ import java.io.IOException; public class DoubleTag extends NumberTag { + public double data; @Override @@ -41,7 +42,7 @@ void load(NBTInputStream dis) throws IOException { public byte getId() { return TAG_Double; } - + @Override public Object getValue() { return this.data; diff --git a/src/main/java/org/dragonet/proxy/data/nbt/tag/EndTag.java b/src/main/java/org/dragonet/proxy/data/nbt/tag/EndTag.java index 787f77fef..53196b109 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/tag/EndTag.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/tag/EndTag.java @@ -23,7 +23,7 @@ void write(NBTOutputStream dos) throws IOException { public byte getId() { return TAG_End; } - + @Override public Object getValue() { return null; diff --git a/src/main/java/org/dragonet/proxy/data/nbt/tag/FloatTag.java b/src/main/java/org/dragonet/proxy/data/nbt/tag/FloatTag.java index d0d25fad4..c96e53204 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/tag/FloatTag.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/tag/FloatTag.java @@ -6,6 +6,7 @@ import java.io.IOException; public class FloatTag extends NumberTag { + public float data; @Override @@ -41,7 +42,7 @@ void load(NBTInputStream dis) throws IOException { public byte getId() { return TAG_Float; } - + @Override public Object getValue() { return this.data; diff --git a/src/main/java/org/dragonet/proxy/data/nbt/tag/IntArrayTag.java b/src/main/java/org/dragonet/proxy/data/nbt/tag/IntArrayTag.java index c17e12970..554e5e565 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/tag/IntArrayTag.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/tag/IntArrayTag.java @@ -7,6 +7,7 @@ import java.util.Arrays; public class IntArrayTag extends Tag { + public int[] data; public IntArrayTag(String name) { @@ -39,7 +40,7 @@ void load(NBTInputStream dis) throws IOException { public byte getId() { return TAG_Int_Array; } - + @Override public Object getValue() { return this.data; diff --git a/src/main/java/org/dragonet/proxy/data/nbt/tag/IntTag.java b/src/main/java/org/dragonet/proxy/data/nbt/tag/IntTag.java index aaa73a94a..d286fac4f 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/tag/IntTag.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/tag/IntTag.java @@ -6,6 +6,7 @@ import java.io.IOException; public class IntTag extends NumberTag { + public int data; @Override @@ -41,7 +42,7 @@ void load(NBTInputStream dis) throws IOException { public byte getId() { return TAG_Int; } - + @Override public Object getValue() { return this.data; diff --git a/src/main/java/org/dragonet/proxy/data/nbt/tag/ListTag.java b/src/main/java/org/dragonet/proxy/data/nbt/tag/ListTag.java index 65e138db8..31747b580 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/tag/ListTag.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/tag/ListTag.java @@ -25,12 +25,17 @@ public ListTag(String name) { @Override void write(NBTOutputStream dos) throws IOException { - if (list.size() > 0) type = list.get(0).getId(); - else type = 1; + if (list.size() > 0) { + type = list.get(0).getId(); + } else { + type = 1; + } dos.writeByte(type); dos.writeInt(list.size()); - for (T aList : list) aList.write(dos); + for (T aList : list) { + aList.write(dos); + } } @Override @@ -51,7 +56,7 @@ void load(NBTInputStream dis) throws IOException { public byte getId() { return TAG_List; } - + @Override public Object getValue() { return this.list; @@ -63,7 +68,9 @@ public void print(String prefix, PrintStream out) { out.println(prefix + "{"); String orgPrefix = prefix; prefix += " "; - for (T aList : list) aList.print(prefix, out); + for (T aList : list) { + aList.print(prefix, out); + } out.println(orgPrefix + "}"); } diff --git a/src/main/java/org/dragonet/proxy/data/nbt/tag/LongTag.java b/src/main/java/org/dragonet/proxy/data/nbt/tag/LongTag.java index d7de6eefd..c7af8d272 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/tag/LongTag.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/tag/LongTag.java @@ -6,6 +6,7 @@ import java.io.IOException; public class LongTag extends NumberTag { + public long data; @Override @@ -41,7 +42,7 @@ void load(NBTInputStream dis) throws IOException { public byte getId() { return TAG_Long; } - + @Override public Object getValue() { return this.data; diff --git a/src/main/java/org/dragonet/proxy/data/nbt/tag/NumberTag.java b/src/main/java/org/dragonet/proxy/data/nbt/tag/NumberTag.java index 63373ebc6..71cc6f200 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/tag/NumberTag.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/tag/NumberTag.java @@ -1,10 +1,10 @@ package org.dragonet.proxy.data.nbt.tag; /** - * author: MagicDroidX - * Nukkit Project + * author: MagicDroidX Nukkit Project */ public abstract class NumberTag extends Tag { + protected NumberTag(String name) { super(name); } diff --git a/src/main/java/org/dragonet/proxy/data/nbt/tag/ShortTag.java b/src/main/java/org/dragonet/proxy/data/nbt/tag/ShortTag.java index 54c76c53f..3ef7689de 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/tag/ShortTag.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/tag/ShortTag.java @@ -6,6 +6,7 @@ import java.io.IOException; public class ShortTag extends NumberTag { + public int data; @Override @@ -41,10 +42,9 @@ void load(NBTInputStream dis) throws IOException { public byte getId() { return TAG_Short; } - + @Override - public Object getValue() - { + public Object getValue() { return this.data; } diff --git a/src/main/java/org/dragonet/proxy/data/nbt/tag/StringTag.java b/src/main/java/org/dragonet/proxy/data/nbt/tag/StringTag.java index a13be9be3..9211821bb 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/tag/StringTag.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/tag/StringTag.java @@ -6,6 +6,7 @@ import java.io.IOException; public class StringTag extends Tag { + public String data; public StringTag(String name) { @@ -15,7 +16,9 @@ public StringTag(String name) { public StringTag(String name, String data) { super(name); this.data = data; - if (data == null) throw new IllegalArgumentException("Empty string not allowed"); + if (data == null) { + throw new IllegalArgumentException("Empty string not allowed"); + } } @Override @@ -32,7 +35,7 @@ void load(NBTInputStream dis) throws IOException { public byte getId() { return TAG_String; } - + @Override public Object getValue() { return this.data; diff --git a/src/main/java/org/dragonet/proxy/data/nbt/tag/Tag.java b/src/main/java/org/dragonet/proxy/data/nbt/tag/Tag.java index 6750ad789..0029e5c08 100644 --- a/src/main/java/org/dragonet/proxy/data/nbt/tag/Tag.java +++ b/src/main/java/org/dragonet/proxy/data/nbt/tag/Tag.java @@ -8,6 +8,7 @@ import java.lang.reflect.Array; public abstract class Tag { + public static final byte TAG_End = 0; public static final byte TAG_Byte = 1; public static final byte TAG_Short = 2; @@ -74,13 +75,17 @@ public Tag setName(String name) { } public String getName() { - if (name == null) return ""; + if (name == null) { + return ""; + } return name; } public static Tag readNamedTag(NBTInputStream dis) throws IOException { byte type = dis.readByte(); - if (type == 0) return new EndTag(); + if (type == 0) { + return new EndTag(); + } String name = dis.readUTF(); @@ -92,7 +97,9 @@ public static Tag readNamedTag(NBTInputStream dis) throws IOException { public static void writeNamedTag(Tag tag, NBTOutputStream dos) throws IOException { dos.writeByte(tag.getId()); - if (tag.getId() == Tag.TAG_End) return; + if (tag.getId() == Tag.TAG_End) { + return; + } dos.writeUTF(tag.getName()); tag.write(dos); @@ -157,18 +164,18 @@ public static String getTagName(byte type) { } return "UNKNOWN"; } - + @Override public String toString() { String name = this.getName() != null && !this.getName().equals("") ? "(" + this.getName() + ")" : ""; String value = ""; - if(this.getValue() != null) { + if (this.getValue() != null) { value = this.getValue().toString(); - if(this.getValue().getClass().isArray()) { + if (this.getValue().getClass().isArray()) { StringBuilder build = new StringBuilder(); build.append("["); - for(int index = 0; index < Array.getLength(this.getValue()); index++) { - if(index > 0) { + for (int index = 0; index < Array.getLength(this.getValue()); index++) { + if (index > 0) { build.append(", "); } diff --git a/src/main/java/org/dragonet/proxy/network/InventoryTranslatorRegister.java b/src/main/java/org/dragonet/proxy/network/InventoryTranslatorRegister.java index 5b4f61639..4a8ff3c8f 100644 --- a/src/main/java/org/dragonet/proxy/network/InventoryTranslatorRegister.java +++ b/src/main/java/org/dragonet/proxy/network/InventoryTranslatorRegister.java @@ -66,12 +66,10 @@ public static PEPacket[] sendPlayerInventory(UpstreamSession session) { public static void open(UpstreamSession session, ServerOpenWindowPacket win) { closeOpened(session, true); if (TRANSLATORS.containsKey(win.getType())) { - CachedWindow cached = new CachedWindow(win.getWindowId(), win.getType(), 36 + win.getSlots()); + CachedWindow cached = new CachedWindow(win.getWindowId(), win.getType(), win.getSlots()); session.getWindowCache().cacheWindow(cached); TRANSLATORS.get(win.getType()).open(session, cached); - - com.github.steveice10.packetlib.packet.Packet[] items = session.getWindowCache() - .getCachedPackets(win.getWindowId()); + com.github.steveice10.packetlib.packet.Packet[] items = session.getWindowCache().getCachedPackets(win.getWindowId()); for (com.github.steveice10.packetlib.packet.Packet item : items) { if (item != null) { if (ServerWindowItemsPacket.class.isAssignableFrom(item.getClass())) { @@ -81,6 +79,7 @@ public static void open(UpstreamSession session, ServerOpenWindowPacket win) { } } } + System.out.println("Window " + win.getWindowId() + " opened !"); } else { // Not supported session.getDownstream().send(new ClientCloseWindowPacket(win.getWindowId())); @@ -91,35 +90,20 @@ public static void closeOpened(UpstreamSession session, boolean byServer) { if (session.getDataCache().containsKey(CacheKey.WINDOW_OPENED_ID)) { // There is already a window opened int id = (int) session.getDataCache().remove(CacheKey.WINDOW_OPENED_ID); - if (!byServer) { - session.getDownstream().send(new ContainerClosePacket((byte) (id & 0xFF))); + System.out.println("Window " + id + " closed !"); + if (byServer) { + session.sendPacket(new ContainerClosePacket(id), true); + } else { + session.getDownstream().send(new ClientCloseWindowPacket(id)); } if (session.getDataCache().containsKey(CacheKey.WINDOW_BLOCK_POSITION)) { // Already a block was replaced to Chest, reset it session.sendFakeBlock(((Position) session.getDataCache().get(CacheKey.WINDOW_BLOCK_POSITION)).getX(), ((Position) session.getDataCache().get(CacheKey.WINDOW_BLOCK_POSITION)).getY(), - ((Position) session.getDataCache().remove(CacheKey.WINDOW_BLOCK_POSITION)).getZ(), 1, // Set to - // stone - // since - // we - // don't - // know - // what - // it - // was, - // server - // will - // correct - // it - // once - // client - // interacts - // it + ((Position) session.getDataCache().remove(CacheKey.WINDOW_BLOCK_POSITION)).getZ(), 1, + // Set to stone since we don't know what it was, server will correct it once client interacts it 0); } - if (byServer) { - session.sendPacket(new ContainerClosePacket((byte) (id & 0xFF)), true); - } } } diff --git a/src/main/java/org/dragonet/proxy/network/PacketTranslatorRegister.java b/src/main/java/org/dragonet/proxy/network/PacketTranslatorRegister.java index 363d8a6c5..0b2affbe4 100644 --- a/src/main/java/org/dragonet/proxy/network/PacketTranslatorRegister.java +++ b/src/main/java/org/dragonet/proxy/network/PacketTranslatorRegister.java @@ -34,6 +34,8 @@ import com.github.steveice10.mc.protocol.packet.ingame.server.entity.player.ServerPlayerHealthPacket; import com.github.steveice10.mc.protocol.packet.ingame.server.entity.player.ServerPlayerSetExperiencePacket; import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnMobPacket; +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnPaintingPacket; +import com.github.steveice10.mc.protocol.packet.ingame.server.window.ServerCloseWindowPacket; import org.dragonet.proxy.protocol.PEPacket; import org.dragonet.proxy.protocol.packets.*; @@ -88,9 +90,12 @@ public final class PacketTranslatorRegister { PC_TO_PE_TRANSLATOR.put(ServerRespawnPacket.class, new PCRespawnPacketTranslator()); PC_TO_PE_TRANSLATOR.put(ServerSpawnPositionPacket.class, new PCSpawnPositionPacketTranslator()); PC_TO_PE_TRANSLATOR.put(ServerPlayerSetExperiencePacket.class, new PCSetExperiencePacketTranslator()); + PC_TO_PE_TRANSLATOR.put(ServerSpawnPaintingPacket.class, new PCSpawnPaintingPacketTranslator()); + PC_TO_PE_TRANSLATOR.put(ServerUpdateTileEntityPacket.class, new PCUpdateTileEntityPacketTranslator()); // // //Inventory PC_TO_PE_TRANSLATOR.put(ServerOpenWindowPacket.class, new PCOpenWindowPacketTranslator()); + PC_TO_PE_TRANSLATOR.put(ServerCloseWindowPacket.class, new PCClosedWindowPacketTranslator()); PC_TO_PE_TRANSLATOR.put(ServerWindowItemsPacket.class, new PCWindowItemsTranslator()); PC_TO_PE_TRANSLATOR.put(ServerSetSlotPacket.class, new PCSetSlotPacketTranslator()); diff --git a/src/main/java/org/dragonet/proxy/network/UpstreamSession.java b/src/main/java/org/dragonet/proxy/network/UpstreamSession.java index 9a7e0d74e..395e0e8cc 100644 --- a/src/main/java/org/dragonet/proxy/network/UpstreamSession.java +++ b/src/main/java/org/dragonet/proxy/network/UpstreamSession.java @@ -29,6 +29,7 @@ import org.dragonet.proxy.DragonProxy; import org.dragonet.proxy.configuration.Lang; import org.dragonet.proxy.configuration.RemoteServer; +import org.dragonet.proxy.data.entity.EntityType; import org.dragonet.proxy.network.cache.EntityCache; import org.dragonet.proxy.network.cache.WindowCache; import org.dragonet.proxy.protocol.PEPacket; @@ -320,7 +321,7 @@ public void postLogin() { pkStartGame.seed = 0; pkStartGame.generator = 1; pkStartGame.spawnPosition = new BlockPosition(0, 72, 0); - pkStartGame.position = new Vector3F(0f, 72f + Constants.PLAYER_HEAD_OFFSET, 0f); + pkStartGame.position = new Vector3F(0f, 72f + EntityType.PLAYER.getOffset(), 0f); pkStartGame.levelId = ""; pkStartGame.worldName = "World"; pkStartGame.defaultPlayerPermission = 2; @@ -411,39 +412,7 @@ public void postLogin() { connectToServer(proxy.getConfig().remote_servers.get(proxy.getConfig().default_server)); } else { protocol = new MinecraftProtocol(username); - proxy.getLogger().debug("Initially joining [" + proxy.getConfig().default_server + "]... "); - - /* - * // begin test things StartGamePacket pkStartGame = new StartGamePacket(); - * pkStartGame.eid = 0; //Use EID 0 for eaisier management pkStartGame.rtid = 0; - * pkStartGame.dimension = (byte) 0; pkStartGame.seed = 0; pkStartGame.generator - * = 1; pkStartGame.position = new Vector3F(0f, 72f, 0f); pkStartGame.levelId = - * ""; pkStartGame.worldName = "World"; pkStartGame.spawnPosition = new - * BlockPosition(0, 0, 0); pkStartGame.premiumWorldTemplateId = ""; - * sendPacket(pkStartGame, true); - * - * PlayStatusPacket pkStat = new PlayStatusPacket(); pkStat.status = - * PlayStatusPacket.PLAYER_SPAWN; sendPacket(pkStat, true); - * - * AdventureSettingsPacket adv = new AdventureSettingsPacket(); - * adv.setFlag(AdventureSettingsPacket.AUTO_JUMP, true); - * adv.setFlag(AdventureSettingsPacket.ALLOW_FLIGHT, true); sendPacket(adv); - * - * for(int x = -7; x < 8; x ++) { for(int z = -7; z < 8; z ++) { - * org.dragonet.proxy.protocol.type.chunk.ChunkData c = new ChunkData(); - * c.sections = new org.dragonet.proxy.protocol.type.chunk.Section[16]; for(int - * cy = 0; cy < 16; cy++) { c.sections[cy] = new - * org.dragonet.proxy.protocol.type.chunk.Section(); if(cy < 4) { - * Arrays.fill(c.sections[cy].blockIds, (byte)1); } } - * org.dragonet.proxy.protocol.packets.FullChunkDataPacket p = new - * org.dragonet.proxy.protocol.packets.FullChunkDataPacket(); p.x = x; p.z = z; - * c.encode(); p.payload = c.getBuffer(); sendPacket(p); } } - * - * // InventoryContentPacket content = new InventoryContentPacket(); // - * content.items = new org.dragonet.proxy.protocol.type.Slot[36]; // - * sendPacket(content); // end of test things - */ connectToServer(proxy.getConfig().remote_servers.get(proxy.getConfig().default_server)); } } diff --git a/src/main/java/org/dragonet/proxy/network/cache/CachedEntity.java b/src/main/java/org/dragonet/proxy/network/cache/CachedEntity.java index 8b13783a3..e053f10e7 100644 --- a/src/main/java/org/dragonet/proxy/network/cache/CachedEntity.java +++ b/src/main/java/org/dragonet/proxy/network/cache/CachedEntity.java @@ -23,6 +23,9 @@ import com.github.steveice10.mc.protocol.data.game.entity.EquipmentSlot; import com.github.steveice10.mc.protocol.data.game.entity.metadata.EntityMetadata; import com.github.steveice10.mc.protocol.data.game.entity.type.object.ObjectType; +import java.util.HashMap; +import java.util.Map; +import org.dragonet.proxy.data.entity.PEEntityAttribute; import org.dragonet.proxy.utilities.BlockPosition; public class CachedEntity { @@ -61,6 +64,7 @@ public class CachedEntity { public EntityMetadata[] pcMeta; public boolean spawned; public final Set effects = Collections.synchronizedSet(new HashSet()); + public Map attributes = Collections.synchronizedMap(new HashMap()); public CachedEntity(long eid, long proxyEid, int pcType, EntityType peType, ObjectType objType, boolean player, UUID playerUniqueId) { diff --git a/src/main/java/org/dragonet/proxy/network/cache/CachedWindow.java b/src/main/java/org/dragonet/proxy/network/cache/CachedWindow.java index 2883f5335..ebcca7db7 100644 --- a/src/main/java/org/dragonet/proxy/network/cache/CachedWindow.java +++ b/src/main/java/org/dragonet/proxy/network/cache/CachedWindow.java @@ -35,7 +35,7 @@ public class CachedWindow { public CachedWindow(int windowId, WindowType pcType, int size) { this.windowId = windowId; this.pcType = pcType; - this.size = size; + this.size = size + 36; //add player inventory slots slots = new ItemStack[this.size]; } diff --git a/src/main/java/org/dragonet/proxy/network/cache/EntityCache.java b/src/main/java/org/dragonet/proxy/network/cache/EntityCache.java index abb44e402..e8ecc2233 100644 --- a/src/main/java/org/dragonet/proxy/network/cache/EntityCache.java +++ b/src/main/java/org/dragonet/proxy/network/cache/EntityCache.java @@ -17,20 +17,17 @@ import com.github.steveice10.mc.protocol.data.MagicValues; import com.github.steveice10.mc.protocol.data.game.entity.type.object.ObjectType; -import com.github.steveice10.mc.protocol.packet.ingame.server.ServerJoinGamePacket; import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnExpOrbPacket; import org.dragonet.proxy.data.entity.EntityType; import org.dragonet.proxy.network.UpstreamSession; import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnMobPacket; import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnObjectPacket; +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnPaintingPacket; import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnPlayerPacket; -import org.dragonet.proxy.network.CacheKey; import org.dragonet.proxy.network.translator.EntityMetaTranslator; -import org.dragonet.proxy.utilities.Constants; public final class EntityCache { - // vars private final UpstreamSession upstream; // proxy eid -> entity @@ -44,13 +41,11 @@ public final class EntityCache { private final Map mapRemoteToClient = Collections.synchronizedMap(new HashMap<>()); private final Map mapClientToRemote = Collections.synchronizedMap(new HashMap<>()); - // constructor public EntityCache(UpstreamSession upstream) { this.upstream = upstream; reset(false); } - // public public UpstreamSession getUpstream() { return upstream; } @@ -73,6 +68,13 @@ public CachedEntity getClientEntity() { return entities.get(1L); } + public void updateClientEntityEID(long eid) { + CachedEntity clientEntity = entities.get(1L); + clientEntity.eid = eid; + mapClientToRemote.put(clientEntity.proxyEid, clientEntity.eid); + mapRemoteToClient.put(clientEntity.eid, clientEntity.proxyEid); + } + public CachedEntity getByRemoteEID(long eid) { if (!mapRemoteToClient.containsKey(eid)) { return null; @@ -128,6 +130,16 @@ public CachedEntity newEntity(ServerSpawnMobPacket packet) { return e; } + public CachedEntity newEntity(ServerSpawnPaintingPacket packet) { + CachedEntity e = new CachedEntity(packet.getEntityId(), nextClientEntityId.getAndIncrement(), -1, EntityType.PAINTING, null, false, null); + e.absoluteMove(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ(), 0, 0); + e.spawned = false; + entities.put(e.proxyEid, e); + mapClientToRemote.put(e.proxyEid, e.eid); + mapRemoteToClient.put(e.eid, e.proxyEid); + return e; + } + public CachedEntity newPlayer(ServerSpawnPlayerPacket packet) { CachedEntity e = new CachedEntity(packet.getEntityId(), nextClientEntityId.getAndIncrement(), -1, EntityType.PLAYER, null, true, packet.getUUID()); e.absoluteMove(packet.getX(), packet.getY(), packet.getZ(), packet.getYaw(), packet.getPitch()); @@ -193,6 +205,4 @@ public void onTick() { * e.z += e.motionZ; return e; }); */ } - - // private } diff --git a/src/main/java/org/dragonet/proxy/network/translator/EntityMetaTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/EntityMetaTranslator.java index 312d6b487..c9013c3a3 100644 --- a/src/main/java/org/dragonet/proxy/network/translator/EntityMetaTranslator.java +++ b/src/main/java/org/dragonet/proxy/network/translator/EntityMetaTranslator.java @@ -234,7 +234,7 @@ public static EntityMetaData translateToPE(UpstreamSession session, EntityMetada case ARMOR_STAND: //Rotation : Head rotation break; case BAT: //Byte : Is hanging - peMeta.setGenericFlag(EntityMetaData.Constants.DATA_FLAG_SITTING, ((boolean) m.getValue())); +// peMeta.setGenericFlag(EntityMetaData.Constants.DATA_FLAG_SITTING, (((byte) m.getValue()) ? 0x01 : 0x00)); //wrong data break; case IRONGOLEM: //Byte : Is player-created case SNOWMAN: //Byte : has no pumpkin hat diff --git a/src/main/java/org/dragonet/proxy/network/translator/ItemBlockTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/ItemBlockTranslator.java index c754b9f1e..c67bad216 100644 --- a/src/main/java/org/dragonet/proxy/network/translator/ItemBlockTranslator.java +++ b/src/main/java/org/dragonet/proxy/network/translator/ItemBlockTranslator.java @@ -18,6 +18,7 @@ import com.github.steveice10.mc.protocol.data.game.entity.metadata.ItemStack; import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace; +import com.github.steveice10.mc.protocol.data.message.Message; import com.github.steveice10.opennbt.tag.builtin.CompoundTag; import com.github.steveice10.opennbt.tag.builtin.IntTag; import com.github.steveice10.opennbt.tag.builtin.StringTag; @@ -36,6 +37,7 @@ public class ItemBlockTranslator { public static final Map NAME_OVERRIDES = new HashMap<>(); static { + //BLOCKS toPEOverride(36, 248); //unkown block swap(125, 157); // double_wooden_slab swap(126, 158); // wooden_slab @@ -57,7 +59,6 @@ public class ItemBlockTranslator { swap(192, new ItemEntry(85, 4)); //acacia_fence swap(203, 202); //purpur_stairs swap(205, 248); //purpur_slab -> unknown - //shulker_box swap(219, new ItemEntry(218, 0)); //white swap(220, new ItemEntry(218, 1)); //orange @@ -75,7 +76,6 @@ public class ItemBlockTranslator { swap(232, new ItemEntry(218, 13)); //green swap(233, new ItemEntry(218, 14)); //red swap(234, new ItemEntry(218, 15)); //black - //glazed terracota swap(235, 220); //white swap(236, 221); //orange @@ -93,22 +93,47 @@ public class ItemBlockTranslator { swap(248, 233); //green swap(249, 234); //red swap(250, 235); //black - swap(251, 236); //concrete swap(252, 237); //concretepowder - swap(218, 251); //observer swap(207, 244); //beetroots swap(255, 252); //structure_block + //ITEMS + swap(416, 425); //armor_stand horsearmorleather + toPCOverride(425, 417); //horsearmorleather horsearmoriron (unavailable on PC) + + swap(443, 444); //elytra + + swap(444, new ItemEntry(333, 1)); //spruce_boat + swap(445, new ItemEntry(333, 2)); //birch_boat + swap(446, new ItemEntry(333, 3)); //jungle_boat + swap(447, new ItemEntry(333, 4)); //acacia_boat + swap(448, new ItemEntry(333, 5)); //dark_oak_boat + + swap(449, 450); //totem shulker_shell + + swap(2256, 500); //record_13 + swap(2257, 501); //record_cat + swap(2258, 502); //record_blocks + swap(2259, 503); //record_chirp + swap(2260, 504); //record_far + swap(2261, 505); //record_far + swap(2262, 506); //record_mellohi + swap(2263, 507); //record_stal + swap(2264, 508); //record_strad + swap(2265, 509); //record_ward + swap(2265, 510); //record_11 + swap(2265, 511); //record_wait + //TODO: replace podzol } public static ItemEntry translateToPE(int pcItemBlockId, int damage) { ItemEntry entry = new ItemEntry(pcItemBlockId, damage); - - //here translate item data value (color / facing ....) need another translator items specific + //here translate item data value (color / facing ....) need another translator items specific + // see https://minecraft.gamepedia.com/Block_states if (!PC_TO_PE_OVERRIDE.containsKey(pcItemBlockId)) { return entry; } @@ -146,14 +171,14 @@ public static Slot translateSlotToPE(ItemStack item) { slot.id = entry.id; slot.damage = entry.damage != null ? entry.damage : item.getData(); slot.count = (item.getAmount() & 0xff); - org.dragonet.proxy.data.nbt.tag.CompoundTag tag = new org.dragonet.proxy.data.nbt.tag.CompoundTag(); - tag.putShort("id", item.getId()); - tag.putShort("amount", item.getAmount()); - tag.putShort("data", item.getData()); - org.dragonet.proxy.data.nbt.tag.CompoundTag rootTag = new org.dragonet.proxy.data.nbt.tag.CompoundTag(); - rootTag.put(DRAGONET_COMPOUND, tag); - slot.tag = rootTag; - translateRawNBT(item.getId(), item.getNBT(), slot.tag); +// org.dragonet.proxy.data.nbt.tag.CompoundTag tag = new org.dragonet.proxy.data.nbt.tag.CompoundTag(); +// tag.putShort("id", item.getId()); +// tag.putShort("amount", item.getAmount()); +// tag.putShort("data", item.getData()); +// org.dragonet.proxy.data.nbt.tag.CompoundTag rootTag = new org.dragonet.proxy.data.nbt.tag.CompoundTag(); +// rootTag.put(DRAGONET_COMPOUND, tag); +// slot.tag = rootTag; + slot.tag = translateRawNBT(item.getId(), item.getNBT(), null); return slot; } @@ -222,7 +247,7 @@ public static org.dragonet.proxy.data.nbt.tag.CompoundTag translateBlockEntityTo switch (output.getString("id")) { case "minecraft:bed": output.putString("id", "Bed"); - output.putByte("color", output.getInt("color")); //TODO check colors + output.putByte("color", 0); //TODO check colors break; case "minecraft:chest": output.putString("id", "Chest"); @@ -235,9 +260,24 @@ public static org.dragonet.proxy.data.nbt.tag.CompoundTag translateBlockEntityTo break; case "minecraft:sign": output.putString("id", "Sign"); + if (!output.contains("Text")) { + output.putString("Text", + Message.fromString(output.getString("Text1")).getFullText() + + "\n" + Message.fromString(output.getString("Text2")).getFullText() + + "\n" + Message.fromString(output.getString("Text3")).getFullText() + + "\n" + Message.fromString(output.getString("Text4")).getFullText()); + } + output.remove("Text1"); + output.remove("Text2"); + output.remove("Text3"); + output.remove("Text4"); break; case "minecraft:flower_pot": output.putString("id", "FlowerPot"); + output.putInt("data", output.getInt("Data")); + output.remove("Data"); + output.putShort("item", 0); + output.remove("Item"); break; case "minecraft:hopper": output.putString("id", "Hopper"); @@ -292,7 +332,8 @@ public static org.dragonet.proxy.data.nbt.tag.CompoundTag translateBlockEntityTo break; } } - output.putBoolean("isMovable", false); +// if (output.getString("id") == "ShulkerBox" || output.getString("id") == "Bed" || output.getString("id") == "Chest") +// System.out.println("translateBlockEntityToPE " + output.toString()); return output; } @@ -340,6 +381,14 @@ private static void toPEOverride(int fromPc, ItemEntry toPe) { PC_TO_PE_OVERRIDE.put(fromPc, toPe); } + private static void toPCOverride(int fromEc, int toPc) { + PE_TO_PC_OVERRIDE.put(fromEc, new ItemEntry(toPc)); + } + + private static void toPCOverride(int fromPc, ItemEntry toPe) { + PE_TO_PC_OVERRIDE.put(fromPc, toPe); + } + public static CompoundTag newTileTag(String id, int x, int y, int z) { CompoundTag t = new CompoundTag(null); t.put(new StringTag("id", id)); diff --git a/src/main/java/org/dragonet/proxy/network/translator/inv/ChestWindowTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/inv/ChestWindowTranslator.java index f059cab70..6d1828d70 100644 --- a/src/main/java/org/dragonet/proxy/network/translator/inv/ChestWindowTranslator.java +++ b/src/main/java/org/dragonet/proxy/network/translator/inv/ChestWindowTranslator.java @@ -12,11 +12,7 @@ */ package org.dragonet.proxy.network.translator.inv; -import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position; import com.github.steveice10.opennbt.tag.builtin.CompoundTag; -import com.github.steveice10.opennbt.tag.builtin.IntTag; -import com.github.steveice10.opennbt.tag.builtin.StringTag; - import org.dragonet.proxy.data.inventory.InventoryType; import org.dragonet.proxy.network.CacheKey; import org.dragonet.proxy.network.UpstreamSession; @@ -26,34 +22,31 @@ import org.dragonet.proxy.protocol.packets.BlockEntityDataPacket; import org.dragonet.proxy.protocol.packets.ContainerOpenPacket; import org.dragonet.proxy.protocol.packets.InventoryContentPacket; +import org.dragonet.proxy.protocol.packets.InventorySlotPacket; import org.dragonet.proxy.protocol.type.Slot; import org.dragonet.proxy.utilities.BlockPosition; public class ChestWindowTranslator implements IInventoryTranslator { public boolean open(UpstreamSession session, CachedWindow window) { - Position pos = new Position((int) session.getEntityCache().getClientEntity().x, + BlockPosition pos = new BlockPosition((int) session.getEntityCache().getClientEntity().x, (int) session.getEntityCache().getClientEntity().y - 4, (int) session.getEntityCache().getClientEntity().z); + session.getDataCache().put(CacheKey.WINDOW_OPENED_ID, window.windowId); session.getDataCache().put(CacheKey.WINDOW_BLOCK_POSITION, pos); - session.sendFakeBlock(pos.getX(), pos.getY(), pos.getZ(), 54, 0); - CompoundTag tag = new CompoundTag(null); - tag.put(new StringTag("id", "Chest")); - tag.put(new IntTag("x", pos.getX())); - tag.put(new IntTag("y", pos.getY())); - tag.put(new IntTag("z", pos.getZ())); + session.sendFakeBlock(pos.x, pos.y, pos.z, 54, 0); + BlockEntityDataPacket blockEntityData = new BlockEntityDataPacket(); - blockEntityData.blockPosition = new BlockPosition(pos.getX(), pos.getY(), pos.getZ()); - blockEntityData.tag = tag; + blockEntityData.blockPosition = new BlockPosition(pos.x, pos.y, pos.z); + blockEntityData.tag = ItemBlockTranslator.translateBlockEntityToPE(ItemBlockTranslator.newTileTag("Chest", pos.x, pos.y, pos.z)); session.sendPacket(blockEntityData); ContainerOpenPacket pk = new ContainerOpenPacket(); + pk.eid = -1; pk.windowId = window.windowId; - // pk. = window.size <= 27 ? (short)(InventoryType.SlotSize.CHEST & 0xFFFF) : - // (short)(InventoryType.SlotSize.DOUBLE_CHEST & 0xFFFF); pk.type = window.size <= 27 ? InventoryType.PEInventory.CHEST : InventoryType.PEInventory.DOUBLE_CHEST; - pk.position = new BlockPosition(pos.getX(), pos.getY(), pos.getZ()); + pk.position = new BlockPosition(pos.x, pos.y, pos.z); session.sendPacket(pk); return true; } @@ -62,17 +55,24 @@ public void updateContent(UpstreamSession session, CachedWindow window) { sendContent(session, window); } - public void updateSlot(UpstreamSession session, CachedWindow window, int slotIndex) { - sendContent(session, window);// TOO LAZY LOL + public void updateSlot(UpstreamSession session, CachedWindow win, int slotIndex) { + InventorySlotPacket pk = new InventorySlotPacket(); + pk.item = ItemBlockTranslator.translateSlotToPE(win.slots[slotIndex]); + pk.slotId = slotIndex; + pk.windowId = win.windowId; + session.sendPacket(pk, true); + System.out.println("update window " + + win.windowId + " slot " + slotIndex); +// sendContent(session, window);// TOO LAZY LOL } private void sendContent(UpstreamSession session, CachedWindow win) { InventoryContentPacket pk = new InventoryContentPacket(); - pk.windowId = (byte) (win.windowId & 0xFF); + pk.windowId = win.windowId; pk.items = new Slot[win.slots.length]; for (int i = 0; i < pk.items.length; i++) { pk.items[i] = ItemBlockTranslator.translateSlotToPE(win.slots[i]); } session.sendPacket(pk, true); + System.out.println("update window " + + win.windowId + " set all content"); } } diff --git a/src/main/java/org/dragonet/proxy/network/translator/pc/PCBlockChangePacketTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/pc/PCBlockChangePacketTranslator.java index 678b714eb..0d66cca40 100644 --- a/src/main/java/org/dragonet/proxy/network/translator/pc/PCBlockChangePacketTranslator.java +++ b/src/main/java/org/dragonet/proxy/network/translator/pc/PCBlockChangePacketTranslator.java @@ -18,20 +18,34 @@ import org.dragonet.proxy.network.translator.IPCPacketTranslator; import org.dragonet.proxy.network.translator.ItemBlockTranslator.ItemEntry; import org.dragonet.proxy.protocol.PEPacket; +import org.dragonet.proxy.protocol.packets.BlockEventPacket; import org.dragonet.proxy.protocol.packets.UpdateBlockPacket; import org.dragonet.proxy.utilities.BlockPosition; +import org.dragonet.proxy.utilities.DebugTools; +import org.dragonet.proxy.utilities.Vector3F; public class PCBlockChangePacketTranslator implements IPCPacketTranslator { public PEPacket[] translate(UpstreamSession session, ServerBlockChangePacket packet) { - UpdateBlockPacket pk = new UpdateBlockPacket(); - pk.flags = UpdateBlockPacket.FLAG_NEIGHBORS << 4; ItemEntry entry = ItemBlockTranslator.translateToPE(packet.getRecord().getBlock().getId(), packet.getRecord().getBlock().getData()); - - pk.data = entry.damage; - pk.id = entry.id; - pk.blockPosition = new BlockPosition(packet.getRecord().getPosition().getX(), - packet.getRecord().getPosition().getY(), packet.getRecord().getPosition().getZ()); - return new PEPacket[]{pk}; +// if (entry.id == 54) { // chest case +//// System.out.println(DebugTools.getAllFields(packet)); +// BlockEventPacket pk1 = new BlockEventPacket(); +// pk1.x = packet.getRecord().getPosition().getX(); +// pk1.y = packet.getRecord().getPosition().getY(); +// pk1.z = packet.getRecord().getPosition().getZ(); +// pk1.case1 = 1; +// pk1.case2 = 2; +// session.sendPacket(pk1); +// } else { + UpdateBlockPacket pk = new UpdateBlockPacket(); + pk.flags = UpdateBlockPacket.FLAG_NEIGHBORS << 4; + pk.data = entry.damage; + pk.id = entry.id; + pk.blockPosition = new BlockPosition(packet.getRecord().getPosition().getX(), + packet.getRecord().getPosition().getY(), packet.getRecord().getPosition().getZ()); + return new PEPacket[]{pk}; +// } +// return null; } } diff --git a/src/main/java/org/dragonet/proxy/network/translator/pc/PCClosedWindowPacketTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/pc/PCClosedWindowPacketTranslator.java new file mode 100644 index 000000000..b954af87e --- /dev/null +++ b/src/main/java/org/dragonet/proxy/network/translator/pc/PCClosedWindowPacketTranslator.java @@ -0,0 +1,30 @@ +/* + * GNU LESSER GENERAL PUBLIC LICENSE + * Version 3, 29 June 2007 + * + * Copyright (C) 2007 Free Software Foundation, Inc. + * Everyone is permitted to copy and distribute verbatim copies + * of this license document, but changing it is not allowed. + * + * You can view LICENCE file for details. + * + * @author The Dragonet Team + */ +package org.dragonet.proxy.network.translator.pc; + +import com.github.steveice10.mc.protocol.packet.ingame.server.window.ServerCloseWindowPacket; +import org.dragonet.proxy.network.InventoryTranslatorRegister; +import org.dragonet.proxy.network.UpstreamSession; +import org.dragonet.proxy.network.translator.IPCPacketTranslator; +import org.dragonet.proxy.protocol.PEPacket; + +public class PCClosedWindowPacketTranslator implements IPCPacketTranslator { + + public PEPacket[] translate(UpstreamSession session, ServerCloseWindowPacket packet) { + System.out.println("Window " + packet.getWindowId() + " closed from server !"); + session.getProxy().getGeneralThreadPool().execute(() -> { + InventoryTranslatorRegister.closeOpened(session, true); + }); + return null; + } +} diff --git a/src/main/java/org/dragonet/proxy/network/translator/pc/PCEntityMetadataPacketTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/pc/PCEntityMetadataPacketTranslator.java index 45978c245..02924c8d0 100644 --- a/src/main/java/org/dragonet/proxy/network/translator/pc/PCEntityMetadataPacketTranslator.java +++ b/src/main/java/org/dragonet/proxy/network/translator/pc/PCEntityMetadataPacketTranslator.java @@ -25,7 +25,9 @@ import org.dragonet.proxy.protocol.PEPacket; import org.dragonet.proxy.protocol.packets.AddEntityPacket; import org.dragonet.proxy.protocol.packets.AddItemEntityPacket; +import org.dragonet.proxy.protocol.packets.AddPaintingPacket; import org.dragonet.proxy.protocol.packets.SetEntityDataPacket; +import org.dragonet.proxy.utilities.BlockPosition; import org.dragonet.proxy.utilities.DebugTools; import org.dragonet.proxy.utilities.Vector3F; @@ -37,10 +39,6 @@ public PEPacket[] translate(UpstreamSession session, ServerEntityMetadataPacket if (entity == null) { return null; } - - if (entity.peType == EntityType.PLAYER) { - System.out.println(); - } entity.pcMeta = packet.getMetadata(); if (entity.spawned) { @@ -59,6 +57,15 @@ public PEPacket[] translate(UpstreamSession session, ServerEntityMetadataPacket pk.motion = new Vector3F((float) entity.motionX, (float) entity.motionY, (float) entity.motionZ); entity.spawned = true; session.sendPacket(pk); + } else if (entity.peType == EntityType.PAINTING) { +// AddPaintingPacket pk = new AddPaintingPacket(); +// pk.rtid = entity.proxyEid; +// pk.eid = entity.proxyEid; +// pk.pos = new BlockPosition((int) entity.x, (int) entity.y, (int) entity.z); +// pk.direction = 1; +// pk.title = "Kebab"; +// entity.spawned = true; +// session.sendPacket(pk); } else { AddEntityPacket pk = new AddEntityPacket(); pk.rtid = entity.proxyEid; @@ -66,18 +73,13 @@ public PEPacket[] translate(UpstreamSession session, ServerEntityMetadataPacket pk.type = entity.peType.getPeType(); pk.position = new Vector3F((float) entity.x, (float) entity.y + entity.peType.getOffset(), (float) entity.z); pk.motion = new Vector3F((float) entity.motionX, (float) entity.motionY, (float) entity.motionZ); - pk.yaw = (byte) entity.yaw; + pk.yaw = entity.yaw; pk.pitch = entity.pitch; pk.meta = EntityMetaTranslator.translateToPE(session, entity.pcMeta, entity.peType); entity.spawned = true; // TODO: Hack for now. ;P - if (entity.peType == EntityType.PLAYER) { - System.out.println("Player meta sent"); - System.out.println(entity.pcMeta.toString()); - System.out.println(pk.meta.toString()); - } - pk.attributes = new PEEntityAttribute[]{}; -// session.sendPacket(pk); + pk.attributes = entity.attributes.values(); + session.sendPacket(pk); } } return null; diff --git a/src/main/java/org/dragonet/proxy/network/translator/pc/PCEntityPropertiesPacketTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/pc/PCEntityPropertiesPacketTranslator.java new file mode 100644 index 000000000..a25d542a2 --- /dev/null +++ b/src/main/java/org/dragonet/proxy/network/translator/pc/PCEntityPropertiesPacketTranslator.java @@ -0,0 +1,65 @@ +/* + * GNU LESSER GENERAL PUBLIC LICENSE + * Version 3, 29 June 2007 + * + * Copyright (C) 2007 Free Software Foundation, Inc. + * Everyone is permitted to copy and distribute verbatim copies + * of this license document, but changing it is not allowed. + * + * You can view LICENCE file for details. + * + * @author The Dragonet Team + */ +package org.dragonet.proxy.network.translator.pc; + +import com.github.steveice10.mc.protocol.data.game.entity.attribute.Attribute; +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityPropertiesPacket; +import org.dragonet.proxy.data.entity.PEEntityAttribute; +import org.dragonet.proxy.network.UpstreamSession; +import org.dragonet.proxy.network.cache.CachedEntity; +import org.dragonet.proxy.network.translator.IPCPacketTranslator; +import org.dragonet.proxy.protocol.PEPacket; +import org.dragonet.proxy.protocol.packets.UpdateAttributesPacket; + +public class PCEntityPropertiesPacketTranslator implements IPCPacketTranslator { + + public PEPacket[] translate(UpstreamSession session, ServerEntityPropertiesPacket packet) { + + CachedEntity entity = session.getEntityCache().getByRemoteEID(packet.getEntityId()); + if (entity == null) { + return null; + } + + for(Attribute attr : packet.getAttributes()) + { + switch(attr.getType()) + { + case GENERIC_FOLLOW_RANGE: + entity.attributes.put(PEEntityAttribute.FOLLOW_RANGE, PEEntityAttribute.findAttribute(PEEntityAttribute.FOLLOW_RANGE).setValue((float)attr.getValue())); + break; + case GENERIC_KNOCKBACK_RESISTANCE: + entity.attributes.put(PEEntityAttribute.KNOCKBACK_RESISTANCE, PEEntityAttribute.findAttribute(PEEntityAttribute.KNOCKBACK_RESISTANCE).setValue((float)attr.getValue())); + break; + case GENERIC_MOVEMENT_SPEED: + entity.attributes.put(PEEntityAttribute.MOVEMENT_SPEED, PEEntityAttribute.findAttribute(PEEntityAttribute.MOVEMENT_SPEED).setValue((float)attr.getValue())); + break; + case GENERIC_ATTACK_DAMAGE: + entity.attributes.put(PEEntityAttribute.ATTACK_DAMAGE, PEEntityAttribute.findAttribute(PEEntityAttribute.ATTACK_DAMAGE).setValue((float)attr.getValue())); + break; + case GENERIC_FLYING_SPEED: + entity.attributes.put(PEEntityAttribute.MOVEMENT_SPEED, PEEntityAttribute.findAttribute(PEEntityAttribute.MOVEMENT_SPEED).setValue((float)attr.getValue())); + break; + } + } + + if (entity.spawned) + { + UpdateAttributesPacket pk = new UpdateAttributesPacket(); + pk.rtid = entity.proxyEid; + pk.entries = entity.attributes.values(); + return new PEPacket[]{pk}; + } + + return null; + } +} diff --git a/src/main/java/org/dragonet/proxy/network/translator/pc/PCEntitySetPassengerPacketTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/pc/PCEntitySetPassengerPacketTranslator.java index 9cdd48445..1ebcdb958 100644 --- a/src/main/java/org/dragonet/proxy/network/translator/pc/PCEntitySetPassengerPacketTranslator.java +++ b/src/main/java/org/dragonet/proxy/network/translator/pc/PCEntitySetPassengerPacketTranslator.java @@ -18,7 +18,6 @@ import org.dragonet.proxy.data.entity.EntityType; import org.dragonet.proxy.data.entity.meta.EntityMetaData; import org.dragonet.proxy.data.entity.meta.type.Vector3FMeta; -import org.dragonet.proxy.network.CacheKey; import org.dragonet.proxy.network.UpstreamSession; import org.dragonet.proxy.network.cache.CachedEntity; import org.dragonet.proxy.network.translator.EntityMetaTranslator; @@ -63,17 +62,11 @@ public PEPacket[] translate(UpstreamSession session, ServerEntitySetPassengersPa } } - //clean cache -// vehicle.passengers.clear(); - //process mount action boolean piloteSet = false; for (int id : packet.getPassengerIds()) { CachedEntity rider = session.getEntityCache().getByRemoteEID(id); -// if (id == (int) session.getDataCache().get(CacheKey.PLAYER_EID)) { -// rider = session.getEntityCache().getClientEntity(); -// } if (rider == null) { continue; @@ -122,7 +115,15 @@ private Vector3F getSeatOffset(EntityType peType, int seat) { switch (peType) { case BOAT: case MINECART: + if (seat > 2) { + return null; //DISMOUNT + } return new Vector3F(0 + seat / 2, 0.35F, 0 + seat / 2); + case HORSE: + if (seat > 1) { + return null; //DISMOUNT + } + return new Vector3F(0, peType.getOffset(), 0); } } return new Vector3F(0, 0.35F, 0); //default diff --git a/src/main/java/org/dragonet/proxy/network/translator/pc/PCJoinGamePacketTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/pc/PCJoinGamePacketTranslator.java index fa9ad8f65..e67aa0ee7 100644 --- a/src/main/java/org/dragonet/proxy/network/translator/pc/PCJoinGamePacketTranslator.java +++ b/src/main/java/org/dragonet/proxy/network/translator/pc/PCJoinGamePacketTranslator.java @@ -22,7 +22,7 @@ public class PCJoinGamePacketTranslator implements IPCPacketTranslator { @@ -55,7 +55,6 @@ public PEPacket[] translate(UpstreamSession session, ServerPlayerPositionRotatio } if (!session.isSpawned()) { - System.out.println("SPAWNED! "); if (session.getDataCache().get(CacheKey.PACKET_JOIN_GAME_PACKET) == null) { session.disconnect(session.getProxy().getLang().get(Lang.MESSAGE_REMOTE_ERROR)); return null; @@ -90,18 +89,26 @@ public PEPacket[] translate(UpstreamSession session, ServerPlayerPositionRotatio ((PCDownstreamSession) session.getDownstream()).send(ClientPluginMessagePacket); LoginPacket loginpacket = (LoginPacket) session.getDataCache().remove(CacheKey.PACKET_LOGIN_PACKET); - ClientSettingsPacket ClientSettingsPacket = new ClientSettingsPacket(loginpacket.decoded.language, 8, ChatVisibility.FULL, false, new SkinPart[]{}, Hand.MAIN_HAND); + ClientSettingsPacket ClientSettingsPacket = new ClientSettingsPacket(loginpacket.decoded.language, 8, ChatVisibility.FULL, false, new SkinPart[]{}, Hand.OFF_HAND); ((PCDownstreamSession) session.getDownstream()).send(ClientSettingsPacket); UpdateAttributesPacket attr = new UpdateAttributesPacket(); attr.rtid = entityPlayer.proxyEid; - attr.entries = new PEEntityAttribute[]{PEEntityAttribute.findAttribute(PEEntityAttribute.ABSORPTION), - PEEntityAttribute.findAttribute(PEEntityAttribute.EXHAUSTION), - PEEntityAttribute.findAttribute(PEEntityAttribute.HUNGER), - PEEntityAttribute.findAttribute(PEEntityAttribute.EXPERIENCE_LEVEL), - PEEntityAttribute.findAttribute(PEEntityAttribute.EXPERIENCE), - PEEntityAttribute.findAttribute(PEEntityAttribute.EXPERIENCE_LEVEL), - PEEntityAttribute.findAttribute(PEEntityAttribute.MOVEMENT_SPEED),}; + if (entityPlayer.attributes.isEmpty()) + { + attr.entries = new ArrayList(); + attr.entries.add(PEEntityAttribute.findAttribute(PEEntityAttribute.ABSORPTION)); + attr.entries.add(PEEntityAttribute.findAttribute(PEEntityAttribute.EXHAUSTION)); + attr.entries.add(PEEntityAttribute.findAttribute(PEEntityAttribute.HUNGER)); + attr.entries.add(PEEntityAttribute.findAttribute(PEEntityAttribute.EXPERIENCE_LEVEL)); + attr.entries.add(PEEntityAttribute.findAttribute(PEEntityAttribute.EXPERIENCE)); + attr.entries.add(PEEntityAttribute.findAttribute(PEEntityAttribute.EXPERIENCE_LEVEL)); + attr.entries.add(PEEntityAttribute.findAttribute(PEEntityAttribute.MOVEMENT_SPEED)); + } + else + { + attr.entries = entityPlayer.attributes.values(); + } session.sendPacket(attr); AdventureSettingsPacket adv = new AdventureSettingsPacket(); @@ -137,8 +144,7 @@ public PEPacket[] translate(UpstreamSession session, ServerPlayerPositionRotatio MovePlayerPacket pk = new MovePlayerPacket(); pk.rtid = entityPlayer.proxyEid; pk.mode = MovePlayerPacket.MODE_TELEPORT; - pk.position = new Vector3F((float) packet.getX(), (float) packet.getY() + Constants.PLAYER_HEAD_OFFSET, - (float) packet.getZ()); + pk.position = new Vector3F((float) packet.getX(), (float) packet.getY() + EntityType.PLAYER.getOffset(), (float) packet.getZ()); pk.yaw = packet.getYaw(); pk.pitch = packet.getPitch(); pk.headYaw = packet.getYaw(); @@ -176,12 +182,10 @@ public PEPacket[] translate(UpstreamSession session, ServerPlayerPositionRotatio Set peEntries = new HashSet(); for (CachedEntity entity : session.getEntityCache().getEntities().values()) { - if (entity.eid == entityPlayer.eid) //never send ME (entry 1L) - { + if (entity.eid == entityPlayer.eid) { //never send ME (entry 1L) continue; } - if (entity.player && entity.playerUniqueId != null) //PLAYER - { + if (entity.peType == EntityType.PLAYER) { PlayerListEntry playerListEntry = session.getPlayerInfoCache().get(entity.playerUniqueId); AddPlayerPacket pkAddPlayer = new AddPlayerPacket(); pkAddPlayer.eid = entity.proxyEid; @@ -210,8 +214,26 @@ public PEPacket[] translate(UpstreamSession session, ServerPlayerPositionRotatio session.sendPacket(pkAddPlayer); session.sendPacket(skin); - } else if (entity.peType != null) //ENTITY - { + } else if (entity.peType == EntityType.ITEM) { + AddItemEntityPacket pk = new AddItemEntityPacket(); + pk.rtid = entity.proxyEid; + pk.eid = entity.proxyEid; + pk.metadata = EntityMetaTranslator.translateToPE(session, entity.pcMeta, entity.peType); + pk.item = ((SlotMeta) pk.metadata.map.get(EntityMetaData.Constants.DATA_TYPE_SLOT)).slot; + pk.position = new Vector3F((float) entity.x, (float) entity.y, (float) entity.z); + pk.motion = new Vector3F((float) entity.motionX, (float) entity.motionY, (float) entity.motionZ); + entity.spawned = true; + session.sendPacket(pk); + } else if (entity.peType == EntityType.PAINTING) { +// AddPaintingPacket pk = new AddPaintingPacket(); +// pk.rtid = entity.proxyEid; +// pk.eid = entity.proxyEid; +// pk.pos = new BlockPosition((int) entity.x, (int) entity.y, (int) entity.z); +// pk.direction = 1; +// pk.title = "Kebab"; +// entity.spawned = true; +// session.sendPacket(pk); + } else if (entity.peType != null) { //ENTITY AddEntityPacket pk = new AddEntityPacket(); pk.rtid = entity.proxyEid; pk.eid = entity.proxyEid; @@ -222,18 +244,7 @@ public PEPacket[] translate(UpstreamSession session, ServerPlayerPositionRotatio pk.pitch = entity.pitch; pk.meta = EntityMetaTranslator.translateToPE(session, entity.pcMeta, entity.peType); // TODO: Hack for now. ;P - pk.attributes = new PEEntityAttribute[]{}; - session.sendPacket(pk); - } else // ITEM - { - AddItemEntityPacket pk = new AddItemEntityPacket(); - pk.rtid = entity.proxyEid; - pk.eid = entity.proxyEid; - pk.metadata = EntityMetaTranslator.translateToPE(session, entity.pcMeta, entity.peType); - pk.item = ((SlotMeta) pk.metadata.map.get(EntityMetaData.Constants.DATA_TYPE_SLOT)).slot; - pk.position = new Vector3F((float) entity.x, (float) entity.y, (float) entity.z); - pk.motion = new Vector3F((float) entity.motionX, (float) entity.motionY, (float) entity.motionZ); - entity.spawned = true; + pk.attributes = entity.attributes.values(); session.sendPacket(pk); } } @@ -241,14 +252,15 @@ public PEPacket[] translate(UpstreamSession session, ServerPlayerPositionRotatio playerListPacket.type = PlayerListPacket.TYPE_ADD; playerListPacket.entries = (org.dragonet.proxy.protocol.type.PlayerListEntry[]) peEntries.toArray(new org.dragonet.proxy.protocol.type.PlayerListEntry[peEntries.size()]); session.sendPacket(playerListPacket); + entityPlayer.spawned = true; + System.out.println("SPAWNED !"); return null; } MovePlayerPacket pk = new MovePlayerPacket(); pk.rtid = entityPlayer.proxyEid; pk.mode = MovePlayerPacket.MODE_TELEPORT; - pk.position = new Vector3F((float) packet.getX(), (float) packet.getY() + Constants.PLAYER_HEAD_OFFSET, - (float) packet.getZ()); + pk.position = new Vector3F((float) packet.getX(), (float) packet.getY() + EntityType.PLAYER.getOffset(), (float) packet.getZ()); pk.yaw = packet.getYaw(); pk.pitch = packet.getPitch(); pk.headYaw = packet.getYaw(); diff --git a/src/main/java/org/dragonet/proxy/network/translator/pc/PCSetExperiencePacketTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/pc/PCSetExperiencePacketTranslator.java index 2fb43f413..d408f149f 100644 --- a/src/main/java/org/dragonet/proxy/network/translator/pc/PCSetExperiencePacketTranslator.java +++ b/src/main/java/org/dragonet/proxy/network/translator/pc/PCSetExperiencePacketTranslator.java @@ -13,6 +13,7 @@ package org.dragonet.proxy.network.translator.pc; import com.github.steveice10.mc.protocol.packet.ingame.server.entity.player.ServerPlayerSetExperiencePacket; +import java.util.ArrayList; import org.dragonet.proxy.data.entity.PEEntityAttribute; import org.dragonet.proxy.network.UpstreamSession; import org.dragonet.proxy.network.translator.IPCPacketTranslator; @@ -24,9 +25,9 @@ public class PCSetExperiencePacketTranslator implements IPCPacketTranslator + * Everyone is permitted to copy and distribute verbatim copies + * of this license document, but changing it is not allowed. + * + * You can view LICENCE file for details. + * + * @author The Dragonet Team + */ +package org.dragonet.proxy.network.translator.pc; + +import org.dragonet.proxy.network.UpstreamSession; +import org.dragonet.proxy.network.cache.CachedEntity; +import org.dragonet.proxy.network.translator.IPCPacketTranslator; +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnPaintingPacket; +import org.dragonet.proxy.protocol.PEPacket; +import org.dragonet.proxy.protocol.packets.AddPaintingPacket; +import org.dragonet.proxy.utilities.BlockPosition; + +public class PCSpawnPaintingPacketTranslator implements IPCPacketTranslator { + + public PEPacket[] translate(UpstreamSession session, ServerSpawnPaintingPacket packet) { + CachedEntity entity = session.getEntityCache().newEntity(packet); + if (entity == null) { + return null; + } + +// if (session.isLoggedIn()) { +// AddPaintingPacket pk = new AddPaintingPacket(); +// pk.rtid = entity.proxyEid; +// pk.eid = entity.proxyEid; +// pk.pos = new BlockPosition((int)entity.x, (int)entity.y, (int)entity.z); +// pk.direction = packet.getDirection().ordinal(); +// pk.title = packet.getPaintingType().name(); +// entity.spawned = true; +// return new PEPacket[]{pk}; +// } + return null; + } +} diff --git a/src/main/java/org/dragonet/proxy/network/translator/pc/PCSpawnPlayerPacketTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/pc/PCSpawnPlayerPacketTranslator.java index a6aa67a97..6639ec81c 100644 --- a/src/main/java/org/dragonet/proxy/network/translator/pc/PCSpawnPlayerPacketTranslator.java +++ b/src/main/java/org/dragonet/proxy/network/translator/pc/PCSpawnPlayerPacketTranslator.java @@ -29,10 +29,10 @@ public PEPacket[] translate(UpstreamSession session, ServerSpawnPlayerPacket pac pkAddPlayer.uuid = packet.getUUID(); - pkAddPlayer.position = new Vector3F((float) packet.getX(), (float) packet.getY(), (float) packet.getZ()); + pkAddPlayer.position = new Vector3F((float) entity.x, (float) entity.y, (float) entity.z); pkAddPlayer.motion = Vector3F.ZERO; - pkAddPlayer.yaw = packet.getYaw(); - pkAddPlayer.pitch = packet.getPitch(); + pkAddPlayer.yaw = entity.yaw; + pkAddPlayer.pitch = entity.pitch; pkAddPlayer.meta = EntityMetaTranslator.translateToPE(session, entity.pcMeta, EntityType.PLAYER); pkAddPlayer.meta.set(EntityMetaData.Constants.DATA_NAMETAG, new ByteArrayMeta(playerListEntry.getProfile().getName())); //hacky for now diff --git a/src/main/java/org/dragonet/proxy/network/translator/pc/PCUpdateSignPacketTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/pc/PCUpdateSignPacketTranslator.java index a17d74e94..40501fba4 100644 --- a/src/main/java/org/dragonet/proxy/network/translator/pc/PCUpdateSignPacketTranslator.java +++ b/src/main/java/org/dragonet/proxy/network/translator/pc/PCUpdateSignPacketTranslator.java @@ -13,6 +13,7 @@ package org.dragonet.proxy.network.translator.pc; import com.github.steveice10.mc.protocol.data.game.world.block.UpdatedTileType; +import com.github.steveice10.mc.protocol.data.message.Message; import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerUpdateTileEntityPacket; import com.github.steveice10.opennbt.tag.builtin.CompoundTag; import com.github.steveice10.opennbt.tag.builtin.IntTag; @@ -20,8 +21,11 @@ import org.dragonet.proxy.network.UpstreamSession; import org.dragonet.proxy.network.translator.IPCPacketTranslator; +import org.dragonet.proxy.network.translator.ItemBlockTranslator; +import org.dragonet.proxy.network.translator.MessageTranslator; import org.dragonet.proxy.protocol.PEPacket; import org.dragonet.proxy.protocol.packets.BlockEntityDataPacket; +import org.dragonet.proxy.utilities.BlockPosition; public class PCUpdateSignPacketTranslator implements IPCPacketTranslator { @@ -32,15 +36,15 @@ public PEPacket[] translate(UpstreamSession session, ServerUpdateTileEntityPacke root.put(new IntTag("x", packet.getPosition().getX())); root.put(new IntTag("y", packet.getPosition().getY())); root.put(new IntTag("z", packet.getPosition().getZ())); - root.put(new StringTag("Text1", (String) packet.getNBT().get("Text1").getValue())); - root.put(new StringTag("Text2", (String) packet.getNBT().get("Text2").getValue())); - root.put(new StringTag("Text3", (String) packet.getNBT().get("Text3").getValue())); - root.put(new StringTag("Text4", (String) packet.getNBT().get("Text4").getValue())); + root.put(new StringTag("Text", + MessageTranslator.translate(Message.fromString((String)packet.getNBT().get("Text1").getValue())) + + "\n" + MessageTranslator.translate(Message.fromString((String)packet.getNBT().get("Text2").getValue())) + + "\n" + MessageTranslator.translate(Message.fromString((String)packet.getNBT().get("Text3").getValue())) + + "\n" + MessageTranslator.translate(Message.fromString((String)packet.getNBT().get("Text4").getValue())))); BlockEntityDataPacket data = new BlockEntityDataPacket(); - data.tag = root; - // packet.getPosition().getX(), packet.getPosition().getY(), - // packet.getPosition().getZ(), root + data.tag = ItemBlockTranslator.translateBlockEntityToPE(root); + data.blockPosition = new BlockPosition(packet.getPosition()); return new PEPacket[]{data}; } else { return null; diff --git a/src/main/java/org/dragonet/proxy/network/translator/pc/PCUpdateTileEntityPacketTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/pc/PCUpdateTileEntityPacketTranslator.java new file mode 100644 index 000000000..5d973aea9 --- /dev/null +++ b/src/main/java/org/dragonet/proxy/network/translator/pc/PCUpdateTileEntityPacketTranslator.java @@ -0,0 +1,32 @@ +/* + * GNU LESSER GENERAL PUBLIC LICENSE + * Version 3, 29 June 2007 + * + * Copyright (C) 2007 Free Software Foundation, Inc. + * Everyone is permitted to copy and distribute verbatim copies + * of this license document, but changing it is not allowed. + * + * You can view LICENCE file for details. + * + * @author The Dragonet Team + */ +package org.dragonet.proxy.network.translator.pc; + +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerUpdateTileEntityPacket; +import org.dragonet.proxy.network.UpstreamSession; +import org.dragonet.proxy.network.translator.ItemBlockTranslator; +import org.dragonet.proxy.network.translator.IPCPacketTranslator; +import org.dragonet.proxy.protocol.PEPacket; +import org.dragonet.proxy.protocol.packets.BlockEntityDataPacket; +import org.dragonet.proxy.utilities.BlockPosition; + +public class PCUpdateTileEntityPacketTranslator implements IPCPacketTranslator { + + public PEPacket[] translate(UpstreamSession session, ServerUpdateTileEntityPacket packet) { + + BlockEntityDataPacket data = new BlockEntityDataPacket(); + data.blockPosition = new BlockPosition(packet.getPosition()); + data.tag = ItemBlockTranslator.translateBlockEntityToPE(packet.getNBT()); + return new PEPacket[]{data}; + } +} diff --git a/src/main/java/org/dragonet/proxy/network/translator/pc/PCVehicleMovePacketTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/pc/PCVehicleMovePacketTranslator.java index 39851726a..2c5003894 100644 --- a/src/main/java/org/dragonet/proxy/network/translator/pc/PCVehicleMovePacketTranslator.java +++ b/src/main/java/org/dragonet/proxy/network/translator/pc/PCVehicleMovePacketTranslator.java @@ -13,19 +13,15 @@ package org.dragonet.proxy.network.translator.pc; import org.dragonet.proxy.network.UpstreamSession; -import org.dragonet.proxy.network.cache.CachedEntity; import org.dragonet.proxy.network.translator.IPCPacketTranslator; import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerVehicleMovePacket; import org.dragonet.proxy.protocol.PEPacket; -import org.dragonet.proxy.protocol.packets.MoveEntityPacket; -import org.dragonet.proxy.utilities.Constants; import org.dragonet.proxy.utilities.DebugTools; -import org.dragonet.proxy.utilities.Vector3F; public class PCVehicleMovePacketTranslator implements IPCPacketTranslator { public PEPacket[] translate(UpstreamSession session, ServerVehicleMovePacket packet) { - System.out.println(DebugTools.getAllFields(packet)); +// System.out.println(DebugTools.getAllFields(packet)); return new PEPacket[]{}; } } diff --git a/src/main/java/org/dragonet/proxy/network/translator/pe/PEInventoryTransactionPacketTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/pe/PEInventoryTransactionPacketTranslator.java index e19821af2..8f7a5f696 100644 --- a/src/main/java/org/dragonet/proxy/network/translator/pe/PEInventoryTransactionPacketTranslator.java +++ b/src/main/java/org/dragonet/proxy/network/translator/pe/PEInventoryTransactionPacketTranslator.java @@ -49,7 +49,7 @@ public Packet[] translate(UpstreamSession session, InventoryTransactionPacket pa switch (packet.transactionType) { case TYPE_NORMAL: //0 -// System.out.println("TYPE_NORMAL"); + System.out.println("TYPE_NORMAL"); List packets = new ArrayList(); for (InventoryTransactionAction action : packet.actions) { @@ -64,10 +64,10 @@ public Packet[] translate(UpstreamSession session, InventoryTransactionPacket pa } return packets.toArray(new Packet[]{}); case TYPE_MISMATCH: //1 -// System.out.println("TYPE_MISMATCH"); + System.out.println("TYPE_MISMATCH"); break; case TYPE_USE_ITEM: //2 -// System.out.println("TYPE_USE_ITEM"); + System.out.println("TYPE_USE_ITEM"); UseItemData useItemData = (UseItemData) packet.transactionData; if (useItemData.blockPos.equals(new BlockPosition(0, 0, 0))) { return null; @@ -98,7 +98,7 @@ public Packet[] translate(UpstreamSession session, InventoryTransactionPacket pa } case TYPE_USE_ITEM_ON_ENTITY: //3 -// System.out.println("TYPE_USE_ITEM_ON_ENTITY"); + System.out.println("TYPE_USE_ITEM_ON_ENTITY"); UseItemOnEntityData useItemOnEntityData = (UseItemOnEntityData) packet.transactionData; CachedEntity cachedEntity = session.getEntityCache().getByLocalEID(useItemOnEntityData.entityRuntimeId); if (cachedEntity == null) { @@ -114,7 +114,7 @@ public Packet[] translate(UpstreamSession session, InventoryTransactionPacket pa ); return new Packet[]{interractPacket}; case TYPE_RELEASE_ITEM: //4 -// System.out.println("TYPE_RELEASE_ITEM"); + System.out.println("TYPE_RELEASE_ITEM"); ReleaseItemData releaseItemData = (ReleaseItemData) packet.transactionData; // ClientPlayerActionPacket act = new ClientPlayerActionPacket( // com.github.steveice10.mc.protocol.data.game.entity.player.PlayerAction.DROP_ITEM, diff --git a/src/main/java/org/dragonet/proxy/network/translator/pe/PEMovePlayerPacketTranslator.java b/src/main/java/org/dragonet/proxy/network/translator/pe/PEMovePlayerPacketTranslator.java index 2c4463359..403b18eff 100644 --- a/src/main/java/org/dragonet/proxy/network/translator/pe/PEMovePlayerPacketTranslator.java +++ b/src/main/java/org/dragonet/proxy/network/translator/pe/PEMovePlayerPacketTranslator.java @@ -18,8 +18,8 @@ import org.dragonet.proxy.network.translator.IPEPacketTranslator; import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionRotationPacket; import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientVehicleMovePacket; +import org.dragonet.proxy.data.entity.EntityType; import org.dragonet.proxy.protocol.packets.MovePlayerPacket; -import org.dragonet.proxy.utilities.Constants; import org.dragonet.proxy.utilities.DebugTools; public class PEMovePlayerPacketTranslator implements IPEPacketTranslator { @@ -27,12 +27,11 @@ public class PEMovePlayerPacketTranslator implements IPEPacketTranslator { public Packet[] translate(UpstreamSession session, ContainerClosePacket packet) { + System.out.println("Window " + packet.windowId + " closed from client !"); session.getProxy().getGeneralThreadPool().execute(() -> { InventoryTranslatorRegister.closeOpened(session, false); }); diff --git a/src/main/java/org/dragonet/proxy/protocol/PEPacket.java b/src/main/java/org/dragonet/proxy/protocol/PEPacket.java index 7e84cea5c..a72acd1b8 100644 --- a/src/main/java/org/dragonet/proxy/protocol/PEPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/PEPacket.java @@ -6,55 +6,51 @@ * Created on 2017/10/21. */ public abstract class PEPacket extends BinaryStream { - // vars - private boolean encoded; - private boolean decoded; - - // constructor - public PEPacket() { - super(); - } - - // public - public boolean isEncoded() { - return encoded; - } - - public boolean isDecoded() { - return decoded; - } - - public final void encode() { - reset(); - encodeHeader(); - encodePayload(); - encoded = true; - } - - public final void decode() { - decodeHeader(); - decodePayload(); - decoded = true; - } - - public void encodeHeader() { - // putUnsignedVarInt(pid()); - putByte((byte)(pid() & 0xFF)); - putByte((byte) 0x00); - putByte((byte) 0x00); - } - - public void decodeHeader() { - getByte(); // getUnsignedVarInt(); - get(2); - } - - public abstract int pid(); - - public abstract void encodePayload(); - - public abstract void decodePayload(); - - // private + + private boolean encoded; + private boolean decoded; + + public PEPacket() { + super(); + } + + public boolean isEncoded() { + return encoded; + } + + public boolean isDecoded() { + return decoded; + } + + public final void encode() { + reset(); + encodeHeader(); + encodePayload(); + encoded = true; + } + + public final void decode() { + decodeHeader(); + decodePayload(); + decoded = true; + } + + public void encodeHeader() { + // putUnsignedVarInt(pid()); + putByte((byte) (pid() & 0xFF)); + putByte((byte) 0x00); + putByte((byte) 0x00); + } + + public void decodeHeader() { + getByte(); // getUnsignedVarInt(); + get(2); + } + + public abstract int pid(); + + public abstract void encodePayload(); + + public abstract void decodePayload(); } diff --git a/src/main/java/org/dragonet/proxy/protocol/Protocol.java b/src/main/java/org/dragonet/proxy/protocol/Protocol.java index cd86da2c2..33fba21d0 100644 --- a/src/main/java/org/dragonet/proxy/protocol/Protocol.java +++ b/src/main/java/org/dragonet/proxy/protocol/Protocol.java @@ -26,121 +26,115 @@ import static org.dragonet.proxy.protocol.ProtocolInfo.*; public final class Protocol { - // vars - public static final Map> packets = new HashMap<>(); - static { - packets.put(DISCONNECT_PACKET, DisconnectPacket.class); - packets.put(LOGIN_PACKET, LoginPacket.class); - packets.put(PLAY_STATUS_PACKET, PlayStatusPacket.class); - packets.put(START_GAME_PACKET, StartGamePacket.class); - packets.put(REQUEST_CHUNK_RADIUS_PACKET, RequestChunkRadiusPacket.class); - packets.put(CHUNK_RADIUS_UPDATED_PACKET, ChunkRadiusUpdatedPacket.class); - packets.put(FULL_CHUNK_DATA_PACKET, FullChunkDataPacket.class); - packets.put(UPDATE_BLOCK_PACKET, UpdateBlockPacket.class); - packets.put(TEXT_PACKET, TextPacket.class); - packets.put(COMMAND_REQUEST_PACKET, CommandRequestPacket.class); - packets.put(CHANGE_DIMENSION_PACKET, ChangeDimensionPacket.class); - packets.put(REMOVE_ENTITY_PACKET, RemoveEntityPacket.class); - packets.put(MOB_EFFECT_PACKET, MobEffectPacket.class); - packets.put(ADD_ITEM_ENTITY_PACKET, AddItemEntityPacket.class); - packets.put(MOVE_ENTITY_PACKET, MoveEntityPacket.class); - packets.put(MOVE_PLAYER_PACKET, MovePlayerPacket.class); - packets.put(SET_ENTITY_MOTION_PACKET, SetEntityMotionPacket.class); - packets.put(SET_PLAYER_GAME_TYPE_PACKET, SetPlayerGameTypePacket.class); - packets.put(ADVENTURE_SETTINGS_PACKET, AdventureSettingsPacket.class); - packets.put(ANIMATE_PACKET, AnimatePacket.class); - packets.put(LEVEL_SOUND_EVENT_PACKET, LevelSoundEventPacket.class); - packets.put(BLOCK_PICK_REQUEST_PACKET, BlockPickRequestPacket.class); - packets.put(SET_SPAWN_POSITION_PACKET, SetSpawnPositionPacket.class); - packets.put(LEVEL_EVENT_PACKET, LevelEventPacket.class); - packets.put(PLAY_SOUND_PACKET, PlaySoundPacket.class); - packets.put(ADD_ENTITY_PACKET, AddEntityPacket.class); - packets.put(ADD_PLAYER_PACKET, AddPlayerPacket.class); - packets.put(PLAYER_LIST_PACKET, PlayerListPacket.class); - packets.put(SET_HEALTH_PACKET, SetHealthPacket.class); - packets.put(RESPAWN_PACKET, RespawnPacket.class); - packets.put(BLOCK_ENTITY_DATA_PACKET, BlockEntityDataPacket.class); - packets.put(SET_TIME_PACKET, SetTimePacket.class); - packets.put(INTERACT_PACKET, InteractPacket.class); - packets.put(PLAYER_ACTION_PACKET, PlayerActionPacket.class); - packets.put(MOB_EQUIPMENT_PACKET, MobEquipmentPacket.class); - packets.put(MOB_ARMOR_EQUIPMENT_PACKET, MobArmorEquipmentPacket.class); - packets.put(SET_ENTITY_DATA_PACKET, SetEntityDataPacket.class); - packets.put(PLAYER_SKIN_PACKET, PlayerSkinPacket.class); - packets.put(PLAYER_HOTBAR_PACKET, PlayerHotbarPacket.class); - packets.put(SET_ENTITY_LINK_PACKET, SetEntityLinkPacket.class); - packets.put(PLAYER_INPUT_PACKET, PlayerInputPacket.class); + public static final Map> packets = new HashMap<>(); - packets.put(CONTAINER_OPEN_PACKET, ContainerOpenPacket.class); - packets.put(CONTAINER_CLOSE_PACKET, ContainerClosePacket.class); - packets.put(INVENTORY_CONTENT_PACKET, InventoryContentPacket.class); - packets.put(INVENTORY_SLOT_PACKET, InventorySlotPacket.class); - packets.put(INVENTORY_TRANSACTION_PACKET, InventoryTransactionPacket.class); + static { + packets.put(DISCONNECT_PACKET, DisconnectPacket.class); + packets.put(LOGIN_PACKET, LoginPacket.class); + packets.put(PLAY_STATUS_PACKET, PlayStatusPacket.class); + packets.put(START_GAME_PACKET, StartGamePacket.class); + packets.put(REQUEST_CHUNK_RADIUS_PACKET, RequestChunkRadiusPacket.class); + packets.put(CHUNK_RADIUS_UPDATED_PACKET, ChunkRadiusUpdatedPacket.class); + packets.put(FULL_CHUNK_DATA_PACKET, FullChunkDataPacket.class); + packets.put(UPDATE_BLOCK_PACKET, UpdateBlockPacket.class); + packets.put(BLOCK_EVENT_PACKET, BlockEventPacket.class); + packets.put(ADD_PAINTING_PACKET, AddPaintingPacket.class); + packets.put(TEXT_PACKET, TextPacket.class); + packets.put(COMMAND_REQUEST_PACKET, CommandRequestPacket.class); + packets.put(CHANGE_DIMENSION_PACKET, ChangeDimensionPacket.class); + packets.put(REMOVE_ENTITY_PACKET, RemoveEntityPacket.class); + packets.put(MOB_EFFECT_PACKET, MobEffectPacket.class); + packets.put(ADD_ITEM_ENTITY_PACKET, AddItemEntityPacket.class); + packets.put(MOVE_ENTITY_PACKET, MoveEntityPacket.class); + packets.put(MOVE_PLAYER_PACKET, MovePlayerPacket.class); + packets.put(SET_ENTITY_MOTION_PACKET, SetEntityMotionPacket.class); + packets.put(SET_PLAYER_GAME_TYPE_PACKET, SetPlayerGameTypePacket.class); + packets.put(ADVENTURE_SETTINGS_PACKET, AdventureSettingsPacket.class); + packets.put(ANIMATE_PACKET, AnimatePacket.class); + packets.put(LEVEL_SOUND_EVENT_PACKET, LevelSoundEventPacket.class); + packets.put(BLOCK_PICK_REQUEST_PACKET, BlockPickRequestPacket.class); + packets.put(SET_SPAWN_POSITION_PACKET, SetSpawnPositionPacket.class); + packets.put(LEVEL_EVENT_PACKET, LevelEventPacket.class); + packets.put(PLAY_SOUND_PACKET, PlaySoundPacket.class); + packets.put(ADD_ENTITY_PACKET, AddEntityPacket.class); + packets.put(ADD_PLAYER_PACKET, AddPlayerPacket.class); + packets.put(PLAYER_LIST_PACKET, PlayerListPacket.class); + packets.put(SET_HEALTH_PACKET, SetHealthPacket.class); + packets.put(RESPAWN_PACKET, RespawnPacket.class); + packets.put(BLOCK_ENTITY_DATA_PACKET, BlockEntityDataPacket.class); + packets.put(SET_TIME_PACKET, SetTimePacket.class); + packets.put(INTERACT_PACKET, InteractPacket.class); + packets.put(PLAYER_ACTION_PACKET, PlayerActionPacket.class); + packets.put(MOB_EQUIPMENT_PACKET, MobEquipmentPacket.class); + packets.put(SET_ENTITY_DATA_PACKET, SetEntityDataPacket.class); + packets.put(PLAYER_SKIN_PACKET, PlayerSkinPacket.class); + packets.put(PLAYER_HOTBAR_PACKET, PlayerHotbarPacket.class); + packets.put(SET_ENTITY_LINK_PACKET, SetEntityLinkPacket.class); + packets.put(PLAYER_INPUT_PACKET, PlayerInputPacket.class); - packets.put(RESOURCE_PACKS_INFO_PACKET, ResourcePacksInfoPacket.class); - packets.put(RESOURCE_PACK_CLIENT_RESPONSE_PACKET, ResourcePackClientResponsePacket.class); - packets.put(RESOURCE_PACK_STACK_PACKET, ResourcePackStackPacket.class); - } + packets.put(CONTAINER_OPEN_PACKET, ContainerOpenPacket.class); + packets.put(CONTAINER_CLOSE_PACKET, ContainerClosePacket.class); + packets.put(INVENTORY_CONTENT_PACKET, InventoryContentPacket.class); + packets.put(INVENTORY_SLOT_PACKET, InventorySlotPacket.class); + packets.put(INVENTORY_TRANSACTION_PACKET, InventoryTransactionPacket.class); - // constructor - public Protocol() { + packets.put(RESOURCE_PACKS_INFO_PACKET, ResourcePacksInfoPacket.class); + packets.put(RESOURCE_PACK_CLIENT_RESPONSE_PACKET, ResourcePackClientResponsePacket.class); + packets.put(RESOURCE_PACK_STACK_PACKET, ResourcePackStackPacket.class); + } - } + public static PEPacket[] decode(byte[] data) throws Exception { + if (data == null || data.length < 1) { + return null; + } - // public - public static PEPacket[] decode(byte[] data) throws Exception { - if (data == null || data.length < 1) { - return null; - } + byte[] inflated; + try { + inflated = Zlib.inflate(Arrays.copyOfRange(data, 1, data.length)); + } catch (IOException e) { + e.printStackTrace(); + return null; + } - byte[] inflated; - try { - inflated = Zlib.inflate(Arrays.copyOfRange(data, 1, data.length)); - } catch (IOException e) { - e.printStackTrace(); - return null; - } + ArrayList packets = new ArrayList<>(2); + BinaryStream stream = new BinaryStream(inflated); + while (stream.offset < inflated.length) { + byte[] buffer = stream.get((int) stream.getUnsignedVarInt()); + PEPacket decoded = decodeSingle(buffer); - ArrayList packets = new ArrayList<>(2); - BinaryStream stream = new BinaryStream(inflated); - while (stream.offset < inflated.length) { - byte[] buffer = stream.get((int) stream.getUnsignedVarInt()); - PEPacket decoded = decodeSingle(buffer); + if (decoded != null) { + packets.add(decoded); + } else { + System.out.println("decode fail"); + } + } - if (decoded != null) { - packets.add(decoded); - } else { - System.out.println("decode fail"); - } - } + return packets.size() > 0 ? packets.toArray(new PEPacket[0]) : null; + } - return packets.size() > 0 ? packets.toArray(new PEPacket[0]) : null; - } - - // private - private static PEPacket decodeSingle(byte[] buffer) { + private static PEPacket decodeSingle(byte[] buffer) { // try { // FileOutputStream fos = new FileOutputStream("raw_" + System.currentTimeMillis() + ".bin"); // fos.write(buffer); // fos.close(); // } catch (Exception e) { // } - byte pid = (byte) new BinaryStream(buffer).getUnsignedVarInt(); - if (packets.containsKey(pid)) { - Class c = packets.get(pid); - try { - PEPacket pk = c.newInstance(); - pk.setBuffer(buffer); - pk.decode(); - return pk; - } catch (SecurityException | InstantiationException | IllegalAccessException - | IllegalArgumentException ex) { - ex.printStackTrace(); - } - } else { - System.out.println("can not decode for pid 0x" + Integer.toHexString(pid)); - } - return null; - } + byte pid = (byte) new BinaryStream(buffer).getUnsignedVarInt(); + if (packets.containsKey(pid)) { + Class c = packets.get(pid); + try { + PEPacket pk = c.newInstance(); + pk.setBuffer(buffer); + pk.decode(); + return pk; + } catch (SecurityException | InstantiationException | IllegalAccessException + | IllegalArgumentException ex) { + ex.printStackTrace(); + } + } else { + System.out.println("can not decode for pid 0x" + Integer.toHexString(pid)); + } + return null; + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/ProtocolInfo.java b/src/main/java/org/dragonet/proxy/protocol/ProtocolInfo.java index 3124a388b..50e3298f4 100644 --- a/src/main/java/org/dragonet/proxy/protocol/ProtocolInfo.java +++ b/src/main/java/org/dragonet/proxy/protocol/ProtocolInfo.java @@ -2,138 +2,128 @@ /** * Class from PMMP project translated to Java - * + * * @author PMMP Created on 2017/10/21. */ public class ProtocolInfo { - // vars - /** - * Actual Minecraft: PE protocol version - */ - public static final int CURRENT_PROTOCOL = 160; - /** - * Current Minecraft PE version reported by the server. This is usually the - * earliest currently supported version. - */ - public static final String MINECRAFT_VERSION = "v1.2.7"; - /** - * Version number sent to clients in ping responses. - */ - public static final String MINECRAFT_VERSION_NETWORK = "1.2.7"; - public static final byte LOGIN_PACKET = (byte) 0x01; - public static final byte PLAY_STATUS_PACKET = (byte) 0x02; - public static final byte SERVER_TO_CLIENT_HANDSHAKE_PACKET = (byte) 0x03; - public static final byte CLIENT_TO_SERVER_HANDSHAKE_PACKET = (byte) 0x04; - public static final byte DISCONNECT_PACKET = (byte) 0x05; - public static final byte RESOURCE_PACKS_INFO_PACKET = (byte) 0x06; - public static final byte RESOURCE_PACK_STACK_PACKET = (byte) 0x07; - public static final byte RESOURCE_PACK_CLIENT_RESPONSE_PACKET = (byte) 0x08; - public static final byte TEXT_PACKET = (byte) 0x09; - public static final byte SET_TIME_PACKET = (byte) 0x0a; - public static final byte START_GAME_PACKET = (byte) 0x0b; - public static final byte ADD_PLAYER_PACKET = (byte) 0x0c; - public static final byte ADD_ENTITY_PACKET = (byte) 0x0d; - public static final byte REMOVE_ENTITY_PACKET = (byte) 0x0e; - public static final byte ADD_ITEM_ENTITY_PACKET = (byte) 0x0f; - public static final byte ADD_HANGING_ENTITY_PACKET = (byte) 0x10; - public static final byte TAKE_ITEM_ENTITY_PACKET = (byte) 0x11; - public static final byte MOVE_ENTITY_PACKET = (byte) 0x12; - public static final byte MOVE_PLAYER_PACKET = (byte) 0x13; - public static final byte RIDER_JUMP_PACKET = (byte) 0x14; - public static final byte UPDATE_BLOCK_PACKET = (byte) 0x15; - public static final byte ADD_PAINTING_PACKET = (byte) 0x16; - public static final byte EXPLODE_PACKET = (byte) 0x17; - public static final byte LEVEL_SOUND_EVENT_PACKET = (byte) 0x18; - public static final byte LEVEL_EVENT_PACKET = (byte) 0x19; - public static final byte BLOCK_EVENT_PACKET = (byte) 0x1a; - public static final byte ENTITY_EVENT_PACKET = (byte) 0x1b; - public static final byte MOB_EFFECT_PACKET = (byte) 0x1c; - public static final byte UPDATE_ATTRIBUTES_PACKET = (byte) 0x1d; - public static final byte INVENTORY_TRANSACTION_PACKET = (byte) 0x1e; - public static final byte MOB_EQUIPMENT_PACKET = (byte) 0x1f; - public static final byte MOB_ARMOR_EQUIPMENT_PACKET = (byte) 0x20; - public static final byte INTERACT_PACKET = (byte) 0x21; - public static final byte BLOCK_PICK_REQUEST_PACKET = (byte) 0x22; - public static final byte ENTITY_PICK_REQUEST_PACKET = (byte) 0x23; - public static final byte PLAYER_ACTION_PACKET = (byte) 0x24; - public static final byte ENTITY_FALL_PACKET = (byte) 0x25; - public static final byte HURT_ARMOR_PACKET = (byte) 0x26; - public static final byte SET_ENTITY_DATA_PACKET = (byte) 0x27; - public static final byte SET_ENTITY_MOTION_PACKET = (byte) 0x28; - public static final byte SET_ENTITY_LINK_PACKET = (byte) 0x29; - public static final byte SET_HEALTH_PACKET = (byte) 0x2a; - public static final byte SET_SPAWN_POSITION_PACKET = (byte) 0x2b; - public static final byte ANIMATE_PACKET = (byte) 0x2c; - public static final byte RESPAWN_PACKET = (byte) 0x2d; - public static final byte CONTAINER_OPEN_PACKET = (byte) 0x2e; - public static final byte CONTAINER_CLOSE_PACKET = (byte) 0x2f; - public static final byte PLAYER_HOTBAR_PACKET = (byte) 0x30; - public static final byte INVENTORY_CONTENT_PACKET = (byte) 0x31; - public static final byte INVENTORY_SLOT_PACKET = (byte) 0x32; - public static final byte CONTAINER_SET_DATA_PACKET = (byte) 0x33; - public static final byte CRAFTING_DATA_PACKET = (byte) 0x34; - public static final byte CRAFTING_EVENT_PACKET = (byte) 0x35; - public static final byte GUI_DATA_PICK_ITEM_PACKET = (byte) 0x36; - public static final byte ADVENTURE_SETTINGS_PACKET = (byte) 0x37; - public static final byte BLOCK_ENTITY_DATA_PACKET = (byte) 0x38; - public static final byte PLAYER_INPUT_PACKET = (byte) 0x39; - public static final byte FULL_CHUNK_DATA_PACKET = (byte) 0x3a; - public static final byte SET_COMMANDS_ENABLED_PACKET = (byte) 0x3b; - public static final byte SET_DIFFICULTY_PACKET = (byte) 0x3c; - public static final byte CHANGE_DIMENSION_PACKET = (byte) 0x3d; - public static final byte SET_PLAYER_GAME_TYPE_PACKET = (byte) 0x3e; - public static final byte PLAYER_LIST_PACKET = (byte) 0x3f; - public static final byte SIMPLE_EVENT_PACKET = (byte) 0x40; - public static final byte EVENT_PACKET = (byte) 0x41; - public static final byte SPAWN_EXPERIENCE_ORB_PACKET = (byte) 0x42; - public static final byte CLIENTBOUND_MAP_ITEM_DATA_PACKET = (byte) 0x43; - public static final byte MAP_INFO_REQUEST_PACKET = (byte) 0x44; - public static final byte REQUEST_CHUNK_RADIUS_PACKET = (byte) 0x45; - public static final byte CHUNK_RADIUS_UPDATED_PACKET = (byte) 0x46; - public static final byte ITEM_FRAME_DROP_ITEM_PACKET = (byte) 0x47; - public static final byte GAME_RULES_CHANGED_PACKET = (byte) 0x48; - public static final byte CAMERA_PACKET = (byte) 0x49; - public static final byte BOSS_EVENT_PACKET = (byte) 0x4a; - public static final byte SHOW_CREDITS_PACKET = (byte) 0x4b; - public static final byte AVAILABLE_COMMANDS_PACKET = (byte) 0x4c; - public static final byte COMMAND_REQUEST_PACKET = (byte) 0x4d; - public static final byte COMMAND_BLOCK_UPDATE_PACKET = (byte) 0x4e; - public static final byte COMMAND_OUTPUT_PACKET = (byte) 0x4f; - public static final byte UPDATE_TRADE_PACKET = (byte) 0x50; - public static final byte UPDATE_EQUIP_PACKET = (byte) 0x51; - public static final byte RESOURCE_PACK_DATA_INFO_PACKET = (byte) 0x52; - public static final byte RESOURCE_PACK_CHUNK_DATA_PACKET = (byte) 0x53; - public static final byte RESOURCE_PACK_CHUNK_REQUEST_PACKET = (byte) 0x54; - public static final byte TRANSFER_PACKET = (byte) 0x55; - public static final byte PLAY_SOUND_PACKET = (byte) 0x56; - public static final byte STOP_SOUND_PACKET = (byte) 0x57; - public static final byte SET_TITLE_PACKET = (byte) 0x58; - public static final byte ADD_BEHAVIOR_TREE_PACKET = (byte) 0x59; - public static final byte STRUCTURE_BLOCK_UPDATE_PACKET = (byte) 0x5a; - public static final byte SHOW_STORE_OFFER_PACKET = (byte) 0x5b; - public static final byte PURCHASE_RECEIPT_PACKET = (byte) 0x5c; - public static final byte PLAYER_SKIN_PACKET = (byte) 0x5d; - public static final byte SUB_CLIENT_LOGIN_PACKET = (byte) 0x5e; - public static final byte W_S_CONNECT_PACKET = (byte) 0x5f; - public static final byte SET_LAST_HURT_BY_PACKET = (byte) 0x60; - public static final byte BOOK_EDIT_PACKET = (byte) 0x61; - public static final byte NPC_REQUEST_PACKET = (byte) 0x62; - public static final byte PHOTO_TRANSFER_PACKET = (byte) 0x63; - public static final byte MODAL_FORM_REQUEST_PACKET = (byte) 0x64; - public static final byte MODAL_FORM_RESPONSE_PACKET = (byte) 0x65; - public static final byte SERVER_SETTINGS_REQUEST_PACKET = (byte) 0x66; - public static final byte SERVER_SETTINGS_RESPONSE_PACKET = (byte) 0x67; - public static final byte SHOW_PROFILE_PACKET = (byte) 0x68; - public static final byte SET_DEFAULT_GAME_TYPE_PACKET = (byte) 0x69; - - // constructor - public ProtocolInfo() { - - } - - // public - - // private + /** + * Actual Minecraft: PE protocol version + */ + public static final int CURRENT_PROTOCOL = 160; + /** + * Current Minecraft PE version reported by the server. This is usually the + * earliest currently supported version. + */ + public static final String MINECRAFT_VERSION = "v1.2.7"; + /** + * Version number sent to clients in ping responses. + */ + public static final String MINECRAFT_VERSION_NETWORK = "1.2.7"; + public static final byte LOGIN_PACKET = (byte) 0x01; + public static final byte PLAY_STATUS_PACKET = (byte) 0x02; + public static final byte SERVER_TO_CLIENT_HANDSHAKE_PACKET = (byte) 0x03; + public static final byte CLIENT_TO_SERVER_HANDSHAKE_PACKET = (byte) 0x04; + public static final byte DISCONNECT_PACKET = (byte) 0x05; + public static final byte RESOURCE_PACKS_INFO_PACKET = (byte) 0x06; + public static final byte RESOURCE_PACK_STACK_PACKET = (byte) 0x07; + public static final byte RESOURCE_PACK_CLIENT_RESPONSE_PACKET = (byte) 0x08; + public static final byte TEXT_PACKET = (byte) 0x09; + public static final byte SET_TIME_PACKET = (byte) 0x0a; + public static final byte START_GAME_PACKET = (byte) 0x0b; + public static final byte ADD_PLAYER_PACKET = (byte) 0x0c; + public static final byte ADD_ENTITY_PACKET = (byte) 0x0d; + public static final byte REMOVE_ENTITY_PACKET = (byte) 0x0e; + public static final byte ADD_ITEM_ENTITY_PACKET = (byte) 0x0f; + public static final byte ADD_HANGING_ENTITY_PACKET = (byte) 0x10; + public static final byte TAKE_ITEM_ENTITY_PACKET = (byte) 0x11; + public static final byte MOVE_ENTITY_PACKET = (byte) 0x12; + public static final byte MOVE_PLAYER_PACKET = (byte) 0x13; + public static final byte RIDER_JUMP_PACKET = (byte) 0x14; + public static final byte UPDATE_BLOCK_PACKET = (byte) 0x15; + public static final byte ADD_PAINTING_PACKET = (byte) 0x16; + public static final byte EXPLODE_PACKET = (byte) 0x17; + public static final byte LEVEL_SOUND_EVENT_PACKET = (byte) 0x18; + public static final byte LEVEL_EVENT_PACKET = (byte) 0x19; + public static final byte BLOCK_EVENT_PACKET = (byte) 0x1a; + public static final byte ENTITY_EVENT_PACKET = (byte) 0x1b; + public static final byte MOB_EFFECT_PACKET = (byte) 0x1c; + public static final byte UPDATE_ATTRIBUTES_PACKET = (byte) 0x1d; + public static final byte INVENTORY_TRANSACTION_PACKET = (byte) 0x1e; + public static final byte MOB_EQUIPMENT_PACKET = (byte) 0x1f; + public static final byte MOB_ARMOR_EQUIPMENT_PACKET = (byte) 0x20; + public static final byte INTERACT_PACKET = (byte) 0x21; + public static final byte BLOCK_PICK_REQUEST_PACKET = (byte) 0x22; + public static final byte ENTITY_PICK_REQUEST_PACKET = (byte) 0x23; + public static final byte PLAYER_ACTION_PACKET = (byte) 0x24; + public static final byte ENTITY_FALL_PACKET = (byte) 0x25; + public static final byte HURT_ARMOR_PACKET = (byte) 0x26; + public static final byte SET_ENTITY_DATA_PACKET = (byte) 0x27; + public static final byte SET_ENTITY_MOTION_PACKET = (byte) 0x28; + public static final byte SET_ENTITY_LINK_PACKET = (byte) 0x29; + public static final byte SET_HEALTH_PACKET = (byte) 0x2a; + public static final byte SET_SPAWN_POSITION_PACKET = (byte) 0x2b; + public static final byte ANIMATE_PACKET = (byte) 0x2c; + public static final byte RESPAWN_PACKET = (byte) 0x2d; + public static final byte CONTAINER_OPEN_PACKET = (byte) 0x2e; + public static final byte CONTAINER_CLOSE_PACKET = (byte) 0x2f; + public static final byte PLAYER_HOTBAR_PACKET = (byte) 0x30; + public static final byte INVENTORY_CONTENT_PACKET = (byte) 0x31; + public static final byte INVENTORY_SLOT_PACKET = (byte) 0x32; + public static final byte CONTAINER_SET_DATA_PACKET = (byte) 0x33; + public static final byte CRAFTING_DATA_PACKET = (byte) 0x34; + public static final byte CRAFTING_EVENT_PACKET = (byte) 0x35; + public static final byte GUI_DATA_PICK_ITEM_PACKET = (byte) 0x36; + public static final byte ADVENTURE_SETTINGS_PACKET = (byte) 0x37; + public static final byte BLOCK_ENTITY_DATA_PACKET = (byte) 0x38; + public static final byte PLAYER_INPUT_PACKET = (byte) 0x39; + public static final byte FULL_CHUNK_DATA_PACKET = (byte) 0x3a; + public static final byte SET_COMMANDS_ENABLED_PACKET = (byte) 0x3b; + public static final byte SET_DIFFICULTY_PACKET = (byte) 0x3c; + public static final byte CHANGE_DIMENSION_PACKET = (byte) 0x3d; + public static final byte SET_PLAYER_GAME_TYPE_PACKET = (byte) 0x3e; + public static final byte PLAYER_LIST_PACKET = (byte) 0x3f; + public static final byte SIMPLE_EVENT_PACKET = (byte) 0x40; + public static final byte EVENT_PACKET = (byte) 0x41; + public static final byte SPAWN_EXPERIENCE_ORB_PACKET = (byte) 0x42; + public static final byte CLIENTBOUND_MAP_ITEM_DATA_PACKET = (byte) 0x43; + public static final byte MAP_INFO_REQUEST_PACKET = (byte) 0x44; + public static final byte REQUEST_CHUNK_RADIUS_PACKET = (byte) 0x45; + public static final byte CHUNK_RADIUS_UPDATED_PACKET = (byte) 0x46; + public static final byte ITEM_FRAME_DROP_ITEM_PACKET = (byte) 0x47; + public static final byte GAME_RULES_CHANGED_PACKET = (byte) 0x48; + public static final byte CAMERA_PACKET = (byte) 0x49; + public static final byte BOSS_EVENT_PACKET = (byte) 0x4a; + public static final byte SHOW_CREDITS_PACKET = (byte) 0x4b; + public static final byte AVAILABLE_COMMANDS_PACKET = (byte) 0x4c; + public static final byte COMMAND_REQUEST_PACKET = (byte) 0x4d; + public static final byte COMMAND_BLOCK_UPDATE_PACKET = (byte) 0x4e; + public static final byte COMMAND_OUTPUT_PACKET = (byte) 0x4f; + public static final byte UPDATE_TRADE_PACKET = (byte) 0x50; + public static final byte UPDATE_EQUIP_PACKET = (byte) 0x51; + public static final byte RESOURCE_PACK_DATA_INFO_PACKET = (byte) 0x52; + public static final byte RESOURCE_PACK_CHUNK_DATA_PACKET = (byte) 0x53; + public static final byte RESOURCE_PACK_CHUNK_REQUEST_PACKET = (byte) 0x54; + public static final byte TRANSFER_PACKET = (byte) 0x55; + public static final byte PLAY_SOUND_PACKET = (byte) 0x56; + public static final byte STOP_SOUND_PACKET = (byte) 0x57; + public static final byte SET_TITLE_PACKET = (byte) 0x58; + public static final byte ADD_BEHAVIOR_TREE_PACKET = (byte) 0x59; + public static final byte STRUCTURE_BLOCK_UPDATE_PACKET = (byte) 0x5a; + public static final byte SHOW_STORE_OFFER_PACKET = (byte) 0x5b; + public static final byte PURCHASE_RECEIPT_PACKET = (byte) 0x5c; + public static final byte PLAYER_SKIN_PACKET = (byte) 0x5d; + public static final byte SUB_CLIENT_LOGIN_PACKET = (byte) 0x5e; + public static final byte W_S_CONNECT_PACKET = (byte) 0x5f; + public static final byte SET_LAST_HURT_BY_PACKET = (byte) 0x60; + public static final byte BOOK_EDIT_PACKET = (byte) 0x61; + public static final byte NPC_REQUEST_PACKET = (byte) 0x62; + public static final byte PHOTO_TRANSFER_PACKET = (byte) 0x63; + public static final byte MODAL_FORM_REQUEST_PACKET = (byte) 0x64; + public static final byte MODAL_FORM_RESPONSE_PACKET = (byte) 0x65; + public static final byte SERVER_SETTINGS_REQUEST_PACKET = (byte) 0x66; + public static final byte SERVER_SETTINGS_RESPONSE_PACKET = (byte) 0x67; + public static final byte SHOW_PROFILE_PACKET = (byte) 0x68; + public static final byte SET_DEFAULT_GAME_TYPE_PACKET = (byte) 0x69; } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/AddEntityPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/AddEntityPacket.java index 9b1400296..5e15843e0 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/AddEntityPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/AddEntityPacket.java @@ -1,5 +1,6 @@ package org.dragonet.proxy.protocol.packets; +import java.util.Collection; import org.dragonet.proxy.data.entity.PEEntityAttribute; import org.dragonet.proxy.data.entity.meta.EntityMetaData; import org.dragonet.proxy.protocol.PEPacket; @@ -11,105 +12,104 @@ * Created on 2017/10/21. */ public class AddEntityPacket extends PEPacket { - //vars - public long eid; - public long rtid; - public int type; - public Vector3F position; - public Vector3F motion; - public float pitch; - public float yaw; - public EntityMetaData meta; - public PEEntityAttribute[] attributes; - public PEEntityLink[] links; - - //constructor - public AddEntityPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.ADD_ENTITY_PACKET; - } - - public void encodePayload() { - putVarLong(eid); - putUnsignedVarLong(rtid); - putUnsignedVarInt(type); - putVector3F(position); - putVector3F(motion); - putLFloat(pitch); - putLFloat(yaw); - if (attributes.length > 0) { - putUnsignedVarInt(attributes.length); - for (PEEntityAttribute attr : attributes) { - putString(attr.name); - putLFloat(attr.min); - putLFloat(attr.currentValue); - putLFloat(attr.max); - } - } else { - putUnsignedVarInt(0); - } + public long eid; + public long rtid; + public int type; + public Vector3F position; + public Vector3F motion; + public float pitch; + public float yaw; + public EntityMetaData meta; + public Collection attributes; + public PEEntityLink[] links; - if (meta != null) { - meta.encode(); - put(meta.getBuffer()); - } else { - putUnsignedVarInt(0); - } + public AddEntityPacket() { - if (links != null && links.length > 0) { - putUnsignedVarInt(links.length); - for (PEEntityLink l : links) { - putEntityLink(l); - } - } else { - putUnsignedVarInt(0); - } - } - /** - * decode will NOT work since meta decoding is not implemented - */ - public void decodePayload() { - eid = getVarLong(); - rtid = getUnsignedVarLong(); - type = (int) getUnsignedVarInt(); - position = getVector3F(); - motion = getVector3F(); - pitch = getLFloat(); - yaw = getLFloat(); + } - int lenAttr = (int) getUnsignedVarInt(); - attributes = new PEEntityAttribute[lenAttr]; - if (lenAttr > 0) { - for (int i = 0; i < lenAttr; i++) { - String name = getString(); - float min = getLFloat(); - float current = getLFloat(); - float max = getLFloat(); - attributes[i] = PEEntityAttribute.findAttribute(name); - if (attributes[i] != null) { - attributes[i].min = min; - attributes[i].max = max; - attributes[i].currentValue = current; - } - } - } + @Override + public int pid() { + return ProtocolInfo.ADD_ENTITY_PACKET; + } - // TODO: read meta!! + @Override + public void encodePayload() { + putVarLong(eid); + putUnsignedVarLong(rtid); + putUnsignedVarInt(type); + putVector3F(position); + putVector3F(motion); + putLFloat(pitch); + putLFloat(yaw); - int lenLinks = (int) getUnsignedVarInt(); - links = new PEEntityLink[lenLinks]; - if (lenLinks > 0) { - for (int i = 0; i < lenLinks; i++) { - links[i] = getEntityLink(); - } - } - } - - //private - + if (attributes!= null && attributes.size() > 0) { + putUnsignedVarInt(attributes.size()); + for (PEEntityAttribute attr : attributes) { + putString(attr.name); + putLFloat(attr.min); + putLFloat(attr.currentValue); + putLFloat(attr.max); + } + } else { + putUnsignedVarInt(0); + } + + if (meta != null) { + meta.encode(); + put(meta.getBuffer()); + } else { + putUnsignedVarInt(0); + } + + if (links != null && links.length > 0) { + putUnsignedVarInt(links.length); + for (PEEntityLink l : links) { + putEntityLink(l); + } + } else { + putUnsignedVarInt(0); + } + } + + /** + * decode will NOT work since meta decoding is not implemented + */ + @Override + public void decodePayload() { + eid = getVarLong(); + rtid = getUnsignedVarLong(); + type = (int) getUnsignedVarInt(); + position = getVector3F(); + motion = getVector3F(); + pitch = getLFloat(); + yaw = getLFloat(); + + int lenAttr = (int) getUnsignedVarInt(); + +// attributes = new PEEntityAttribute[lenAttr]; +// if (lenAttr > 0) { +// for (int i = 0; i < lenAttr; i++) { +// String name = getString(); +// float min = getLFloat(); +// float current = getLFloat(); +// float max = getLFloat(); +// attributes[i] = PEEntityAttribute.findAttribute(name); +// if (attributes[i] != null) { +// attributes[i].min = min; +// attributes[i].max = max; +// attributes[i].currentValue = current; +// } +// } +// } + + // TODO: read meta!! + int lenLinks = (int) getUnsignedVarInt(); + links = new PEEntityLink[lenLinks]; + if (lenLinks > 0) { + for (int i = 0; i < lenLinks; i++) { + links[i] = getEntityLink(); + } + } + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/AddItemEntityPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/AddItemEntityPacket.java index 0ab833427..14649b0a9 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/AddItemEntityPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/AddItemEntityPacket.java @@ -10,46 +10,45 @@ * Created on 2017/10/21. */ public class AddItemEntityPacket extends PEPacket { - //vars - public long rtid; - public long eid; - public Slot item; - public Vector3F position; - public Vector3F motion; - public EntityMetaData metadata; - - //constructor - public AddItemEntityPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.ADD_ITEM_ENTITY_PACKET; - } - - public void encodePayload() { - putVarLong(rtid); - putUnsignedVarLong(eid); - putSlot(item); - putVector3F(position); - putVector3F(position); - if (metadata != null) { - metadata.encode(); - put(metadata.getBuffer()); - } else { - putUnsignedVarInt(0); - } - } - public void decodePayload() { - rtid = getVarLong(); - eid = getUnsignedVarLong(); - item = getSlot(); - position = getVector3F(); - motion = getVector3F(); - metadata = EntityMetaData.from(this); - } - - //private - + + public long rtid; + public long eid; + public Slot item; + public Vector3F position; + public Vector3F motion; + public EntityMetaData metadata; + + public AddItemEntityPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.ADD_ITEM_ENTITY_PACKET; + } + + @Override + public void encodePayload() { + putVarLong(rtid); + putUnsignedVarLong(eid); + putSlot(item); + putVector3F(position); + putVector3F(position); + if (metadata != null) { + metadata.encode(); + put(metadata.getBuffer()); + } else { + putUnsignedVarInt(0); + } + } + + @Override + public void decodePayload() { + rtid = getVarLong(); + eid = getUnsignedVarLong(); + item = getSlot(); + position = getVector3F(); + motion = getVector3F(); + metadata = EntityMetaData.from(this); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/AddPaintingPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/AddPaintingPacket.java new file mode 100644 index 000000000..13a86528d --- /dev/null +++ b/src/main/java/org/dragonet/proxy/protocol/packets/AddPaintingPacket.java @@ -0,0 +1,35 @@ +package org.dragonet.proxy.protocol.packets; + +import org.dragonet.proxy.protocol.PEPacket; +import org.dragonet.proxy.protocol.ProtocolInfo; +import org.dragonet.proxy.utilities.BlockPosition; + +public class AddPaintingPacket extends PEPacket { + + public long eid; + public long rtid; + public BlockPosition pos; + public int direction; + public String title; + + @Override + public void decodePayload() { + + } + + @Override + public void encodePayload() { + this.reset(); + this.putEntityUniqueId(this.eid); + this.putEntityRuntimeId(this.rtid); + this.putBlockPosition(this.pos); + this.putVarInt(this.direction); + this.putString(this.title); + } + + @Override + public int pid() { + return ProtocolInfo.ADD_PAINTING_PACKET; + } + +} diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/AddPlayerPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/AddPlayerPacket.java index 98e85f943..6ad113192 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/AddPlayerPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/AddPlayerPacket.java @@ -13,93 +13,92 @@ * Created on 2017/10/21. */ public class AddPlayerPacket extends PEPacket { - //vars - public UUID uuid; - public String username; - public long eid; - public long rtid; - public Vector3F position; - public Vector3F motion; - public float pitch; - public float yaw; - public float headYaw; - public Slot item; - public EntityMetaData meta; - public PEEntityLink[] links; - - //constructor - public AddPlayerPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.ADD_PLAYER_PACKET; - } - - public void encodePayload() { - putUUID(uuid); - putString(username); - putVarLong(eid); - putUnsignedVarLong(rtid); - putVector3F(position); - putVector3F(motion); - putLFloat(pitch); - putLFloat(yaw); - putLFloat(headYaw); - putSlot(item); - if (meta != null) { - meta.encode(); - put(meta.getBuffer()); - } else { - putUnsignedVarInt(0); - } - putUnsignedVarInt(0); - putUnsignedVarInt(0); - putUnsignedVarInt(0); - putUnsignedVarInt(0); - putUnsignedVarInt(0); - putLLong(0L); - if (links != null && links.length > 0) { - putUnsignedVarInt(links.length); - for (PEEntityLink l : links) { - putEntityLink(l); - } - } else { - putUnsignedVarInt(0); - } - } - public void decodePayload() { - uuid = getUUID(); - username = getString(); - eid = getVarLong(); - rtid = getUnsignedVarLong(); - position = getVector3F(); - motion = getVector3F(); - pitch = getLFloat(); - yaw = getLFloat(); - headYaw = getLFloat(); - item = getSlot(); - // meta = getEntityMetadata(); - meta = EntityMetaData.createDefault(); // TODO - getUnsignedVarInt(); - getUnsignedVarInt(); - getUnsignedVarInt(); - getUnsignedVarInt(); - getUnsignedVarInt(); + public UUID uuid; + public String username; + public long eid; + public long rtid; + public Vector3F position; + public Vector3F motion; + public float pitch; + public float yaw; + public float headYaw; + public Slot item; + public EntityMetaData meta; + public PEEntityLink[] links; - getLLong(); + public AddPlayerPacket() { - int linkCount = (int) getUnsignedVarInt(); - links = new PEEntityLink[linkCount]; - if (linkCount > 0) { - for (int i = 0; i < linkCount; ++i) { - links[i] = getEntityLink(); - } - } - } - - //private - + } + + @Override + public int pid() { + return ProtocolInfo.ADD_PLAYER_PACKET; + } + + @Override + public void encodePayload() { + putUUID(uuid); + putString(username); + putVarLong(eid); + putUnsignedVarLong(rtid); + putVector3F(position); + putVector3F(motion); + putLFloat(pitch); + putLFloat(yaw); + putLFloat(headYaw); + putSlot(item); + if (meta != null) { + meta.encode(); + put(meta.getBuffer()); + } else { + putUnsignedVarInt(0); + } + putUnsignedVarInt(0); + putUnsignedVarInt(0); + putUnsignedVarInt(0); + putUnsignedVarInt(0); + putUnsignedVarInt(0); + putLLong(0L); + if (links != null && links.length > 0) { + putUnsignedVarInt(links.length); + for (PEEntityLink l : links) { + putEntityLink(l); + } + } else { + putUnsignedVarInt(0); + } + } + + @Override + public void decodePayload() { + uuid = getUUID(); + username = getString(); + eid = getVarLong(); + rtid = getUnsignedVarLong(); + position = getVector3F(); + motion = getVector3F(); + pitch = getLFloat(); + yaw = getLFloat(); + headYaw = getLFloat(); + item = getSlot(); + // meta = getEntityMetadata(); + meta = EntityMetaData.createDefault(); // TODO + + getUnsignedVarInt(); + getUnsignedVarInt(); + getUnsignedVarInt(); + getUnsignedVarInt(); + getUnsignedVarInt(); + + getLLong(); + + int linkCount = (int) getUnsignedVarInt(); + links = new PEEntityLink[linkCount]; + if (linkCount > 0) { + for (int i = 0; i < linkCount; ++i) { + links[i] = getEntityLink(); + } + } + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/AdventureSettingsPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/AdventureSettingsPacket.java index 49353e1bb..0b87555fc 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/AdventureSettingsPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/AdventureSettingsPacket.java @@ -7,7 +7,6 @@ * Created on 2017/10/21. */ public class AdventureSettingsPacket extends PEPacket { - //vars public static final int PERMISSION_NORMAL = 0; public static final int PERMISSION_OPERATOR = 1; @@ -28,7 +27,6 @@ public class AdventureSettingsPacket extends PEPacket { */ public static final int BITFLAG_SECOND_SET = 1 << 16; - //flags public static final int WORLD_IMMUTABLE = 0x01; public static final int NO_PVP = 0x02; public static final int AUTO_JUMP = 0x20; @@ -54,16 +52,16 @@ public class AdventureSettingsPacket extends PEPacket { public int customFlags; public long eid; - //constructor public AdventureSettingsPacket() { } - //public + @Override public int pid() { return ProtocolInfo.ADVENTURE_SETTINGS_PACKET; } + @Override public void encodePayload() { putUnsignedVarInt(flags); putUnsignedVarInt(commandsPermission); @@ -73,6 +71,7 @@ public void encodePayload() { putLLong(eid); } + @Override public void decodePayload() { flags = (int) getUnsignedVarInt(); commandsPermission = (int) getUnsignedVarInt(); @@ -107,6 +106,4 @@ public void setFlag(int flag, boolean value) { } } } - - //private } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/BlockEntityDataPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/BlockEntityDataPacket.java index f5848c0f3..49ad50513 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/BlockEntityDataPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/BlockEntityDataPacket.java @@ -4,52 +4,49 @@ import org.dragonet.proxy.protocol.ProtocolInfo; import org.dragonet.proxy.utilities.BlockPosition; -import com.github.steveice10.opennbt.NBTIO; -import com.github.steveice10.opennbt.tag.builtin.CompoundTag; - import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; +import java.nio.ByteOrder; +import org.dragonet.proxy.data.nbt.NBTIO; +import org.dragonet.proxy.data.nbt.tag.CompoundTag; /** * Created on 2017/10/22. */ public class BlockEntityDataPacket extends PEPacket { - //vars - public BlockPosition blockPosition; - public CompoundTag tag; - - //constructor - public BlockEntityDataPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.BLOCK_ENTITY_DATA_PACKET; - } - - public void encodePayload() { - putBlockPosition(blockPosition); - if (tag != null) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - NBTIO.writeTag(bos, tag); - bos.close(); - } catch (Exception e) { - e.printStackTrace(); - } - put(bos.toByteArray()); - } - } - public void decodePayload() { - blockPosition = getBlockPosition(); - try { - tag = (CompoundTag) NBTIO.readTag(new ByteArrayInputStream(get(getBuffer().length - offset))); - } catch (Exception e) { - e.printStackTrace(); - } - } - - //private - + + public BlockPosition blockPosition; + public CompoundTag tag; + + public BlockEntityDataPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.BLOCK_ENTITY_DATA_PACKET; + } + + @Override + public void encodePayload() { + putBlockPosition(blockPosition); + if (tag != null) { + byte[] bytes = new byte[]{}; + try { + bytes = NBTIO.write(tag, ByteOrder.LITTLE_ENDIAN, true); + } catch (Exception e) { + e.printStackTrace(); + } + put(bytes); + } + } + + @Override + public void decodePayload() { + blockPosition = getBlockPosition(); + try { + tag = (CompoundTag) NBTIO.read(get(), ByteOrder.LITTLE_ENDIAN, true); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/BlockEventPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/BlockEventPacket.java new file mode 100644 index 000000000..5d7890953 --- /dev/null +++ b/src/main/java/org/dragonet/proxy/protocol/packets/BlockEventPacket.java @@ -0,0 +1,31 @@ +package org.dragonet.proxy.protocol.packets; + +import org.dragonet.proxy.protocol.PEPacket; +import org.dragonet.proxy.protocol.ProtocolInfo; + +public class BlockEventPacket extends PEPacket { + + @Override + public int pid() { + return ProtocolInfo.BLOCK_EVENT_PACKET; + } + + public int x; + public int y; + public int z; + public int case1; + public int case2; + + @Override + public void decodePayload() { + + } + + @Override + public void encodePayload() { + this.reset(); + this.putBlockPosition(this.x, this.y, this.z); + this.putVarInt(this.case1); + this.putVarInt(this.case2); + } +} diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/ChangeDimensionPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/ChangeDimensionPacket.java index 054200e3b..33bc153ec 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/ChangeDimensionPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/ChangeDimensionPacket.java @@ -8,30 +8,29 @@ * Created on 2017/11/15. */ public class ChangeDimensionPacket extends PEPacket { - //vars - public int dimension; - public Vector3F position; - public boolean respawn; - - //constructor - public ChangeDimensionPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.CHANGE_DIMENSION_PACKET; - } - - public void encodePayload() { - putVarInt(dimension); - putVector3F(position); - putBoolean(respawn); - } - public void decodePayload() { - - } - - //private - + + public int dimension; + public Vector3F position; + public boolean respawn; + + public ChangeDimensionPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.CHANGE_DIMENSION_PACKET; + } + + @Override + public void encodePayload() { + putVarInt(dimension); + putVector3F(position); + putBoolean(respawn); + } + + @Override + public void decodePayload() { + + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/ChunkRadiusUpdatedPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/ChunkRadiusUpdatedPacket.java index fbd6f3407..42f24c116 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/ChunkRadiusUpdatedPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/ChunkRadiusUpdatedPacket.java @@ -7,29 +7,29 @@ * Created on 2017/10/22. */ public class ChunkRadiusUpdatedPacket extends PEPacket { - //vars - public int radius; - - //constructor - public ChunkRadiusUpdatedPacket() { - - } - public ChunkRadiusUpdatedPacket(int radius) { - this.radius = radius; - } - - //public - public int pid() { - return ProtocolInfo.CHUNK_RADIUS_UPDATED_PACKET; - } - - public void encodePayload() { - putVarInt(radius); - } - public void decodePayload() { - radius = getVarInt(); - } - - //private - + + public int radius; + + public ChunkRadiusUpdatedPacket() { + + } + + public ChunkRadiusUpdatedPacket(int radius) { + this.radius = radius; + } + + @Override + public int pid() { + return ProtocolInfo.CHUNK_RADIUS_UPDATED_PACKET; + } + + @Override + public void encodePayload() { + putVarInt(radius); + } + + @Override + public void decodePayload() { + radius = getVarInt(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/CommandRequestPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/CommandRequestPacket.java index 60a405a7a..5f6cb0142 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/CommandRequestPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/CommandRequestPacket.java @@ -7,26 +7,25 @@ * Created on 2017/11/15. */ public class CommandRequestPacket extends PEPacket { - //vars - public String command; - - //constructor - public CommandRequestPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.COMMAND_REQUEST_PACKET; - } - - public void encodePayload() { - putString(command); - } - public void decodePayload() { - command = getString(); - } - - //private - + + public String command; + + public CommandRequestPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.COMMAND_REQUEST_PACKET; + } + + @Override + public void encodePayload() { + putString(command); + } + + @Override + public void decodePayload() { + command = getString(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/ContainerClosePacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/ContainerClosePacket.java index 015352d92..ba201d333 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/ContainerClosePacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/ContainerClosePacket.java @@ -7,29 +7,29 @@ * Created on 2017/10/21. */ public class ContainerClosePacket extends PEPacket { - //vars - public int windowId; - - //constructor - public ContainerClosePacket() { - - } - public ContainerClosePacket(int windowId) { - this.windowId = windowId; - } - - //public - public int pid() { - return ProtocolInfo.CONTAINER_CLOSE_PACKET; - } - - public void encodePayload() { - putByte((byte) (windowId & 0xFF)); - } - public void decodePayload() { - windowId = getByte(); - } - - //private - + + public int windowId; + + public ContainerClosePacket() { + + } + + public ContainerClosePacket(int windowId) { + this.windowId = windowId; + } + + @Override + public int pid() { + return ProtocolInfo.CONTAINER_CLOSE_PACKET; + } + + @Override + public void encodePayload() { + putByte((byte) (windowId & 0xFF)); + } + + @Override + public void decodePayload() { + windowId = getByte(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/ContainerOpenPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/ContainerOpenPacket.java index 206099e3b..acadf663e 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/ContainerOpenPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/ContainerOpenPacket.java @@ -8,32 +8,32 @@ * Created on 2017/10/21. */ public class ContainerOpenPacket extends PEPacket { - //vars - public int windowId; - public int type; - public BlockPosition position; - public long eid; - - //constructor - - //public - public int pid() { - return ProtocolInfo.CONTAINER_OPEN_PACKET; - } - - public void encodePayload() { - putByte((byte) (windowId & 0xFF)); - putByte((byte) (type & 0xFF)); - putBlockPosition(position); - putVarLong(eid); - } - public void decodePayload() { - windowId = getByte(); - type = getByte(); - position = getBlockPosition(); - eid = getVarLong(); - } - - //private - + + public int windowId; + public int type; + public BlockPosition position; + public long eid; + + @Override + public int pid() { + return ProtocolInfo.CONTAINER_OPEN_PACKET; + } + + @Override + public void encodePayload() { + putByte((byte) (windowId)); + putByte((byte) (type)); + putBlockPosition(position); + putVarLong(eid); + } + + @Override + public void decodePayload() { + windowId = getByte(); + type = getByte(); + position = getBlockPosition(); + eid = getVarLong(); + } + + //private } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/DisconnectPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/DisconnectPacket.java index 4dc0f8390..e4b82f3ba 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/DisconnectPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/DisconnectPacket.java @@ -7,33 +7,33 @@ * Created on 2017/10/21. */ public class DisconnectPacket extends PEPacket { - //vars - public boolean hideDisconnectionScreen; - public String message; - - //constructor - public DisconnectPacket() { - - } - public DisconnectPacket(boolean hideDisconnectionScreen, String message) { - this.hideDisconnectionScreen = hideDisconnectionScreen; - this.message = message; - } - - //public - public int pid() { - return ProtocolInfo.DISCONNECT_PACKET; - } - - public void encodePayload() { - putBoolean(hideDisconnectionScreen); - putString(message); - } - public void decodePayload() { - hideDisconnectionScreen = getBoolean(); - message = getString(); - } - - //private - + + public boolean hideDisconnectionScreen; + public String message; + + public DisconnectPacket() { + + } + + public DisconnectPacket(boolean hideDisconnectionScreen, String message) { + this.hideDisconnectionScreen = hideDisconnectionScreen; + this.message = message; + } + + @Override + public int pid() { + return ProtocolInfo.DISCONNECT_PACKET; + } + + @Override + public void encodePayload() { + putBoolean(hideDisconnectionScreen); + putString(message); + } + + @Override + public void decodePayload() { + hideDisconnectionScreen = getBoolean(); + message = getString(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/FullChunkDataPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/FullChunkDataPacket.java index cbc3765cd..8c926b1b4 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/FullChunkDataPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/FullChunkDataPacket.java @@ -7,41 +7,42 @@ * Created on 2017/10/21. */ public class FullChunkDataPacket extends PEPacket { - //vars - public int x; - public int z; - public byte[] payload; - - //constructor - public FullChunkDataPacket() { - - } - public FullChunkDataPacket(int x, int z) { - this.x = x; - this.z = z; - } - public FullChunkDataPacket(int x, int z, byte[] payload) { - this.x = x; - this.z = z; - this.payload = payload; - } - - //public - public int pid() { - return ProtocolInfo.FULL_CHUNK_DATA_PACKET; - } - - public void decodePayload() { - x = getVarInt(); - z = getVarInt(); - payload = getByteArray(); - } - public void encodePayload() { - putVarInt(x); - putVarInt(z); - putByteArray(payload); - } - - //private - + + public int x; + public int z; + public byte[] payload; + + public FullChunkDataPacket() { + + } + + public FullChunkDataPacket(int x, int z) { + this.x = x; + this.z = z; + } + + public FullChunkDataPacket(int x, int z, byte[] payload) { + this.x = x; + this.z = z; + this.payload = payload; + } + + @Override + public int pid() { + return ProtocolInfo.FULL_CHUNK_DATA_PACKET; + } + + @Override + public void decodePayload() { + x = getVarInt(); + z = getVarInt(); + payload = getByteArray(); + } + + @Override + public void encodePayload() { + putVarInt(x); + putVarInt(z); + putByteArray(payload); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/InteractPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/InteractPacket.java index 1e1e7dd59..6586b5ed5 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/InteractPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/InteractPacket.java @@ -8,42 +8,41 @@ * Created on 2017/10/22. */ public class InteractPacket extends PEPacket { - //vars - public static final byte ACTION_RIGHT_CLICK = 1; - public static final byte ACTION_LEFT_CLICK = 2; - public static final byte ACTION_LEAVE_VEHICLE = 3; - public static final byte ACTION_MOUSEOVER = 4; - public static final byte ACTION_OPEN_INVENTORY = 6; - - public byte type; - public long targetRtid; - public Vector3F position; - - //constructor - public InteractPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.INTERACT_PACKET; - } - - public void encodePayload() { - putByte(type); - putUnsignedVarLong(targetRtid); - if (type == ACTION_MOUSEOVER) { - putVector3F(position); - } - } - public void decodePayload() { - type = (byte) (getByte() & 0xFF); - targetRtid = getUnsignedVarLong(); - if (type == ACTION_MOUSEOVER) { - position = getVector3F(); - } - } - - //private - + + public static final byte ACTION_RIGHT_CLICK = 1; + public static final byte ACTION_LEFT_CLICK = 2; + public static final byte ACTION_LEAVE_VEHICLE = 3; + public static final byte ACTION_MOUSEOVER = 4; + public static final byte ACTION_OPEN_INVENTORY = 6; + + public byte type; + public long targetRtid; + public Vector3F position; + + public InteractPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.INTERACT_PACKET; + } + + @Override + public void encodePayload() { + putByte(type); + putUnsignedVarLong(targetRtid); + if (type == ACTION_MOUSEOVER) { + putVector3F(position); + } + } + + @Override + public void decodePayload() { + type = (byte) (getByte() & 0xFF); + targetRtid = getUnsignedVarLong(); + if (type == ACTION_MOUSEOVER) { + position = getVector3F(); + } + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/InventoryContentPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/InventoryContentPacket.java index 38eb3b3d0..9e6ace3df 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/InventoryContentPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/InventoryContentPacket.java @@ -8,39 +8,37 @@ * Created on 2017/10/21. */ public class InventoryContentPacket extends PEPacket { - //vars - public int windowId; - public Slot[] items; - - //constructor - - //public - public int pid() { - return ProtocolInfo.INVENTORY_CONTENT_PACKET; - } - - public void encodePayload() { - putUnsignedVarInt(windowId); - if (items != null && items.length > 0) { - putUnsignedVarInt(items.length); - for (Slot s : items) { - putSlot(s); - } - } else { - putUnsignedVarInt(0); - } - } - public void decodePayload() { - windowId = (int) getUnsignedVarInt(); - int count = (int) getUnsignedVarInt(); - items = new Slot[count]; - if (count > 0) { - for (int i = 0; i < count; i++) { - items[i] = getSlot(); - } - } - } - - //private - + + public int windowId; + public Slot[] items; + + @Override + public int pid() { + return ProtocolInfo.INVENTORY_CONTENT_PACKET; + } + + @Override + public void encodePayload() { + putUnsignedVarInt(windowId); + if (items != null && items.length > 0) { + putUnsignedVarInt(items.length); + for (Slot s : items) { + putSlot(s); + } + } else { + putUnsignedVarInt(0); + } + } + + @Override + public void decodePayload() { + windowId = (int) getUnsignedVarInt(); + int count = (int) getUnsignedVarInt(); + items = new Slot[count]; + if (count > 0) { + for (int i = 0; i < count; i++) { + items[i] = getSlot(); + } + } + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/InventorySlotPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/InventorySlotPacket.java index bcc9c756e..62fc89124 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/InventorySlotPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/InventorySlotPacket.java @@ -8,32 +8,31 @@ * Created on 2017/10/21. */ public class InventorySlotPacket extends PEPacket { - //vars - public int windowId; - public int slotId; - public Slot item; - - //constructor - public InventorySlotPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.INVENTORY_SLOT_PACKET; - } - - public void encodePayload() { - putUnsignedVarInt(windowId); - putUnsignedVarInt(slotId); - putSlot(item); - } - public void decodePayload() { - windowId = (int) getUnsignedVarInt(); - slotId = (int) getUnsignedVarInt(); - item = getSlot(); - } - - //private - + + public int windowId; + public int slotId; + public Slot item; + + public InventorySlotPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.INVENTORY_SLOT_PACKET; + } + + @Override + public void encodePayload() { + putUnsignedVarInt(windowId); + putUnsignedVarInt(slotId); + putSlot(item); + } + + @Override + public void decodePayload() { + windowId = (int) getUnsignedVarInt(); + slotId = (int) getUnsignedVarInt(); + item = getSlot(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/InventoryTransactionPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/InventoryTransactionPacket.java index 05c469892..ef53a1e24 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/InventoryTransactionPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/InventoryTransactionPacket.java @@ -11,8 +11,8 @@ /** * Created on 2017/10/21. */ -public class InventoryTransactionPacket extends PEPacket -{ +public class InventoryTransactionPacket extends PEPacket { + public static final int TYPE_NORMAL = 0; public static final int TYPE_MISMATCH = 1; public static final int TYPE_USE_ITEM = 2; @@ -29,7 +29,6 @@ public class InventoryTransactionPacket extends PEPacket public static final int USE_ITEM_ON_ENTITY_ACTION_INTERACT = 0; public static final int USE_ITEM_ON_ENTITY_ACTION_ATTACK = 1; - public static final int ACTION_MAGIC_SLOT_DROP_ITEM = 0; public static final int ACTION_MAGIC_SLOT_PICKUP_ITEM = 1; @@ -146,7 +145,4 @@ public void decodePayload() { throw new RuntimeException("Unknown transaction type " + this.transactionType); } } - - //private - } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/LevelEventPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/LevelEventPacket.java index 9b9d5dff8..94392f516 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/LevelEventPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/LevelEventPacket.java @@ -8,110 +8,109 @@ * Created on 2017/10/21. */ public class LevelEventPacket extends PEPacket { - //vars - public static final int EVENT_SOUND_CLICK = 1000; - public static final int EVENT_SOUND_CLICK_FAIL = 1001; - public static final int EVENT_SOUND_SHOOT = 1002; - public static final int EVENT_SOUND_DOOR = 1003; - public static final int EVENT_SOUND_FIZZ = 1004; - public static final int EVENT_SOUND_IGNITE = 1005; - - public static final int EVENT_SOUND_GHAST = 1007; - public static final int EVENT_SOUND_GHAST_SHOOT = 1008; - public static final int EVENT_SOUND_BLAZE_SHOOT = 1009; - public static final int EVENT_SOUND_DOOR_BUMP = 1010; - - public static final int EVENT_SOUND_DOOR_CRASH = 1012; - - public static final int EVENT_SOUND_ENDERMAN_TELEPORT = 1018; - - public static final int EVENT_SOUND_ANVIL_BREAK = 1020; - public static final int EVENT_SOUND_ANVIL_USE = 1021; - public static final int EVENT_SOUND_ANVIL_FALL = 1022; - - public static final int EVENT_SOUND_POP = 1030; - - public static final int EVENT_SOUND_PORTAL = 1032; - - public static final int EVENT_SOUND_ITEMFRAME_ADD_ITEM = 1040; - public static final int EVENT_SOUND_ITEMFRAME_REMOVE = 1041; - public static final int EVENT_SOUND_ITEMFRAME_PLACE = 1042; - public static final int EVENT_SOUND_ITEMFRAME_REMOVE_ITEM = 1043; - public static final int EVENT_SOUND_ITEMFRAME_ROTATE_ITEM = 1044; - - public static final int EVENT_SOUND_CAMERA = 1050; - public static final int EVENT_SOUND_ORB = 1051; - public static final int EVENT_SOUND_TOTEM = 1052; - - public static final int EVENT_SOUND_ARMOR_STAND_BREAK = 1060; - public static final int EVENT_SOUND_ARMOR_STAND_HIT = 1061; - public static final int EVENT_SOUND_ARMOR_STAND_FALL = 1062; - public static final int EVENT_SOUND_ARMOR_STAND_PLACE = 1063; - - // TODO: check 2000-2017 - public static final int EVENT_PARTICLE_SHOOT = 2000; - public static final int EVENT_PARTICLE_DESTROY = 2001; - public static final int EVENT_PARTICLE_SPLASH = 2002; - public static final int EVENT_PARTICLE_EYE_DESPAWN = 2003; - public static final int EVENT_PARTICLE_SPAWN = 2004; - - public static final int EVENT_GUARDIAN_CURSE = 2006; - - public static final int EVENT_PARTICLE_BLOCK_FORCE_FIELD = 2008; - - public static final int EVENT_PARTICLE_PUNCH_BLOCK = 2014; - - public static final int EVENT_START_RAIN = 3001; - public static final int EVENT_START_THUNDER = 3002; - public static final int EVENT_STOP_RAIN = 3003; - public static final int EVENT_STOP_THUNDER = 3004; - public static final int EVENT_PAUSE_GAME = 3005; // data: 1 to pause, 0 to resume - - public static final int EVENT_REDSTONE_TRIGGER = 3500; - public static final int EVENT_CAULDRON_EXPLODE = 3501; - public static final int EVENT_CAULDRON_DYE_ARMOR = 3502; - public static final int EVENT_CAULDRON_CLEAN_ARMOR = 3503; - public static final int EVENT_CAULDRON_FILL_POTION = 3504; - public static final int EVENT_CAULDRON_TAKE_POTION = 3505; - public static final int EVENT_CAULDRON_FILL_WATER = 3506; - public static final int EVENT_CAULDRON_TAKE_WATER = 3507; - public static final int EVENT_CAULDRON_ADD_DYE = 3508; - public static final int EVENT_CAULDRON_CLEAN_BANNER = 3509; - - public static final int EVENT_BLOCK_START_BREAK = 3600; - public static final int EVENT_BLOCK_STOP_BREAK = 3601; - - public static final int EVENT_SET_DATA = 4000; - - public static final int EVENT_PLAYERS_SLEEPING = 9800; - - public static final int EVENT_ADD_PARTICLE_MASK = 0x4000; - - public int eventId; - public Vector3F position; - public int data; - - //constructor - public LevelEventPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.LEVEL_EVENT_PACKET; - } - - public void encodePayload() { - putVarInt(eventId); - putVector3F(position); - putVarInt(data); - } - public void decodePayload() { - eventId = getVarInt(); - position = getVector3F(); - data = getVarInt(); - } - - //private - + + public static final int EVENT_SOUND_CLICK = 1000; + public static final int EVENT_SOUND_CLICK_FAIL = 1001; + public static final int EVENT_SOUND_SHOOT = 1002; + public static final int EVENT_SOUND_DOOR = 1003; + public static final int EVENT_SOUND_FIZZ = 1004; + public static final int EVENT_SOUND_IGNITE = 1005; + + public static final int EVENT_SOUND_GHAST = 1007; + public static final int EVENT_SOUND_GHAST_SHOOT = 1008; + public static final int EVENT_SOUND_BLAZE_SHOOT = 1009; + public static final int EVENT_SOUND_DOOR_BUMP = 1010; + + public static final int EVENT_SOUND_DOOR_CRASH = 1012; + + public static final int EVENT_SOUND_ENDERMAN_TELEPORT = 1018; + + public static final int EVENT_SOUND_ANVIL_BREAK = 1020; + public static final int EVENT_SOUND_ANVIL_USE = 1021; + public static final int EVENT_SOUND_ANVIL_FALL = 1022; + + public static final int EVENT_SOUND_POP = 1030; + + public static final int EVENT_SOUND_PORTAL = 1032; + + public static final int EVENT_SOUND_ITEMFRAME_ADD_ITEM = 1040; + public static final int EVENT_SOUND_ITEMFRAME_REMOVE = 1041; + public static final int EVENT_SOUND_ITEMFRAME_PLACE = 1042; + public static final int EVENT_SOUND_ITEMFRAME_REMOVE_ITEM = 1043; + public static final int EVENT_SOUND_ITEMFRAME_ROTATE_ITEM = 1044; + + public static final int EVENT_SOUND_CAMERA = 1050; + public static final int EVENT_SOUND_ORB = 1051; + public static final int EVENT_SOUND_TOTEM = 1052; + + public static final int EVENT_SOUND_ARMOR_STAND_BREAK = 1060; + public static final int EVENT_SOUND_ARMOR_STAND_HIT = 1061; + public static final int EVENT_SOUND_ARMOR_STAND_FALL = 1062; + public static final int EVENT_SOUND_ARMOR_STAND_PLACE = 1063; + + // TODO: check 2000-2017 + public static final int EVENT_PARTICLE_SHOOT = 2000; + public static final int EVENT_PARTICLE_DESTROY = 2001; + public static final int EVENT_PARTICLE_SPLASH = 2002; + public static final int EVENT_PARTICLE_EYE_DESPAWN = 2003; + public static final int EVENT_PARTICLE_SPAWN = 2004; + + public static final int EVENT_GUARDIAN_CURSE = 2006; + + public static final int EVENT_PARTICLE_BLOCK_FORCE_FIELD = 2008; + + public static final int EVENT_PARTICLE_PUNCH_BLOCK = 2014; + + public static final int EVENT_START_RAIN = 3001; + public static final int EVENT_START_THUNDER = 3002; + public static final int EVENT_STOP_RAIN = 3003; + public static final int EVENT_STOP_THUNDER = 3004; + public static final int EVENT_PAUSE_GAME = 3005; // data: 1 to pause, 0 to resume + + public static final int EVENT_REDSTONE_TRIGGER = 3500; + public static final int EVENT_CAULDRON_EXPLODE = 3501; + public static final int EVENT_CAULDRON_DYE_ARMOR = 3502; + public static final int EVENT_CAULDRON_CLEAN_ARMOR = 3503; + public static final int EVENT_CAULDRON_FILL_POTION = 3504; + public static final int EVENT_CAULDRON_TAKE_POTION = 3505; + public static final int EVENT_CAULDRON_FILL_WATER = 3506; + public static final int EVENT_CAULDRON_TAKE_WATER = 3507; + public static final int EVENT_CAULDRON_ADD_DYE = 3508; + public static final int EVENT_CAULDRON_CLEAN_BANNER = 3509; + + public static final int EVENT_BLOCK_START_BREAK = 3600; + public static final int EVENT_BLOCK_STOP_BREAK = 3601; + + public static final int EVENT_SET_DATA = 4000; + + public static final int EVENT_PLAYERS_SLEEPING = 9800; + + public static final int EVENT_ADD_PARTICLE_MASK = 0x4000; + + public int eventId; + public Vector3F position; + public int data; + + public LevelEventPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.LEVEL_EVENT_PACKET; + } + + @Override + public void encodePayload() { + putVarInt(eventId); + putVector3F(position); + putVarInt(data); + } + + @Override + public void decodePayload() { + eventId = getVarInt(); + position = getVector3F(); + data = getVarInt(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/LoginPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/LoginPacket.java index 8ad48545a..9268f49df 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/LoginPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/LoginPacket.java @@ -9,42 +9,41 @@ * Created on 2017/10/21. */ public class LoginPacket extends PEPacket { - //vars - public int protocol; - public LoginChainDecoder decoded; - - //constructor - public LoginPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.LOGIN_PACKET; - } - - public void decodePayload() { - protocol = getInt(); - - if (protocol != ProtocolInfo.CURRENT_PROTOCOL) { - if (protocol > 0xffff) { // guess MCPE <= 1.1 - offset -= 6; - protocol = getInt(); - } - return; // Do not attempt to continue decoding for non-accepted protocols - } - - byte[] payload = getByteArray(); - BinaryStream bin = new BinaryStream(payload); - byte[] chain = bin.get(bin.getLInt()); - byte[] client = bin.get(bin.getLInt()); - decoded = new LoginChainDecoder(chain, client); - decoded.decode(); - } - public void encodePayload() { - // TODO - } - - //private - + + public int protocol; + public LoginChainDecoder decoded; + + public LoginPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.LOGIN_PACKET; + } + + @Override + public void decodePayload() { + protocol = getInt(); + + if (protocol != ProtocolInfo.CURRENT_PROTOCOL) { + if (protocol > 0xffff) { // guess MCPE <= 1.1 + offset -= 6; + protocol = getInt(); + } + return; // Do not attempt to continue decoding for non-accepted protocols + } + + byte[] payload = getByteArray(); + BinaryStream bin = new BinaryStream(payload); + byte[] chain = bin.get(bin.getLInt()); + byte[] client = bin.get(bin.getLInt()); + decoded = new LoginChainDecoder(chain, client); + decoded.decode(); + } + + @Override + public void encodePayload() { + // TODO + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/MobEffectPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/MobEffectPacket.java index 01720d879..78561fecf 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/MobEffectPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/MobEffectPacket.java @@ -7,45 +7,44 @@ * Created on 2017/10/21. */ public class MobEffectPacket extends PEPacket { - //vars - public static final byte EVENT_ADD = 1; - public static final byte EVENT_MODIFY = 2; - public static final byte EVENT_REMOVE = 3; - - public long rtid; - public byte eventId; - public int effectId; - public int amplifier; - public boolean particles; - public int duration; - - //constructor - public MobEffectPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.MOB_EFFECT_PACKET; - } - - public void encodePayload() { - putUnsignedVarLong(rtid); - putByte(eventId); - putVarInt(effectId); - putVarInt(amplifier); - putBoolean(particles); - putVarInt(duration); - } - public void decodePayload() { - rtid = getUnsignedVarLong(); - eventId = (byte) (getByte() & 0xFF); - effectId = getVarInt(); - amplifier = getVarInt(); - particles = getBoolean(); - duration = getVarInt(); - } - - //private - + + public static final byte EVENT_ADD = 1; + public static final byte EVENT_MODIFY = 2; + public static final byte EVENT_REMOVE = 3; + + public long rtid; + public byte eventId; + public int effectId; + public int amplifier; + public boolean particles; + public int duration; + + public MobEffectPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.MOB_EFFECT_PACKET; + } + + @Override + public void encodePayload() { + putUnsignedVarLong(rtid); + putByte(eventId); + putVarInt(effectId); + putVarInt(amplifier); + putBoolean(particles); + putVarInt(duration); + } + + @Override + public void decodePayload() { + rtid = getUnsignedVarLong(); + eventId = (byte) (getByte() & 0xFF); + effectId = getVarInt(); + amplifier = getVarInt(); + particles = getBoolean(); + duration = getVarInt(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/MobEquipmentPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/MobEquipmentPacket.java index 9dfca57d6..1feb60853 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/MobEquipmentPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/MobEquipmentPacket.java @@ -8,35 +8,33 @@ * Created on 2017/10/22. */ public class MobEquipmentPacket extends PEPacket { - //vars - public long rtid; - public Slot item; - public int inventorySlot; - public int hotbarSlot; - public int windowId; - - //constructor - - //public - public int pid() { - return ProtocolInfo.MOB_EQUIPMENT_PACKET; - } - - public void encodePayload() { - putUnsignedVarLong(rtid); - putSlot(item); - putByte((byte) (inventorySlot & 0xFF)); - putByte((byte) (hotbarSlot & 0xFF)); - putByte((byte) (windowId & 0xFF)); - } - public void decodePayload() { - rtid = getUnsignedVarLong(); - item = getSlot(); - inventorySlot = getByte(); - hotbarSlot = getByte(); - windowId = getByte(); - } - - //private - + + public long rtid; + public Slot item; + public int inventorySlot; + public int hotbarSlot; + public int windowId; + + @Override + public int pid() { + return ProtocolInfo.MOB_EQUIPMENT_PACKET; + } + + @Override + public void encodePayload() { + putUnsignedVarLong(rtid); + putSlot(item); + putByte((byte) (inventorySlot & 0xFF)); + putByte((byte) (hotbarSlot & 0xFF)); + putByte((byte) (windowId & 0xFF)); + } + + @Override + public void decodePayload() { + rtid = getUnsignedVarLong(); + item = getSlot(); + inventorySlot = getByte(); + hotbarSlot = getByte(); + windowId = getByte(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/MoveEntityPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/MoveEntityPacket.java index 80abb61e3..1b6d870f6 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/MoveEntityPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/MoveEntityPacket.java @@ -8,44 +8,43 @@ * Created on 2017/10/21. */ public class MoveEntityPacket extends PEPacket { - //vars - public long rtid; - public Vector3F position; - public float yaw; - public float headYaw; - public float pitch; - public boolean onGround; - public boolean teleported; - - //constructor - public MoveEntityPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.MOVE_ENTITY_PACKET; - } - - public void encodePayload() { - putUnsignedVarLong(rtid); - putVector3F(position); - putByteRotation(pitch); - putByteRotation(headYaw); - putByteRotation(yaw); - putBoolean(onGround); - putBoolean(teleported); - } - public void decodePayload() { - rtid = getUnsignedVarLong(); - position = getVector3F(); - pitch = getByteRotation(); - headYaw = getByteRotation(); - yaw = getByteRotation(); - onGround = getBoolean(); - teleported = getBoolean(); - } - - //private - + + public long rtid; + public Vector3F position; + public float yaw; + public float headYaw; + public float pitch; + public boolean onGround; + public boolean teleported; + + public MoveEntityPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.MOVE_ENTITY_PACKET; + } + + @Override + public void encodePayload() { + putUnsignedVarLong(rtid); + putVector3F(position); + putByteRotation(pitch); + putByteRotation(headYaw); + putByteRotation(yaw); + putBoolean(onGround); + putBoolean(teleported); + } + + @Override + public void decodePayload() { + rtid = getUnsignedVarLong(); + position = getVector3F(); + pitch = getByteRotation(); + headYaw = getByteRotation(); + yaw = getByteRotation(); + onGround = getBoolean(); + teleported = getBoolean(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/MovePlayerPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/MovePlayerPacket.java index 72e886053..50cdfbefd 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/MovePlayerPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/MovePlayerPacket.java @@ -8,60 +8,59 @@ * Created on 2017/10/21. */ public class MovePlayerPacket extends PEPacket { - //vars - public static final byte MODE_NORMAL = 0; - public static final byte MODE_RESET = 1; - public static final byte MODE_TELEPORT = 2; - public static final byte MODE_PITCH = 3; - - public long rtid; - public Vector3F position; - public float pitch; - public float yaw; - public float headYaw; - public byte mode; - public boolean onGround; - public long ridingRuntimeId; - - //constructor - public MovePlayerPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.MOVE_PLAYER_PACKET; - } - - public void encodePayload() { - putUnsignedVarLong(rtid); - putVector3F(position); - putLFloat(pitch); - putLFloat(yaw); - putLFloat(headYaw); - putByte(mode); - putBoolean(onGround); - putUnsignedVarLong(ridingRuntimeId); - if (mode == MODE_TELEPORT) { - putLInt(0); - putLInt(0); - } - } - public void decodePayload() { - rtid = getUnsignedVarLong(); - position = getVector3F(); - pitch = getLFloat(); - yaw = getLFloat(); - headYaw = getLFloat(); - mode = (byte) (getByte() & 0xFF); - onGround = getBoolean(); - ridingRuntimeId = getUnsignedVarLong(); - // if(mode == MODE_TELEPORT) { - // getLInt(); - // getLInt(); - // } - } - - //private - + + public static final byte MODE_NORMAL = 0; + public static final byte MODE_RESET = 1; + public static final byte MODE_TELEPORT = 2; + public static final byte MODE_PITCH = 3; + + public long rtid; + public Vector3F position; + public float pitch; + public float yaw; + public float headYaw; + public byte mode; + public boolean onGround; + public long ridingRuntimeId; + + public MovePlayerPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.MOVE_PLAYER_PACKET; + } + + @Override + public void encodePayload() { + putUnsignedVarLong(rtid); + putVector3F(position); + putLFloat(pitch); + putLFloat(yaw); + putLFloat(headYaw); + putByte(mode); + putBoolean(onGround); + putUnsignedVarLong(ridingRuntimeId); + if (mode == MODE_TELEPORT) { + putLInt(0); + putLInt(0); + } + } + + @Override + public void decodePayload() { + rtid = getUnsignedVarLong(); + position = getVector3F(); + pitch = getLFloat(); + yaw = getLFloat(); + headYaw = getLFloat(); + mode = (byte) (getByte() & 0xFF); + onGround = getBoolean(); + ridingRuntimeId = getUnsignedVarLong(); + // if(mode == MODE_TELEPORT) { + // getLInt(); + // getLInt(); + // } + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/PlaySoundPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/PlaySoundPacket.java index 03adc7d0a..bc77b208e 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/PlaySoundPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/PlaySoundPacket.java @@ -8,38 +8,37 @@ * Created on 2017/10/21. */ public class PlaySoundPacket extends PEPacket { - //vars - public String name; - public BlockPosition blockPosition; - public float volume; - public float pitch; - - //constructor - public PlaySoundPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.PLAY_SOUND_PACKET; - } - - public void encodePayload() { - putString(name); - putBlockPosition(new BlockPosition(blockPosition.x * 8, blockPosition.y * 8, blockPosition.z * 8)); - putLFloat(volume); - putLFloat(pitch); - } - public void decodePayload() { - name = getString(); - blockPosition = getBlockPosition(); - blockPosition.x /= 8; - blockPosition.y /= 8; - blockPosition.z /= 8; - volume = getLFloat(); - pitch = getLFloat(); - } - - //private - + + public String name; + public BlockPosition blockPosition; + public float volume; + public float pitch; + + public PlaySoundPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.PLAY_SOUND_PACKET; + } + + @Override + public void encodePayload() { + putString(name); + putBlockPosition(new BlockPosition(blockPosition.x * 8, blockPosition.y * 8, blockPosition.z * 8)); + putLFloat(volume); + putLFloat(pitch); + } + + @Override + public void decodePayload() { + name = getString(); + blockPosition = getBlockPosition(); + blockPosition.x /= 8; + blockPosition.y /= 8; + blockPosition.z /= 8; + volume = getLFloat(); + pitch = getLFloat(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/PlayStatusPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/PlayStatusPacket.java index 59f89aaaf..6606954a7 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/PlayStatusPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/PlayStatusPacket.java @@ -8,49 +8,52 @@ * Created on 2017/10/21. */ public class PlayStatusPacket extends PEPacket { - //vars - public static final int LOGIN_SUCCESS = 0; - public static final int LOGIN_FAILED_CLIENT = 1; - public static final int LOGIN_FAILED_SERVER = 2; - public static final int PLAYER_SPAWN = 3; - public static final int LOGIN_FAILED_INVALID_TENANT = 4; - public static final int LOGIN_FAILED_VANILLA_EDU = 5; - public static final int LOGIN_FAILED_EDU_VANILLA = 6; - - public int status; - public int protocol = Versioning.MINECRAFT_PE_PROTOCOL; - - //constructor - public PlayStatusPacket() { - - } - public PlayStatusPacket(int status) { - this.status = status; - } - public PlayStatusPacket(int status, int protocol) { - this.status = status; - this.protocol = protocol; - } - - //public - public int pid() { - return ProtocolInfo.PLAY_STATUS_PACKET; - } - - public void encodeHeader() { - if (protocol < 130) { // MCPE <= 1.1 - putByte((byte) (pid() & 0xFF)); - } else { - super.encodeHeader(); - } - } - public void encodePayload() { - putInt(status); - } - public void decodePayload() { - status = getInt(); - } - - //private - + + public static final int LOGIN_SUCCESS = 0; + public static final int LOGIN_FAILED_CLIENT = 1; + public static final int LOGIN_FAILED_SERVER = 2; + public static final int PLAYER_SPAWN = 3; + public static final int LOGIN_FAILED_INVALID_TENANT = 4; + public static final int LOGIN_FAILED_VANILLA_EDU = 5; + public static final int LOGIN_FAILED_EDU_VANILLA = 6; + + public int status; + public int protocol = Versioning.MINECRAFT_PE_PROTOCOL; + + public PlayStatusPacket() { + + } + + public PlayStatusPacket(int status) { + this.status = status; + } + + public PlayStatusPacket(int status, int protocol) { + this.status = status; + this.protocol = protocol; + } + + @Override + public int pid() { + return ProtocolInfo.PLAY_STATUS_PACKET; + } + + @Override + public void encodeHeader() { + if (protocol < 130) { // MCPE <= 1.1 + putByte((byte) (pid() & 0xFF)); + } else { + super.encodeHeader(); + } + } + + @Override + public void encodePayload() { + putInt(status); + } + + @Override + public void decodePayload() { + status = getInt(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/PlayerActionPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/PlayerActionPacket.java index 4564a6408..047c1cfb7 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/PlayerActionPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/PlayerActionPacket.java @@ -8,58 +8,57 @@ * Created on 2017/10/22. */ public class PlayerActionPacket extends PEPacket { - //vars - public static final int ACTION_START_BREAK = 0; - public static final int ACTION_ABORT_BREAK = 1; - public static final int ACTION_STOP_BREAK = 2; - public static final int ACTION_GET_UPDATED_BLOCK = 3; - public static final int ACTION_DROP_ITEM = 4; - public static final int ACTION_START_SLEEPING = 5; - public static final int ACTION_STOP_SLEEPING = 6; - public static final int ACTION_RESPAWN = 7; - public static final int ACTION_JUMP = 8; - public static final int ACTION_START_SPRINT = 9; - public static final int ACTION_STOP_SPRINT = 10; - public static final int ACTION_START_SNEAK = 11; - public static final int ACTION_STOP_SNEAK = 12; - public static final int ACTION_DIMENSION_CHANGE_REQUEST = 13; // sent when dying in different dimension - public static final int ACTION_DIMENSION_CHANGE_ACK = 14; // sent when spawning in a different dimension to tell the - // server we spawned - public static final int ACTION_START_GLIDE = 15; - public static final int ACTION_STOP_GLIDE = 16; - public static final int ACTION_BUILD_DENIED = 17; - public static final int ACTION_CONTINUE_BREAK = 18; - - public static final int ACTION_SET_ENCHANTMENT_SEED = 20; - - public long rtid; - public int action; - public BlockPosition position; - public int face; - - //constructor - public PlayerActionPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.PLAYER_ACTION_PACKET; - } - - public void encodePayload() { - putUnsignedVarLong(rtid); - putVarInt(action); - putBlockPosition(position); - putVarInt(face); - } - public void decodePayload() { - rtid = getUnsignedVarLong(); - action = getVarInt(); - position = getBlockPosition(); - face = getVarInt(); - } - - //private - + + public static final int ACTION_START_BREAK = 0; + public static final int ACTION_ABORT_BREAK = 1; + public static final int ACTION_STOP_BREAK = 2; + public static final int ACTION_GET_UPDATED_BLOCK = 3; + public static final int ACTION_DROP_ITEM = 4; + public static final int ACTION_START_SLEEPING = 5; + public static final int ACTION_STOP_SLEEPING = 6; + public static final int ACTION_RESPAWN = 7; + public static final int ACTION_JUMP = 8; + public static final int ACTION_START_SPRINT = 9; + public static final int ACTION_STOP_SPRINT = 10; + public static final int ACTION_START_SNEAK = 11; + public static final int ACTION_STOP_SNEAK = 12; + public static final int ACTION_DIMENSION_CHANGE_REQUEST = 13; // sent when dying in different dimension + public static final int ACTION_DIMENSION_CHANGE_ACK = 14; // sent when spawning in a different dimension to tell the + // server we spawned + public static final int ACTION_START_GLIDE = 15; + public static final int ACTION_STOP_GLIDE = 16; + public static final int ACTION_BUILD_DENIED = 17; + public static final int ACTION_CONTINUE_BREAK = 18; + + public static final int ACTION_SET_ENCHANTMENT_SEED = 20; + + public long rtid; + public int action; + public BlockPosition position; + public int face; + + public PlayerActionPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.PLAYER_ACTION_PACKET; + } + + @Override + public void encodePayload() { + putUnsignedVarLong(rtid); + putVarInt(action); + putBlockPosition(position); + putVarInt(face); + } + + @Override + public void decodePayload() { + rtid = getUnsignedVarLong(); + action = getVarInt(); + position = getBlockPosition(); + face = getVarInt(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/PlayerHotbarPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/PlayerHotbarPacket.java index 081cc77bc..ec7a997a6 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/PlayerHotbarPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/PlayerHotbarPacket.java @@ -4,7 +4,6 @@ import org.dragonet.proxy.protocol.ProtocolInfo; import org.dragonet.proxy.utilities.Binary; - public class PlayerHotbarPacket extends PEPacket { public int selectedHotbarSlot; @@ -41,7 +40,6 @@ public void encodePayload() { for (int i : slots) { this.putUnsignedVarInt(i); } - this.putBoolean(this.selectHotbarSlot); } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/PlayerListPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/PlayerListPacket.java index 207191179..fc704512f 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/PlayerListPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/PlayerListPacket.java @@ -9,57 +9,56 @@ * Created on 2017/10/22. */ public class PlayerListPacket extends PEPacket { - //vars - public static final byte TYPE_ADD = 0; - public static final byte TYPE_REMOVE = 1; - public byte type; - public PlayerListEntry[] entries; - - //constructor - public PlayerListPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.PLAYER_LIST_PACKET; - } - - public void encodePayload() { - putByte(type); - if (entries != null && entries.length > 0) { - putUnsignedVarInt(entries.length); - for (PlayerListEntry e : entries) { - putUUID(e.uuid); - if (type == TYPE_ADD) { - putUnsignedVarLong(e.eid); - putString(e.username); - e.skin.write(this); - putString(e.xboxUserId); - } - } - } else { - putUnsignedVarInt(0); - } - } - public void decodePayload() { - type = (byte) (getByte() & 0xFF); - int len = (int) getUnsignedVarInt(); - entries = new PlayerListEntry[len]; - if (len > 0) { - for (int i = 0; i < len; i++) { - entries[i] = new PlayerListEntry(); - entries[i].uuid = getUUID(); - if (type == TYPE_ADD) { - entries[i].eid = getVarLong(); - entries[i].username = getString(); - entries[i].skin = Skin.read(this); - entries[i].xboxUserId = getString(); - } - } - } - } - - //private - + + public static final byte TYPE_ADD = 0; + public static final byte TYPE_REMOVE = 1; + public byte type; + public PlayerListEntry[] entries; + + public PlayerListPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.PLAYER_LIST_PACKET; + } + + @Override + public void encodePayload() { + putByte(type); + if (entries != null && entries.length > 0) { + putUnsignedVarInt(entries.length); + for (PlayerListEntry e : entries) { + putUUID(e.uuid); + if (type == TYPE_ADD) { + putUnsignedVarLong(e.eid); + putString(e.username); + e.skin.write(this); + putString(e.xboxUserId); + } + } + } else { + putUnsignedVarInt(0); + } + } + + @Override + public void decodePayload() { + type = (byte) (getByte() & 0xFF); + int len = (int) getUnsignedVarInt(); + entries = new PlayerListEntry[len]; + if (len > 0) { + for (int i = 0; i < len; i++) { + entries[i] = new PlayerListEntry(); + entries[i].uuid = getUUID(); + if (type == TYPE_ADD) { + entries[i].eid = getVarLong(); + entries[i].username = getString(); + entries[i].skin = Skin.read(this); + entries[i].xboxUserId = getString(); + } + } + } + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/PlayerSkinPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/PlayerSkinPacket.java index ddb85d0fd..bf1f32a6d 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/PlayerSkinPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/PlayerSkinPacket.java @@ -16,7 +16,6 @@ public class PlayerSkinPacket extends PEPacket { public String newSkinName = ""; public Skin skin; - // constructor public PlayerSkinPacket() { } @@ -24,7 +23,6 @@ public PlayerSkinPacket(UUID uuid) { this.uuid = uuid; } - // public @Override public int pid() { return ProtocolInfo.PLAYER_SKIN_PACKET; @@ -33,7 +31,9 @@ public int pid() { @Override public void encodePayload() { putUUID(uuid); - if (skin == null) skin = Skin.DEFAULT_SKIN; + if (skin == null) { + skin = Skin.DEFAULT_SKIN; + } putString(skin.skinId); putString(oldSkinName); putString(newSkinName); @@ -48,6 +48,4 @@ public void encodePayload() { public void decodePayload() { } - - // private } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/RemoveEntityPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/RemoveEntityPacket.java index a03bdfcf7..05b967205 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/RemoveEntityPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/RemoveEntityPacket.java @@ -7,26 +7,25 @@ * Created on 2017/10/21. */ public class RemoveEntityPacket extends PEPacket { - //vars - public long eid; - - //constructor - public RemoveEntityPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.REMOVE_ENTITY_PACKET; - } - - public void encodePayload() { - putVarLong(eid); - } - public void decodePayload() { - eid = getVarLong(); - } - - //private - + + public long eid; + + public RemoveEntityPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.REMOVE_ENTITY_PACKET; + } + + @Override + public void encodePayload() { + putVarLong(eid); + } + + @Override + public void decodePayload() { + eid = getVarLong(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/RequestChunkRadiusPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/RequestChunkRadiusPacket.java index 3312de034..72f04dfb9 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/RequestChunkRadiusPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/RequestChunkRadiusPacket.java @@ -7,26 +7,25 @@ * Created on 2017/10/22. */ public class RequestChunkRadiusPacket extends PEPacket { - //vars - public int radius; - - //constructor - public RequestChunkRadiusPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.REQUEST_CHUNK_RADIUS_PACKET; - } - - public void encodePayload() { - putVarInt(radius); - } - public void decodePayload() { - radius = getVarInt(); - } - - //private - + + public int radius; + + public RequestChunkRadiusPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.REQUEST_CHUNK_RADIUS_PACKET; + } + + @Override + public void encodePayload() { + putVarInt(radius); + } + + @Override + public void decodePayload() { + radius = getVarInt(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/ResourcePackClientResponsePacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/ResourcePackClientResponsePacket.java index 15ba9ba48..0d0f3c19f 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/ResourcePackClientResponsePacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/ResourcePackClientResponsePacket.java @@ -7,47 +7,46 @@ * Created on 2017/10/22. */ public class ResourcePackClientResponsePacket extends PEPacket { - //vars - public static final byte STATUS_REFUSED = 1; - public static final byte STATUS_SEND_PACKS = 2; - public static final byte STATUS_HAVE_ALL_PACKS = 3; - public static final byte STATUS_COMPLETED = 4; - - public byte status; - public byte[][] packs; - - //constructor - public ResourcePackClientResponsePacket() { - - } - - //public - public int pid() { - return ProtocolInfo.RESOURCE_PACK_CLIENT_RESPONSE_PACKET; - } - - public void encodePayload() { - putByte(status); - if (packs != null && packs.length > 0) { - putLShort(packs.length); - for (byte[] p : packs) { - putByteArray(p); - } - } else { - putLShort(0); - } - } - public void decodePayload() { - status = (byte) (getByte() & 0xFF); - int len = getLShort(); - packs = new byte[len][]; - if (len > 0) { - for (int i = 0; i < len; i++) { - packs[i] = getByteArray(); - } - } - } - - //private - + + public static final byte STATUS_REFUSED = 1; + public static final byte STATUS_SEND_PACKS = 2; + public static final byte STATUS_HAVE_ALL_PACKS = 3; + public static final byte STATUS_COMPLETED = 4; + + public byte status; + public byte[][] packs; + + public ResourcePackClientResponsePacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.RESOURCE_PACK_CLIENT_RESPONSE_PACKET; + } + + @Override + public void encodePayload() { + putByte(status); + if (packs != null && packs.length > 0) { + putLShort(packs.length); + for (byte[] p : packs) { + putByteArray(p); + } + } else { + putLShort(0); + } + } + + @Override + public void decodePayload() { + status = (byte) (getByte() & 0xFF); + int len = getLShort(); + packs = new byte[len][]; + if (len > 0) { + for (int i = 0; i < len; i++) { + packs[i] = getByteArray(); + } + } + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/ResourcePackStackPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/ResourcePackStackPacket.java index 231720951..f11505719 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/ResourcePackStackPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/ResourcePackStackPacket.java @@ -7,24 +7,21 @@ * Created on 2017/10/23. */ public class ResourcePackStackPacket extends PEPacket { - //vars - - //constructor - - //public - public int pid() { - return ProtocolInfo.RESOURCE_PACK_STACK_PACKET; - } - - public void encodePayload() { - putBoolean(false); - putUnsignedVarInt(0); - putUnsignedVarInt(0); - } - public void decodePayload() { - } - - //private - + @Override + public int pid() { + return ProtocolInfo.RESOURCE_PACK_STACK_PACKET; + } + + @Override + public void encodePayload() { + putBoolean(false); + putUnsignedVarInt(0); + putUnsignedVarInt(0); + } + + @Override + public void decodePayload() { + + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/ResourcePacksInfoPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/ResourcePacksInfoPacket.java index aaaf4ebbb..6081991eb 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/ResourcePacksInfoPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/ResourcePacksInfoPacket.java @@ -7,28 +7,26 @@ * Created on 2017/10/21. */ public class ResourcePacksInfoPacket extends PEPacket { - //vars - - //constructor - public ResourcePacksInfoPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.RESOURCE_PACKS_INFO_PACKET; - } - - public void encodePayload() { - // TODO: real encode - putBoolean(false); - putLShort(0); - putLShort(0); - } - public void decodePayload() { - // TODO: real decode - } - - //private - + + public ResourcePacksInfoPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.RESOURCE_PACKS_INFO_PACKET; + } + + @Override + public void encodePayload() { + // TODO: real encode + putBoolean(false); + putLShort(0); + putLShort(0); + } + + @Override + public void decodePayload() { + // TODO: real decode + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/RespawnPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/RespawnPacket.java index afa216a9c..4cd853815 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/RespawnPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/RespawnPacket.java @@ -8,26 +8,25 @@ * Created on 2017/10/22. */ public class RespawnPacket extends PEPacket { - //vars - public Vector3F position; - - //constructor - public RespawnPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.RESPAWN_PACKET; - } - - public void encodePayload() { - putVector3F(position); - } - public void decodePayload() { - position = getVector3F(); - } - - //private - + + public Vector3F position; + + public RespawnPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.RESPAWN_PACKET; + } + + @Override + public void encodePayload() { + putVector3F(position); + } + + @Override + public void decodePayload() { + position = getVector3F(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/SetEntityDataPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/SetEntityDataPacket.java index 91248c09c..15a2d5dda 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/SetEntityDataPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/SetEntityDataPacket.java @@ -8,32 +8,31 @@ * Created on 2017/10/23. */ public class SetEntityDataPacket extends PEPacket { - //vars - public long rtid; - public EntityMetaData meta; - - //constructor - public SetEntityDataPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.SET_ENTITY_DATA_PACKET; - } - - public void encodePayload() { - putUnsignedVarLong(rtid); - if (meta == null) { - meta = EntityMetaData.createDefault(); - } - meta.encode(); - put(meta.getBuffer()); - } - public void decodePayload() { - - } - - //private - + + public long rtid; + public EntityMetaData meta; + + public SetEntityDataPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.SET_ENTITY_DATA_PACKET; + } + + @Override + public void encodePayload() { + putUnsignedVarLong(rtid); + if (meta == null) { + meta = EntityMetaData.createDefault(); + } + meta.encode(); + put(meta.getBuffer()); + } + + @Override + public void decodePayload() { + + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/SetEntityMotionPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/SetEntityMotionPacket.java index f738c7d72..e3a6e5c8b 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/SetEntityMotionPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/SetEntityMotionPacket.java @@ -8,29 +8,28 @@ * Created on 2017/10/21. */ public class SetEntityMotionPacket extends PEPacket { - //vars - public long rtid; - public Vector3F motion; - - //constructor - public SetEntityMotionPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.SET_ENTITY_MOTION_PACKET; - } - - public void encodePayload() { - putUnsignedVarLong(rtid); - putVector3F(motion); - } - public void decodePayload() { - rtid = getUnsignedVarLong(); - motion = getVector3F(); - } - - //private - + + public long rtid; + public Vector3F motion; + + public SetEntityMotionPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.SET_ENTITY_MOTION_PACKET; + } + + @Override + public void encodePayload() { + putUnsignedVarLong(rtid); + putVector3F(motion); + } + + @Override + public void decodePayload() { + rtid = getUnsignedVarLong(); + motion = getVector3F(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/SetHealthPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/SetHealthPacket.java index 2e9ec0ec4..379f3bdd4 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/SetHealthPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/SetHealthPacket.java @@ -7,29 +7,29 @@ * Created on 2017/10/22. */ public class SetHealthPacket extends PEPacket { - //vars - public int health; - - //constructor - public SetHealthPacket() { - - } - public SetHealthPacket(int health) { - this.health = health; - } - - //public - public int pid() { - return ProtocolInfo.SET_HEALTH_PACKET; - } - - public void encodePayload() { - putVarInt(health); - } - public void decodePayload() { - health = getVarInt(); - } - - //private - + + public int health; + + public SetHealthPacket() { + + } + + public SetHealthPacket(int health) { + this.health = health; + } + + @Override + public int pid() { + return ProtocolInfo.SET_HEALTH_PACKET; + } + + @Override + public void encodePayload() { + putVarInt(health); + } + + @Override + public void decodePayload() { + health = getVarInt(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/SetPlayerGameTypePacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/SetPlayerGameTypePacket.java index 99902c03f..bf6713cd4 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/SetPlayerGameTypePacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/SetPlayerGameTypePacket.java @@ -7,26 +7,26 @@ * Created on 2017/10/21. */ public class SetPlayerGameTypePacket extends PEPacket { - //vars - public int gamemode; - - //constructor - public SetPlayerGameTypePacket() { - - } - - //public - public int pid() { - return ProtocolInfo.SET_PLAYER_GAME_TYPE_PACKET; - } - - public void encodePayload() { - putVarInt(gamemode); - } - public void decodePayload() { - gamemode = getVarInt(); - } - - //private - + + public int gamemode; + + public SetPlayerGameTypePacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.SET_PLAYER_GAME_TYPE_PACKET; + } + + @Override + public void encodePayload() { + putVarInt(gamemode); + } + + @Override + public void decodePayload() { + gamemode = getVarInt(); + } + } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/SetSpawnPositionPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/SetSpawnPositionPacket.java index 834965165..7924f4a73 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/SetSpawnPositionPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/SetSpawnPositionPacket.java @@ -8,35 +8,34 @@ * Created on 2017/10/21. */ public class SetSpawnPositionPacket extends PEPacket { - //vars - public static final int TYPE_PLAYER_SPAWN = 0; - public static final int TYPE_WORLD_SPAWN = 1; - - public int type; - public BlockPosition position; - public boolean forced; - - //constructor - public SetSpawnPositionPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.SET_SPAWN_POSITION_PACKET; - } - - public void encodePayload() { - putVarInt(type); - putBlockPosition(position); - putBoolean(forced); - } - public void decodePayload() { - type = getVarInt(); - position = getBlockPosition(); - forced = getBoolean(); - } - - //private - + + public static final int TYPE_PLAYER_SPAWN = 0; + public static final int TYPE_WORLD_SPAWN = 1; + + public int type; + public BlockPosition position; + public boolean forced; + + public SetSpawnPositionPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.SET_SPAWN_POSITION_PACKET; + } + + @Override + public void encodePayload() { + putVarInt(type); + putBlockPosition(position); + putBoolean(forced); + } + + @Override + public void decodePayload() { + type = getVarInt(); + position = getBlockPosition(); + forced = getBoolean(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/SetTimePacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/SetTimePacket.java index f6f38f4c6..984555d6e 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/SetTimePacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/SetTimePacket.java @@ -7,26 +7,25 @@ * Created on 2017/10/22. */ public class SetTimePacket extends PEPacket { - //vars - public int time; - - //constructor - public SetTimePacket() { - - } - - //public - public int pid() { - return ProtocolInfo.SET_TIME_PACKET; - } - - public void encodePayload() { - putVarInt(time); - } - public void decodePayload() { - time = getVarInt(); - } - - //private - + + public int time; + + public SetTimePacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.SET_TIME_PACKET; + } + + @Override + public void encodePayload() { + putVarInt(time); + } + + @Override + public void decodePayload() { + time = getVarInt(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/StartGamePacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/StartGamePacket.java index 77cebf5fe..0f235e71f 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/StartGamePacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/StartGamePacket.java @@ -12,141 +12,140 @@ * Created on 2017/10/21. */ public class StartGamePacket extends PEPacket { - //vars - public long eid; - public long rtid; - public int gamemode; - public Vector3F position; - public float pitch; - public float yaw; - - // world settings - public int seed; - public int dimension; - public int generator; - public int worldGamemode; - public int difficulty; - public BlockPosition spawnPosition; - public boolean achievementsDisabled; - public int time; - public boolean eduMode; - public float rainLevel; - public float lightningLevel; - public boolean multiplayerGame = true; - public boolean lanBroadcast = true; - public boolean xboxLiveBroadcast; - public boolean commandsEnabled; - public boolean texturePacksRequired; - public Map gameRules; - public boolean bonusChestEnabled; - public boolean startWithMapEnabled; - public boolean trustPlayersEnabled; - public int defaultPlayerPermission; - public int xboxLiveBroadcastMode; - - public String levelId; - public String worldName; - public String premiumWorldTemplateId; - public boolean unknownBool; - public long currentTick; - - public int enchantmentSeed; - - //constructor - public StartGamePacket() { - - } - - //public - public int pid() { - return ProtocolInfo.START_GAME_PACKET; - } - - public void encodePayload() { - putVarLong(eid); - putUnsignedVarLong(rtid); - putVarInt(gamemode); - - putVector3F(position); - - putLFloat(pitch); - putLFloat(yaw); - - // Level settings - putVarInt(seed); - putVarInt(dimension); - putVarInt(generator); - putVarInt(worldGamemode); - putVarInt(difficulty); - putBlockPosition(spawnPosition); - putBoolean(achievementsDisabled); - putVarInt(time); - putBoolean(eduMode); - putLFloat(rainLevel); - putLFloat(lightningLevel); - putBoolean(multiplayerGame); - putBoolean(lanBroadcast); - putBoolean(xboxLiveBroadcast); - putBoolean(commandsEnabled); - putBoolean(texturePacksRequired); - putGameRules(gameRules); - putBoolean(bonusChestEnabled); - putBoolean(startWithMapEnabled); - putBoolean(trustPlayersEnabled); - putVarInt(defaultPlayerPermission); - putVarInt(xboxLiveBroadcastMode); - - putString(levelId); - putString(worldName); - putString(premiumWorldTemplateId); - putBoolean(unknownBool); - putLLong(currentTick); - - putVarInt(enchantmentSeed); - } - public void decodePayload() { - eid = getVarLong(); - rtid = getUnsignedVarLong(); - gamemode = getVarInt(); - - position = getVector3F(); - - pitch = getLFloat(); - yaw = getLFloat(); - - // Level settings - seed = getVarInt(); - dimension = getVarInt(); - generator = getVarInt(); - worldGamemode = getVarInt(); - difficulty = getVarInt(); - spawnPosition = getBlockPosition(); - achievementsDisabled = getBoolean(); - time = getVarInt(); - eduMode = getBoolean(); - rainLevel = getLFloat(); - lightningLevel = getLFloat(); - multiplayerGame = getBoolean(); - lanBroadcast = getBoolean(); - xboxLiveBroadcast = getBoolean(); - commandsEnabled = getBoolean(); - texturePacksRequired = getBoolean(); - gameRules = getGameRules(); - bonusChestEnabled = getBoolean(); - startWithMapEnabled = getBoolean(); - trustPlayersEnabled = getBoolean(); - defaultPlayerPermission = getVarInt(); - xboxLiveBroadcastMode = getVarInt(); - - levelId = getString(); - worldName = getString(); - premiumWorldTemplateId = getString(); - unknownBool = getBoolean(); - currentTick = getLLong(); - - enchantmentSeed = getVarInt(); - } - - //private - + + public long eid; + public long rtid; + public int gamemode; + public Vector3F position; + public float pitch; + public float yaw; + + // world settings + public int seed; + public int dimension; + public int generator; + public int worldGamemode; + public int difficulty; + public BlockPosition spawnPosition; + public boolean achievementsDisabled; + public int time; + public boolean eduMode; + public float rainLevel; + public float lightningLevel; + public boolean multiplayerGame = true; + public boolean lanBroadcast = true; + public boolean xboxLiveBroadcast; + public boolean commandsEnabled; + public boolean texturePacksRequired; + public Map gameRules; + public boolean bonusChestEnabled; + public boolean startWithMapEnabled; + public boolean trustPlayersEnabled; + public int defaultPlayerPermission; + public int xboxLiveBroadcastMode; + + public String levelId; + public String worldName; + public String premiumWorldTemplateId; + public boolean unknownBool; + public long currentTick; + + public int enchantmentSeed; + + public StartGamePacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.START_GAME_PACKET; + } + + @Override + public void encodePayload() { + putVarLong(eid); + putUnsignedVarLong(rtid); + putVarInt(gamemode); + + putVector3F(position); + + putLFloat(pitch); + putLFloat(yaw); + + // Level settings + putVarInt(seed); + putVarInt(dimension); + putVarInt(generator); + putVarInt(worldGamemode); + putVarInt(difficulty); + putBlockPosition(spawnPosition); + putBoolean(achievementsDisabled); + putVarInt(time); + putBoolean(eduMode); + putLFloat(rainLevel); + putLFloat(lightningLevel); + putBoolean(multiplayerGame); + putBoolean(lanBroadcast); + putBoolean(xboxLiveBroadcast); + putBoolean(commandsEnabled); + putBoolean(texturePacksRequired); + putGameRules(gameRules); + putBoolean(bonusChestEnabled); + putBoolean(startWithMapEnabled); + putBoolean(trustPlayersEnabled); + putVarInt(defaultPlayerPermission); + putVarInt(xboxLiveBroadcastMode); + + putString(levelId); + putString(worldName); + putString(premiumWorldTemplateId); + putBoolean(unknownBool); + putLLong(currentTick); + + putVarInt(enchantmentSeed); + } + + @Override + public void decodePayload() { + eid = getVarLong(); + rtid = getUnsignedVarLong(); + gamemode = getVarInt(); + + position = getVector3F(); + + pitch = getLFloat(); + yaw = getLFloat(); + + // Level settings + seed = getVarInt(); + dimension = getVarInt(); + generator = getVarInt(); + worldGamemode = getVarInt(); + difficulty = getVarInt(); + spawnPosition = getBlockPosition(); + achievementsDisabled = getBoolean(); + time = getVarInt(); + eduMode = getBoolean(); + rainLevel = getLFloat(); + lightningLevel = getLFloat(); + multiplayerGame = getBoolean(); + lanBroadcast = getBoolean(); + xboxLiveBroadcast = getBoolean(); + commandsEnabled = getBoolean(); + texturePacksRequired = getBoolean(); + gameRules = getGameRules(); + bonusChestEnabled = getBoolean(); + startWithMapEnabled = getBoolean(); + trustPlayersEnabled = getBoolean(); + defaultPlayerPermission = getVarInt(); + xboxLiveBroadcastMode = getVarInt(); + + levelId = getString(); + worldName = getString(); + premiumWorldTemplateId = getString(); + unknownBool = getBoolean(); + currentTick = getLLong(); + + enchantmentSeed = getVarInt(); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/TextPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/TextPacket.java index f75b66bd4..874a5e3ab 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/TextPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/TextPacket.java @@ -7,99 +7,100 @@ * Created on 2017/10/21. */ public class TextPacket extends PEPacket { - //vars - public static final int TYPE_RAW = 0; - public static final int TYPE_CHAT = 1; - public static final int TYPE_TRANSLATION = 2; - public static final int TYPE_POPUP = 3; - public static final int TYPE_JUKEBOX_POPUP = 4; - public static final int TYPE_TIP = 5; - public static final int TYPE_SYSTEM = 6; - public static final int TYPE_WHISPER = 7; - public static final int TYPE_ANNOUNCEMENT = 8; - - public int type; - public boolean needsTranslation; - public String source; - public String message; - public String[] params; - public String xboxUserId; - - //constructor - public TextPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.TEXT_PACKET; - } - - public void decodePayload() { - type = getByte(); - needsTranslation = getBoolean(); - switch (type) { - case TYPE_CHAT: - case TYPE_WHISPER: - case TYPE_ANNOUNCEMENT: - source = getString(); - case TYPE_RAW: - case TYPE_TIP: - case TYPE_SYSTEM: - message = getString(); - break; - case TYPE_TRANSLATION: - case TYPE_POPUP: - case TYPE_JUKEBOX_POPUP: - message = getString(); - int count = (int) getUnsignedVarInt(); - params = new String[count]; - for (int i = 0; i < count; i++) { - params[i] = getString(); - } - break; - } + public static final int TYPE_RAW = 0; + public static final int TYPE_CHAT = 1; + public static final int TYPE_TRANSLATION = 2; + public static final int TYPE_POPUP = 3; + public static final int TYPE_JUKEBOX_POPUP = 4; + public static final int TYPE_TIP = 5; + public static final int TYPE_SYSTEM = 6; + public static final int TYPE_WHISPER = 7; + public static final int TYPE_ANNOUNCEMENT = 8; - xboxUserId = getString(); - } - public void encodePayload() { - putByte((byte) (type & 0xFF)); - putBoolean(needsTranslation); - switch (type) { - case TYPE_CHAT: - case TYPE_WHISPER: - /** @noinspection PhpMissingBreakStatementInspection */ - case TYPE_ANNOUNCEMENT: - putString(source); - case TYPE_RAW: - case TYPE_TIP: - case TYPE_SYSTEM: - putString(message); - break; + public int type; + public boolean needsTranslation; + public String source; + public String message; + public String[] params; + public String xboxUserId; - case TYPE_TRANSLATION: - case TYPE_POPUP: - case TYPE_JUKEBOX_POPUP: - putString(message); - if (params != null && params.length > 0) { - putUnsignedVarInt(params.length); - for (String s : params) { - putString(s); - } - } else { - putUnsignedVarInt(0); - } - break; - } + public TextPacket() { - if (xboxUserId != null) { - putString(xboxUserId); - } else { - putString(""); - } - } - - //private - + } + + @Override + public int pid() { + return ProtocolInfo.TEXT_PACKET; + } + + @Override + public void decodePayload() { + type = getByte(); + needsTranslation = getBoolean(); + switch (type) { + case TYPE_CHAT: + case TYPE_WHISPER: + case TYPE_ANNOUNCEMENT: + source = getString(); + case TYPE_RAW: + case TYPE_TIP: + case TYPE_SYSTEM: + message = getString(); + break; + + case TYPE_TRANSLATION: + case TYPE_POPUP: + case TYPE_JUKEBOX_POPUP: + message = getString(); + int count = (int) getUnsignedVarInt(); + params = new String[count]; + for (int i = 0; i < count; i++) { + params[i] = getString(); + } + break; + } + + xboxUserId = getString(); + } + + @Override + public void encodePayload() { + putByte((byte) (type & 0xFF)); + putBoolean(needsTranslation); + switch (type) { + case TYPE_CHAT: + case TYPE_WHISPER: + /** + * @noinspection PhpMissingBreakStatementInspection + */ + case TYPE_ANNOUNCEMENT: + putString(source); + case TYPE_RAW: + case TYPE_TIP: + case TYPE_SYSTEM: + putString(message); + break; + + case TYPE_TRANSLATION: + case TYPE_POPUP: + case TYPE_JUKEBOX_POPUP: + putString(message); + if (params != null && params.length > 0) { + putUnsignedVarInt(params.length); + for (String s : params) { + putString(s); + } + } else { + putUnsignedVarInt(0); + } + break; + } + + if (xboxUserId != null) { + putString(xboxUserId); + } else { + putString(""); + } + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/UpdateAttributesPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/UpdateAttributesPacket.java index 0808cca7b..05f498566 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/UpdateAttributesPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/UpdateAttributesPacket.java @@ -1,5 +1,8 @@ package org.dragonet.proxy.protocol.packets; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; import org.dragonet.proxy.data.entity.PEEntityAttribute; import org.dragonet.proxy.protocol.PEPacket; import org.dragonet.proxy.protocol.ProtocolInfo; @@ -8,39 +11,38 @@ * Created on 2017/10/23. */ public class UpdateAttributesPacket extends PEPacket { - //vars - public long rtid; - public PEEntityAttribute[] entries; - - //constructor - public UpdateAttributesPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.UPDATE_ATTRIBUTES_PACKET; - } - - public void encodePayload() { - putUnsignedVarLong(rtid); - if (entries != null && entries.length > 0) { - putUnsignedVarInt(entries.length); - for (PEEntityAttribute attr : entries) { - putLFloat(attr.min); - putLFloat(attr.max); - putLFloat(attr.currentValue); - putLFloat(attr.defaultValue); - putString(attr.name); - } - } else { - putUnsignedVarInt(0); - } - } - public void decodePayload() { - - } - - //private - + + public long rtid; + public Collection entries; + + public UpdateAttributesPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.UPDATE_ATTRIBUTES_PACKET; + } + + @Override + public void encodePayload() { + putUnsignedVarLong(rtid); + if (entries != null && entries.size() > 0) { + putUnsignedVarInt(entries.size()); + for (PEEntityAttribute attr : entries) { + putLFloat(attr.min); + putLFloat(attr.max); + putLFloat(attr.currentValue); + putLFloat(attr.defaultValue); + putString(attr.name); + } + } else { + putUnsignedVarInt(0); + } + } + + @Override + public void decodePayload() { + + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/packets/UpdateBlockPacket.java b/src/main/java/org/dragonet/proxy/protocol/packets/UpdateBlockPacket.java index d13a34dd3..8f12d40c2 100644 --- a/src/main/java/org/dragonet/proxy/protocol/packets/UpdateBlockPacket.java +++ b/src/main/java/org/dragonet/proxy/protocol/packets/UpdateBlockPacket.java @@ -8,46 +8,44 @@ * Created on 2017/10/21. */ public class UpdateBlockPacket extends PEPacket { - //vars - public static final int FLAG_NONE = 0b0000; - public static final int FLAG_NEIGHBORS = 0b0001; - public static final int FLAG_NETWORK = 0b0010; - public static final int FLAG_NOGRAPHIC = 0b0100; - public static final int FLAG_PRIORITY = 0b1000; - - public static final int FLAG_ALL = FLAG_NEIGHBORS | FLAG_NETWORK; - public static final int FLAG_ALL_PRIORITY = FLAG_ALL | FLAG_PRIORITY; - - public BlockPosition blockPosition; - public int id; - public int data; - public int flags; - - //constructor - public UpdateBlockPacket() { - - } - - //public - public int pid() { - return ProtocolInfo.UPDATE_BLOCK_PACKET; - } - - public void decodePayload() { - blockPosition = getBlockPosition(); - id = (int) getUnsignedVarInt(); - long aux = getUnsignedVarInt(); - data = (int) (aux & 0xf); - flags = (int) (aux >> 4); - } - public void encodePayload() { - putBlockPosition(blockPosition); - ; - putUnsignedVarInt(id); - int aux = ((flags & 0xf) << 4) | (data & 0xf); - putUnsignedVarInt(aux); - } - - //private - + + public static final int FLAG_NONE = 0b0000; + public static final int FLAG_NEIGHBORS = 0b0001; + public static final int FLAG_NETWORK = 0b0010; + public static final int FLAG_NOGRAPHIC = 0b0100; + public static final int FLAG_PRIORITY = 0b1000; + + public static final int FLAG_ALL = FLAG_NEIGHBORS | FLAG_NETWORK; + public static final int FLAG_ALL_PRIORITY = FLAG_ALL | FLAG_PRIORITY; + + public BlockPosition blockPosition; + public int id; + public int data; + public int flags; + + public UpdateBlockPacket() { + + } + + @Override + public int pid() { + return ProtocolInfo.UPDATE_BLOCK_PACKET; + } + + @Override + public void decodePayload() { + blockPosition = getBlockPosition(); + id = (int) getUnsignedVarInt(); + long aux = getUnsignedVarInt(); + data = (int) (aux & 0xf); + flags = (int) (aux >> 4); + } + + @Override + public void encodePayload() { + putBlockPosition(blockPosition); + putUnsignedVarInt(id); + int aux = ((flags) << 4) | (data & 0xf); + putUnsignedVarInt(aux); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/type/InventoryTransactionAction.java b/src/main/java/org/dragonet/proxy/protocol/type/InventoryTransactionAction.java index 506ffd5d1..7580fe441 100644 --- a/src/main/java/org/dragonet/proxy/protocol/type/InventoryTransactionAction.java +++ b/src/main/java/org/dragonet/proxy/protocol/type/InventoryTransactionAction.java @@ -7,118 +7,116 @@ * Created on 2017/10/21. */ public class InventoryTransactionAction { - // vars - public static final int SOURCE_CONTAINER = 0; - public static final int SOURCE_WORLD = 2; // drop/pickup item entity - public static final int SOURCE_CREATIVE = 3; - public static final int SOURCE_TODO = 99999; - - /** - * Fake window IDs for the SOURCE_TODO type (99999) - * - * These identifiers are used for inventory source types which are not currently - * implemented server-side in MCPE. As a general rule of thumb, anything that - * doesn't have a permanent inventory is client-side. These types are to allow - * servers to track what is going on in client-side windows. - * - * Expect these to change in the future. - */ - public static final int SOURCE_TYPE_CRAFTING_ADD_INGREDIENT = -2; - public static final int SOURCE_TYPE_CRAFTING_REMOVE_INGREDIENT = -3; - public static final int SOURCE_TYPE_CRAFTING_RESULT = -4; - public static final int SOURCE_TYPE_CRAFTING_USE_INGREDIENT = -5; - - public static final int SOURCE_TYPE_ANVIL_INPUT = -10; - public static final int SOURCE_TYPE_ANVIL_MATERIAL = -11; - public static final int SOURCE_TYPE_ANVIL_RESULT = -12; - public static final int SOURCE_TYPE_ANVIL_OUTPUT = -13; - - public static final int SOURCE_TYPE_ENCHANT_INPUT = -15; - public static final int SOURCE_TYPE_ENCHANT_MATERIAL = -16; - public static final int SOURCE_TYPE_ENCHANT_OUTPUT = -17; - - public static final int SOURCE_TYPE_TRADING_INPUT_1 = -20; - public static final int SOURCE_TYPE_TRADING_INPUT_2 = -21; - public static final int SOURCE_TYPE_TRADING_USE_INPUTS = -22; - public static final int SOURCE_TYPE_TRADING_OUTPUT = -23; - - public static final int SOURCE_TYPE_BEACON = -24; - - /** Any client-side window dropping its contents when the player closes it */ - public static final int SOURCE_TYPE_CONTAINER_DROP_CONTENTS = -100; - - public static final int ACTION_MAGIC_SLOT_CREATIVE_DELETE_ITEM = 0; - public static final int ACTION_MAGIC_SLOT_CREATIVE_CREATE_ITEM = 1; - - public static final int ACTION_MAGIC_SLOT_DROP_ITEM = 0; - public static final int ACTION_MAGIC_SLOT_PICKUP_ITEM = 1; - - public int sourceType; - public int containerId; - public int unknown; - public boolean craftingPart; - public int slotId; - public Slot oldItem; - public Slot newItem; - - // constructor - public InventoryTransactionAction() { - - } - - // public - public static InventoryTransactionAction read(InventoryTransactionPacket packet) { - InventoryTransactionAction action = new InventoryTransactionAction(); - action.sourceType = (int) packet.getUnsignedVarInt(); - - switch (action.sourceType) { - case SOURCE_CONTAINER: - action.containerId = packet.getVarInt(); - break; - case SOURCE_WORLD: - action.unknown = (int) packet.getUnsignedVarInt(); - break; - case SOURCE_CREATIVE: - break; - case SOURCE_TODO: - action.containerId = packet.getVarInt(); - switch (action.containerId) { - case SOURCE_TYPE_CRAFTING_USE_INGREDIENT: - case SOURCE_TYPE_CRAFTING_RESULT: -// packet.craftingPart = true; - break; - } - break; - } - - action.slotId = (int) packet.getUnsignedVarInt(); - action.oldItem = packet.getSlot(); - action.newItem = packet.getSlot(); - return action; - } - - public void write(BinaryStream packet) { - packet.putUnsignedVarInt(sourceType); - - switch (sourceType) { - case SOURCE_CONTAINER: - packet.putVarInt(containerId); - break; - case SOURCE_WORLD: - packet.putUnsignedVarInt(unknown); - break; - case SOURCE_CREATIVE: - break; - case SOURCE_TODO: - packet.putVarInt(containerId); - break; - } - - packet.putUnsignedVarInt(slotId); - packet.putSlot(oldItem); - packet.putSlot(newItem); - } - - // private + public static final int SOURCE_CONTAINER = 0; + public static final int SOURCE_WORLD = 2; // drop/pickup item entity + public static final int SOURCE_CREATIVE = 3; + public static final int SOURCE_TODO = 99999; + + /** + * Fake window IDs for the SOURCE_TODO type (99999) + * + * These identifiers are used for inventory source types which are not + * currently implemented server-side in MCPE. As a general rule of thumb, + * anything that doesn't have a permanent inventory is client-side. These + * types are to allow servers to track what is going on in client-side + * windows. + * + * Expect these to change in the future. + */ + public static final int SOURCE_TYPE_CRAFTING_ADD_INGREDIENT = -2; + public static final int SOURCE_TYPE_CRAFTING_REMOVE_INGREDIENT = -3; + public static final int SOURCE_TYPE_CRAFTING_RESULT = -4; + public static final int SOURCE_TYPE_CRAFTING_USE_INGREDIENT = -5; + + public static final int SOURCE_TYPE_ANVIL_INPUT = -10; + public static final int SOURCE_TYPE_ANVIL_MATERIAL = -11; + public static final int SOURCE_TYPE_ANVIL_RESULT = -12; + public static final int SOURCE_TYPE_ANVIL_OUTPUT = -13; + + public static final int SOURCE_TYPE_ENCHANT_INPUT = -15; + public static final int SOURCE_TYPE_ENCHANT_MATERIAL = -16; + public static final int SOURCE_TYPE_ENCHANT_OUTPUT = -17; + + public static final int SOURCE_TYPE_TRADING_INPUT_1 = -20; + public static final int SOURCE_TYPE_TRADING_INPUT_2 = -21; + public static final int SOURCE_TYPE_TRADING_USE_INPUTS = -22; + public static final int SOURCE_TYPE_TRADING_OUTPUT = -23; + + public static final int SOURCE_TYPE_BEACON = -24; + + /** + * Any client-side window dropping its contents when the player closes it + */ + public static final int SOURCE_TYPE_CONTAINER_DROP_CONTENTS = -100; + + public static final int ACTION_MAGIC_SLOT_CREATIVE_DELETE_ITEM = 0; + public static final int ACTION_MAGIC_SLOT_CREATIVE_CREATE_ITEM = 1; + + public static final int ACTION_MAGIC_SLOT_DROP_ITEM = 0; + public static final int ACTION_MAGIC_SLOT_PICKUP_ITEM = 1; + + public int sourceType; + public int containerId; + public int unknown; + public boolean craftingPart; + public int slotId; + public Slot oldItem; + public Slot newItem; + + public InventoryTransactionAction() { + + } + + public static InventoryTransactionAction read(InventoryTransactionPacket packet) { + InventoryTransactionAction action = new InventoryTransactionAction(); + action.sourceType = (int) packet.getUnsignedVarInt(); + + switch (action.sourceType) { + case SOURCE_CONTAINER: + action.containerId = packet.getVarInt(); + break; + case SOURCE_WORLD: + action.unknown = (int) packet.getUnsignedVarInt(); + break; + case SOURCE_CREATIVE: + break; + case SOURCE_TODO: + action.containerId = packet.getVarInt(); + switch (action.containerId) { + case SOURCE_TYPE_CRAFTING_USE_INGREDIENT: + case SOURCE_TYPE_CRAFTING_RESULT: +// packet.craftingPart = true; + break; + } + break; + } + + action.slotId = (int) packet.getUnsignedVarInt(); + action.oldItem = packet.getSlot(); + action.newItem = packet.getSlot(); + return action; + } + + public void write(BinaryStream packet) { + packet.putUnsignedVarInt(sourceType); + + switch (sourceType) { + case SOURCE_CONTAINER: + packet.putVarInt(containerId); + break; + case SOURCE_WORLD: + packet.putUnsignedVarInt(unknown); + break; + case SOURCE_CREATIVE: + break; + case SOURCE_TODO: + packet.putVarInt(containerId); + break; + } + + packet.putUnsignedVarInt(slotId); + packet.putSlot(oldItem); + packet.putSlot(newItem); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/type/PEEntityLink.java b/src/main/java/org/dragonet/proxy/protocol/type/PEEntityLink.java index 48cff6232..9a9df0417 100644 --- a/src/main/java/org/dragonet/proxy/protocol/type/PEEntityLink.java +++ b/src/main/java/org/dragonet/proxy/protocol/type/PEEntityLink.java @@ -4,25 +4,16 @@ * Created on 2017/10/21. */ public class PEEntityLink { - // vars - public long eidFrom; - public long eidTo; - public int type; - public boolean bool; - // constructor - public PEEntityLink() { - - } - - // public - public PEEntityLink(long eidFrom, long eidTo, int type, boolean bool) { - this.eidFrom = eidFrom; - this.eidTo = eidTo; - this.type = type; - this.bool = bool; - } - - // private + public long eidFrom; + public long eidTo; + public int type; + public boolean bool; + public PEEntityLink(long eidFrom, long eidTo, int type, boolean bool) { + this.eidFrom = eidFrom; + this.eidTo = eidTo; + this.type = type; + this.bool = bool; + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/type/PlayerListEntry.java b/src/main/java/org/dragonet/proxy/protocol/type/PlayerListEntry.java index 8ce258565..db2585e1d 100644 --- a/src/main/java/org/dragonet/proxy/protocol/type/PlayerListEntry.java +++ b/src/main/java/org/dragonet/proxy/protocol/type/PlayerListEntry.java @@ -6,20 +6,10 @@ * Created on 2017/10/22. */ public class PlayerListEntry { - // vars - public UUID uuid; - public long eid; - public String username; - public Skin skin; - public String xboxUserId; - - // constructor - public PlayerListEntry() { - - } - - // public - - // private + public UUID uuid; + public long eid; + public String username; + public Skin skin; + public String xboxUserId; } diff --git a/src/main/java/org/dragonet/proxy/protocol/type/Skin.java b/src/main/java/org/dragonet/proxy/protocol/type/Skin.java index 66b30c8ff..01cf73159 100644 --- a/src/main/java/org/dragonet/proxy/protocol/type/Skin.java +++ b/src/main/java/org/dragonet/proxy/protocol/type/Skin.java @@ -10,64 +10,58 @@ */ public class Skin { - public final static byte[] DEFAULT_SKIN_FULL_BINARY; - public final static Skin DEFAULT_SKIN; + public final static byte[] DEFAULT_SKIN_FULL_BINARY; + public final static Skin DEFAULT_SKIN; - static { - byte[] load = null; - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - InputStream ins = Skin.class.getResourceAsStream("/STEVE_SKIN_FULL_BINARY.bin"); - byte[] buffer = new byte[2048]; - int read; - while ((read = ins.read(buffer)) != -1) { - bos.write(buffer, 0, read); - } - bos.close(); - load = bos.toByteArray(); - }catch (Exception e){ - e.printStackTrace(); - } finally { - DEFAULT_SKIN_FULL_BINARY = load; + static { + byte[] load = null; + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + InputStream ins = Skin.class.getResourceAsStream("/STEVE_SKIN_FULL_BINARY.bin"); + byte[] buffer = new byte[2048]; + int read; + while ((read = ins.read(buffer)) != -1) { + bos.write(buffer, 0, read); + } + bos.close(); + load = bos.toByteArray(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + DEFAULT_SKIN_FULL_BINARY = load; - if(load != null) { - DEFAULT_SKIN = Skin.read(new BinaryStream(load)); - } else { - DEFAULT_SKIN = null; - } - } - } + if (load != null) { + DEFAULT_SKIN = Skin.read(new BinaryStream(load)); + } else { + DEFAULT_SKIN = null; + } + } + } - // vars - public String skinId; - public byte[] skinData; - public byte[] capeData; - public String geometryId; - public byte[] geometryData; + public String skinId; + public byte[] skinData; + public byte[] capeData; + public String geometryId; + public byte[] geometryData; - // constructor - public Skin(String skinId, byte[] skinData, byte[] capeData, String geometryId, byte[] geometryData) { - this.skinId = skinId; - this.skinData = skinData; - this.capeData = capeData; - this.geometryId = geometryId; - this.geometryData = geometryData; - } + public Skin(String skinId, byte[] skinData, byte[] capeData, String geometryId, byte[] geometryData) { + this.skinId = skinId; + this.skinData = skinData; + this.capeData = capeData; + this.geometryId = geometryId; + this.geometryData = geometryData; + } - // public - public static Skin read(BinaryStream source) { - return new Skin(source.getString(), source.getByteArray(), source.getByteArray(), source.getString(), - source.getByteArray()); - } - - public void write(BinaryStream dest) { - dest.putString(skinId); - dest.putByteArray(skinData); - dest.putByteArray(capeData); - dest.putString(geometryId); - dest.putByteArray(geometryData); - } - - // private + public static Skin read(BinaryStream source) { + return new Skin(source.getString(), source.getByteArray(), source.getByteArray(), source.getString(), + source.getByteArray()); + } + public void write(BinaryStream dest) { + dest.putString(skinId); + dest.putByteArray(skinData); + dest.putByteArray(capeData); + dest.putString(geometryId); + dest.putByteArray(geometryData); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/type/Slot.java b/src/main/java/org/dragonet/proxy/protocol/type/Slot.java index 999f4bc36..48b0520d4 100644 --- a/src/main/java/org/dragonet/proxy/protocol/type/Slot.java +++ b/src/main/java/org/dragonet/proxy/protocol/type/Slot.java @@ -1,51 +1,45 @@ package org.dragonet.proxy.protocol.type; - import org.dragonet.proxy.data.nbt.tag.CompoundTag; /** * Created on 2017/10/21. */ public class Slot { - // vars - public static final Slot AIR = new Slot(); - public int id; - public int damage; - public int count; - public CompoundTag tag; - - // constructor - public Slot() { - - } - - public Slot(int id) { - this.id = id; - } - - public Slot(int id, int damage) { - this.id = id; - this.damage = damage; - } - - public Slot(int id, int damage, int count) { - this.id = id; - this.damage = damage; - this.count = count; - } - - public Slot(int id, int damage, int count, CompoundTag tag) { - this.id = id; - this.damage = damage; - this.count = count; - this.tag = tag; - } - - // public - public Slot clone() { - return new Slot(id, damage, count, tag); - } - - // private + public static final Slot AIR = new Slot(); + public int id; + public int damage; + public int count; + public CompoundTag tag; + + public Slot() { + + } + + public Slot(int id) { + this.id = id; + } + + public Slot(int id, int damage) { + this.id = id; + this.damage = damage; + } + + public Slot(int id, int damage, int count) { + this.id = id; + this.damage = damage; + this.count = count; + } + + public Slot(int id, int damage, int count, CompoundTag tag) { + this.id = id; + this.damage = damage; + this.count = count; + this.tag = tag; + } + + public Slot clone() { + return new Slot(id, damage, count, tag); + } } diff --git a/src/main/java/org/dragonet/proxy/protocol/type/chunk/ChunkData.java b/src/main/java/org/dragonet/proxy/protocol/type/chunk/ChunkData.java index 031db9d9c..ff436b3b4 100644 --- a/src/main/java/org/dragonet/proxy/protocol/type/chunk/ChunkData.java +++ b/src/main/java/org/dragonet/proxy/protocol/type/chunk/ChunkData.java @@ -16,76 +16,72 @@ * Chunk's blocks, lights and other immutable data. */ public class ChunkData extends BinaryStream { - // vars - /** - * 16x16x16 section of the chunk. The array's keys also indicate the section's - * height (the 3rd element of the array will be the 3rd section from bottom, - * starting at `y=24`). The amount of sections should be in a range from 0 - * (empty chunk) to 16. - */ - public Section[] sections = new Section[0]; - public short[] heights = new short[256]; - /** - * Biomes in order `xz`. - */ - public byte[] biomes = new byte[256]; - /** - * Colums where there are world borders (in format `xz`). This feature hasn't - * been implemented in the game yet and crashes the client. - */ - public byte[] borders = new byte[0]; - public ExtraData[] extraData = new ExtraData[0]; - /** - * Additional data for the chunk's block entities (tiles), encoded in the same - * way as BlockEntityData.nbt is. The position is given by the `Int` tags `x`, - * `y`, `z` which are added to the block's compound tag together with the - * `String` tag `id` that contains the name of the tile in pascal case. Wrong - * encoding or missing tags may result in the block becoming invisible. - */ - public byte[] blockEntities = new byte[0]; - // constructor - public ChunkData() { + /** + * 16x16x16 section of the chunk. The array's keys also indicate the + * section's height (the 3rd element of the array will be the 3rd section + * from bottom, starting at `y=24`). The amount of sections should be in a + * range from 0 (empty chunk) to 16. + */ + public Section[] sections = new Section[0]; + public short[] heights = new short[256]; + /** + * Biomes in order `xz`. + */ + public byte[] biomes = new byte[256]; + /** + * Colums where there are world borders (in format `xz`). This feature + * hasn't been implemented in the game yet and crashes the client. + */ + public byte[] borders = new byte[0]; + public ExtraData[] extraData = new ExtraData[0]; + /** + * Additional data for the chunk's block entities (tiles), encoded in the + * same way as BlockEntityData.nbt is. The position is given by the `Int` + * tags `x`, `y`, `z` which are added to the block's compound tag together + * with the `String` tag `id` that contains the name of the tile in pascal + * case. Wrong encoding or missing tags may result in the block becoming + * invisible. + */ + public byte[] blockEntities = new byte[0]; - } + public ChunkData() { - public ChunkData(Section[] sections, short[] heights, byte[] biomes, byte[] borders, ExtraData[] extraData, - byte[] blockEntities) { - this.sections = sections; - this.heights = heights; - this.biomes = biomes; - this.borders = borders; - this.extraData = extraData; - this.blockEntities = blockEntities; - } + } - // public - public void encode() { - reset(); - putByte((byte) (sections.length & 0xff)); - for (Section s : sections) { - s.encode(this); - } - for (short h : heights) { - this.putLShort(h); - } - this.put(biomes); - this.putByte((byte) (borders.length & 0xFF)); - this.put(borders); - this.putVarInt(extraData.length); - for (ExtraData extra : extraData) { - extra.encode(this); - } - this.put(blockEntities); - } + public ChunkData(Section[] sections, short[] heights, byte[] biomes, byte[] borders, ExtraData[] extraData, + byte[] blockEntities) { + this.sections = sections; + this.heights = heights; + this.biomes = biomes; + this.borders = borders; + this.extraData = extraData; + this.blockEntities = blockEntities; + } - public String toString() { - return "ChunkData(sections: " + Arrays.deepToString(this.sections) + ", heights: " - + Arrays.toString(this.heights) + ", biomes: " + Arrays.toString(this.biomes) + ", borders: " - + Arrays.toString(this.borders) + ", extraData: " + Arrays.deepToString(this.extraData) - + ", blockEntities: " + Arrays.toString(this.blockEntities) + ")"; - } + public void encode() { + reset(); + putByte((byte) (sections.length & 0xff)); + for (Section s : sections) { + s.encode(this); + } + for (short h : heights) { + this.putLShort(h); + } + this.put(biomes); + this.putByte((byte) (borders.length & 0xFF)); + this.put(borders); + this.putVarInt(extraData.length); + for (ExtraData extra : extraData) { + extra.encode(this); + } + this.put(blockEntities); + } - // private - -} \ No newline at end of file + public String toString() { + return "ChunkData(sections: " + Arrays.deepToString(this.sections) + ", heights: " + + Arrays.toString(this.heights) + ", biomes: " + Arrays.toString(this.biomes) + ", borders: " + + Arrays.toString(this.borders) + ", extraData: " + Arrays.deepToString(this.extraData) + + ", blockEntities: " + Arrays.toString(this.blockEntities) + ")"; + } +} diff --git a/src/main/java/org/dragonet/proxy/protocol/type/chunk/ExtraData.java b/src/main/java/org/dragonet/proxy/protocol/type/chunk/ExtraData.java index a75b67b60..6fb3f97ac 100644 --- a/src/main/java/org/dragonet/proxy/protocol/type/chunk/ExtraData.java +++ b/src/main/java/org/dragonet/proxy/protocol/type/chunk/ExtraData.java @@ -11,35 +11,30 @@ import org.dragonet.proxy.utilities.BinaryStream; public class ExtraData { - // vars - public int key; - public short value; - // constructor - public ExtraData() { + public int key; + public short value; - } + public ExtraData() { - public ExtraData(int key, short value) { - this.key = key; - this.value = value; - } + } - // public - public void encode(BinaryStream out) { - out.putVarInt(key); - out.putLShort(value); - } + public ExtraData(int key, short value) { + this.key = key; + this.value = value; + } - public void decode(BinaryStream in) { - key = (int) in.getUnsignedVarInt(); - value = (short) in.getLShort(); - } + public void encode(BinaryStream out) { + out.putVarInt(key); + out.putLShort(value); + } - public String toString() { - return "ExtraData(key: " + this.key + ", value: " + this.value + ")"; - } + public void decode(BinaryStream in) { + key = (int) in.getUnsignedVarInt(); + value = (short) in.getLShort(); + } - // private - -} \ No newline at end of file + public String toString() { + return "ExtraData(key: " + this.key + ", value: " + this.value + ")"; + } +} diff --git a/src/main/java/org/dragonet/proxy/protocol/type/chunk/Section.java b/src/main/java/org/dragonet/proxy/protocol/type/chunk/Section.java index 1b6474146..6b5affe46 100644 --- a/src/main/java/org/dragonet/proxy/protocol/type/chunk/Section.java +++ b/src/main/java/org/dragonet/proxy/protocol/type/chunk/Section.java @@ -17,40 +17,35 @@ * bytes are always ordered `xzy`. */ public class Section { - // vars - public byte storageVersion = 0; - public byte[] blockIds = new byte[4096]; - public byte[] blockMetas = new byte[2048]; - - // constructor - public Section() { - - } - - public Section(byte storageVersion, byte[] blockIds, byte[] blockMetas) { - this.storageVersion = storageVersion; - this.blockIds = blockIds; - this.blockMetas = blockMetas; - } - - // public - public void encode(BinaryStream out) { - out.putByte(storageVersion); - out.put(blockIds); - out.put(blockMetas); - } - - public void decode(BinaryStream in) { - storageVersion = (byte) (in.getByte() & 0xFF); - blockIds = in.get(4096); - blockMetas = in.get(2048); - } - - public String toString() { - return "Section(storageVersion: " + this.storageVersion + ", blockIds: " + Arrays.toString(this.blockIds) - + ", blockMetas: " + Arrays.toString(this.blockMetas) + ")"; - } - - // private - -} \ No newline at end of file + + public byte storageVersion = 0; + public byte[] blockIds = new byte[4096]; + public byte[] blockMetas = new byte[2048]; + + public Section() { + + } + + public Section(byte storageVersion, byte[] blockIds, byte[] blockMetas) { + this.storageVersion = storageVersion; + this.blockIds = blockIds; + this.blockMetas = blockMetas; + } + + public void encode(BinaryStream out) { + out.putByte(storageVersion); + out.put(blockIds); + out.put(blockMetas); + } + + public void decode(BinaryStream in) { + storageVersion = (byte) (in.getByte() & 0xFF); + blockIds = in.get(4096); + blockMetas = in.get(2048); + } + + public String toString() { + return "Section(storageVersion: " + this.storageVersion + ", blockIds: " + Arrays.toString(this.blockIds) + + ", blockMetas: " + Arrays.toString(this.blockMetas) + ")"; + } +} diff --git a/src/main/java/org/dragonet/proxy/protocol/type/transaction/action/InventoryAction.java b/src/main/java/org/dragonet/proxy/protocol/type/transaction/action/InventoryAction.java index e6910620d..ca61680f3 100644 --- a/src/main/java/org/dragonet/proxy/protocol/type/transaction/action/InventoryAction.java +++ b/src/main/java/org/dragonet/proxy/protocol/type/transaction/action/InventoryAction.java @@ -8,7 +8,6 @@ */ public abstract class InventoryAction { - private long creationTime; protected Slot sourceItem; diff --git a/src/main/java/org/dragonet/proxy/utilities/Binary.java b/src/main/java/org/dragonet/proxy/utilities/Binary.java index cbbaa2c91..bc957d327 100644 --- a/src/main/java/org/dragonet/proxy/utilities/Binary.java +++ b/src/main/java/org/dragonet/proxy/utilities/Binary.java @@ -8,319 +8,313 @@ * author: MagicDroidX Nukkit Project */ public class Binary { - // vars - // constructor - public Binary() { + public Binary() { - } + } - // public - public static int signByte(int value) { - return value << 56 >> 56; - } - - public static int unsignByte(int value) { - return value & 0xff; - } - - public static int signShort(int value) { - return value << 48 >> 48; - } - - public int unsignShort(int value) { - return value & 0xffff; - } - - public static int signInt(int value) { - return value << 32 >> 32; - } - - public static int unsignInt(int value) { - return value; - } - - // Triad: {0x00,0x00,0x01}<=>1 - public static int readTriad(byte[] bytes) { - return readInt(new byte[] { (byte) 0x00, bytes[0], bytes[1], bytes[2] }); - } - - public static byte[] writeTriad(int value) { - return new byte[] { (byte) ((value >>> 16) & 0xFF), (byte) ((value >>> 8) & 0xFF), (byte) (value & 0xFF) }; - } - - // LTriad: {0x01,0x00,0x00}<=>1 - public static int readLTriad(byte[] bytes) { - return readLInt(new byte[] { bytes[0], bytes[1], bytes[2], (byte) 0x00 }); - } - - public static byte[] writeLTriad(int value) { - return new byte[] { (byte) (value & 0xFF), (byte) ((value >>> 8) & 0xFF), (byte) ((value >>> 16) & 0xFF) }; - } - - public static UUID readUUID(byte[] bytes) { - return new UUID(readLLong(bytes), readLLong( - new byte[] { bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15] })); - } - - public static byte[] writeUUID(UUID uuid) { - return appendBytes(writeLLong(uuid.getMostSignificantBits()), writeLLong(uuid.getLeastSignificantBits())); - } - - public static boolean readBool(byte b) { - return b == 0; - } - - public static byte writeBool(boolean b) { - return (byte) (b ? 0x01 : 0x00); - } - - public static int readSignedByte(byte b) { - return b & 0xFF; - } - - public static byte writeByte(byte b) { - return b; - } - - public static int readShort(byte[] bytes) { - return ((bytes[0] & 0xFF) << 8) + (bytes[1] & 0xFF); - } - - public static short readSignedShort(byte[] bytes) { - return (short) readShort(bytes); - } - - public static byte[] writeShort(int s) { - return new byte[] { (byte) ((s >>> 8) & 0xFF), (byte) (s & 0xFF) }; - } - - public static int readLShort(byte[] bytes) { - return (bytes[1] & 0xFF << 8) + (bytes[0] & 0xFF); - } - - public static short readSignedLShort(byte[] bytes) { - return (short) readLShort(bytes); - } - - public static byte[] writeLShort(int s) { - s &= 0xffff; - return new byte[] { (byte) (s & 0xFF), (byte) ((s >>> 8) & 0xFF) }; - } - - public static int readInt(byte[] bytes) { - return ((bytes[0] & 0xff) << 24) + ((bytes[1] & 0xff) << 16) + ((bytes[2] & 0xff) << 8) + (bytes[3] & 0xff); - } - - public static byte[] writeInt(int i) { - return new byte[] { (byte) ((i >>> 24) & 0xFF), (byte) ((i >>> 16) & 0xFF), (byte) ((i >>> 8) & 0xFF), - (byte) (i & 0xFF) }; - } - - public static int readLInt(byte[] bytes) { - return ((bytes[3] & 0xff) << 24) + ((bytes[2] & 0xff) << 16) + ((bytes[1] & 0xff) << 8) + (bytes[0] & 0xff); - } - - public static byte[] writeLInt(int i) { - return new byte[] { (byte) (i & 0xFF), (byte) ((i >>> 8) & 0xFF), (byte) ((i >>> 16) & 0xFF), - (byte) ((i >>> 24) & 0xFF) }; - } - - public static float readFloat(byte[] bytes) { - return readFloat(bytes, -1); - } - - public static float readFloat(byte[] bytes, int accuracy) { - float val = Float.intBitsToFloat(readInt(bytes)); - if (accuracy > -1) { - return (float) NukkitMath.round(val, accuracy); - } else { - return val; - } - } - - public static byte[] writeFloat(float f) { - return writeInt(Float.floatToIntBits(f)); - } - - public static float readLFloat(byte[] bytes) { - return readLFloat(bytes, -1); - } - - public static float readLFloat(byte[] bytes, int accuracy) { - float val = Float.intBitsToFloat(readLInt(bytes)); - if (accuracy > -1) { - return (float) NukkitMath.round(val, accuracy); - } else { - return val; - } - } - - public static byte[] writeLFloat(float f) { - return writeLInt(Float.floatToIntBits(f)); - } - - public static double readDouble(byte[] bytes) { - return Double.longBitsToDouble(readLong(bytes)); - } - - public static byte[] writeDouble(double d) { - return writeLong(Double.doubleToLongBits(d)); - } - - public static double readLDouble(byte[] bytes) { - return Double.longBitsToDouble(readLLong(bytes)); - } - - public static byte[] writeLDouble(double d) { - return writeLLong(Double.doubleToLongBits(d)); - } - - public static long readLong(byte[] bytes) { - return (((long) bytes[0] << 56) + ((long) (bytes[1] & 0xFF) << 48) + ((long) (bytes[2] & 0xFF) << 40) - + ((long) (bytes[3] & 0xFF) << 32) + ((long) (bytes[4] & 0xFF) << 24) + ((bytes[5] & 0xFF) << 16) - + ((bytes[6] & 0xFF) << 8) + ((bytes[7] & 0xFF))); - } - - public static byte[] writeLong(long l) { - return new byte[] { (byte) (l >>> 56), (byte) (l >>> 48), (byte) (l >>> 40), (byte) (l >>> 32), - (byte) (l >>> 24), (byte) (l >>> 16), (byte) (l >>> 8), (byte) (l) }; - } - - public static long readLLong(byte[] bytes) { - return (((long) bytes[7] << 56) + ((long) (bytes[6] & 0xFF) << 48) + ((long) (bytes[5] & 0xFF) << 40) - + ((long) (bytes[4] & 0xFF) << 32) + ((long) (bytes[3] & 0xFF) << 24) + ((bytes[2] & 0xFF) << 16) - + ((bytes[1] & 0xFF) << 8) + ((bytes[0] & 0xFF))); - } - - public static byte[] writeLLong(long l) { - return new byte[] { (byte) (l), (byte) (l >>> 8), (byte) (l >>> 16), (byte) (l >>> 24), (byte) (l >>> 32), - (byte) (l >>> 40), (byte) (l >>> 48), (byte) (l >>> 56), }; - } - - public static byte[] writeVarInt(int v) { - BinaryStream stream = new BinaryStream(); - stream.putVarInt(v); - return stream.getBuffer(); - } - - public static byte[] writeUnsignedVarInt(long v) { - BinaryStream stream = new BinaryStream(); - stream.putUnsignedVarInt(v); - return stream.getBuffer(); - } - - public static byte[] reserveBytes(byte[] bytes) { - byte[] newBytes = new byte[bytes.length]; - for (int i = 0; i < bytes.length; i++) { - newBytes[bytes.length - 1 - i] = bytes[i]; - } - return newBytes; - } - - public static String bytesToHexString(byte[] src) { - return bytesToHexString(src, false); - } - - public static String bytesToHexString(byte[] src, boolean blank) { - StringBuilder stringBuilder = new StringBuilder(""); - if (src == null || src.length <= 0) { - return null; - } - - for (byte b : src) { - if (!(stringBuilder.length() == 0) && blank) { - stringBuilder.append(" "); - } - int v = b & 0xFF; - String hv = Integer.toHexString(v); - if (hv.length() < 2) { - stringBuilder.append(0); - } - stringBuilder.append(hv); - } - return stringBuilder.toString().toUpperCase(); - } - - public static byte[] hexStringToBytes(String hexString) { - if (hexString == null || hexString.equals("")) { - return null; - } - String str = "0123456789ABCDEF"; - hexString = hexString.toUpperCase().replace(" ", ""); - int length = hexString.length() / 2; - char[] hexChars = hexString.toCharArray(); - byte[] d = new byte[length]; - for (int i = 0; i < length; i++) { - int pos = i * 2; - d[i] = (byte) (((byte) str.indexOf(hexChars[pos]) << 4) | ((byte) str.indexOf(hexChars[pos + 1]))); - } - return d; - } - - public static byte[] subBytes(byte[] bytes, int start, int length) { - int len = Math.min(bytes.length, start + length); - return Arrays.copyOfRange(bytes, start, len); - } - - public static byte[] subBytes(byte[] bytes, int start) { - return subBytes(bytes, start, bytes.length - start); - } - - public static byte[][] splitBytes(byte[] bytes, int chunkSize) { - byte[][] splits = new byte[(bytes.length + chunkSize - 1) / chunkSize][chunkSize]; - int chunks = 0; - - for (int i = 0; i < bytes.length; i += chunkSize) { - if ((bytes.length - i) > chunkSize) { - splits[chunks] = Arrays.copyOfRange(bytes, i, i + chunkSize); - } else { - splits[chunks] = Arrays.copyOfRange(bytes, i, bytes.length); - } - chunks++; - } - - return splits; - } - - public static byte[] appendBytes(byte[][] bytes) { - int length = 0; - for (byte[] b : bytes) { - length += b.length; - } - ByteBuffer buffer = ByteBuffer.allocate(length); - for (byte[] b : bytes) { - buffer.put(b); - } - return buffer.array(); - } - - public static byte[] appendBytes(byte byte1, byte[]... bytes2) { - int length = 1; - for (byte[] bytes : bytes2) { - length += bytes.length; - } - ByteBuffer buffer = ByteBuffer.allocate(length); - buffer.put(byte1); - for (byte[] bytes : bytes2) { - buffer.put(bytes); - } - return buffer.array(); - } - - public static byte[] appendBytes(byte[] bytes1, byte[]... bytes2) { - int length = bytes1.length; - for (byte[] bytes : bytes2) { - length += bytes.length; - } - ByteBuffer buffer = ByteBuffer.allocate(length); - buffer.put(bytes1); - for (byte[] bytes : bytes2) { - buffer.put(bytes); - } - return buffer.array(); - } - - // private + public static int signByte(int value) { + return value << 56 >> 56; + } + public static int unsignByte(int value) { + return value & 0xff; + } + + public static int signShort(int value) { + return value << 48 >> 48; + } + + public int unsignShort(int value) { + return value & 0xffff; + } + + public static int signInt(int value) { + return value << 32 >> 32; + } + + public static int unsignInt(int value) { + return value; + } + + // Triad: {0x00,0x00,0x01}<=>1 + public static int readTriad(byte[] bytes) { + return readInt(new byte[]{(byte) 0x00, bytes[0], bytes[1], bytes[2]}); + } + + public static byte[] writeTriad(int value) { + return new byte[]{(byte) ((value >>> 16) & 0xFF), (byte) ((value >>> 8) & 0xFF), (byte) (value & 0xFF)}; + } + + // LTriad: {0x01,0x00,0x00}<=>1 + public static int readLTriad(byte[] bytes) { + return readLInt(new byte[]{bytes[0], bytes[1], bytes[2], (byte) 0x00}); + } + + public static byte[] writeLTriad(int value) { + return new byte[]{(byte) (value & 0xFF), (byte) ((value >>> 8) & 0xFF), (byte) ((value >>> 16) & 0xFF)}; + } + + public static UUID readUUID(byte[] bytes) { + return new UUID(readLLong(bytes), readLLong( + new byte[]{bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]})); + } + + public static byte[] writeUUID(UUID uuid) { + return appendBytes(writeLLong(uuid.getMostSignificantBits()), writeLLong(uuid.getLeastSignificantBits())); + } + + public static boolean readBool(byte b) { + return b == 0; + } + + public static byte writeBool(boolean b) { + return (byte) (b ? 0x01 : 0x00); + } + + public static int readSignedByte(byte b) { + return b & 0xFF; + } + + public static byte writeByte(byte b) { + return b; + } + + public static int readShort(byte[] bytes) { + return ((bytes[0] & 0xFF) << 8) + (bytes[1] & 0xFF); + } + + public static short readSignedShort(byte[] bytes) { + return (short) readShort(bytes); + } + + public static byte[] writeShort(int s) { + return new byte[]{(byte) ((s >>> 8) & 0xFF), (byte) (s & 0xFF)}; + } + + public static int readLShort(byte[] bytes) { + return (bytes[1] & 0xFF << 8) + (bytes[0] & 0xFF); + } + + public static short readSignedLShort(byte[] bytes) { + return (short) readLShort(bytes); + } + + public static byte[] writeLShort(int s) { + s &= 0xffff; + return new byte[]{(byte) (s & 0xFF), (byte) ((s >>> 8) & 0xFF)}; + } + + public static int readInt(byte[] bytes) { + return ((bytes[0] & 0xff) << 24) + ((bytes[1] & 0xff) << 16) + ((bytes[2] & 0xff) << 8) + (bytes[3] & 0xff); + } + + public static byte[] writeInt(int i) { + return new byte[]{(byte) ((i >>> 24) & 0xFF), (byte) ((i >>> 16) & 0xFF), (byte) ((i >>> 8) & 0xFF), + (byte) (i & 0xFF)}; + } + + public static int readLInt(byte[] bytes) { + return ((bytes[3] & 0xff) << 24) + ((bytes[2] & 0xff) << 16) + ((bytes[1] & 0xff) << 8) + (bytes[0] & 0xff); + } + + public static byte[] writeLInt(int i) { + return new byte[]{(byte) (i & 0xFF), (byte) ((i >>> 8) & 0xFF), (byte) ((i >>> 16) & 0xFF), + (byte) ((i >>> 24) & 0xFF)}; + } + + public static float readFloat(byte[] bytes) { + return readFloat(bytes, -1); + } + + public static float readFloat(byte[] bytes, int accuracy) { + float val = Float.intBitsToFloat(readInt(bytes)); + if (accuracy > -1) { + return (float) NukkitMath.round(val, accuracy); + } else { + return val; + } + } + + public static byte[] writeFloat(float f) { + return writeInt(Float.floatToIntBits(f)); + } + + public static float readLFloat(byte[] bytes) { + return readLFloat(bytes, -1); + } + + public static float readLFloat(byte[] bytes, int accuracy) { + float val = Float.intBitsToFloat(readLInt(bytes)); + if (accuracy > -1) { + return (float) NukkitMath.round(val, accuracy); + } else { + return val; + } + } + + public static byte[] writeLFloat(float f) { + return writeLInt(Float.floatToIntBits(f)); + } + + public static double readDouble(byte[] bytes) { + return Double.longBitsToDouble(readLong(bytes)); + } + + public static byte[] writeDouble(double d) { + return writeLong(Double.doubleToLongBits(d)); + } + + public static double readLDouble(byte[] bytes) { + return Double.longBitsToDouble(readLLong(bytes)); + } + + public static byte[] writeLDouble(double d) { + return writeLLong(Double.doubleToLongBits(d)); + } + + public static long readLong(byte[] bytes) { + return (((long) bytes[0] << 56) + ((long) (bytes[1] & 0xFF) << 48) + ((long) (bytes[2] & 0xFF) << 40) + + ((long) (bytes[3] & 0xFF) << 32) + ((long) (bytes[4] & 0xFF) << 24) + ((bytes[5] & 0xFF) << 16) + + ((bytes[6] & 0xFF) << 8) + ((bytes[7] & 0xFF))); + } + + public static byte[] writeLong(long l) { + return new byte[]{(byte) (l >>> 56), (byte) (l >>> 48), (byte) (l >>> 40), (byte) (l >>> 32), + (byte) (l >>> 24), (byte) (l >>> 16), (byte) (l >>> 8), (byte) (l)}; + } + + public static long readLLong(byte[] bytes) { + return (((long) bytes[7] << 56) + ((long) (bytes[6] & 0xFF) << 48) + ((long) (bytes[5] & 0xFF) << 40) + + ((long) (bytes[4] & 0xFF) << 32) + ((long) (bytes[3] & 0xFF) << 24) + ((bytes[2] & 0xFF) << 16) + + ((bytes[1] & 0xFF) << 8) + ((bytes[0] & 0xFF))); + } + + public static byte[] writeLLong(long l) { + return new byte[]{(byte) (l), (byte) (l >>> 8), (byte) (l >>> 16), (byte) (l >>> 24), (byte) (l >>> 32), + (byte) (l >>> 40), (byte) (l >>> 48), (byte) (l >>> 56),}; + } + + public static byte[] writeVarInt(int v) { + BinaryStream stream = new BinaryStream(); + stream.putVarInt(v); + return stream.getBuffer(); + } + + public static byte[] writeUnsignedVarInt(long v) { + BinaryStream stream = new BinaryStream(); + stream.putUnsignedVarInt(v); + return stream.getBuffer(); + } + + public static byte[] reserveBytes(byte[] bytes) { + byte[] newBytes = new byte[bytes.length]; + for (int i = 0; i < bytes.length; i++) { + newBytes[bytes.length - 1 - i] = bytes[i]; + } + return newBytes; + } + + public static String bytesToHexString(byte[] src) { + return bytesToHexString(src, false); + } + + public static String bytesToHexString(byte[] src, boolean blank) { + StringBuilder stringBuilder = new StringBuilder(""); + if (src == null || src.length <= 0) { + return null; + } + + for (byte b : src) { + if (!(stringBuilder.length() == 0) && blank) { + stringBuilder.append(" "); + } + int v = b & 0xFF; + String hv = Integer.toHexString(v); + if (hv.length() < 2) { + stringBuilder.append(0); + } + stringBuilder.append(hv); + } + return stringBuilder.toString().toUpperCase(); + } + + public static byte[] hexStringToBytes(String hexString) { + if (hexString == null || hexString.equals("")) { + return null; + } + String str = "0123456789ABCDEF"; + hexString = hexString.toUpperCase().replace(" ", ""); + int length = hexString.length() / 2; + char[] hexChars = hexString.toCharArray(); + byte[] d = new byte[length]; + for (int i = 0; i < length; i++) { + int pos = i * 2; + d[i] = (byte) (((byte) str.indexOf(hexChars[pos]) << 4) | ((byte) str.indexOf(hexChars[pos + 1]))); + } + return d; + } + + public static byte[] subBytes(byte[] bytes, int start, int length) { + int len = Math.min(bytes.length, start + length); + return Arrays.copyOfRange(bytes, start, len); + } + + public static byte[] subBytes(byte[] bytes, int start) { + return subBytes(bytes, start, bytes.length - start); + } + + public static byte[][] splitBytes(byte[] bytes, int chunkSize) { + byte[][] splits = new byte[(bytes.length + chunkSize - 1) / chunkSize][chunkSize]; + int chunks = 0; + + for (int i = 0; i < bytes.length; i += chunkSize) { + if ((bytes.length - i) > chunkSize) { + splits[chunks] = Arrays.copyOfRange(bytes, i, i + chunkSize); + } else { + splits[chunks] = Arrays.copyOfRange(bytes, i, bytes.length); + } + chunks++; + } + + return splits; + } + + public static byte[] appendBytes(byte[][] bytes) { + int length = 0; + for (byte[] b : bytes) { + length += b.length; + } + ByteBuffer buffer = ByteBuffer.allocate(length); + for (byte[] b : bytes) { + buffer.put(b); + } + return buffer.array(); + } + + public static byte[] appendBytes(byte byte1, byte[]... bytes2) { + int length = 1; + for (byte[] bytes : bytes2) { + length += bytes.length; + } + ByteBuffer buffer = ByteBuffer.allocate(length); + buffer.put(byte1); + for (byte[] bytes : bytes2) { + buffer.put(bytes); + } + return buffer.array(); + } + + public static byte[] appendBytes(byte[] bytes1, byte[]... bytes2) { + int length = bytes1.length; + for (byte[] bytes : bytes2) { + length += bytes.length; + } + ByteBuffer buffer = ByteBuffer.allocate(length); + buffer.put(bytes1); + for (byte[] bytes : bytes2) { + buffer.put(bytes); + } + return buffer.array(); + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/BinaryStream.java b/src/main/java/org/dragonet/proxy/utilities/BinaryStream.java index 45b8fa97f..9f206221d 100644 --- a/src/main/java/org/dragonet/proxy/utilities/BinaryStream.java +++ b/src/main/java/org/dragonet/proxy/utilities/BinaryStream.java @@ -16,501 +16,499 @@ * author: MagicDroidX Nukkit Project */ public class BinaryStream { - // vars - public int offset; - private byte[] buffer = new byte[32]; - private int count; - - private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; - - // constructor - public BinaryStream() { - this.buffer = new byte[32]; - this.offset = 0; - this.count = 0; - } - - public BinaryStream(byte[] buffer) { - this(buffer, 0); - } - - public BinaryStream(byte[] buffer, int offset) { - this.buffer = buffer; - this.offset = offset; - this.count = buffer.length; - } - - // public - public void reset() { - this.buffer = new byte[32]; - this.offset = 0; - this.count = 0; - } - - public byte[] getBuffer() { - return Arrays.copyOf(buffer, count); - } - - public void setBuffer(byte[] buffer) { - this.buffer = buffer; - this.count = buffer == null ? -1 : buffer.length; - } - - public void setBuffer(byte[] buffer, int offset) { - this.setBuffer(buffer); - this.setOffset(offset); - } - - public int getOffset() { - return offset; - } - - public void setOffset(int offset) { - this.offset = offset; - } - - public int getCount() { - return count; - } - - public byte[] get() { - return this.get(this.count - this.offset); - } - - public byte[] get(int len) { - if (len < 0) { - this.offset = this.count - 1; - return new byte[0]; - } - len = Math.min(len, this.getCount() - this.offset); - this.offset += len; - return Arrays.copyOfRange(this.buffer, this.offset - len, this.offset); - } - - public void put(byte[] bytes) { - if (bytes == null) { - return; - } - - this.ensureCapacity(this.count + bytes.length); - - System.arraycopy(bytes, 0, this.buffer, this.count, bytes.length); - this.count += bytes.length; - } - - public long getLong() { - return Binary.readLong(this.get(8)); - } - - public void putLong(long l) { - this.put(Binary.writeLong(l)); - } - - public int getInt() { - return Binary.readInt(this.get(4)); - } - - public void putInt(int i) { - this.put(Binary.writeInt(i)); - } - - public long getLLong() { - return Binary.readLLong(this.get(8)); - } - - public void putLLong(long l) { - this.put(Binary.writeLLong(l)); - } - - public int getLInt() { - return Binary.readLInt(this.get(4)); - } - - public void putLInt(int i) { - this.put(Binary.writeLInt(i)); - } - - public int getShort() { - return Binary.readShort(this.get(2)); - } - - public void putShort(int s) { - this.put(Binary.writeShort(s)); - } - - public int getLShort() { - return Binary.readLShort(this.get(2)); - } - - public void putLShort(int s) { - this.put(Binary.writeLShort(s)); - } - - public float getFloat() { - return getFloat(-1); - } - - public float getFloat(int accuracy) { - return Binary.readFloat(this.get(4), accuracy); - } - - public void putFloat(float v) { - this.put(Binary.writeFloat(v)); - } - - public float getLFloat() { - return getLFloat(-1); - } - - public float getLFloat(int accuracy) { - return Binary.readLFloat(this.get(4), accuracy); - } - - public void putLFloat(float v) { - this.put(Binary.writeLFloat(v)); - } - - public int getTriad() { - return Binary.readTriad(this.get(3)); - } - - public void putTriad(int triad) { - this.put(Binary.writeTriad(triad)); - } - - public int getLTriad() { - return Binary.readLTriad(this.get(3)); - } - - public void putLTriad(int triad) { - this.put(Binary.writeLTriad(triad)); - } - - public boolean getBoolean() { - return this.getByte() == 0x01; - } - - public void putBoolean(boolean bool) { - this.putByte((byte) (bool ? 1 : 0)); - } - - public int getByte() { - return this.buffer[this.offset++] & 0xff; - } - - public void putByte(byte b) { - this.put(new byte[] { b }); - } - - public void putEntityLink(PEEntityLink link) { - putVarLong(link.eidFrom); - putVarLong(link.eidTo); - putByte((byte) (link.type & 0xFF)); - putBoolean(link.bool); - } - - public PEEntityLink getEntityLink() { - return new PEEntityLink(getVarLong(), getVarLong(), getByte(), getBoolean()); - } - - public Map getGameRules() { - int count = (int) getUnsignedVarInt(); - Map rules = new HashMap<>(); - for (int i = 0; i < count; i++) { - GameRule rule = GameRule.read(this); - rules.put(rule.name, rule); - } - return rules; - } - - public void putGameRules(Map rules) { - if (rules == null) { - putUnsignedVarInt(0); - return; - } - putUnsignedVarInt(rules.size()); - for (GameRule rule : rules.values()) { - rule.write(this); - } - } - - public float getByteRotation() { - return (((float) (getByte() & 0xFF)) * (360 / 256)); - } - - public void putByteRotation(float rotation) { - putByte((byte) (((int) (rotation / (360 / 256))) & 0xFF)); - } - - /** - * Reads a list of Attributes from the stream. - * - * @return Attribute[] - */ - public PEEntityAttribute[] getAttributeList() throws Exception { - List list = new ArrayList<>(); - long count = this.getUnsignedVarInt(); - - for (int i = 0; i < count; ++i) { - String name = this.getString(); - PEEntityAttribute attr = PEEntityAttribute.findAttribute(name); - if (attr != null) { - attr.min = getLFloat(); - attr.currentValue = getLFloat(); - attr.max = this.getLFloat(); - list.add(attr); - } else { - throw new Exception("Unknown attribute type \"" + name + "\""); - } - } - - return list.stream().toArray(PEEntityAttribute[]::new); - } - - /** - * Writes a list of Attributes to the packet buffer using the standard format. - */ - public void putAttributeList(PEEntityAttribute[] attributes) { - this.putUnsignedVarInt(attributes.length); - for (PEEntityAttribute attribute : attributes) { - this.putString(attribute.name); - this.putLFloat(attribute.min); - this.putLFloat(attribute.currentValue); - this.putLFloat(attribute.max); - } - } - - public void putUUID(UUID uuid) { - this.put(Binary.writeUUID(uuid)); - } - - public UUID getUUID() { - return Binary.readUUID(this.get(16)); - } - - public Slot getSlot() { - int id = this.getVarInt(); - - if (id <= 0) { - return Slot.AIR; - } - int auxValue = this.getVarInt(); - int data = auxValue >> 8; - if (data == Short.MAX_VALUE) { - data = -1; - } - int cnt = auxValue & 0xff; - - int nbtLen = this.getLShort(); - byte[] nbt; - CompoundTag tag = null; - if (nbtLen > 0) { - nbt = this.get(nbtLen); - try { - tag = NBTIO.read(nbt, ByteOrder.LITTLE_ENDIAN); - } catch (IOException e) { - e.printStackTrace(); - } - } - - // TODO - int canPlaceOn = this.getVarInt(); - if (canPlaceOn > 0) { - for (int i = 0; i < canPlaceOn; ++i) { - this.getString(); - } - } - - // TODO - int canDestroy = this.getVarInt(); - if (canDestroy > 0) { - for (int i = 0; i < canDestroy; ++i) { - this.getString(); - } - } - - return new Slot(id, data, cnt, tag); - } - - public void putSlot(Slot item) { - if (item == null || item.id == 0) { - this.putVarInt(0); - return; - } - - this.putVarInt(item.id); - int auxValue = ((item.damage & 0x7fff) << 8) | item.count; - this.putVarInt(auxValue); - byte[] nbt; - if (item.tag != null) { - try { - nbt = NBTIO.write(item.tag, ByteOrder.LITTLE_ENDIAN); - } catch (IOException e) { - e.printStackTrace(); - nbt = new byte[0]; - } - } else { - nbt = new byte[0]; - } - this.putLShort(nbt.length); - this.put(nbt); - this.putVarInt(0); // TODO CanPlaceOn entry count - this.putVarInt(0); // TODO CanDestroy entry count - } - - public byte[] getByteArray() { - return this.get((int) this.getUnsignedVarInt()); - } - - public void putByteArray(byte[] b) { - this.putUnsignedVarInt(b.length); - this.put(b); - } - - public String getString() { - return new String(this.getByteArray(), StandardCharsets.UTF_8); - } - - public void putString(String string) { - byte[] b = string.getBytes(StandardCharsets.UTF_8); - this.putByteArray(b); - } - - public long getUnsignedVarInt() { - return VarInt.readUnsignedVarInt(this); - } - - public void putUnsignedVarInt(long v) { - VarInt.writeUnsignedVarInt(this, v); - } - - public int getVarInt() { - return VarInt.readVarInt(this); - } - - public void putVarInt(int v) { - VarInt.writeVarInt(this, v); - } - - public long getVarLong() { - return VarInt.readVarLong(this); - } - - public void putVarLong(long v) { - VarInt.writeVarLong(this, v); - } - - public long getUnsignedVarLong() { - return VarInt.readUnsignedVarLong(this); - } - - public void putUnsignedVarLong(long v) { - VarInt.writeUnsignedVarLong(this, v); - } - - public BlockPosition getBlockPosition() { - return new BlockPosition(this.getVarInt(), (int) this.getUnsignedVarInt(), this.getVarInt()); - } - - public BlockPosition getSignedBlockPosition() { - return new BlockPosition(getVarInt(), getVarInt(), getVarInt()); - } - - public void putSignedBlockPosition(BlockPosition v) { - putVarInt(v.x); - putVarInt(v.y); - putVarInt(v.z); - } - - public void putBlockPosition(BlockPosition v) { - this.putBlockPosition(v.x, v.y, v.z); - } - - public void putBlockPosition(int x, int y, int z) { - this.putVarInt(x); - this.putUnsignedVarInt(y); - this.putVarInt(z); - } - - public Vector3F getVector3F() { - return new Vector3F(this.getLFloat(4), this.getLFloat(4), this.getLFloat(4)); - } - - public void putVector3F(Vector3F v) { - if(v == null) { - this.putVector3F(0f, 0f, 0f); - } else { - this.putVector3F(v.x, v.y, v.z); - } - } - - public void putVector3F(float x, float y, float z) { - this.putLFloat(Math.round(x * 10000f) / 10000f); - this.putLFloat(Math.round(y * 10000f) / 10000f); - this.putLFloat(Math.round(z * 10000f) / 10000f); - } - - /** - * Reads and returns an EntityUniqueID - * - * @return int - */ - public long getEntityUniqueId() { - return this.getVarLong(); - } - - /** - * Writes an EntityUniqueID - */ - public void putEntityUniqueId(long eid) { - this.putVarLong(eid); - } - - /** - * Reads and returns an EntityRuntimeID - */ - public long getEntityRuntimeId() { - return this.getUnsignedVarLong(); - } - - /** - * Writes an EntityUniqueID - */ - public void putEntityRuntimeId(long eid) { - this.putUnsignedVarLong(eid); - } - - public boolean feof() { - return this.offset < 0 || this.offset >= this.buffer.length; - } - - // private - private void ensureCapacity(int minCapacity) { - // overflow-conscious code - if (minCapacity - buffer.length > 0) { - grow(minCapacity); - } - } - - private void grow(int minCapacity) { - // overflow-conscious code - int oldCapacity = buffer.length; - int newCapacity = oldCapacity << 1; - - if (newCapacity - minCapacity < 0) { - newCapacity = minCapacity; - } - - if (newCapacity - MAX_ARRAY_SIZE > 0) { - newCapacity = hugeCapacity(minCapacity); - } - this.buffer = Arrays.copyOf(buffer, newCapacity); - } - - private static int hugeCapacity(int minCapacity) { - if (minCapacity < 0) { // overflow - throw new OutOfMemoryError(); - } - return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; - } + + public int offset; + private byte[] buffer = new byte[32]; + private int count; + + private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; + + public BinaryStream() { + this.buffer = new byte[32]; + this.offset = 0; + this.count = 0; + } + + public BinaryStream(byte[] buffer) { + this(buffer, 0); + } + + public BinaryStream(byte[] buffer, int offset) { + this.buffer = buffer; + this.offset = offset; + this.count = buffer.length; + } + + public void reset() { + this.buffer = new byte[32]; + this.offset = 0; + this.count = 0; + } + + public byte[] getBuffer() { + return Arrays.copyOf(buffer, count); + } + + public void setBuffer(byte[] buffer) { + this.buffer = buffer; + this.count = buffer == null ? -1 : buffer.length; + } + + public void setBuffer(byte[] buffer, int offset) { + this.setBuffer(buffer); + this.setOffset(offset); + } + + public int getOffset() { + return offset; + } + + public void setOffset(int offset) { + this.offset = offset; + } + + public int getCount() { + return count; + } + + public byte[] get() { + return this.get(this.count - this.offset); + } + + public byte[] get(int len) { + if (len < 0) { + this.offset = this.count - 1; + return new byte[0]; + } + len = Math.min(len, this.getCount() - this.offset); + this.offset += len; + return Arrays.copyOfRange(this.buffer, this.offset - len, this.offset); + } + + public void put(byte[] bytes) { + if (bytes == null) { + return; + } + + this.ensureCapacity(this.count + bytes.length); + + System.arraycopy(bytes, 0, this.buffer, this.count, bytes.length); + this.count += bytes.length; + } + + public long getLong() { + return Binary.readLong(this.get(8)); + } + + public void putLong(long l) { + this.put(Binary.writeLong(l)); + } + + public int getInt() { + return Binary.readInt(this.get(4)); + } + + public void putInt(int i) { + this.put(Binary.writeInt(i)); + } + + public long getLLong() { + return Binary.readLLong(this.get(8)); + } + + public void putLLong(long l) { + this.put(Binary.writeLLong(l)); + } + + public int getLInt() { + return Binary.readLInt(this.get(4)); + } + + public void putLInt(int i) { + this.put(Binary.writeLInt(i)); + } + + public int getShort() { + return Binary.readShort(this.get(2)); + } + + public void putShort(int s) { + this.put(Binary.writeShort(s)); + } + + public int getLShort() { + return Binary.readLShort(this.get(2)); + } + + public void putLShort(int s) { + this.put(Binary.writeLShort(s)); + } + + public float getFloat() { + return getFloat(-1); + } + + public float getFloat(int accuracy) { + return Binary.readFloat(this.get(4), accuracy); + } + + public void putFloat(float v) { + this.put(Binary.writeFloat(v)); + } + + public float getLFloat() { + return getLFloat(-1); + } + + public float getLFloat(int accuracy) { + return Binary.readLFloat(this.get(4), accuracy); + } + + public void putLFloat(float v) { + this.put(Binary.writeLFloat(v)); + } + + public int getTriad() { + return Binary.readTriad(this.get(3)); + } + + public void putTriad(int triad) { + this.put(Binary.writeTriad(triad)); + } + + public int getLTriad() { + return Binary.readLTriad(this.get(3)); + } + + public void putLTriad(int triad) { + this.put(Binary.writeLTriad(triad)); + } + + public boolean getBoolean() { + return this.getByte() == 0x01; + } + + public void putBoolean(boolean bool) { + this.putByte((byte) (bool ? 1 : 0)); + } + + public int getByte() { + return this.buffer[this.offset++] & 0xff; + } + + public void putByte(byte b) { + this.put(new byte[]{b}); + } + + public void putEntityLink(PEEntityLink link) { + putVarLong(link.eidFrom); + putVarLong(link.eidTo); + putByte((byte) (link.type & 0xFF)); + putBoolean(link.bool); + } + + public PEEntityLink getEntityLink() { + return new PEEntityLink(getVarLong(), getVarLong(), getByte(), getBoolean()); + } + + public Map getGameRules() { + int count = (int) getUnsignedVarInt(); + Map rules = new HashMap<>(); + for (int i = 0; i < count; i++) { + GameRule rule = GameRule.read(this); + rules.put(rule.name, rule); + } + return rules; + } + + public void putGameRules(Map rules) { + if (rules == null) { + putUnsignedVarInt(0); + return; + } + putUnsignedVarInt(rules.size()); + for (GameRule rule : rules.values()) { + rule.write(this); + } + } + + public float getByteRotation() { + return (((float) (getByte() & 0xFF)) * (360 / 256)); + } + + public void putByteRotation(float rotation) { + putByte((byte) (((int) (rotation / (360 / 256))) & 0xFF)); + } + + /** + * Reads a list of Attributes from the stream. + * + * @return Attribute[] + */ + public PEEntityAttribute[] getAttributeList() throws Exception { + List list = new ArrayList<>(); + long count = this.getUnsignedVarInt(); + + for (int i = 0; i < count; ++i) { + String name = this.getString(); + PEEntityAttribute attr = PEEntityAttribute.findAttribute(name); + if (attr != null) { + attr.min = getLFloat(); + attr.currentValue = getLFloat(); + attr.max = this.getLFloat(); + list.add(attr); + } else { + throw new Exception("Unknown attribute type \"" + name + "\""); + } + } + + return list.stream().toArray(PEEntityAttribute[]::new); + } + + /** + * Writes a list of Attributes to the packet buffer using the standard + * format. + */ + public void putAttributeList(PEEntityAttribute[] attributes) { + this.putUnsignedVarInt(attributes.length); + for (PEEntityAttribute attribute : attributes) { + this.putString(attribute.name); + this.putLFloat(attribute.min); + this.putLFloat(attribute.currentValue); + this.putLFloat(attribute.max); + } + } + + public void putUUID(UUID uuid) { + this.put(Binary.writeUUID(uuid)); + } + + public UUID getUUID() { + return Binary.readUUID(this.get(16)); + } + + public Slot getSlot() { + int id = this.getVarInt(); + + if (id <= 0) { + return Slot.AIR; + } + int auxValue = this.getVarInt(); + int data = auxValue >> 8; + if (data == Short.MAX_VALUE) { + data = -1; + } + int cnt = auxValue & 0xff; + + int nbtLen = this.getLShort(); + byte[] nbt; + CompoundTag tag = null; + if (nbtLen > 0) { + nbt = this.get(nbtLen); + try { + tag = NBTIO.read(nbt, ByteOrder.LITTLE_ENDIAN); + } catch (IOException e) { + e.printStackTrace(); + } + } + + // TODO + int canPlaceOn = this.getVarInt(); + if (canPlaceOn > 0) { + for (int i = 0; i < canPlaceOn; ++i) { + this.getString(); + } + } + + // TODO + int canDestroy = this.getVarInt(); + if (canDestroy > 0) { + for (int i = 0; i < canDestroy; ++i) { + this.getString(); + } + } + + return new Slot(id, data, cnt, tag); + } + + public void putSlot(Slot item) { + if (item == null || item.id == 0) { + this.putVarInt(0); + return; + } + + this.putVarInt(item.id); + int auxValue = ((item.damage & 0x7fff) << 8) | item.count; + this.putVarInt(auxValue); + byte[] nbt; + if (item.tag != null) { + try { + nbt = NBTIO.write(item.tag, ByteOrder.LITTLE_ENDIAN); + } catch (IOException e) { + e.printStackTrace(); + nbt = new byte[0]; + } + } else { + nbt = new byte[0]; + } + this.putLShort(nbt.length); + this.put(nbt); + this.putVarInt(0); // TODO CanPlaceOn entry count + this.putVarInt(0); // TODO CanDestroy entry count + } + + public byte[] getByteArray() { + return this.get((int) this.getUnsignedVarInt()); + } + + public void putByteArray(byte[] b) { + this.putUnsignedVarInt(b.length); + this.put(b); + } + + public String getString() { + return new String(this.getByteArray(), StandardCharsets.UTF_8); + } + + public void putString(String string) { + byte[] b = string.getBytes(StandardCharsets.UTF_8); + this.putByteArray(b); + } + + public long getUnsignedVarInt() { + return VarInt.readUnsignedVarInt(this); + } + + public void putUnsignedVarInt(long v) { + VarInt.writeUnsignedVarInt(this, v); + } + + public int getVarInt() { + return VarInt.readVarInt(this); + } + + public void putVarInt(int v) { + VarInt.writeVarInt(this, v); + } + + public long getVarLong() { + return VarInt.readVarLong(this); + } + + public void putVarLong(long v) { + VarInt.writeVarLong(this, v); + } + + public long getUnsignedVarLong() { + return VarInt.readUnsignedVarLong(this); + } + + public void putUnsignedVarLong(long v) { + VarInt.writeUnsignedVarLong(this, v); + } + + public BlockPosition getBlockPosition() { + return new BlockPosition(this.getVarInt(), (int) this.getUnsignedVarInt(), this.getVarInt()); + } + + public BlockPosition getSignedBlockPosition() { + return new BlockPosition(getVarInt(), getVarInt(), getVarInt()); + } + + public void putSignedBlockPosition(BlockPosition v) { + putVarInt(v.x); + putVarInt(v.y); + putVarInt(v.z); + } + + public void putBlockPosition(BlockPosition v) { + this.putBlockPosition(v.x, v.y, v.z); + } + + public void putBlockPosition(int x, int y, int z) { + this.putVarInt(x); + this.putUnsignedVarInt(y); + this.putVarInt(z); + } + + public Vector3F getVector3F() { + return new Vector3F(this.getLFloat(4), this.getLFloat(4), this.getLFloat(4)); + } + + public void putVector3F(Vector3F v) { + if (v == null) { + this.putVector3F(0f, 0f, 0f); + } else { + this.putVector3F(v.x, v.y, v.z); + } + } + + public void putVector3F(float x, float y, float z) { + this.putLFloat(Math.round(x * 10000f) / 10000f); + this.putLFloat(Math.round(y * 10000f) / 10000f); + this.putLFloat(Math.round(z * 10000f) / 10000f); + } + + /** + * Reads and returns an EntityUniqueID + * + * @return int + */ + public long getEntityUniqueId() { + return this.getVarLong(); + } + + /** + * Writes an EntityUniqueID + */ + public void putEntityUniqueId(long eid) { + this.putVarLong(eid); + } + + /** + * Reads and returns an EntityRuntimeID + */ + public long getEntityRuntimeId() { + return this.getUnsignedVarLong(); + } + + /** + * Writes an EntityUniqueID + */ + public void putEntityRuntimeId(long eid) { + this.putUnsignedVarLong(eid); + } + + public boolean feof() { + return this.offset < 0 || this.offset >= this.buffer.length; + } + + private void ensureCapacity(int minCapacity) { + // overflow-conscious code + if (minCapacity - buffer.length > 0) { + grow(minCapacity); + } + } + + private void grow(int minCapacity) { + // overflow-conscious code + int oldCapacity = buffer.length; + int newCapacity = oldCapacity << 1; + + if (newCapacity - minCapacity < 0) { + newCapacity = minCapacity; + } + + if (newCapacity - MAX_ARRAY_SIZE > 0) { + newCapacity = hugeCapacity(minCapacity); + } + this.buffer = Arrays.copyOf(buffer, newCapacity); + } + + private static int hugeCapacity(int minCapacity) { + if (minCapacity < 0) { // overflow + throw new OutOfMemoryError(); + } + return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/BlockPosition.java b/src/main/java/org/dragonet/proxy/utilities/BlockPosition.java index 0da4fa36b..809f5d1a2 100644 --- a/src/main/java/org/dragonet/proxy/utilities/BlockPosition.java +++ b/src/main/java/org/dragonet/proxy/utilities/BlockPosition.java @@ -20,9 +20,8 @@ public BlockPosition(int x, int y, int z) { this.y = y; this.z = z; } - - public BlockPosition(Position pos) - { + + public BlockPosition(Position pos) { this.x = pos.getX(); this.y = pos.getY(); this.z = pos.getZ(); diff --git a/src/main/java/org/dragonet/proxy/utilities/Constants.java b/src/main/java/org/dragonet/proxy/utilities/Constants.java index 936db641f..f1b55e131 100644 --- a/src/main/java/org/dragonet/proxy/utilities/Constants.java +++ b/src/main/java/org/dragonet/proxy/utilities/Constants.java @@ -4,16 +4,10 @@ * Created on 2017/10/23. */ public class Constants { - // vars - public static final float PLAYER_HEAD_OFFSET = 1.6200000047683716f; - // constructor - public Constants() { + public static final float PLAYER_HEAD_OFFSET = 1.6200000047683716f; //UNUSED - } - - // public - - // private + public Constants() { + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/DebugTools.java b/src/main/java/org/dragonet/proxy/utilities/DebugTools.java index 9383777e4..1b287b3a1 100644 --- a/src/main/java/org/dragonet/proxy/utilities/DebugTools.java +++ b/src/main/java/org/dragonet/proxy/utilities/DebugTools.java @@ -9,16 +9,14 @@ * Created on 2017/12/3. */ public class DebugTools { - + private static final Set> WRAPPER_TYPES = getWrapperTypes(); - public static boolean isWrapperType(Class clazz) - { + public static boolean isWrapperType(Class clazz) { return WRAPPER_TYPES.contains(clazz); } - private static Set> getWrapperTypes() - { + private static Set> getWrapperTypes() { Set> ret = new HashSet>(); ret.add(Boolean.class); ret.add(Character.class); @@ -33,29 +31,27 @@ private static Set> getWrapperTypes() } public static String getAllFields(Object obj) { - if(obj == null) { + if (obj == null) { return "NULL"; } Field[] fields = obj.getClass().getDeclaredFields(); String data = "INSTANCE OF " + obj.getClass().getName() + "\n"; - if (obj instanceof com.github.steveice10.opennbt.tag.builtin.CompoundTag) - { - data += ((com.github.steveice10.opennbt.tag.builtin.CompoundTag)obj).toString() + "\n"; - } - else if (obj instanceof org.dragonet.proxy.data.nbt.tag.CompoundTag) - { - data += ((org.dragonet.proxy.data.nbt.tag.CompoundTag)obj).toString() + "\n"; - } - else - { - for(Field f : fields) { + if (obj instanceof com.github.steveice10.opennbt.tag.builtin.CompoundTag) { + data += ((com.github.steveice10.opennbt.tag.builtin.CompoundTag) obj).toString() + "\n"; + } else if (obj instanceof org.dragonet.proxy.data.nbt.tag.CompoundTag) { + data += ((org.dragonet.proxy.data.nbt.tag.CompoundTag) obj).toString() + "\n"; + } else { + for (Field f : fields) { f.setAccessible(true); - if((f.getModifiers() & Modifier.STATIC) > 0) continue; + if ((f.getModifiers() & Modifier.STATIC) > 0) { + continue; + } try { - if (isWrapperType(f.get(obj).getClass())) + if (isWrapperType(f.get(obj).getClass())) { data += f.getName() + " = " + f.get(obj).toString(); - else + } else { data += f.getName() + " = " + getAllFields(f.get(obj)); + } } catch (Exception e) { data += ": " + f.getName() + " = ERROR"; } diff --git a/src/main/java/org/dragonet/proxy/utilities/DefaultSkin.java b/src/main/java/org/dragonet/proxy/utilities/DefaultSkin.java index 0f6a5f071..2d58d39dc 100644 --- a/src/main/java/org/dragonet/proxy/utilities/DefaultSkin.java +++ b/src/main/java/org/dragonet/proxy/utilities/DefaultSkin.java @@ -15,56 +15,51 @@ import java.io.*; public class DefaultSkin { - // vars - protected static String NAME; - protected static String SKIN_BASE64_ENCODED; - protected static MCPESkin SKIN; - static { - loadSkin(); - } + protected static String NAME; + protected static String SKIN_BASE64_ENCODED; + protected static MCPESkin SKIN; - // constructor - public DefaultSkin() { + static { + loadSkin(); + } - } + public DefaultSkin() { - // public - public static String getDefaultSkinName() { - return NAME; - } + } - public static String getDefaultSkinBase64Encoded() { - return SKIN_BASE64_ENCODED; - } + public static String getDefaultSkinName() { + return NAME; + } - public static MCPESkin getDefaultSkin() { - return SKIN; - } + public static String getDefaultSkinBase64Encoded() { + return SKIN_BASE64_ENCODED; + } - private static void loadSkin() { - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - InputStream ins = DefaultSkin.class.getResourceAsStream("/defaults/SKIN.BIN"); - int d = -1; - while ((d = ins.read()) != -1) { - if (d == ':') { - NAME = new String(bos.toByteArray(), "UTF-8"); - bos.reset(); - } else { - bos.write(d); - } + public static MCPESkin getDefaultSkin() { + return SKIN; + } - } - ins.close(); - SKIN_BASE64_ENCODED = new String(bos.toByteArray(), "UTF-8"); + private static void loadSkin() { + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + InputStream ins = DefaultSkin.class.getResourceAsStream("/defaults/SKIN.BIN"); + int d = -1; + while ((d = ins.read()) != -1) { + if (d == ':') { + NAME = new String(bos.toByteArray(), "UTF-8"); + bos.reset(); + } else { + bos.write(d); + } - SKIN = new MCPESkin(SKIN_BASE64_ENCODED, NAME); - } catch (IOException e) { - e.printStackTrace(); - } - } - - // private + } + ins.close(); + SKIN_BASE64_ENCODED = new String(bos.toByteArray(), "UTF-8"); + SKIN = new MCPESkin(SKIN_BASE64_ENCODED, NAME); + } catch (IOException e) { + e.printStackTrace(); + } + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/GameRule.java b/src/main/java/org/dragonet/proxy/utilities/GameRule.java index 2fb70fd1f..149a0e648 100644 --- a/src/main/java/org/dragonet/proxy/utilities/GameRule.java +++ b/src/main/java/org/dragonet/proxy/utilities/GameRule.java @@ -4,62 +4,58 @@ * Created on 2017/10/21. */ public class GameRule { - // vars - public String name; - public GameRuleType type; - public Object value; - public enum GameRuleType { - UNKNOWN, BOOLEAN, VARUINT, FLOAT - } + public String name; + public GameRuleType type; + public Object value; - // constructor - public GameRule(String name, GameRuleType type, Object value) { - this.name = name; - this.type = type; - this.value = value; - } + public enum GameRuleType { + UNKNOWN, BOOLEAN, VARUINT, FLOAT + } - // public - public static GameRule read(BinaryStream source) { - String name = source.getString(); - GameRuleType type = GameRuleType.values()[(int) source.getUnsignedVarInt()]; - Object value; - switch (type) { - case BOOLEAN: - value = source.getBoolean(); - break; - case VARUINT: - value = source.getUnsignedVarInt(); - break; - case FLOAT: - value = source.getLFloat(); - break; - default: - value = null; - break; - } - return new GameRule(name, type, value); - } + public GameRule(String name, GameRuleType type, Object value) { + this.name = name; + this.type = type; + this.value = value; + } - public void write(BinaryStream out) { - if (type.ordinal() == 0) - return; // wtf - out.putString(name); - out.putUnsignedVarInt(type.ordinal()); - switch (type) { - case BOOLEAN: - out.putBoolean((boolean) value); - break; - case VARUINT: - out.putUnsignedVarInt((int) value); - break; - case FLOAT: - out.putLFloat((Float) value); - break; - } - } - - // private + public static GameRule read(BinaryStream source) { + String name = source.getString(); + GameRuleType type = GameRuleType.values()[(int) source.getUnsignedVarInt()]; + Object value; + switch (type) { + case BOOLEAN: + value = source.getBoolean(); + break; + case VARUINT: + value = source.getUnsignedVarInt(); + break; + case FLOAT: + value = source.getLFloat(); + break; + default: + value = null; + break; + } + return new GameRule(name, type, value); + } + public void write(BinaryStream out) { + if (type.ordinal() == 0) { + return; // wtf + } + out.putString(name); + out.putUnsignedVarInt(type.ordinal()); + switch (type) { + case BOOLEAN: + out.putBoolean((boolean) value); + break; + case VARUINT: + out.putUnsignedVarInt((int) value); + break; + case FLOAT: + out.putLFloat((Float) value); + break; + } + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/HTTP.java b/src/main/java/org/dragonet/proxy/utilities/HTTP.java index e52e330e5..77922249d 100644 --- a/src/main/java/org/dragonet/proxy/utilities/HTTP.java +++ b/src/main/java/org/dragonet/proxy/utilities/HTTP.java @@ -20,59 +20,53 @@ import java.net.URL; public class HTTP { - // vars - // constructor - public HTTP() { + public HTTP() { - } + } - // public - public static String performGetRequest(String url) { - if (url == null) { - throw new IllegalArgumentException("URL cannot be null."); - } + public static String performGetRequest(String url) { + if (url == null) { + throw new IllegalArgumentException("URL cannot be null."); + } - InputStream in = null; - try { - HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); - connection.setConnectTimeout(15000); - connection.setReadTimeout(15000); - connection.setUseCaches(false); - connection.setDoInput(true); + InputStream in = null; + try { + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setConnectTimeout(15000); + connection.setReadTimeout(15000); + connection.setUseCaches(false); + connection.setDoInput(true); - int responseCode = connection.getResponseCode(); - if (responseCode == 200) { - in = connection.getInputStream(); - } else { - in = connection.getErrorStream(); - } + int responseCode = connection.getResponseCode(); + if (responseCode == 200) { + in = connection.getInputStream(); + } else { + in = connection.getErrorStream(); + } - if (in != null) { - int data = -1; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + if (in != null) { + int data = -1; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); - while ((data = in.read()) != -1) { - bos.write(data); - } - - return new String(bos.toByteArray(), CharsetUtil.UTF_8); - } else { - return null; - } - } catch (Exception e) { - e.printStackTrace(); - return null; - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - } - } - } - } - - // private + while ((data = in.read()) != -1) { + bos.write(data); + } + return new String(bos.toByteArray(), CharsetUtil.UTF_8); + } else { + return null; + } + } catch (Exception e) { + e.printStackTrace(); + return null; + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + } + } + } + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/Logger.java b/src/main/java/org/dragonet/proxy/utilities/Logger.java index de1a0a2ab..020537906 100644 --- a/src/main/java/org/dragonet/proxy/utilities/Logger.java +++ b/src/main/java/org/dragonet/proxy/utilities/Logger.java @@ -18,60 +18,58 @@ import java.util.Calendar; public class Logger { - // vars - private boolean colorful = false; - private DragonProxy proxy; - private Calendar calender; - private SimpleDateFormat consoleDate; - public boolean debug = false; - // constructor - public Logger(DragonProxy proxy) { - this.proxy = proxy; - calender = Calendar.getInstance(); - consoleDate = new SimpleDateFormat("HH:mm:ss"); - } + private boolean colorful = false; + private DragonProxy proxy; + private Calendar calender; + private SimpleDateFormat consoleDate; + public boolean debug = false; - // public - public void info(String message) { - log("INFO", message); - } + public Logger(DragonProxy proxy) { + this.proxy = proxy; + calender = Calendar.getInstance(); + consoleDate = new SimpleDateFormat("HH:mm:ss"); + } - public void warning(String message) { - log(MCColor.YELLOW, "WARNING", message); - } + public void info(String message) { + log("INFO", message); + } - public void severe(String message) { - log(MCColor.RED, "SEVERE", message); - } + public void warning(String message) { + log(MCColor.YELLOW, "WARNING", message); + } - public void debug(String message) { - if (debug) - log(MCColor.GRAY, "DEBUG", message); - } + public void severe(String message) { + log(MCColor.RED, "SEVERE", message); + } - // private - private void log(String level, String message) { - log(MCColor.WHITE, level, message); - } + public void debug(String message) { + if (debug) { + log(MCColor.GRAY, "DEBUG", message); + } + } - private void log(String levelColor, String level, String message) { - if (colorful) { - StringBuilder builder = new StringBuilder(); + private void log(String level, String message) { + log(MCColor.WHITE, level, message); + } - builder.append(MCColor.toANSI(MCColor.AQUA + "[" + consoleDate.format(calender.getTime()) + "] ")); - builder.append(MCColor.toANSI(levelColor + "[" + level + "] ")); - builder.append(MCColor.toANSI(message + MCColor.WHITE + MCColor.RESET)); + private void log(String levelColor, String level, String message) { + if (colorful) { + StringBuilder builder = new StringBuilder(); - System.out.println(builder.toString()); - } else { - StringBuilder builder = new StringBuilder(); + builder.append(MCColor.toANSI(MCColor.AQUA + "[" + consoleDate.format(calender.getTime()) + "] ")); + builder.append(MCColor.toANSI(levelColor + "[" + level + "] ")); + builder.append(MCColor.toANSI(message + MCColor.WHITE + MCColor.RESET)); - builder.append("[" + consoleDate.format(calender.getTime()) + "] "); - builder.append("[" + level + "] "); - builder.append(message); + System.out.println(builder.toString()); + } else { + StringBuilder builder = new StringBuilder(); - System.out.println(builder.toString()); - } - } + builder.append("[" + consoleDate.format(calender.getTime()) + "] "); + builder.append("[" + level + "] "); + builder.append(message); + + System.out.println(builder.toString()); + } + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/LoginChainDecoder.java b/src/main/java/org/dragonet/proxy/utilities/LoginChainDecoder.java index e7ee3e7ea..276e65861 100644 --- a/src/main/java/org/dragonet/proxy/utilities/LoginChainDecoder.java +++ b/src/main/java/org/dragonet/proxy/utilities/LoginChainDecoder.java @@ -15,7 +15,6 @@ * Created on 2017/9/12. */ public class LoginChainDecoder { - // vars private final byte[] chainJWT; private final byte[] clientDataJWT; @@ -25,13 +24,11 @@ public class LoginChainDecoder { public String language; public Skin skin; - // constructor public LoginChainDecoder(byte[] chainJWT, byte[] clientDataJWT) { this.chainJWT = chainJWT; this.clientDataJWT = clientDataJWT; } - // public /** * decode the chain data in Login packet for MCPE Note: the credit of this * function goes to Nukkit development team @@ -75,7 +72,6 @@ public void decode() { ); } - // private /** * Note: the credit of this function goes to Nukkit development team * diff --git a/src/main/java/org/dragonet/proxy/utilities/MCColor.java b/src/main/java/org/dragonet/proxy/utilities/MCColor.java index 988255352..9acf02bcc 100644 --- a/src/main/java/org/dragonet/proxy/utilities/MCColor.java +++ b/src/main/java/org/dragonet/proxy/utilities/MCColor.java @@ -13,67 +13,62 @@ package org.dragonet.proxy.utilities; public class MCColor { - // vars - public static final String ESCAPE = "§"; - public static final String BLACK = ESCAPE + "0"; - public static final String DARK_BLUE = ESCAPE + "1"; - public static final String DARK_GREEN = ESCAPE + "2"; - public static final String DARK_AQUA = ESCAPE + "3"; - public static final String DARK_RED = ESCAPE + "4"; - public static final String DARK_PURPLE = ESCAPE + "5"; - public static final String GOLD = ESCAPE + "6"; - public static final String GRAY = ESCAPE + "7"; - public static final String DARK_GRAY = ESCAPE + "8"; - public static final String BLUE = ESCAPE + "9"; - public static final String GREEN = ESCAPE + "a"; - public static final String AQUA = ESCAPE + "b"; - public static final String RED = ESCAPE + "c"; - public static final String LIGHT_PURPLE = ESCAPE + "d"; - public static final String YELLOW = ESCAPE + "e"; - public static final String WHITE = ESCAPE + "f"; - public static final String OBFUSCATED = ESCAPE + "k"; - public static final String BOLD = ESCAPE + "l"; - public static final String STRIKETHROUGH = ESCAPE + "m"; - public static final String UNDERLINE = ESCAPE + "n"; - public static final String ITALIC = ESCAPE + "o"; - public static final String RESET = ESCAPE + "r"; - // constructor - public MCColor() { + public static final String ESCAPE = "§"; + public static final String BLACK = ESCAPE + "0"; + public static final String DARK_BLUE = ESCAPE + "1"; + public static final String DARK_GREEN = ESCAPE + "2"; + public static final String DARK_AQUA = ESCAPE + "3"; + public static final String DARK_RED = ESCAPE + "4"; + public static final String DARK_PURPLE = ESCAPE + "5"; + public static final String GOLD = ESCAPE + "6"; + public static final String GRAY = ESCAPE + "7"; + public static final String DARK_GRAY = ESCAPE + "8"; + public static final String BLUE = ESCAPE + "9"; + public static final String GREEN = ESCAPE + "a"; + public static final String AQUA = ESCAPE + "b"; + public static final String RED = ESCAPE + "c"; + public static final String LIGHT_PURPLE = ESCAPE + "d"; + public static final String YELLOW = ESCAPE + "e"; + public static final String WHITE = ESCAPE + "f"; + public static final String OBFUSCATED = ESCAPE + "k"; + public static final String BOLD = ESCAPE + "l"; + public static final String STRIKETHROUGH = ESCAPE + "m"; + public static final String UNDERLINE = ESCAPE + "n"; + public static final String ITALIC = ESCAPE + "o"; + public static final String RESET = ESCAPE + "r"; - } + public MCColor() { - // public - public static String toANSI(String string) { - string = string.replace(BOLD, ""); - string = string.replace(OBFUSCATED, (char) 0x1b + "[8m"); - string = string.replace(ITALIC, (char) 0x1b + "[3m"); - string = string.replace(UNDERLINE, (char) 0x1b + "[4m"); - string = string.replace(STRIKETHROUGH, (char) 0x1b + "[9m"); - string = string.replace(RESET, (char) 0x1b + "[0m"); - string = string.replace(BLACK, (char) 0x1b + "[0;30m"); - string = string.replace(DARK_BLUE, (char) 0x1b + "[0;34m"); - string = string.replace(DARK_GREEN, (char) 0x1b + "[0;32m"); - string = string.replace(DARK_AQUA, (char) 0x1b + "[0;36m"); - string = string.replace(DARK_RED, (char) 0x1b + "[0;31m"); - string = string.replace(DARK_PURPLE, (char) 0x1b + "[0;35m"); - string = string.replace(GOLD, (char) 0x1b + "[0;33m"); - string = string.replace(GRAY, (char) 0x1b + "[0;37m"); - string = string.replace(DARK_GRAY, (char) 0x1b + "[30;1m"); - string = string.replace(BLUE, (char) 0x1b + "[34;1m"); - string = string.replace(GREEN, (char) 0x1b + "[32;1m"); - string = string.replace(AQUA, (char) 0x1b + "[36;1m"); - string = string.replace(RED, (char) 0x1b + "[31;1m"); - string = string.replace(LIGHT_PURPLE, (char) 0x1b + "[35;1m"); - string = string.replace(YELLOW, (char) 0x1b + "[33;1m"); - string = string.replace(WHITE, (char) 0x1b + "[37;1m"); - return string; - } + } - public static String clean(String message) { - return message = message.replaceAll((char) 0x1b + "[0-9;\\[\\(]+[Bm]", ""); - } + public static String toANSI(String string) { + string = string.replace(BOLD, ""); + string = string.replace(OBFUSCATED, (char) 0x1b + "[8m"); + string = string.replace(ITALIC, (char) 0x1b + "[3m"); + string = string.replace(UNDERLINE, (char) 0x1b + "[4m"); + string = string.replace(STRIKETHROUGH, (char) 0x1b + "[9m"); + string = string.replace(RESET, (char) 0x1b + "[0m"); + string = string.replace(BLACK, (char) 0x1b + "[0;30m"); + string = string.replace(DARK_BLUE, (char) 0x1b + "[0;34m"); + string = string.replace(DARK_GREEN, (char) 0x1b + "[0;32m"); + string = string.replace(DARK_AQUA, (char) 0x1b + "[0;36m"); + string = string.replace(DARK_RED, (char) 0x1b + "[0;31m"); + string = string.replace(DARK_PURPLE, (char) 0x1b + "[0;35m"); + string = string.replace(GOLD, (char) 0x1b + "[0;33m"); + string = string.replace(GRAY, (char) 0x1b + "[0;37m"); + string = string.replace(DARK_GRAY, (char) 0x1b + "[30;1m"); + string = string.replace(BLUE, (char) 0x1b + "[34;1m"); + string = string.replace(GREEN, (char) 0x1b + "[32;1m"); + string = string.replace(AQUA, (char) 0x1b + "[36;1m"); + string = string.replace(RED, (char) 0x1b + "[31;1m"); + string = string.replace(LIGHT_PURPLE, (char) 0x1b + "[35;1m"); + string = string.replace(YELLOW, (char) 0x1b + "[33;1m"); + string = string.replace(WHITE, (char) 0x1b + "[37;1m"); + return string; + } - // private - -} \ No newline at end of file + public static String clean(String message) { + return message = message.replaceAll((char) 0x1b + "[0-9;\\[\\(]+[Bm]", ""); + } +} diff --git a/src/main/java/org/dragonet/proxy/utilities/MCPESkin.java b/src/main/java/org/dragonet/proxy/utilities/MCPESkin.java index e0018b8a4..ecd477c67 100644 --- a/src/main/java/org/dragonet/proxy/utilities/MCPESkin.java +++ b/src/main/java/org/dragonet/proxy/utilities/MCPESkin.java @@ -10,7 +10,6 @@ * * @author The Dragonet Team */ - package org.dragonet.proxy.utilities; import javax.imageio.ImageIO; @@ -28,144 +27,139 @@ * author: MagicDroidX Nukkit Project */ public class MCPESkin { - // vars - public static final int SINGLE_SKIN_SIZE = 64 * 32 * 4; - public static final int DOUBLE_SKIN_SIZE = 64 * 64 * 4; - public static final String MODEL_STEVE = "Standard_Steve"; - public static final String MODEL_ALEX = "Standard_Alex"; - private byte[] data = new byte[SINGLE_SKIN_SIZE]; - private String model; - - // constructor - public MCPESkin(byte[] data) { - this(data, MODEL_STEVE); - } - - public MCPESkin(InputStream inputStream) { - this(inputStream, MODEL_STEVE); - } - - public MCPESkin(ImageInputStream inputStream) { - this(inputStream, MODEL_STEVE); - } - - public MCPESkin(File file) { - this(file, MODEL_STEVE); - } - - public MCPESkin(URL url) { - this(url, MODEL_STEVE); - } - - public MCPESkin(BufferedImage image) { - this(image, MODEL_STEVE); - } - - public MCPESkin(byte[] data, String model) { - this.setData(data); - this.setModel(model); - } - - public MCPESkin(InputStream inputStream, String model) { - BufferedImage image; - try { - image = ImageIO.read(inputStream); - } catch (IOException e) { - throw new RuntimeException(e); - } - this.parseBufferedImage(image); - this.setModel(model); - } - - public MCPESkin(ImageInputStream inputStream, String model) { - BufferedImage image; - try { - image = ImageIO.read(inputStream); - } catch (IOException e) { - throw new RuntimeException(e); - } - this.parseBufferedImage(image); - this.setModel(model); - } - - public MCPESkin(File file, String model) { - BufferedImage image; - try { - image = ImageIO.read(file); - } catch (IOException e) { - throw new RuntimeException(e); - } - this.parseBufferedImage(image); - this.setModel(model); - } - - public MCPESkin(URL url, String model) { - BufferedImage image; - try { - image = ImageIO.read(url); - } catch (IOException e) { - throw new RuntimeException(e); - } - this.parseBufferedImage(image); - this.setModel(model); - } - - public MCPESkin(BufferedImage image, String model) { - this.parseBufferedImage(image); - this.setModel(model); - } - - public MCPESkin(String base64) { - this(Base64.getDecoder().decode(base64)); - } - - public MCPESkin(String base64, String model) { - this(Base64.getDecoder().decode(base64), model); - } - - // public - public void parseBufferedImage(BufferedImage image) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - for (int y = 0; y < image.getHeight(); y++) { - for (int x = 0; x < image.getWidth(); x++) { - Color color = new Color(image.getRGB(x, y), true); - outputStream.write(color.getRed()); - outputStream.write(color.getGreen()); - outputStream.write(color.getBlue()); - outputStream.write(color.getAlpha()); - } - } - image.flush(); - this.setData(outputStream.toByteArray()); - } - - public byte[] getData() { - return data; - } - - public String getModel() { - return model; - } - - public void setData(byte[] data) { - if (data.length != SINGLE_SKIN_SIZE && data.length != DOUBLE_SKIN_SIZE) { - throw new IllegalArgumentException("Invalid skin"); - } - this.data = data; - } - - public void setModel(String model) { - if (model == null || model.trim().isEmpty()) { - model = MODEL_STEVE; - } - - this.model = model; - } - - public boolean isValid() { - return this.data.length == SINGLE_SKIN_SIZE || this.data.length == DOUBLE_SKIN_SIZE; - } - - // private - -} \ No newline at end of file + + public static final int SINGLE_SKIN_SIZE = 64 * 32 * 4; + public static final int DOUBLE_SKIN_SIZE = 64 * 64 * 4; + public static final String MODEL_STEVE = "Standard_Steve"; + public static final String MODEL_ALEX = "Standard_Alex"; + private byte[] data = new byte[SINGLE_SKIN_SIZE]; + private String model; + + public MCPESkin(byte[] data) { + this(data, MODEL_STEVE); + } + + public MCPESkin(InputStream inputStream) { + this(inputStream, MODEL_STEVE); + } + + public MCPESkin(ImageInputStream inputStream) { + this(inputStream, MODEL_STEVE); + } + + public MCPESkin(File file) { + this(file, MODEL_STEVE); + } + + public MCPESkin(URL url) { + this(url, MODEL_STEVE); + } + + public MCPESkin(BufferedImage image) { + this(image, MODEL_STEVE); + } + + public MCPESkin(byte[] data, String model) { + this.setData(data); + this.setModel(model); + } + + public MCPESkin(InputStream inputStream, String model) { + BufferedImage image; + try { + image = ImageIO.read(inputStream); + } catch (IOException e) { + throw new RuntimeException(e); + } + this.parseBufferedImage(image); + this.setModel(model); + } + + public MCPESkin(ImageInputStream inputStream, String model) { + BufferedImage image; + try { + image = ImageIO.read(inputStream); + } catch (IOException e) { + throw new RuntimeException(e); + } + this.parseBufferedImage(image); + this.setModel(model); + } + + public MCPESkin(File file, String model) { + BufferedImage image; + try { + image = ImageIO.read(file); + } catch (IOException e) { + throw new RuntimeException(e); + } + this.parseBufferedImage(image); + this.setModel(model); + } + + public MCPESkin(URL url, String model) { + BufferedImage image; + try { + image = ImageIO.read(url); + } catch (IOException e) { + throw new RuntimeException(e); + } + this.parseBufferedImage(image); + this.setModel(model); + } + + public MCPESkin(BufferedImage image, String model) { + this.parseBufferedImage(image); + this.setModel(model); + } + + public MCPESkin(String base64) { + this(Base64.getDecoder().decode(base64)); + } + + public MCPESkin(String base64, String model) { + this(Base64.getDecoder().decode(base64), model); + } + + public void parseBufferedImage(BufferedImage image) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + for (int y = 0; y < image.getHeight(); y++) { + for (int x = 0; x < image.getWidth(); x++) { + Color color = new Color(image.getRGB(x, y), true); + outputStream.write(color.getRed()); + outputStream.write(color.getGreen()); + outputStream.write(color.getBlue()); + outputStream.write(color.getAlpha()); + } + } + image.flush(); + this.setData(outputStream.toByteArray()); + } + + public byte[] getData() { + return data; + } + + public String getModel() { + return model; + } + + public void setData(byte[] data) { + if (data.length != SINGLE_SKIN_SIZE && data.length != DOUBLE_SKIN_SIZE) { + throw new IllegalArgumentException("Invalid skin"); + } + this.data = data; + } + + public void setModel(String model) { + if (model == null || model.trim().isEmpty()) { + model = MODEL_STEVE; + } + + this.model = model; + } + + public boolean isValid() { + return this.data.length == SINGLE_SKIN_SIZE || this.data.length == DOUBLE_SKIN_SIZE; + } +} diff --git a/src/main/java/org/dragonet/proxy/utilities/NukkitMath.java b/src/main/java/org/dragonet/proxy/utilities/NukkitMath.java index 4f6876c32..69757890a 100644 --- a/src/main/java/org/dragonet/proxy/utilities/NukkitMath.java +++ b/src/main/java/org/dragonet/proxy/utilities/NukkitMath.java @@ -4,70 +4,64 @@ * author: MagicDroidX Nukkit Project */ public class NukkitMath { - // vars - // constructor - public NukkitMath() { + public NukkitMath() { - } + } - // public - public static int floorDouble(double n) { - int i = (int) n; - return n >= i ? i : i - 1; - } + public static int floorDouble(double n) { + int i = (int) n; + return n >= i ? i : i - 1; + } - public static int ceilDouble(double n) { - int i = (int) (n + 1); - return n >= i ? i : i - 1; - } + public static int ceilDouble(double n) { + int i = (int) (n + 1); + return n >= i ? i : i - 1; + } - public static int floorFloat(float n) { - int i = (int) n; - return n >= i ? i : i - 1; - } + public static int floorFloat(float n) { + int i = (int) n; + return n >= i ? i : i - 1; + } - public static int ceilFloat(float n) { - int i = (int) (n + 1); - return n >= i ? i : i - 1; - } + public static int ceilFloat(float n) { + int i = (int) (n + 1); + return n >= i ? i : i - 1; + } - public static int randomRange(NukkitRandom random) { - return randomRange(random, 0); - } + public static int randomRange(NukkitRandom random) { + return randomRange(random, 0); + } - public static int randomRange(NukkitRandom random, int start) { - return randomRange(random, 0, 0x7fffffff); - } + public static int randomRange(NukkitRandom random, int start) { + return randomRange(random, 0, 0x7fffffff); + } - public static int randomRange(NukkitRandom random, int start, int end) { - return start + (random.nextInt() % (end + 1 - start)); - } + public static int randomRange(NukkitRandom random, int start, int end) { + return start + (random.nextInt() % (end + 1 - start)); + } - public static double round(double d) { - return round(d, 0); - } + public static double round(double d) { + return round(d, 0); + } - public static double round(double d, int precision) { - return ((double) Math.round(d * Math.pow(10, precision))) / Math.pow(10, precision); - } + public static double round(double d, int precision) { + return ((double) Math.round(d * Math.pow(10, precision))) / Math.pow(10, precision); + } - public static double clamp(double check, double min, double max) { - return check > max ? max : (check < min ? min : check); - } + public static double clamp(double check, double min, double max) { + return check > max ? max : (check < min ? min : check); + } - public static double getDirection(double d0, double d1) { - if (d0 < 0.0D) { - d0 = -d0; - } + public static double getDirection(double d0, double d1) { + if (d0 < 0.0D) { + d0 = -d0; + } - if (d1 < 0.0D) { - d1 = -d1; - } - - return d0 > d1 ? d0 : d1; - } - - // private + if (d1 < 0.0D) { + d1 = -d1; + } + return d0 > d1 ? d0 : d1; + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/NukkitRandom.java b/src/main/java/org/dragonet/proxy/utilities/NukkitRandom.java index 61d9a34d1..a2f010e40 100644 --- a/src/main/java/org/dragonet/proxy/utilities/NukkitRandom.java +++ b/src/main/java/org/dragonet/proxy/utilities/NukkitRandom.java @@ -8,76 +8,72 @@ * author: Angelic47 Nukkit Project */ public class NukkitRandom { - // vars - protected long seed; - - // constructor - public NukkitRandom() { - this(-1); - } - - public NukkitRandom(long seeds) { - if (seeds == -1) { - seeds = System.currentTimeMillis() / 1000L; - } - this.setSeed(seeds); - } - - // public - public void setSeed(long seeds) { - CRC32 crc32 = new CRC32(); - ByteBuffer buffer = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN); - buffer.putInt((int) seeds); - crc32.update(buffer.array()); - this.seed = crc32.getValue(); - } - - public int nextSignedInt() { - int t = (((int) ((this.seed * 65535) + 31337) >> 8) + 1337); - this.seed ^= t; - return t; - } - - public int nextInt() { - return this.nextSignedInt() & 0x7fffffff; - } - - public double nextDouble() { - return (double) this.nextInt() / 0x7fffffff; - } - - public float nextFloat() { - return (float) this.nextInt() / 0x7fffffff; - } - - public float nextSignedFloat() { - return (float) this.nextInt() / 0x7fffffff; - } - - public double nextSignedDouble() { - return (double) this.nextSignedInt() / 0x7fffffff; - } - - public boolean nextBoolean() { - return (this.nextSignedInt() & 0x01) == 0; - } - - public int nextRange() { - return nextRange(0, 0x7fffffff); - } - - public int nextRange(int start) { - return nextRange(start, 0x7fffffff); - } - - public int nextRange(int start, int end) { - return start + (this.nextInt() % (end + 1 - start)); - } - - public int nextBoundedInt(int bound) { - return this.nextInt() % bound; - } - - // private + protected long seed; + + // constructor + public NukkitRandom() { + this(-1); + } + + public NukkitRandom(long seeds) { + if (seeds == -1) { + seeds = System.currentTimeMillis() / 1000L; + } + this.setSeed(seeds); + } + + public void setSeed(long seeds) { + CRC32 crc32 = new CRC32(); + ByteBuffer buffer = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN); + buffer.putInt((int) seeds); + crc32.update(buffer.array()); + this.seed = crc32.getValue(); + } + + public int nextSignedInt() { + int t = (((int) ((this.seed * 65535) + 31337) >> 8) + 1337); + this.seed ^= t; + return t; + } + + public int nextInt() { + return this.nextSignedInt() & 0x7fffffff; + } + + public double nextDouble() { + return (double) this.nextInt() / 0x7fffffff; + } + + public float nextFloat() { + return (float) this.nextInt() / 0x7fffffff; + } + + public float nextSignedFloat() { + return (float) this.nextInt() / 0x7fffffff; + } + + public double nextSignedDouble() { + return (double) this.nextSignedInt() / 0x7fffffff; + } + + public boolean nextBoolean() { + return (this.nextSignedInt() & 0x01) == 0; + } + + public int nextRange() { + return nextRange(0, 0x7fffffff); + } + + public int nextRange(int start) { + return nextRange(start, 0x7fffffff); + } + + public int nextRange(int start, int end) { + return start + (this.nextInt() % (end + 1 - start)); + } + + public int nextBoundedInt(int bound) { + return this.nextInt() % bound; + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/NumberConversions.java b/src/main/java/org/dragonet/proxy/utilities/NumberConversions.java index c4fc66ae3..cd5fe2ccd 100644 --- a/src/main/java/org/dragonet/proxy/utilities/NumberConversions.java +++ b/src/main/java/org/dragonet/proxy/utilities/NumberConversions.java @@ -4,130 +4,124 @@ * Utils for casting number type to other number type */ public final class NumberConversions { - // vars - - // constructor - private NumberConversions() { - - } - - // public - public static int floor(double num) { - final int floor = (int) num; - return floor == num ? floor : floor - (int) (Double.doubleToRawLongBits(num) >>> 63); - } - - public static int ceil(final double num) { - final int floor = (int) num; - return floor == num ? floor : floor + (int) (~Double.doubleToRawLongBits(num) >>> 63); - } - - public static int round(double num) { - return floor(num + 0.5d); - } - - public static double square(double num) { - return num * num; - } - - public static int toInt(Object object) { - if (object instanceof Number) { - return ((Number) object).intValue(); - } - - try { - return Integer.valueOf(object.toString()); - } catch (NumberFormatException e) { - } catch (NullPointerException e) { - } - return 0; - } - - public static float toFloat(Object object) { - if (object instanceof Number) { - return ((Number) object).floatValue(); - } - - try { - return Float.valueOf(object.toString()); - } catch (NumberFormatException e) { - } catch (NullPointerException e) { - } - return 0; - } - - public static double toDouble(Object object) { - if (object instanceof Number) { - return ((Number) object).doubleValue(); - } - - try { - return Double.valueOf(object.toString()); - } catch (NumberFormatException e) { - } catch (NullPointerException e) { - } - return 0; - } - - public static long toLong(Object object) { - if (object instanceof Number) { - return ((Number) object).longValue(); - } - - try { - return Long.valueOf(object.toString()); - } catch (NumberFormatException e) { - } catch (NullPointerException e) { - } - return 0; - } - - public static short toShort(Object object) { - if (object instanceof Number) { - return ((Number) object).shortValue(); - } - - try { - return Short.valueOf(object.toString()); - } catch (NumberFormatException e) { - } catch (NullPointerException e) { - } - return 0; - } - - public static byte toByte(Object object) { - if (object instanceof Number) { - return ((Number) object).byteValue(); - } - - try { - return Byte.valueOf(object.toString()); - } catch (NumberFormatException e) { - } catch (NullPointerException e) { - } - return 0; - } - - public static boolean isFinite(double d) { - return Math.abs(d) <= Double.MAX_VALUE; - } - - public static boolean isFinite(float f) { - return Math.abs(f) <= Float.MAX_VALUE; - } - - public static void checkFinite(double d, String message) { - if (!isFinite(d)) { - throw new IllegalArgumentException(message); - } - } - - public static void checkFinite(float d, String message) { - if (!isFinite(d)) { - throw new IllegalArgumentException(message); - } - } - - // private + private NumberConversions() { + + } + + public static int floor(double num) { + final int floor = (int) num; + return floor == num ? floor : floor - (int) (Double.doubleToRawLongBits(num) >>> 63); + } + + public static int ceil(final double num) { + final int floor = (int) num; + return floor == num ? floor : floor + (int) (~Double.doubleToRawLongBits(num) >>> 63); + } + + public static int round(double num) { + return floor(num + 0.5d); + } + + public static double square(double num) { + return num * num; + } + + public static int toInt(Object object) { + if (object instanceof Number) { + return ((Number) object).intValue(); + } + + try { + return Integer.valueOf(object.toString()); + } catch (NumberFormatException e) { + } catch (NullPointerException e) { + } + return 0; + } + + public static float toFloat(Object object) { + if (object instanceof Number) { + return ((Number) object).floatValue(); + } + + try { + return Float.valueOf(object.toString()); + } catch (NumberFormatException e) { + } catch (NullPointerException e) { + } + return 0; + } + + public static double toDouble(Object object) { + if (object instanceof Number) { + return ((Number) object).doubleValue(); + } + + try { + return Double.valueOf(object.toString()); + } catch (NumberFormatException e) { + } catch (NullPointerException e) { + } + return 0; + } + + public static long toLong(Object object) { + if (object instanceof Number) { + return ((Number) object).longValue(); + } + + try { + return Long.valueOf(object.toString()); + } catch (NumberFormatException e) { + } catch (NullPointerException e) { + } + return 0; + } + + public static short toShort(Object object) { + if (object instanceof Number) { + return ((Number) object).shortValue(); + } + + try { + return Short.valueOf(object.toString()); + } catch (NumberFormatException e) { + } catch (NullPointerException e) { + } + return 0; + } + + public static byte toByte(Object object) { + if (object instanceof Number) { + return ((Number) object).byteValue(); + } + + try { + return Byte.valueOf(object.toString()); + } catch (NumberFormatException e) { + } catch (NullPointerException e) { + } + return 0; + } + + public static boolean isFinite(double d) { + return Math.abs(d) <= Double.MAX_VALUE; + } + + public static boolean isFinite(float f) { + return Math.abs(f) <= Float.MAX_VALUE; + } + + public static void checkFinite(double d, String message) { + if (!isFinite(d)) { + throw new IllegalArgumentException(message); + } + } + + public static void checkFinite(float d, String message) { + if (!isFinite(d)) { + throw new IllegalArgumentException(message); + } + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/PatternChecker.java b/src/main/java/org/dragonet/proxy/utilities/PatternChecker.java index 04e17aeee..af7a35b22 100644 --- a/src/main/java/org/dragonet/proxy/utilities/PatternChecker.java +++ b/src/main/java/org/dragonet/proxy/utilities/PatternChecker.java @@ -16,25 +16,20 @@ import java.util.regex.Pattern; public final class PatternChecker { - /* - * TODO "Beware the regex e-mail validation, for this way lies madness." -egg82 - */ - - // vars - public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; - public static final Pattern PATTERN_EMAIL = Pattern.compile(REGEX_EMAIL); - // constructor - public PatternChecker() { + /* + * TODO "Beware the regex e-mail validation, for this way lies madness." -egg82 + */ - } + public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; + public static final Pattern PATTERN_EMAIL = Pattern.compile(REGEX_EMAIL); - // public - public static boolean matchEmail(String email) { - Matcher matcher = PATTERN_EMAIL.matcher(email); - return matcher.matches(); - } + public PatternChecker() { - // private + } + public static boolean matchEmail(String email) { + Matcher matcher = PATTERN_EMAIL.matcher(email); + return matcher.matches(); + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/Terminal.java b/src/main/java/org/dragonet/proxy/utilities/Terminal.java index 4ce83bc06..58f60450d 100644 --- a/src/main/java/org/dragonet/proxy/utilities/Terminal.java +++ b/src/main/java/org/dragonet/proxy/utilities/Terminal.java @@ -1,27 +1,20 @@ - package org.dragonet.proxy.utilities; @Deprecated public class Terminal { - // vars - public static final String ITALIC = "\u001B[3m"; - public static final String UNDERLINE = "\u001B[4m"; - public static final String BLACK = "\u001B[30m"; - public static final String RED = "\u001B[31m"; - public static final String GREEN = "\u001B[32m"; - public static final String YELLOW = "\u001B[33m"; - public static final String BLUE = "\u001B[34m"; - public static final String MAGENTA = "\u001B[35m"; - public static final String CYAN = "\u001B[36m"; - public static final String WHITE = "\u001B[37m"; - - // constructor - public Terminal() { - - } - // public + public static final String ITALIC = "\u001B[3m"; + public static final String UNDERLINE = "\u001B[4m"; + public static final String BLACK = "\u001B[30m"; + public static final String RED = "\u001B[31m"; + public static final String GREEN = "\u001B[32m"; + public static final String YELLOW = "\u001B[33m"; + public static final String BLUE = "\u001B[34m"; + public static final String MAGENTA = "\u001B[35m"; + public static final String CYAN = "\u001B[36m"; + public static final String WHITE = "\u001B[37m"; - // private + public Terminal() { -} \ No newline at end of file + } +} diff --git a/src/main/java/org/dragonet/proxy/utilities/VarInt.java b/src/main/java/org/dragonet/proxy/utilities/VarInt.java index a621db069..7d9d9e008 100644 --- a/src/main/java/org/dragonet/proxy/utilities/VarInt.java +++ b/src/main/java/org/dragonet/proxy/utilities/VarInt.java @@ -13,255 +13,223 @@ * @author lmlstarqaq */ public final class VarInt { - // vars - // constructor - private VarInt() { - // no instance - } - - // public - /** - * @param v - * Signed int - * @return Unsigned encoded int - */ - public static long encodeZigZag32(int v) { - // Note: the right-shift must be arithmetic - return (long) ((v << 1) ^ (v >> 31)); - } - - /** - * @param v - * Unsigned encoded int - * @return Signed decoded int - */ - public static int decodeZigZag32(long v) { - return (int) (v >> 1) ^ -(int) (v & 1); - } - - /** - * @param v - * Signed long - * @return Unsigned encoded long - */ - public static long encodeZigZag64(long v) { - return (v << 1) ^ (v >> 63); - } - - /** - * @param v - * Signed encoded long - * @return Unsigned decoded long - */ - public static long decodeZigZag64(long v) { - return (v >>> 1) ^ -(v & 1); - } - - /** - * @param stream - * BinaryStream - * @return Signed int - */ - public static int readVarInt(BinaryStream stream) { - return decodeZigZag32(readUnsignedVarInt(stream)); - } - - /** - * @param stream - * InputStream - * @return Signed int - */ - public static int readVarInt(InputStream stream) throws IOException { - return decodeZigZag32(readUnsignedVarInt(stream)); - } - - /** - * @param stream - * BinaryStream - * @return Unsigned int - */ - public static long readUnsignedVarInt(BinaryStream stream) { - return read(stream, 5); - } - - /** - * @param stream - * InputStream - * @return Unsigned int - */ - public static long readUnsignedVarInt(InputStream stream) throws IOException { - return read(stream, 5); - } - - /** - * @param stream - * BinaryStream - * @return Signed long - */ - public static long readVarLong(BinaryStream stream) { - return decodeZigZag64(readUnsignedVarLong(stream)); - } - - /** - * @param stream - * InputStream - * @return Signed long - */ - public static long readVarLong(InputStream stream) throws IOException { - return decodeZigZag64(readUnsignedVarLong(stream)); - } - - /** - * @param stream - * BinaryStream - * @return Unsigned long - */ - public static long readUnsignedVarLong(BinaryStream stream) { - return read(stream, 10); - } - - /** - * @param stream - * InputStream - * @return Unsigned long - */ - public static long readUnsignedVarLong(InputStream stream) throws IOException { - return read(stream, 10); - } - - /** - * @param stream - * BinaryStream - * @param value - * Signed int - */ - public static void writeVarInt(BinaryStream stream, int value) { - writeUnsignedVarInt(stream, encodeZigZag32(value)); - } - - /** - * @param stream - * OutputStream - * @param value - * Signed int - */ - public static void writeVarInt(OutputStream stream, int value) throws IOException { - writeUnsignedVarInt(stream, encodeZigZag32(value)); - } - - /** - * @param stream - * BinaryStream - * @param value - * Unsigned int - */ - public static void writeUnsignedVarInt(BinaryStream stream, long value) { - write(stream, value); - } - - /** - * @param stream - * OutputStream - * @param value - * Unsigned int - */ - public static void writeUnsignedVarInt(OutputStream stream, long value) throws IOException { - write(stream, value); - } - - /** - * @param stream - * BinaryStream - * @param value - * Signed long - */ - public static void writeVarLong(BinaryStream stream, long value) { - writeUnsignedVarLong(stream, encodeZigZag64(value)); - } - - /** - * @param stream - * OutputStream - * @param value - * Signed long - */ - public static void writeVarLong(OutputStream stream, long value) throws IOException { - writeUnsignedVarLong(stream, encodeZigZag64(value)); - } - - /** - * @param stream - * BinaryStream - * @param value - * Unsigned long - */ - public static void writeUnsignedVarLong(BinaryStream stream, long value) { - write(stream, value); - } - - /** - * @param stream - * OutputStream - * @param value - * Unsigned long - */ - public static void writeUnsignedVarLong(OutputStream stream, long value) throws IOException { - write(stream, value); - } - - // private - private static long read(BinaryStream stream, int maxSize) { - long value = 0; - int size = 0; - int b; - while (((b = stream.getByte()) & 0x80) == 0x80) { - value |= (long) (b & 0x7F) << (size++ * 7); - if (size >= maxSize) { - throw new IllegalArgumentException("VarLong too big"); - } - } - - return value | ((long) (b & 0x7F) << (size * 7)); - } - - private static long read(InputStream stream, int maxSize) throws IOException { - long value = 0; - int size = 0; - int b; - while (((b = stream.read()) & 0x80) == 0x80) { - value |= (long) (b & 0x7F) << (size++ * 7); - if (size >= maxSize) { - throw new IllegalArgumentException("VarLong too big"); - } - } - - return value | ((long) (b & 0x7F) << (size * 7)); - } - - private static void write(BinaryStream stream, long value) { - do { - byte temp = (byte) (value & 0b01111111); - // Note: >>> means that the sign bit is shifted with the rest of the number - // rather than being left alone - value >>>= 7; - if (value != 0) { - temp |= 0b10000000; - } - stream.putByte(temp); - } while (value != 0); - } - - private static void write(OutputStream stream, long value) throws IOException { - do { - byte temp = (byte) (value & 0b01111111); - // Note: >>> means that the sign bit is shifted with the rest of the number - // rather than being left alone - value >>>= 7; - if (value != 0) { - temp |= 0b10000000; - } - stream.write(temp); - } while (value != 0); - } -} \ No newline at end of file + private VarInt() { + // no instance + } + + /** + * @param v Signed int + * @return Unsigned encoded int + */ + public static long encodeZigZag32(int v) { + // Note: the right-shift must be arithmetic + return (long) ((v << 1) ^ (v >> 31)); + } + + /** + * @param v Unsigned encoded int + * @return Signed decoded int + */ + public static int decodeZigZag32(long v) { + return (int) (v >> 1) ^ -(int) (v & 1); + } + + /** + * @param v Signed long + * @return Unsigned encoded long + */ + public static long encodeZigZag64(long v) { + return (v << 1) ^ (v >> 63); + } + + /** + * @param v Signed encoded long + * @return Unsigned decoded long + */ + public static long decodeZigZag64(long v) { + return (v >>> 1) ^ -(v & 1); + } + + /** + * @param stream BinaryStream + * @return Signed int + */ + public static int readVarInt(BinaryStream stream) { + return decodeZigZag32(readUnsignedVarInt(stream)); + } + + /** + * @param stream InputStream + * @return Signed int + */ + public static int readVarInt(InputStream stream) throws IOException { + return decodeZigZag32(readUnsignedVarInt(stream)); + } + + /** + * @param stream BinaryStream + * @return Unsigned int + */ + public static long readUnsignedVarInt(BinaryStream stream) { + return read(stream, 5); + } + + /** + * @param stream InputStream + * @return Unsigned int + */ + public static long readUnsignedVarInt(InputStream stream) throws IOException { + return read(stream, 5); + } + + /** + * @param stream BinaryStream + * @return Signed long + */ + public static long readVarLong(BinaryStream stream) { + return decodeZigZag64(readUnsignedVarLong(stream)); + } + + /** + * @param stream InputStream + * @return Signed long + */ + public static long readVarLong(InputStream stream) throws IOException { + return decodeZigZag64(readUnsignedVarLong(stream)); + } + + /** + * @param stream BinaryStream + * @return Unsigned long + */ + public static long readUnsignedVarLong(BinaryStream stream) { + return read(stream, 10); + } + + /** + * @param stream InputStream + * @return Unsigned long + */ + public static long readUnsignedVarLong(InputStream stream) throws IOException { + return read(stream, 10); + } + + /** + * @param stream BinaryStream + * @param value Signed int + */ + public static void writeVarInt(BinaryStream stream, int value) { + writeUnsignedVarInt(stream, encodeZigZag32(value)); + } + + /** + * @param stream OutputStream + * @param value Signed int + */ + public static void writeVarInt(OutputStream stream, int value) throws IOException { + writeUnsignedVarInt(stream, encodeZigZag32(value)); + } + + /** + * @param stream BinaryStream + * @param value Unsigned int + */ + public static void writeUnsignedVarInt(BinaryStream stream, long value) { + write(stream, value); + } + + /** + * @param stream OutputStream + * @param value Unsigned int + */ + public static void writeUnsignedVarInt(OutputStream stream, long value) throws IOException { + write(stream, value); + } + + /** + * @param stream BinaryStream + * @param value Signed long + */ + public static void writeVarLong(BinaryStream stream, long value) { + writeUnsignedVarLong(stream, encodeZigZag64(value)); + } + + /** + * @param stream OutputStream + * @param value Signed long + */ + public static void writeVarLong(OutputStream stream, long value) throws IOException { + writeUnsignedVarLong(stream, encodeZigZag64(value)); + } + + /** + * @param stream BinaryStream + * @param value Unsigned long + */ + public static void writeUnsignedVarLong(BinaryStream stream, long value) { + write(stream, value); + } + + /** + * @param stream OutputStream + * @param value Unsigned long + */ + public static void writeUnsignedVarLong(OutputStream stream, long value) throws IOException { + write(stream, value); + } + + private static long read(BinaryStream stream, int maxSize) { + long value = 0; + int size = 0; + int b; + while (((b = stream.getByte()) & 0x80) == 0x80) { + value |= (long) (b & 0x7F) << (size++ * 7); + if (size >= maxSize) { + throw new IllegalArgumentException("VarLong too big"); + } + } + + return value | ((long) (b & 0x7F) << (size * 7)); + } + + private static long read(InputStream stream, int maxSize) throws IOException { + long value = 0; + int size = 0; + int b; + while (((b = stream.read()) & 0x80) == 0x80) { + value |= (long) (b & 0x7F) << (size++ * 7); + if (size >= maxSize) { + throw new IllegalArgumentException("VarLong too big"); + } + } + + return value | ((long) (b & 0x7F) << (size * 7)); + } + + private static void write(BinaryStream stream, long value) { + do { + byte temp = (byte) (value & 0b01111111); + // Note: >>> means that the sign bit is shifted with the rest of the number + // rather than being left alone + value >>>= 7; + if (value != 0) { + temp |= 0b10000000; + } + stream.putByte(temp); + } while (value != 0); + } + + private static void write(OutputStream stream, long value) throws IOException { + do { + byte temp = (byte) (value & 0b01111111); + // Note: >>> means that the sign bit is shifted with the rest of the number + // rather than being left alone + value >>>= 7; + if (value != 0) { + temp |= 0b10000000; + } + stream.write(temp); + } while (value != 0); + } +} diff --git a/src/main/java/org/dragonet/proxy/utilities/Vector3F.java b/src/main/java/org/dragonet/proxy/utilities/Vector3F.java index b02c4c663..29ab3b1bd 100644 --- a/src/main/java/org/dragonet/proxy/utilities/Vector3F.java +++ b/src/main/java/org/dragonet/proxy/utilities/Vector3F.java @@ -5,29 +5,23 @@ */ public class Vector3F { - public final static Vector3F ZERO = new Vector3F(0f, 0f, 0f); + public final static Vector3F ZERO = new Vector3F(0f, 0f, 0f); - // vars - public float x; - public float y; - public float z; + public float x; + public float y; + public float z; - // constructor - public Vector3F() { + public Vector3F() { - } + } - public Vector3F(float x, float y, float z) { - this.x = x; - this.y = y; - this.z = z; - } - - // public - public String toString() { - return String.format("Vector3F (%.2f, %.2f, %.2f)", x, y, z); - } - - // private + public Vector3F(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + public String toString() { + return String.format("Vector3F (%.2f, %.2f, %.2f)", x, y, z); + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/Versioning.java b/src/main/java/org/dragonet/proxy/utilities/Versioning.java index 261186c20..1b1d05c60 100644 --- a/src/main/java/org/dragonet/proxy/utilities/Versioning.java +++ b/src/main/java/org/dragonet/proxy/utilities/Versioning.java @@ -15,21 +15,16 @@ import org.dragonet.proxy.protocol.ProtocolInfo; public class Versioning { - // vars - public static final String RELEASE_VERSION = "0.3.1"; - public static final String MINECRAFT_PC_VERSION = "1.12.2"; - // public static final int MINECRAFT_PC_PROTOCOL = 47; - // This is STRICT to MCPE binary's definition, DO NOT CHANGE - public static final String MINECRAFT_PE_VERSION = ProtocolInfo.MINECRAFT_VERSION; - public static final int MINECRAFT_PE_PROTOCOL = ProtocolInfo.CURRENT_PROTOCOL; - // constructor - public Versioning() { + public static final String RELEASE_VERSION = "0.3.1"; + public static final String MINECRAFT_PC_VERSION = "1.12.2"; + // public static final int MINECRAFT_PC_PROTOCOL = 47; + // This is STRICT to MCPE binary's definition, DO NOT CHANGE + public static final String MINECRAFT_PE_VERSION = ProtocolInfo.MINECRAFT_VERSION; + public static final int MINECRAFT_PE_PROTOCOL = ProtocolInfo.CURRENT_PROTOCOL; - } + public Versioning() { - // public - - // private + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/Zlib.java b/src/main/java/org/dragonet/proxy/utilities/Zlib.java index 4083282da..4729e307a 100644 --- a/src/main/java/org/dragonet/proxy/utilities/Zlib.java +++ b/src/main/java/org/dragonet/proxy/utilities/Zlib.java @@ -8,64 +8,58 @@ import java.util.zip.InflaterInputStream; public abstract class Zlib { - // vars - // constructor - public Zlib() { + public Zlib() { - } + } - // public - public static byte[] deflate(byte[] data) throws Exception { - return deflate(data, Deflater.DEFAULT_COMPRESSION); - } + public static byte[] deflate(byte[] data) throws Exception { + return deflate(data, Deflater.DEFAULT_COMPRESSION); + } - public static byte[] deflate(byte[] data, int level) throws Exception { - Deflater deflater = new Deflater(level); - deflater.reset(); - deflater.setInput(data); - deflater.finish(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length); - byte[] buf = new byte[1024]; - try { - while (!deflater.finished()) { - int i = deflater.deflate(buf); - bos.write(buf, 0, i); - } - } finally { - deflater.end(); - } - return bos.toByteArray(); - } + public static byte[] deflate(byte[] data, int level) throws Exception { + Deflater deflater = new Deflater(level); + deflater.reset(); + deflater.setInput(data); + deflater.finish(); + ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length); + byte[] buf = new byte[1024]; + try { + while (!deflater.finished()) { + int i = deflater.deflate(buf); + bos.write(buf, 0, i); + } + } finally { + deflater.end(); + } + return bos.toByteArray(); + } - public static byte[] inflate(InputStream stream) throws IOException { - InflaterInputStream inputStream = new InflaterInputStream(stream); - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - int length; + public static byte[] inflate(InputStream stream) throws IOException { + InflaterInputStream inputStream = new InflaterInputStream(stream); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int length; - try { - while ((length = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, length); - } - } finally { - buffer = outputStream.toByteArray(); - outputStream.flush(); - outputStream.close(); - inputStream.close(); - } + try { + while ((length = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, length); + } + } finally { + buffer = outputStream.toByteArray(); + outputStream.flush(); + outputStream.close(); + inputStream.close(); + } - return buffer; - } + return buffer; + } - public static byte[] inflate(byte[] data) throws IOException { - return inflate(new ByteArrayInputStream(data)); - } - - public static byte[] inflate(byte[] data, int maxSize) throws IOException { - return inflate(new ByteArrayInputStream(data, 0, maxSize)); - } - - // private + public static byte[] inflate(byte[] data) throws IOException { + return inflate(new ByteArrayInputStream(data)); + } + public static byte[] inflate(byte[] data, int maxSize) throws IOException { + return inflate(new ByteArrayInputStream(data, 0, maxSize)); + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/io/ArraySplitter.java b/src/main/java/org/dragonet/proxy/utilities/io/ArraySplitter.java index 404a5d082..dd4c518c5 100644 --- a/src/main/java/org/dragonet/proxy/utilities/io/ArraySplitter.java +++ b/src/main/java/org/dragonet/proxy/utilities/io/ArraySplitter.java @@ -15,37 +15,31 @@ import java.util.Arrays; public final class ArraySplitter { - // vars - // constructor - public ArraySplitter() { + public ArraySplitter() { - } - - // public - public static byte[][] splitArray(byte[] array, int singleSlice) { - if (array.length <= singleSlice) { - byte[][] singleRet = new byte[1][]; - singleRet[0] = array; - return singleRet; - } - byte[][] ret = new byte[(array.length / singleSlice + (array.length % singleSlice == 0 ? 0 : 1))][]; - int pos = 0; - int slice = 0; - while (slice < ret.length) { - if (pos + singleSlice < array.length) { - ret[slice] = Arrays.copyOfRange(array, pos, pos + singleSlice); - pos += singleSlice; - slice++; - } else { - ret[slice] = Arrays.copyOfRange(array, pos, array.length); - pos += array.length - pos; - slice++; - } - } - return ret; - } - - // private + } + public static byte[][] splitArray(byte[] array, int singleSlice) { + if (array.length <= singleSlice) { + byte[][] singleRet = new byte[1][]; + singleRet[0] = array; + return singleRet; + } + byte[][] ret = new byte[(array.length / singleSlice + (array.length % singleSlice == 0 ? 0 : 1))][]; + int pos = 0; + int slice = 0; + while (slice < ret.length) { + if (pos + singleSlice < array.length) { + ret[slice] = Arrays.copyOfRange(array, pos, pos + singleSlice); + pos += singleSlice; + slice++; + } else { + ret[slice] = Arrays.copyOfRange(array, pos, array.length); + pos += array.length - pos; + slice++; + } + } + return ret; + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/io/ByteUtility.java b/src/main/java/org/dragonet/proxy/utilities/io/ByteUtility.java index e9ffaeacb..787ddebcc 100644 --- a/src/main/java/org/dragonet/proxy/utilities/io/ByteUtility.java +++ b/src/main/java/org/dragonet/proxy/utilities/io/ByteUtility.java @@ -13,27 +13,21 @@ package org.dragonet.proxy.utilities.io; public class ByteUtility { - // vars - // constructor - public ByteUtility() { + public ByteUtility() { - } - - // public - public static String bytesToHexString(byte[] data) { - StringBuilder sb = new StringBuilder(); - String sTemp; - for (int i = 0; i < data.length; i++) { - sTemp = Integer.toHexString(0xFF & data[i]); - if (sTemp.length() < 2) { - sb.append(0); - } - sb.append(sTemp.toUpperCase()).append(", "); - } - return sb.toString(); - } - - // private + } + public static String bytesToHexString(byte[] data) { + StringBuilder sb = new StringBuilder(); + String sTemp; + for (int i = 0; i < data.length; i++) { + sTemp = Integer.toHexString(0xFF & data[i]); + if (sTemp.length() < 2) { + sb.append(0); + } + sb.append(sTemp.toUpperCase()).append(", "); + } + return sb.toString(); + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/io/DataIOPair.java b/src/main/java/org/dragonet/proxy/utilities/io/DataIOPair.java index acd786027..49746fd41 100644 --- a/src/main/java/org/dragonet/proxy/utilities/io/DataIOPair.java +++ b/src/main/java/org/dragonet/proxy/utilities/io/DataIOPair.java @@ -16,25 +16,20 @@ import java.io.DataOutputStream; public class DataIOPair { - // vars - DataInputStream input; - DataOutputStream output; - // constructor - public DataIOPair(DataInputStream input, DataOutputStream output) { - this.input = input; - this.output = output; - } + DataInputStream input; + DataOutputStream output; - // public - public DataInputStream getInput() { - return input; - } + public DataIOPair(DataInputStream input, DataOutputStream output) { + this.input = input; + this.output = output; + } - public DataOutputStream getOutput() { - return output; - } - - // private + public DataInputStream getInput() { + return input; + } + public DataOutputStream getOutput() { + return output; + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/io/PEBinaryReader.java b/src/main/java/org/dragonet/proxy/utilities/io/PEBinaryReader.java index 0c53404d8..4ce4de206 100644 --- a/src/main/java/org/dragonet/proxy/utilities/io/PEBinaryReader.java +++ b/src/main/java/org/dragonet/proxy/utilities/io/PEBinaryReader.java @@ -23,189 +23,186 @@ import java.util.UUID; public class PEBinaryReader implements Closeable { - // vars - protected InputStream is; - protected boolean endianness; - private int totallyRead; - - // constructor - public PEBinaryReader(InputStream is) { - this(is, PEBinaryUtils.BIG_ENDIAN); - } - - public PEBinaryReader(InputStream is, boolean endianness) { - this.is = is; - this.endianness = endianness; - } - - // public - public boolean switchEndianness() { - this.endianness = !this.endianness; - return this.endianness; - } - - public boolean getEndianness() { - return this.endianness; - } - - public void close() throws IOException { - is.close(); - } - - public int readVarInt() throws IOException { - return VarInt.decodeZigZag32(readUnsignedVarInt()); - } - - public int readUnsignedVarInt() throws IOException { - return readVar(5).intValue(); - } - - public long readVarLong() throws IOException { - return VarInt.decodeZigZag64(readUnsignedVarLong().longValue()); - } - - public BigInteger readUnsignedVarLong() throws IOException { - return readVar(10); - } - - public BigInteger readVar(int maxLength) throws IOException { - BigInteger result = BigInteger.ZERO; - int offset = 0; - int b; - - do { - if (offset >= maxLength) { - throw new IllegalArgumentException("VarInt overflow"); - } - - b = readByte(); - result = result.or(BigInteger.valueOf((b & 0x7f) << (offset * 7))); - offset++; - } while ((b & 0x80) > 0); - - return result; - } - - public float[] readVector3f() throws IOException { - // FORCED to use LITTLE-ENDIAN - if (endianness != PEBinaryUtils.LITTLE_ENDIAN) { - switchEndianness(); - float[] r = readVector3f(); - switchEndianness(); - return r; - } else { - float[] r = new float[] { readFloat(), readFloat(), readFloat() }; - return r; - } - } - - public int[] readBlockCoords() throws IOException { - return new int[] { readVarInt(), readUnsignedVarInt(), readVarInt() }; - } - - public BinaryAddress readAddress() throws IOException { - BinaryAddress addr = new BinaryAddress(); - addr.type = readByte(); - if ((addr.type & 0xFF) == 4) { - // IPv4 - addr.address = read(4); - } else { - addr.address = read(8); - } - addr.port = readShort(); - return addr; - } - - public UUID readUUID() throws IOException { - long first = readLong(); - long last = readLong(); - return new UUID(first, last); - } - - public String readString() throws IOException { - int len = readVarInt(); - falloc(len); - return new String(read(len), StandardCharsets.UTF_8); - } - - public byte readByte() throws IOException { - falloc(1); - totallyRead += 1; - return (byte) is.read(); - } - - public short readShort() throws IOException { - falloc(2); - return (short) (readNat(2) & 0xFFFF); - } - - public int readTriad() throws IOException { - falloc(3); - this.endianness = !this.endianness; - int triad = (int) (readNat(3) & 0xFFFFFF); - this.endianness = !this.endianness; - return triad; - } - - public int readInt() throws IOException { - falloc(4); - return (int) (readNat(4) & 0xFFFFFFFF); - } - - public long readLong() throws IOException { - falloc(8); - return readNat(8); - } - - public float readFloat() throws IOException { - falloc(4); - ByteBuffer bb = ByteBuffer.wrap(read(4)); - return bb.getFloat(); - } - - public double readDouble() throws IOException { - falloc(8); - ByteBuffer bb = ByteBuffer.wrap(read(8)); - return bb.getDouble(); - } - - public byte[] read(int length) throws IOException { - falloc(length); - this.totallyRead += length; - byte[] buffer = new byte[length]; - is.read(buffer, 0, length); - return buffer; - } - - public long readNat(int length) throws IOException { - falloc(length); - return PEBinaryUtils.read(read(length), 0, length, endianness); - } - - protected void falloc(int l) throws IOException { - int lack = l - is.available(); - if (lack > 0) { - throw getUEOFException(lack); - } - } - - protected IOException getUEOFException(int needed) { - return new IOException(String.format("Unexpected end of file: %d more bytes expected", needed)); - } - - public int available() throws IOException { - return this.is.available(); - } - - public int totallyRead() { - return this.totallyRead; - } - - // private - - public static class BinaryAddress { - public byte type; - public byte[] address; - public short port; - } + + protected InputStream is; + protected boolean endianness; + private int totallyRead; + + public PEBinaryReader(InputStream is) { + this(is, PEBinaryUtils.BIG_ENDIAN); + } + + public PEBinaryReader(InputStream is, boolean endianness) { + this.is = is; + this.endianness = endianness; + } + + public boolean switchEndianness() { + this.endianness = !this.endianness; + return this.endianness; + } + + public boolean getEndianness() { + return this.endianness; + } + + public void close() throws IOException { + is.close(); + } + + public int readVarInt() throws IOException { + return VarInt.decodeZigZag32(readUnsignedVarInt()); + } + + public int readUnsignedVarInt() throws IOException { + return readVar(5).intValue(); + } + + public long readVarLong() throws IOException { + return VarInt.decodeZigZag64(readUnsignedVarLong().longValue()); + } + + public BigInteger readUnsignedVarLong() throws IOException { + return readVar(10); + } + + public BigInteger readVar(int maxLength) throws IOException { + BigInteger result = BigInteger.ZERO; + int offset = 0; + int b; + + do { + if (offset >= maxLength) { + throw new IllegalArgumentException("VarInt overflow"); + } + + b = readByte(); + result = result.or(BigInteger.valueOf((b & 0x7f) << (offset * 7))); + offset++; + } while ((b & 0x80) > 0); + + return result; + } + + public float[] readVector3f() throws IOException { + // FORCED to use LITTLE-ENDIAN + if (endianness != PEBinaryUtils.LITTLE_ENDIAN) { + switchEndianness(); + float[] r = readVector3f(); + switchEndianness(); + return r; + } else { + float[] r = new float[]{readFloat(), readFloat(), readFloat()}; + return r; + } + } + + public int[] readBlockCoords() throws IOException { + return new int[]{readVarInt(), readUnsignedVarInt(), readVarInt()}; + } + + public BinaryAddress readAddress() throws IOException { + BinaryAddress addr = new BinaryAddress(); + addr.type = readByte(); + if ((addr.type & 0xFF) == 4) { + // IPv4 + addr.address = read(4); + } else { + addr.address = read(8); + } + addr.port = readShort(); + return addr; + } + + public UUID readUUID() throws IOException { + long first = readLong(); + long last = readLong(); + return new UUID(first, last); + } + + public String readString() throws IOException { + int len = readVarInt(); + falloc(len); + return new String(read(len), StandardCharsets.UTF_8); + } + + public byte readByte() throws IOException { + falloc(1); + totallyRead += 1; + return (byte) is.read(); + } + + public short readShort() throws IOException { + falloc(2); + return (short) (readNat(2) & 0xFFFF); + } + + public int readTriad() throws IOException { + falloc(3); + this.endianness = !this.endianness; + int triad = (int) (readNat(3) & 0xFFFFFF); + this.endianness = !this.endianness; + return triad; + } + + public int readInt() throws IOException { + falloc(4); + return (int) (readNat(4) & 0xFFFFFFFF); + } + + public long readLong() throws IOException { + falloc(8); + return readNat(8); + } + + public float readFloat() throws IOException { + falloc(4); + ByteBuffer bb = ByteBuffer.wrap(read(4)); + return bb.getFloat(); + } + + public double readDouble() throws IOException { + falloc(8); + ByteBuffer bb = ByteBuffer.wrap(read(8)); + return bb.getDouble(); + } + + public byte[] read(int length) throws IOException { + falloc(length); + this.totallyRead += length; + byte[] buffer = new byte[length]; + is.read(buffer, 0, length); + return buffer; + } + + public long readNat(int length) throws IOException { + falloc(length); + return PEBinaryUtils.read(read(length), 0, length, endianness); + } + + protected void falloc(int l) throws IOException { + int lack = l - is.available(); + if (lack > 0) { + throw getUEOFException(lack); + } + } + + protected IOException getUEOFException(int needed) { + return new IOException(String.format("Unexpected end of file: %d more bytes expected", needed)); + } + + public int available() throws IOException { + return this.is.available(); + } + + public int totallyRead() { + return this.totallyRead; + } + + public static class BinaryAddress { + + public byte type; + public byte[] address; + public short port; + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/io/PEBinaryUtils.java b/src/main/java/org/dragonet/proxy/utilities/io/PEBinaryUtils.java index c384b840d..6b4aaa6cd 100644 --- a/src/main/java/org/dragonet/proxy/utilities/io/PEBinaryUtils.java +++ b/src/main/java/org/dragonet/proxy/utilities/io/PEBinaryUtils.java @@ -13,50 +13,45 @@ package org.dragonet.proxy.utilities.io; public abstract class PEBinaryUtils { - // vars - public static final boolean BIG_ENDIAN = false; - public static final boolean LITTLE_ENDIAN = true; - - // constructor - public PEBinaryUtils() { - - } - - // public - public static byte[] write(long x, int length, boolean endianness) { - byte[] result = new byte[length]; - for (int i = 0; i < length; i++) { - result[endianness == BIG_ENDIAN ? (length - 1 - i) : i] = (byte) (x & 0xFF); - x >>= 8; - } - return result; - } - - public static byte[] write(long x, int length) { - return write(x, length, BIG_ENDIAN); - } - - public static long read(byte[] buffer, int start, int length, boolean endianness) { - long x = 0; - for (int i = 0; i < length; i++) { - x <<= 8; - x |= buffer[endianness == BIG_ENDIAN ? (start + i) : (start + length - 1 - i)] & 0xFF; - } - return x; - } - - public static long read(byte[] buffer, int start, int length) { - return read(buffer, start, length, BIG_ENDIAN); - } - - public static long read(byte[] buffer, boolean endianness) { - return read(buffer, 0, buffer.length, endianness); - } - - public static long read(byte[] buffer) { - return read(buffer, 0, buffer.length, BIG_ENDIAN); - } - - // private + public static final boolean BIG_ENDIAN = false; + public static final boolean LITTLE_ENDIAN = true; + + public PEBinaryUtils() { + + } + + public static byte[] write(long x, int length, boolean endianness) { + byte[] result = new byte[length]; + for (int i = 0; i < length; i++) { + result[endianness == BIG_ENDIAN ? (length - 1 - i) : i] = (byte) (x & 0xFF); + x >>= 8; + } + return result; + } + + public static byte[] write(long x, int length) { + return write(x, length, BIG_ENDIAN); + } + + public static long read(byte[] buffer, int start, int length, boolean endianness) { + long x = 0; + for (int i = 0; i < length; i++) { + x <<= 8; + x |= buffer[endianness == BIG_ENDIAN ? (start + i) : (start + length - 1 - i)] & 0xFF; + } + return x; + } + + public static long read(byte[] buffer, int start, int length) { + return read(buffer, start, length, BIG_ENDIAN); + } + + public static long read(byte[] buffer, boolean endianness) { + return read(buffer, 0, buffer.length, endianness); + } + + public static long read(byte[] buffer) { + return read(buffer, 0, buffer.length, BIG_ENDIAN); + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/io/PEBinaryWriter.java b/src/main/java/org/dragonet/proxy/utilities/io/PEBinaryWriter.java index 6387144ea..2cc43d5f3 100644 --- a/src/main/java/org/dragonet/proxy/utilities/io/PEBinaryWriter.java +++ b/src/main/java/org/dragonet/proxy/utilities/io/PEBinaryWriter.java @@ -26,161 +26,156 @@ import java.util.UUID; public class PEBinaryWriter implements Flushable, Closeable { - // vars - private static final BigInteger UNSIGNED_LONG_MAX_VALUE = new BigInteger("FFFFFFFFFFFFFFFF", 16); - protected OutputStream os; - protected boolean endianness; - - // constructor - public PEBinaryWriter(OutputStream os) { - this(os, PEBinaryUtils.BIG_ENDIAN); - } - - public PEBinaryWriter(OutputStream os, boolean endianness) { - this.os = os; - this.endianness = endianness; - } - - // public - public boolean switchEndianness() { - this.endianness = !this.endianness; - return this.endianness; - } - - public boolean getEndianness() { - return this.endianness; - } - - public void flush() throws IOException { - os.flush(); - } - - public void close() throws IOException { - os.close(); - } - - public void writeVarInt(int value) throws IOException { - writeUnsignedVarInt(VarInt.encodeZigZag32(value)); - } - - public void writeUnsignedVarInt(long value) throws IOException { - writeVar(BigInteger.valueOf(value)); - } - - public void writeVarLong(long value) throws IOException { - writeUnsignedVarLong(BigInteger.valueOf(VarInt.encodeZigZag64(value))); - } - - public void writeUnsignedVarLong(BigInteger value) throws IOException { - writeVar(value); - } - - public void writeVar(BigInteger v) throws IOException { - v = v.and(UNSIGNED_LONG_MAX_VALUE); - BigInteger i = BigInteger.valueOf(-128); - BigInteger BIX7F = BigInteger.valueOf(0x7f); - BigInteger BIX80 = BigInteger.valueOf(0x80); - while (!v.and(i).equals(BigInteger.ZERO)) { - writeByte(v.and(BIX7F).or(BIX80).byteValue()); - v = v.shiftRight(7); - } - - writeByte(v.byteValue()); - } - - public void writeVector3f(float x, float y, float z) throws IOException { - // FORCED to use LITTLE-ENDIAN - if (endianness != PEBinaryUtils.LITTLE_ENDIAN) { - switchEndianness(); - writeVector3f(x, y, z); - switchEndianness(); - } else { - writeFloat(x); - writeFloat(y); - writeFloat(z); - } - } - - public void writeBlockCoords(int x, int y, int z) throws IOException { - writeVarInt(x); - writeUnsignedVarInt(y); - writeVarInt(z); - } - - public void writeUUID(UUID uuid) throws IOException { - writeLong(uuid.getMostSignificantBits()); - writeLong(uuid.getLeastSignificantBits()); - } - - public void writeString(String string) throws IOException { - byte[] data = string.getBytes(StandardCharsets.UTF_8); - writeUnsignedVarInt(data.length); - write(data); - } - - public void writeAddress(InetAddress addr, short port) throws IOException { - if (addr instanceof Inet4Address) { - writeByte((byte) 4); - writeInt((addr.getAddress()[0] << 24) | (addr.getAddress()[1] << 16) | (addr.getAddress()[2] << 8) - | addr.getAddress()[3]); - writeShort(port); - } else { - // IPv6? Nah, we do this later. - writeByte((byte) 6); - writeLong(0L); - } - } - - public void writeByte(byte b) throws IOException { - os.write(b); - } - - public void writeBoolean(boolean b) throws IOException { - writeByte(b ? (byte) 0x01 : (byte) 0x00); - } - - public void writeShort(short s) throws IOException { - write(s, 2); - } - - public void writeTriad(int t) throws IOException { - this.endianness = !this.endianness; - write(t, 3); - this.endianness = !this.endianness; - } - - public void writeInt(int i) throws IOException { - write(i, 4); - } - - public void writeLong(long l) throws IOException { - write(l, 8); - } - - public void writeFloat(float f) throws IOException { - ByteBuffer bb = ByteBuffer.allocate(4); - bb.putFloat(f); - os.write(bb.array()); - } - - public void writeDouble(double d) throws IOException { - ByteBuffer bb = ByteBuffer.allocate(8); - bb.putDouble(d); - os.write(bb.array()); - } - - public void write(long x, int len) throws IOException { - os.write(PEBinaryUtils.write(x, len, endianness)); - } - - public void write(byte[] bytes) throws IOException { - os.write(bytes); - } - - public void writeNat(int oneByte) throws IOException { - os.write(oneByte); - } - - // private + private static final BigInteger UNSIGNED_LONG_MAX_VALUE = new BigInteger("FFFFFFFFFFFFFFFF", 16); + protected OutputStream os; + protected boolean endianness; + + public PEBinaryWriter(OutputStream os) { + this(os, PEBinaryUtils.BIG_ENDIAN); + } + + public PEBinaryWriter(OutputStream os, boolean endianness) { + this.os = os; + this.endianness = endianness; + } + + public boolean switchEndianness() { + this.endianness = !this.endianness; + return this.endianness; + } + + public boolean getEndianness() { + return this.endianness; + } + + public void flush() throws IOException { + os.flush(); + } + + public void close() throws IOException { + os.close(); + } + + public void writeVarInt(int value) throws IOException { + writeUnsignedVarInt(VarInt.encodeZigZag32(value)); + } + + public void writeUnsignedVarInt(long value) throws IOException { + writeVar(BigInteger.valueOf(value)); + } + + public void writeVarLong(long value) throws IOException { + writeUnsignedVarLong(BigInteger.valueOf(VarInt.encodeZigZag64(value))); + } + + public void writeUnsignedVarLong(BigInteger value) throws IOException { + writeVar(value); + } + + public void writeVar(BigInteger v) throws IOException { + v = v.and(UNSIGNED_LONG_MAX_VALUE); + BigInteger i = BigInteger.valueOf(-128); + BigInteger BIX7F = BigInteger.valueOf(0x7f); + BigInteger BIX80 = BigInteger.valueOf(0x80); + while (!v.and(i).equals(BigInteger.ZERO)) { + writeByte(v.and(BIX7F).or(BIX80).byteValue()); + v = v.shiftRight(7); + } + + writeByte(v.byteValue()); + } + + public void writeVector3f(float x, float y, float z) throws IOException { + // FORCED to use LITTLE-ENDIAN + if (endianness != PEBinaryUtils.LITTLE_ENDIAN) { + switchEndianness(); + writeVector3f(x, y, z); + switchEndianness(); + } else { + writeFloat(x); + writeFloat(y); + writeFloat(z); + } + } + + public void writeBlockCoords(int x, int y, int z) throws IOException { + writeVarInt(x); + writeUnsignedVarInt(y); + writeVarInt(z); + } + + public void writeUUID(UUID uuid) throws IOException { + writeLong(uuid.getMostSignificantBits()); + writeLong(uuid.getLeastSignificantBits()); + } + + public void writeString(String string) throws IOException { + byte[] data = string.getBytes(StandardCharsets.UTF_8); + writeUnsignedVarInt(data.length); + write(data); + } + + public void writeAddress(InetAddress addr, short port) throws IOException { + if (addr instanceof Inet4Address) { + writeByte((byte) 4); + writeInt((addr.getAddress()[0] << 24) | (addr.getAddress()[1] << 16) | (addr.getAddress()[2] << 8) + | addr.getAddress()[3]); + writeShort(port); + } else { + // IPv6? Nah, we do this later. + writeByte((byte) 6); + writeLong(0L); + } + } + + public void writeByte(byte b) throws IOException { + os.write(b); + } + + public void writeBoolean(boolean b) throws IOException { + writeByte(b ? (byte) 0x01 : (byte) 0x00); + } + + public void writeShort(short s) throws IOException { + write(s, 2); + } + + public void writeTriad(int t) throws IOException { + this.endianness = !this.endianness; + write(t, 3); + this.endianness = !this.endianness; + } + + public void writeInt(int i) throws IOException { + write(i, 4); + } + + public void writeLong(long l) throws IOException { + write(l, 8); + } + + public void writeFloat(float f) throws IOException { + ByteBuffer bb = ByteBuffer.allocate(4); + bb.putFloat(f); + os.write(bb.array()); + } + + public void writeDouble(double d) throws IOException { + ByteBuffer bb = ByteBuffer.allocate(8); + bb.putDouble(d); + os.write(bb.array()); + } + + public void write(long x, int len) throws IOException { + os.write(PEBinaryUtils.write(x, len, endianness)); + } + + public void write(byte[] bytes) throws IOException { + os.write(bytes); + } + + public void writeNat(int oneByte) throws IOException { + os.write(oneByte); + } } diff --git a/src/main/java/org/dragonet/proxy/utilities/io/SkinDownloader.java b/src/main/java/org/dragonet/proxy/utilities/io/SkinDownloader.java index 9563e0605..0190ea25a 100644 --- a/src/main/java/org/dragonet/proxy/utilities/io/SkinDownloader.java +++ b/src/main/java/org/dragonet/proxy/utilities/io/SkinDownloader.java @@ -11,38 +11,32 @@ import java.net.URL; public class SkinDownloader { - // vars - // constructor - public SkinDownloader() { + public SkinDownloader() { - } + } - // public - public static byte[] download(String username) { - try { - URL url = new URL(String.format("http://s3.amazonaws.com/MinecraftSkins/%s.png", username)); + public static byte[] download(String username) { + try { + URL url = new URL(String.format("http://s3.amazonaws.com/MinecraftSkins/%s.png", username)); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - DataInputStream in = new DataInputStream(connection.getInputStream()); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + DataInputStream in = new DataInputStream(connection.getInputStream()); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buffer = new byte[4096]; - int count = 0; - while ((count = in.read(buffer)) > 0) { - out.write(buffer, 0, count); - } - out.close(); - in.close(); - connection.disconnect(); - return out.toByteArray(); - - } catch (Exception e) { - return null; - } - } - - // private + byte[] buffer = new byte[4096]; + int count = 0; + while ((count = in.read(buffer)) > 0) { + out.write(buffer, 0, count); + } + out.close(); + in.close(); + connection.disconnect(); + return out.toByteArray(); + } catch (Exception e) { + return null; + } + } }