diff --git a/src/net/TheDgtl/Stargate/Blox.java b/src/net/TheDgtl/Stargate/Blox.java index 61e9b12..8689977 100644 --- a/src/net/TheDgtl/Stargate/Blox.java +++ b/src/net/TheDgtl/Stargate/Blox.java @@ -47,13 +47,13 @@ public class Blox { return new Location(this.world, (double)this.x + x, (double)this.y + y, (double)this.z + z, rotX, rotY); } - public Blox modRelative(int right, int depth, int distance, int modX, int modY, int modZ) { - return makeRelative(-right * modX + distance * modZ, -depth * modY, -right * modZ + -distance * modX); - } + public Blox modRelative(int right, int depth, int distance, int modX, int modY, int modZ) { + return makeRelative(-right * modX + distance * modZ, -depth * modY, -right * modZ + -distance * modX); + } - public Location modRelativeLoc(double right, double depth, double distance, float rotX, float rotY, int modX, int modY, int modZ) { - return makeRelativeLoc(0.5 + -right * modX + distance * modZ, depth, 0.5 + -right * modZ + -distance * modX, rotX, 0); - } + public Location modRelativeLoc(double right, double depth, double distance, float rotX, float rotY, int modX, int modY, int modZ) { + return makeRelativeLoc(0.5 + -right * modX + distance * modZ, depth, 0.5 + -right * modZ + -distance * modX, rotX, 0); + } public void setType(int type) { world.getBlockAt(x, y, z).setTypeId(type); diff --git a/src/net/TheDgtl/Stargate/Gate.java b/src/net/TheDgtl/Stargate/Gate.java index a641e40..d7d18fd 100644 --- a/src/net/TheDgtl/Stargate/Gate.java +++ b/src/net/TheDgtl/Stargate/Gate.java @@ -19,387 +19,387 @@ import org.bukkit.block.Block; * @author Dinnerbone */ public class Gate { - public static final int ANYTHING = -1; - public static final int ENTRANCE = -2; - public static final int CONTROL = -3; - public static final int EXIT = -4; - private static HashMap gates = new HashMap(); - private static HashMap> controlBlocks = new HashMap>(); - - private String filename; - private Integer[][] layout; - private HashMap types; - private RelativeBlockVector[] entrances = new RelativeBlockVector[0]; - private RelativeBlockVector[] border = new RelativeBlockVector[0]; - private RelativeBlockVector[] controls = new RelativeBlockVector[0]; - private RelativeBlockVector exitBlock = null; - private HashMap exits = new HashMap(); - private int portalBlockOpen = Material.PORTAL.getId(); - private int portalBlockClosed = Material.AIR.getId(); - - private Gate(String filename, Integer[][] layout, HashMap types) { - this.filename = filename; - this.layout = layout; - this.types = types; - - populateCoordinates(); - } - - private void populateCoordinates() { - ArrayList entranceList = new ArrayList(); - ArrayList borderList = new ArrayList(); - ArrayList controlList = new ArrayList(); - RelativeBlockVector[] relativeExits = new RelativeBlockVector[layout[0].length]; - int[] exitDepths = new int[layout[0].length]; - //int bottom = 0; - RelativeBlockVector lastExit = null; - - for (int y = 0; y < layout.length; y++) { - for (int x = 0; x < layout[y].length; x++) { - Integer id = layout[y][x]; - - if (id == ENTRANCE || id == EXIT) { - entranceList.add(new RelativeBlockVector(x, y, 0)); - exitDepths[x] = y; - if (id == EXIT) - this.exitBlock = new RelativeBlockVector(x, y, 0); - //bottom = y; - } else if (id == CONTROL) { - controlList.add(new RelativeBlockVector(x, y, 0)); - } else if (id != ANYTHING) { - borderList.add(new RelativeBlockVector(x, y, 0)); - } - } - } - - for (int x = 0; x < exitDepths.length; x++) { - relativeExits[x] = new RelativeBlockVector(x, exitDepths[x], 0); - } - - for (int x = relativeExits.length - 1; x >= 0; x--) { - if (relativeExits[x] != null) { - lastExit = relativeExits[x]; - } else { - relativeExits[x] = lastExit; - } - - if (exitDepths[x] > 0) this.exits.put(relativeExits[x], x); - } - - this.entrances = entranceList.toArray(this.entrances); - this.border = borderList.toArray(this.border); - this.controls = controlList.toArray(this.controls); - } - - public void save(String gateFolder) { - HashMap reverse = new HashMap(); - - try { - BufferedWriter bw = new BufferedWriter(new FileWriter(gateFolder + filename)); - - writeConfig(bw, "portal-open", portalBlockOpen); - writeConfig(bw, "portal-closed", portalBlockClosed); - - for (Character type : types.keySet()) { - Integer value = types.get(type); - - if (!type.equals('-')) { - reverse.put(value, type); - } - - bw.append(type); - bw.append('='); - bw.append(value.toString()); - bw.newLine(); - } - - bw.newLine(); - - for (int y = 0; y < layout.length; y++) { - for (int x = 0; x < layout[y].length; x++) { - Integer id = layout[y][x]; - Character symbol; - - if (id == ENTRANCE) { - symbol = '.'; - } else if (id == ANYTHING) { - symbol = ' '; - } else if (id == CONTROL) { - symbol = '-'; - } else if (id == EXIT) { - symbol = '*'; - } else if (reverse.containsKey(id)) { - symbol = reverse.get(id); - } else { - symbol = '?'; - } - - bw.append(symbol); - } - bw.newLine(); - } - - bw.close(); - } catch (IOException ex) { - Stargate.log.log(Level.SEVERE, "Could not load Gate " + filename + " - " + ex.getMessage()); - } - } - - private void writeConfig(BufferedWriter bw, String key, int value) throws IOException { - bw.append(String.format("%s=%d", key, value)); - bw.newLine(); - } - - public Integer[][] getLayout() { - return layout; - } - - public RelativeBlockVector[] getEntrances() { - return entrances; - } - - public RelativeBlockVector[] getBorder() { - return border; - } - - public RelativeBlockVector[] getControls() { - return controls; - } - - public HashMap getExits() { - return exits; - } - public RelativeBlockVector getExit() { - return exitBlock; - } - - public int getControlBlock() { - return types.get('-'); - } - - public String getFilename() { - return filename; - } - - public int getPortalBlockOpen() { - return portalBlockOpen; - } - - public int getPortalBlockClosed() { - return portalBlockClosed; - } - - public boolean matches(Block topleft, int modX, int modZ) { - return matches(new Blox(topleft), modX, modZ); - } - - public boolean matches(Blox topleft, int modX, int modZ) { - for (int y = 0; y < layout.length; y++) { - for (int x = 0; x < layout[y].length; x++) { - int id = layout[y][x]; - - if (id == ENTRANCE || id == EXIT) { - if (topleft.modRelative(x, y, 0, modX, 1, modZ).getType() != 0) { - return false; - } - } else if (id == CONTROL) { - if (topleft.modRelative(x, y, 0, modX, 1, modZ).getType() != getControlBlock()) { - return false; - } - } else if (id != ANYTHING) { - if (topleft.modRelative(x, y, 0, modX, 1, modZ).getType() != id) { - return false; - } - } - } - } - - return true; - } - - private static void registerGate(Gate gate) { - gates.put(gate.getFilename(), gate); - - int blockID = gate.getControlBlock(); - - if (!controlBlocks.containsKey(blockID)) { - controlBlocks.put(blockID, new ArrayList()); - } - - controlBlocks.get(blockID).add(gate); - } - - private static Gate loadGate(File file) { - Scanner scanner = null; - boolean designing = false; - ArrayList> design = new ArrayList>(); - HashMap types = new HashMap(); - HashMap config = new HashMap(); - int cols = 0; - - try { - scanner = new Scanner(file); - - while (scanner.hasNextLine()) { - String line = scanner.nextLine(); - - if (designing) { - ArrayList row = new ArrayList(); - - if (line.length() > cols) { - cols = line.length(); - } - - for (Character symbol : line.toCharArray()) { - Integer id = ANYTHING; - - if (symbol.equals('.')) { - id = ENTRANCE; - } else if (symbol.equals('*')) { - id = EXIT; - } else if (symbol.equals(' ')) { - id = ANYTHING; - } else if (symbol.equals('-')) { - id = CONTROL; - } else if ((symbol.equals('?')) || (!types.containsKey(symbol))) { - Stargate.log.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Unknown symbol '" + symbol + "' in diagram"); - return null; - } else { - id = types.get(symbol); - } - - row.add(id); - } - - design.add(row); - } else { - if ((line.isEmpty()) || (!line.contains("="))) { - designing = true; - } else { - String[] split = line.split("="); - String key = split[0].trim(); - String value = split[1].trim(); - - if (key.length() == 1) { - Character symbol = key.charAt(0); - Integer id = Integer.parseInt(value); - - types.put(symbol, id); - } else { - config.put(key, value); - } - } - } - } - } catch (Exception ex) { - Stargate.log.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Invalid block ID given"); - return null; - } finally { - if (scanner != null) scanner.close(); - } - - Integer[][] layout = new Integer[design.size()][cols]; - - for (int y = 0; y < design.size(); y++) { - ArrayList row = design.get(y); - Integer[] result = new Integer[cols]; - - for (int x = 0; x < cols; x++) { - if (x < row.size()) { - result[x] = row.get(x); - } else { - result[x] = ANYTHING; - } - } - - layout[y] = result; - } - - Gate gate = new Gate(file.getName(), layout, types); - - gate.portalBlockOpen = readConfig(config, gate, file, "portal-open", gate.portalBlockOpen); - gate.portalBlockClosed = readConfig(config, gate, file, "portal-closed", gate.portalBlockClosed); - - if (gate.getControls().length != 2) { - Stargate.log.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Gates must have exactly 2 control points."); - return null; - } else { - gate.save(file.getParent() + "/"); // Updates format for version changes - return gate; - } - } - - private static int readConfig(HashMap config, Gate gate, File file, String key, int def) { - if (config.containsKey(key)) { - try { - return Integer.parseInt(config.get(key)); - } catch (NumberFormatException ex) { - Stargate.log.log(Level.WARNING, String.format("%s reading %s: %s is not numeric", ex.getClass().getName(), file, key)); - } - } - - return def; - } - - public static void loadGates(String gateFolder) { - File dir = new File(gateFolder); - File[] files; - - if (dir.exists()) { - files = dir.listFiles(new StargateFilenameFilter()); - } else { - files = new File[0]; - } - - if (files.length == 0) { - dir.mkdir(); - populateDefaults(gateFolder); - } else { - for (File file : files) { - Gate gate = loadGate(file); - if (gate != null) registerGate(gate); - } - } - } - - public static void populateDefaults(String gateFolder) { - int Obsidian = Material.OBSIDIAN.getId(); - Integer[][] layout = new Integer[][] { - {ANYTHING, Obsidian,Obsidian, ANYTHING}, - {Obsidian, ENTRANCE, ENTRANCE, Obsidian}, - {CONTROL, ENTRANCE, ENTRANCE, CONTROL}, - {Obsidian, EXIT, ENTRANCE, Obsidian}, - {ANYTHING, Obsidian, Obsidian, ANYTHING}, - }; - HashMap types = new HashMap(); - types.put('X', Obsidian); - types.put('-', Obsidian); - - Gate gate = new Gate("nethergate.gate", layout, types); - gate.save(gateFolder); - registerGate(gate); - } - - public static Gate[] getGatesByControlBlock(Block block) { - return getGatesByControlBlock(block.getTypeId()); - } - - public static Gate[] getGatesByControlBlock(int type) { - Gate[] result = new Gate[0]; - ArrayList lookup = controlBlocks.get(type); - - if (lookup != null) result = lookup.toArray(result); - - return result; - } - - public static Gate getGateByName(String name) { - return gates.get(name); - } - - static class StargateFilenameFilter implements FilenameFilter { - public boolean accept(File dir, String name) { - return name.endsWith(".gate"); - } - } + public static final int ANYTHING = -1; + public static final int ENTRANCE = -2; + public static final int CONTROL = -3; + public static final int EXIT = -4; + private static HashMap gates = new HashMap(); + private static HashMap> controlBlocks = new HashMap>(); + + private String filename; + private Integer[][] layout; + private HashMap types; + private RelativeBlockVector[] entrances = new RelativeBlockVector[0]; + private RelativeBlockVector[] border = new RelativeBlockVector[0]; + private RelativeBlockVector[] controls = new RelativeBlockVector[0]; + private RelativeBlockVector exitBlock = null; + private HashMap exits = new HashMap(); + private int portalBlockOpen = Material.PORTAL.getId(); + private int portalBlockClosed = Material.AIR.getId(); + + private Gate(String filename, Integer[][] layout, HashMap types) { + this.filename = filename; + this.layout = layout; + this.types = types; + + populateCoordinates(); + } + + private void populateCoordinates() { + ArrayList entranceList = new ArrayList(); + ArrayList borderList = new ArrayList(); + ArrayList controlList = new ArrayList(); + RelativeBlockVector[] relativeExits = new RelativeBlockVector[layout[0].length]; + int[] exitDepths = new int[layout[0].length]; + //int bottom = 0; + RelativeBlockVector lastExit = null; + + for (int y = 0; y < layout.length; y++) { + for (int x = 0; x < layout[y].length; x++) { + Integer id = layout[y][x]; + + if (id == ENTRANCE || id == EXIT) { + entranceList.add(new RelativeBlockVector(x, y, 0)); + exitDepths[x] = y; + if (id == EXIT) + this.exitBlock = new RelativeBlockVector(x, y, 0); + //bottom = y; + } else if (id == CONTROL) { + controlList.add(new RelativeBlockVector(x, y, 0)); + } else if (id != ANYTHING) { + borderList.add(new RelativeBlockVector(x, y, 0)); + } + } + } + + for (int x = 0; x < exitDepths.length; x++) { + relativeExits[x] = new RelativeBlockVector(x, exitDepths[x], 0); + } + + for (int x = relativeExits.length - 1; x >= 0; x--) { + if (relativeExits[x] != null) { + lastExit = relativeExits[x]; + } else { + relativeExits[x] = lastExit; + } + + if (exitDepths[x] > 0) this.exits.put(relativeExits[x], x); + } + + this.entrances = entranceList.toArray(this.entrances); + this.border = borderList.toArray(this.border); + this.controls = controlList.toArray(this.controls); + } + + public void save(String gateFolder) { + HashMap reverse = new HashMap(); + + try { + BufferedWriter bw = new BufferedWriter(new FileWriter(gateFolder + filename)); + + writeConfig(bw, "portal-open", portalBlockOpen); + writeConfig(bw, "portal-closed", portalBlockClosed); + + for (Character type : types.keySet()) { + Integer value = types.get(type); + + if (!type.equals('-')) { + reverse.put(value, type); + } + + bw.append(type); + bw.append('='); + bw.append(value.toString()); + bw.newLine(); + } + + bw.newLine(); + + for (int y = 0; y < layout.length; y++) { + for (int x = 0; x < layout[y].length; x++) { + Integer id = layout[y][x]; + Character symbol; + + if (id == ENTRANCE) { + symbol = '.'; + } else if (id == ANYTHING) { + symbol = ' '; + } else if (id == CONTROL) { + symbol = '-'; + } else if (id == EXIT) { + symbol = '*'; + } else if (reverse.containsKey(id)) { + symbol = reverse.get(id); + } else { + symbol = '?'; + } + + bw.append(symbol); + } + bw.newLine(); + } + + bw.close(); + } catch (IOException ex) { + Stargate.log.log(Level.SEVERE, "Could not load Gate " + filename + " - " + ex.getMessage()); + } + } + + private void writeConfig(BufferedWriter bw, String key, int value) throws IOException { + bw.append(String.format("%s=%d", key, value)); + bw.newLine(); + } + + public Integer[][] getLayout() { + return layout; + } + + public RelativeBlockVector[] getEntrances() { + return entrances; + } + + public RelativeBlockVector[] getBorder() { + return border; + } + + public RelativeBlockVector[] getControls() { + return controls; + } + + public HashMap getExits() { + return exits; + } + public RelativeBlockVector getExit() { + return exitBlock; + } + + public int getControlBlock() { + return types.get('-'); + } + + public String getFilename() { + return filename; + } + + public int getPortalBlockOpen() { + return portalBlockOpen; + } + + public int getPortalBlockClosed() { + return portalBlockClosed; + } + + public boolean matches(Block topleft, int modX, int modZ) { + return matches(new Blox(topleft), modX, modZ); + } + + public boolean matches(Blox topleft, int modX, int modZ) { + for (int y = 0; y < layout.length; y++) { + for (int x = 0; x < layout[y].length; x++) { + int id = layout[y][x]; + + if (id == ENTRANCE || id == EXIT) { + if (topleft.modRelative(x, y, 0, modX, 1, modZ).getType() != 0) { + return false; + } + } else if (id == CONTROL) { + if (topleft.modRelative(x, y, 0, modX, 1, modZ).getType() != getControlBlock()) { + return false; + } + } else if (id != ANYTHING) { + if (topleft.modRelative(x, y, 0, modX, 1, modZ).getType() != id) { + return false; + } + } + } + } + + return true; + } + + private static void registerGate(Gate gate) { + gates.put(gate.getFilename(), gate); + + int blockID = gate.getControlBlock(); + + if (!controlBlocks.containsKey(blockID)) { + controlBlocks.put(blockID, new ArrayList()); + } + + controlBlocks.get(blockID).add(gate); + } + + private static Gate loadGate(File file) { + Scanner scanner = null; + boolean designing = false; + ArrayList> design = new ArrayList>(); + HashMap types = new HashMap(); + HashMap config = new HashMap(); + int cols = 0; + + try { + scanner = new Scanner(file); + + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + + if (designing) { + ArrayList row = new ArrayList(); + + if (line.length() > cols) { + cols = line.length(); + } + + for (Character symbol : line.toCharArray()) { + Integer id = ANYTHING; + + if (symbol.equals('.')) { + id = ENTRANCE; + } else if (symbol.equals('*')) { + id = EXIT; + } else if (symbol.equals(' ')) { + id = ANYTHING; + } else if (symbol.equals('-')) { + id = CONTROL; + } else if ((symbol.equals('?')) || (!types.containsKey(symbol))) { + Stargate.log.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Unknown symbol '" + symbol + "' in diagram"); + return null; + } else { + id = types.get(symbol); + } + + row.add(id); + } + + design.add(row); + } else { + if ((line.isEmpty()) || (!line.contains("="))) { + designing = true; + } else { + String[] split = line.split("="); + String key = split[0].trim(); + String value = split[1].trim(); + + if (key.length() == 1) { + Character symbol = key.charAt(0); + Integer id = Integer.parseInt(value); + + types.put(symbol, id); + } else { + config.put(key, value); + } + } + } + } + } catch (Exception ex) { + Stargate.log.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Invalid block ID given"); + return null; + } finally { + if (scanner != null) scanner.close(); + } + + Integer[][] layout = new Integer[design.size()][cols]; + + for (int y = 0; y < design.size(); y++) { + ArrayList row = design.get(y); + Integer[] result = new Integer[cols]; + + for (int x = 0; x < cols; x++) { + if (x < row.size()) { + result[x] = row.get(x); + } else { + result[x] = ANYTHING; + } + } + + layout[y] = result; + } + + Gate gate = new Gate(file.getName(), layout, types); + + gate.portalBlockOpen = readConfig(config, gate, file, "portal-open", gate.portalBlockOpen); + gate.portalBlockClosed = readConfig(config, gate, file, "portal-closed", gate.portalBlockClosed); + + if (gate.getControls().length != 2) { + Stargate.log.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Gates must have exactly 2 control points."); + return null; + } else { + gate.save(file.getParent() + "/"); // Updates format for version changes + return gate; + } + } + + private static int readConfig(HashMap config, Gate gate, File file, String key, int def) { + if (config.containsKey(key)) { + try { + return Integer.parseInt(config.get(key)); + } catch (NumberFormatException ex) { + Stargate.log.log(Level.WARNING, String.format("%s reading %s: %s is not numeric", ex.getClass().getName(), file, key)); + } + } + + return def; + } + + public static void loadGates(String gateFolder) { + File dir = new File(gateFolder); + File[] files; + + if (dir.exists()) { + files = dir.listFiles(new StargateFilenameFilter()); + } else { + files = new File[0]; + } + + if (files.length == 0) { + dir.mkdir(); + populateDefaults(gateFolder); + } else { + for (File file : files) { + Gate gate = loadGate(file); + if (gate != null) registerGate(gate); + } + } + } + + public static void populateDefaults(String gateFolder) { + int Obsidian = Material.OBSIDIAN.getId(); + Integer[][] layout = new Integer[][] { + {ANYTHING, Obsidian,Obsidian, ANYTHING}, + {Obsidian, ENTRANCE, ENTRANCE, Obsidian}, + {CONTROL, ENTRANCE, ENTRANCE, CONTROL}, + {Obsidian, EXIT, ENTRANCE, Obsidian}, + {ANYTHING, Obsidian, Obsidian, ANYTHING}, + }; + HashMap types = new HashMap(); + types.put('X', Obsidian); + types.put('-', Obsidian); + + Gate gate = new Gate("nethergate.gate", layout, types); + gate.save(gateFolder); + registerGate(gate); + } + + public static Gate[] getGatesByControlBlock(Block block) { + return getGatesByControlBlock(block.getTypeId()); + } + + public static Gate[] getGatesByControlBlock(int type) { + Gate[] result = new Gate[0]; + ArrayList lookup = controlBlocks.get(type); + + if (lookup != null) result = lookup.toArray(result); + + return result; + } + + public static Gate getGateByName(String name) { + return gates.get(name); + } + + static class StargateFilenameFilter implements FilenameFilter { + public boolean accept(File dir, String name) { + return name.endsWith(".gate"); + } + } } diff --git a/src/net/TheDgtl/Stargate/Portal.java b/src/net/TheDgtl/Stargate/Portal.java index cac240a..3c84122 100644 --- a/src/net/TheDgtl/Stargate/Portal.java +++ b/src/net/TheDgtl/Stargate/Portal.java @@ -29,836 +29,836 @@ import org.bukkit.util.Vector; */ public class Portal { // Variables used to store portal lists - private static final HashMap lookupBlocks = new HashMap(); - private static final HashMap lookupEntrances = new HashMap(); - private static final ArrayList allPortals = new ArrayList(); - private static final HashMap> allPortalsNet = new HashMap>(); - private static final HashMap> lookupNamesNet = new HashMap>(); - - // Gate location block info - private Blox topLeft; - private int modX; - private int modZ; - private float rotX; - // Block references - private SignPost id; - private Blox button; - private Blox[] frame; - private Blox[] entrances; - // Gate information - private String name; - private String destination; - private String network; - private Gate gate; - private String owner = ""; - private boolean hidden = false; - private boolean alwaysOn = false; - private boolean priv = false; - private World world; - // Gate options - private boolean verified; - private boolean fixed; - // In-use information - private Player player; - private Player activePlayer; - private ArrayList destinations = new ArrayList(); - private boolean isOpen = false; - private long openTime; + private static final HashMap lookupBlocks = new HashMap(); + private static final HashMap lookupEntrances = new HashMap(); + private static final ArrayList allPortals = new ArrayList(); + private static final HashMap> allPortalsNet = new HashMap>(); + private static final HashMap> lookupNamesNet = new HashMap>(); + + // Gate location block info + private Blox topLeft; + private int modX; + private int modZ; + private float rotX; + // Block references + private SignPost id; + private Blox button; + private Blox[] frame; + private Blox[] entrances; + // Gate information + private String name; + private String destination; + private String network; + private Gate gate; + private String owner = ""; + private boolean hidden = false; + private boolean alwaysOn = false; + private boolean priv = false; + private World world; + // Gate options + private boolean verified; + private boolean fixed; + // In-use information + private Player player; + private Player activePlayer; + private ArrayList destinations = new ArrayList(); + private boolean isOpen = false; + private long openTime; - private Portal(Blox topLeft, int modX, int modZ, - float rotX, SignPost id, Blox button, - String dest, String name, - boolean verified, String network, Gate gate, - String owner, boolean hidden, boolean alwaysOn, boolean priv) { - this.topLeft = topLeft; - this.modX = modX; - this.modZ = modZ; - this.rotX = rotX; - this.id = id; - this.destination = dest; - this.button = button; - this.verified = verified; - this.fixed = dest.length() > 0; - this.network = network; - this.name = name; - this.gate = gate; - this.owner = owner; - this.hidden = hidden; - this.alwaysOn = alwaysOn; - this.priv = priv; - this.world = topLeft.getWorld(); - - if (this.alwaysOn && !this.fixed) { - this.alwaysOn = false; - Stargate.log.log(Level.WARNING, "Can not create a non-fixed always-on gate."); - } + private Portal(Blox topLeft, int modX, int modZ, + float rotX, SignPost id, Blox button, + String dest, String name, + boolean verified, String network, Gate gate, + String owner, boolean hidden, boolean alwaysOn, boolean priv) { + this.topLeft = topLeft; + this.modX = modX; + this.modZ = modZ; + this.rotX = rotX; + this.id = id; + this.destination = dest; + this.button = button; + this.verified = verified; + this.fixed = dest.length() > 0; + this.network = network; + this.name = name; + this.gate = gate; + this.owner = owner; + this.hidden = hidden; + this.alwaysOn = alwaysOn; + this.priv = priv; + this.world = topLeft.getWorld(); + + if (this.alwaysOn && !this.fixed) { + this.alwaysOn = false; + Stargate.log.log(Level.WARNING, "Can not create a non-fixed always-on gate."); + } - this.register(); - if (verified) { - this.drawSign(); - } - } + this.register(); + if (verified) { + this.drawSign(); + } + } - public boolean isOpen() { - return isOpen || isAlwaysOn(); - } - - public boolean isAlwaysOn() { - return alwaysOn && isFixed(); - } - - public boolean isHidden() { - return hidden; - } - - public boolean isPrivate() { - return priv; - } + public boolean isOpen() { + return isOpen || isAlwaysOn(); + } + + public boolean isAlwaysOn() { + return alwaysOn && isFixed(); + } + + public boolean isHidden() { + return hidden; + } + + public boolean isPrivate() { + return priv; + } - public boolean open(boolean force) { - return open(null, force); - } + public boolean open(boolean force) { + return open(null, force); + } - public boolean open(Player openFor, boolean force) { - if (isOpen() && !force) return false; + public boolean open(Player openFor, boolean force) { + if (isOpen() && !force) return false; - world.loadChunk(world.getChunkAt(topLeft.getBlock())); + world.loadChunk(world.getChunkAt(topLeft.getBlock())); - for (Blox inside : getEntrances()) { - inside.setType(gate.getPortalBlockOpen()); - } + for (Blox inside : getEntrances()) { + inside.setType(gate.getPortalBlockOpen()); + } - isOpen = true; - openTime = System.currentTimeMillis() / 1000; - Stargate.openList.add(this); - Stargate.activeList.remove(this); - // Open remote gate - if (!isAlwaysOn()) { - player = openFor; + isOpen = true; + openTime = System.currentTimeMillis() / 1000; + Stargate.openList.add(this); + Stargate.activeList.remove(this); + // Open remote gate + if (!isAlwaysOn()) { + player = openFor; - Portal end = getDestination(); - if (end != null && !end.isFixed() && !end.isOpen()) { - end.open(openFor, false); - end.setDestination(this); - if (end.isVerified()) end.drawSign(); - } - } + Portal end = getDestination(); + if (end != null && !end.isFixed() && !end.isOpen()) { + end.open(openFor, false); + end.setDestination(this); + if (end.isVerified()) end.drawSign(); + } + } - return true; - } + return true; + } - public void close(boolean force) { - if (isAlwaysOn() && !force) return; // Never close an always open gate - - // Close this gate, then the dest gate. - for (Blox inside : getEntrances()) { - inside.setType(gate.getPortalBlockClosed()); - } + public void close(boolean force) { + if (isAlwaysOn() && !force) return; // Never close an always open gate + + // Close this gate, then the dest gate. + for (Blox inside : getEntrances()) { + inside.setType(gate.getPortalBlockClosed()); + } - player = null; - isOpen = false; - Stargate.openList.remove(this); - Stargate.activeList.remove(this); - - if (!isAlwaysOn()) { - Portal end = getDestination(); + player = null; + isOpen = false; + Stargate.openList.remove(this); + Stargate.activeList.remove(this); + + if (!isAlwaysOn()) { + Portal end = getDestination(); - if (end != null && end.isOpen()) { - end.deactivate(); // Clear it's destination first. - end.close(false); - } - } - - deactivate(); - } + if (end != null && end.isOpen()) { + end.deactivate(); // Clear it's destination first. + end.close(false); + } + } + + deactivate(); + } - public boolean isOpenFor(Player player) { - if ((isAlwaysOn()) || (this.player == null)) { - return true; - } - return (player != null) && (player.getName().equalsIgnoreCase(this.player.getName())); - } + public boolean isOpenFor(Player player) { + if ((isAlwaysOn()) || (this.player == null)) { + return true; + } + return (player != null) && (player.getName().equalsIgnoreCase(this.player.getName())); + } - public boolean isFixed() { - return fixed; - } + public boolean isFixed() { + return fixed; + } - public boolean isPowered() { - RelativeBlockVector[] controls = gate.getControls(); + public boolean isPowered() { + RelativeBlockVector[] controls = gate.getControls(); - for (RelativeBlockVector vector : controls) { - MaterialData mat = getBlockAt(vector).getBlock().getState().getData(); - - if (mat instanceof Button && ((Button)mat).isPowered()) - return true; - } + for (RelativeBlockVector vector : controls) { + MaterialData mat = getBlockAt(vector).getBlock().getState().getData(); + + if (mat instanceof Button && ((Button)mat).isPowered()) + return true; + } - return false; - } + return false; + } - public void teleport(Player player, Portal origin, PlayerMoveEvent event) { - Location traveller = player.getLocation(); - Location exit = getExit(traveller, origin); + public void teleport(Player player, Portal origin, PlayerMoveEvent event) { + Location traveller = player.getLocation(); + Location exit = getExit(traveller, origin); - exit.setYaw(origin.getRotation() - traveller.getYaw() + this.getRotation() + 180); + exit.setYaw(origin.getRotation() - traveller.getYaw() + this.getRotation() + 180); - // Change "from" so we don't get hack warnings. Cancel player move event. - event.setFrom(exit); - player.teleportTo(exit); - event.setCancelled(true); - } + // Change "from" so we don't get hack warnings. Cancel player move event. + event.setFrom(exit); + player.teleportTo(exit); + event.setCancelled(true); + } - public void teleport(Vehicle vehicle, Portal origin) { - Location traveller = new Location(this.world, vehicle.getLocation().getX(), vehicle.getLocation().getY(), vehicle.getLocation().getZ()); - Location exit = getExit(traveller, origin); - - //double velocity = vehicle.getVelocity().length(); - - // Stop and teleport - vehicle.setVelocity(new Vector()); - Entity passenger = vehicle.getPassenger(); - - vehicle.teleportTo(exit); - if (passenger != null) { - if (passenger instanceof Player) - ((Player)passenger).teleportTo(exit); - vehicle.setPassenger(passenger); - } - - // Get new velocity - Vector newVelocity = new Vector(); - switch ((int)id.getBlock().getData()) { - case 2: + public void teleport(Vehicle vehicle, Portal origin) { + Location traveller = new Location(this.world, vehicle.getLocation().getX(), vehicle.getLocation().getY(), vehicle.getLocation().getZ()); + Location exit = getExit(traveller, origin); + + //double velocity = vehicle.getVelocity().length(); + + // Stop and teleport + vehicle.setVelocity(new Vector()); + Entity passenger = vehicle.getPassenger(); + + vehicle.teleportTo(exit); + if (passenger != null) { + if (passenger instanceof Player) + ((Player)passenger).teleportTo(exit); + vehicle.setPassenger(passenger); + } + + // Get new velocity + Vector newVelocity = new Vector(); + switch ((int)id.getBlock().getData()) { + case 2: newVelocity.setZ(-1); break; - case 3: - newVelocity.setZ(1); + case 3: + newVelocity.setZ(1); break; - case 4: - newVelocity.setX(-1); + case 4: + newVelocity.setX(-1); break; - case 5: - newVelocity.setX(1); + case 5: + newVelocity.setX(1); break; } - // TODO: Initial velocity is returning 0, odd. - //newVelocity.multiply(velocity); - // Set new velocity. - vehicle.setVelocity(newVelocity); - } + // TODO: Initial velocity is returning 0, odd. + //newVelocity.multiply(velocity); + // Set new velocity. + vehicle.setVelocity(newVelocity); + } - public Location getExit(Location traveller, Portal origin) { - Location loc = null; - // Check if the gate has an exit block + public Location getExit(Location traveller, Portal origin) { + Location loc = null; + // Check if the gate has an exit block if (gate.getExit() != null) { Blox exit = getBlockAt(gate.getExit()); loc = exit.modRelativeLoc(0D, 0D, 1D, traveller.getYaw(), traveller.getPitch(), modX, 1, modZ); } else { - Stargate.log.log(Level.WARNING, "[Stargate] Missing destination point in .gate file " + gate.getFilename()); - } - if (loc != null) { - Block block = world.getBlockAt(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); - - if (block.getType() == Material.STEP) { - loc.setY(loc.getY() + 0.5); - } - - loc.setPitch(traveller.getPitch()); - return loc; - } - return traveller; - } - - public float getRotation() { - return rotX; - } - - public void setName(String name) { - this.name = filterName(name); - - drawSign(); - } - - public String getName() { - return name; - } - - public void setDestination(Portal destination) { - setDestination(destination.getName()); - } - - public void setDestination(String destination) { - this.destination = destination; - } - - public Portal getDestination() { - return Portal.getByName(destination, getNetwork()); - } - - public String getDestinationName() { - return destination; - } - - public boolean isChunkLoaded() { - return topLeft.getWorld().isChunkLoaded(topLeft.getBlock().getChunk()); - } - - public void loadChunk() { - topLeft.getWorld().loadChunk(topLeft.getBlock().getChunk()); - } - - public boolean isVerified() { - for (RelativeBlockVector control : gate.getControls()) - verified = verified || getBlockAt(control).getBlock().getTypeId() == gate.getControlBlock(); - return verified; - } - - public boolean wasVerified() { - return verified; - } - - public boolean checkIntegrity() { - return gate.matches(topLeft, modX, modZ); - } - - public Gate getGate() { - return gate; - } - - public String getOwner() { - return owner; - } - - public void activate(Player player) { - destinations.clear(); - destination = ""; - drawSign(); - Stargate.activeList.add(this); - activePlayer = player; - for (String dest : allPortalsNet.get(getNetwork().toLowerCase())) { - Portal portal = getByName(dest, getNetwork()); - // Not fixed, not this portal, and visible to this player. - if ( (!portal.isFixed()) && - (!dest.equalsIgnoreCase(getName())) && // Not this portal - (!portal.isHidden() || Stargate.hasPerm(player, "stargate.hidden", player.isOp()) || portal.getOwner().equals(player.getName())) - ) { - destinations.add(portal.getName()); - } - } - } - - public void deactivate() { - Stargate.activeList.remove(this); - if (isFixed()) { - return; - } - destinations.clear(); - destination = ""; - activePlayer = null; - drawSign(); - } - - public boolean isActive() { - return fixed || (destinations.size() > 0); - } - - public Player getActivePlayer() { - return activePlayer; - } - - public String getNetwork() { - return network; - } - - public long getOpenTime() { - return openTime; - } - - public void cycleDestination(Player player) { - if (!isActive() || getActivePlayer() != player) { - activate(player); - } - - if (destinations.size() > 0) { - int index = destinations.indexOf(destination); - if (++index >= destinations.size()) { - index = 0; - } - destination = destinations.get(index); - } - openTime = System.currentTimeMillis() / 1000; - drawSign(); - } - - public final void drawSign() { - id.setText(0, "--" + name + "--"); - int max = destinations.size() - 1; - int done = 0; - - if (!isActive()) { - id.setText(++done, "Right click to"); - id.setText(++done, "use the gate"); - id.setText(++done, " (" + network + ") "); - } else { - if (isFixed()) { - id.setText(++done, "To: " + destination); - id.setText(++done, " (" + network + ") "); - } else { - int index = destinations.indexOf(destination); - - if ((index == max) && (max > 1) && (++done <= 3)) { - id.setText(done, destinations.get(index - 2)); - } - if ((index > 0) && (++done <= 3)) { - id.setText(done, destinations.get(index - 1)); - } - if (++done <= 3) { - id.setText(done, " >" + destination + "< "); - } - if ((max >= index + 1) && (++done <= 3)) { - id.setText(done, destinations.get(index + 1)); - } - if ((max >= index + 2) && (++done <= 3)) { - id.setText(done, destinations.get(index + 2)); - } - } - } - - for (done++; done <= 3; done++) { - id.setText(done, ""); - } - - id.update(); - } - - public Blox[] getEntrances() { - if (entrances == null) { - RelativeBlockVector[] space = gate.getEntrances(); - entrances = new Blox[space.length]; - int i = 0; - - for (RelativeBlockVector vector : space) { - entrances[i++] = getBlockAt(vector); - } - } - return entrances; - } - - public Blox[] getFrame() { - if (frame == null) { - RelativeBlockVector[] border = gate.getBorder(); - RelativeBlockVector[] controls = gate.getControls(); - frame = new Blox[border.length + controls.length]; - int i = 0; - - for (RelativeBlockVector vector : border) { - frame[i++] = getBlockAt(vector); - } - - for (RelativeBlockVector vector : controls) { - frame[i++] = getBlockAt(vector); - } - } - - return frame; - } - - public void unregister(boolean removeAll) { - Stargate.log.info("[Stargate] Unregistering gate " + getName()); - close(true); - lookupNamesNet.get(getNetwork().toLowerCase()).remove(getName().toLowerCase()); - - for (Blox block : getFrame()) { - lookupBlocks.remove(block); - } - // Include the sign and button - lookupBlocks.remove(new Blox(id.getBlock())); - if (button != null) { - lookupBlocks.remove(button); - } - - for (Blox entrance : getEntrances()) { - lookupEntrances.remove(entrance); - } - - if (removeAll) - allPortals.remove(this); - - allPortalsNet.get(getNetwork().toLowerCase()).remove(getName().toLowerCase()); - - if (id.getBlock().getType() == Material.WALL_SIGN) { - id.setText(0, getName()); - id.setText(1, ""); - id.setText(2, ""); - id.setText(3, ""); - id.update(); - } - - for (String originName : allPortalsNet.get(getNetwork().toLowerCase())) { - Portal origin = Portal.getByName(originName, getNetwork()); - if ((origin != null) && (origin.isAlwaysOn()) && (origin.getDestinationName().equalsIgnoreCase(getName())) && (origin.isVerified())) { - origin.close(true); - } - } - - saveAllGates(world); - } - - private Blox getBlockAt(RelativeBlockVector vector) { - return topLeft.modRelative(vector.getRight(), vector.getDepth(), vector.getDistance(), modX, 1, modZ); - } - - private void register() { - if (!lookupNamesNet.containsKey(getNetwork().toLowerCase())) - lookupNamesNet.put(getNetwork().toLowerCase(), new HashMap()); - lookupNamesNet.get(getNetwork().toLowerCase()).put(getName().toLowerCase(), this); - - for (Blox block : getFrame()) { - lookupBlocks.put(block, this); - } - // Include the sign and button - lookupBlocks.put(new Blox(id.getBlock()), this); - if (button != null) { - lookupBlocks.put(button, this); - } - - for (Blox entrance : getEntrances()) { - lookupEntrances.put(entrance, this); - } - - allPortals.add(this); - // Check if this network exists - if (!allPortalsNet.containsKey(getNetwork().toLowerCase())) - allPortalsNet.put(getNetwork().toLowerCase(), new ArrayList()); - allPortalsNet.get(getNetwork().toLowerCase()).add(getName().toLowerCase()); - } - - public static Portal createPortal(SignPost id, Player player) { - Block idParent = id.getParent(); - if (idParent == null) return null; - if (Gate.getGatesByControlBlock(idParent).length == 0) return null; - - Blox parent = new Blox(player.getWorld(), idParent.getX(), idParent.getY(), idParent.getZ()); - Blox topleft = null; - String name = filterName(id.getText(0)); - String destName = filterName(id.getText(1)); - String network = filterName(id.getText(2)); - String options = filterName(id.getText(3)); - boolean hidden = (options.indexOf('h') != -1 || options.indexOf('H') != -1); - boolean alwaysOn = (options.indexOf('a') != -1 || options.indexOf('A') != -1); - boolean priv = (options.indexOf('p') != -1 || options.indexOf('P') != -1); - - // Check if the user can only create personal gates, set network if so - if (Stargate.hasPerm(player, "stargate.create.personal", false) && - !Stargate.hasPerm(player, "stargate.create", player.isOp()) ) { - network = player.getName(); - if (network.length() > 11) network = network.substring(0, 11); - } - - // Can not create a non-fixed always-on gate. - if (alwaysOn && destName.length() == 0) { - alwaysOn = false; - } - - if ((network.length() < 1) || (network.length() > 11)) { - network = Stargate.getDefaultNetwork(); - } - if ((name.length() < 1) || (name.length() > 11) || (getByName(name, network) != null)) { - return null; - } - - int modX = 0; - int modZ = 0; - float rotX = 0f; - int facing = 0; - - if (idParent.getX() > id.getBlock().getX()) { - modZ -= 1; - rotX = 90f; - facing = 2; - } else if (idParent.getX() < id.getBlock().getX()) { - modZ += 1; - rotX = 270f; - facing = 1; - } else if (idParent.getZ() > id.getBlock().getZ()) { - modX += 1; - rotX = 180f; - facing = 4; - } else if (idParent.getZ() < id.getBlock().getZ()) { - modX -= 1; - rotX = 0f; - facing = 3; - } - - Gate[] possibleGates = Gate.getGatesByControlBlock(idParent); - Gate gate = null; - RelativeBlockVector buttonVector = null; - - for (Gate possibility : possibleGates) { - if ((gate == null) && (buttonVector == null)) { - RelativeBlockVector[] vectors = possibility.getControls(); - RelativeBlockVector otherControl = null; - - for (RelativeBlockVector vector : vectors) { - Blox tl = parent.modRelative(-vector.getRight(), -vector.getDepth(), -vector.getDistance(), modX, 1, modZ); - - if (gate == null) { - if (possibility.matches(tl, modX, modZ)) { - gate = possibility; - topleft = tl; - - if (otherControl != null) { - buttonVector = otherControl; - } - } - } else if (otherControl != null) { - buttonVector = vector; - } - - otherControl = vector; - } - } - } - - if ((gate == null) || (buttonVector == null)) { - return null; - } - - Portal portal = null; - - Blox button = null; - // No button on an always-open gate. - if (!alwaysOn) { - button = topleft.modRelative(buttonVector.getRight(), buttonVector.getDepth(), buttonVector.getDistance() + 1, modX, 1, modZ); - button.setType(Material.STONE_BUTTON.getId()); - button.setData(facing); - } - portal = new Portal(topleft, modX, modZ, rotX, id, button, destName, name, true, network, gate, player.getName(), hidden, alwaysOn, priv); - - // Open always on gate - if (portal.isAlwaysOn()) { - Portal dest = Portal.getByName(destName, portal.getNetwork()); - if (dest != null) - portal.open(true); - } - - // Open any always on gate pointing at this gate - for (String originName : allPortalsNet.get(portal.getNetwork().toLowerCase())) { - Portal origin = Portal.getByName(originName, portal.getNetwork()); - if (origin != null && origin.isAlwaysOn() && origin.getDestinationName().equalsIgnoreCase(portal.getName()) && origin.isVerified()) - origin.open(true); - } - - saveAllGates(topleft.getWorld()); - - return portal; - } - - public static Portal getByName(String name, String network) { - if (!lookupNamesNet.containsKey(network.toLowerCase())) return null; - return lookupNamesNet.get(network.toLowerCase()).get(name.toLowerCase()); - - } - - public static Portal getByEntrance(Location location) { - return getByEntrance(new Blox(location).getBlock()); - } - - public static Portal getByEntrance(Block block) { - return lookupEntrances.get(new Blox(block)); - } - - public static Portal getByBlock(Block block) { - return lookupBlocks.get(new Blox(block)); - } - - public static void saveAllGates(World world) { - String loc = Stargate.getSaveLocation() + "/" + world.getName() + ".db"; - - try { - BufferedWriter bw = new BufferedWriter(new FileWriter(loc, false)); - - for (Portal portal : allPortals) { - String wName = portal.world.getName(); - if (!wName.equalsIgnoreCase(world.getName())) continue; - StringBuilder builder = new StringBuilder(); - Blox sign = new Blox(portal.id.getBlock()); - Blox button = portal.button; - - builder.append(portal.name); - builder.append(':'); - builder.append(sign.toString()); - builder.append(':'); - builder.append((button != null) ? button.toString() : ""); - builder.append(':'); - builder.append(portal.modX); - builder.append(':'); - builder.append(portal.modZ); - builder.append(':'); - builder.append(portal.rotX); - builder.append(':'); - builder.append(portal.topLeft.toString()); - builder.append(':'); - builder.append(portal.gate.getFilename()); - builder.append(':'); - builder.append(portal.isFixed() ? portal.getDestinationName() : ""); - builder.append(':'); - builder.append(portal.getNetwork()); - builder.append(':'); - builder.append(portal.getOwner()); - builder.append(':'); - builder.append(portal.isHidden()); - builder.append(':'); - builder.append(portal.isAlwaysOn()); - builder.append(':'); - builder.append(portal.isPrivate()); - builder.append(':'); - builder.append(portal.world.getName()); - - bw.append(builder.toString()); - bw.newLine(); - } - - bw.close(); - } catch (Exception e) { - Stargate.log.log(Level.SEVERE, "Exception while writing stargates to " + loc + ": " + e); - } - } - - public static void clearGates() { - lookupBlocks.clear(); - lookupNamesNet.clear(); - lookupEntrances.clear(); - allPortals.clear(); - allPortalsNet.clear(); - } - - public static void loadAllGates(World world) { - String location = Stargate.getSaveLocation(); - - File db = new File(location, world.getName() + ".db"); - - if (db.exists()) { - int l = 0; - int portalCount = 0; - try { - Scanner scanner = new Scanner(db); - while (scanner.hasNextLine()) { - l++; - String line = scanner.nextLine().trim(); - if (line.startsWith("#") || line.isEmpty()) { - continue; - } - String[] split = line.split(":"); - if (split.length < 8) { - Stargate.log.info("[Stargate] Invalid line - " + l); - continue; - } - String name = split[0]; - Blox s = new Blox(world, split[1]); - if (!(s.getBlock().getState() instanceof Sign)) { - Stargate.log.info("[Stargate] Invalid sign on line " + l + " [" + s.getBlock() + "]"); - continue; - } - SignPost sign = new SignPost(s); - Blox button = (split[2].length() > 0) ? new Blox(world, split[2]) : null; - int modX = Integer.parseInt(split[3]); - int modZ = Integer.parseInt(split[4]); - float rotX = Float.parseFloat(split[5]); - Blox topLeft = new Blox(world, split[6]); - Gate gate = (split[7].contains(";")) ? Gate.getGateByName("nethergate.gate") : Gate.getGateByName(split[7]); - if (gate == null) { - Stargate.log.info("[Stargate] Invalid gate layout on line " + l + " [" + split[7] + "]"); - continue; - } - - String dest = (split.length > 8) ? split[8] : ""; - String network = (split.length > 9) ? split[9] : Stargate.getDefaultNetwork(); - if (network.isEmpty()) network = Stargate.getDefaultNetwork(); - String owner = (split.length > 10) ? split[10] : ""; - boolean hidden = (split.length > 11) ? split[11].equalsIgnoreCase("true") : false; - boolean alwaysOn = (split.length > 12) ? split[12].equalsIgnoreCase("true") : false; - boolean priv = (split.length > 13) ? split[13].equalsIgnoreCase("true") : false; - - Portal portal = new Portal(topLeft, modX, modZ, rotX, sign, button, dest, name, false, network, gate, owner, hidden, alwaysOn, priv); - portal.close(true); - } - scanner.close(); - - // Open any always-on gates. Do this here as it should be more efficient than in the loop. - int OpenCount = 0; - //for (Portal portal : allPortals) { - for (Iterator iter = allPortals.iterator(); iter.hasNext(); ) { - Portal portal = iter.next(); - if (portal == null) continue; - - // Verify portal integrity/register portal - if (!portal.wasVerified()) { - if (!portal.isVerified() || !portal.checkIntegrity()) { - portal.unregister(false); - iter.remove(); - Stargate.log.info("[Stargate] Destroying stargate at " + portal.toString()); - continue; - } else { - portal.drawSign(); - portalCount++; - } - } - - if (!portal.isAlwaysOn()) continue; - - Portal dest = portal.getDestination(); - if (dest != null) { - portal.open(true); - OpenCount++; - } - } - Stargate.log.info("[Stargate] {" + world.getName() + "} Loaded " + portalCount + " stargates with " + OpenCount + " set as always-on"); - } catch (Exception e) { - Stargate.log.log(Level.SEVERE, "Exception while reading stargates from " + db.getName() + ": " + l); - e.printStackTrace(); - } - } else { - Stargate.log.info("[Stargate] {" + world.getName() + "} No stargates for world "); - } - } - - public static void closeAllGates() { - Stargate.log.info("Closing all stargates."); - for (Portal p : allPortals) { - if (p == null) continue; - p.close(true); - } - } - - public static String filterName(String input) { - return input.replaceAll("[\\|:#]", "").trim(); - } - - @Override - public String toString() { - return String.format("Portal [id=%s, network=%s name=%s, type=%s]", id, network, name, gate.getFilename()); - } - - @Override - public int hashCode() { - return getName().hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - - Portal portal = (Portal) obj; - return (this.getNetwork().equalsIgnoreCase(portal.getNetwork()) && - this.getName().equalsIgnoreCase(portal.getName())); - } + Stargate.log.log(Level.WARNING, "[Stargate] Missing destination point in .gate file " + gate.getFilename()); + } + if (loc != null) { + Block block = world.getBlockAt(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + + if (block.getType() == Material.STEP) { + loc.setY(loc.getY() + 0.5); + } + + loc.setPitch(traveller.getPitch()); + return loc; + } + return traveller; + } + + public float getRotation() { + return rotX; + } + + public void setName(String name) { + this.name = filterName(name); + + drawSign(); + } + + public String getName() { + return name; + } + + public void setDestination(Portal destination) { + setDestination(destination.getName()); + } + + public void setDestination(String destination) { + this.destination = destination; + } + + public Portal getDestination() { + return Portal.getByName(destination, getNetwork()); + } + + public String getDestinationName() { + return destination; + } + + public boolean isChunkLoaded() { + return topLeft.getWorld().isChunkLoaded(topLeft.getBlock().getChunk()); + } + + public void loadChunk() { + topLeft.getWorld().loadChunk(topLeft.getBlock().getChunk()); + } + + public boolean isVerified() { + for (RelativeBlockVector control : gate.getControls()) + verified = verified || getBlockAt(control).getBlock().getTypeId() == gate.getControlBlock(); + return verified; + } + + public boolean wasVerified() { + return verified; + } + + public boolean checkIntegrity() { + return gate.matches(topLeft, modX, modZ); + } + + public Gate getGate() { + return gate; + } + + public String getOwner() { + return owner; + } + + public void activate(Player player) { + destinations.clear(); + destination = ""; + drawSign(); + Stargate.activeList.add(this); + activePlayer = player; + for (String dest : allPortalsNet.get(getNetwork().toLowerCase())) { + Portal portal = getByName(dest, getNetwork()); + // Not fixed, not this portal, and visible to this player. + if ( (!portal.isFixed()) && + (!dest.equalsIgnoreCase(getName())) && // Not this portal + (!portal.isHidden() || Stargate.hasPerm(player, "stargate.hidden", player.isOp()) || portal.getOwner().equals(player.getName())) + ) { + destinations.add(portal.getName()); + } + } + } + + public void deactivate() { + Stargate.activeList.remove(this); + if (isFixed()) { + return; + } + destinations.clear(); + destination = ""; + activePlayer = null; + drawSign(); + } + + public boolean isActive() { + return fixed || (destinations.size() > 0); + } + + public Player getActivePlayer() { + return activePlayer; + } + + public String getNetwork() { + return network; + } + + public long getOpenTime() { + return openTime; + } + + public void cycleDestination(Player player) { + if (!isActive() || getActivePlayer() != player) { + activate(player); + } + + if (destinations.size() > 0) { + int index = destinations.indexOf(destination); + if (++index >= destinations.size()) { + index = 0; + } + destination = destinations.get(index); + } + openTime = System.currentTimeMillis() / 1000; + drawSign(); + } + + public final void drawSign() { + id.setText(0, "--" + name + "--"); + int max = destinations.size() - 1; + int done = 0; + + if (!isActive()) { + id.setText(++done, "Right click to"); + id.setText(++done, "use the gate"); + id.setText(++done, " (" + network + ") "); + } else { + if (isFixed()) { + id.setText(++done, "To: " + destination); + id.setText(++done, " (" + network + ") "); + } else { + int index = destinations.indexOf(destination); + + if ((index == max) && (max > 1) && (++done <= 3)) { + id.setText(done, destinations.get(index - 2)); + } + if ((index > 0) && (++done <= 3)) { + id.setText(done, destinations.get(index - 1)); + } + if (++done <= 3) { + id.setText(done, " >" + destination + "< "); + } + if ((max >= index + 1) && (++done <= 3)) { + id.setText(done, destinations.get(index + 1)); + } + if ((max >= index + 2) && (++done <= 3)) { + id.setText(done, destinations.get(index + 2)); + } + } + } + + for (done++; done <= 3; done++) { + id.setText(done, ""); + } + + id.update(); + } + + public Blox[] getEntrances() { + if (entrances == null) { + RelativeBlockVector[] space = gate.getEntrances(); + entrances = new Blox[space.length]; + int i = 0; + + for (RelativeBlockVector vector : space) { + entrances[i++] = getBlockAt(vector); + } + } + return entrances; + } + + public Blox[] getFrame() { + if (frame == null) { + RelativeBlockVector[] border = gate.getBorder(); + RelativeBlockVector[] controls = gate.getControls(); + frame = new Blox[border.length + controls.length]; + int i = 0; + + for (RelativeBlockVector vector : border) { + frame[i++] = getBlockAt(vector); + } + + for (RelativeBlockVector vector : controls) { + frame[i++] = getBlockAt(vector); + } + } + + return frame; + } + + public void unregister(boolean removeAll) { + Stargate.log.info("[Stargate] Unregistering gate " + getName()); + close(true); + lookupNamesNet.get(getNetwork().toLowerCase()).remove(getName().toLowerCase()); + + for (Blox block : getFrame()) { + lookupBlocks.remove(block); + } + // Include the sign and button + lookupBlocks.remove(new Blox(id.getBlock())); + if (button != null) { + lookupBlocks.remove(button); + } + + for (Blox entrance : getEntrances()) { + lookupEntrances.remove(entrance); + } + + if (removeAll) + allPortals.remove(this); + + allPortalsNet.get(getNetwork().toLowerCase()).remove(getName().toLowerCase()); + + if (id.getBlock().getType() == Material.WALL_SIGN) { + id.setText(0, getName()); + id.setText(1, ""); + id.setText(2, ""); + id.setText(3, ""); + id.update(); + } + + for (String originName : allPortalsNet.get(getNetwork().toLowerCase())) { + Portal origin = Portal.getByName(originName, getNetwork()); + if ((origin != null) && (origin.isAlwaysOn()) && (origin.getDestinationName().equalsIgnoreCase(getName())) && (origin.isVerified())) { + origin.close(true); + } + } + + saveAllGates(world); + } + + private Blox getBlockAt(RelativeBlockVector vector) { + return topLeft.modRelative(vector.getRight(), vector.getDepth(), vector.getDistance(), modX, 1, modZ); + } + + private void register() { + if (!lookupNamesNet.containsKey(getNetwork().toLowerCase())) + lookupNamesNet.put(getNetwork().toLowerCase(), new HashMap()); + lookupNamesNet.get(getNetwork().toLowerCase()).put(getName().toLowerCase(), this); + + for (Blox block : getFrame()) { + lookupBlocks.put(block, this); + } + // Include the sign and button + lookupBlocks.put(new Blox(id.getBlock()), this); + if (button != null) { + lookupBlocks.put(button, this); + } + + for (Blox entrance : getEntrances()) { + lookupEntrances.put(entrance, this); + } + + allPortals.add(this); + // Check if this network exists + if (!allPortalsNet.containsKey(getNetwork().toLowerCase())) + allPortalsNet.put(getNetwork().toLowerCase(), new ArrayList()); + allPortalsNet.get(getNetwork().toLowerCase()).add(getName().toLowerCase()); + } + + public static Portal createPortal(SignPost id, Player player) { + Block idParent = id.getParent(); + if (idParent == null) return null; + if (Gate.getGatesByControlBlock(idParent).length == 0) return null; + + Blox parent = new Blox(player.getWorld(), idParent.getX(), idParent.getY(), idParent.getZ()); + Blox topleft = null; + String name = filterName(id.getText(0)); + String destName = filterName(id.getText(1)); + String network = filterName(id.getText(2)); + String options = filterName(id.getText(3)); + boolean hidden = (options.indexOf('h') != -1 || options.indexOf('H') != -1); + boolean alwaysOn = (options.indexOf('a') != -1 || options.indexOf('A') != -1); + boolean priv = (options.indexOf('p') != -1 || options.indexOf('P') != -1); + + // Check if the user can only create personal gates, set network if so + if (Stargate.hasPerm(player, "stargate.create.personal", false) && + !Stargate.hasPerm(player, "stargate.create", player.isOp()) ) { + network = player.getName(); + if (network.length() > 11) network = network.substring(0, 11); + } + + // Can not create a non-fixed always-on gate. + if (alwaysOn && destName.length() == 0) { + alwaysOn = false; + } + + if ((network.length() < 1) || (network.length() > 11)) { + network = Stargate.getDefaultNetwork(); + } + if ((name.length() < 1) || (name.length() > 11) || (getByName(name, network) != null)) { + return null; + } + + int modX = 0; + int modZ = 0; + float rotX = 0f; + int facing = 0; + + if (idParent.getX() > id.getBlock().getX()) { + modZ -= 1; + rotX = 90f; + facing = 2; + } else if (idParent.getX() < id.getBlock().getX()) { + modZ += 1; + rotX = 270f; + facing = 1; + } else if (idParent.getZ() > id.getBlock().getZ()) { + modX += 1; + rotX = 180f; + facing = 4; + } else if (idParent.getZ() < id.getBlock().getZ()) { + modX -= 1; + rotX = 0f; + facing = 3; + } + + Gate[] possibleGates = Gate.getGatesByControlBlock(idParent); + Gate gate = null; + RelativeBlockVector buttonVector = null; + + for (Gate possibility : possibleGates) { + if ((gate == null) && (buttonVector == null)) { + RelativeBlockVector[] vectors = possibility.getControls(); + RelativeBlockVector otherControl = null; + + for (RelativeBlockVector vector : vectors) { + Blox tl = parent.modRelative(-vector.getRight(), -vector.getDepth(), -vector.getDistance(), modX, 1, modZ); + + if (gate == null) { + if (possibility.matches(tl, modX, modZ)) { + gate = possibility; + topleft = tl; + + if (otherControl != null) { + buttonVector = otherControl; + } + } + } else if (otherControl != null) { + buttonVector = vector; + } + + otherControl = vector; + } + } + } + + if ((gate == null) || (buttonVector == null)) { + return null; + } + + Portal portal = null; + + Blox button = null; + // No button on an always-open gate. + if (!alwaysOn) { + button = topleft.modRelative(buttonVector.getRight(), buttonVector.getDepth(), buttonVector.getDistance() + 1, modX, 1, modZ); + button.setType(Material.STONE_BUTTON.getId()); + button.setData(facing); + } + portal = new Portal(topleft, modX, modZ, rotX, id, button, destName, name, true, network, gate, player.getName(), hidden, alwaysOn, priv); + + // Open always on gate + if (portal.isAlwaysOn()) { + Portal dest = Portal.getByName(destName, portal.getNetwork()); + if (dest != null) + portal.open(true); + } + + // Open any always on gate pointing at this gate + for (String originName : allPortalsNet.get(portal.getNetwork().toLowerCase())) { + Portal origin = Portal.getByName(originName, portal.getNetwork()); + if (origin != null && origin.isAlwaysOn() && origin.getDestinationName().equalsIgnoreCase(portal.getName()) && origin.isVerified()) + origin.open(true); + } + + saveAllGates(topleft.getWorld()); + + return portal; + } + + public static Portal getByName(String name, String network) { + if (!lookupNamesNet.containsKey(network.toLowerCase())) return null; + return lookupNamesNet.get(network.toLowerCase()).get(name.toLowerCase()); + + } + + public static Portal getByEntrance(Location location) { + return getByEntrance(new Blox(location).getBlock()); + } + + public static Portal getByEntrance(Block block) { + return lookupEntrances.get(new Blox(block)); + } + + public static Portal getByBlock(Block block) { + return lookupBlocks.get(new Blox(block)); + } + + public static void saveAllGates(World world) { + String loc = Stargate.getSaveLocation() + "/" + world.getName() + ".db"; + + try { + BufferedWriter bw = new BufferedWriter(new FileWriter(loc, false)); + + for (Portal portal : allPortals) { + String wName = portal.world.getName(); + if (!wName.equalsIgnoreCase(world.getName())) continue; + StringBuilder builder = new StringBuilder(); + Blox sign = new Blox(portal.id.getBlock()); + Blox button = portal.button; + + builder.append(portal.name); + builder.append(':'); + builder.append(sign.toString()); + builder.append(':'); + builder.append((button != null) ? button.toString() : ""); + builder.append(':'); + builder.append(portal.modX); + builder.append(':'); + builder.append(portal.modZ); + builder.append(':'); + builder.append(portal.rotX); + builder.append(':'); + builder.append(portal.topLeft.toString()); + builder.append(':'); + builder.append(portal.gate.getFilename()); + builder.append(':'); + builder.append(portal.isFixed() ? portal.getDestinationName() : ""); + builder.append(':'); + builder.append(portal.getNetwork()); + builder.append(':'); + builder.append(portal.getOwner()); + builder.append(':'); + builder.append(portal.isHidden()); + builder.append(':'); + builder.append(portal.isAlwaysOn()); + builder.append(':'); + builder.append(portal.isPrivate()); + builder.append(':'); + builder.append(portal.world.getName()); + + bw.append(builder.toString()); + bw.newLine(); + } + + bw.close(); + } catch (Exception e) { + Stargate.log.log(Level.SEVERE, "Exception while writing stargates to " + loc + ": " + e); + } + } + + public static void clearGates() { + lookupBlocks.clear(); + lookupNamesNet.clear(); + lookupEntrances.clear(); + allPortals.clear(); + allPortalsNet.clear(); + } + + public static void loadAllGates(World world) { + String location = Stargate.getSaveLocation(); + + File db = new File(location, world.getName() + ".db"); + + if (db.exists()) { + int l = 0; + int portalCount = 0; + try { + Scanner scanner = new Scanner(db); + while (scanner.hasNextLine()) { + l++; + String line = scanner.nextLine().trim(); + if (line.startsWith("#") || line.isEmpty()) { + continue; + } + String[] split = line.split(":"); + if (split.length < 8) { + Stargate.log.info("[Stargate] Invalid line - " + l); + continue; + } + String name = split[0]; + Blox s = new Blox(world, split[1]); + if (!(s.getBlock().getState() instanceof Sign)) { + Stargate.log.info("[Stargate] Invalid sign on line " + l + " [" + s.getBlock() + "]"); + continue; + } + SignPost sign = new SignPost(s); + Blox button = (split[2].length() > 0) ? new Blox(world, split[2]) : null; + int modX = Integer.parseInt(split[3]); + int modZ = Integer.parseInt(split[4]); + float rotX = Float.parseFloat(split[5]); + Blox topLeft = new Blox(world, split[6]); + Gate gate = (split[7].contains(";")) ? Gate.getGateByName("nethergate.gate") : Gate.getGateByName(split[7]); + if (gate == null) { + Stargate.log.info("[Stargate] Invalid gate layout on line " + l + " [" + split[7] + "]"); + continue; + } + + String dest = (split.length > 8) ? split[8] : ""; + String network = (split.length > 9) ? split[9] : Stargate.getDefaultNetwork(); + if (network.isEmpty()) network = Stargate.getDefaultNetwork(); + String owner = (split.length > 10) ? split[10] : ""; + boolean hidden = (split.length > 11) ? split[11].equalsIgnoreCase("true") : false; + boolean alwaysOn = (split.length > 12) ? split[12].equalsIgnoreCase("true") : false; + boolean priv = (split.length > 13) ? split[13].equalsIgnoreCase("true") : false; + + Portal portal = new Portal(topLeft, modX, modZ, rotX, sign, button, dest, name, false, network, gate, owner, hidden, alwaysOn, priv); + portal.close(true); + } + scanner.close(); + + // Open any always-on gates. Do this here as it should be more efficient than in the loop. + int OpenCount = 0; + //for (Portal portal : allPortals) { + for (Iterator iter = allPortals.iterator(); iter.hasNext(); ) { + Portal portal = iter.next(); + if (portal == null) continue; + + // Verify portal integrity/register portal + if (!portal.wasVerified()) { + if (!portal.isVerified() || !portal.checkIntegrity()) { + portal.unregister(false); + iter.remove(); + Stargate.log.info("[Stargate] Destroying stargate at " + portal.toString()); + continue; + } else { + portal.drawSign(); + portalCount++; + } + } + + if (!portal.isAlwaysOn()) continue; + + Portal dest = portal.getDestination(); + if (dest != null) { + portal.open(true); + OpenCount++; + } + } + Stargate.log.info("[Stargate] {" + world.getName() + "} Loaded " + portalCount + " stargates with " + OpenCount + " set as always-on"); + } catch (Exception e) { + Stargate.log.log(Level.SEVERE, "Exception while reading stargates from " + db.getName() + ": " + l); + e.printStackTrace(); + } + } else { + Stargate.log.info("[Stargate] {" + world.getName() + "} No stargates for world "); + } + } + + public static void closeAllGates() { + Stargate.log.info("Closing all stargates."); + for (Portal p : allPortals) { + if (p == null) continue; + p.close(true); + } + } + + public static String filterName(String input) { + return input.replaceAll("[\\|:#]", "").trim(); + } + + @Override + public String toString() { + return String.format("Portal [id=%s, network=%s name=%s, type=%s]", id, network, name, gate.getFilename()); + } + + @Override + public int hashCode() { + return getName().hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + + Portal portal = (Portal) obj; + return (this.getNetwork().equalsIgnoreCase(portal.getNetwork()) && + this.getName().equalsIgnoreCase(portal.getName())); + } } diff --git a/src/net/TheDgtl/Stargate/RelativeBlockVector.java b/src/net/TheDgtl/Stargate/RelativeBlockVector.java index f9910f9..ba75588 100644 --- a/src/net/TheDgtl/Stargate/RelativeBlockVector.java +++ b/src/net/TheDgtl/Stargate/RelativeBlockVector.java @@ -6,25 +6,25 @@ package net.TheDgtl.Stargate; * @author Dinnerbone */ public class RelativeBlockVector { - private int right = 0; - private int depth = 0; - private int distance = 0; + private int right = 0; + private int depth = 0; + private int distance = 0; - public RelativeBlockVector(int right, int depth, int distance) { - this.right = right; - this.depth = depth; - this.distance = distance; - } + public RelativeBlockVector(int right, int depth, int distance) { + this.right = right; + this.depth = depth; + this.distance = distance; + } - public int getRight() { - return right; - } + public int getRight() { + return right; + } - public int getDepth() { - return depth; - } + public int getDepth() { + return depth; + } - public int getDistance() { - return distance; - } + public int getDistance() { + return distance; + } } diff --git a/src/net/TheDgtl/Stargate/Stargate.java b/src/net/TheDgtl/Stargate/Stargate.java index a335507..af576a9 100644 --- a/src/net/TheDgtl/Stargate/Stargate.java +++ b/src/net/TheDgtl/Stargate/Stargate.java @@ -54,123 +54,123 @@ public class Stargate extends JavaPlugin { // Permissions private static Permissions permissions = null; - private final bListener blockListener = new bListener(); - private final pListener playerListener = new pListener(); - private final vListener vehicleListener = new vListener(); - private final wListener worldListener = new wListener(); - private final eListener entityListener = new eListener(); - private final sListener serverListener = new sListener(); - - public static Logger log; - private Configuration config; - private PluginManager pm; - - private static String portalFolder; - private static String gateFolder; - private static String teleMsg = "Teleported"; - private static String regMsg = "Gate Created"; - private static String dmgMsg = "Gate Destroyed"; - private static String denyMsg = "Access Denied"; - private static String invMsg = "Invalid Destination"; - private static String blockMsg = "Destination Blocked"; - private static String defNetwork = "central"; - private static boolean destroyExplosion = false; - private static int activeLimit = 10; - private static int openLimit = 10; - - public static ConcurrentLinkedQueue openList = new ConcurrentLinkedQueue(); - public static ConcurrentLinkedQueue activeList = new ConcurrentLinkedQueue(); - //private HashMap vehicles = new HashMap(); + private final bListener blockListener = new bListener(); + private final pListener playerListener = new pListener(); + private final vListener vehicleListener = new vListener(); + private final wListener worldListener = new wListener(); + private final eListener entityListener = new eListener(); + private final sListener serverListener = new sListener(); - public void onDisable() { - Portal.closeAllGates(); - Portal.clearGates(); - } + public static Logger log; + private Configuration config; + private PluginManager pm; + + private static String portalFolder; + private static String gateFolder; + private static String teleMsg = "Teleported"; + private static String regMsg = "Gate Created"; + private static String dmgMsg = "Gate Destroyed"; + private static String denyMsg = "Access Denied"; + private static String invMsg = "Invalid Destination"; + private static String blockMsg = "Destination Blocked"; + private static String defNetwork = "central"; + private static boolean destroyExplosion = false; + private static int activeLimit = 10; + private static int openLimit = 10; + + public static ConcurrentLinkedQueue openList = new ConcurrentLinkedQueue(); + public static ConcurrentLinkedQueue activeList = new ConcurrentLinkedQueue(); + //private HashMap vehicles = new HashMap(); + + public void onDisable() { + Portal.closeAllGates(); + Portal.clearGates(); + } - public void onEnable() { - PluginDescriptionFile pdfFile = this.getDescription(); - pm = getServer().getPluginManager(); - config = this.getConfiguration(); - log = Logger.getLogger("Minecraft"); - - // Set portalFile and gateFolder to the plugin folder as defaults. - portalFolder = getDataFolder() + "/portals"; - gateFolder = getDataFolder() + "/gates/"; - - log.info(pdfFile.getName() + " v." + pdfFile.getVersion() + " is enabled."); + public void onEnable() { + PluginDescriptionFile pdfFile = this.getDescription(); + pm = getServer().getPluginManager(); + config = this.getConfiguration(); + log = Logger.getLogger("Minecraft"); - pm.registerEvent(Event.Type.BLOCK_FLOW, blockListener, Priority.Normal, this); - pm.registerEvent(Event.Type.BLOCK_PHYSICS, blockListener, Priority.Normal, this); + // Set portalFile and gateFolder to the plugin folder as defaults. + portalFolder = getDataFolder() + "/portals"; + gateFolder = getDataFolder() + "/gates/"; - this.reloadConfig(); - this.migrate(); - this.reloadGates(); - - // Check to see if iConomy/Permissions is loaded yet. - checkiConomy(); - checkPermissions(); - - pm.registerEvent(Event.Type.PLAYER_MOVE, playerListener, Priority.Normal, this); - - pm.registerEvent(Event.Type.BLOCK_RIGHTCLICKED, blockListener, Priority.Normal, this); - pm.registerEvent(Event.Type.BLOCK_PLACED, blockListener, Priority.Normal, this); - pm.registerEvent(Event.Type.BLOCK_DAMAGED, blockListener, Priority.Normal, this); - pm.registerEvent(Event.Type.BLOCK_BREAK, blockListener, Priority.Normal, this); - pm.registerEvent(Event.Type.VEHICLE_MOVE, vehicleListener, Priority.Normal, this); - pm.registerEvent(Event.Type.SIGN_CHANGE, blockListener, Priority.Normal, this); - - pm.registerEvent(Event.Type.WORLD_LOADED, worldListener, Priority.Normal, this); - - pm.registerEvent(Event.Type.ENTITY_EXPLODE, entityListener, Priority.Normal, this); - - // iConomy Loading - pm.registerEvent(Event.Type.PLUGIN_ENABLE, serverListener, Priority.Monitor, this); - pm.registerEvent(Event.Type.PLUGIN_DISABLE, serverListener, Priority.Monitor, this); - - getServer().getScheduler().scheduleSyncRepeatingTask(this, new SGThread(), 0L, 100L); - } + log.info(pdfFile.getName() + " v." + pdfFile.getVersion() + " is enabled."); + + pm.registerEvent(Event.Type.BLOCK_FLOW, blockListener, Priority.Normal, this); + pm.registerEvent(Event.Type.BLOCK_PHYSICS, blockListener, Priority.Normal, this); + + this.reloadConfig(); + this.migrate(); + this.reloadGates(); + + // Check to see if iConomy/Permissions is loaded yet. + checkiConomy(); + checkPermissions(); + + pm.registerEvent(Event.Type.PLAYER_MOVE, playerListener, Priority.Normal, this); + + pm.registerEvent(Event.Type.BLOCK_RIGHTCLICKED, blockListener, Priority.Normal, this); + pm.registerEvent(Event.Type.BLOCK_PLACED, blockListener, Priority.Normal, this); + pm.registerEvent(Event.Type.BLOCK_DAMAGED, blockListener, Priority.Normal, this); + pm.registerEvent(Event.Type.BLOCK_BREAK, blockListener, Priority.Normal, this); + pm.registerEvent(Event.Type.VEHICLE_MOVE, vehicleListener, Priority.Normal, this); + pm.registerEvent(Event.Type.SIGN_CHANGE, blockListener, Priority.Normal, this); + + pm.registerEvent(Event.Type.WORLD_LOADED, worldListener, Priority.Normal, this); + + pm.registerEvent(Event.Type.ENTITY_EXPLODE, entityListener, Priority.Normal, this); + + // iConomy Loading + pm.registerEvent(Event.Type.PLUGIN_ENABLE, serverListener, Priority.Monitor, this); + pm.registerEvent(Event.Type.PLUGIN_DISABLE, serverListener, Priority.Monitor, this); + + getServer().getScheduler().scheduleSyncRepeatingTask(this, new SGThread(), 0L, 100L); + } public void reloadConfig() { - config.load(); - portalFolder = config.getString("portal-folder", portalFolder); - gateFolder = config.getString("gate-folder", gateFolder); - teleMsg = config.getString("teleport-message", teleMsg); - regMsg = config.getString("portal-create-message", regMsg); - dmgMsg = config.getString("portal-destroy-message", dmgMsg); - denyMsg = config.getString("not-owner-message", denyMsg); - invMsg = config.getString("not-selected-message", invMsg); - blockMsg = config.getString("other-side-blocked-message", blockMsg); - defNetwork = config.getString("default-gate-network", defNetwork).trim(); - destroyExplosion = config.getBoolean("destroyexplosion", destroyExplosion); - // iConomy - iConomyHandler.useiConomy = config.getBoolean("useiconomy", iConomyHandler.useiConomy); - iConomyHandler.createCost = config.getInt("createcost", iConomyHandler.createCost); - iConomyHandler.destroyCost = config.getInt("destroycost", iConomyHandler.destroyCost); - iConomyHandler.useCost = config.getInt("usecost", iConomyHandler.useCost); - iConomyHandler.inFundMsg = config.getString("not-enough-money-message", iConomyHandler.inFundMsg); - - saveConfig(); - } + config.load(); + portalFolder = config.getString("portal-folder", portalFolder); + gateFolder = config.getString("gate-folder", gateFolder); + teleMsg = config.getString("teleport-message", teleMsg); + regMsg = config.getString("portal-create-message", regMsg); + dmgMsg = config.getString("portal-destroy-message", dmgMsg); + denyMsg = config.getString("not-owner-message", denyMsg); + invMsg = config.getString("not-selected-message", invMsg); + blockMsg = config.getString("other-side-blocked-message", blockMsg); + defNetwork = config.getString("default-gate-network", defNetwork).trim(); + destroyExplosion = config.getBoolean("destroyexplosion", destroyExplosion); + // iConomy + iConomyHandler.useiConomy = config.getBoolean("useiconomy", iConomyHandler.useiConomy); + iConomyHandler.createCost = config.getInt("createcost", iConomyHandler.createCost); + iConomyHandler.destroyCost = config.getInt("destroycost", iConomyHandler.destroyCost); + iConomyHandler.useCost = config.getInt("usecost", iConomyHandler.useCost); + iConomyHandler.inFundMsg = config.getString("not-enough-money-message", iConomyHandler.inFundMsg); + + saveConfig(); + } public void saveConfig() { - config.setProperty("portal-folder", portalFolder); - config.setProperty("gate-folder", gateFolder); - config.setProperty("teleport-message", teleMsg); - config.setProperty("portal-create-message", regMsg); - config.setProperty("portal-destroy-message", dmgMsg); - config.setProperty("not-owner-message", denyMsg); - config.setProperty("not-selected-message", invMsg); - config.setProperty("other-side-blocked-message", blockMsg); - config.setProperty("default-gate-network", defNetwork); - config.setProperty("destroyexplosion", destroyExplosion); - // iConomy - config.setProperty("useiconomy", iConomyHandler.useiConomy); - config.setProperty("createcost", iConomyHandler.createCost); - config.setProperty("destroycost", iConomyHandler.destroyCost); - config.setProperty("usecost", iConomyHandler.useCost); - config.setProperty("not-enough-money-message", iConomyHandler.inFundMsg); - - config.save(); + config.setProperty("portal-folder", portalFolder); + config.setProperty("gate-folder", gateFolder); + config.setProperty("teleport-message", teleMsg); + config.setProperty("portal-create-message", regMsg); + config.setProperty("portal-destroy-message", dmgMsg); + config.setProperty("not-owner-message", denyMsg); + config.setProperty("not-selected-message", invMsg); + config.setProperty("other-side-blocked-message", blockMsg); + config.setProperty("default-gate-network", defNetwork); + config.setProperty("destroyexplosion", destroyExplosion); + // iConomy + config.setProperty("useiconomy", iConomyHandler.useiConomy); + config.setProperty("createcost", iConomyHandler.createCost); + config.setProperty("destroycost", iConomyHandler.destroyCost); + config.setProperty("usecost", iConomyHandler.useCost); + config.setProperty("not-enough-money-message", iConomyHandler.inFundMsg); + + config.save(); } public void reloadGates() { @@ -194,87 +194,87 @@ public class Stargate extends JavaPlugin { File newFile = new File(portalFolder, getServer().getWorlds().get(0).getName() + ".db"); if (!newFile.exists()) { newFile.getParentFile().mkdirs(); - // Migrate not-so-old stargate db - File oldishFile = new File("plugins/Stargate/stargate.db"); - if (oldishFile.exists()) { - Stargate.log.info("[Stargate] Migrating existing stargate.db"); - oldishFile.renameTo(newFile); - } + // Migrate not-so-old stargate db + File oldishFile = new File("plugins/Stargate/stargate.db"); + if (oldishFile.exists()) { + Stargate.log.info("[Stargate] Migrating existing stargate.db"); + oldishFile.renameTo(newFile); + } + } + + // Migrate old gates if applicaple + File oldDir = new File("stargates"); + if (oldDir.exists()) { + File newDir = new File(gateFolder); + if (!newDir.exists()) newDir.mkdirs(); + for (File file : oldDir.listFiles(new Gate.StargateFilenameFilter())) { + Stargate.log.info("[Stargate] Migrating existing gate " + file.getName()); + file.renameTo(new File(gateFolder, file.getName())); + } } - - // Migrate old gates if applicaple - File oldDir = new File("stargates"); - if (oldDir.exists()) { - File newDir = new File(gateFolder); - if (!newDir.exists()) newDir.mkdirs(); - for (File file : oldDir.listFiles(new Gate.StargateFilenameFilter())) { - Stargate.log.info("[Stargate] Migrating existing gate " + file.getName()); - file.renameTo(new File(gateFolder, file.getName())); - } - } } - public static String getSaveLocation() { - return portalFolder; - } + public static String getSaveLocation() { + return portalFolder; + } - public static String getDefaultNetwork() { - return defNetwork; - } + public static String getDefaultNetwork() { + return defNetwork; + } - private void onButtonPressed(Player player, Portal gate) { - Portal destination = gate.getDestination(); + private void onButtonPressed(Player player, Portal gate) { + Portal destination = gate.getDestination(); - if (!gate.isOpen()) { - if (iConomyHandler.useiConomy() && iConomyHandler.getBalance(player.getName()) < iConomyHandler.useCost) { - player.sendMessage(ChatColor.RED + iConomyHandler.inFundMsg); - } else if ((!gate.isFixed()) && gate.isActive() && (gate.getActivePlayer() != player)) { - gate.deactivate(); - if (!denyMsg.isEmpty()) { - player.sendMessage(ChatColor.RED + denyMsg); - } - } else if (gate.isPrivate() && !gate.getOwner().equals(player.getName()) && !hasPerm(player, "stargate.private", player.isOp())) { - if (!denyMsg.isEmpty()) { - player.sendMessage(ChatColor.RED + denyMsg); - } - } else if ((destination == null) || (destination == gate)) { - if (!invMsg.isEmpty()) { - player.sendMessage(ChatColor.RED + invMsg); - } - } else if ((destination.isOpen()) && (!destination.isAlwaysOn())) { - if (!blockMsg.isEmpty()) { - player.sendMessage(ChatColor.RED + blockMsg); - } - } else { - gate.open(player, false); - } - } else { - gate.close(false); - } - } - - /* - * Check if iConomy is loaded/enabled already - */ - private void checkiConomy() { - if (!iConomyHandler.useiConomy) return; - Plugin ico = pm.getPlugin("iConomy"); - if (ico != null && ico.isEnabled()) { - iConomyHandler.iConomy = (iConomy)ico; - Stargate.log.info("[Stargate] Using iConomy (v" + iConomyHandler.iConomy.getDescription().getVersion() + ")"); - } - } - - /* - * Check if Permissions is loaded/enabled already - */ - private void checkPermissions() { - Plugin perm = pm.getPlugin("Permissions"); - if (perm != null && perm.isEnabled()) { - permissions = (Permissions)perm; - Stargate.log.info("[Stargate] Using Permissions (v" + permissions.getDescription().getVersion() + ")"); - } - } + if (!gate.isOpen()) { + if (iConomyHandler.useiConomy() && iConomyHandler.getBalance(player.getName()) < iConomyHandler.useCost) { + player.sendMessage(ChatColor.RED + iConomyHandler.inFundMsg); + } else if ((!gate.isFixed()) && gate.isActive() && (gate.getActivePlayer() != player)) { + gate.deactivate(); + if (!denyMsg.isEmpty()) { + player.sendMessage(ChatColor.RED + denyMsg); + } + } else if (gate.isPrivate() && !gate.getOwner().equals(player.getName()) && !hasPerm(player, "stargate.private", player.isOp())) { + if (!denyMsg.isEmpty()) { + player.sendMessage(ChatColor.RED + denyMsg); + } + } else if ((destination == null) || (destination == gate)) { + if (!invMsg.isEmpty()) { + player.sendMessage(ChatColor.RED + invMsg); + } + } else if ((destination.isOpen()) && (!destination.isAlwaysOn())) { + if (!blockMsg.isEmpty()) { + player.sendMessage(ChatColor.RED + blockMsg); + } + } else { + gate.open(player, false); + } + } else { + gate.close(false); + } + } + + /* + * Check if iConomy is loaded/enabled already + */ + private void checkiConomy() { + if (!iConomyHandler.useiConomy) return; + Plugin ico = pm.getPlugin("iConomy"); + if (ico != null && ico.isEnabled()) { + iConomyHandler.iConomy = (iConomy)ico; + Stargate.log.info("[Stargate] Using iConomy (v" + iConomyHandler.iConomy.getDescription().getVersion() + ")"); + } + } + + /* + * Check if Permissions is loaded/enabled already + */ + private void checkPermissions() { + Plugin perm = pm.getPlugin("Permissions"); + if (perm != null && perm.isEnabled()) { + permissions = (Permissions)perm; + Stargate.log.info("[Stargate] Using Permissions (v" + permissions.getDescription().getVersion() + ")"); + } + } /* * Check whether the player has the given permissions. @@ -286,308 +286,308 @@ public class Stargate extends JavaPlugin { return def; } } - - private class vListener extends VehicleListener { - @Override - public void onVehicleMove(VehicleMoveEvent event) { - Entity passenger = event.getVehicle().getPassenger(); - Vehicle vehicle = event.getVehicle(); - - Portal portal = Portal.getByEntrance(event.getTo()); - if (portal != null && portal.isOpen()) { - if (passenger instanceof Player) { - Player player = (Player)event.getVehicle().getPassenger(); - if (!portal.isOpenFor(player)) { - player.sendMessage(ChatColor.RED + denyMsg); - return; - } - Portal dest = portal.getDestination(); - if (dest == null) return; - dest.teleport(vehicle, portal); - - if (!teleMsg.isEmpty()) - player.sendMessage(ChatColor.BLUE + teleMsg); - portal.close(false); - } else { - - } - } - } - } - - private class pListener extends PlayerListener { - @Override - public void onPlayerMove(PlayerMoveEvent event) { - Player player = event.getPlayer(); - Portal portal = Portal.getByEntrance(event.getTo()); - - if ((portal != null) && (portal.isOpen())) { - if (portal.isOpenFor(player)) { - Portal destination = portal.getDestination(); - - if (destination != null) { - if (!iConomyHandler.useiConomy() || iConomyHandler.chargePlayer(player.getName(), iConomyHandler.useCost)) { - if (iConomyHandler.useiConomy()) { - player.sendMessage(ChatColor.GREEN + "Deducted " + iConomy.getBank().format(iConomyHandler.useCost)); - } - if (!teleMsg.isEmpty()) { - player.sendMessage(ChatColor.BLUE + teleMsg); - } - destination.teleport(player, portal, event); - } else { - if (!iConomyHandler.inFundMsg.isEmpty()) { - player.sendMessage(ChatColor.RED + iConomyHandler.inFundMsg); - } - } - portal.close(false); - } - } else { - if (!denyMsg.isEmpty()) { - player.sendMessage(ChatColor.RED + denyMsg); - } - } - } - } - } + private class vListener extends VehicleListener { + @Override + public void onVehicleMove(VehicleMoveEvent event) { + Entity passenger = event.getVehicle().getPassenger(); + Vehicle vehicle = event.getVehicle(); + + Portal portal = Portal.getByEntrance(event.getTo()); + if (portal != null && portal.isOpen()) { + if (passenger instanceof Player) { + Player player = (Player)event.getVehicle().getPassenger(); + if (!portal.isOpenFor(player)) { + player.sendMessage(ChatColor.RED + denyMsg); + return; + } + Portal dest = portal.getDestination(); + if (dest == null) return; + dest.teleport(vehicle, portal); + + if (!teleMsg.isEmpty()) + player.sendMessage(ChatColor.BLUE + teleMsg); + portal.close(false); + } else { + + } + } + } + } + + private class pListener extends PlayerListener { + @Override + public void onPlayerMove(PlayerMoveEvent event) { + Player player = event.getPlayer(); + Portal portal = Portal.getByEntrance(event.getTo()); - private class bListener extends BlockListener { - @Override - public void onBlockPlace(BlockPlaceEvent event) { - // Stop player from placing a block touching a portals controls - if (event.getBlockAgainst().getType() == Material.STONE_BUTTON || - event.getBlockAgainst().getType() == Material.WALL_SIGN) { - Portal portal = Portal.getByBlock(event.getBlockAgainst()); - if (portal != null) event.setCancelled(true); - } - } - - @Override - public void onSignChange(SignChangeEvent event) { - Player player = event.getPlayer(); - Block block = event.getBlock(); - if (block.getType() != Material.WALL_SIGN) return; - - // Initialize a stargate - if (hasPerm(player, "stargate.create", player.isOp()) || - hasPerm(player, "stargate.create.personal", false)) { - if (iConomyHandler.useiConomy() && !iConomyHandler.chargePlayer(player.getName(), iConomyHandler.createCost)) { - if (!iConomyHandler.inFundMsg.isEmpty()) { - player.sendMessage(ChatColor.RED + iConomyHandler.inFundMsg); - } - return; - } - SignPost sign = new SignPost(new Blox(block)); - // Set sign text so we can create a gate with it. - sign.setText(0, event.getLine(0)); - sign.setText(1, event.getLine(1)); - sign.setText(2, event.getLine(2)); - sign.setText(3, event.getLine(3)); - Portal portal = Portal.createPortal(sign, player); - if (portal == null) return; - - if (iConomyHandler.useiConomy()) { - player.sendMessage(ChatColor.GREEN + "Deducted " + iConomy.getBank().format(iConomyHandler.createCost)); - } - if (!regMsg.isEmpty()) { - player.sendMessage(ChatColor.GREEN + regMsg); - } - log.info("[Stargate] Initialized stargate: " + portal.getName()); - portal.drawSign(); - // Set event text so our new sign is instantly initialized - event.setLine(0, sign.getText(0)); - event.setLine(1, sign.getText(1)); - event.setLine(2, sign.getText(2)); - event.setLine(3, sign.getText(3)); - } - } + if ((portal != null) && (portal.isOpen())) { + if (portal.isOpenFor(player)) { + Portal destination = portal.getDestination(); - @Override - public void onBlockRightClick(BlockRightClickEvent event) { - Player player = event.getPlayer(); - Block block = event.getBlock(); - if (block.getType() == Material.WALL_SIGN) { - Portal portal = Portal.getByBlock(block); - // Cycle through a stargates locations - if (portal != null) { - if (hasPerm(player, "stargate.use", true)) { - if ((!portal.isOpen()) && (!portal.isFixed())) { - portal.cycleDestination(player); - } - } else { - if (!denyMsg.isEmpty()) { - player.sendMessage(denyMsg); - } - } - } - } - - // Implement right-click to toggle a stargate, gets around spawn protection problem. - if ((block.getType() == Material.STONE_BUTTON)) { - if (hasPerm(player, "stargate.use", true)) { - Portal portal = Portal.getByBlock(block); - if (portal != null) { - onButtonPressed(player, portal); - } - } - } - } + if (destination != null) { + if (!iConomyHandler.useiConomy() || iConomyHandler.chargePlayer(player.getName(), iConomyHandler.useCost)) { + if (iConomyHandler.useiConomy()) { + player.sendMessage(ChatColor.GREEN + "Deducted " + iConomy.getBank().format(iConomyHandler.useCost)); + } + if (!teleMsg.isEmpty()) { + player.sendMessage(ChatColor.BLUE + teleMsg); + } + + destination.teleport(player, portal, event); + } else { + if (!iConomyHandler.inFundMsg.isEmpty()) { + player.sendMessage(ChatColor.RED + iConomyHandler.inFundMsg); + } + } + portal.close(false); + } + } else { + if (!denyMsg.isEmpty()) { + player.sendMessage(ChatColor.RED + denyMsg); + } + } + } + } + } - @Override - public void onBlockDamage(BlockDamageEvent event) { - Player player = event.getPlayer(); - Block block = event.getBlock(); - // Check if we're pushing a button. - if (block.getType() == Material.STONE_BUTTON && event.getDamageLevel() == BlockDamageLevel.STARTED) { - if (hasPerm(player, "stargate.use", true)) { - Portal portal = Portal.getByBlock(block); - if (portal != null) { - onButtonPressed(player, portal); - } - } - } - } - - @Override - public void onBlockBreak(BlockBreakEvent event) { - Block block = event.getBlock(); - Player player = event.getPlayer(); - if (block.getType() != Material.WALL_SIGN && block.getType() != Material.STONE_BUTTON && Gate.getGatesByControlBlock(block).length == 0) { - return; - } + private class bListener extends BlockListener { + @Override + public void onBlockPlace(BlockPlaceEvent event) { + // Stop player from placing a block touching a portals controls + if (event.getBlockAgainst().getType() == Material.STONE_BUTTON || + event.getBlockAgainst().getType() == Material.WALL_SIGN) { + Portal portal = Portal.getByBlock(event.getBlockAgainst()); + if (portal != null) event.setCancelled(true); + } + } + + @Override + public void onSignChange(SignChangeEvent event) { + Player player = event.getPlayer(); + Block block = event.getBlock(); + if (block.getType() != Material.WALL_SIGN) return; + + // Initialize a stargate + if (hasPerm(player, "stargate.create", player.isOp()) || + hasPerm(player, "stargate.create.personal", false)) { + if (iConomyHandler.useiConomy() && !iConomyHandler.chargePlayer(player.getName(), iConomyHandler.createCost)) { + if (!iConomyHandler.inFundMsg.isEmpty()) { + player.sendMessage(ChatColor.RED + iConomyHandler.inFundMsg); + } + return; + } + SignPost sign = new SignPost(new Blox(block)); + // Set sign text so we can create a gate with it. + sign.setText(0, event.getLine(0)); + sign.setText(1, event.getLine(1)); + sign.setText(2, event.getLine(2)); + sign.setText(3, event.getLine(3)); + Portal portal = Portal.createPortal(sign, player); + if (portal == null) return; + + if (iConomyHandler.useiConomy()) { + player.sendMessage(ChatColor.GREEN + "Deducted " + iConomy.getBank().format(iConomyHandler.createCost)); + } + if (!regMsg.isEmpty()) { + player.sendMessage(ChatColor.GREEN + regMsg); + } + log.info("[Stargate] Initialized stargate: " + portal.getName()); + portal.drawSign(); + // Set event text so our new sign is instantly initialized + event.setLine(0, sign.getText(0)); + event.setLine(1, sign.getText(1)); + event.setLine(2, sign.getText(2)); + event.setLine(3, sign.getText(3)); + } + } - Portal portal = Portal.getByBlock(block); - if (portal == null) return; - - if (hasPerm(player, "stargate.destroy", player.isOp()) || hasPerm(player, "stargate.destroy.all", player.isOp()) || - ( portal.getOwner().equalsIgnoreCase(player.getName()) && hasPerm(player, "stargate.destroy.owner", false) )) { - // Can't afford - if (iConomyHandler.useiConomy() && (iConomyHandler.destroyCost > 0 && iConomyHandler.getBalance(player.getName()) < iConomyHandler.destroyCost)) { - if (!iConomyHandler.inFundMsg.isEmpty()) { - player.sendMessage(ChatColor.RED + iConomyHandler.inFundMsg); - event.setCancelled(true); - return; - } - } - if (iConomyHandler.useiConomy()) { - iConomyHandler.chargePlayer(player.getName(), iConomyHandler.destroyCost); - if (iConomyHandler.destroyCost > 0) { - player.sendMessage(ChatColor.GREEN + "Deducted " + iConomy.getBank().format(iConomyHandler.destroyCost)); - } else if (iConomyHandler.destroyCost < 0) { - player.sendMessage(ChatColor.GREEN + "Refunded " + iConomy.getBank().format(-iConomyHandler.destroyCost)); - } - } - - portal.unregister(true); - if (!dmgMsg.isEmpty()) { - player.sendMessage(ChatColor.RED + dmgMsg); - } - return; - } - - event.setCancelled(true); - } + @Override + public void onBlockRightClick(BlockRightClickEvent event) { + Player player = event.getPlayer(); + Block block = event.getBlock(); + if (block.getType() == Material.WALL_SIGN) { + Portal portal = Portal.getByBlock(block); + // Cycle through a stargates locations + if (portal != null) { + if (hasPerm(player, "stargate.use", true)) { + if ((!portal.isOpen()) && (!portal.isFixed())) { + portal.cycleDestination(player); + } + } else { + if (!denyMsg.isEmpty()) { + player.sendMessage(denyMsg); + } + } + } + } + + // Implement right-click to toggle a stargate, gets around spawn protection problem. + if ((block.getType() == Material.STONE_BUTTON)) { + if (hasPerm(player, "stargate.use", true)) { + Portal portal = Portal.getByBlock(block); + if (portal != null) { + onButtonPressed(player, portal); + } + } + } + } - @Override - public void onBlockPhysics(BlockPhysicsEvent event) { - Block block = event.getBlock(); - if (block.getType() == Material.PORTAL) { - event.setCancelled((Portal.getByEntrance(block) != null)); - } - } + @Override + public void onBlockDamage(BlockDamageEvent event) { + Player player = event.getPlayer(); + Block block = event.getBlock(); + // Check if we're pushing a button. + if (block.getType() == Material.STONE_BUTTON && event.getDamageLevel() == BlockDamageLevel.STARTED) { + if (hasPerm(player, "stargate.use", true)) { + Portal portal = Portal.getByBlock(block); + if (portal != null) { + onButtonPressed(player, portal); + } + } + } + } + + @Override + public void onBlockBreak(BlockBreakEvent event) { + Block block = event.getBlock(); + Player player = event.getPlayer(); + if (block.getType() != Material.WALL_SIGN && block.getType() != Material.STONE_BUTTON && Gate.getGatesByControlBlock(block).length == 0) { + return; + } - @Override - public void onBlockFlow(BlockFromToEvent event) { - Portal portal = Portal.getByEntrance(event.getBlock()); + Portal portal = Portal.getByBlock(block); + if (portal == null) return; + + if (hasPerm(player, "stargate.destroy", player.isOp()) || hasPerm(player, "stargate.destroy.all", player.isOp()) || + ( portal.getOwner().equalsIgnoreCase(player.getName()) && hasPerm(player, "stargate.destroy.owner", false) )) { + // Can't afford + if (iConomyHandler.useiConomy() && (iConomyHandler.destroyCost > 0 && iConomyHandler.getBalance(player.getName()) < iConomyHandler.destroyCost)) { + if (!iConomyHandler.inFundMsg.isEmpty()) { + player.sendMessage(ChatColor.RED + iConomyHandler.inFundMsg); + event.setCancelled(true); + return; + } + } + if (iConomyHandler.useiConomy()) { + iConomyHandler.chargePlayer(player.getName(), iConomyHandler.destroyCost); + if (iConomyHandler.destroyCost > 0) { + player.sendMessage(ChatColor.GREEN + "Deducted " + iConomy.getBank().format(iConomyHandler.destroyCost)); + } else if (iConomyHandler.destroyCost < 0) { + player.sendMessage(ChatColor.GREEN + "Refunded " + iConomy.getBank().format(-iConomyHandler.destroyCost)); + } + } + + portal.unregister(true); + if (!dmgMsg.isEmpty()) { + player.sendMessage(ChatColor.RED + dmgMsg); + } + return; + } + + event.setCancelled(true); + } - if (portal != null) { - event.setCancelled((event.getBlock().getY() == event.getToBlock().getY())); - } - } - } - - private class wListener extends WorldListener { - @Override - public void onWorldLoaded(WorldEvent event) { - World w = event.getWorld(); - // We have to make sure the world is actually loaded. This gets called twice for some reason. - if (w.getBlockAt(w.getSpawnLocation()).getWorld() != null) { - Portal.loadAllGates(w); - } - } - } - - private class eListener extends EntityListener { - @Override - public void onEntityExplode(EntityExplodeEvent event) { - if (event.isCancelled()) return; - for (Block b : event.blockList()) { - if (b.getTypeId() != Material.WALL_SIGN.getId() && b.getTypeId() != Material.STONE_BUTTON.getId()) continue; - Portal portal = Portal.getByBlock(b); - if (portal == null) continue; - if (destroyExplosion) { - portal.unregister(true); - } else { - b.setType(b.getType()); - event.setCancelled(true); - } - } - } - } - - private class sListener extends ServerListener { - @Override - public void onPluginEnabled(PluginEvent event) { - if (iConomyHandler.useiConomy && iConomyHandler.iConomy == null) { - if (event.getPlugin().getDescription().getName().equalsIgnoreCase("iConomy")) { - iConomyHandler.iConomy = (iConomy)event.getPlugin(); - Stargate.log.info("[Stargate] Using iConomy (v" + iConomyHandler.iConomy.getDescription().getVersion() + ")"); - } - } - if (permissions == null) { - if (event.getPlugin().getDescription().getName().equalsIgnoreCase("Permissions")) { - permissions = (Permissions)event.getPlugin(); - Stargate.log.info("[Stargate] Using Permissions (v" + permissions.getDescription().getVersion() + ")"); - } - } - } - - @Override - public void onPluginDisabled(PluginEvent event) { - if (iConomyHandler.useiConomy && iConomyHandler.iConomy != null) { - if (event.getPlugin().getDescription().getName().equalsIgnoreCase("iConomy")) { - iConomyHandler.iConomy = null; - Stargate.log.info("[Stargate] iConomy Disabled"); - } - } - if (permissions != null) { - if (event.getPlugin().getDescription().getName().equalsIgnoreCase("Permissions")) { - permissions = null; - Stargate.log.info("[Stargate] Permissions Disabled"); - } - } - } - } - - private class SGThread implements Runnable { - public void run() { - long time = System.currentTimeMillis() / 1000; - // Close open portals - for (Iterator iter = Stargate.openList.iterator(); iter.hasNext();) { - Portal p = iter.next(); - if (time > p.getOpenTime() + Stargate.openLimit) { - p.close(false); - iter.remove(); - } - } - // Deactivate active portals - for (Iterator iter = Stargate.activeList.iterator(); iter.hasNext();) { - Portal p = iter.next(); - if (time > p.getOpenTime() + Stargate.activeLimit) { - p.deactivate(); - iter.remove(); - } - } - } - } + @Override + public void onBlockPhysics(BlockPhysicsEvent event) { + Block block = event.getBlock(); + if (block.getType() == Material.PORTAL) { + event.setCancelled((Portal.getByEntrance(block) != null)); + } + } + + @Override + public void onBlockFlow(BlockFromToEvent event) { + Portal portal = Portal.getByEntrance(event.getBlock()); + + if (portal != null) { + event.setCancelled((event.getBlock().getY() == event.getToBlock().getY())); + } + } + } + + private class wListener extends WorldListener { + @Override + public void onWorldLoaded(WorldEvent event) { + World w = event.getWorld(); + // We have to make sure the world is actually loaded. This gets called twice for some reason. + if (w.getBlockAt(w.getSpawnLocation()).getWorld() != null) { + Portal.loadAllGates(w); + } + } + } + + private class eListener extends EntityListener { + @Override + public void onEntityExplode(EntityExplodeEvent event) { + if (event.isCancelled()) return; + for (Block b : event.blockList()) { + if (b.getTypeId() != Material.WALL_SIGN.getId() && b.getTypeId() != Material.STONE_BUTTON.getId()) continue; + Portal portal = Portal.getByBlock(b); + if (portal == null) continue; + if (destroyExplosion) { + portal.unregister(true); + } else { + b.setType(b.getType()); + event.setCancelled(true); + } + } + } + } + + private class sListener extends ServerListener { + @Override + public void onPluginEnabled(PluginEvent event) { + if (iConomyHandler.useiConomy && iConomyHandler.iConomy == null) { + if (event.getPlugin().getDescription().getName().equalsIgnoreCase("iConomy")) { + iConomyHandler.iConomy = (iConomy)event.getPlugin(); + Stargate.log.info("[Stargate] Using iConomy (v" + iConomyHandler.iConomy.getDescription().getVersion() + ")"); + } + } + if (permissions == null) { + if (event.getPlugin().getDescription().getName().equalsIgnoreCase("Permissions")) { + permissions = (Permissions)event.getPlugin(); + Stargate.log.info("[Stargate] Using Permissions (v" + permissions.getDescription().getVersion() + ")"); + } + } + } + + @Override + public void onPluginDisabled(PluginEvent event) { + if (iConomyHandler.useiConomy && iConomyHandler.iConomy != null) { + if (event.getPlugin().getDescription().getName().equalsIgnoreCase("iConomy")) { + iConomyHandler.iConomy = null; + Stargate.log.info("[Stargate] iConomy Disabled"); + } + } + if (permissions != null) { + if (event.getPlugin().getDescription().getName().equalsIgnoreCase("Permissions")) { + permissions = null; + Stargate.log.info("[Stargate] Permissions Disabled"); + } + } + } + } + + private class SGThread implements Runnable { + public void run() { + long time = System.currentTimeMillis() / 1000; + // Close open portals + for (Iterator iter = Stargate.openList.iterator(); iter.hasNext();) { + Portal p = iter.next(); + if (time > p.getOpenTime() + Stargate.openLimit) { + p.close(false); + iter.remove(); + } + } + // Deactivate active portals + for (Iterator iter = Stargate.activeList.iterator(); iter.hasNext();) { + Portal p = iter.next(); + if (time > p.getOpenTime() + Stargate.activeLimit) { + p.deactivate(); + iter.remove(); + } + } + } + } }