Retire regions components (Residence, Towny, WorldGuard, Factions)

This commit is contained in:
Mike Primm 2011-12-05 14:57:16 +08:00 committed by mikeprimm
parent 4f2f968353
commit 3e4bc59834
9 changed files with 5 additions and 1301 deletions

View File

@ -1,297 +0,0 @@
package org.dynmap.regions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.util.config.Configuration;
import org.dynmap.ConfigurationNode;
import org.dynmap.DynmapPlugin;
import org.dynmap.Log;
import org.dynmap.utils.TileFlags;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class FactionsConfigHandler {
private int townblocksize = 16;
protected JSONParser parser = new JSONParser();
private Charset cs_utf8 = Charset.forName("UTF-8");
public FactionsConfigHandler(ConfigurationNode cfg) {
}
/**
* Get map of attributes for given world
*/
public Map<String, Object> getRegionData(String wname) {
Map<String, Object> rslt = new HashMap<String, Object>();
/* Load factions.json file */
File faction = new File("plugins/Factions/factions.json");
if(faction.canRead() == false) { /* Can't read config */
Log.severe("Cannot find Faction file - " + faction.getPath());
return rslt;
}
JSONObject fact = null;
Reader inputFileReader = null;
try {
inputFileReader = new InputStreamReader(new FileInputStream(faction), cs_utf8);
fact = (JSONObject) parser.parse(inputFileReader);
} catch (IOException ex) {
Log.severe("Exception while reading factions.json.", ex);
} catch (ParseException ex) {
Log.severe("Exception while parsing factions.json.", ex);
} finally {
if(inputFileReader != null) {
try {
inputFileReader.close();
} catch (IOException iox) {}
inputFileReader = null;
}
}
if(fact == null)
return rslt;
/* Load board.json */
File board = new File("plugins/Factions/board.json");
if(board.canRead() == false) { /* Can't read config */
Log.severe("Cannot find Faction file - " + board.getPath());
return rslt;
}
JSONObject blocks = null;
try {
inputFileReader = new InputStreamReader(new FileInputStream(board), cs_utf8);
blocks = (JSONObject) parser.parse(inputFileReader);
} catch (IOException ex) {
Log.severe("Exception while reading board.json.", ex);
} catch (ParseException ex) {
Log.severe("Exception while parsing board.json.", ex);
} finally {
if(inputFileReader != null) {
try {
inputFileReader.close();
} catch (IOException iox) {}
inputFileReader = null;
}
}
if(blocks == null)
return rslt;
/* Get value from board.json for requested world */
Object wb = blocks.get(wname);
if((wb == null) || (!(wb instanceof JSONObject))) {
return rslt;
}
JSONObject wblocks = (JSONObject)wb;
/* Now go through the factions list, and find outline */
for(Object factid : fact.keySet()) {
int fid = 0;
try {
fid = Integer.valueOf(factid.toString());
} catch (NumberFormatException nfx) {
continue;
}
JSONObject fobj = (JSONObject)fact.get(factid); /* Get faction info */
String town = (String)fobj.get("tag");
town = ChatColor.stripColor(town); /* Strip color */
Map<?,?> td = processFaction(wblocks, fobj, fid);
if(td != null) {
rslt.put(town, td);
}
}
return rslt;
}
enum direction { XPLUS, YPLUS, XMINUS, YMINUS };
private static final String FLAGS[] = {
"open", "peaceful", "peacefulExplosionsEnabled"
};
/**
* Find all contiguous blocks, set in target and clear in source
*/
private int floodFillTarget(TileFlags src, TileFlags dest, int x, int y) {
int cnt = 0;
if(src.getFlag(x, y)) { /* Set in src */
src.setFlag(x, y, false); /* Clear source */
dest.setFlag(x, y, true); /* Set in destination */
cnt++;
cnt += floodFillTarget(src, dest, x+1, y); /* Fill adjacent blocks */
cnt += floodFillTarget(src, dest, x-1, y);
cnt += floodFillTarget(src, dest, x, y+1);
cnt += floodFillTarget(src, dest, x, y-1);
}
return cnt;
}
/**
* Process data from given town file
*/
public Map<String,Object> processFaction(JSONObject blocks, JSONObject faction, int factid) {
/* Build list of nodes matching our faction ID */
LinkedList<int[]> nodevals = new LinkedList<int[]>();
TileFlags blks = new TileFlags();
for(Object k: blocks.keySet()) {
Object fid = blocks.get(k);
int bfid = 0;
try {
bfid = Integer.valueOf(fid.toString());
} catch (NumberFormatException nfx) {
continue;
}
if(bfid == factid) { /* Our faction? */
String[] coords = k.toString().split(",");
if(coords.length >= 2) {
try {
int[] vv = new int[] { Integer.valueOf(coords[0]), Integer.valueOf(coords[1]) };
blks.setFlag(vv[0], vv[1], true);
nodevals.add(vv);
} catch (NumberFormatException nfx) {
Log.severe("Error parsing Factions blocks");
return null;
}
}
}
}
/* If nothing found for this faction, skip */
if(nodevals.size() == 0)
return null;
/* Loop through until we don't find more areas */
ArrayList<Map<String,Integer>[]> polygons = new ArrayList<Map<String,Integer>[]>();
while(nodevals != null) {
LinkedList<int[]> ournodes = null;
LinkedList<int[]> newlist = null;
TileFlags ourblks = null;
int minx = Integer.MAX_VALUE;
int miny = Integer.MAX_VALUE;
for(int[] node : nodevals) {
if((ourblks == null) && blks.getFlag(node[0], node[1])) { /* Node still in map? */
ourblks = new TileFlags(); /* Create map for shape */
ournodes = new LinkedList<int[]>();
floodFillTarget(blks, ourblks, node[0], node[1]); /* Copy shape */
ournodes.add(node); /* Add it to our node list */
minx = node[0]; miny = node[1];
}
/* If shape found, and we're in it, add to our node list */
else if((ourblks != null) && (ourblks.getFlag(node[0], node[1]))) {
ournodes.add(node);
if(node[0] < minx) {
minx = node[0]; miny = node[1];
}
else if((node[0] == minx) && (node[1] < miny)) {
miny = node[1];
}
}
else { /* Else, keep it in the list for the next polygon */
if(newlist == null) newlist = new LinkedList<int[]>();
newlist.add(node);
}
}
nodevals = newlist; /* Replace list (null if no more to process) */
if(ourblks == null) continue; /* Nothing found, skip to end */
/* Trace outline of blocks - start from minx, miny going to x+ */
int init_x = minx;
int init_y = miny;
int cur_x = minx;
int cur_y = miny;
direction dir = direction.XPLUS;
ArrayList<int[]> linelist = new ArrayList<int[]>();
linelist.add(new int[] { init_x, init_y } ); // Add start point
while((cur_x != init_x) || (cur_y != init_y) || (dir != direction.YMINUS)) {
switch(dir) {
case XPLUS: /* Segment in X+ direction */
if(!ourblks.getFlag(cur_x+1, cur_y)) { /* Right turn? */
linelist.add(new int[] { cur_x+1, cur_y }); /* Finish line */
dir = direction.YPLUS; /* Change direction */
}
else if(!ourblks.getFlag(cur_x+1, cur_y-1)) { /* Straight? */
cur_x++;
}
else { /* Left turn */
linelist.add(new int[] { cur_x+1, cur_y }); /* Finish line */
dir = direction.YMINUS;
cur_x++; cur_y--;
}
break;
case YPLUS: /* Segment in Y+ direction */
if(!ourblks.getFlag(cur_x, cur_y+1)) { /* Right turn? */
linelist.add(new int[] { cur_x+1, cur_y+1 }); /* Finish line */
dir = direction.XMINUS; /* Change direction */
}
else if(!ourblks.getFlag(cur_x+1, cur_y+1)) { /* Straight? */
cur_y++;
}
else { /* Left turn */
linelist.add(new int[] { cur_x+1, cur_y+1 }); /* Finish line */
dir = direction.XPLUS;
cur_x++; cur_y++;
}
break;
case XMINUS: /* Segment in X- direction */
if(!ourblks.getFlag(cur_x-1, cur_y)) { /* Right turn? */
linelist.add(new int[] { cur_x, cur_y+1 }); /* Finish line */
dir = direction.YMINUS; /* Change direction */
}
else if(!ourblks.getFlag(cur_x-1, cur_y+1)) { /* Straight? */
cur_x--;
}
else { /* Left turn */
linelist.add(new int[] { cur_x, cur_y+1 }); /* Finish line */
dir = direction.YPLUS;
cur_x--; cur_y++;
}
break;
case YMINUS: /* Segment in Y- direction */
if(!ourblks.getFlag(cur_x, cur_y-1)) { /* Right turn? */
linelist.add(new int[] { cur_x, cur_y }); /* Finish line */
dir = direction.XPLUS; /* Change direction */
}
else if(!ourblks.getFlag(cur_x-1, cur_y-1)) { /* Straight? */
cur_y--;
}
else { /* Left turn */
linelist.add(new int[] { cur_x, cur_y }); /* Finish line */
dir = direction.XMINUS;
cur_x--; cur_y--;
}
break;
}
}
@SuppressWarnings("unchecked")
Map<String,Integer>[] coordlist = new Map[linelist.size()];
for(int i = 0; i < linelist.size(); i++) {
coordlist[i] = new HashMap<String,Integer>();
coordlist[i].put("x", linelist.get(i)[0] * townblocksize);
coordlist[i].put("z", linelist.get(i)[1] * townblocksize);
}
polygons.add(coordlist);
}
@SuppressWarnings("unchecked")
Map<String,Integer>[][] polylist = new Map[polygons.size()][];
polygons.toArray(polylist);
HashMap<String,Object> rslt = new HashMap<String,Object>();
rslt.put("points", polylist);
/* Add other data */
Map<String,String> flags = new HashMap<String,String>();
for(String f : FLAGS) {
Object fval = faction.get(f);
if(fval != null) flags.put(f, fval.toString());
}
rslt.put("flags", flags);
return rslt;
}
}

