3
0
Mirror von https://github.com/ViaVersion/ViaVersion.git synchronisiert 2024-12-27 08:30:09 +01:00

Merge pull request #162 from phenomax/master

General code improvements
Dieser Commit ist enthalten in:
Myles 2016-03-07 16:28:04 +00:00
Commit 6b5c166a22
34 geänderte Dateien mit 496 neuen und 626 gelöschten Zeilen

Datei anzeigen

@ -170,5 +170,12 @@
<scope>provided</scope> <scope>provided</scope>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.6</version>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
</project> </project>

Datei anzeigen

@ -17,7 +17,7 @@ public class BlockStorage {
public BlockStorage() { public BlockStorage() {
this.bitsPerEntry = 4; this.bitsPerEntry = 4;
this.states = new ArrayList<Integer>(); this.states = new ArrayList<>();
this.states.add(0); this.states.add(0);
this.storage = new FlexibleStorage(this.bitsPerEntry, 4096); this.storage = new FlexibleStorage(this.bitsPerEntry, 4096);
@ -26,7 +26,7 @@ public class BlockStorage {
public BlockStorage(ByteBuf in) throws IOException { public BlockStorage(ByteBuf in) throws IOException {
this.bitsPerEntry = in.readUnsignedByte(); this.bitsPerEntry = in.readUnsignedByte();
this.states = new ArrayList<Integer>(); this.states = new ArrayList<>();
int stateCount = PacketUtil.readVarInt(in); int stateCount = PacketUtil.readVarInt(in);
for (int i = 0; i < stateCount; i++) { for (int i = 0; i < stateCount; i++) {
this.states.add(PacketUtil.readVarInt(in)); this.states.add(PacketUtil.readVarInt(in));
@ -35,6 +35,10 @@ public class BlockStorage {
this.storage = new FlexibleStorage(this.bitsPerEntry, PacketUtil.readLongs(PacketUtil.readVarInt(in), in)); this.storage = new FlexibleStorage(this.bitsPerEntry, PacketUtil.readLongs(PacketUtil.readVarInt(in), in));
} }
private static int index(int x, int y, int z) {
return y << 8 | z << 4 | x;
}
public void write(ByteBuf out) throws IOException { public void write(ByteBuf out) throws IOException {
out.writeByte(this.bitsPerEntry); out.writeByte(this.bitsPerEntry);
@ -78,7 +82,7 @@ public class BlockStorage {
List<Integer> oldStates = this.states; List<Integer> oldStates = this.states;
if (this.bitsPerEntry > 8) { if (this.bitsPerEntry > 8) {
oldStates = new ArrayList<Integer>(this.states); oldStates = new ArrayList<>(this.states);
this.states.clear(); this.states.clear();
this.bitsPerEntry = 13; this.bitsPerEntry = 13;
} }
@ -107,10 +111,6 @@ public class BlockStorage {
return true; return true;
} }
private static int index(int x, int y, int z) {
return y << 8 | z << 4 | x;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
return this == o || (o instanceof BlockStorage && this.bitsPerEntry == ((BlockStorage) o).bitsPerEntry && this.states.equals(((BlockStorage) o).states) && this.storage.equals(((BlockStorage) o).storage)); return this == o || (o instanceof BlockStorage && this.bitsPerEntry == ((BlockStorage) o).bitsPerEntry && this.states.equals(((BlockStorage) o).states) && this.storage.equals(((BlockStorage) o).storage));

Datei anzeigen

@ -1,5 +1,10 @@
package org.spacehq.mc.protocol.data.game.chunk; package org.spacehq.mc.protocol.data.game.chunk;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Column { public class Column {
private int x; private int x;
private int z; private int z;
@ -23,9 +28,9 @@ public class Column {
this.skylight = false; this.skylight = false;
boolean noSkylight = false; boolean noSkylight = false;
for(int index = 0; index < chunks.length; index++) { for (Chunk chunk : chunks) {
if(chunks[index] != null) { if (chunk != null) {
if(chunks[index].getSkyLight() == null) { if (chunk.getSkyLight() == null) {
noSkylight = true; noSkylight = true;
} else { } else {
this.skylight = true; this.skylight = true;
@ -43,26 +48,11 @@ public class Column {
this.biomeData = biomeData; this.biomeData = biomeData;
} }
public int getX() {
return this.x;
}
public int getZ() {
return this.z;
}
public Chunk[] getChunks() {
return this.chunks;
}
public boolean hasBiomeData() { public boolean hasBiomeData() {
return this.biomeData != null; return this.biomeData != null;
} }
public byte[] getBiomeData() {
return this.biomeData;
}
public boolean hasSkylight() { public boolean hasSkylight() {
return this.skylight; return this.skylight;
} }

Datei anzeigen

@ -40,30 +40,30 @@ public class ConnectionInfo {
this.state = state; this.state = state;
} }
public void setCompression(int compression) {
this.compression = compression;
}
public int getCompression() { public int getCompression() {
return compression; return compression;
} }
public void setLastPacket(Object lastPacket) { public void setCompression(int compression) {
this.lastPacket = lastPacket; this.compression = compression;
} }
public Object getLastPacket() { public Object getLastPacket() {
return lastPacket; return lastPacket;
} }
public void setUUID(UUID UUID) { public void setLastPacket(Object lastPacket) {
this.UUID = UUID; this.lastPacket = lastPacket;
} }
public java.util.UUID getUUID() { public java.util.UUID getUUID() {
return UUID; return UUID;
} }
public void setUUID(UUID UUID) {
this.UUID = UUID;
}
public Player getPlayer() { public Player getPlayer() {
return UUID == null ? null : Bukkit.getPlayer(UUID); return UUID == null ? null : Bukkit.getPlayer(UUID);
} }
@ -102,11 +102,11 @@ public class ConnectionInfo {
this.openWindow = null; this.openWindow = null;
} }
public void setUsername(String username) {
this.username = username;
}
public String getUsername() { public String getUsername() {
return username; return username;
} }
public void setUsername(String username) {
this.username = username;
}
} }

Datei anzeigen

@ -28,7 +28,6 @@ import us.myles.ViaVersion.update.UpdateUtil;
import us.myles.ViaVersion.util.ReflectionUtil; import us.myles.ViaVersion.util.ReflectionUtil;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@ -39,9 +38,27 @@ import java.util.concurrent.TimeUnit;
public class ViaVersionPlugin extends JavaPlugin implements ViaVersionAPI { public class ViaVersionPlugin extends JavaPlugin implements ViaVersionAPI {
private final Map<UUID, ConnectionInfo> portedPlayers = new ConcurrentHashMap<UUID, ConnectionInfo>(); private final Map<UUID, ConnectionInfo> portedPlayers = new ConcurrentHashMap<>();
private boolean debug = false; private boolean debug = false;
public static ItemStack getHandItem(final ConnectionInfo info) {
try {
return Bukkit.getScheduler().callSyncMethod(Bukkit.getPluginManager().getPlugin("ViaVersion"), new Callable<ItemStack>() {
@Override
public ItemStack call() throws Exception {
if (info.getPlayer() != null) {
return info.getPlayer().getItemInHand();
}
return null;
}
}).get(10, TimeUnit.SECONDS);
} catch (Exception e) {
System.out.println("Error fetching hand item ");
e.printStackTrace();
return null;
}
}
@Override @Override
public void onEnable() { public void onEnable() {
ViaVersion.setInstance(this); ViaVersion.setInstance(this);
@ -154,6 +171,10 @@ public class ViaVersionPlugin extends JavaPlugin implements ViaVersionAPI {
return this.debug; return this.debug;
} }
public void setDebug(boolean value) {
this.debug = value;
}
@Override @Override
public boolean isSyncedChunks() { public boolean isSyncedChunks() {
return getConfig().getBoolean("sync-chunks", true); return getConfig().getBoolean("sync-chunks", true);
@ -169,10 +190,6 @@ public class ViaVersionPlugin extends JavaPlugin implements ViaVersionAPI {
return getConfig().getBoolean("auto-team", true); return getConfig().getBoolean("auto-team", true);
} }
public void setDebug(boolean value) {
this.debug = value;
}
public void addPortedClient(ConnectionInfo info) { public void addPortedClient(ConnectionInfo info) {
portedPlayers.put(info.getUUID(), info); portedPlayers.put(info.getUUID(), info);
} }
@ -181,24 +198,6 @@ public class ViaVersionPlugin extends JavaPlugin implements ViaVersionAPI {
portedPlayers.remove(clientID); portedPlayers.remove(clientID);
} }
public static ItemStack getHandItem(final ConnectionInfo info) {
try {
return Bukkit.getScheduler().callSyncMethod(Bukkit.getPluginManager().getPlugin("ViaVersion"), new Callable<ItemStack>() {
@Override
public ItemStack call() throws Exception {
if (info.getPlayer() != null) {
return info.getPlayer().getItemInHand();
}
return null;
}
}).get(10, TimeUnit.SECONDS);
} catch (Exception e) {
System.out.println("Error fetching hand item ");
e.printStackTrace();
return null;
}
}
public void run(final Runnable runnable, boolean wait) { public void run(final Runnable runnable, boolean wait) {
try { try {
Future f = Bukkit.getScheduler().callSyncMethod(Bukkit.getPluginManager().getPlugin("ViaVersion"), new Callable<Boolean>() { Future f = Bukkit.getScheduler().callSyncMethod(Bukkit.getPluginManager().getPlugin("ViaVersion"), new Callable<Boolean>() {

Datei anzeigen

@ -1,17 +1,11 @@
package us.myles.ViaVersion.api; package us.myles.ViaVersion.api;
import lombok.Getter;
import lombok.Setter;
public class ViaVersion { public class ViaVersion {
private static ViaVersionAPI INSTANCE; @Getter
@Setter
public static void setInstance(ViaVersionAPI api) { private static ViaVersionAPI instance;
if (INSTANCE != null) {
throw new IllegalStateException("Instance already set.");
}
INSTANCE = api;
}
public static ViaVersionAPI getInstance() {
return INSTANCE;
}
} }

Datei anzeigen

@ -13,13 +13,6 @@ public interface BossBar {
*/ */
void setTitle(String title); void setTitle(String title);
/**
* Get the current title
*
* @return the title
*/
String getTitle();
/** /**
* Change the health * Change the health
* *
@ -27,20 +20,6 @@ public interface BossBar {
*/ */
void setHealth(float health); void setHealth(float health);
/**
* Get the health
*
* @return float between 0F - 1F
*/
float getHealth();
/**
* Yay colors!
*
* @param color Whatever color you want!
*/
void setColor(BossColor color);
/** /**
* Get the bossbar color * Get the bossbar color
* *
@ -48,6 +27,13 @@ public interface BossBar {
*/ */
BossColor getColor(); BossColor getColor();
/**
* Yay colors!
*
* @param color Whatever color you want!
*/
void setColor(BossColor color);
/** /**
* Change the bosbar style * Change the bosbar style
* *
@ -55,13 +41,6 @@ public interface BossBar {
*/ */
void setStyle(BossStyle style); void setStyle(BossStyle style);
/**
* Get the bosbar style
*
* @return BossStyle
*/
BossStyle getStyle();
/** /**
* Show the bossbar to a player. * Show the bossbar to a player.
* *

Datei anzeigen

@ -1,5 +1,10 @@
package us.myles.ViaVersion.api.boss; package us.myles.ViaVersion.api.boss;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Getter
public enum BossColor { public enum BossColor {
PINK(0), PINK(0),
BLUE(1), BLUE(1),
@ -10,12 +15,4 @@ public enum BossColor {
WHITE(6); WHITE(6);
private final int id; private final int id;
BossColor(int id) {
this.id = id;
}
public int getId() {
return id;
}
} }

Datei anzeigen

@ -1,16 +1,13 @@
package us.myles.ViaVersion.api.boss; package us.myles.ViaVersion.api.boss;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Getter
public enum BossFlag { public enum BossFlag {
DARKEN_SKY(1), DARKEN_SKY(1),
PLAY_BOSS_MUSIC(2); PLAY_BOSS_MUSIC(2);
private final int id; private final int id;
BossFlag(int id) {
this.id = id;
}
public int getId() {
return id;
}
} }

Datei anzeigen

@ -1,5 +1,10 @@
package us.myles.ViaVersion.api.boss; package us.myles.ViaVersion.api.boss;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Getter
public enum BossStyle { public enum BossStyle {
SOLID(0), SOLID(0),
SEGMENTED_6(1), SEGMENTED_6(1),
@ -8,12 +13,4 @@ public enum BossStyle {
SEGMENTED_20(4); SEGMENTED_20(4);
private final int id; private final int id;
BossStyle(int id) {
this.id = id;
}
public int getId() {
return id;
}
} }

Datei anzeigen

@ -2,6 +2,7 @@ package us.myles.ViaVersion.armor;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import lombok.RequiredArgsConstructor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -21,14 +22,27 @@ import java.util.UUID;
import static us.myles.ViaVersion.util.PacketUtil.*; import static us.myles.ViaVersion.util.PacketUtil.*;
@RequiredArgsConstructor
public class ArmorListener implements Listener { public class ArmorListener implements Listener {
private static final UUID ARMOR_ATTRIBUTE = UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150");
private final ViaVersionPlugin plugin; private final ViaVersionPlugin plugin;
private static UUID armorAttribute = UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150"); public static void sendArmorUpdate(Player player) {
int armor = ArmorType.calculateArmorPoints(player.getInventory().getArmorContents());
public ArmorListener(ViaVersionPlugin plugin) { ByteBuf buf = Unpooled.buffer();
this.plugin = plugin; writeVarInt(PacketType.PLAY_ENTITY_PROPERTIES.getNewPacketID(), buf);
writeVarInt(player.getEntityId(), buf);
buf.writeInt(1); // only 1 property
writeString("generic.armor", buf);
buf.writeDouble(0); //default 0 armor
writeVarInt(1, buf); // 1 modifier
writeUUID(ARMOR_ATTRIBUTE, buf); // armor modifier uuid
buf.writeDouble((double) armor); // the modifier value
buf.writeByte(0); // the modifier operation, 0 is add number
ViaVersion.getInstance().sendRawPacket(player, buf);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
@ -45,7 +59,6 @@ public class ArmorListener implements Listener {
} }
if (e.getRawSlot() >= 5 && e.getRawSlot() <= 8) { if (e.getRawSlot() >= 5 && e.getRawSlot() <= 8) {
sendDelayedArmorUpdate(player); sendDelayedArmorUpdate(player);
return;
} }
} }
} }
@ -86,21 +99,4 @@ public class ArmorListener implements Listener {
} }
}); });
} }
public static void sendArmorUpdate(Player player) {
int armor = ArmorType.calculateArmorPoints(player.getInventory().getArmorContents());
ByteBuf buf = Unpooled.buffer();
writeVarInt(PacketType.PLAY_ENTITY_PROPERTIES.getNewPacketID(), buf);
writeVarInt(player.getEntityId(), buf);
buf.writeInt(1); // only 1 property
writeString("generic.armor", buf);
buf.writeDouble(0); //default 0 armor
writeVarInt(1, buf); // 1 modifier
writeUUID(armorAttribute, buf); // armor modifier uuid
buf.writeDouble((double) armor); // the modifier value
buf.writeByte(0); // the modifier operation, 0 is add number
ViaVersion.getInstance().sendRawPacket(player, buf);
}
} }

Datei anzeigen

@ -1,8 +1,12 @@
package us.myles.ViaVersion.armor; package us.myles.ViaVersion.armor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@RequiredArgsConstructor
@Getter
public enum ArmorType { public enum ArmorType {
LEATHER_HELMET(1, 298, Material.LEATHER_HELMET), LEATHER_HELMET(1, 298, Material.LEATHER_HELMET),
@ -27,27 +31,9 @@ public enum ArmorType {
GOLD_BOOTS(1, 317, Material.GOLD_BOOTS), GOLD_BOOTS(1, 317, Material.GOLD_BOOTS),
NONE(0, 0, Material.AIR); NONE(0, 0, Material.AIR);
private int armorpoints; private final int armorPoints;
private int id; private final int id;
private Material type; private final Material type;
ArmorType(int armor, int id, Material type) {
this.armorpoints = armor;
this.id = id;
this.type = type;
}
public int getArmorPoints() {
return this.armorpoints;
}
public int getId() {
return this.id;
}
public Material getType() {
return this.type;
}
public static ArmorType findByType(Material type) { public static ArmorType findByType(Material type) {
for(ArmorType a : ArmorType.values()) for(ArmorType a : ArmorType.values())
@ -58,9 +44,9 @@ public enum ArmorType {
public static int calculateArmorPoints(ItemStack[] armor) { public static int calculateArmorPoints(ItemStack[] armor) {
int total = 0; int total = 0;
for(int i = 0; i < armor.length; i++) { for (ItemStack anArmor : armor) {
if(armor[i] != null) if (anArmor != null)
total += findByType(armor[i].getType()).getArmorPoints(); total += findByType(anArmor.getType()).getArmorPoints();
} }
return total; return total;
} }
@ -81,11 +67,15 @@ public enum ArmorType {
public static int calculateArmorPoints(int[] armor) { public static int calculateArmorPoints(int[] armor) {
int total = 0; int total = 0;
for(int i = 0; i < armor.length; i++) { for (int anArmor : armor) {
if(armor[i] != -1) if (anArmor != -1)
total += findById(armor[i]).getArmorPoints(); total += findById(anArmor).getArmorPoints();
} }
return total; return total;
} }
public Material getType() {
return this.type;
}
} }

Datei anzeigen

@ -2,6 +2,8 @@ package us.myles.ViaVersion.boss;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.Validate; import org.apache.commons.lang.Validate;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import us.myles.ViaVersion.api.ViaVersion; import us.myles.ViaVersion.api.ViaVersion;
@ -18,6 +20,7 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
@Getter
public class ViaBossBar implements BossBar { public class ViaBossBar implements BossBar {
private UUID uuid; private UUID uuid;
private String title; private String title;
@ -48,11 +51,6 @@ public class ViaBossBar implements BossBar {
sendPacket(UpdateAction.UPDATE_TITLE); sendPacket(UpdateAction.UPDATE_TITLE);
} }
@Override
public String getTitle() {
return title;
}
@Override @Override
public void setHealth(float health) { public void setHealth(float health) {
Validate.isTrue((health >= 0 && health <= 1), "Health must be between 0 and 1"); Validate.isTrue((health >= 0 && health <= 1), "Health must be between 0 and 1");
@ -61,8 +59,8 @@ public class ViaBossBar implements BossBar {
} }
@Override @Override
public float getHealth() { public BossColor getColor() {
return health; return color;
} }
@Override @Override
@ -72,11 +70,6 @@ public class ViaBossBar implements BossBar {
sendPacket(UpdateAction.UPDATE_STYLE); sendPacket(UpdateAction.UPDATE_STYLE);
} }
@Override
public BossColor getColor() {
return color;
}
@Override @Override
public void setStyle(BossStyle style) { public void setStyle(BossStyle style) {
Validate.notNull(style, "Style cannot be null"); Validate.notNull(style, "Style cannot be null");
@ -84,11 +77,6 @@ public class ViaBossBar implements BossBar {
sendPacket(UpdateAction.UPDATE_STYLE); sendPacket(UpdateAction.UPDATE_STYLE);
} }
@Override
public BossStyle getStyle() {
return style;
}
@Override @Override
public void addPlayer(Player player) { public void addPlayer(Player player) {
if (player != null && !players.contains(player.getUniqueId())) { if (player != null && !players.contains(player.getUniqueId())) {
@ -210,6 +198,8 @@ public class ViaBossBar implements BossBar {
return OutgoingTransformer.fixJson(text); return OutgoingTransformer.fixJson(text);
} }
@RequiredArgsConstructor
@Getter
private enum UpdateAction { private enum UpdateAction {
ADD(0), ADD(0),
REMOVE(1), REMOVE(1),
@ -219,13 +209,5 @@ public class ViaBossBar implements BossBar {
UPDATE_FLAGS(5); UPDATE_FLAGS(5);
private final int id; private final int id;
UpdateAction(int id) {
this.id = id;
}
public int getId() {
return id;
}
} }
} }

Datei anzeigen

@ -1,20 +1,19 @@
package us.myles.ViaVersion.chunks; package us.myles.ViaVersion.chunks;
import lombok.Getter;
@Getter
public class ByteWriter { public class ByteWriter {
private final byte[] bytes;
private final byte[] output;
private int byteIndex; private int byteIndex;
private int bitIndex; private int bitIndex;
public ByteWriter(int size) { public ByteWriter(int size) {
this.bytes = new byte[size]; this.output = new byte[size];
this.byteIndex = 0; this.byteIndex = 0;
this.bitIndex = 0; this.bitIndex = 0;
} }
public byte[] getOutput() {
return this.bytes;
}
public void writeFullByte(int b){ public void writeFullByte(int b){
writeByte(b, 8); writeByte(b, 8);
} }
@ -28,8 +27,8 @@ public class ByteWriter {
int space = (8 - bitIndex); int space = (8 - bitIndex);
int written = space > length ? length : space; int written = space > length ? length : space;
System.out.println("Written is " + written); System.out.println("Written is " + written);
bytes[byteIndex] = (byte) (current | (extractRange(byteB, 0, written) >> (bitIndex - 1))); output[byteIndex] = (byte) (current | (extractRange(byteB, 0, written) >> (bitIndex - 1)));
System.out.println("output value: " + bytes[byteIndex]); System.out.println("output value: " + output[byteIndex]);
this.bitIndex += length; this.bitIndex += length;
if(this.bitIndex >= 8) { if(this.bitIndex >= 8) {
this.byteIndex += 1; this.byteIndex += 1;
@ -37,7 +36,7 @@ public class ByteWriter {
// write remaining into this // write remaining into this
System.out.println("Writing from " + written + " to " + (written + bitIndex)); System.out.println("Writing from " + written + " to " + (written + bitIndex));
System.out.println("Value: " + extractRange(byteB, written, written + bitIndex)); System.out.println("Value: " + extractRange(byteB, written, written + bitIndex));
bytes[byteIndex] = (byte) (extractRange(byteB, written, written + bitIndex) << written); output[byteIndex] = (byte) (extractRange(byteB, written, written + bitIndex) << written);
} }
} }
@ -45,8 +44,8 @@ public class ByteWriter {
return (byte) ((in >> begin) & ((1 << (end - begin)) - 1)); return (byte) ((in >> begin) & ((1 << (end - begin)) - 1));
} }
public byte getCurrentByte() { public byte getCurrentByte() {
if(byteIndex == bytes.length) throw new RuntimeException("ByteWriter overflow!"); if (byteIndex == output.length) throw new RuntimeException("ByteWriter overflow!");
return bytes[byteIndex]; return output[byteIndex];
} }
} }

Datei anzeigen

@ -1,15 +1,13 @@
package us.myles.ViaVersion.chunks; package us.myles.ViaVersion.chunks;
import lombok.RequiredArgsConstructor;
import java.util.BitSet; import java.util.BitSet;
@RequiredArgsConstructor
public class MagicBitSet extends BitSet { public class MagicBitSet extends BitSet {
private final int initLength; private final int initLength;
public MagicBitSet(int nbits) {
super(nbits);
this.initLength = nbits;
}
public int getTrueLength() { public int getTrueLength() {
return length() == 0 ? initLength : length(); return length() == 0 ? initLength : length();
} }

Datei anzeigen

@ -1,19 +1,14 @@
package us.myles.ViaVersion.chunks; package us.myles.ViaVersion.chunks;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
public class PacketChunk { public class PacketChunk {
private PacketChunkData[] chunkData; private PacketChunkData[] chunkData;
private byte[] biomeData; private byte[] biomeData;
public PacketChunk(PacketChunkData[] chunkData, byte[] biomeData) {
this.chunkData = chunkData;
this.biomeData = biomeData;
}
public PacketChunkData[] getChunkData() {
return chunkData;
}
public byte[] getBiomeData() {
return biomeData;
}
} }

Datei anzeigen

@ -1,5 +1,6 @@
package us.myles.ViaVersion.commands; package us.myles.ViaVersion.commands;
import lombok.RequiredArgsConstructor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
@ -14,12 +15,11 @@ import java.util.List;
/** /**
* Created by fillefilip8 on 2016-03-03. * Created by fillefilip8 on 2016-03-03.
*/ */
@RequiredArgsConstructor
public class ViaVersionCommand implements CommandExecutor { public class ViaVersionCommand implements CommandExecutor {
private final ViaVersionPlugin plugin; private final ViaVersionPlugin plugin;
public ViaVersionCommand(ViaVersionPlugin plugin) {
this.plugin = plugin;
}
@Override @Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
@ -32,8 +32,8 @@ public class ViaVersionCommand implements CommandExecutor {
sender.sendMessage(color("&2/viaversion dontbugme &7- &6Toggle checking for updates.")); sender.sendMessage(color("&2/viaversion dontbugme &7- &6Toggle checking for updates."));
} else if (args.length == 1) { } else if (args.length == 1) {
if (args[0].equalsIgnoreCase("list")) { if (args[0].equalsIgnoreCase("list")) {
List<String> portedPlayers = new ArrayList<String>(); List<String> portedPlayers = new ArrayList<>();
List<String> normalPlayers = new ArrayList<String>(); List<String> normalPlayers = new ArrayList<>();
for (Player p : Bukkit.getOnlinePlayers()) { for (Player p : Bukkit.getOnlinePlayers()) {
if (ViaVersion.getInstance().isPorted(p)) { if (ViaVersion.getInstance().isPorted(p)) {
portedPlayers.add(p.getName()); portedPlayers.add(p.getName());

Datei anzeigen

@ -11,6 +11,7 @@ import us.myles.ViaVersion.util.PacketUtil;
import java.util.List; import java.util.List;
public class ViaDecodeHandler extends ByteToMessageDecoder { public class ViaDecodeHandler extends ByteToMessageDecoder {
private final IncomingTransformer incomingTransformer; private final IncomingTransformer incomingTransformer;
private final ByteToMessageDecoder minecraftDecoder; private final ByteToMessageDecoder minecraftDecoder;
private final ConnectionInfo info; private final ConnectionInfo info;

Datei anzeigen

@ -5,8 +5,6 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder; import io.netty.handler.codec.MessageToByteEncoder;
import us.myles.ViaVersion.CancelException; import us.myles.ViaVersion.CancelException;
import us.myles.ViaVersion.ConnectionInfo; import us.myles.ViaVersion.ConnectionInfo;
import us.myles.ViaVersion.ViaVersionPlugin;
import us.myles.ViaVersion.api.ViaVersion;
import us.myles.ViaVersion.transformers.OutgoingTransformer; import us.myles.ViaVersion.transformers.OutgoingTransformer;
import us.myles.ViaVersion.util.PacketUtil; import us.myles.ViaVersion.util.PacketUtil;
import us.myles.ViaVersion.util.ReflectionUtil; import us.myles.ViaVersion.util.ReflectionUtil;
@ -26,6 +24,7 @@ public class ViaEncodeHandler extends MessageToByteEncoder {
} }
@Override @Override
protected void encode(final ChannelHandlerContext ctx, Object o, final ByteBuf bytebuf) throws Exception { protected void encode(final ChannelHandlerContext ctx, Object o, final ByteBuf bytebuf) throws Exception {
// handle the packet type // handle the packet type
@ -52,15 +51,7 @@ public class ViaEncodeHandler extends MessageToByteEncoder {
Object chunk = ReflectionUtil.nms("World").getDeclaredMethod("getChunkAt", int.class, int.class).invoke(world, x, z); Object chunk = ReflectionUtil.nms("World").getDeclaredMethod("getChunkAt", int.class, int.class).invoke(world, x, z);
Object packet = constructor.newInstance(chunk, true, 65535); Object packet = constructor.newInstance(chunk, true, 65535);
ctx.pipeline().writeAndFlush(packet); ctx.pipeline().writeAndFlush(packet);
} catch (InstantiationException e) { } catch (InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException | NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }

Datei anzeigen

@ -10,6 +10,7 @@ import us.myles.ViaVersion.ConnectionInfo;
import java.lang.reflect.Method; import java.lang.reflect.Method;
public class ViaVersionInitializer extends ChannelInitializer<SocketChannel> { public class ViaVersionInitializer extends ChannelInitializer<SocketChannel> {
private final ChannelInitializer<SocketChannel> oldInit; private final ChannelInitializer<SocketChannel> oldInit;
private Method method; private Method method;

Datei anzeigen

@ -2,6 +2,7 @@ package us.myles.ViaVersion.listeners;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import lombok.RequiredArgsConstructor;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.CommandBlock; import org.bukkit.block.CommandBlock;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -19,12 +20,10 @@ import us.myles.ViaVersion.util.ReflectionUtil;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@RequiredArgsConstructor
public class CommandBlockListener implements Listener { public class CommandBlockListener implements Listener {
private final ViaVersionPlugin plugin;
public CommandBlockListener(ViaVersionPlugin plugin) { private final ViaVersionPlugin plugin;
this.plugin = plugin;
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onJoin(final PlayerJoinEvent e) { public void onJoin(final PlayerJoinEvent e) {

Datei anzeigen

@ -1,7 +1,9 @@
package us.myles.ViaVersion.metadata; package us.myles.ViaVersion.metadata;
import lombok.Getter;
import org.bukkit.entity.*; import org.bukkit.entity.*;
@Getter
public enum MetaIndex { public enum MetaIndex {
// entity // entity
@ -144,26 +146,6 @@ public enum MetaIndex {
this.newType = newType; this.newType = newType;
} }
public int getNewIndex() {
return newIndex;
}
public NewType getNewType() {
return newType;
}
public Type getOldType() {
return oldType;
}
public int getIndex() {
return index;
}
public Class<?> getApplicableClass() {
return this.clazz;
}
public static MetaIndex getIndex(EntityType type, int index) { public static MetaIndex getIndex(EntityType type, int index) {
Class<? extends org.bukkit.entity.Entity> entityClass = type.getEntityClass(); Class<? extends org.bukkit.entity.Entity> entityClass = type.getEntityClass();
if (entityClass == null) { if (entityClass == null) {
@ -192,5 +174,9 @@ public enum MetaIndex {
} }
return null; return null;
} }
public Class<?> getApplicableClass() {
return this.clazz;
}
} }

Datei anzeigen

@ -1,6 +1,8 @@
package us.myles.ViaVersion.metadata; package us.myles.ViaVersion.metadata;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.util.EulerAngle; import org.bukkit.util.EulerAngle;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
@ -10,7 +12,6 @@ import us.myles.ViaVersion.transformers.OutgoingTransformer;
import us.myles.ViaVersion.util.PacketUtil; import us.myles.ViaVersion.util.PacketUtil;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -19,9 +20,7 @@ public class MetadataRewriter {
public static void writeMetadata1_9(EntityType type, List<Entry> list, ByteBuf output) { public static void writeMetadata1_9(EntityType type, List<Entry> list, ByteBuf output) {
short id = -1; short id = -1;
int data = -1; int data = -1;
Iterator<Entry> iterator = list.iterator(); for (Entry entry : list) {
while (iterator.hasNext()) {
Entry entry = iterator.next(); //
MetaIndex metaIndex = entry.index; MetaIndex metaIndex = entry.index;
try { try {
if (metaIndex.getNewType() != NewType.Discontinued) { if (metaIndex.getNewType() != NewType.Discontinued) {
@ -34,7 +33,7 @@ public class MetadataRewriter {
case Byte: case Byte:
// convert from int, byte // convert from int, byte
if (metaIndex.getOldType() == Type.Byte) { if (metaIndex.getOldType() == Type.Byte) {
output.writeByte(((Byte) value).byteValue()); output.writeByte((Byte) value);
} }
if (metaIndex.getOldType() == Type.Int) { if (metaIndex.getOldType() == Type.Int) {
output.writeByte(((Integer) value).byteValue()); output.writeByte(((Integer) value).byteValue());
@ -51,15 +50,15 @@ public class MetadataRewriter {
} }
output.writeBoolean(toWrite != null); output.writeBoolean(toWrite != null);
if (toWrite != null) if (toWrite != null)
PacketUtil.writeUUID((UUID) toWrite, output); PacketUtil.writeUUID(toWrite, output);
break; break;
case BlockID: case BlockID:
// if we have both sources :)) // if we have both sources :))
if (metaIndex.getOldType() == Type.Byte) { if (metaIndex.getOldType() == Type.Byte) {
data = ((Byte) value).byteValue(); data = (Byte) value;
} }
if (metaIndex.getOldType() == Type.Short) { if (metaIndex.getOldType() == Type.Short) {
id = ((Short) value).shortValue(); id = (Short) value;
} }
if (id != -1 && data != -1) { if (id != -1 && data != -1) {
int combined = id << 4 | data; int combined = id << 4 | data;
@ -77,20 +76,20 @@ public class MetadataRewriter {
PacketUtil.writeVarInt(((Short) value).intValue(), output); PacketUtil.writeVarInt(((Short) value).intValue(), output);
} }
if (metaIndex.getOldType() == Type.Int) { if (metaIndex.getOldType() == Type.Int) {
PacketUtil.writeVarInt(((Integer) value).intValue(), output); PacketUtil.writeVarInt((Integer) value, output);
} }
break; break;
case Float: case Float:
output.writeFloat(((Float) value).floatValue()); output.writeFloat((Float) value);
break; break;
case String: case String:
PacketUtil.writeString((String) value, output); PacketUtil.writeString((String) value, output);
break; break;
case Boolean: case Boolean:
if (metaIndex == MetaIndex.AGEABLE_AGE) if (metaIndex == MetaIndex.AGEABLE_AGE)
output.writeBoolean(((Byte) value).byteValue() < 0); output.writeBoolean((Byte) value < 0);
else else
output.writeBoolean(((Byte) value).byteValue() != 0); output.writeBoolean((Byte) value != 0);
break; break;
case Slot: case Slot:
ItemStack item = (ItemStack) value; ItemStack item = (ItemStack) value;
@ -186,7 +185,9 @@ public class MetadataRewriter {
return entries; return entries;
} }
public static class Entry { @Getter
@Setter
public static final class Entry {
private final int oldID; private final int oldID;
private MetaIndex index; private MetaIndex index;

Datei anzeigen

@ -1,5 +1,10 @@
package us.myles.ViaVersion.metadata; package us.myles.ViaVersion.metadata;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Getter
public enum NewType { public enum NewType {
Byte(0), Byte(0),
VarInt(1), VarInt(1),
@ -15,13 +20,7 @@ public enum NewType {
OptUUID(11), OptUUID(11),
BlockID(12), BlockID(12),
Discontinued(99); Discontinued(99);
private final int typeID; private final int typeID;
NewType(int typeID){
this.typeID = typeID;
}
public int getTypeID() {
return typeID;
}
} }

Datei anzeigen

@ -1,5 +1,10 @@
package us.myles.ViaVersion.metadata; package us.myles.ViaVersion.metadata;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Getter
public enum Type { public enum Type {
Byte(0), Byte(0),
Short(1), Short(1),
@ -11,14 +16,6 @@ public enum Type {
Rotation(7); Rotation(7);
private final int typeID; private final int typeID;
Type(int typeID){
this.typeID = typeID;
}
public int getTypeID() {
return typeID;
}
public static Type byId(int id) { public static Type byId(int id) {
return values()[id]; return values()[id];
} }

Datei anzeigen

@ -17,182 +17,10 @@ import java.util.Map;
public class ItemSlotRewriter { public class ItemSlotRewriter {
public static void rewrite1_9To1_8(ByteBuf input, ByteBuf output) throws CancelException { private static final Map<String, Integer> ENTTIY_NAME_TO_ID = new HashMap<>();
try { private static final Map<Integer, String> ENTTIY_ID_TO_NAME = new HashMap<>();
ItemStack item = readItemStack(input); private static final Map<String, Integer> POTION_NAME_TO_ID = new HashMap<>();
fixIdsFrom1_9To1_8(item); private static final Map<Integer, String> POTION_ID_TO_NAME = new HashMap<>();
writeItemStack(item, output);
} catch (Exception e) {
System.out.println("Error while rewriting an item slot.");
e.printStackTrace();
throw new CancelException();
}
}
public static void rewrite1_8To1_9(ByteBuf input, ByteBuf output) throws CancelException {
try {
ItemStack item = readItemStack(input);
fixIdsFrom1_8To1_9(item);
writeItemStack(item, output);
} catch (Exception e) {
System.out.println("Error while rewriting an item slot.");
e.printStackTrace();
throw new CancelException();
}
}
public static void fixIdsFrom1_9To1_8(ItemStack item) {
if (item != null) {
if (item.id == Material.MONSTER_EGG.getId() && item.data == 0) {
CompoundTag tag = item.tag;
int data = 0;
if (tag != null && tag.get("EntityTag") instanceof CompoundTag) {
CompoundTag entityTag = tag.get("EntityTag");
if (entityTag.get("id") instanceof StringTag) {
StringTag id = entityTag.get("id");
if (ENTTIY_NAME_TO_ID.containsKey(id.getValue()))
data = ENTTIY_NAME_TO_ID.get(id.getValue());
}
}
item.tag = null;
item.data = (short) data;
}
if (item.id == Material.POTION.getId()) {
CompoundTag tag = item.tag;
int data = 0;
if (tag != null && tag.get("Potion") instanceof StringTag) {
StringTag potion = tag.get("Potion");
String potionName = potion.getValue().replace("minecraft:", "");
if (POTION_NAME_TO_ID.containsKey(potionName)) {
data = POTION_NAME_TO_ID.get(potionName);
}
}
item.tag = null;
item.data = (short) data;
}
if (item.id == 438) {
CompoundTag tag = item.tag;
int data = 0;
item.id = (short) Material.POTION.getId();
if (tag != null && tag.get("Potion") instanceof StringTag) {
StringTag potion = tag.get("Potion");
String potionName = potion.getValue().replace("minecraft:", "");
if (POTION_NAME_TO_ID.containsKey(potionName)) {
data = POTION_NAME_TO_ID.get(potionName) + 8192;
}
}
item.tag = null;
item.data = (short) data;
}
}
}
public static void fixIdsFrom1_8To1_9(ItemStack item) {
if (item != null) {
if (item.id == Material.MONSTER_EGG.getId() && item.data != 0) {
CompoundTag tag = item.tag;
if (tag == null) {
tag = new CompoundTag("tag");
}
CompoundTag entityTag = new CompoundTag("EntityTag");
if (ENTTIY_ID_TO_NAME.containsKey(Integer.valueOf(item.data))) {
StringTag id = new StringTag("id", ENTTIY_ID_TO_NAME.get(Integer.valueOf(item.data)));
entityTag.put(id);
tag.put(entityTag);
}
item.tag = tag;
item.data = 0;
}
if (item.id == Material.POTION.getId()) {
CompoundTag tag = item.tag;
if (tag == null) {
tag = new CompoundTag("tag");
}
if (item.data >= 16384) {
item.id = 438; // splash id
item.data = (short) (item.data - 8192);
}
if (POTION_ID_TO_NAME.containsKey(Integer.valueOf(item.data))) {
String name = POTION_ID_TO_NAME.get(Integer.valueOf(item.data));
StringTag potion = new StringTag("Potion", "minecraft:" + name);
tag.put(potion);
}
item.tag = tag;
item.data = 0;
}
if (item.id == Material.WRITTEN_BOOK.getId()) {
CompoundTag tag = item.tag;
if (tag == null) {
tag = new CompoundTag("tag");
}
ListTag pages = tag.get("pages");
if (pages == null) {
pages = new ListTag("pages", Collections.<Tag>singletonList(new StringTag(OutgoingTransformer.fixJson(""))));
tag.put(pages);
item.tag = tag;
return;
}
for (int i = 0; i < pages.size(); i++) {
if (!(pages.get(i) instanceof StringTag))
continue;
StringTag page = pages.get(i);
page.setValue(OutgoingTransformer.fixJson(page.getValue()));
}
item.tag = tag;
}
}
}
public static ItemStack readItemStack(ByteBuf input) throws IOException {
short id = input.readShort();
if (id < 0) {
return null;
} else {
ItemStack item = new ItemStack();
item.id = id;
item.amount = input.readByte();
item.data = input.readShort();
item.tag = PacketUtil.readNBT(input);
return item;
}
}
public static void writeItemStack(ItemStack item, ByteBuf output) throws IOException {
if (item == null) {
output.writeShort(-1);
} else {
output.writeShort(item.id);
output.writeByte(item.amount);
output.writeShort(item.data);
PacketUtil.writeNBT(output, item.tag);
}
}
public static class ItemStack {
public short id;
public byte amount;
public short data;
public CompoundTag tag;
public static ItemStack fromBukkit(org.bukkit.inventory.ItemStack stack) {
if(stack == null) return null;
ItemStack item = new ItemStack();
item.id = (short) stack.getTypeId();
item.amount = (byte) stack.getAmount();
item.data = stack.getData().getData();
// TODO: nbt
return item;
}
}
private static Map<String, Integer> ENTTIY_NAME_TO_ID = new HashMap<>();
private static Map<Integer, String> ENTTIY_ID_TO_NAME = new HashMap<>();
private static Map<String, Integer> POTION_NAME_TO_ID = new HashMap<>();
private static Map<Integer, String> POTION_ID_TO_NAME = new HashMap<>();
static { static {
/* Entities */ /* Entities */
@ -311,6 +139,159 @@ public class ItemSlotRewriter {
} }
public static void rewrite1_9To1_8(ByteBuf input, ByteBuf output) throws CancelException {
try {
ItemStack item = readItemStack(input);
fixIdsFrom1_9To1_8(item);
writeItemStack(item, output);
} catch (Exception e) {
System.out.println("Error while rewriting an item slot.");
e.printStackTrace();
throw new CancelException();
}
}
public static void rewrite1_8To1_9(ByteBuf input, ByteBuf output) throws CancelException {
try {
ItemStack item = readItemStack(input);
fixIdsFrom1_8To1_9(item);
writeItemStack(item, output);
} catch (Exception e) {
System.out.println("Error while rewriting an item slot.");
e.printStackTrace();
throw new CancelException();
}
}
public static void fixIdsFrom1_9To1_8(ItemStack item) {
if (item != null) {
if (item.id == Material.MONSTER_EGG.getId() && item.data == 0) {
CompoundTag tag = item.tag;
int data = 0;
if (tag != null && tag.get("EntityTag") instanceof CompoundTag) {
CompoundTag entityTag = tag.get("EntityTag");
if (entityTag.get("id") instanceof StringTag) {
StringTag id = entityTag.get("id");
if (ENTTIY_NAME_TO_ID.containsKey(id.getValue()))
data = ENTTIY_NAME_TO_ID.get(id.getValue());
}
}
item.tag = null;
item.data = (short) data;
}
if (item.id == Material.POTION.getId()) {
CompoundTag tag = item.tag;
int data = 0;
if (tag != null && tag.get("Potion") instanceof StringTag) {
StringTag potion = tag.get("Potion");
String potionName = potion.getValue().replace("minecraft:", "");
if (POTION_NAME_TO_ID.containsKey(potionName)) {
data = POTION_NAME_TO_ID.get(potionName);
}
}
item.tag = null;
item.data = (short) data;
}
if (item.id == 438) {
CompoundTag tag = item.tag;
int data = 0;
item.id = (short) Material.POTION.getId();
if (tag != null && tag.get("Potion") instanceof StringTag) {
StringTag potion = tag.get("Potion");
String potionName = potion.getValue().replace("minecraft:", "");
if (POTION_NAME_TO_ID.containsKey(potionName)) {
data = POTION_NAME_TO_ID.get(potionName) + 8192;
}
}
item.tag = null;
item.data = (short) data;
}
}
}
public static void fixIdsFrom1_8To1_9(ItemStack item) {
if (item != null) {
if (item.id == Material.MONSTER_EGG.getId() && item.data != 0) {
CompoundTag tag = item.tag;
if (tag == null) {
tag = new CompoundTag("tag");
}
CompoundTag entityTag = new CompoundTag("EntityTag");
if (ENTTIY_ID_TO_NAME.containsKey((int) item.data)) {
StringTag id = new StringTag("id", ENTTIY_ID_TO_NAME.get((int) item.data));
entityTag.put(id);
tag.put(entityTag);
}
item.tag = tag;
item.data = 0;
}
if (item.id == Material.POTION.getId()) {
CompoundTag tag = item.tag;
if (tag == null) {
tag = new CompoundTag("tag");
}
if (item.data >= 16384) {
item.id = 438; // splash id
item.data = (short) (item.data - 8192);
}
if (POTION_ID_TO_NAME.containsKey((int) item.data)) {
String name = POTION_ID_TO_NAME.get((int) item.data);
StringTag potion = new StringTag("Potion", "minecraft:" + name);
tag.put(potion);
}
item.tag = tag;
item.data = 0;
}
if (item.id == Material.WRITTEN_BOOK.getId()) {
CompoundTag tag = item.tag;
if (tag == null) {
tag = new CompoundTag("tag");
}
ListTag pages = tag.get("pages");
if (pages == null) {
pages = new ListTag("pages", Collections.<Tag>singletonList(new StringTag(OutgoingTransformer.fixJson(""))));
tag.put(pages);
item.tag = tag;
return;
}
for (int i = 0; i < pages.size(); i++) {
if (!(pages.get(i) instanceof StringTag))
continue;
StringTag page = pages.get(i);
page.setValue(OutgoingTransformer.fixJson(page.getValue()));
}
item.tag = tag;
}
}
}
public static ItemStack readItemStack(ByteBuf input) throws IOException {
short id = input.readShort();
if (id < 0) {
return null;
} else {
ItemStack item = new ItemStack();
item.id = id;
item.amount = input.readByte();
item.data = input.readShort();
item.tag = PacketUtil.readNBT(input);
return item;
}
}
public static void writeItemStack(ItemStack item, ByteBuf output) throws IOException {
if (item == null) {
output.writeShort(-1);
} else {
output.writeShort(item.id);
output.writeByte(item.amount);
output.writeShort(item.data);
PacketUtil.writeNBT(output, item.tag);
}
}
private static void registerEntity(Integer id, String name) { private static void registerEntity(Integer id, String name) {
ENTTIY_ID_TO_NAME.put(id, name); ENTTIY_ID_TO_NAME.put(id, name);
ENTTIY_NAME_TO_ID.put(name, id); ENTTIY_NAME_TO_ID.put(name, id);
@ -320,4 +301,22 @@ public class ItemSlotRewriter {
POTION_ID_TO_NAME.put(id, name); POTION_ID_TO_NAME.put(id, name);
POTION_NAME_TO_ID.put(name, id); POTION_NAME_TO_ID.put(name, id);
} }
public static class ItemStack {
public short id;
public byte amount;
public short data;
public CompoundTag tag;
public static ItemStack fromBukkit(org.bukkit.inventory.ItemStack stack) {
if(stack == null) return null;
ItemStack item = new ItemStack();
item.id = (short) stack.getTypeId();
item.amount = (byte) stack.getAmount();
item.data = stack.getData().getData();
// TODO: nbt
return item;
}
}
} }

Datei anzeigen

@ -1,5 +1,10 @@
package us.myles.ViaVersion.sounds; package us.myles.ViaVersion.sounds;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Getter
public enum SoundCategory { public enum SoundCategory {
@ -14,20 +19,7 @@ public enum SoundCategory {
AMBIENT("ambient", 8), AMBIENT("ambient", 8),
VOICE("voice", 9); VOICE("voice", 9);
private String name; private final String name;
private int id; private final int id;
SoundCategory(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
} }

Datei anzeigen

@ -1,5 +1,8 @@
package us.myles.ViaVersion.sounds; package us.myles.ViaVersion.sounds;
import lombok.Getter;
@Getter
public enum SoundEffect { public enum SoundEffect {
MOB_HORSE_ZOMBIE_IDLE("mob.horse.zombie.idle", "entity.zombie_horse.ambient", SoundCategory.NEUTRAL), MOB_HORSE_ZOMBIE_IDLE("mob.horse.zombie.idle", "entity.zombie_horse.ambient", SoundCategory.NEUTRAL),
@ -249,21 +252,21 @@ public enum SoundEffect {
MUSIC_GAME_END_CREDITS("music.game.end.credits", "music.credits", SoundCategory.MUSIC), MUSIC_GAME_END_CREDITS("music.game.end.credits", "music.credits", SoundCategory.MUSIC),
MUSIC_GAME_CREATIVE("music.game.creative", "music.creative", SoundCategory.MUSIC); MUSIC_GAME_CREATIVE("music.game.creative", "music.creative", SoundCategory.MUSIC);
private String name; private final String name;
private String newname; private final String newName;
private SoundCategory cat; private final SoundCategory category;
private boolean breaksound; private final boolean breaksound;
SoundEffect(String name, String newname, SoundCategory cat) { SoundEffect(String name, String newname, SoundCategory cat) {
this.cat = cat; this.category = cat;
this.newname = newname; this.newName = newname;
this.name = name; this.name = name;
this.breaksound = name.startsWith("dig."); this.breaksound = name.startsWith("dig.");
} }
SoundEffect(String name, String newname, SoundCategory cat, boolean shouldIgnore) { SoundEffect(String name, String newname, SoundCategory cat, boolean shouldIgnore) {
this.cat = cat; this.category = cat;
this.newname = newname; this.newName = newname;
this.name = name; this.name = name;
this.breaksound = name.startsWith("dig.") || shouldIgnore; this.breaksound = name.startsWith("dig.") || shouldIgnore;
} }
@ -277,20 +280,4 @@ public enum SoundEffect {
return null; return null;
} }
public String getNewName() {
return newname;
}
public String getName() {
return name;
}
public SoundCategory getCategory() {
return cat;
}
public boolean isBreakPlaceSound() {
return breaksound;
}
} }

Datei anzeigen

@ -188,7 +188,8 @@ public class IncomingTransformer {
byte[] b = new byte[input.readableBytes()]; byte[] b = new byte[input.readableBytes()];
input.readBytes(b); input.readBytes(b);
// patch books // patch books
if (name.equals("MC|BSign")) { switch (name) {
case "MC|BSign": {
ByteBuf in = Unpooled.wrappedBuffer(b); ByteBuf in = Unpooled.wrappedBuffer(b);
try { try {
ItemSlotRewriter.ItemStack stack = ItemSlotRewriter.readItemStack(in); ItemSlotRewriter.ItemStack stack = ItemSlotRewriter.readItemStack(in);
@ -199,7 +200,8 @@ public class IncomingTransformer {
e.printStackTrace(); e.printStackTrace();
} }
return; return;
} else if (name.equals("MC|AutoCmd")) { }
case "MC|AutoCmd": {
ByteBuf in = Unpooled.wrappedBuffer(b); ByteBuf in = Unpooled.wrappedBuffer(b);
int x = in.readInt(); int x = in.readInt();
int y = in.readInt(); int y = in.readInt();
@ -217,11 +219,13 @@ public class IncomingTransformer {
PacketUtil.writeString(command, output); PacketUtil.writeString(command, output);
output.writeBoolean(flag); output.writeBoolean(flag);
return; return;
} else if (name.equals("MC|AdvCmd")) { }
case "MC|AdvCmd":
output.clear(); output.clear();
PacketUtil.writeVarInt(PacketType.PLAY_PLUGIN_MESSAGE_REQUEST.getPacketID(), output); PacketUtil.writeVarInt(PacketType.PLAY_PLUGIN_MESSAGE_REQUEST.getPacketID(), output);
PacketUtil.writeString("MC|AdvCdm", output); PacketUtil.writeString("MC|AdvCdm", output);
output.writeBytes(b); output.writeBytes(b);
break;
} }
output.writeBytes(b); output.writeBytes(b);
} }

Datei anzeigen

@ -33,20 +33,44 @@ import java.util.*;
import static us.myles.ViaVersion.util.PacketUtil.*; import static us.myles.ViaVersion.util.PacketUtil.*;
public class OutgoingTransformer { public class OutgoingTransformer {
private final ConnectionInfo info;
private final ViaVersionPlugin plugin = (ViaVersionPlugin) ViaVersion.getInstance(); private final ViaVersionPlugin plugin = (ViaVersionPlugin) ViaVersion.getInstance();
private final ConnectionInfo info;
private final Map<Integer, UUID> uuidMap = new HashMap<>();
private final Map<Integer, EntityType> clientEntityTypes = new HashMap<>();
private final Map<Integer, Integer> vehicleMap = new HashMap<>();
private boolean cancel = false; private boolean cancel = false;
private boolean autoTeam = false; private boolean autoTeam = false;
private Map<Integer, UUID> uuidMap = new HashMap<Integer, UUID>();
private Map<Integer, EntityType> clientEntityTypes = new HashMap<Integer, EntityType>();
private Map<Integer, Integer> vehicleMap = new HashMap<>();
public OutgoingTransformer(ConnectionInfo info) { public OutgoingTransformer(ConnectionInfo info) {
this.info = info; this.info = info;
} }
public static String fixJson(String line) {
if (line == null || line.equalsIgnoreCase("null")) {
line = "{\"text\":\"\"}";
} else {
if ((!line.startsWith("\"") || !line.endsWith("\"")) && (!line.startsWith("{") || !line.endsWith("}"))) {
JSONObject obj = new JSONObject();
obj.put("text", line);
return obj.toJSONString();
}
if (line.startsWith("\"") && line.endsWith("\"")) {
line = "{\"text\":" + line + "}";
}
}
try {
new JSONParser().parse(line);
} catch (Exception e) {
System.out.println("Invalid JSON String: \"" + line + "\" Please report this issue to the ViaVersion Github: " + e.getMessage());
return "{\"text\":\"\"}";
}
return line;
}
public void transform(int packetID, ByteBuf input, ByteBuf output) throws CancelException { public void transform(int packetID, ByteBuf input, ByteBuf output) throws CancelException {
if (cancel) { if (cancel) {
throw new CancelException(); throw new CancelException();
@ -75,7 +99,7 @@ public class OutgoingTransformer {
int catid = 0; int catid = 0;
String newname = name; String newname = name;
if (effect != null) { if (effect != null) {
if (effect.isBreakPlaceSound()) { if (effect.isBreaksound()) {
throw new CancelException(); throw new CancelException();
} }
catid = effect.getCategory().getId(); catid = effect.getCategory().getId();
@ -774,28 +798,6 @@ public class OutgoingTransformer {
info.sendRawPacket(buf); info.sendRawPacket(buf);
} }
public static String fixJson(String line) {
if (line == null || line.equalsIgnoreCase("null")) {
line = "{\"text\":\"\"}";
} else {
if ((!line.startsWith("\"") || !line.endsWith("\"")) && (!line.startsWith("{") || !line.endsWith("}"))) {
JSONObject obj = new JSONObject();
obj.put("text", line);
return obj.toJSONString();
}
if (line.startsWith("\"") && line.endsWith("\"")) {
line = "{\"text\":" + line + "}";
}
}
try {
new JSONParser().parse(line);
} catch (Exception e) {
System.out.println("Invalid JSON String: \"" + line + "\" Please report this issue to the ViaVersion Github: " + e.getMessage());
return "{\"text\":\"\"}";
}
return line;
}
private void transformMetadata(int entityID, ByteBuf input, ByteBuf output) throws CancelException { private void transformMetadata(int entityID, ByteBuf input, ByteBuf output) throws CancelException {
EntityType type = clientEntityTypes.get(entityID); EntityType type = clientEntityTypes.get(entityID);
if (type == null) { if (type == null) {

Datei anzeigen

@ -1,17 +1,15 @@
package us.myles.ViaVersion.update; package us.myles.ViaVersion.update;
import lombok.RequiredArgsConstructor;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
@RequiredArgsConstructor
public class UpdateListener implements Listener { public class UpdateListener implements Listener {
private Plugin plugin; private final Plugin plugin;
public UpdateListener(Plugin plugin) {
this.plugin = plugin;
}
@EventHandler @EventHandler
public void onJoin(PlayerJoinEvent e) { public void onJoin(PlayerJoinEvent e) {

Datei anzeigen

@ -9,7 +9,7 @@ public class Version implements Comparable<Version> {
if (value == null) if (value == null)
throw new IllegalArgumentException("Version can not be null"); throw new IllegalArgumentException("Version can not be null");
if (value.matches("^[0-9]+(\\.[0-9]+)*$") == false) if (!value.matches("^[0-9]+(\\.[0-9]+)*$"))
throw new IllegalArgumentException("Invalid version format"); throw new IllegalArgumentException("Invalid version format");
String[] split = value.split("\\."); String[] split = value.split("\\.");
@ -19,16 +19,6 @@ public class Version implements Comparable<Version> {
parts[i] = Integer.parseInt(split[i]); parts[i] = Integer.parseInt(split[i]);
} }
@Override
public String toString() {
String[] split = new String[parts.length];
for (int i = 0; i < parts.length; i += 1)
split[i] = String.valueOf(parts[i]);
return StringUtils.join(split, ".");
}
public static int compare(Version verA, Version verB) { public static int compare(Version verA, Version verB) {
if (verA == verB) return 0; if (verA == verB) return 0;
if (verA == null) return -1; if (verA == null) return -1;
@ -46,18 +36,25 @@ public class Version implements Comparable<Version> {
return 0; return 0;
} }
public static boolean equals(Version verA, Version verB) {
return verA == verB || verA != null && verB != null && compare(verA, verB) == 0;
}
@Override
public String toString() {
String[] split = new String[parts.length];
for (int i = 0; i < parts.length; i += 1)
split[i] = String.valueOf(parts[i]);
return StringUtils.join(split, ".");
}
@Override @Override
public int compareTo(Version that) { public int compareTo(Version that) {
return compare(this, that); return compare(this, that);
} }
public static boolean equals(Version verA, Version verB) {
if (verA == verB) return true;
if (verA == null) return false;
if (verB == null) return false;
return compare(verA, verB) == 0;
}
@Override @Override
public boolean equals(Object that) { public boolean equals(Object that) {
return that instanceof Version && equals(this, (Version) that); return that instanceof Version && equals(this, (Version) that);

Datei anzeigen

@ -3,6 +3,7 @@ package us.myles.ViaVersion.util;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
public class EntityUtil { public class EntityUtil {
public static EntityType getTypeFromID(int typeID, boolean isObject) { public static EntityType getTypeFromID(int typeID, boolean isObject) {
if (isObject) { if (isObject) {
return getObjectFromID(typeID); return getObjectFromID(typeID);

Datei anzeigen

@ -69,12 +69,10 @@ public class PacketUtil {
} }
public static List<Object> callDecode(ByteToMessageDecoder decoder, ChannelHandlerContext ctx, Object input) { public static List<Object> callDecode(ByteToMessageDecoder decoder, ChannelHandlerContext ctx, Object input) {
List<Object> output = new ArrayList<Object>(); List<Object> output = new ArrayList<>();
try { try {
PacketUtil.DECODE_METHOD.invoke(decoder, ctx, input, output); PacketUtil.DECODE_METHOD.invoke(decoder, ctx, input, output);
} catch (IllegalAccessException e) { } catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace(); e.printStackTrace();
} }
return output; return output;
@ -83,9 +81,7 @@ public class PacketUtil {
public static void callEncode(MessageToByteEncoder encoder, ChannelHandlerContext ctx, Object msg, ByteBuf output) { public static void callEncode(MessageToByteEncoder encoder, ChannelHandlerContext ctx, Object msg, ByteBuf output) {
try { try {
PacketUtil.ENCODE_METHOD.invoke(encoder, ctx, msg, output); PacketUtil.ENCODE_METHOD.invoke(encoder, ctx, msg, output);
} catch (IllegalAccessException e) { } catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -169,7 +165,7 @@ public class PacketUtil {
public static List<String> readStringArray(ByteBuf buf) { public static List<String> readStringArray(ByteBuf buf) {
int len = readVarInt(buf); int len = readVarInt(buf);
List<String> ret = new ArrayList<String>(len); List<String> ret = new ArrayList<>(len);
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
ret.add(readString(buf)); ret.add(readString(buf));
} }
@ -258,8 +254,8 @@ public class PacketUtil {
} }
public static void writeLongs(long[] data, ByteBuf output) { public static void writeLongs(long[] data, ByteBuf output) {
for (int index = 0; index < data.length; index++) { for (long aData : data) {
output.writeLong(data[index]); output.writeLong(aData);
} }
} }
@ -336,7 +332,7 @@ public class PacketUtil {
// Data Array Length // Data Array Length
byte[] blockData = convertBlockArray(chunk.getBlocks()); byte[] blockData = convertBlockArray(chunk.getBlocks());
writeVarInt(blockData.length / 8, buffer); // Notchian is divide by 8 writeVarInt((blockData != null ? blockData.length : 0) / 8, buffer); // Notchian is divide by 8
buffer.writeBytes(blockData); buffer.writeBytes(blockData);
// Block Light // Block Light
@ -360,9 +356,8 @@ public class PacketUtil {
} }
private static BitSet append(BitSet base, int index, MagicBitSet toAdd) { private static BitSet append(BitSet base, int index, MagicBitSet toAdd) {
int length = index;
for (int i = 0; i < toAdd.getTrueLength(); i++) { for (int i = 0; i < toAdd.getTrueLength(); i++) {
base.set(length + i, toAdd.get(i)); base.set(index + i, toAdd.get(i));
} }
return base; return base;
} }