Reformat code

This commit is contained in:
sauilitired
2018-08-10 17:01:10 +02:00
parent 02ee1e8fa1
commit 1646cd0f5a
437 changed files with 12795 additions and 14203 deletions

View File

@ -15,18 +15,15 @@ import java.util.List;
public class BukkitChatManager extends ChatManager<FancyMessage> {
@Override
public FancyMessage builder() {
@Override public FancyMessage builder() {
return new FancyMessage("");
}
@Override
public void color(PlotMessage message, String color) {
@Override public void color(PlotMessage message, String color) {
message.$(this).color(ChatColor.getByChar(C.color(color).substring(1)));
}
@Override
public void tooltip(PlotMessage message, PlotMessage... tooltips) {
@Override public void tooltip(PlotMessage message, PlotMessage... tooltips) {
List<FancyMessage> lines = new ArrayList<>();
for (PlotMessage tooltip : tooltips) {
lines.add(tooltip.$(this));
@ -34,18 +31,15 @@ public class BukkitChatManager extends ChatManager<FancyMessage> {
message.$(this).formattedTooltip(lines);
}
@Override
public void command(PlotMessage message, String command) {
@Override public void command(PlotMessage message, String command) {
message.$(this).command(command);
}
@Override
public void text(PlotMessage message, String text) {
@Override public void text(PlotMessage message, String text) {
message.$(this).then(ChatColor.stripColor(text));
}
@Override
public void send(PlotMessage plotMessage, PlotPlayer player) {
@Override public void send(PlotMessage plotMessage, PlotPlayer player) {
if (player instanceof ConsolePlayer || !Settings.Chat.INTERACTIVE) {
player.sendMessage(plotMessage.$(this).toOldMessageFormat());
} else {
@ -53,8 +47,7 @@ public class BukkitChatManager extends ChatManager<FancyMessage> {
}
}
@Override
public void suggest(PlotMessage plotMessage, String command) {
@Override public void suggest(PlotMessage plotMessage, String command) {
plotMessage.$(this).suggest(command);
}

View File

@ -2,61 +2,23 @@ package com.plotsquared.bukkit.util;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.generator.AugmentedUtils;
import com.intellectualcrafters.plot.object.BlockLoc;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.*;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.PlotLoc;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue;
import com.plotsquared.bukkit.object.entity.EntityWrapper;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.Note;
import org.bukkit.SkullType;
import org.bukkit.World;
import org.bukkit.block.Banner;
import org.bukkit.block.Beacon;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.BrewingStand;
import org.bukkit.block.CommandBlock;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.block.Dispenser;
import org.bukkit.block.Dropper;
import org.bukkit.block.Furnace;
import org.bukkit.block.Hopper;
import org.bukkit.block.Jukebox;
import org.bukkit.block.NoteBlock;
import org.bukkit.block.Sign;
import org.bukkit.block.Skull;
import org.bukkit.*;
import org.bukkit.block.*;
import org.bukkit.block.banner.Pattern;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.entity.*;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.Map.Entry;
import java.util.Set;
public class BukkitChunkManager extends ChunkManager {
@ -73,7 +35,8 @@ public class BukkitChunkManager extends ChunkManager {
return 0;
}
public static ContentMap swapChunk(World world1, World world2, Chunk pos1, Chunk pos2, RegionWrapper r1, RegionWrapper r2) {
public static ContentMap swapChunk(World world1, World world2, Chunk pos1, Chunk pos2,
RegionWrapper r1, RegionWrapper r2) {
ContentMap map = new ContentMap();
int relX = r2.minX - r1.minX;
int relZ = r2.minZ - r1.minZ;
@ -127,8 +90,7 @@ public class BukkitChunkManager extends ChunkManager {
return map;
}
@Override
public Set<ChunkLoc> getChunkChunks(String world) {
@Override public Set<ChunkLoc> getChunkChunks(String world) {
Set<ChunkLoc> chunks = super.getChunkChunks(world);
for (Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) {
ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5);
@ -139,13 +101,15 @@ public class BukkitChunkManager extends ChunkManager {
return chunks;
}
@Override
public boolean copyRegion(Location pos1, Location pos2, Location newPos, final Runnable whenDone) {
@Override public boolean copyRegion(Location pos1, Location pos2, Location newPos,
final Runnable whenDone) {
final int relX = newPos.getX() - pos1.getX();
final int relZ = newPos.getZ() - pos1.getZ();
Location pos4 = new Location(newPos.getWorld(), newPos.getX() + relX, 256, newPos.getZ() + relZ);
Location pos4 =
new Location(newPos.getWorld(), newPos.getX() + relX, 256, newPos.getZ() + relZ);
final RegionWrapper region = new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
final RegionWrapper region =
new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
final World oldWorld = Bukkit.getWorld(pos1.getWorld());
final World newWorld = Bukkit.getWorld(newPos.getWorld());
final String newWorldName = newWorld.getName();
@ -153,8 +117,7 @@ public class BukkitChunkManager extends ChunkManager {
final ContentMap map = new ContentMap();
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(newWorldName, false);
ChunkManager.chunkTask(pos1, pos2, new RunnableVal<int[]>() {
@Override
public void run(int[] value) {
@Override public void run(int[] value) {
int bx = value[2];
int bz = value[3];
int tx = value[4];
@ -171,8 +134,7 @@ public class BukkitChunkManager extends ChunkManager {
}
}
}, new Runnable() {
@Override
public void run() {
@Override public void run() {
for (Entry<PlotLoc, PlotBlock[]> entry : map.allBlocks.entrySet()) {
PlotLoc loc = entry.getKey();
PlotBlock[] blocks = entry.getValue();
@ -185,8 +147,7 @@ public class BukkitChunkManager extends ChunkManager {
}
queue.enqueue();
GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override
public void run() {
@Override public void run() {
map.restoreBlocks(newWorld, 0, 0);
map.restoreEntities(newWorld, relX, relZ);
TaskManager.runTask(whenDone);
@ -197,8 +158,8 @@ public class BukkitChunkManager extends ChunkManager {
return true;
}
@Override
public boolean regenerateRegion(final Location pos1, final Location pos2, final boolean ignoreAugment, final Runnable whenDone) {
@Override public boolean regenerateRegion(final Location pos1, final Location pos2,
final boolean ignoreAugment, final Runnable whenDone) {
final String world = pos1.getWorld();
final int p1x = pos1.getX();
@ -219,8 +180,7 @@ public class BukkitChunkManager extends ChunkManager {
}
final World worldObj = Bukkit.getWorld(world);
TaskManager.runTask(new Runnable() {
@Override
public void run() {
@Override public void run() {
long start = System.currentTimeMillis();
while (!chunks.isEmpty() && System.currentTimeMillis() - start < 5) {
final ChunkLoc chunk = chunks.remove(0);
@ -235,11 +195,11 @@ public class BukkitChunkManager extends ChunkManager {
continue;
}
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
RegionWrapper currentPlotClear = new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
RegionWrapper currentPlotClear =
new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) {
AugmentedUtils.bypass(ignoreAugment, new Runnable() {
@Override
public void run() {
@Override public void run() {
queue.regenChunkSafe(chunk.x, chunk.z);
}
});
@ -306,11 +266,9 @@ public class BukkitChunkManager extends ChunkManager {
}
map.saveEntitiesOut(chunkObj, currentPlotClear);
AugmentedUtils.bypass(ignoreAugment, new Runnable() {
@Override
public void run() {
@Override public void run() {
setChunkInPlotArea(null, new RunnableVal<ScopedLocalBlockQueue>() {
@Override
public void run(ScopedLocalBlockQueue value) {
@Override public void run(ScopedLocalBlockQueue value) {
Location min = value.getMin();
int bx = min.getX();
int bz = min.getZ();
@ -319,7 +277,8 @@ public class BukkitChunkManager extends ChunkManager {
PlotLoc loc = new PlotLoc(bx + x, bz + z);
PlotBlock[] ids = map.allBlocks.get(loc);
if (ids != null) {
for (int y = 0; y < Math.min(128, ids.length); y++) {
for (int y = 0;
y < Math.min(128, ids.length); y++) {
PlotBlock id = ids[y];
if (id != null) {
value.setBlock(x, y, z, id);
@ -327,7 +286,8 @@ public class BukkitChunkManager extends ChunkManager {
value.setBlock(x, y, z, 0, (byte) 0);
}
}
for (int y = Math.min(128, ids.length); y < ids.length; y++) {
for (int y = Math.min(128, ids.length);
y < ids.length; y++) {
PlotBlock id = ids[y];
if (id != null) {
value.setBlock(x, y, z, id);
@ -353,8 +313,7 @@ public class BukkitChunkManager extends ChunkManager {
return true;
}
@Override
public void clearAllEntities(Location pos1, Location pos2) {
@Override public void clearAllEntities(Location pos1, Location pos2) {
String world = pos1.getWorld();
List<Entity> entities = BukkitUtil.getEntities(world);
int bx = pos1.getX();
@ -364,26 +323,24 @@ public class BukkitChunkManager extends ChunkManager {
for (Entity entity : entities) {
if (!(entity instanceof Player)) {
org.bukkit.Location location = entity.getLocation();
if (location.getX() >= bx && location.getX() <= tx && location.getZ() >= bz && location.getZ() <= tz) {
if (location.getX() >= bx && location.getX() <= tx && location.getZ() >= bz
&& location.getZ() <= tz) {
entity.remove();
}
}
}
}
@Override
public boolean loadChunk(String world, ChunkLoc loc, boolean force) {
@Override public boolean loadChunk(String world, ChunkLoc loc, boolean force) {
return BukkitUtil.getWorld(world).getChunkAt(loc.x, loc.z).load(force);
}
@SuppressWarnings("deprecation")
@Override
public void unloadChunk(final String world, final ChunkLoc loc, final boolean save, final boolean safe) {
@SuppressWarnings("deprecation") @Override
public void unloadChunk(final String world, final ChunkLoc loc, final boolean save,
final boolean safe) {
if (!PS.get().isMainThread(Thread.currentThread())) {
TaskManager.runTask(new Runnable() {
@SuppressWarnings("deprecation")
@Override
public void run() {
@SuppressWarnings("deprecation") @Override public void run() {
BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save, safe);
}
});
@ -392,10 +349,12 @@ public class BukkitChunkManager extends ChunkManager {
}
}
@Override
public void swap(Location bot1, Location top1, Location bot2, Location top2, final Runnable whenDone) {
RegionWrapper region1 = new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ());
RegionWrapper region2 = new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ());
@Override public void swap(Location bot1, Location top1, Location bot2, Location top2,
final Runnable whenDone) {
RegionWrapper region1 =
new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ());
RegionWrapper region2 =
new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ());
final World world1 = Bukkit.getWorld(bot1.getWorld());
World world2 = Bukkit.getWorld(bot2.getWorld());
@ -412,8 +371,7 @@ public class BukkitChunkManager extends ChunkManager {
}
}
GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override
public void run() {
@Override public void run() {
for (ContentMap map : maps) {
map.restoreBlocks(world1, 0, 0);
map.restoreEntities(world1, 0, 0);
@ -423,10 +381,10 @@ public class BukkitChunkManager extends ChunkManager {
});
}
@Override
public int[] countEntities(Plot plot) {
@Override public int[] countEntities(Plot plot) {
int[] existing = (int[]) plot.getMeta("EntityCount");
if (existing != null && (System.currentTimeMillis() - (long) plot.getMeta("EntityCountTime") < 1000)) {
if (existing != null && (System.currentTimeMillis() - (long) plot.getMeta("EntityCountTime")
< 1000)) {
return existing;
}
PlotArea area = plot.getArea();
@ -542,7 +500,7 @@ public class BukkitChunkManager extends ChunkManager {
case ARMOR_STAND:
count[5]++;
break;
// misc
// misc
case MINECART:
case MINECART_CHEST:
case MINECART_COMMAND:
@ -705,7 +663,8 @@ public class BukkitChunkManager extends ChunkManager {
}
}
public void saveEntitiesIn(Chunk chunk, RegionWrapper region, int offsetX, int offsetZ, boolean delete) {
public void saveEntitiesIn(Chunk chunk, RegionWrapper region, int offsetX, int offsetZ,
boolean delete) {
for (Entity entity : chunk.getEntities()) {
Location loc = BukkitUtil.getLocation(entity);
int x = loc.getX();
@ -743,26 +702,30 @@ public class BukkitChunkManager extends ChunkManager {
public void restoreBlocks(World world, int xOffset, int zOffset) {
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.chestContents.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof InventoryHolder) {
InventoryHolder chest = (InventoryHolder) state;
chest.getInventory().setContents(blockLocEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate chest: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate chest: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IllegalArgumentException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate chest (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate chest (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, String[]> blockLocEntry : this.signContents.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Sign) {
Sign sign = (Sign) state;
@ -773,95 +736,105 @@ public class BukkitChunkManager extends ChunkManager {
}
state.update(true);
} else {
PS.debug(
"&c[WARN] Plot clear failed to regenerate sign: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y
+ ',' + (
blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IndexOutOfBoundsException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (
blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.dispenserContents.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Dispenser) {
((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue());
((InventoryHolder) state).getInventory()
.setContents(blockLocEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IllegalArgumentException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.dropperContents.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Dropper) {
((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue());
((InventoryHolder) state).getInventory()
.setContents(blockLocEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IllegalArgumentException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.beaconContents.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Beacon) {
((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue());
((InventoryHolder) state).getInventory()
.setContents(blockLocEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate beacon: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate beacon: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IllegalArgumentException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate beacon (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate beacon (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, Material> blockLocMaterialEntry : this.jukeboxDisc.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocMaterialEntry.getKey().x + xOffset, blockLocMaterialEntry.getKey().y, blockLocMaterialEntry
.getKey().z + zOffset);
Block block = world.getBlockAt(blockLocMaterialEntry.getKey().x + xOffset,
blockLocMaterialEntry.getKey().y,
blockLocMaterialEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Jukebox) {
((Jukebox) state).setPlaying(blockLocMaterialEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to restore jukebox: " + (blockLocMaterialEntry.getKey().x + xOffset) + ','
+ blockLocMaterialEntry
.getKey().y + ',' + (
blockLocMaterialEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore jukebox: " + (
blockLocMaterialEntry.getKey().x + xOffset) + ','
+ blockLocMaterialEntry.getKey().y + ',' + (
blockLocMaterialEntry.getKey().z + zOffset));
}
} catch (Exception ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate jukebox (e): " + (blockLocMaterialEntry.getKey().x + xOffset) + ','
+ blockLocMaterialEntry
.getKey().y + ',' + (
blockLocMaterialEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate jukebox (e): " + (
blockLocMaterialEntry.getKey().x + xOffset) + ',' + blockLocMaterialEntry
.getKey().y + ',' + (blockLocMaterialEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, Object[]> blockLocEntry : this.skullData.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Skull) {
Object[] data = blockLocEntry.getValue();
@ -872,193 +845,210 @@ public class BukkitChunkManager extends ChunkManager {
((Skull) state).setSkullType((SkullType) data[3]);
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to restore skull: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore skull: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (Exception e) {
PS.debug("&c[WARN] Plot clear failed to regenerate skull (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate skull (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
e.printStackTrace();
}
}
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.hopperContents.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Hopper) {
((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue());
((InventoryHolder) state).getInventory()
.setContents(blockLocEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate hopper: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate hopper: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IllegalArgumentException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate hopper (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate hopper (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, Note> blockLocNoteEntry : this.noteBlockContents.entrySet()) {
try {
Block block = world.getBlockAt(
blockLocNoteEntry.getKey().x + xOffset, blockLocNoteEntry.getKey().y, blockLocNoteEntry.getKey().z + zOffset);
Block block = world.getBlockAt(blockLocNoteEntry.getKey().x + xOffset,
blockLocNoteEntry.getKey().y, blockLocNoteEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof NoteBlock) {
((NoteBlock) state).setNote(blockLocNoteEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate note block: " + (blockLocNoteEntry.getKey().x + xOffset) + ','
+ blockLocNoteEntry
.getKey().y + ',' + (
blockLocNoteEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate note block: " + (
blockLocNoteEntry.getKey().x + xOffset) + ',' + blockLocNoteEntry
.getKey().y + ',' + (blockLocNoteEntry.getKey().z + zOffset));
}
} catch (Exception ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate note block (e): " + (blockLocNoteEntry.getKey().x + xOffset) + ','
+ blockLocNoteEntry
.getKey().y + ',' + (
blockLocNoteEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate note block (e): " + (
blockLocNoteEntry.getKey().x + xOffset) + ',' + blockLocNoteEntry.getKey().y
+ ',' + (blockLocNoteEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, Short> blockLocShortEntry : this.brewTime.entrySet()) {
try {
Block block = world.getBlockAt(
blockLocShortEntry.getKey().x + xOffset, blockLocShortEntry.getKey().y, blockLocShortEntry.getKey().z + zOffset);
Block block = world.getBlockAt(blockLocShortEntry.getKey().x + xOffset,
blockLocShortEntry.getKey().y, blockLocShortEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof BrewingStand) {
((BrewingStand) state).setBrewingTime(blockLocShortEntry.getValue());
} else {
PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking: " + (blockLocShortEntry.getKey().x + xOffset) + ','
+ blockLocShortEntry
.getKey().y + ',' + (
blockLocShortEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking: " + (
blockLocShortEntry.getKey().x + xOffset) + ',' + blockLocShortEntry
.getKey().y + ',' + (blockLocShortEntry.getKey().z + zOffset));
}
} catch (Exception ignored) {
PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking (e): " + (blockLocShortEntry.getKey().x + xOffset) + ','
+ blockLocShortEntry.getKey().y + ',' + (blockLocShortEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking (e): " + (
blockLocShortEntry.getKey().x + xOffset) + ',' + blockLocShortEntry
.getKey().y + ',' + (blockLocShortEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, EntityType> blockLocEntityTypeEntry : this.spawnerData.entrySet()) {
for (Entry<BlockLoc, EntityType> blockLocEntityTypeEntry : this.spawnerData
.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntityTypeEntry.getKey().x + xOffset, blockLocEntityTypeEntry.getKey().y, blockLocEntityTypeEntry
.getKey().z + zOffset);
Block block = world.getBlockAt(blockLocEntityTypeEntry.getKey().x + xOffset,
blockLocEntityTypeEntry.getKey().y,
blockLocEntityTypeEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof CreatureSpawner) {
((CreatureSpawner) state).setSpawnedType(blockLocEntityTypeEntry.getValue());
((CreatureSpawner) state)
.setSpawnedType(blockLocEntityTypeEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to restore spawner type: " + (blockLocEntityTypeEntry.getKey().x + xOffset) + ','
+ blockLocEntityTypeEntry
.getKey().y + ',' + (
blockLocEntityTypeEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore spawner type: " + (
blockLocEntityTypeEntry.getKey().x + xOffset) + ','
+ blockLocEntityTypeEntry.getKey().y + ',' + (
blockLocEntityTypeEntry.getKey().z + zOffset));
}
} catch (Exception ignored) {
PS.debug("&c[WARN] Plot clear failed to restore spawner type (e): " + (blockLocEntityTypeEntry.getKey().x + xOffset) + ','
+ blockLocEntityTypeEntry.getKey().y + ',' + (blockLocEntityTypeEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore spawner type (e): " + (
blockLocEntityTypeEntry.getKey().x + xOffset) + ','
+ blockLocEntityTypeEntry.getKey().y + ',' + (
blockLocEntityTypeEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, String> blockLocStringEntry : this.cmdData.entrySet()) {
try {
Block block = world.getBlockAt(
blockLocStringEntry.getKey().x + xOffset, blockLocStringEntry.getKey().y, blockLocStringEntry.getKey().z + zOffset);
Block block = world.getBlockAt(blockLocStringEntry.getKey().x + xOffset,
blockLocStringEntry.getKey().y, blockLocStringEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof CommandBlock) {
((CommandBlock) state).setCommand(blockLocStringEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to restore command block: " + (blockLocStringEntry.getKey().x + xOffset) + ','
+ blockLocStringEntry
.getKey().y + ',' + (
blockLocStringEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore command block: " + (
blockLocStringEntry.getKey().x + xOffset) + ',' + blockLocStringEntry
.getKey().y + ',' + (blockLocStringEntry.getKey().z + zOffset));
}
} catch (Exception ignored) {
PS.debug("&c[WARN] Plot clear failed to restore command block (e): " + (blockLocStringEntry.getKey().x + xOffset) + ','
+ blockLocStringEntry
.getKey().y + ',' + (
blockLocStringEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore command block (e): " + (
blockLocStringEntry.getKey().x + xOffset) + ',' + blockLocStringEntry
.getKey().y + ',' + (blockLocStringEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.brewingStandContents.entrySet()) {
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.brewingStandContents
.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof BrewingStand) {
((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue());
((InventoryHolder) state).getInventory()
.setContents(blockLocEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand: " + (blockLocEntry.getKey().x + xOffset) + ','
+ blockLocEntry
.getKey().y + ',' + (
blockLocEntry.getKey().z
+ zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IllegalArgumentException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand (e): " + (blockLocEntry.getKey().x + xOffset) + ','
+ blockLocEntry.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, Short[]> blockLocEntry : this.furnaceTime.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Furnace) {
Short[] time = blockLocEntry.getValue();
((Furnace) state).setBurnTime(time[0]);
((Furnace) state).setCookTime(time[1]);
} else {
PS.debug(
"&c[WARN] Plot clear failed to restore furnace cooking: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore furnace cooking: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (Exception ignored) {
PS.debug(
"&c[WARN] Plot clear failed to restore furnace cooking (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore furnace cooking (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.furnaceContents.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Furnace) {
((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue());
((InventoryHolder) state).getInventory()
.setContents(blockLocEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate furnace: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate furnace: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IllegalArgumentException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate furnace (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate furnace (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, DyeColor> blockLocByteEntry : this.bannerBase.entrySet()) {
try {
Block block = world.getBlockAt(
blockLocByteEntry.getKey().x + xOffset, blockLocByteEntry.getKey().y, blockLocByteEntry.getKey().z + zOffset);
Block block = world.getBlockAt(blockLocByteEntry.getKey().x + xOffset,
blockLocByteEntry.getKey().y, blockLocByteEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Banner) {
Banner banner = (Banner) state;
DyeColor base = blockLocByteEntry.getValue();
List<Pattern> patterns = this.bannerPatterns.get(blockLocByteEntry.getKey());
List<Pattern> patterns =
this.bannerPatterns.get(blockLocByteEntry.getKey());
banner.setBaseColor(base);
banner.setPatterns(patterns);
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate banner: " + (blockLocByteEntry.getKey().x + xOffset) + ','
+ blockLocByteEntry.getKey().y + ',' + (blockLocByteEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate banner: " + (
blockLocByteEntry.getKey().x + xOffset) + ',' + blockLocByteEntry
.getKey().y + ',' + (blockLocByteEntry.getKey().z + zOffset));
}
} catch (Exception ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate banner (e): " + (blockLocByteEntry.getKey().x + xOffset) + ','
+ blockLocByteEntry.getKey().y + ',' + (blockLocByteEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate banner (e): " + (
blockLocByteEntry.getKey().x + xOffset) + ',' + blockLocByteEntry.getKey().y
+ ',' + (blockLocByteEntry.getKey().z + zOffset));
}
}
}
public void saveBlocks(World world, int maxY, int x, int z, int offsetX, int offsetZ, boolean storeNormal) {
public void saveBlocks(World world, int maxY, int x, int z, int offsetX, int offsetZ,
boolean storeNormal) {
maxY = Math.min(255, maxY);
PlotBlock[] ids;
if (storeNormal) {
@ -1082,7 +1072,8 @@ public class BukkitChunkManager extends ChunkManager {
BlockLoc bl = new BlockLoc(x + offsetX, y, z + offsetZ);
if (block.getState() instanceof InventoryHolder) {
InventoryHolder inventoryHolder = (InventoryHolder) block.getState();
ItemStack[] inventory = inventoryHolder.getInventory().getContents().clone();
ItemStack[] inventory =
inventoryHolder.getInventory().getContents().clone();
switch (id) {
case CHEST:
this.chestContents.put(bl, inventory);
@ -1105,7 +1096,8 @@ public class BukkitChunkManager extends ChunkManager {
if (time > 0) {
this.brewTime.put(bl, time);
}
ItemStack[] invBre = brewingStand.getInventory().getContents().clone();
ItemStack[] invBre =
brewingStand.getInventory().getContents().clone();
this.brewingStandContents.put(bl, invBre);
break;
case FURNACE:
@ -1113,10 +1105,11 @@ public class BukkitChunkManager extends ChunkManager {
Furnace furnace = (Furnace) inventoryHolder;
short burn = furnace.getBurnTime();
short cook = furnace.getCookTime();
ItemStack[] invFur = furnace.getInventory().getContents().clone();
ItemStack[] invFur =
furnace.getInventory().getContents().clone();
this.furnaceContents.put(bl, invFur);
if (cook != 0) {
this.furnaceTime.put(bl, new Short[]{burn, cook});
this.furnaceTime.put(bl, new Short[] {burn, cook});
}
break;
}
@ -1144,7 +1137,8 @@ public class BukkitChunkManager extends ChunkManager {
}
} else if (block.getState() instanceof Skull) {
Skull skull = (Skull) block.getState();
this.skullData.put(bl, new Object[]{skull.hasOwner(), skull.getOwner(), skull.getRotation(), skull.getSkullType()});
this.skullData.put(bl, new Object[] {skull.hasOwner(), skull.getOwner(),
skull.getRotation(), skull.getSkullType()});
} else if (block.getState() instanceof Banner) {
Banner banner = (Banner) block.getState();
DyeColor base = banner.getBaseColor();

View File

@ -4,13 +4,7 @@ import com.intellectualcrafters.plot.commands.MainCommand;
import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.bukkit.commands.DebugUUID;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.ProxiedCommandSender;
import org.bukkit.command.RemoteConsoleCommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import java.util.ArrayList;
@ -25,19 +19,22 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
}
@Override
public boolean onCommand(CommandSender commandSender, Command command, String commandLabel, String[] args) {
public boolean onCommand(CommandSender commandSender, Command command, String commandLabel,
String[] args) {
if (commandSender instanceof Player) {
return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), args);
}
if (commandSender instanceof ConsoleCommandSender || commandSender instanceof ProxiedCommandSender
|| commandSender instanceof RemoteConsoleCommandSender) {
if (commandSender instanceof ConsoleCommandSender
|| commandSender instanceof ProxiedCommandSender
|| commandSender instanceof RemoteConsoleCommandSender) {
return MainCommand.onCommand(ConsolePlayer.getConsole(), args);
}
return false;
}
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) {
public List<String> onTabComplete(CommandSender commandSender, Command command, String s,
String[] args) {
if (!(commandSender instanceof Player)) {
return null;
}

View File

@ -24,7 +24,8 @@ public class BukkitEconHandler extends EconHandler {
}
private boolean setupPermissions() {
RegisteredServiceProvider<Permission> permissionProvider = Bukkit.getServer().getServicesManager().getRegistration(Permission.class);
RegisteredServiceProvider<Permission> permissionProvider =
Bukkit.getServer().getServicesManager().getRegistration(Permission.class);
if (permissionProvider != null) {
this.perms = permissionProvider.getProvider();
}
@ -35,15 +36,15 @@ public class BukkitEconHandler extends EconHandler {
if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) {
return false;
}
RegisteredServiceProvider<Economy> economyProvider = Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
RegisteredServiceProvider<Economy> economyProvider =
Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
if (economyProvider != null) {
this.econ = economyProvider.getProvider();
}
return this.econ != null;
}
@Override
public double getMoney(PlotPlayer player) {
@Override public double getMoney(PlotPlayer player) {
double bal = super.getMoney(player);
if (Double.isNaN(bal)) {
return this.econ.getBalance(((BukkitPlayer) player).player);
@ -51,28 +52,23 @@ public class BukkitEconHandler extends EconHandler {
return bal;
}
@Override
public void withdrawMoney(PlotPlayer player, double amount) {
@Override public void withdrawMoney(PlotPlayer player, double amount) {
this.econ.withdrawPlayer(((BukkitPlayer) player).player, amount);
}
@Override
public void depositMoney(PlotPlayer player, double amount) {
@Override public void depositMoney(PlotPlayer player, double amount) {
this.econ.depositPlayer(((BukkitPlayer) player).player, amount);
}
@Override
public void depositMoney(OfflinePlotPlayer player, double amount) {
@Override public void depositMoney(OfflinePlotPlayer player, double amount) {
this.econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount);
}
@Override
public boolean hasPermission(String world, String player, String perm) {
@Override public boolean hasPermission(String world, String player, String perm) {
return this.perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm);
}
@Override
public double getBalance(PlotPlayer player) {
@Override public double getBalance(PlotPlayer player) {
return this.econ.getBalance(player.getName());
}

View File

@ -1,30 +1,9 @@
package com.plotsquared.bukkit.util;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotCluster;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.Rating;
import com.intellectualcrafters.plot.object.*;
import com.intellectualcrafters.plot.util.EventUtil;
import com.plotsquared.bukkit.events.ClusterFlagRemoveEvent;
import com.plotsquared.bukkit.events.PlayerClaimPlotEvent;
import com.plotsquared.bukkit.events.PlayerEnterPlotEvent;
import com.plotsquared.bukkit.events.PlayerLeavePlotEvent;
import com.plotsquared.bukkit.events.PlayerPlotDeniedEvent;
import com.plotsquared.bukkit.events.PlayerPlotHelperEvent;
import com.plotsquared.bukkit.events.PlayerPlotTrustedEvent;
import com.plotsquared.bukkit.events.PlayerTeleportToPlotEvent;
import com.plotsquared.bukkit.events.PlotClearEvent;
import com.plotsquared.bukkit.events.PlotComponentSetEvent;
import com.plotsquared.bukkit.events.PlotDeleteEvent;
import com.plotsquared.bukkit.events.PlotFlagAddEvent;
import com.plotsquared.bukkit.events.PlotFlagRemoveEvent;
import com.plotsquared.bukkit.events.PlotMergeEvent;
import com.plotsquared.bukkit.events.PlotRateEvent;
import com.plotsquared.bukkit.events.PlotUnlinkEvent;
import com.plotsquared.bukkit.events.*;
import com.plotsquared.bukkit.object.BukkitPlayer;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@ -48,83 +27,67 @@ public class BukkitEventUtil extends EventUtil {
return !(event instanceof Cancellable) || !((Cancellable) event).isCancelled();
}
@Override
public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) {
@Override public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) {
return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto));
}
@Override
public boolean callTeleport(PlotPlayer player, Location from, Plot plot) {
@Override public boolean callTeleport(PlotPlayer player, Location from, Plot plot) {
return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot));
}
@Override
public boolean callComponentSet(Plot plot, String component) {
@Override public boolean callComponentSet(Plot plot, String component) {
return callEvent(new PlotComponentSetEvent(plot, component));
}
@Override
public boolean callClear(Plot plot) {
@Override public boolean callClear(Plot plot) {
return callEvent(new PlotClearEvent(plot));
}
@Override
public void callDelete(Plot plot) {
@Override public void callDelete(Plot plot) {
callEvent(new PlotDeleteEvent(plot));
}
@Override
public boolean callFlagAdd(Flag flag, Plot plot) {
@Override public boolean callFlagAdd(Flag flag, Plot plot) {
return callEvent(new PlotFlagAddEvent(flag, plot));
}
@Override
public boolean callFlagRemove(Flag<?> flag, Plot plot, Object value) {
@Override public boolean callFlagRemove(Flag<?> flag, Plot plot, Object value) {
return callEvent(new PlotFlagRemoveEvent(flag, plot));
}
@Override
public boolean callMerge(Plot plot, ArrayList<PlotId> plots) {
@Override public boolean callMerge(Plot plot, ArrayList<PlotId> plots) {
return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(plot.getWorldName()), plot, plots));
}
@Override
public boolean callUnlink(PlotArea area, ArrayList<PlotId> plots) {
@Override public boolean callUnlink(PlotArea area, ArrayList<PlotId> plots) {
return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(area.worldname), area, plots));
}
@Override
public void callEntry(PlotPlayer player, Plot plot) {
@Override public void callEntry(PlotPlayer player, Plot plot) {
callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot));
}
@Override
public void callLeave(PlotPlayer player, Plot plot) {
@Override public void callLeave(PlotPlayer player, Plot plot) {
callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot));
}
@Override
public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
@Override public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added));
}
@Override
public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
@Override public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added));
}
@Override
public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
@Override public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added));
}
@Override
public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) {
@Override public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) {
return callEvent(new ClusterFlagRemoveEvent(flag, cluster));
}
@Override
public Rating callRating(PlotPlayer player, Plot plot, Rating rating) {
@Override public Rating callRating(PlotPlayer player, Plot plot, Rating rating) {
PlotRateEvent event = new PlotRateEvent(player, rating, plot);
Bukkit.getServer().getPluginManager().callEvent(event);
return event.getRating();

View File

@ -26,8 +26,8 @@ import java.util.Random;
public class BukkitHybridUtils extends HybridUtils {
@Override
public void analyzeRegion(final String world, final RegionWrapper region, final RunnableVal<PlotAnalysis> whenDone) {
@Override public void analyzeRegion(final String world, final RegionWrapper region,
final RunnableVal<PlotAnalysis> whenDone) {
// int diff, int variety, int vertices, int rotation, int height_sd
/*
* diff: compare to base by looping through all blocks
@ -41,8 +41,7 @@ public class BukkitHybridUtils extends HybridUtils {
*
*/
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@Override public void run() {
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
final World worldObj = Bukkit.getWorld(world);
final ChunkGenerator gen = worldObj.getGenerator();
@ -50,12 +49,10 @@ public class BukkitHybridUtils extends HybridUtils {
return;
}
final BiomeGrid nullBiomeGrid = new BiomeGrid() {
@Override
public void setBiome(int a, int b, Biome c) {
@Override public void setBiome(int a, int b, Biome c) {
}
@Override
public Biome getBiome(int a, int b) {
@Override public Biome getBiome(int a, int b) {
return null;
}
};
@ -82,15 +79,14 @@ public class BukkitHybridUtils extends HybridUtils {
final short[][][] newBlocks = new short[256][width][length];
final Runnable run = new Runnable() {
@Override
public void run() {
@Override public void run() {
ChunkManager.chunkTask(bot, top, new RunnableVal<int[]>() {
@Override
public void run(int[] value) {
@Override public void run(int[] value) {
// [chunkx, chunkz, pos1x, pos1z, pos2x, pos2z, isedge]
int X = value[0];
int Z = value[1];
short[][] result = gen.generateExtBlockSections(worldObj, r, X, Z, nullBiomeGrid);
short[][] result =
gen.generateExtBlockSections(worldObj, r, X, Z, nullBiomeGrid);
int xb = (X << 4) - bx;
int zb = (Z << 4) - bz;
for (int i = 0; i < result.length; i++) {
@ -125,11 +121,9 @@ public class BukkitHybridUtils extends HybridUtils {
}
}, new Runnable() {
@Override
public void run() {
@Override public void run() {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@Override public void run() {
int size = width * length;
int[] changes = new int[size];
int[] faces = new int[size];
@ -151,7 +145,8 @@ public class BukkitHybridUtils extends HybridUtils {
} else {
// check vertices
// modifications_adjacent
if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 && y < 255) {
if (x > 0 && z > 0 && y > 0 && x < width - 1
&& z < length - 1 && y < 255) {
if (newBlocks[y - 1][x][z] == 0) {
faces[i]++;
}
@ -172,12 +167,15 @@ public class BukkitHybridUtils extends HybridUtils {
}
}
Material material = Material.getMaterial(now);
Material material =
Material.getMaterial(now);
if (material != null) {
Class<? extends MaterialData> md = material.getData();
Class<? extends MaterialData> md =
material.getData();
if (md.equals(Directional.class)) {
data[i] += 8;
} else if (!md.equals(MaterialData.class)) {
} else if (!md
.equals(MaterialData.class)) {
data[i]++;
}
}
@ -199,11 +197,14 @@ public class BukkitHybridUtils extends HybridUtils {
analysis.air = (int) (MathMan.getMean(air) * 100);
analysis.variety = (int) (MathMan.getMean(variety) * 100);
analysis.changes_sd = (int) MathMan.getSD(changes, analysis.changes);
analysis.faces_sd = (int) MathMan.getSD(faces, analysis.faces);
analysis.changes_sd =
(int) MathMan.getSD(changes, analysis.changes);
analysis.faces_sd =
(int) MathMan.getSD(faces, analysis.faces);
analysis.data_sd = (int) MathMan.getSD(data, analysis.data);
analysis.air_sd = (int) MathMan.getSD(air, analysis.air);
analysis.variety_sd = (int) MathMan.getSD(variety, analysis.variety);
analysis.variety_sd =
(int) MathMan.getSD(variety, analysis.variety);
System.gc();
System.gc();
whenDone.value = analysis;
@ -219,8 +220,7 @@ public class BukkitHybridUtils extends HybridUtils {
MainUtil.initCache();
ChunkManager.chunkTask(bot, top, new RunnableVal<int[]>() {
@Override
public void run(int[] value) {
@Override public void run(int[] value) {
int X = value[0];
int Z = value[1];
worldObj.loadChunk(X, Z);
@ -269,8 +269,7 @@ public class BukkitHybridUtils extends HybridUtils {
worldObj.unloadChunkRequest(X, Z, true);
}
}, new Runnable() {
@Override
public void run() {
@Override public void run() {
TaskManager.runTaskAsync(run);
}
}, 5);

View File

@ -45,8 +45,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
return stack;
}
@Override
public void open(PlotInventory inv) {
@Override public void open(PlotInventory inv) {
BukkitPlayer bp = (BukkitPlayer) inv.player;
Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle());
PlotItemStack[] items = inv.getItems();
@ -60,8 +59,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
bp.player.openInventory(inventory);
}
@Override
public void close(PlotInventory inv) {
@Override public void close(PlotInventory inv) {
if (!inv.isOpen()) {
return;
}
@ -70,8 +68,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
bp.player.closeInventory();
}
@Override
public void setItem(PlotInventory inv, int index, PlotItemStack item) {
@Override public void setItem(PlotInventory inv, int index, PlotItemStack item) {
BukkitPlayer bp = (BukkitPlayer) inv.player;
InventoryView opened = bp.player.getOpenInventory();
if (!inv.isOpen()) {
@ -103,8 +100,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
return new PlotItemStack(id, data, amount, name, lore);
}
@Override
public PlotItemStack[] getItems(PlotPlayer player) {
@Override public PlotItemStack[] getItems(PlotPlayer player) {
BukkitPlayer bp = (BukkitPlayer) player;
PlayerInventory inv = bp.player.getInventory();
PlotItemStack[] items = new PlotItemStack[36];
@ -114,13 +110,13 @@ public class BukkitInventoryUtil extends InventoryUtil {
return items;
}
@Override
public boolean isOpen(PlotInventory inv) {
@Override public boolean isOpen(PlotInventory inv) {
if (!inv.isOpen()) {
return false;
}
BukkitPlayer bp = (BukkitPlayer) inv.player;
InventoryView opened = bp.player.getOpenInventory();
return inv.isOpen() && opened.getType() == InventoryType.CRAFTING && opened.getTitle() == null;
return inv.isOpen() && opened.getType() == InventoryType.CRAFTING
&& opened.getTitle() == null;
}
}

View File

@ -1,12 +1,6 @@
package com.plotsquared.bukkit.util;
import com.intellectualcrafters.jnbt.ByteArrayTag;
import com.intellectualcrafters.jnbt.CompoundTag;
import com.intellectualcrafters.jnbt.IntTag;
import com.intellectualcrafters.jnbt.ListTag;
import com.intellectualcrafters.jnbt.ShortTag;
import com.intellectualcrafters.jnbt.StringTag;
import com.intellectualcrafters.jnbt.Tag;
import com.intellectualcrafters.jnbt.*;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.RegionWrapper;
@ -22,24 +16,18 @@ import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
/**
* Schematic Handler.
*/
public class BukkitSchematicHandler extends SchematicHandler {
@Override
public void getCompoundTag(final String world, final Set<RegionWrapper> regions, final RunnableVal<CompoundTag> whenDone) {
@Override public void getCompoundTag(final String world, final Set<RegionWrapper> regions,
final RunnableVal<CompoundTag> whenDone) {
// async
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@Override public void run() {
// Main positions
Location[] corners = MainUtil.getCorners(world, regions);
final Location bot = corners[0];
@ -67,16 +55,18 @@ public class BukkitSchematicHandler extends SchematicHandler {
// Queue
final ArrayDeque<RegionWrapper> queue = new ArrayDeque<>(regions);
TaskManager.runTask(new Runnable() {
@Override
public void run() {
@Override public void run() {
if (queue.isEmpty()) {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@Override public void run() {
schematic.put("Blocks", new ByteArrayTag("Blocks", blocks));
schematic.put("Data", new ByteArrayTag("Data", blockData));
schematic.put("Entities", new ListTag("Entities", CompoundTag.class, new ArrayList<Tag>()));
schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, tileEntities));
schematic.put("Entities",
new ListTag("Entities", CompoundTag.class,
new ArrayList<Tag>()));
schematic.put("TileEntities",
new ListTag("TileEntities", CompoundTag.class,
tileEntities));
whenDone.value = new CompoundTag("Schematic", schematic);
TaskManager.runTask(whenDone);
System.gc();
@ -111,10 +101,10 @@ public class BukkitSchematicHandler extends SchematicHandler {
final World worldObj = Bukkit.getWorld(world);
// Main thread
TaskManager.runTask(new Runnable() {
@Override
public void run() {
@Override public void run() {
long start = System.currentTimeMillis();
while (!chunks.isEmpty() && System.currentTimeMillis() - start < 20) {
while (!chunks.isEmpty()
&& System.currentTimeMillis() - start < 20) {
// save schematics
ChunkLoc chunk = chunks.remove(0);
Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z);
@ -259,15 +249,20 @@ public class BukkitSchematicHandler extends SchematicHandler {
// TODO implement fully
BlockState state = block.getState();
if (state != null) {
StateWrapper wrapper = new StateWrapper(state);
StateWrapper wrapper =
new StateWrapper(state);
CompoundTag rawTag = wrapper.getTag();
if (rawTag != null) {
Map<String, Tag> values = new HashMap<>(rawTag.getValue());
values.put("id", new StringTag("id", wrapper.getId()));
Map<String, Tag> values =
new HashMap<>(
rawTag.getValue());
values.put("id", new StringTag("id",
wrapper.getId()));
values.put("x", new IntTag("x", x));
values.put("y", new IntTag("y", y));
values.put("z", new IntTag("z", z));
CompoundTag tileEntityTag = new CompoundTag(values);
CompoundTag tileEntityTag =
new CompoundTag(values);
tileEntities.add(tileEntityTag);
}
}

View File

@ -9,25 +9,21 @@ import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import org.bukkit.*;
import org.bukkit.World.Environment;
import org.bukkit.entity.Player;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Objects;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.WorldCreator;
import org.bukkit.WorldType;
import org.bukkit.entity.Player;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
public class BukkitSetupUtils extends SetupUtils {
@Override
public void updateGenerators() {
@Override public void updateGenerators() {
if (!SetupUtils.generators.isEmpty()) {
return;
}
@ -54,8 +50,7 @@ public class BukkitSetupUtils extends SetupUtils {
}
}
@Override
public void unload(String worldName, boolean save) {
@Override public void unload(String worldName, boolean save) {
World world = Bukkit.getWorld(worldName);
if (world == null) {
return;
@ -76,8 +71,7 @@ public class BukkitSetupUtils extends SetupUtils {
Bukkit.unloadWorld(world, false);
}
@Override
public String setupWorld(SetupObject object) {
@Override public String setupWorld(SetupObject object) {
SetupUtils.manager.updateGenerators();
ConfigurationNode[] steps = object.step == null ? new ConfigurationNode[0] : object.step;
String world = object.world;
@ -89,13 +83,15 @@ public class BukkitSetupUtils extends SetupUtils {
if (!PS.get().worlds.contains(worldPath)) {
PS.get().worlds.createSection(worldPath);
}
ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection(worldPath);
ConfigurationSection worldSection =
PS.get().worlds.getConfigurationSection(worldPath);
String areaName = object.id + "-" + object.min + "-" + object.max;
String areaPath = "areas." + areaName;
if (!worldSection.contains(areaPath)) {
worldSection.createSection(areaPath);
}
ConfigurationSection areaSection = worldSection.getConfigurationSection(areaPath);
ConfigurationSection areaSection =
worldSection.getConfigurationSection(areaPath);
HashMap<String, Object> options = new HashMap<>();
for (ConfigurationNode step : steps) {
options.put(step.getConstant(), step.getValue());
@ -103,7 +99,8 @@ public class BukkitSetupUtils extends SetupUtils {
options.put("generator.type", object.type);
options.put("generator.terrain", object.terrain);
options.put("generator.plugin", object.plotManager);
if (object.setupGenerator != null && !object.setupGenerator.equals(object.plotManager)) {
if (object.setupGenerator != null && !object.setupGenerator
.equals(object.plotManager)) {
options.put("generator.init", object.setupGenerator);
}
for (Entry<String, Object> entry : options.entrySet()) {
@ -129,15 +126,18 @@ public class BukkitSetupUtils extends SetupUtils {
if (!PS.get().worlds.contains(worldPath)) {
PS.get().worlds.createSection(worldPath);
}
ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection(worldPath);
ConfigurationSection worldSection =
PS.get().worlds.getConfigurationSection(worldPath);
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
PS.get().worlds.set("worlds." + world + ".generator.type", object.type);
PS.get().worlds.set("worlds." + world + ".generator.terrain", object.terrain);
PS.get().worlds.set("worlds." + world + ".generator.plugin", object.plotManager);
if (object.setupGenerator != null && !object.setupGenerator.equals(object.plotManager)) {
PS.get().worlds.set("worlds." + world + ".generator.init", object.setupGenerator);
if (object.setupGenerator != null && !object.setupGenerator
.equals(object.plotManager)) {
PS.get().worlds
.set("worlds." + world + ".generator.init", object.setupGenerator);
}
GeneratorWrapper<?> gen = SetupUtils.generators.get(object.setupGenerator);
if (gen != null && gen.isFull()) {
@ -150,7 +150,8 @@ public class BukkitSetupUtils extends SetupUtils {
if (!PS.get().worlds.contains(worldPath)) {
PS.get().worlds.createSection(worldPath);
}
ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection(worldPath);
ConfigurationSection worldSection =
PS.get().worlds.getConfigurationSection(worldPath);
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
@ -164,17 +165,19 @@ public class BukkitSetupUtils extends SetupUtils {
e.printStackTrace();
}
if (object.setupGenerator != null) {
if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit.getPluginManager().getPlugin("Multiverse-Core")
.isEnabled()) {
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal -g " + object.setupGenerator);
if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit
.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv create " + world + " normal -g " + object.setupGenerator);
setGenerator(world, object.setupGenerator);
if (Bukkit.getWorld(world) != null) {
return world;
}
}
if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world + " plugin:" + object.setupGenerator);
if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit
.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mw create " + world + " plugin:" + object.setupGenerator);
setGenerator(world, object.setupGenerator);
if (Bukkit.getWorld(world) != null) {
return world;
@ -187,20 +190,24 @@ public class BukkitSetupUtils extends SetupUtils {
Bukkit.createWorld(wc);
setGenerator(world, object.setupGenerator);
} else {
if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit.getPluginManager().getPlugin("Multiverse-Core")
.isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal");
if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit
.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv create " + world + " normal");
if (Bukkit.getWorld(world) != null) {
return world;
}
}
if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world);
if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit
.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world);
if (Bukkit.getWorld(world) != null) {
return world;
}
}
World bw = Bukkit.createWorld(new WorldCreator(object.world).environment(Environment.NORMAL));
World bw =
Bukkit.createWorld(new WorldCreator(object.world).environment(Environment.NORMAL));
}
return object.world;
}
@ -219,8 +226,7 @@ public class BukkitSetupUtils extends SetupUtils {
}
}
@Override
public String getGenerator(PlotArea plotArea) {
@Override public String getGenerator(PlotArea plotArea) {
if (SetupUtils.generators.isEmpty()) {
updateGenerators();
}

View File

@ -12,39 +12,37 @@ public class BukkitTaskManager extends TaskManager {
this.bukkitMain = bukkitMain;
}
@Override
public int taskRepeat(Runnable runnable, int interval) {
return this.bukkitMain.getServer().getScheduler().scheduleSyncRepeatingTask(this.bukkitMain, runnable, interval, interval);
@Override public int taskRepeat(Runnable runnable, int interval) {
return this.bukkitMain.getServer().getScheduler()
.scheduleSyncRepeatingTask(this.bukkitMain, runnable, interval, interval);
}
@SuppressWarnings("deprecation")
@Override
@SuppressWarnings("deprecation") @Override
public int taskRepeatAsync(Runnable runnable, int interval) {
return this.bukkitMain.getServer().getScheduler().scheduleAsyncRepeatingTask(this.bukkitMain, runnable, interval, interval);
return this.bukkitMain.getServer().getScheduler()
.scheduleAsyncRepeatingTask(this.bukkitMain, runnable, interval, interval);
}
@Override
public void taskAsync(Runnable runnable) {
this.bukkitMain.getServer().getScheduler().runTaskAsynchronously(this.bukkitMain, runnable).getTaskId();
@Override public void taskAsync(Runnable runnable) {
this.bukkitMain.getServer().getScheduler().runTaskAsynchronously(this.bukkitMain, runnable)
.getTaskId();
}
@Override
public void task(Runnable runnable) {
@Override public void task(Runnable runnable) {
this.bukkitMain.getServer().getScheduler().runTask(this.bukkitMain, runnable).getTaskId();
}
@Override
public void taskLater(Runnable runnable, int delay) {
this.bukkitMain.getServer().getScheduler().runTaskLater(this.bukkitMain, runnable, delay).getTaskId();
@Override public void taskLater(Runnable runnable, int delay) {
this.bukkitMain.getServer().getScheduler().runTaskLater(this.bukkitMain, runnable, delay)
.getTaskId();
}
@Override
public void taskLaterAsync(Runnable runnable, int delay) {
this.bukkitMain.getServer().getScheduler().runTaskLaterAsynchronously(this.bukkitMain, runnable, delay);
@Override public void taskLaterAsync(Runnable runnable, int delay) {
this.bukkitMain.getServer().getScheduler()
.runTaskLaterAsynchronously(this.bukkitMain, runnable, delay);
}
@Override
public void cancelTask(int task) {
@Override public void cancelTask(int task) {
if (task != -1) {
Bukkit.getScheduler().cancelTask(task);
}

View File

@ -10,9 +10,6 @@ import com.intellectualcrafters.plot.util.StringComparison;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.bukkit.object.BukkitPlayer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
@ -26,12 +23,11 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.material.Sandstone;
import org.bukkit.material.Step;
import org.bukkit.material.Tree;
import org.bukkit.material.WoodenStep;
import org.bukkit.material.Wool;
import org.bukkit.material.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class BukkitUtil extends WorldUtil {
@ -71,12 +67,13 @@ public class BukkitUtil extends WorldUtil {
}
public static Location getLocation(org.bukkit.Location location) {
return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()),
MathMan.roundInt(location.getZ()));
return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()),
MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()));
}
public static org.bukkit.Location getLocation(Location location) {
return new org.bukkit.Location(getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ());
return new org.bukkit.Location(getWorld(location.getWorld()), location.getX(),
location.getY(), location.getZ());
}
public static World getWorld(String string) {
@ -95,37 +92,40 @@ public class BukkitUtil extends WorldUtil {
public static Location getLocation(Entity entity) {
org.bukkit.Location location = entity.getLocation();
String world = location.getWorld().getName();
return new Location(world, location.getBlockX(), location.getBlockY(), location.getBlockZ());
return new Location(world, location.getBlockX(), location.getBlockY(),
location.getBlockZ());
}
public static Location getLocationFull(Entity entity) {
org.bukkit.Location location = entity.getLocation();
return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()),
location.getYaw(), location.getPitch());
return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()),
MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()), location.getYaw(),
location.getPitch());
}
@Override
public boolean isWorld(String worldName) {
@Override public boolean isWorld(String worldName) {
return getWorld(worldName) != null;
}
@Override
public String getBiome(String world, int x, int z) {
@Override public String getBiome(String world, int x, int z) {
return getWorld(world).getBiome(x, z).name();
}
@Override
public void setSign(String worldName, int x, int y, int z, String[] lines) {
@Override public void setSign(String worldName, int x, int y, int z, String[] lines) {
World world = getWorld(worldName);
Block block = world.getBlockAt(x, y, z);
// block.setType(Material.AIR);
Material type = block.getType();
if (type != Material.SIGN && type != Material.SIGN_POST) {
int data = 2;
if (world.getBlockAt(x, y, z + 1).getType().isSolid()) data = 2;
else if (world.getBlockAt(x + 1, y, z).getType().isSolid()) data = 4;
else if (world.getBlockAt(x, y, z - 1).getType().isSolid()) data = 3;
else if (world.getBlockAt(x - 1, y, z).getType().isSolid()) data = 5;
if (world.getBlockAt(x, y, z + 1).getType().isSolid())
data = 2;
else if (world.getBlockAt(x + 1, y, z).getType().isSolid())
data = 4;
else if (world.getBlockAt(x, y, z - 1).getType().isSolid())
data = 3;
else if (world.getBlockAt(x - 1, y, z).getType().isSolid())
data = 5;
block.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) data, false);
}
BlockState blockstate = block.getState();
@ -138,9 +138,9 @@ public class BukkitUtil extends WorldUtil {
}
}
@Override
public String[] getSign(Location location) {
Block block = getWorld(location.getWorld()).getBlockAt(location.getX(), location.getY(), location.getZ());
@Override public String[] getSign(Location location) {
Block block = getWorld(location.getWorld())
.getBlockAt(location.getX(), location.getY(), location.getZ());
if (block != null) {
if (block.getState() instanceof Sign) {
Sign sign = (Sign) block.getState();
@ -150,35 +150,31 @@ public class BukkitUtil extends WorldUtil {
return null;
}
@Override
public Location getSpawn(PlotPlayer player) {
@Override public Location getSpawn(PlotPlayer player) {
return getLocation(((BukkitPlayer) player).player.getBedSpawnLocation());
}
@Override
public Location getSpawn(String world) {
@Override public Location getSpawn(String world) {
org.bukkit.Location temp = getWorld(world).getSpawnLocation();
return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch());
return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(),
temp.getYaw(), temp.getPitch());
}
@Override
public void setSpawn(Location location) {
@Override public void setSpawn(Location location) {
World world = getWorld(location.getWorld());
if (world != null) {
world.setSpawnLocation(location.getX(), location.getY(), location.getZ());
}
}
@Override
public void saveWorld(String worldName) {
@Override public void saveWorld(String worldName) {
World world = getWorld(worldName);
if (world != null) {
world.save();
}
}
@Override
public int getHighestBlock(String world, int x, int z) {
@Override public int getHighestBlock(String world, int x, int z) {
World bukkitWorld = getWorld(world);
// Skip top and bottom block
int air = 1;
@ -187,7 +183,8 @@ public class BukkitUtil extends WorldUtil {
if (block != null) {
Material type = block.getType();
if (type.isSolid()) {
if (air > 1) return y;
if (air > 1)
return y;
air = 0;
} else {
switch (type) {
@ -204,8 +201,7 @@ public class BukkitUtil extends WorldUtil {
return bukkitWorld.getMaxHeight() - 1;
}
@Override
public int getBiomeFromString(String biomeString) {
@Override public int getBiomeFromString(String biomeString) {
try {
Biome biome = Biome.valueOf(biomeString.toUpperCase());
return Arrays.asList(Biome.values()).indexOf(biome);
@ -214,8 +210,7 @@ public class BukkitUtil extends WorldUtil {
}
}
@Override
public String[] getBiomeList() {
@Override public String[] getBiomeList() {
Biome[] biomes = Biome.values();
String[] list = new String[biomes.length];
for (int i = 0; i < biomes.length; i++) {
@ -224,8 +219,7 @@ public class BukkitUtil extends WorldUtil {
return list;
}
@Override
public boolean addItems(String worldName, PlotItem items) {
@Override public boolean addItems(String worldName, PlotItem items) {
World world = getWorld(worldName);
Block block = world.getBlockAt(items.x, items.y, items.z);
if (block == null) {
@ -245,18 +239,15 @@ public class BukkitUtil extends WorldUtil {
return false;
}
@Override
public boolean isBlockSolid(PlotBlock block) {
@Override public boolean isBlockSolid(PlotBlock block) {
try {
Material material = Material.getMaterial(block.id);
if (material.isBlock() && material.isSolid() && !material.hasGravity()) {
Class<? extends MaterialData> data = material.getData();
if (data.equals(MaterialData.class) && !material.isTransparent() && material.isOccluding()
|| data.equals(Tree.class)
|| data.equals(Sandstone.class)
|| data.equals(Wool.class)
|| data.equals(Step.class)
|| data.equals(WoodenStep.class)) {
if (data.equals(MaterialData.class) && !material.isTransparent() && material
.isOccluding() || data.equals(Tree.class) || data.equals(Sandstone.class)
|| data.equals(Wool.class) || data.equals(Step.class) || data
.equals(WoodenStep.class)) {
switch (material) {
case NOTE_BLOCK:
case MOB_SPAWNER:
@ -272,8 +263,7 @@ public class BukkitUtil extends WorldUtil {
}
}
@Override
public String getClosestMatchingName(PlotBlock block) {
@Override public String getClosestMatchingName(PlotBlock block) {
try {
return Material.getMaterial(block.id).name();
} catch (Exception ignored) {
@ -281,12 +271,13 @@ public class BukkitUtil extends WorldUtil {
}
}
@Override
public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) {
@Override public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) {
try {
Material material = Material.valueOf(name.toUpperCase());
return new StringComparison<PlotBlock>().new ComparisonResult(0, PlotBlock.get((short) material.getId(), (byte) 0));
} catch (IllegalArgumentException ignored) {}
return new StringComparison<PlotBlock>().new ComparisonResult(0,
PlotBlock.get((short) material.getId(), (byte) 0));
} catch (IllegalArgumentException ignored) {
}
try {
byte data;
String[] split = name.split(":");
@ -302,7 +293,8 @@ public class BukkitUtil extends WorldUtil {
id = Short.parseShort(split[0]);
match = 0;
} else {
StringComparison<Material>.ComparisonResult comparison = new StringComparison<>(name, Material.values()).getBestMatchAdvanced();
StringComparison<Material>.ComparisonResult comparison =
new StringComparison<>(name, Material.values()).getBestMatchAdvanced();
match = comparison.match;
id = (short) comparison.best.getId();
}
@ -310,12 +302,12 @@ public class BukkitUtil extends WorldUtil {
StringComparison<PlotBlock> outer = new StringComparison<>();
return outer.new ComparisonResult(match, block);
} catch (NumberFormatException ignored) {}
} catch (NumberFormatException ignored) {
}
return null;
}
@Override
public void setBiomes(String worldName, RegionWrapper region, String biomeString) {
@Override public void setBiomes(String worldName, RegionWrapper region, String biomeString) {
World world = getWorld(worldName);
Biome biome = Biome.valueOf(biomeString.toUpperCase());
for (int x = region.minX; x <= region.maxX; x++) {
@ -325,8 +317,7 @@ public class BukkitUtil extends WorldUtil {
}
}
@Override
public PlotBlock getBlock(Location location) {
@Override public PlotBlock getBlock(Location location) {
World world = getWorld(location.getWorld());
Block block = world.getBlockAt(location.getX(), location.getY(), location.getZ());
if (block == null) {
@ -335,8 +326,7 @@ public class BukkitUtil extends WorldUtil {
return PlotBlock.get((short) block.getTypeId(), block.getData());
}
@Override
public String getMainWorld() {
@Override public String getMainWorld() {
return Bukkit.getWorlds().get(0).getName();
}
}

View File

@ -6,12 +6,7 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.scheduler.BukkitTask;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLConnection;
@ -22,19 +17,33 @@ import java.util.zip.GZIPOutputStream;
public class Metrics {
/** The current revision number. */
/**
* The current revision number.
*/
private static final int REVISION = 7;
/** The base url of the metrics domain.*/
/**
* The base url of the metrics domain.
*/
private static final String BASE_URL = "http://report.mcstats.org";
/** The url used to report a server's status. */
/**
* The url used to report a server's status.
*/
private static final String REPORT_URL = "/plugin/%s";
/** Interval of time to ping (in minutes). */
/**
* Interval of time to ping (in minutes).
*/
private static final int PING_INTERVAL = 15;
/** The plugin this metrics submits for. */
/**
* The plugin this metrics submits for.
*/
private final Plugin plugin;
/** Unique server id. */
/**
* Unique server id.
*/
private final String guid;
/** The scheduled task. */
/**
* The scheduled task.
*/
private volatile BukkitTask task = null;
public Metrics(Plugin plugin) {
@ -46,7 +55,6 @@ public class Metrics {
* GZip compress a string of bytes.
*
* @param input
*
* @return byte[] the file as a byte array
*/
public static byte[] gzip(String input) {
@ -61,7 +69,8 @@ public class Metrics {
if (gzos != null) {
try {
gzos.close();
} catch (IOException ignore) {}
} catch (IOException ignore) {
}
}
}
return baos.toByteArray();
@ -73,7 +82,6 @@ public class Metrics {
* @param json
* @param key
* @param value
*
*/
private static void appendJSONPair(StringBuilder json, String key, String value) {
boolean isValueNumeric = false;
@ -101,7 +109,6 @@ public class Metrics {
* Escape a string to create a valid JSON string
*
* @param text
*
* @return String
*/
private static String escapeJSON(String text) {
@ -145,7 +152,6 @@ public class Metrics {
* Encode text as UTF-8
*
* @param text the text to encode
*
* @return the encoded text, as UTF-8
*/
private static String urlEncode(String text) throws UnsupportedEncodingException {
@ -165,22 +171,22 @@ public class Metrics {
return true;
}
// Begin hitting the server with glorious data
this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() {
private boolean firstPost = true;
this.task = this.plugin.getServer().getScheduler()
.runTaskTimerAsynchronously(this.plugin, new Runnable() {
private boolean firstPost = true;
@Override
public void run() {
try {
postPlugin(!this.firstPost);
// After the first post we set firstPost to
// false
// Each post thereafter will be a ping
this.firstPost = false;
} catch (IOException e) {
e.printStackTrace();
@Override public void run() {
try {
postPlugin(!this.firstPost);
// After the first post we set firstPost to
// false
// Each post thereafter will be a ping
this.firstPost = false;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}, 0, PING_INTERVAL * 1200);
}, 0, PING_INTERVAL * 1200);
return true;
}
@ -196,10 +202,15 @@ public class Metrics {
String serverVersion = Bukkit.getVersion();
int playersOnline = 0;
try {
if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType() == Collection.class) {
playersOnline = ((Collection<?>) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null)).size();
if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType()
== Collection.class) {
playersOnline =
((Collection<?>) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0])
.invoke(null)).size();
} else {
playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null)).length;
playersOnline =
((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0])
.invoke(null)).length;
}
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
ex.printStackTrace();
@ -256,7 +267,8 @@ public class Metrics {
os.flush();
}
String response;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()))) {
response = reader.readLine();
}
if (response == null || response.startsWith("ERR") || response.startsWith("7")) {
@ -267,6 +279,7 @@ public class Metrics {
}
throw new IOException(response);
}
} catch (IOException ignored) {}
} catch (IOException ignored) {
}
}
}
}

View File

@ -8,36 +8,18 @@ import com.google.common.collect.MapMaker;
import com.google.common.io.ByteSink;
import com.google.common.io.Closeables;
import com.google.common.primitives.Primitives;
import java.io.BufferedInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.AbstractList;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class NbtFactory {
// Convert between NBT type and the equivalent class in java
@ -73,14 +55,16 @@ public class NbtFactory {
ClassLoader loader = NbtFactory.class.getClassLoader();
String packageName = getPackageName();
String craftpackageName = getCraftPackageName();
String craftpackageName = getCraftPackageName();
Class<?> offlinePlayer = loader.loadClass(packageName + ".CraftOfflinePlayer");
// Prepare NBT
this.COMPOUND_CLASS = getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType();
this.COMPOUND_CLASS =
getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType();
this.BASE_CLASS = loader.loadClass(craftpackageName + ".NBTBase");
this.NBT_GET_TYPE = getMethod(0, Modifier.STATIC, this.BASE_CLASS, "getTypeId");
this.NBT_CREATE_TAG = getMethod(Modifier.STATIC, 0, this.BASE_CLASS, "createTag", byte.class);
this.NBT_CREATE_TAG =
getMethod(Modifier.STATIC, 0, this.BASE_CLASS, "createTag", byte.class);
// Prepare CraftItemStack
this.CRAFT_STACK = loader.loadClass(packageName + ".inventory.CraftItemStack");
@ -92,11 +76,14 @@ public class NbtFactory {
initializeNMS(loader, nmsPackage);
if (this.READ_LIMITER_CLASS != null) {
this.LOAD_COMPOUND = new LoadMethodSkinUpdate(this.STREAM_TOOLS, this.READ_LIMITER_CLASS);
this.LOAD_COMPOUND =
new LoadMethodSkinUpdate(this.STREAM_TOOLS, this.READ_LIMITER_CLASS);
} else {
this.LOAD_COMPOUND = new LoadMethodWorldUpdate(this.STREAM_TOOLS);
}
this.SAVE_COMPOUND = getMethod(Modifier.STATIC, 0, this.STREAM_TOOLS, null, this.BASE_CLASS, DataOutput.class);
this.SAVE_COMPOUND =
getMethod(Modifier.STATIC, 0, this.STREAM_TOOLS, null, this.BASE_CLASS,
DataOutput.class);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Unable to find offline player.", e);
@ -106,6 +93,7 @@ public class NbtFactory {
/**
* Retrieve or construct a shared NBT factory.
*
* @return The factory.
*/
private static NbtFactory get() {
@ -117,6 +105,7 @@ public class NbtFactory {
/**
* Construct a new NBT list of an unspecified type.
*
* @return The NBT list.
*/
public static NbtList createList(Object... content) {
@ -125,6 +114,7 @@ public class NbtFactory {
/**
* Construct a new NBT list of an unspecified type.
*
* @return The NBT list.
*/
public static NbtList createList(Iterable<? extends Object> iterable) {
@ -148,6 +138,7 @@ public class NbtFactory {
/**
* Construct a new NBT wrapper from a list.
*
* @param nmsList - the NBT list.
* @return The wrapper.
*/
@ -158,12 +149,13 @@ public class NbtFactory {
/**
* Load the content of a file from a stream.
*
* @param input - the stream.
* @param input - the stream.
* @param option - whether or not to decompress the input stream.
* @return The decoded NBT compound.
* @throws IOException If anything went wrong.
*/
public static NbtCompound fromStream(InputStream input, StreamOptions option) throws IOException {
public static NbtCompound fromStream(InputStream input, StreamOptions option)
throws IOException {
DataInputStream data = null;
boolean suppress = true;
@ -195,14 +187,16 @@ public class NbtFactory {
* @param option - whether or not to compress the output.
* @throws IOException If anything went wrong.
*/
public static void saveStream(NbtCompound source, ByteSink stream, StreamOptions option) throws IOException {
public static void saveStream(NbtCompound source, ByteSink stream, StreamOptions option)
throws IOException {
OutputStream output = null;
DataOutputStream data = null;
boolean suppress = true;
try {
output = stream.openStream();
data = new DataOutputStream(option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output);
data = new DataOutputStream(
option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output);
invokeMethod(get().SAVE_COMPOUND, null, source.getHandle(), data);
suppress = false;
@ -218,6 +212,7 @@ public class NbtFactory {
/**
* Construct a new NBT wrapper from a compound.
*
* @param nmsCompound - the NBT compound.
* @return The wrapper.
*/
@ -228,7 +223,8 @@ public class NbtFactory {
/**
* Set the NBT compound tag of a given item stack.
* <p>
* @param stack - the item stack, cannot be air.
*
* @param stack - the item stack, cannot be air.
* @param compound - the new NBT compound, or NULL to remove it.
* @throws IllegalArgumentException If the stack is not a CraftItemStack, or it represents air.
*/
@ -246,6 +242,7 @@ public class NbtFactory {
* material, damage value or count.
* <p>
* The item stack must be a wrapper for a CraftItemStack.
*
* @param stack - the item stack.
* @return A wrapper for its NBT tag.
*/
@ -265,6 +262,7 @@ public class NbtFactory {
/**
* Retrieve a CraftItemStack version of the stack.
*
* @param stack - the stack to convert.
* @return The CraftItemStack version.
*/
@ -279,12 +277,14 @@ public class NbtFactory {
caller.setAccessible(true);
return (ItemStack) caller.newInstance(stack);
} catch (Exception ignored) {
throw new IllegalStateException("Unable to convert " + stack + " + to a CraftItemStack.");
throw new IllegalStateException(
"Unable to convert " + stack + " + to a CraftItemStack.");
}
}
/**
* Ensure that the given stack can store arbitrary NBT information.
*
* @param stack - the stack to check.
*/
private static void checkItemStack(ItemStack stack) {
@ -295,12 +295,14 @@ public class NbtFactory {
throw new IllegalArgumentException("Stack must be a CraftItemStack.");
}
if (stack.getType() == Material.AIR) {
throw new IllegalArgumentException("ItemStacks representing air cannot store NMS information.");
throw new IllegalArgumentException(
"ItemStacks representing air cannot store NMS information.");
}
}
/**
* Invoke a method on the given target instance using the provided parameters.
*
* @param method - the method to invoke.
* @param target - the target.
* @param params - the parameters to supply.
@ -332,22 +334,23 @@ public class NbtFactory {
/**
* Search for the first publicly and privately defined method of the given name and parameter count.
*
* @param requireMod - modifiers that are required.
* @param bannedMod - modifiers that are banned.
* @param clazz - a class to start with.
* @param bannedMod - modifiers that are banned.
* @param clazz - a class to start with.
* @param methodName - the method name, or NULL to skip.
* @param params - the expected parameters.
* @param params - the expected parameters.
* @return The first method by this name.
* @throws IllegalStateException If we cannot find this method.
*/
private static Method getMethod(int requireMod, int bannedMod, Class<?> clazz, String methodName,
Class<?>... params) {
private static Method getMethod(int requireMod, int bannedMod, Class<?> clazz,
String methodName, Class<?>... params) {
for (Method method : clazz.getDeclaredMethods()) {
// Limitation: Doesn't handle overloads
if (((method.getModifiers() & requireMod) == requireMod)
&& ((method.getModifiers() & bannedMod) == 0)
&& ((methodName == null) || method.getName().equals(methodName))
&& Arrays.equals(method.getParameterTypes(), params)) {
if (((method.getModifiers() & requireMod) == requireMod) && (
(method.getModifiers() & bannedMod) == 0) && ((methodName == null) || method
.getName().equals(methodName)) && Arrays
.equals(method.getParameterTypes(), params)) {
method.setAccessible(true);
return method;
@ -357,13 +360,15 @@ public class NbtFactory {
if (clazz.getSuperclass() != null) {
return getMethod(requireMod, bannedMod, clazz.getSuperclass(), methodName, params);
}
throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params)));
throw new IllegalStateException(
String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params)));
}
/**
* Search for the first publicly and privately defined field of the given name.
* @param instance - an instance of the class with the field.
* @param clazz - an optional class to start with, or NULL to deduce it from instance.
*
* @param instance - an instance of the class with the field.
* @param clazz - an optional class to start with, or NULL to deduce it from instance.
* @param fieldName - the field name.
* @return The first field by this name.
* @throws IllegalStateException If we cannot find this field.
@ -390,7 +395,8 @@ public class NbtFactory {
try {
this.STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools");
this.READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter");
} catch (ClassNotFoundException ignored) {}
} catch (ClassNotFoundException ignored) {
}
}
private String getPackageName() {
@ -404,24 +410,25 @@ public class NbtFactory {
return "org.bukkit.craftbukkit.v1_13_R1";
}
}
private String getCraftPackageName() {
String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
return "net.minecraft.server." + version;
private String getCraftPackageName() {
String version =
Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
return "net.minecraft.server." + version;
}
@SuppressWarnings("unchecked")
private Map<String, Object> getDataMap(Object handle) {
return (Map<String, Object>) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle), handle);
@SuppressWarnings("unchecked") private Map<String, Object> getDataMap(Object handle) {
return (Map<String, Object>) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle),
handle);
}
@SuppressWarnings("unchecked")
private List<Object> getDataList(Object handle) {
@SuppressWarnings("unchecked") private List<Object> getDataList(Object handle) {
return (List<Object>) getFieldValue(getDataField(NbtType.TAG_LIST, handle), handle);
}
/**
* Convert wrapped List and Map objects into their respective NBT counterparts.
*
* @param value - the value of the element to create. Can be a List or a Map.
* @return The NBT element.
*/
@ -444,6 +451,7 @@ public class NbtFactory {
/**
* Convert a given NBT element to a primitive wrapper or List/Map equivalent.
* <p> All changes to any mutable objects will be reflected in the underlying NBT element(s).
*
* @param nms - the NBT element.
* @return The wrapper equivalent.
*/
@ -470,7 +478,8 @@ public class NbtFactory {
/**
* Construct a new NMS NBT tag initialized with the given value.
* @param type - the NBT type.
*
* @param type - the NBT type.
* @param value - the value, or NULL to keep the original value.
* @return The created tag.
*/
@ -485,8 +494,9 @@ public class NbtFactory {
/**
* Retrieve the field where the NBT class stores its value.
*
* @param type - the NBT type.
* @param nms - the NBT class instance.
* @param nms - the NBT class instance.
* @return The corresponding field.
*/
private Field getDataField(NbtType type, Object nms) {
@ -498,6 +508,7 @@ public class NbtFactory {
/**
* Retrieve the NBT type from a given NMS NBT tag.
*
* @param nms - the native NBT tag.
* @return The corresponding type.
*/
@ -508,40 +519,38 @@ public class NbtFactory {
/**
* Retrieve the nearest NBT type for a given primitive type.
*
* @param primitive - the primitive type.
* @return The corresponding type.
*/
private NbtType getPrimitiveType(Object primitive) {
NbtType type = NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass())));
NbtType type =
NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass())));
// Display the illegal value at least
if (type == null) {
throw new IllegalArgumentException(String.format("Illegal type: %s (%s)", primitive.getClass(), primitive));
throw new IllegalArgumentException(
String.format("Illegal type: %s (%s)", primitive.getClass(), primitive));
}
return type;
}
/**
* Whether or not to enable stream compression.
*
* @author Kristian
*/
public enum StreamOptions {
NO_COMPRESSION, GZIP_COMPRESSION,
}
private enum NbtType {
TAG_END(0, Void.class),
TAG_BYTE(1, byte.class),
TAG_SHORT(2, short.class),
TAG_INT(3, int.class),
TAG_LONG(4, long.class),
TAG_FLOAT(5, float.class),
TAG_DOUBLE(6, double.class),
TAG_BYTE_ARRAY(7, byte[].class),
TAG_INT_ARRAY(11, int[].class),
TAG_STRING(8, String.class),
TAG_LIST(9, List.class),
TAG_COMPOUND(10, Map.class);
TAG_END(0, Void.class), TAG_BYTE(1, byte.class), TAG_SHORT(2, short.class), TAG_INT(3,
int.class), TAG_LONG(4, long.class), TAG_FLOAT(5, float.class), TAG_DOUBLE(6,
double.class), TAG_BYTE_ARRAY(7, byte[].class), TAG_INT_ARRAY(11,
int[].class), TAG_STRING(8, String.class), TAG_LIST(9, List.class), TAG_COMPOUND(10,
Map.class);
// Unique NBT type
public final int id;
@ -563,21 +572,26 @@ public class NbtFactory {
}
}
/**
* Represents an object that provides a view of a native NMS class.
*
* @author Kristian
*/
public interface Wrapper {
/**
* Retrieve the underlying native NBT tag.
*
* @return The underlying NBT.
*/
Object getHandle();
}
/**
* Represents a method for loading an NBT compound.
*
* @author Kristian
*/
private static abstract class LoadCompoundMethod {
@ -591,12 +605,14 @@ public class NbtFactory {
/**
* Load an NBT compound from a given stream.
*
* @param input - the input stream.
* @return The loaded NBT compound.
*/
public abstract Object loadNbt(DataInput input);
}
/**
* Load an NBT compound from the NBTCompressedStreamTools static method in 1.7.2 - 1.7.5
*/
@ -606,12 +622,12 @@ public class NbtFactory {
setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class));
}
@Override
public Object loadNbt(DataInput input) {
@Override public Object loadNbt(DataInput input) {
return invokeMethod(this.staticMethod, null, input);
}
}
/**
* Load an NBT compound from the NBTCompressedStreamTools static method in 1.7.8
*/
@ -620,7 +636,8 @@ public class NbtFactory {
private Object readLimiter;
LoadMethodSkinUpdate(Class<?> streamClass, Class<?> readLimiterClass) {
setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class, readLimiterClass));
setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class,
readLimiterClass));
// Find the unlimited read limiter
for (Field field : readLimiterClass.getDeclaredFields()) {
@ -634,27 +651,28 @@ public class NbtFactory {
}
}
@Override
public Object loadNbt(DataInput input) {
@Override public Object loadNbt(DataInput input) {
return invokeMethod(this.staticMethod, null, input, this.readLimiter);
}
}
/**
* Represents a root NBT compound.
* <p> All changes to this map will be reflected in the underlying NBT compound. Values may only be one of the following:
* <ul>
* <li>Primitive types</li>
* <li>{@link String String}</li>
* <li>{@link NbtList}</li>
* <li>{@link NbtCompound}</li>
* <li>Primitive types</li>
* <li>{@link String String}</li>
* <li>{@link NbtList}</li>
* <li>{@link NbtCompound}</li>
* </ul>
* <p>
* See also:
* <ul>
* <li>{@link NbtFactory#createCompound()}</li>
* <li>{@link NbtFactory#fromCompound(Object)}</li>
* <li>{@link NbtFactory#createCompound()}</li>
* <li>{@link NbtFactory#fromCompound(Object)}</li>
* </ul>
*
* @author Kristian
*/
public final class NbtCompound extends ConvertedMap {
@ -702,7 +720,8 @@ public class NbtFactory {
/**
* Retrieve the list by the given name.
* @param key - the name of the list.
*
* @param key - the name of the list.
* @param createNew - whether or not to create a new list if its missing.
* @return An existing list, a new list or NULL.
*/
@ -717,7 +736,8 @@ public class NbtFactory {
/**
* Retrieve the map by the given name.
* @param key - the name of the map.
*
* @param key - the name of the map.
* @param createNew - whether or not to create a new map if its missing.
* @return An existing map, a new map or NULL.
*/
@ -732,7 +752,8 @@ public class NbtFactory {
* <p>
* Every element of the path (except the end) are assumed to be compounds, and will
* be created if they are missing.
* @param path - the path to the entry.
*
* @param path - the path to the entry.
* @param value - the new value of this entry.
* @return This compound, for chaining.
*/
@ -749,11 +770,11 @@ public class NbtFactory {
* <p>
* Every element of the path (except the end) are assumed to be compounds. The
* retrieval operation will be cancelled if any of them are missing.
*
* @param path - path to the entry.
* @return The value, or NULL if not found.
*/
@SuppressWarnings("unchecked")
public <T> T getPath(String path) {
@SuppressWarnings("unchecked") public <T> T getPath(String path) {
List<String> entries = getPathElements(path);
NbtCompound map = getMap(entries.subList(0, entries.size() - 1), false);
@ -765,6 +786,7 @@ public class NbtFactory {
/**
* Save the content of a NBT compound to a stream.
*
* @param stream - the output stream.
* @param option - whether or not to compress the output.
* @throws IOException If anything went wrong.
@ -775,7 +797,8 @@ public class NbtFactory {
/**
* Retrieve a map from a given path.
* @param path - path of compounds to look up.
*
* @param path - path of compounds to look up.
* @param createNew - whether or not to create new compounds on the way.
* @return The map at this location.
*/
@ -798,6 +821,7 @@ public class NbtFactory {
/**
* Split the path into separate elements.
*
* @param path - the path to split.
* @return The elements.
*/
@ -806,13 +830,15 @@ public class NbtFactory {
}
}
/**
* Represents a root NBT list.
* See also:
* <ul>
* <li>{@link NbtFactory#createList(Iterable)}}</li>
* <li>{@link NbtFactory#fromList(Object)}</li>
* <li>{@link NbtFactory#createList(Iterable)}}</li>
* <li>{@link NbtFactory#fromList(Object)}</li>
* </ul>
*
* @author Kristian
*/
public final class NbtList extends ConvertedList {
@ -822,8 +848,10 @@ public class NbtFactory {
}
}
/**
* Represents a class for caching wrappers.
*
* @author Kristian
*/
private final class CachedNativeWrapper {
@ -846,9 +874,11 @@ public class NbtFactory {
}
}
/**
* Represents a map that wraps another map and automatically
* converts entries of its type and another exposed type.
*
* @author Kristian
*/
private class ConvertedMap extends AbstractMap<String, Object> implements Wrapper {
@ -873,32 +903,26 @@ public class NbtFactory {
}
// Modification
@Override
public Object put(String key, Object value) {
@Override public Object put(String key, Object value) {
return wrapOutgoing(this.original.put(key, unwrapIncoming(value)));
}
// Performance
@Override
public Object get(Object key) {
@Override public Object get(Object key) {
return wrapOutgoing(this.original.get(key));
}
@Override
public Object remove(Object key) {
@Override public Object remove(Object key) {
return wrapOutgoing(this.original.remove(key));
}
@Override
public boolean containsKey(Object key) {
@Override public boolean containsKey(Object key) {
return this.original.containsKey(key);
}
@Override
public Set<Entry<String, Object>> entrySet() {
@Override public Set<Entry<String, Object>> entrySet() {
return new AbstractSet<Entry<String, Object>>() {
@Override
public boolean add(Entry<String, Object> e) {
@Override public boolean add(Entry<String, Object> e) {
String key = e.getKey();
Object value = e.getValue();
@ -906,13 +930,11 @@ public class NbtFactory {
return true;
}
@Override
public int size() {
@Override public int size() {
return ConvertedMap.this.original.size();
}
@Override
public Iterator<Entry<String, Object>> iterator() {
@Override public Iterator<Entry<String, Object>> iterator() {
return ConvertedMap.this.iterator();
}
};
@ -922,34 +944,33 @@ public class NbtFactory {
final Iterator<Entry<String, Object>> proxy = this.original.entrySet().iterator();
return new Iterator<Entry<String, Object>>() {
@Override
public boolean hasNext() {
@Override public boolean hasNext() {
return proxy.hasNext();
}
@Override
public Entry<String, Object> next() {
@Override public Entry<String, Object> next() {
Entry<String, Object> entry = proxy.next();
return new SimpleEntry<String, Object>(entry.getKey(), wrapOutgoing(entry.getValue()));
return new SimpleEntry<String, Object>(entry.getKey(),
wrapOutgoing(entry.getValue()));
}
@Override
public void remove() {
@Override public void remove() {
proxy.remove();
}
};
}
@Override
public Object getHandle() {
@Override public Object getHandle() {
return this.handle;
}
}
/**
* Represents a list that wraps another list and converts elements
* of its type and another exposed type.
*
* @author Kristian
*/
private class ConvertedList extends AbstractList<Object> implements Wrapper {
@ -975,44 +996,38 @@ public class NbtFactory {
return unwrapValue(wrapped);
}
@Override
public Object get(int index) {
@Override public Object get(int index) {
return wrapOutgoing(this.original.get(index));
}
@Override
public int size() {
@Override public int size() {
return this.original.size();
}
@Override
public Object set(int index, Object element) {
@Override public Object set(int index, Object element) {
return wrapOutgoing(this.original.set(index, unwrapIncoming(element)));
}
@Override
public void add(int index, Object element) {
@Override public void add(int index, Object element) {
Object nbt = unwrapIncoming(element);
// Set the list type if its the first element
if (size() == 0) {
setFieldValue(NbtFactory.this.NBT_LIST_TYPE, this.handle, (byte) getNbtType(nbt).id);
setFieldValue(NbtFactory.this.NBT_LIST_TYPE, this.handle,
(byte) getNbtType(nbt).id);
}
this.original.add(index, nbt);
}
@Override
public Object remove(int index) {
@Override public Object remove(int index) {
return wrapOutgoing(this.original.remove(index));
}
@Override
public boolean remove(Object o) {
@Override public boolean remove(Object o) {
return this.original.remove(unwrapIncoming(o));
}
@Override
public Object getHandle() {
@Override public Object getHandle() {
return this.handle;
}
}

View File

@ -1,13 +1,5 @@
package com.plotsquared.bukkit.util;
import static com.intellectualcrafters.plot.util.ReflectionUtils.callConstructor;
import static com.intellectualcrafters.plot.util.ReflectionUtils.callMethod;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getCbClass;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getNmsClass;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getUtilClass;
import static com.intellectualcrafters.plot.util.ReflectionUtils.makeConstructor;
import static com.intellectualcrafters.plot.util.ReflectionUtils.makeMethod;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Entity;
@ -17,6 +9,8 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.UUID;
import static com.intellectualcrafters.plot.util.ReflectionUtils.*;
public class OfflinePlayerUtil {
public static Player loadPlayer(String name) {
@ -43,10 +37,12 @@ public class OfflinePlayerUtil {
Object worldServer = getWorldServer();
Object profile = newGameProfile(id, name);
Class<?> entityPlayerClass = getNmsClass("EntityPlayer");
Constructor entityPlayerConstructor = makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), getNmsClass("WorldServer"),
getUtilClass("com.mojang.authlib.GameProfile"),
Constructor entityPlayerConstructor =
makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"),
getNmsClass("WorldServer"), getUtilClass("com.mojang.authlib.GameProfile"),
getNmsClass("PlayerInteractManager"));
Object entityPlayer = callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager);
Object entityPlayer =
callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager);
return (Player) getBukkitEntity(entityPlayer);
}
@ -55,7 +51,8 @@ public class OfflinePlayerUtil {
if (gameProfileClass == null) { //Before uuids
return name;
}
Constructor gameProfileConstructor = makeConstructor(gameProfileClass, UUID.class, String.class);
Constructor gameProfileConstructor =
makeConstructor(gameProfileClass, UUID.class, String.class);
if (gameProfileConstructor == null) { //Version has string constructor
gameProfileConstructor = makeConstructor(gameProfileClass, String.class, String.class);
return callConstructor(gameProfileConstructor, id.toString(), name);

View File

@ -1,7 +1,5 @@
package com.plotsquared.bukkit.util;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.Location;
@ -25,6 +23,8 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
/**
* An utility that can be used to send chunks, rather than using bukkit code
* to do so (uses heavy NMS).
@ -52,12 +52,14 @@ public class SendChunk {
RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk");
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_4)) {
//this works for 1.9.4 and 1.10
tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(),int.class);
tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), int.class);
} else {
try {
tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class);
tempMapChunk = classMapChunk
.getConstructor(classChunk.getRealClass(), boolean.class, int.class);
} catch (NoSuchMethodException ignored) {
tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(),boolean.class, int.class, int.class);
tempMapChunk = classMapChunk
.getConstructor(classChunk.getRealClass(), boolean.class, int.class, int.class);
}
}
this.mapChunk = tempMapChunk;
@ -118,8 +120,9 @@ public class SendChunk {
Object packet = null;
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_4)) {
try {
packet = this.mapChunk.create(c,65535);
} catch (Exception ignored) {}
packet = this.mapChunk.create(c, 65535);
} catch (Exception ignored) {
}
} else {
try {
packet = this.mapChunk.create(c, true, 65535);
@ -139,16 +142,16 @@ public class SendChunk {
}
for (final Chunk chunk : chunks) {
TaskManager.runTask(new Runnable() {
@Override
public void run() {
@Override public void run() {
try {
chunk.unload(true, false);
} catch (Throwable ignored) {
String worldName = chunk.getWorld().getName();
PS.debug("$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" + chunk.getZ());
PS.debug("$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";"
+ chunk.getZ());
PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
PS.debug("$3 - $4" + worldName + "/level.dat or " + worldName
+ "/level_old.dat may be corrupt (try repairing or removing these)");
+ "/level_old.dat may be corrupt (try repairing or removing these)");
}
}
});

View File

@ -4,34 +4,35 @@ import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
private Field fieldNeighbors;
private Method chunkGetHandle;
public BukkitLocalQueue(String world) {
super(world);
}
@Override
public LocalChunk<T> getLocalChunk(int x, int z) {
@Override public LocalChunk<T> getLocalChunk(int x, int z) {
return (LocalChunk<T>) new BasicLocalChunk(this, x, z) {
// Custom stuff?
};
}
@Override
public void optimize() {
@Override public void optimize() {
}
@Override
public PlotBlock getBlock(int x, int y, int z) {
@Override public PlotBlock getBlock(int x, int y, int z) {
World worldObj = Bukkit.getWorld(getWorld());
Block block = worldObj.getBlockAt(x, y, z);
if (block == null) {
@ -44,25 +45,21 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
return PlotBlock.get(id, block.getData());
}
@Override
public void refreshChunk(int x, int z) {
@Override public void refreshChunk(int x, int z) {
World worldObj = Bukkit.getWorld(getWorld());
worldObj.refreshChunk(x, z);
}
@Override
public void fixChunkLighting(int x, int z) {
@Override public void fixChunkLighting(int x, int z) {
// Do nothing
}
@Override
public final void regenChunk(int x, int z) {
@Override public final void regenChunk(int x, int z) {
World worldObj = Bukkit.getWorld(getWorld());
worldObj.regenerateChunk(x, z);
}
@Override
public final void setComponents(LocalChunk<T> lc) {
@Override public final void setComponents(LocalChunk<T> lc) {
setBlocks(lc);
setBiomes(lc);
}
@ -129,13 +126,11 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
}
}
private Field fieldNeighbors;
private Method chunkGetHandle;
/**
* Exploiting a bug in the vanilla lighting algorithm for faster block placement
* - Could have been achieved without reflection by force unloading specific chunks
* - Much faster just setting the variable manually though
* - Could have been achieved without reflection by force unloading specific chunks
* - Much faster just setting the variable manually though
*
* @param chunk
* @return
*/
@ -153,7 +148,8 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
Object value = fieldNeighbors.get(nmsChunk);
fieldNeighbors.set(nmsChunk, 0);
return new Object[] {nmsChunk, value};
} catch (Throwable ignore) {}
} catch (Throwable ignore) {
}
return null;
}
@ -181,7 +177,8 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
if (disableResult != null) {
try {
fieldNeighbors.set(disableResult[0], 0x739C0);
} catch (Throwable ignore) {}
} catch (Throwable ignore) {
}
}
}
}
}

View File

@ -6,16 +6,11 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.ReflectionUtils;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.SendChunk;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import java.util.*;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
@ -36,24 +31,26 @@ public class BukkitLocalQueue_1_7 extends BukkitLocalQueue<PlotBlock[]> {
private final HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>();
public BukkitLocalQueue_1_7(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
public BukkitLocalQueue_1_7(String world)
throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
super(world);
this.methodGetHandle = this.classCraftWorld.getMethod("getHandle");
this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class);
this.methodA = this.classChunk.getMethod("a", int.class, int.class, int.class, this.classBlock, int.class);
this.methodA = this.classChunk
.getMethod("a", int.class, int.class, int.class, this.classBlock, int.class);
this.methodGetById = this.classBlock.getMethod("getById", int.class);
this.methodGetHandleChunk = this.classCraftChunk.getMethod("getHandle");
this.methodInitLighting = this.classChunk.getMethod("initLighting");
this.sendChunk = new SendChunk();
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
@Override public void run() {
if (BukkitLocalQueue_1_7.this.toUpdate.isEmpty()) {
return;
}
int count = 0;
ArrayList<Chunk> chunks = new ArrayList<>();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i = BukkitLocalQueue_1_7.this.toUpdate.entrySet().iterator();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i =
BukkitLocalQueue_1_7.this.toUpdate.entrySet().iterator();
while (i.hasNext() && (count < 128)) {
chunks.add(i.next().getValue());
i.remove();
@ -88,14 +85,12 @@ public class BukkitLocalQueue_1_7 extends BukkitLocalQueue<PlotBlock[]> {
}
}
@Override
public void fixChunkLighting(int x, int z) {
@Override public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
@Override
public void setBlocks(LocalChunk<PlotBlock[]> lc) {
@Override public void setBlocks(LocalChunk<PlotBlock[]> lc) {
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
@ -128,8 +123,7 @@ public class BukkitLocalQueue_1_7 extends BukkitLocalQueue<PlotBlock[]> {
fixChunkLighting(lc.getX(), lc.getZ());
}
@Override
public void refreshChunk(int x, int z) {
@Override public void refreshChunk(int x, int z) {
update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z)));
}
}

View File

@ -1,7 +1,5 @@
package com.plotsquared.bukkit.util.block;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import com.intellectualcrafters.plot.object.ChunkWrapper;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
@ -10,17 +8,15 @@ import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.SendChunk;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import java.util.*;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
public class BukkitLocalQueue_1_8 extends BukkitLocalQueue<PlotBlock[]> {
private final ReflectionUtils.RefMethod methodInitLighting;
@ -39,26 +35,29 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue<PlotBlock[]> {
private final SendChunk sendChunk;
private final RefMethod methodGetHandleChunk;
public BukkitLocalQueue_1_8(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
public BukkitLocalQueue_1_8(String world)
throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
super(world);
this.methodInitLighting = this.classChunk.getMethod("initLighting");
this.constructorBlockPosition = this.classBlockPosition.getConstructor(int.class, int.class, int.class);
this.constructorBlockPosition =
this.classBlockPosition.getConstructor(int.class, int.class, int.class);
this.methodGetByCombinedId = this.classBlock.getMethod("getByCombinedId", int.class);
this.methodGetHandle = this.classCraftWorld.getMethod("getHandle");
RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class);
this.methodA = this.classChunk.getMethod("a", this.classBlockPosition, this.classIBlockData);
this.methodA =
this.classChunk.getMethod("a", this.classBlockPosition, this.classIBlockData);
this.sendChunk = new SendChunk();
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
@Override public void run() {
if (BukkitLocalQueue_1_8.this.toUpdate.isEmpty()) {
return;
}
int count = 0;
ArrayList<Chunk> chunks = new ArrayList<>();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i = BukkitLocalQueue_1_8.this.toUpdate.entrySet().iterator();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i =
BukkitLocalQueue_1_8.this.toUpdate.entrySet().iterator();
while (i.hasNext() && count < 128) {
chunks.add(i.next().getValue());
i.remove();
@ -73,14 +72,12 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue<PlotBlock[]> {
MainUtil.initCache();
}
@Override
public void fixChunkLighting(int x, int z) {
@Override public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
@Override
public void setBlocks(LocalChunk<PlotBlock[]> lc) {
@Override public void setBlocks(LocalChunk<PlotBlock[]> lc) {
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
@ -100,7 +97,8 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue<PlotBlock[]> {
int y = MainUtil.y_loc[i][j];
int z = MainUtil.z_loc[i][j];
PlotBlock newBlock = result2[j];
if (newBlock == null) continue;
if (newBlock == null)
continue;
if (newBlock.id == -1) {
chunk.getBlock(x, y, z).setData(newBlock.data, false);
@ -309,7 +307,8 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue<PlotBlock[]> {
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
Object combined = this.methodGetByCombinedId.call(newBlock.id + (newBlock.data << 12));
Object combined =
this.methodGetByCombinedId.call(newBlock.id + (newBlock.data << 12));
this.methodA.of(c).call(pos, combined);
}
}
@ -336,8 +335,7 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue<PlotBlock[]> {
}
}
@Override
public void refreshChunk(int x, int z) {
@Override public void refreshChunk(int x, int z) {
update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z)));
}
}

View File

@ -9,20 +9,14 @@ import com.intellectualcrafters.plot.util.ReflectionUtils;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue;
import com.plotsquared.bukkit.util.SendChunk;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
@ -43,7 +37,8 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue<char[]> {
private final ReflectionUtils.RefMethod methodGetWorld;
private final ReflectionUtils.RefField tileEntityListTick;
public BukkitLocalQueue_1_8_3(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
public BukkitLocalQueue_1_8_3(String world)
throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
super(world);
ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
@ -51,7 +46,8 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue<char[]> {
ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
this.methodInitLighting = classChunk.getMethod("initLighting");
ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class);
this.classBlockPositionConstructor =
classBlockPosition.getConstructor(int.class, int.class, int.class);
ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World");
this.methodX = classWorld.getMethod("x", classBlockPosition.getRealClass());
this.fieldSections = classChunk.getField("sections");
@ -59,20 +55,21 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue<char[]> {
ReflectionUtils.RefClass classChunkSection = getRefClass("{nms}.ChunkSection");
this.methodGetIdArray = classChunkSection.getMethod("getIdArray");
this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class);
this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class);
this.classChunkSectionConstructor =
classChunkSection.getConstructor(int.class, boolean.class, char[].class);
this.tileEntityListTick = classWorld.getField("tileEntityList");
this.methodGetHandleWorld = classCraftWorld.getMethod("getHandle");
this.methodGetWorld = classChunk.getMethod("getWorld");
this.sendChunk = new SendChunk();
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
@Override public void run() {
if (BukkitLocalQueue_1_8_3.this.toUpdate.isEmpty()) {
return;
}
int count = 0;
ArrayList<Chunk> chunks = new ArrayList<>();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i = BukkitLocalQueue_1_8_3.this.toUpdate.entrySet().iterator();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i =
BukkitLocalQueue_1_8_3.this.toUpdate.entrySet().iterator();
while (i.hasNext() && count < 128) {
chunks.add(i.next().getValue());
i.remove();
@ -87,11 +84,290 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue<char[]> {
MainUtil.initCache();
}
@Override
public LocalChunk<char[]> getLocalChunk(int x, int z) {
@Override public LocalChunk<char[]> getLocalChunk(int x, int z) {
return new CharLocalChunk_1_8_3(this, x, z);
}
@Override public void setBlocks(LocalChunk lc) {
CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc;
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ());
if (!this.toUpdate.containsKey(wrapper)) {
this.toUpdate.put(wrapper, chunk);
}
try {
boolean flag = world.getEnvironment() == World.Environment.NORMAL;
// Sections
Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
Object c = getHandle.invoke(chunk);
Object w = this.methodGetWorld.of(c).call();
Class<?> clazz = c.getClass();
Field sections1 = clazz.getDeclaredField("sections");
sections1.setAccessible(true);
Field tileEntities = clazz.getDeclaredField("tileEntities");
Field entitySlices = clazz.getDeclaredField("entitySlices");
Object[] sections = (Object[]) sections1.get(c);
Map<?, ?> tiles = (Map<?, ?>) tileEntities.get(c);
Collection<?>[] entities = (Collection<?>[]) entitySlices.get(c);
Method getX = null;
Method getY = null;
Method getZ = null;
// Trim tiles
boolean removed = false;
Set<Map.Entry<?, ?>> entrySet = (Set<Map.Entry<?, ?>>) (Set<?>) tiles.entrySet();
Iterator<Map.Entry<?, ?>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<?, ?> tile = iterator.next();
Object pos = tile.getKey();
if (getX == null) {
Class<? extends Object> clazz2 = pos.getClass().getSuperclass();
getX = clazz2.getDeclaredMethod("getX");
getY = clazz2.getDeclaredMethod("getY");
getZ = clazz2.getDeclaredMethod("getZ");
}
int lx = (int) getX.invoke(pos) & 15;
int ly = (int) getY.invoke(pos);
int lz = (int) getZ.invoke(pos) & 15;
int j = MainUtil.CACHE_I[ly][lx][lz];
int k = MainUtil.CACHE_J[ly][lx][lz];
char[] array = fs.getIdArray(j);
if (array == null) {
continue;
}
if (array[k] != 0) {
removed = true;
iterator.remove();
}
}
if (removed) {
((Collection) this.tileEntityListTick.of(w).get()).clear();
}
// Trim entities
for (int i = 0; i < 16; i++) {
if ((entities[i] != null) && (fs.getCount(i) >= 4096)) {
entities[i].clear();
}
}
// Efficiently merge sections
for (int j = 0; j < sections.length; j++) {
if (fs.getCount(j) == 0) {
continue;
}
char[] newArray = fs.getIdArray(j);
if (newArray == null) {
continue;
}
Object section = sections[j];
if ((section == null) || (fs.getCount(j) >= 4096)) {
section = sections[j] = newChunkSection(j << 4, flag, newArray);
continue;
}
char[] currentArray = getIdArray(section);
boolean fill = true;
for (int k = 0; k < newArray.length; k++) {
char n = newArray[k];
switch (n) {
case 0:
fill = false;
continue;
case 1:
fill = false;
currentArray[k] = 0;
continue;
default:
currentArray[k] = n;
continue;
}
}
if (fill) {
fs.setCount(j, Short.MAX_VALUE);
}
}
// Clear
} catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) {
e.printStackTrace();
}
fixLighting(chunk, fs, true);
}
public Object newChunkSection(int i, boolean flag, char[] ids)
throws ReflectiveOperationException {
return this.classChunkSectionConstructor.create(i, flag, ids);
}
public char[] getIdArray(Object obj) {
return (char[]) this.methodGetIdArray.of(obj).call();
}
@Override public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) {
try {
if (!chunk.isLoaded()) {
chunk.load(false);
} else {
chunk.unload(true, false);
chunk.load(false);
}
// Initialize lighting
Object c = this.methodGetHandleChunk.of(chunk).call();
if (fixAll && !(boolean) this.methodAreNeighborsLoaded.of(c).call(1)) {
World world = chunk.getWorld();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ());
for (int x = wrapper.x - 1; x <= wrapper.x + 1; x++) {
for (int z = wrapper.z - 1; z <= wrapper.z + 1; z++) {
if (x != 0 && z != 0) {
Chunk other = world.getChunkAt(x, z);
while (!other.isLoaded()) {
other.load(true);
}
ChunkManager.manager.loadChunk(wrapper.world, new ChunkLoc(x, z), true);
}
}
}
/*
if (!(boolean) methodAreNeighborsLoaded.of(c).call(1)) {
return false;
}
*/
}
this.methodInitLighting.of(c).call();
if (bc.getTotalRelight() == 0 && !fixAll) {
return true;
}
Object[] sections = (Object[]) this.fieldSections.of(c).get();
Object w = this.fieldWorld.of(c).get();
int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4;
ReflectionUtils.RefMethod.RefExecutor relight = this.methodX.of(w);
for (int j = 0; j < sections.length; j++) {
Object section = sections[j];
if (section == null) {
continue;
}
if ((bc.getRelight(j) == 0 && !fixAll) || bc.getCount(j) == 0 || (
bc.getCount(j) >= 4096 && bc.getAir(j) == 0)) {
continue;
}
char[] array = getIdArray(section);
int l = PseudoRandom.random.random(2);
for (int k = 0; k < array.length; k++) {
int i = array[k];
if (i < 16) {
continue;
}
short id = (short) (i >> 4);
switch (id) { // Lighting
default:
if (!fixAll) {
continue;
}
if ((k & 1) == l) {
l = 1 - l;
continue;
}
case 10:
case 11:
case 39:
case 40:
case 50:
case 51:
case 62:
case 74:
case 76:
case 89:
case 122:
case 124:
case 130:
case 138:
case 169:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
if (isSurrounded(sections, x, y, z)) {
continue;
}
Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z);
relight.call(pos);
}
}
}
return true;
} catch (Throwable e) {
e.printStackTrace();
}
return false;
}
public boolean isSurrounded(Object[] sections, int x, int y, int z) {
return isSolid(getId(sections, x, y + 1, z)) && isSolid(getId(sections, x + 1, y - 1, z))
&& isSolid(getId(sections, x - 1, y, z)) && isSolid(getId(sections, x, y, z + 1))
&& isSolid(getId(sections, x, y, z - 1));
}
public boolean isSolid(int i) {
return i != 0 && Material.getMaterial(i).isOccluding();
}
public int getId(Object[] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1;
}
if (y < 0 || y > 255) {
return 1;
}
int i = MainUtil.CACHE_I[y][x][z];
Object section = sections[i];
if (section == null) {
return 0;
}
char[] array = getIdArray(section);
int j = MainUtil.CACHE_J[y][x][z];
return array[j] >> 4;
}
public void update(Collection<Chunk> chunks) {
if (chunks.isEmpty()) {
return;
}
if (!MainUtil.canSendChunk) {
for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try {
this.sendChunk.sendChunk(chunks);
} catch (Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;
}
}
@Override public void refreshChunk(int x, int z) {
update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z)));
}
public class CharLocalChunk_1_8_3 extends CharLocalChunk {
public short[] count;
public short[] air;
@ -104,8 +380,7 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue<char[]> {
this.relight = new short[16];
}
@Override
public void setBlock(int x, int y, int z, int id, int data) {
@Override public void setBlock(int x, int y, int z, int id, int data) {
int i = MainUtil.CACHE_I[y][x][z];
int j = MainUtil.CACHE_J[y][x][z];
char[] vs = this.blocks[i];
@ -252,286 +527,4 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue<char[]> {
return total;
}
}
@Override
public void setBlocks(LocalChunk lc) {
CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc;
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ());
if (!this.toUpdate.containsKey(wrapper)) {
this.toUpdate.put(wrapper, chunk);
}
try {
boolean flag = world.getEnvironment() == World.Environment.NORMAL;
// Sections
Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
Object c = getHandle.invoke(chunk);
Object w = this.methodGetWorld.of(c).call();
Class<?> clazz = c.getClass();
Field sections1 = clazz.getDeclaredField("sections");
sections1.setAccessible(true);
Field tileEntities = clazz.getDeclaredField("tileEntities");
Field entitySlices = clazz.getDeclaredField("entitySlices");
Object[] sections = (Object[]) sections1.get(c);
Map<?, ?> tiles = (Map<?, ?>) tileEntities.get(c);
Collection<?>[] entities = (Collection<?>[]) entitySlices.get(c);
Method getX = null;
Method getY = null;
Method getZ = null;
// Trim tiles
boolean removed = false;
Set<Map.Entry<?, ?>> entrySet = (Set<Map.Entry<?, ?>>) (Set<?>) tiles.entrySet();
Iterator<Map.Entry<?, ?>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<?, ?> tile = iterator.next();
Object pos = tile.getKey();
if (getX == null) {
Class<? extends Object> clazz2 = pos.getClass().getSuperclass();
getX = clazz2.getDeclaredMethod("getX");
getY = clazz2.getDeclaredMethod("getY");
getZ = clazz2.getDeclaredMethod("getZ");
}
int lx = (int) getX.invoke(pos) & 15;
int ly = (int) getY.invoke(pos);
int lz = (int) getZ.invoke(pos) & 15;
int j = MainUtil.CACHE_I[ly][lx][lz];
int k = MainUtil.CACHE_J[ly][lx][lz];
char[] array = fs.getIdArray(j);
if (array == null) {
continue;
}
if (array[k] != 0) {
removed = true;
iterator.remove();
}
}
if (removed) {
((Collection) this.tileEntityListTick.of(w).get()).clear();
}
// Trim entities
for (int i = 0; i < 16; i++) {
if ((entities[i] != null) && (fs.getCount(i) >= 4096)) {
entities[i].clear();
}
}
// Efficiently merge sections
for (int j = 0; j < sections.length; j++) {
if (fs.getCount(j) == 0) {
continue;
}
char[] newArray = fs.getIdArray(j);
if (newArray == null) {
continue;
}
Object section = sections[j];
if ((section == null) || (fs.getCount(j) >= 4096)) {
section = sections[j] = newChunkSection(j << 4, flag, newArray);
continue;
}
char[] currentArray = getIdArray(section);
boolean fill = true;
for (int k = 0; k < newArray.length; k++) {
char n = newArray[k];
switch (n) {
case 0:
fill = false;
continue;
case 1:
fill = false;
currentArray[k] = 0;
continue;
default:
currentArray[k] = n;
continue;
}
}
if (fill) {
fs.setCount(j, Short.MAX_VALUE);
}
}
// Clear
} catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) {
e.printStackTrace();
}
fixLighting(chunk, fs, true);
}
public Object newChunkSection(int i, boolean flag, char[] ids) throws ReflectiveOperationException {
return this.classChunkSectionConstructor.create(i, flag, ids);
}
public char[] getIdArray(Object obj) {
return (char[]) this.methodGetIdArray.of(obj).call();
}
@Override
public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) {
try {
if (!chunk.isLoaded()) {
chunk.load(false);
} else {
chunk.unload(true, false);
chunk.load(false);
}
// Initialize lighting
Object c = this.methodGetHandleChunk.of(chunk).call();
if (fixAll && !(boolean) this.methodAreNeighborsLoaded.of(c).call(1)) {
World world = chunk.getWorld();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ());
for (int x = wrapper.x - 1; x <= wrapper.x + 1; x++) {
for (int z = wrapper.z - 1; z <= wrapper.z + 1; z++) {
if (x != 0 && z != 0) {
Chunk other = world.getChunkAt(x, z);
while (!other.isLoaded()) {
other.load(true);
}
ChunkManager.manager.loadChunk(wrapper.world, new ChunkLoc(x, z), true);
}
}
}
/*
if (!(boolean) methodAreNeighborsLoaded.of(c).call(1)) {
return false;
}
*/
}
this.methodInitLighting.of(c).call();
if (bc.getTotalRelight() == 0 && !fixAll) {
return true;
}
Object[] sections = (Object[]) this.fieldSections.of(c).get();
Object w = this.fieldWorld.of(c).get();
int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4;
ReflectionUtils.RefMethod.RefExecutor relight = this.methodX.of(w);
for (int j = 0; j < sections.length; j++) {
Object section = sections[j];
if (section == null) {
continue;
}
if ((bc.getRelight(j) == 0 && !fixAll) || bc.getCount(j) == 0 || (bc.getCount(j) >= 4096 && bc.getAir(j) == 0)) {
continue;
}
char[] array = getIdArray(section);
int l = PseudoRandom.random.random(2);
for (int k = 0; k < array.length; k++) {
int i = array[k];
if (i < 16) {
continue;
}
short id = (short) (i >> 4);
switch (id) { // Lighting
default:
if (!fixAll) {
continue;
}
if ((k & 1) == l) {
l = 1 - l;
continue;
}
case 10:
case 11:
case 39:
case 40:
case 50:
case 51:
case 62:
case 74:
case 76:
case 89:
case 122:
case 124:
case 130:
case 138:
case 169:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
if (isSurrounded(sections, x, y, z)) {
continue;
}
Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z);
relight.call(pos);
}
}
}
return true;
} catch (Throwable e) {
e.printStackTrace();
}
return false;
}
public boolean isSurrounded(Object[] sections, int x, int y, int z) {
return isSolid(getId(sections, x, y + 1, z))
&& isSolid(getId(sections, x + 1, y - 1, z))
&& isSolid(getId(sections, x - 1, y, z))
&& isSolid(getId(sections, x, y, z + 1))
&& isSolid(getId(sections, x, y, z - 1));
}
public boolean isSolid(int i) {
return i != 0 && Material.getMaterial(i).isOccluding();
}
public int getId(Object[] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1;
}
if (y < 0 || y > 255) {
return 1;
}
int i = MainUtil.CACHE_I[y][x][z];
Object section = sections[i];
if (section == null) {
return 0;
}
char[] array = getIdArray(section);
int j = MainUtil.CACHE_J[y][x][z];
return array[j] >> 4;
}
public void update(Collection<Chunk> chunks) {
if (chunks.isEmpty()) {
return;
}
if (!MainUtil.canSendChunk) {
for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try {
this.sendChunk.sendChunk(chunks);
} catch (Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;
}
}
@Override
public void refreshChunk(int x, int z) {
update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z)));
}
}

View File

@ -5,17 +5,13 @@ import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.ReflectionUtils;
import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
@ -40,14 +36,16 @@ public class BukkitLocalQueue_1_9 extends BukkitLocalQueue<char[]> {
private final ReflectionUtils.RefField tileEntityListTick;
public BukkitLocalQueue_1_9(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
public BukkitLocalQueue_1_9(String world)
throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
super(world);
ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
this.methodInitLighting = classChunk.getMethod("initLighting");
ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class);
this.classBlockPositionConstructor =
classBlockPosition.getConstructor(int.class, int.class, int.class);
ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World");
this.tileEntityListTick = classWorld.getField("tileEntityListTick");
this.methodGetWorld = classChunk.getMethod("getWorld");
@ -56,23 +54,284 @@ public class BukkitLocalQueue_1_9 extends BukkitLocalQueue<char[]> {
this.fieldWorld = classChunk.getField("world");
ReflectionUtils.RefClass classBlock = getRefClass("{nms}.Block");
ReflectionUtils.RefClass classIBlockData = getRefClass("{nms}.IBlockData");
this.methodGetCombinedId = classBlock.getMethod("getCombinedId", classIBlockData.getRealClass());
this.methodGetCombinedId =
classBlock.getMethod("getCombinedId", classIBlockData.getRealClass());
this.methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class);
ReflectionUtils.RefClass classChunkSection = getRefClass("{nms}.ChunkSection");
this.methodGetBlocks = classChunkSection.getMethod("getBlocks");
this.methodGetType = classChunkSection.getMethod("getType", int.class, int.class, int.class);
this.methodSetType = classChunkSection.getMethod("setType", int.class, int.class, int.class, classIBlockData.getRealClass());
this.methodGetType =
classChunkSection.getMethod("getType", int.class, int.class, int.class);
this.methodSetType = classChunkSection
.getMethod("setType", int.class, int.class, int.class, classIBlockData.getRealClass());
this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class);
this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class);
this.classChunkSectionConstructor =
classChunkSection.getConstructor(int.class, boolean.class, char[].class);
this.air = this.methodGetByCombinedId.call(0);
MainUtil.initCache();
}
@Override
public LocalChunk<char[]> getLocalChunk(int x, int z) {
@Override public LocalChunk<char[]> getLocalChunk(int x, int z) {
return new CharLocalChunk_1_8_3(this, x, z);
}
@Override public void setBlocks(LocalChunk lc) {
CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc;
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
try {
boolean flag = world.getEnvironment() == World.Environment.NORMAL;
// Sections
Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
Object c = getHandle.invoke(chunk);
Object w = this.methodGetWorld.of(c).call();
Class<? extends Object> clazz = c.getClass();
Field sf = clazz.getDeclaredField("sections");
sf.setAccessible(true);
Field tf = clazz.getDeclaredField("tileEntities");
Field entitySlices = clazz.getDeclaredField("entitySlices");
Object[] sections = (Object[]) sf.get(c);
Map<?, ?> tiles = (Map<?, ?>) tf.get(c);
Collection<?>[] entities = (Collection<?>[]) entitySlices.get(c);
Method xm = null;
Method ym = null;
Method zm = null;
// Trim tiles
Collection tickList = ((Collection) this.tileEntityListTick.of(w).get());
Set<Map.Entry<?, ?>> entrySet = (Set<Map.Entry<?, ?>>) (Set<?>) tiles.entrySet();
Iterator<Map.Entry<?, ?>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<?, ?> tile = iterator.next();
Object pos = tile.getKey();
if (xm == null) {
Class<?> clazz2 = pos.getClass().getSuperclass();
xm = clazz2.getDeclaredMethod("getX");
ym = clazz2.getDeclaredMethod("getY");
zm = clazz2.getDeclaredMethod("getZ");
}
int lx = (int) xm.invoke(pos) & 15;
int ly = (int) ym.invoke(pos);
int lz = (int) zm.invoke(pos) & 15;
int j = MainUtil.CACHE_I[ly][lx][lz];
int k = MainUtil.CACHE_J[ly][lx][lz];
char[] array = fs.getIdArray(j);
if (array == null) {
continue;
}
if (array[k] != 0) {
tickList.remove(tile.getValue());
iterator.remove();
}
}
// Trim entities
for (int i = 0; i < 16; i++) {
if (entities[i] != null && fs.getCount(i) >= 4096) {
entities[i].clear();
}
}
// Efficiently merge sections
for (int j = 0; j < sections.length; j++) {
if (fs.getCount(j) == 0) {
continue;
}
char[] newArray = fs.getIdArray(j);
if (newArray == null) {
continue;
}
Object section = sections[j];
if (section == null || fs.getCount(j) >= 4096) {
section = sections[j] = newChunkSection(j << 4, flag, fs.getIdArray(j));
continue;
}
Object currentArray = getBlocks(section);
ReflectionUtils.RefMethod.RefExecutor setType = this.methodSetType.of(section);
boolean fill = true;
for (int k = 0; k < newArray.length; k++) {
char n = newArray[k];
switch (n) {
case 0:
fill = false;
continue;
case 1: {
fill = false;
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
setType.call(x, y & 15, z, this.air);
continue;
}
default:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
int id = n >> 4;
int data = n & 15;
Object iBlock =
this.methodGetByCombinedId.call((int) (id & 0xFFF) + (data << 12));
setType.call(x, y & 15, z, iBlock);
}
}
if (fill) {
fs.setCount(j, Short.MAX_VALUE);
}
}
// Clear
} catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) {
e.printStackTrace();
}
fixLighting(chunk, fs, true);
refreshChunk(fs.getX(), fs.getZ());
}
public Object newChunkSection(int i, boolean flag, char[] ids)
throws ReflectiveOperationException {
return this.classChunkSectionConstructor.create(i, flag, ids);
}
public Object getBlocks(Object obj) {
return this.methodGetBlocks.of(obj).call();
}
@Override public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) {
try {
if (!chunk.isLoaded()) {
chunk.load(false);
} else {
chunk.unload(true, false);
chunk.load(false);
}
// Initialize lighting
Object c = this.methodGetHandleChunk.of(chunk).call();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), bc.getX(), bc.getZ());
Object[] result = disableLighting(chunk);
enableLighting(result);
this.methodInitLighting.of(c).call();
if (bc.getTotalRelight() != 0 || fixAll) {
Object[] sections = (Object[]) this.fieldSections.of(c).get();
Object w = this.fieldWorld.of(c).get();
int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4;
ReflectionUtils.RefMethod.RefExecutor relight = this.methodW.of(w);
for (int j = 0; j < sections.length; j++) {
Object section = sections[j];
if (section == null) {
continue;
}
if (bc.getRelight(j) == 0 && !fixAll || bc.getCount(j) == 0
|| bc.getCount(j) >= 4096 && bc.getAir(j) == 0) {
continue;
}
char[] array = bc.getIdArray(j);
if (array != null) {
int l = PseudoRandom.random.random(2);
for (int k = 0; k < array.length; k++) {
int i = array[k];
if (i < 16) {
continue;
}
short id = (short) (i >> 4);
switch (id) { // Lighting
default:
if (!fixAll) {
continue;
}
if ((k & 1) == l) {
l = 1 - l;
continue;
}
case 10:
case 11:
case 39:
case 40:
case 50:
case 51:
case 62:
case 74:
case 76:
case 89:
case 122:
case 124:
case 130:
case 138:
case 169:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
if (isSurrounded(bc.blocks, x, y, z)) {
continue;
}
Object pos =
this.classBlockPositionConstructor.create(X + x, y, Z + z);
relight.call(pos);
}
}
}
}
}
resetLighting(result);
return true;
} catch (Throwable e) {
e.printStackTrace();
}
return false;
}
@Override public void refreshChunk(int x, int z) {
getBukkitWorld().refreshChunk(x, z);
}
public boolean isSurrounded(char[][] sections, int x, int y, int z) {
return isSolid(getId(sections, x, y + 1, z)) && isSolid(getId(sections, x + 1, y - 1, z))
&& isSolid(getId(sections, x - 1, y, z)) && isSolid(getId(sections, x, y, z + 1))
&& isSolid(getId(sections, x, y, z - 1));
}
public boolean isSolid(int i) {
if (i != 0) {
Material material = Material.getMaterial(i);
return material != null && Material.getMaterial(i).isOccluding();
}
return false;
}
public int getId(char[] section, int x, int y, int z) {
if (section == null) {
return 0;
}
int j = MainUtil.CACHE_J[y][x][z];
return section[j] >> 4;
}
public int getId(char[][] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1;
}
if (y < 0 || y > 255) {
return 1;
}
int i = MainUtil.CACHE_I[y][x][z];
char[] section = sections[i];
if (section == null) {
return 0;
}
return getId(section, x, y, z);
}
public class CharLocalChunk_1_8_3 extends CharLocalChunk {
public short[] count;
public short[] air;
@ -85,8 +344,7 @@ public class BukkitLocalQueue_1_9 extends BukkitLocalQueue<char[]> {
this.relight = new short[16];
}
@Override
public void setBlock(int x, int y, int z, int id, int data) {
@Override public void setBlock(int x, int y, int z, int id, int data) {
int i = MainUtil.CACHE_I[y][x][z];
int j = MainUtil.CACHE_J[y][x][z];
char[] vs = this.blocks[i];
@ -233,262 +491,4 @@ public class BukkitLocalQueue_1_9 extends BukkitLocalQueue<char[]> {
return total;
}
}
@Override
public void setBlocks(LocalChunk lc) {
CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc;
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
try {
boolean flag = world.getEnvironment() == World.Environment.NORMAL;
// Sections
Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
Object c = getHandle.invoke(chunk);
Object w = this.methodGetWorld.of(c).call();
Class<? extends Object> clazz = c.getClass();
Field sf = clazz.getDeclaredField("sections");
sf.setAccessible(true);
Field tf = clazz.getDeclaredField("tileEntities");
Field entitySlices = clazz.getDeclaredField("entitySlices");
Object[] sections = (Object[]) sf.get(c);
Map<?, ?> tiles = (Map<?, ?>) tf.get(c);
Collection<?>[] entities = (Collection<?>[]) entitySlices.get(c);
Method xm = null;
Method ym = null;
Method zm = null;
// Trim tiles
Collection tickList = ((Collection) this.tileEntityListTick.of(w).get());
Set<Map.Entry<?, ?>> entrySet = (Set<Map.Entry<?, ?>>) (Set<?>) tiles.entrySet();
Iterator<Map.Entry<?, ?>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<?, ?> tile = iterator.next();
Object pos = tile.getKey();
if (xm == null) {
Class<?> clazz2 = pos.getClass().getSuperclass();
xm = clazz2.getDeclaredMethod("getX");
ym = clazz2.getDeclaredMethod("getY");
zm = clazz2.getDeclaredMethod("getZ");
}
int lx = (int) xm.invoke(pos) & 15;
int ly = (int) ym.invoke(pos);
int lz = (int) zm.invoke(pos) & 15;
int j = MainUtil.CACHE_I[ly][lx][lz];
int k = MainUtil.CACHE_J[ly][lx][lz];
char[] array = fs.getIdArray(j);
if (array == null) {
continue;
}
if (array[k] != 0) {
tickList.remove(tile.getValue());
iterator.remove();
}
}
// Trim entities
for (int i = 0; i < 16; i++) {
if (entities[i] != null && fs.getCount(i) >= 4096) {
entities[i].clear();
}
}
// Efficiently merge sections
for (int j = 0; j < sections.length; j++) {
if (fs.getCount(j) == 0) {
continue;
}
char[] newArray = fs.getIdArray(j);
if (newArray == null) {
continue;
}
Object section = sections[j];
if (section == null || fs.getCount(j) >= 4096) {
section = sections[j] = newChunkSection(j << 4, flag, fs.getIdArray(j));
continue;
}
Object currentArray = getBlocks(section);
ReflectionUtils.RefMethod.RefExecutor setType = this.methodSetType.of(section);
boolean fill = true;
for (int k = 0; k < newArray.length; k++) {
char n = newArray[k];
switch (n) {
case 0:
fill = false;
continue;
case 1: {
fill = false;
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
setType.call(x, y & 15, z, this.air);
continue;
}
default:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
int id = n >> 4;
int data = n & 15;
Object iBlock = this.methodGetByCombinedId.call((int) (id & 0xFFF) + (data << 12));
setType.call(x, y & 15, z, iBlock);
}
}
if (fill) {
fs.setCount(j, Short.MAX_VALUE);
}
}
// Clear
} catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) {
e.printStackTrace();
}
fixLighting(chunk, fs, true);
refreshChunk(fs.getX(), fs.getZ());
}
public Object newChunkSection(int i, boolean flag, char[] ids) throws ReflectiveOperationException {
return this.classChunkSectionConstructor.create(i, flag, ids);
}
public Object getBlocks(Object obj) {
return this.methodGetBlocks.of(obj).call();
}
@Override
public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) {
try {
if (!chunk.isLoaded()) {
chunk.load(false);
} else {
chunk.unload(true, false);
chunk.load(false);
}
// Initialize lighting
Object c = this.methodGetHandleChunk.of(chunk).call();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), bc.getX(), bc.getZ());
Object[] result = disableLighting(chunk);
enableLighting(result);
this.methodInitLighting.of(c).call();
if (bc.getTotalRelight() != 0 || fixAll) {
Object[] sections = (Object[]) this.fieldSections.of(c).get();
Object w = this.fieldWorld.of(c).get();
int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4;
ReflectionUtils.RefMethod.RefExecutor relight = this.methodW.of(w);
for (int j = 0; j < sections.length; j++) {
Object section = sections[j];
if (section == null) {
continue;
}
if (bc.getRelight(j) == 0 && !fixAll || bc.getCount(j) == 0 || bc.getCount(j) >= 4096 && bc.getAir(j) == 0) {
continue;
}
char[] array = bc.getIdArray(j);
if (array != null) {
int l = PseudoRandom.random.random(2);
for (int k = 0; k < array.length; k++) {
int i = array[k];
if (i < 16) {
continue;
}
short id = (short) (i >> 4);
switch (id) { // Lighting
default:
if (!fixAll) {
continue;
}
if ((k & 1) == l) {
l = 1 - l;
continue;
}
case 10:
case 11:
case 39:
case 40:
case 50:
case 51:
case 62:
case 74:
case 76:
case 89:
case 122:
case 124:
case 130:
case 138:
case 169:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
if (isSurrounded(bc.blocks, x, y, z)) {
continue;
}
Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z);
relight.call(pos);
}
}
}
}
}
resetLighting(result);
return true;
} catch (Throwable e) {
e.printStackTrace();
}
return false;
}
@Override
public void refreshChunk(int x, int z) {
getBukkitWorld().refreshChunk(x, z);
}
public boolean isSurrounded(char[][] sections, int x, int y, int z) {
return isSolid(getId(sections, x, y + 1, z))
&& isSolid(getId(sections, x + 1, y - 1, z))
&& isSolid(getId(sections, x - 1, y, z))
&& isSolid(getId(sections, x, y, z + 1))
&& isSolid(getId(sections, x, y, z - 1));
}
public boolean isSolid(int i) {
if (i != 0) {
Material material = Material.getMaterial(i);
return material != null && Material.getMaterial(i).isOccluding();
}
return false;
}
public int getId(char[] section, int x, int y, int z) {
if (section == null) {
return 0;
}
int j = MainUtil.CACHE_J[y][x][z];
return section[j] >> 4;
}
public int getId(char[][] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1;
}
if (y < 0 || y > 255) {
return 1;
}
int i = MainUtil.CACHE_I[y][x][z];
char[] section = sections[i];
if (section == null) {
return 0;
}
return getId(section, x, y, z);
}
}

View File

@ -6,7 +6,6 @@ import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue;
import com.plotsquared.bukkit.util.BukkitUtil;
import java.util.Arrays;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
@ -15,6 +14,8 @@ import org.bukkit.generator.ChunkGenerator.BiomeGrid;
import org.bukkit.generator.ChunkGenerator.ChunkData;
import org.bukkit.material.MaterialData;
import java.util.Arrays;
public class GenChunk extends ScopedLocalBlockQueue {
public final Biome[] biomes;
@ -37,13 +38,6 @@ public class GenChunk extends ScopedLocalBlockQueue {
this.chunk = chunk;
}
public void setChunk(ChunkWrapper wrap) {
chunk = null;
world = wrap.world;
cx = wrap.x;
cz = wrap.z;
}
public Chunk getChunk() {
if (chunk == null) {
World worldObj = BukkitUtil.getWorld(world);
@ -54,6 +48,13 @@ public class GenChunk extends ScopedLocalBlockQueue {
return chunk;
}
public void setChunk(ChunkWrapper wrap) {
chunk = null;
world = wrap.world;
cx = wrap.x;
cz = wrap.z;
}
public ChunkWrapper getChunkWrapper() {
if (chunk == null) {
return new ChunkWrapper(world, cx, cz);
@ -61,8 +62,7 @@ public class GenChunk extends ScopedLocalBlockQueue {
return new ChunkWrapper(chunk.getWorld().getName(), chunk.getX(), chunk.getZ());
}
@Override
public void fillBiome(String biomeName) {
@Override public void fillBiome(String biomeName) {
if (grid == null) {
return;
}
@ -74,9 +74,9 @@ public class GenChunk extends ScopedLocalBlockQueue {
}
}
@Override
public void setCuboid(Location pos1, Location pos2, PlotBlock block) {
if (block.data == 0 && result != null && pos1.getX() == 0 && pos1.getZ() == 0 && pos2.getX() == 15 && pos2.getZ() == 15) {
@Override public void setCuboid(Location pos1, Location pos2, PlotBlock block) {
if (block.data == 0 && result != null && pos1.getX() == 0 && pos1.getZ() == 0
&& pos2.getX() == 15 && pos2.getZ() == 15) {
for (int y = pos1.getY(); y <= pos2.getY(); y++) {
int layer = y >> 4;
short[] data = result[layer];
@ -92,8 +92,7 @@ public class GenChunk extends ScopedLocalBlockQueue {
}
}
@Override
public boolean setBiome(int x, int z, String biome) {
@Override public boolean setBiome(int x, int z, String biome) {
return setBiome(x, z, Biome.valueOf(biome.toUpperCase()));
}
@ -113,8 +112,7 @@ public class GenChunk extends ScopedLocalBlockQueue {
return false;
}
@Override
public boolean setBlock(int x, int y, int z, int id, int data) {
@Override public boolean setBlock(int x, int y, int z, int id, int data) {
if (this.result == null) {
this.cd.setBlock(x, y, z, new MaterialData(Material.getMaterial(id), (byte) data));
return true;
@ -136,8 +134,7 @@ public class GenChunk extends ScopedLocalBlockQueue {
return true;
}
@Override
public PlotBlock getBlock(int x, int y, int z) {
@Override public PlotBlock getBlock(int x, int y, int z) {
int i = MainUtil.CACHE_I[y][x][z];
if (result == null) {
MaterialData md = cd.getTypeAndData(x, y, z);
@ -167,23 +164,21 @@ public class GenChunk extends ScopedLocalBlockQueue {
return chunk == null ? cz : chunk.getZ();
}
@Override
public String getWorld() {
@Override public String getWorld() {
return chunk == null ? world : chunk.getWorld().getName();
}
@Override
public Location getMax() {
@Override public Location getMax() {
return new Location(getWorld(), 15 + (getX() << 4), 255, 15 + (getZ() << 4));
}
@Override
public Location getMin() {
@Override public Location getMin() {
return new Location(getWorld(), getX() << 4, 0, getZ() << 4);
}
public GenChunk clone() {
GenChunk toReturn = new GenChunk(chunk, new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ()));
GenChunk toReturn =
new GenChunk(chunk, new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ()));
if (this.result != null) {
for (int i = 0; i < this.result.length; i++) {
short[] matrix = this.result[i];