View File

@ -1,126 +0,0 @@
package org.dynmap.regions;
import java.io.File;
import java.util.List;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Map;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import org.bukkit.util.config.Configuration;
import org.dynmap.ConfigurationNode;
import org.dynmap.Log;
import org.dynmap.web.HttpRequest;
import org.dynmap.web.HttpResponse;
import org.dynmap.web.Json;
import org.dynmap.web.handlers.FileHandler;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
public class RegionHandler extends FileHandler {
private ConfigurationNode regions;
private String regiontype;
private TownyConfigHandler towny;
private FactionsConfigHandler factions;
public RegionHandler(ConfigurationNode regions) {
this.regions = regions;
regiontype = regions.getString("name", "WorldGuard");
if(regiontype.equals("Towny")) {
towny = new TownyConfigHandler(regions);
}
else if(regiontype.equals("Factions")) {
factions = new FactionsConfigHandler(regions);
}
}
@Override
protected InputStream getFileInput(String path, HttpRequest request, HttpResponse response) {
if(regions == null)
return null;
/* Right path? */
if(path.endsWith(".json") == false)
return null;
String worldname = path.substring(0, path.lastIndexOf(".json"));
Configuration regionConfig = null;
File infile;
String regionFile;
Map<?, ?> regionData;
if(regiontype.equals("Towny")) {
regionData = towny.getRegionData(worldname);
}
else if(regiontype.equals("Factions")) {
regionData = factions.getRegionData(worldname);
}
else if(regiontype.equals("Residence")) {
File f = new File("plugins/Residence/Save/Worlds", "res_" + worldname + ".yml");
if(f.exists()) {
regionConfig = new org.bukkit.util.config.Configuration(f);
}
else {
f = new File("plugins/Residence", "res.yml");
if(f.exists()) {
regionConfig = new org.bukkit.util.config.Configuration(f);
}
}
if(regionConfig == null) return null;
regionConfig.load();
regionData = (Map<?, ?>) regionConfig.getProperty("Residences");
if(regionData == null) {
Log.severe("Region data from " + f.getPath() + " does not include basenode 'Residences'");
return null;
}
}
else {
/* If using worldpath, format is either plugins/<plugin>/<worldname>/<filename> OR
* plugins/<plugin>/worlds/<worldname>/<filename>
*/
File basepath = new File("plugins", regiontype);
if(basepath.exists() == false)
return null;
if(regions.getBoolean("useworldpath", false)) {
regionFile = worldname + "/" + regions.getString("filename", "regions.yml");
infile = new File(basepath, regionFile);
if(!infile.exists()) {
infile = new File(basepath, "worlds/" + regionFile);
}
}
else { /* Else, its plugins/<plugin>/<filename> */
regionFile = regions.getString("filename", "regions.yml");
infile = new File(basepath, regionFile);
}
if(infile.exists()) {
regionConfig = new Configuration(infile);
}
//File didn't exist
if(regionConfig == null)
return null;
regionConfig.load();
/* Parse region data and store in MemoryInputStream */
String bnode = regions.getString("basenode", "regions");
regionData = (Map<?, ?>) regionConfig.getProperty(bnode);
if(regionData == null) {
Log.severe("Region data from " + infile.getPath() + " does not include basenode '" + bnode + "'");
return null;
}
}
/* See if we have explicit list of regions to report - limit to this list if we do */
RegionsComponent.filterOutHidden(regions.getStrings("visibleregions", null), regions.getStrings("hiddenregions", null), regionData, regiontype);
try {
ByteArrayOutputStream fos = new ByteArrayOutputStream();
fos.write(Json.stringifyJson(regionData).getBytes());
fos.close();
return new ByteArrayInputStream(fos.toByteArray());
} catch (FileNotFoundException ex) {
log.log(Level.SEVERE, "Exception while writing JSON-file.", ex);
} catch (IOException ioe) {
log.log(Level.SEVERE, "Exception while writing JSON-file.", ioe);
}
return null;
}
}

View File

@ -1,213 +1,22 @@
package org.dynmap.regions; package org.dynmap.regions;
import java.io.File; import org.dynmap.Component;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.World;
import org.dynmap.ClientComponent;
import org.dynmap.ClientUpdateEvent;
import org.dynmap.ConfigurationNode; import org.dynmap.ConfigurationNode;
import org.dynmap.DynmapPlugin; import org.dynmap.DynmapPlugin;
import org.dynmap.Event;
import org.dynmap.Log; import org.dynmap.Log;
import org.dynmap.web.Json;
public class RegionsComponent extends ClientComponent {
private TownyConfigHandler towny;
private FactionsConfigHandler factions;
private String regiontype;
public class RegionsComponent extends Component {
private static String deprecated_ids[] = { "Residence", "Factions", "Towny", "WorldGuard" }; private static String deprecated_ids[] = { "Residence", "Factions", "Towny", "WorldGuard" };
private static String deprecated_new_plugins[] = { "dynmap-residence", "Dynmap-Factions", "Dynmap-Towny", "Dynmap-WorldGuard" }; private static String deprecated_new_plugins[] = { "dynmap-residence", "Dynmap-Factions", "Dynmap-Towny", "Dynmap-WorldGuard" };
public RegionsComponent(final DynmapPlugin plugin, final ConfigurationNode configuration) { public RegionsComponent(final DynmapPlugin plugin, final ConfigurationNode configuration) {
super(plugin, configuration); super(plugin, configuration);
regiontype = configuration.getString("name", "WorldGuard"); String regiontype = configuration.getString("name", "WorldGuard");
/* Check if a deprecated component */ /* Check if a deprecated component */
for(int i = 0; i < deprecated_ids.length; i++) { for(int i = 0; i < deprecated_ids.length; i++) {
if(regiontype.equals(deprecated_ids[i])) { /* If match */ if(regiontype.equals(deprecated_ids[i])) { /* If match */
/* See if new plugin is installed - disable if it is */ Log.info("Region component for '" + regiontype + "' has been RETIRED - migrate to '" + deprecated_new_plugins[i] + "' plugin");
if(plugin.getServer().getPluginManager().getPlugin(deprecated_new_plugins[i]) != null) {
Log.info("Region component for '" + regiontype + "' disabled, replaced by '" + deprecated_new_plugins[i] + "' plugin, which is installed");
disableComponent();
return;
}
else {
Log.info("Region component for '" + regiontype + "' has been DEPRECATED - migrate to '" + deprecated_new_plugins[i] + "' plugin");
}
}
}
// For internal webserver.
String fname = configuration.getString("filename", "regions.yml");
/* Load special handler for Towny */
if(regiontype.equals("Towny")) {
towny = new TownyConfigHandler(configuration);
plugin.webServer.handlers.put("/standalone/towny_*", new RegionHandler(configuration));
}
/* Load special handler for Factions */
else if(regiontype.equals("Factions")) {
factions = new FactionsConfigHandler(configuration);
plugin.webServer.handlers.put("/standalone/factions_*", new RegionHandler(configuration));
}
else {
plugin.webServer.handlers.put("/standalone/" + fname.substring(0, fname.lastIndexOf('.')) + "_*", new RegionHandler(configuration));
}
// For external webserver.
//Parse region file for multi world style
if (configuration.getBoolean("useworldpath", false)) {
plugin.events.addListener("clientupdatewritten", new Event.Listener<ClientUpdateEvent>() {
@Override
public void triggered(ClientUpdateEvent t) {
World world = t.world.world;
parseRegionFile(world.getName(), world.getName() + "/" + configuration.getString("filename", "regions.yml"), configuration.getString("filename", "regions.yml").replace(".", "_" + world.getName() + ".yml"));
}
});
} else {
plugin.events.addListener("clientupdatewritten", new Event.Listener<ClientUpdateEvent>() {
@Override
public void triggered(ClientUpdateEvent t) {
World world = t.world.world;
parseRegionFile(world.getName(), configuration.getString("filename", "regions.yml"), configuration.getString("filename", "regions.yml").replace(".", "_" + world.getName() + ".yml"));
}
});
}
}
//handles parsing and writing region json files
private void parseRegionFile(String wname, String regionFile, String outputFileName)
{
File outputFile;
org.bukkit.util.config.Configuration regionConfig = null;
Map<?, ?> regionData = null;
File webWorldPath;
if(regiontype.equals("Towny")) {
regionData = towny.getRegionData(wname);
outputFileName = "towny_" + wname + ".json";
webWorldPath = new File(plugin.getWebPath()+"/standalone/", outputFileName);
}
else if(regiontype.equals("Factions")) {
regionData = factions.getRegionData(wname);
outputFileName = "factions_" + wname + ".json";
webWorldPath = new File(plugin.getWebPath()+"/standalone/", outputFileName);
}
else if(regiontype.equals("Residence")) {
File f = new File("plugins/Residence/Save/Worlds", "res_" + wname + ".yml");
if(f.exists()) {
regionConfig = new org.bukkit.util.config.Configuration(f);
}
else {
f = new File("plugins/Residence", "res.yml");
if(f.exists()) {
regionConfig = new org.bukkit.util.config.Configuration(f);
}
}
if(regionConfig == null) return;
outputFileName = "res_" + wname + ".json";
webWorldPath = new File(plugin.getWebPath()+"/standalone/", outputFileName);
regionConfig.load();
regionData = (Map<?, ?>) regionConfig.getProperty("Residences");
}
else {
if(configuration.getBoolean("useworldpath", false))
{
if(new File("plugins/"+regiontype, regionFile).exists())
regionConfig = new org.bukkit.util.config.Configuration(new File("plugins/"+regiontype, regionFile));
else if(new File("plugins/"+regiontype+"/worlds", regionFile).exists())
regionConfig = new org.bukkit.util.config.Configuration(new File("plugins/"+regiontype+"/worlds", regionFile));
}
else
regionConfig = new org.bukkit.util.config.Configuration(new File("plugins/"+regiontype, regionFile));
//File didn't exist
if(regionConfig == null)
return;
regionConfig.load();
regionData = (Map<?, ?>) regionConfig.getProperty(configuration.getString("basenode", "regions"));
outputFileName = outputFileName.substring(0, outputFileName.lastIndexOf("."))+".json";
webWorldPath = new File(plugin.getWebPath()+"/standalone/", outputFileName);
}
/* Process out hidden data */
filterOutHidden(configuration.getStrings("visibleregions", null), configuration.getStrings("hiddenregions", null), regionData, regiontype);
if (webWorldPath.isAbsolute())
outputFile = webWorldPath;
else {
outputFile = new File(plugin.getDataFolder(), webWorldPath.toString());
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(outputFile);
fos.write(Json.stringifyJson(regionData).getBytes());
} catch (FileNotFoundException ex) {
Log.severe("Exception while writing JSON-file.", ex);
} catch (IOException ioe) {
Log.severe("Exception while writing JSON-file.", ioe);
} finally {
if(fos != null) {
try {
fos.close();
} catch (IOException iox) {}
fos = null;
}
}
}
public static void filterOutHidden(List<String> idlist, List<String> hidlist, Map<?,?> regionData, String regiontype) {
/* See if we have explicit list of regions to report - limit to this list if we do */
if((regionData != null) && ((idlist != null) || (hidlist != null))) {
@SuppressWarnings("unchecked")
HashSet<String> ids = new HashSet<String>((Collection<? extends String>) regionData.keySet());
for(String id : ids) {
/* If include list defined, and we're not in it, remove */
if((idlist != null) && (!idlist.contains(id))) {
regionData.remove(id);
}
/* If exclude list defined, and we're on it, remove */
else if(hidlist != null) {
if(hidlist.contains(id)) {
/* If residence, we want to zap the areas list, so that we still get subregions */
if(regiontype.equals("Residence")) {
Map<?,?> m = (Map<?,?>)regionData.get(id);
if(m != null) {
Map<?,?> a = (Map<?,?>)m.get("Areas");
if(a != null) {
a.clear();
}
}
}
else {
regionData.remove(id);
}
}
if(regiontype.equals("Residence")) {
Map<?,?> m = (Map<?,?>)regionData.get(id);
if(m != null) {
m = (Map<?,?>)m.get("Subzones");
if(m != null) {
Set<?> ks = m.keySet();
for(Object k : ks) {
String sid = id + "." + k;
if(hidlist.contains(sid)) {
m.remove(k);
}
}
}
}
}
}
} }
} }
} }

View File

@ -1,301 +0,0 @@
package org.dynmap.regions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.bukkit.World;
import org.bukkit.util.config.Configuration;
import org.dynmap.ConfigurationNode;
import org.dynmap.DynmapPlugin;
import org.dynmap.Log;
import org.dynmap.utils.TileFlags;
public class TownyConfigHandler {
private int townblocksize; /* Size of each block - default is 16x16 */
public TownyConfigHandler(ConfigurationNode cfg) {
/* Find path to Towny base configuration */
File cfgfile = new File("plugins/Towny/settings/config.yml");
if(cfgfile.canRead() == false) { /* Can't read config */
Log.severe("Cannot find Towny file - " + cfgfile.getPath());
return;
}
Configuration tcfg = new Configuration(cfgfile);
tcfg.load();
org.bukkit.util.config.ConfigurationNode townnode = tcfg.getNode("town");
String tbsize = "16";
if(townnode != null)
tbsize = townnode.getString("town_block_size", "16");
else
tbsize = tcfg.getString("town_block_size", "16");
try {
townblocksize = Integer.valueOf(tbsize);
} catch (NumberFormatException nfx) {
townblocksize = 16;
}
}
/**
* Get map of attributes for given world
*/
public Map<String, Object> getRegionData(String wname) {
Map<String, Object> rslt = new HashMap<String, Object>();
FileInputStream fis = null;
List<String> towns = new LinkedList<String>();
/* Get town list */
try {
fis = new FileInputStream("plugins/Towny/data/towns.txt"); /* Open and load file */
LineNumberReader rdr = new LineNumberReader(new InputStreamReader(fis));
String id;
while((id = rdr.readLine()) != null) {
towns.add(id);
}
} catch (IOException iox) {
Log.severe("Error loading Towny world file " + wname + ".txt");
} finally {
if(fis != null) {
try { fis.close(); } catch (IOException iox) {}
}
}
/* List towns directory - process all towns there */
for(String town : towns) {
town = town.trim();
if(town.length() == 0) continue;
File tfile = new File("plugins/Towny/data/towns/" + town + ".txt");
Map<?,?> td = processTown(tfile, wname);
if(td != null) {
rslt.put(town, td);
}
}
return rslt;
}
enum direction { XPLUS, YPLUS, XMINUS, YMINUS };
private static final String FLAGS[] = {
"hasUpkeep", "pvp", "mobs", "public", "explosion", "fire"
};
/**
* Find all contiguous blocks, set in target and clear in source
*/
private int floodFillTarget(TileFlags src, TileFlags dest, int x, int y) {
int cnt = 0;
if(src.getFlag(x, y)) { /* Set in src */
src.setFlag(x, y, false); /* Clear source */
dest.setFlag(x, y, true); /* Set in destination */
cnt++;
cnt += floodFillTarget(src, dest, x+1, y); /* Fill adjacent blocks */
cnt += floodFillTarget(src, dest, x-1, y);
cnt += floodFillTarget(src, dest, x, y+1);
cnt += floodFillTarget(src, dest, x, y-1);
}
return cnt;
}
/**
* Process data from given town file
*/
public Map<String,Object> processTown(File townfile, String wname) {
Properties p = new Properties();
FileInputStream fis = null;
Map<String, Object> rslt = null;
try {
fis = new FileInputStream(townfile); /* Open and load file */
p.load(fis);
} catch (IOException iox) {
Log.severe("Error loading Towny file " + townfile.getPath());
} finally {
if(fis != null) {
try { fis.close(); } catch (IOException iox) {}
}
}
/* Get block list */
String blocks = p.getProperty("townBlocks");
if(blocks == null) /* Skip if no blocks */
return null;
String[] nodes = blocks.split(";"); /* Split into list */
TileFlags blks = new TileFlags();
LinkedList<int[]> nodevals = new LinkedList<int[]>();
boolean worldmatch = false;
for(String n: nodes) {
/* Is world prefix? */
int idx = n.indexOf(':');
if(idx >= 0) {
String w = n.substring(0, idx);
if(w.startsWith("|")) w = w.substring(1);
worldmatch = w.equals(wname); /* See if our world */
n = n.substring(idx+1); /* Process remainder as coordinate */
}
if(!worldmatch) continue;
int bidx = n.indexOf(']');
if(bidx >= 0) { /* If 0.75 block type present, skip it (we don't care yet) */
n = n.substring(bidx+1);
}
String[] v = n.split(",");
if(v.length >= 2) { /* Price in 0.75 is third - don't care :) */
try {
int[] vv = new int[] { Integer.valueOf(v[0]), Integer.valueOf(v[1]) };
blks.setFlag(vv[0], vv[1], true);
nodevals.add(vv);
} catch (NumberFormatException nfx) {
Log.severe("Error parsing block list in Towny - " + townfile.getPath());
return null;
}
} else if(n.startsWith("|")){ /* End of list? */
} else {
Log.severe("Invalid block list format in Towny - " + townfile.getPath());
return null;
}
}
/* If nothing in this world, skip */
if(nodevals.size() == 0)
return null;
/* Loop through until we don't find more areas */
ArrayList<Map<String,Integer>[]> polygons = new ArrayList<Map<String,Integer>[]>();
while(nodevals != null) {
LinkedList<int[]> ournodes = null;
LinkedList<int[]> newlist = null;
TileFlags ourblks = null;
int minx = Integer.MAX_VALUE;
int miny = Integer.MAX_VALUE;
for(int[] node : nodevals) {
if((ourblks == null) && blks.getFlag(node[0], node[1])) { /* Node still in map? */
ourblks = new TileFlags(); /* Create map for shape */
ournodes = new LinkedList<int[]>();
floodFillTarget(blks, ourblks, node[0], node[1]); /* Copy shape */
ournodes.add(node); /* Add it to our node list */
minx = node[0]; miny = node[1];
}
/* If shape found, and we're in it, add to our node list */
else if((ourblks != null) && (ourblks.getFlag(node[0], node[1]))) {
ournodes.add(node);
if(node[0] < minx) {
minx = node[0]; miny = node[1];
}
else if((node[0] == minx) && (node[1] < miny)) {
miny = node[1];
}
}
else { /* Else, keep it in the list for the next polygon */
if(newlist == null) newlist = new LinkedList<int[]>();
newlist.add(node);
}
}
nodevals = newlist; /* Replace list (null if no more to process) */
if(ourblks == null) continue; /* Nothing found, skip to end */
/* Trace outline of blocks - start from minx, miny going to x+ */
int init_x = minx;
int init_y = miny;
int cur_x = minx;
int cur_y = miny;
direction dir = direction.XPLUS;
ArrayList<int[]> linelist = new ArrayList<int[]>();
linelist.add(new int[] { init_x, init_y } ); // Add start point
while((cur_x != init_x) || (cur_y != init_y) || (dir != direction.YMINUS)) {
switch(dir) {
case XPLUS: /* Segment in X+ direction */
if(!ourblks.getFlag(cur_x+1, cur_y)) { /* Right turn? */
linelist.add(new int[] { cur_x+1, cur_y }); /* Finish line */
dir = direction.YPLUS; /* Change direction */
}
else if(!ourblks.getFlag(cur_x+1, cur_y-1)) { /* Straight? */
cur_x++;
}
else { /* Left turn */
linelist.add(new int[] { cur_x+1, cur_y }); /* Finish line */
dir = direction.YMINUS;
cur_x++; cur_y--;
}
break;
case YPLUS: /* Segment in Y+ direction */
if(!ourblks.getFlag(cur_x, cur_y+1)) { /* Right turn? */
linelist.add(new int[] { cur_x+1, cur_y+1 }); /* Finish line */
dir = direction.XMINUS; /* Change direction */
}
else if(!ourblks.getFlag(cur_x+1, cur_y+1)) { /* Straight? */
cur_y++;
}
else { /* Left turn */
linelist.add(new int[] { cur_x+1, cur_y+1 }); /* Finish line */
dir = direction.XPLUS;
cur_x++; cur_y++;
}
break;
case XMINUS: /* Segment in X- direction */
if(!ourblks.getFlag(cur_x-1, cur_y)) { /* Right turn? */
linelist.add(new int[] { cur_x, cur_y+1 }); /* Finish line */
dir = direction.YMINUS; /* Change direction */
}
else if(!ourblks.getFlag(cur_x-1, cur_y+1)) { /* Straight? */
cur_x--;
}
else { /* Left turn */
linelist.add(new int[] { cur_x, cur_y+1 }); /* Finish line */
dir = direction.YPLUS;
cur_x--; cur_y++;
}
break;
case YMINUS: /* Segment in Y- direction */
if(!ourblks.getFlag(cur_x, cur_y-1)) { /* Right turn? */
linelist.add(new int[] { cur_x, cur_y }); /* Finish line */
dir = direction.XPLUS; /* Change direction */
}
else if(!ourblks.getFlag(cur_x-1, cur_y-1)) { /* Straight? */
cur_y--;
}
else { /* Left turn */
linelist.add(new int[] { cur_x, cur_y }); /* Finish line */
dir = direction.XMINUS;
cur_x--; cur_y--;
}
break;
}
}
@SuppressWarnings("unchecked")
Map<String,Integer>[] coordlist = new Map[linelist.size()];
for(int i = 0; i < linelist.size(); i++) {
coordlist[i] = new HashMap<String,Integer>();
coordlist[i].put("x", linelist.get(i)[0] * townblocksize);
coordlist[i].put("z", linelist.get(i)[1] * townblocksize);
}
polygons.add(coordlist);
}
@SuppressWarnings("unchecked")
Map<String,Integer>[][] polylist = new Map[polygons.size()][];
polygons.toArray(polylist);
rslt = new HashMap<String,Object>();
rslt.put("points", polylist);
/* Add other data */
String mayor = p.getProperty("mayor");
if(mayor != null) rslt.put("mayor", mayor);
String nation = p.getProperty("nation");
if(nation != null) rslt.put("nation", nation);
String assistants = p.getProperty("assistants");
if(assistants != null) rslt.put("assistants", assistants);
String residents = p.getProperty("residents");
if(residents != null) rslt.put("residents", residents);
Map<String,String> flags = new HashMap<String,String>();
for(String f : FLAGS) {
String fval = p.getProperty(f);
if(fval != null) flags.put(f, fval);
}
rslt.put("flags", flags);
return rslt;
}
}

View File

@ -1,204 +1,3 @@
var regionConstructors = {};
componentconstructors['regions'] = function(dynmap, configuration) { componentconstructors['regions'] = function(dynmap, configuration) {
// Compatibility with older configurations.
if (configuration.regionstyle) {
configuration.regionstyle = $.extend({
stroke: true,
color: configuration.regionstyle.strokeColor,
opacity: configuration.regionstyle.strokeOpacity || 0.01,
weight: configuration.regionstyle.strokeWeight,
fill: true,
smoothFactor: 0.0,
fillOpacity: configuration.regionstyle.fillOpacity || 0.01,
fillColor: configuration.regionstyle.fillColor
}, configuration.regionstyle);
}
function getStyle(name, group) {
var style = $.extend({}, configuration.regionstyle);
if(configuration.groupstyle && group && configuration.groupstyle[group]) {
var cs = configuration.groupstyle[group];
if(cs.strokeColor)
style.color = cs.strokeColor;
if(cs.strokeOpacity)
style.opacity = cs.strokeOpacity;
if(cs.strokeWeight)
style.weight = cs.strokeWeight;
if(cs.fillOpacity)
style.fillOpacity = cs.fillOpacity;
if(cs.fillColor)
style.fillColor = cs.fillColor;
}
if(configuration.customstyle && name && configuration.customstyle[name]) {
var cs = configuration.customstyle[name];
if(cs.strokeColor)
style.color = cs.strokeColor;
if(cs.strokeOpacity)
style.opacity = cs.strokeOpacity;
if(cs.strokeWeight)
style.weight = cs.strokeWeight;
if(cs.fillOpacity)
style.fillOpacity = cs.fillOpacity;
if(cs.fillColor)
style.fillColor = cs.fillColor;
}
return style;
}
// Helper functions
latlng = function(x, y, z) {
return dynmap.getProjection().fromLocationToLatLng(new Location(undefined, x,y,z));
}
function create3DBoxLayer(maxx, minx, maxy, miny, maxz, minz, style) {
return new L.MultiPolygon([
[
latlng(minx,miny,minz),
latlng(maxx,miny,minz),
latlng(maxx,miny,maxz),
latlng(minx,miny,maxz)
],[
latlng(minx,maxy,minz),
latlng(maxx,maxy,minz),
latlng(maxx,maxy,maxz),
latlng(minx,maxy,maxz)
],[
latlng(minx,miny,minz),
latlng(minx,maxy,minz),
latlng(maxx,maxy,minz),
latlng(maxx,miny,minz)
],[
latlng(maxx,miny,minz),
latlng(maxx,maxy,minz),
latlng(maxx,maxy,maxz),
latlng(maxx,miny,maxz)
],[
latlng(minx,miny,maxz),
latlng(minx,maxy,maxz),
latlng(maxx,maxy,maxz),
latlng(maxx,miny,maxz)
],[
latlng(minx,miny,minz),
latlng(minx,maxy,minz),
latlng(minx,maxy,maxz),
latlng(minx,miny,maxz)
]], style);
}
function create2DBoxLayer(maxx, minx, maxy, miny, maxz, minz, style) {
return new L.Polygon([
latlng(minx,64,minz),
latlng(maxx,64,minz),
latlng(maxx,64,maxz),
latlng(minx,64,maxz)
], style);
}
function create3DOutlineLayer(xarray, maxy, miny, zarray, style) {
var toplist = [];
var botlist = [];
var i;
var polylist = [];
for(i = 0; i < xarray.length; i++) {
toplist[i] = latlng(xarray[i], maxy, zarray[i]);
botlist[i] = latlng(xarray[i], miny, zarray[i]);
}
for(i = 0; i < xarray.length; i++) {
var sidelist = [];
sidelist[0] = toplist[i];
sidelist[1] = botlist[i];
sidelist[2] = botlist[(i+1)%xarray.length];
sidelist[3] = toplist[(i+1)%xarray.length];
polylist[i] = sidelist;
}
polylist[xarray.length] = botlist;
polylist[xarray.length+1] = toplist;
return new L.MultiPolygon(polylist, style);
}
function create2DOutlineLayer(xarray, maxy, miny, zarray, style) {
var llist = [];
var i;
for(i = 0; i < xarray.length; i++) {
llist[i] = latlng(xarray[i], 64, zarray[i]);
}
return new L.Polygon(llist, style);
}
function createPopupContent(name, region) {
function join(a) {
if (a instanceof Array) {
return a.join(', ');
} else if (typeof a === 'string') {
return a;
} else {
return "";
}
}
var members = region.members || {};
var popup = this.infowindow || '<div class="infowindow"><span style="font-size:120%;">%regionname%</span><br /> Owner <span style="font-weight:bold;">%playerowners%</span><br />Flags<br /><span style="font-weight:bold;">%flags%</span></div>';
popup = popup.replace('%regionname%', name);
popup = popup.replace('%playerowners%', join(region.owners.players));
popup = popup.replace('%groupowners%', join(region.owners.groups));
popup = popup.replace('%playermanagers%', join(region.associates || ""));
popup = popup.replace('%playermembers%', join(members.players));
popup = popup.replace('%groupmembers%', join(members.groups));
popup = popup.replace('%parent%', region.parent || "");
popup = popup.replace('%priority%', region.priority || "");
popup = popup.replace('%nation%', region.nation || "");
var regionflags = "";
$.each(region.flags, function(name, value) {
regionflags = regionflags + "<span>" + name + ": " + value + "</span><br>";
});
popup = popup.replace('%flags%', regionflags);
return $('<div/>').addClass('regioninfo')
.append(popup)[0];
}
var self = this;
loadcss('css/regions.css');
var regionType = configuration.name;
loadjs('js/regions_' + regionType + '.js', function() {
configuration.activeLayer = undefined;
function undraw() {
if (configuration.activeLayer) {
configuration.activeLayer.clearLayers();
}
}
function redraw() {
undraw();
var worldName = dynmap.world && dynmap.world.name;
if (worldName) {
regionConstructors[regionType](dynmap, $.extend({}, configuration, {
component: self,
worldName: worldName,
createPopupContent: createPopupContent,
createBoxLayer: configuration.use3dregions ? create3DBoxLayer : create2DBoxLayer,
createOutlineLayer: configuration.use3dregions ? create3DOutlineLayer : create2DOutlineLayer,
getStyle: getStyle,
result: function(regionsLayer) {
if(configuration.activeLayer) { /* Not first time */
for(var i in regionsLayer._layers) {
configuration.activeLayer.addLayer(regionsLayer._layers[i]);
}
regionsLayer.clearLayers();
}
else {
configuration.activeLayer = regionsLayer;
if(!configuration.hidebydefault)
dynmap.map.addLayer(configuration.activeLayer);
//dynmap.layercontrol.addOverlay(configuration.activeLayer, regionType);
dynmap.addToLayerSelector(configuration.activeLayer, regionType, configuration.layerprio || 0);
}
}
}));
}
}
$(dynmap).bind('mapchanged', redraw);
$(dynmap).bind('mapchanging', undraw);
redraw(true);
});
} }

View File

@ -1,37 +0,0 @@
regionConstructors['Factions'] = function(dynmap, configuration) {
// Helper function.
function createOutlineFromRegion(name, region, points, outCreator) {
var xarray = [];
var zarray = [];
var i;
for(i = 0; i < points.length; i++) {
xarray[i] = points[i].x;
zarray[i] = points[i].z;
}
var ymin = 64;
var ymax = 65;
return outCreator(xarray, ymax, ymin, zarray, configuration.getStyle(name, region.nation));
}
var regionFile = 'factions_'+configuration.worldName+'.json';
$.getJSON('standalone/'+regionFile, function(data) {
var boxLayers = [];
$.each(data, function(name, region) {
var i;
for(i = 0; i < region.points.length; i++) {
var outLayer = createOutlineFromRegion(name, region, region.points[i], configuration.createOutlineLayer);
if (outLayer) {
outLayer.bindPopup(configuration.createPopupContent(name,
$.extend(region, {
owners: { players: [region.mayor] },
members: { players: [ region.residents ] }
})));
boxLayers.push(outLayer);
}
}
});
configuration.result(new L.LayerGroup(boxLayers));
});
};

View File

@ -1,36 +0,0 @@
regionConstructors['Residence'] = function(dynmap, configuration) {
// Helper function.
function createBoxFromArea(area, boxCreator) {
return boxCreator(area.X1, area.X2, area.Y1, area.Y2, area.Z1, area.Z2);
}
$.getJSON('standalone/res_' + configuration.worldName + '.json', function(data) {
var boxLayers = [];
$.each(data, function(name, residence) {
if(configuration.worldName == residence.Permissions.World) {
$.each(residence.Areas, function(aname, area) {
var boxLayer = configuration.createBoxLayer(area.X1, area.X2, area.Y1, area.Y2, area.Z1, area.Z2, configuration.getStyle(name));
boxLayer.bindPopup(configuration.createPopupContent(name, $.extend(residence, {
owners: { players: [residence.Permissions.Owner] },
flags: residence.Permissions.AreaFlags
})));
boxLayers.push(boxLayer);
});
$.each(residence.Subzones, function(szname, subzone) {
$.each(subzone.Areas, function(name2, area2) {
var subzoneLayer = configuration.createBoxLayer(area2.X1, area2.X2, area2.Y1, area2.Y2, area2.Z1, area2.Z2, configuration.getStyle(name+"."+szname, name));
subzoneLayer.bindPopup(configuration.createPopupContent(name + '.' + szname, $.extend(subzone, {
owners: { players: [subzone.Permissions.Owner] },
flags: subzone.Permissions.AreaFlags
})));
boxLayers.push(subzoneLayer);
});
});
}
});
configuration.result(new L.LayerGroup(boxLayers));
});
};

View File

@ -1,37 +0,0 @@
regionConstructors['Towny'] = function(dynmap, configuration) {
// Helper function.
function createOutlineFromRegion(name, region, points, outCreator) {
var xarray = [];
var zarray = [];
var i;
for(i = 0; i < points.length; i++) {
xarray[i] = points[i].x;
zarray[i] = points[i].z;
}
var ymin = 64;
var ymax = 65;
return outCreator(xarray, ymax, ymin, zarray, configuration.getStyle(name, region.nation));
}
var regionFile = 'towny_'+configuration.worldName+'.json';
$.getJSON('standalone/'+regionFile, function(data) {
var boxLayers = [];
$.each(data, function(name, region) {
var i;
for(i = 0; i < region.points.length; i++) {
var outLayer = createOutlineFromRegion(name, region, region.points[i], configuration.createOutlineLayer);
if (outLayer) {
outLayer.bindPopup(configuration.createPopupContent(name,
$.extend(region, {
owners: { players: [region.mayor] },
members: { players: [ region.residents ] }
})));
boxLayers.push(outLayer);
}
}
});
configuration.result(new L.LayerGroup(boxLayers));
});
};

View File

@ -1,70 +0,0 @@
regionConstructors['WorldGuard'] = function(dynmap, configuration) {
// Helper function.
function createBoxFromRegion(name, region, boxCreator) {
function ArrayMax( array ) {
return Math.max.apply( Math, array );
}
function ArrayMin( array ) {
return Math.min.apply( Math, array );
}
if(region.points) {
var i;
var xs = region.points.map(function(p) { return p.x; });
var zs = region.points.map(function(p) { return p.z; });
return boxCreator(ArrayMax(xs), ArrayMin(xs), region['max-y'], region['min-y'], ArrayMax(zs), ArrayMin(zs), configuration.getStyle(name));
}
if(!region.min || !region.max)
return null;
if(region.max.y <= region.min.y)
region.min.y = region.max.y - 1;
return boxCreator(region.max.x+1, region.min.x, region.max.y, region.min.y, region.max.z+1, region.min.z, configuration.getStyle(name));
}
function createOutlineFromRegion(name, region, outCreator) {
var xarray = [];
var zarray = [];
if(region.points) {
var i;
for(i = 0; i < region.points.length; i++) {
xarray[i] = region.points[i].x;
zarray[i] = region.points[i].z;
}
}
var ymin = 64;
var ymax = 64;
if(region['max-y'])
ymax = region['max-y'];
if(region['min-y'])
ymin = region['min-y'];
if(ymax < ymin) ymax = ymin;
return outCreator(xarray, ymax, ymin, zarray, configuration.getStyle(name));
}
var regionFile = configuration.filename.substr(0, configuration.filename.lastIndexOf('.'));
regionFile += '_'+configuration.worldName+'.json';
$.getJSON('standalone/'+regionFile, function(data) {
var boxLayers = [];
$.each(data, function(name, region) {
// Only handle cuboids for the moment (therefore skipping 'global')
if (region.type === 'cuboid') {
var boxLayer = createBoxFromRegion(name, region, configuration.createBoxLayer);
// Skip errorous regions.
if (boxLayer) {
boxLayer.bindPopup(configuration.createPopupContent(name, region));
boxLayers.push(boxLayer);
}
}
else if(region.type === 'poly2d') {
var outLayer = createOutlineFromRegion(name, region, configuration.createOutlineLayer);
if (outLayer) {
outLayer.bindPopup(configuration.createPopupContent(name, region));
boxLayers.push(outLayer);
}
}
});
configuration.result(new L.LayerGroup(boxLayers));
});
};