diff --git a/src/com/imraginbro/wurm/mapgen/FileGeneration.java b/src/com/imraginbro/wurm/mapgen/FileGeneration.java deleted file mode 100644 index 366c389..0000000 --- a/src/com/imraginbro/wurm/mapgen/FileGeneration.java +++ /dev/null @@ -1,312 +0,0 @@ -package com.imraginbro.wurm.mapgen; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.text.DecimalFormat; - -import com.wurmonline.mesh.MeshIO; - -public class FileGeneration { - - final static String newLine = System.lineSeparator(); - final static String separator = java.io.File.separator; - - static int html_nativeZoom = 0; - static int html_mapMinZoom = 0; - static int html_mapMaxZoom = 0; - static int html_actualMapSize = 0; - static int html_maxMapSize = 0; - - public static void generateFiles(MeshIO map) throws IOException, SQLException { - setHTMLvars(map); - generateDeedsFile(MapGen.saveLocation, MapGen.db_wurmZones); - generateGuardTowersFile(MapGen.saveLocation, MapGen.db_wurmItems, MapGen.db_wurmPlayers); - generateStructuresFile(MapGen.saveLocation, MapGen.db_wurmZones, MapGen.db_wurmPlayers); - generateConfigFile(MapGen.saveLocation); - } - - public static void generateStructuresFile(File saveLocation, File db_wurmZones, File db_wurmPlayers) throws IOException, SQLException { - if (!MapGen.showStructures) { - return; - } - if (!db_wurmZones.exists()) { - System.out.println("[ERROR] Could not find wurmzones.db. Skipping structures.js file generation."); - return; - } - if (!db_wurmPlayers.exists()) { - System.out.println("[ERROR] Could not find wurmplayers.db. Skipping structures.js file generation."); - return; - } - System.out.println("Writing structures.js file..."); - BufferedWriter bw = new BufferedWriter(new FileWriter(saveLocation.getAbsolutePath() + separator + "structures.js", false)); - String structBordersString = ""; - System.out.println("Loading structures from wurmzones.db..."); - Connection zonesDBcon = DriverManager.getConnection("jdbc:sqlite:"+db_wurmZones); - Connection playersDBcon = DriverManager.getConnection("jdbc:sqlite:"+db_wurmPlayers); - Statement statement = zonesDBcon.createStatement(); - ResultSet resultSet = statement.executeQuery("SELECT * FROM STRUCTURES WHERE FINISHED='1';"); - - structBordersString += ("function getStructures() {" + newLine); - structBordersString += ("\tvar structureBorders = [];" + newLine); - - int count = 0; - while (resultSet.next()) { - int minX = -1; - int maxX = -1; - int minY = -1; - int maxY = -1; - long structureID = resultSet.getLong("WURMID"); - - Statement structStatement = zonesDBcon.createStatement(); - ResultSet structRes = structStatement.executeQuery("SELECT TILEX, TILEY FROM BUILDTILES WHERE STRUCTUREID='"+structureID+"';"); - if (structRes.next()) { - minX = structRes.getInt("TILEX"); - maxX = structRes.getInt("TILEX"); - minY = structRes.getInt("TILEY"); - maxY = structRes.getInt("TILEY"); - while (structRes.next()) { - final int nX = structRes.getInt("TILEX"); - final int nY = structRes.getInt("TILEY"); - if (nX < minX) { - minX = nX; - } - if (nX > maxX) { - maxX = nX; - } - if (nY < minY) { - minY = nY; - } - if (nY > maxY) { - maxY = nY; - } - } - } - - maxX++; - maxY++; - - structStatement.close(); - - String name = resultSet.getString("NAME"); - long ownerID = resultSet.getLong("OWNERID"); - Statement nameStatement = playersDBcon.createStatement(); - ResultSet nameRes = nameStatement.executeQuery("SELECT NAME FROM PLAYERS WHERE WURMID='"+ownerID+"';"); - String pname = ""; - if (nameRes.next()) { - pname = nameRes.getString("NAME"); - } - nameStatement.close(); - structBordersString += ("\tstructureBorders.push(L.polygon(["); - structBordersString += ("xy("+minX+","+minY+"),"); - structBordersString += ("xy("+maxX+","+minY+"),"); - structBordersString += ("xy("+maxX+","+maxY+"),"); - structBordersString += ("xy("+minX+","+maxY+")]"); - structBordersString += (", {color:'blue',fillOpacity:0.1,weight:1})"); - structBordersString += (".bindPopup(\"
" + name + "
Created by " + pname + "
\"));" + newLine); - - count++; - } - System.out.println("Added "+count+" structures to structures.js..."); - structBordersString += ("\treturn structureBorders;" + newLine); - structBordersString += ("}" + newLine + newLine); - bw.append(structBordersString); - zonesDBcon.close(); - playersDBcon.close(); - bw.close(); - } - - public static void generateGuardTowersFile(File saveLocation, File db_wurmItems, File db_wurmPlayers) throws IOException, SQLException { - if (!MapGen.showGuardTowers) { - return; - } - if (!db_wurmItems.exists()) { - System.out.println("[ERROR] Could not find wurmitems.db. Skipping guardtowers.js file generation."); - return; - } - if (!db_wurmPlayers.exists()) { - System.out.println("[ERROR] Could not find wurmplayers.db. Skipping guardtowers.js file generation."); - return; - } - System.out.println("Writing guardtowers.js file..."); - BufferedWriter bw = new BufferedWriter(new FileWriter(saveLocation.getAbsolutePath() + separator + "guardtowers.js", false)); - String deedBordersString = ""; - String deedMarkersString = ""; - System.out.println("Loading guard towers from wurmitems.db..."); - Connection itemsDBcon = DriverManager.getConnection("jdbc:sqlite:"+db_wurmItems); - Connection playersDBcon = DriverManager.getConnection("jdbc:sqlite:"+db_wurmPlayers); - Statement statement = itemsDBcon.createStatement(); - ResultSet resultSet = statement.executeQuery("SELECT * FROM ITEMS WHERE (TEMPLATEID='384' OR TEMPLATEID='430' OR TEMPLATEID='528' OR TEMPLATEID='638' OR TEMPLATEID='996') AND CREATIONSTATE='0';"); - - deedBordersString += ("function getGuardTowerBorders() {" + newLine); - deedBordersString += ("\tvar guardTowerBorders = [];" + newLine); - - deedMarkersString += ("function getGuardTowers() {" + newLine); - deedMarkersString += ("\tvar guardTower = [];" + newLine); - - int count = 0; - while (resultSet.next()) { - int x = (int) Math.floor(resultSet.getInt("POSX")/4); - int y = (int) Math.floor(resultSet.getInt("POSY")/4); - float ql = resultSet.getFloat("QUALITYLEVEL"); - float dmg = resultSet.getFloat("DAMAGE"); - long ownerID = resultSet.getLong("LASTOWNERID"); - Statement nameStatement = playersDBcon.createStatement(); - ResultSet nameRes = nameStatement.executeQuery("SELECT NAME FROM PLAYERS WHERE WURMID='"+ownerID+"';"); - String pname = ""; - if (nameRes.next()) { - pname = nameRes.getString("NAME"); - } - nameStatement.close(); - deedBordersString += ("\tguardTowerBorders.push(L.polygon(["); - deedBordersString += ("xy("+(x-50)+","+(y-50)+"),"); - deedBordersString += ("xy("+(x+51)+","+(y-50)+"),"); - deedBordersString += ("xy("+(x+51)+","+(y+51)+"),"); - deedBordersString += ("xy("+(x-50)+","+(y+51)+")]"); - deedBordersString += (", {color:'red',fillOpacity:0.1,weight:1}));" + newLine); - - deedMarkersString += ("\tguardTower.push(L.marker("); - deedMarkersString += ("xy("+(x+0.5)+","+(y+0.5)+"),"); - deedMarkersString += ("{icon: guardTowerIcon})"); - DecimalFormat f = new DecimalFormat("0.00"); - deedMarkersString += (".bindPopup(\"
Guard Tower
Created by " + pname + "

QL: " + f.format(ql) + "
DMG: " + f.format(dmg) + "\"));" + newLine); - - count++; - } - System.out.println("Added "+count+" guard towers to guardtowers.js..."); - deedBordersString += ("\treturn guardTowerBorders;" + newLine); - deedBordersString += ("}" + newLine + newLine); - deedMarkersString += ("\treturn guardTower;" + newLine); - deedMarkersString += ("}"); - bw.append(deedBordersString); - bw.append(deedMarkersString); - itemsDBcon.close(); - playersDBcon.close(); - bw.close(); - } - - public static void generateDeedsFile(File saveLocation, File db_wurmZones) throws IOException, SQLException { - if (!MapGen.showDeeds) { - return; - } - if (!db_wurmZones.exists()) { - System.out.println("[ERROR] Could not find wurmzones.db. Skipping deeds.js file generation."); - return; - } - System.out.println("Writing deeds.js file..."); - BufferedWriter bw = new BufferedWriter(new FileWriter(saveLocation.getAbsolutePath() + separator + "deeds.js", false)); - String deedBordersString = ""; - String deedMarkersString = ""; - String mainDeedString = ""; - System.out.println("Loading deeds from wurmzones.db..."); - Connection connection = DriverManager.getConnection("jdbc:sqlite:"+db_wurmZones); - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery("SELECT * FROM VILLAGES WHERE DISBANDED=0;"); - - mainDeedString += ("function setViewOnMainDeed(map) {" + newLine); - - deedBordersString += ("function deedBorders() {" + newLine); - deedBordersString += ("\tvar deedBorders = [];" + newLine); - - deedMarkersString += ("function deedMarkers() {" + newLine); - deedMarkersString += ("\tvar deedMarkers = [];" + newLine); - - double mainX = 0; - double mainY = 0; - - int count = 0; - while (resultSet.next()) { - int sx = resultSet.getInt("STARTX"); - int sy = resultSet.getInt("STARTY"); - int ex = resultSet.getInt("ENDX"); - int ey = resultSet.getInt("ENDY"); - double x = (sx + ex + 1) / 2; - double y = (sy + ey + 1) / 2; - deedBordersString += ("\tdeedBorders.push(L.polygon(["); - deedBordersString += ("xy("+sx+","+sy+"),"); - deedBordersString += ("xy("+(ex+1)+","+sy+"),"); - deedBordersString += ("xy("+(ex+1)+","+(ey+1)+"),"); - deedBordersString += ("xy("+sx+","+(ey+1)+")]"); - boolean perm = resultSet.getBoolean("PERMANENT"); - if (perm) { - deedBordersString += (", {color:'orange',fillOpacity:0,weight:1})"); - if (mainX == 0 && mainY == 0) { - mainX = x; - mainY = y; - mainDeedString += ("\tmap.setView(xy("+mainX+","+mainY+"), config.mapMaxZoom-1)" + newLine); - } - } else { - deedBordersString += (", {color:'white',fillOpacity:0,weight:1})"); - } - deedBordersString += (".bindPopup(\"" + resultSet.getString("NAME") + "\"));" + newLine); - - String firstLetter = resultSet.getString("NAME").substring(0, 1).toLowerCase(); - deedMarkersString += ("\tdeedMarkers.push(L.marker("); - deedMarkersString += ("xy("+(x+0.5)+","+(y+0.5)+"),"); - if (perm) { - deedMarkersString += ("{icon: mainIcon})"); - } else { - deedMarkersString += ("{icon: letter_"+firstLetter+"Icon})"); - } - deedMarkersString += (".bindPopup(\""+resultSet.getString("NAME")+"\"));" + newLine); - count++; - } - System.out.println("Added "+count+" deeds to deeds.js..."); - deedBordersString += ("\treturn deedBorders;" + newLine); - deedBordersString += ("}" + newLine + newLine); - deedMarkersString += ("\treturn deedMarkers;" + newLine); - deedMarkersString += ("}"); - mainDeedString += ("}" + newLine + newLine); - bw.append(mainDeedString); - bw.append(deedBordersString); - bw.append(deedMarkersString); - connection.close(); - bw.close(); - } - - public static void generateConfigFile(File saveLocation) throws IOException { - System.out.println("Writing config.js file..."); - BufferedWriter bw = new BufferedWriter(new FileWriter(saveLocation.getAbsolutePath() + separator + "config.js", false)); - bw.append("function Config() {}" + newLine); - bw.append("var config = new Config();" + newLine); - bw.append("config.nativeZoom = "+html_nativeZoom+";" + newLine); - bw.append("config.mapMinZoom = "+html_mapMinZoom+";" + newLine); - bw.append("config.mapMaxZoom = "+html_mapMaxZoom+";" + newLine); - bw.append("config.actualMapSize = "+html_actualMapSize+";" + newLine); - bw.append("config.maxMapSize = "+html_maxMapSize+";" + newLine); - bw.append("" + newLine); - bw.append("var xyMulitiplier = (config.actualMapSize / 256);" + newLine); - bw.append("" + newLine); - bw.append("var yx = L.latLng;" + newLine); - bw.append("var xy = function(x, y) {" + newLine); - bw.append("\treturn yx(-(y / xyMulitiplier), (x / xyMulitiplier));" + newLine); - bw.append("};"); - bw.close(); - } - - public static void setHTMLvars(MeshIO map) { - System.out.println("Generating config.js variables..."); - html_actualMapSize = map.getSize(); - html_maxMapSize = html_actualMapSize * 8; - int count = 0; - for (int i = html_actualMapSize; i > 256; i++) { - i = (i/2); - html_nativeZoom = count; - count++; - } - count = 0; - for (int i = html_maxMapSize; i > 256; i++) { - i = (i/2); - html_mapMaxZoom = count; - count++; - } - html_mapMinZoom = 1; - } - -} diff --git a/src/com/imraginbro/wurm/mapgen/FileManagement.java b/src/com/imraginbro/wurm/mapgen/FileManagement.java deleted file mode 100644 index 7150f80..0000000 --- a/src/com/imraginbro/wurm/mapgen/FileManagement.java +++ /dev/null @@ -1,213 +0,0 @@ -package com.imraginbro.wurm.mapgen; - -import java.awt.image.BufferedImage; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.channels.FileChannel; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.Iterator; -import java.util.Properties; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -import javax.imageio.IIOImage; -import javax.imageio.ImageIO; -import javax.imageio.ImageWriteParam; -import javax.imageio.ImageWriter; -import javax.imageio.plugins.jpeg.JPEGImageWriteParam; -import javax.imageio.stream.ImageOutputStream; - -public class FileManagement { - - final static String separator = java.io.File.separator; - - public static void relocateFileVars() { - MapGen.map_topLayer = new File(MapGen.saveLocation.getAbsolutePath() + separator + "tmp" + separator + MapGen.map_topLayer.getName()); - MapGen.db_wurmZones = new File(MapGen.saveLocation.getAbsolutePath() + separator + "tmp" + separator + MapGen.db_wurmZones.getName()); - MapGen.db_wurmItems = new File(MapGen.saveLocation.getAbsolutePath() + separator + "tmp" + separator + MapGen.db_wurmItems.getName()); - MapGen.db_wurmPlayers = new File(MapGen.saveLocation.getAbsolutePath() + separator + "tmp" + separator + MapGen.db_wurmPlayers.getName()); - } - - public static void saveToFile(BufferedImage newImg, File file) throws IOException { - ImageWriter writer = null; - Iterator iter = ImageIO.getImageWritersByFormatName("png"); - if (iter.hasNext()) { - writer = (ImageWriter)iter.next(); - } - ImageOutputStream ios = ImageIO.createImageOutputStream(file); - writer.setOutput(ios); - ImageWriteParam param = new JPEGImageWriteParam(java.util.Locale.getDefault()); - param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ; - param.setCompressionQuality(1f); - writer.write(null, new IIOImage( newImg, null, null ), param); - } - - public static void copy(InputStream source , String destination) { - try { - Files.copy(source, Paths.get(destination), StandardCopyOption.REPLACE_EXISTING); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - - public static void extractRescources(String zipFileLocation, File saveLocation) throws Exception { - System.out.println("Copying "+zipFileLocation+" file from jar..."); - InputStream in = FileManagement.class.getResourceAsStream(zipFileLocation); - copy(in, saveLocation.getAbsolutePath() + separator + "tmp" + separator + "required.zip"); - in.close(); - System.out.println("Extracting resources from "+zipFileLocation+"..."); - unzip(saveLocation.getAbsolutePath() + separator + "tmp" + separator + "required.zip", saveLocation.getAbsolutePath()); - } - - public static void extractFile(ZipInputStream zipIn, String filePath) throws IOException { - if (!MapGen.replaceFiles && new File(filePath).exists()) { - return; - } - BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); - byte[] bytesIn = new byte[4096]; - int read = 0; - while ((read = zipIn.read(bytesIn)) != -1) { - bos.write(bytesIn, 0, read); - } - bos.close(); - } - - public static void unzip(String zipFilePath, String destDirectory) throws IOException { - File destDir = new File(destDirectory); - if (!destDir.exists()) { - destDir.mkdir(); - } - ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); - ZipEntry entry = zipIn.getNextEntry(); - while (entry != null) { - String filePath = destDirectory + separator + entry.getName(); - File checkDir = new File(destDirectory + separator + entry.getName()).getParentFile(); - if (!checkDir.exists()) { - checkDir.mkdir(); - } - new File(destDirectory).mkdirs(); - if (!entry.isDirectory()) { - extractFile(zipIn, filePath); - } else { - new File(filePath).mkdirs(); - } - zipIn.closeEntry(); - entry = zipIn.getNextEntry(); - } - zipIn.close(); - } - - @SuppressWarnings("resource") - public static void copyFile(File sourceFile, File destFile) throws IOException { - if(!destFile.exists()) { - destFile.createNewFile(); - } - FileChannel source = null; - FileChannel destination = null; - try { - source = new FileInputStream(sourceFile).getChannel(); - destination = new FileOutputStream(destFile).getChannel(); - destination.transferFrom(source, 0, source.size()); - } - finally { - if(source != null) { - source.close(); - } - if(destination != null) { - destination.close(); - } - } - } - - public static void makeTempCopies(File[] files, File saveLocation) throws IOException { - new File(saveLocation.getAbsolutePath() + separator + "tmp").mkdirs(); - for (int i = 0; i < files.length; i++) { - File old = files[i]; - System.out.println("Creating a temp copy of "+old.getName()+"..."); - copyFile(old, new File(saveLocation.getAbsolutePath() + separator + "tmp" + separator + old.getName())); - } - } - - public static void deleteDir(File file) { - File[] contents = file.listFiles(); - if (contents != null) { - for (File f : contents) { - deleteDir(f); - } - } - file.delete(); - } - - public static void copyPropertiesFile() { - try { - InputStream in = FileManagement.class.getResourceAsStream("/resources/WurmMapGen.properties"); - copy(in, "WurmMapGen.properties"); - in.close(); - } catch(Exception e) { - System.out.println("Error copying properties file from jar - " + e.getMessage()); - } - } - - public static boolean loadPropValues() { - System.out.println("Loading WurmMapGen.properties file!"); - Properties prop = new Properties(); - InputStream input = null; - try { - input = new FileInputStream("WurmMapGen.properties"); - } catch (Exception e) { - System.out.println("[ERROR] problem loading properties FileInputStream - " + e.getMessage()); - System.out.println("Copying properties file from jar... please configure and restart program."); - copyPropertiesFile(); - return false; - } - if (input != null) { - try { - prop.load(input); - } catch (Exception e) { - System.out.println("Error loading properties file - " + e.getMessage()); - } - } - - String maploc = prop.getProperty("wurmMapLocation", "C:/location/to/map/folder"); - String saveloc = prop.getProperty("saveLocation", "C:/location/to/save/folder"); - - System.out.println("[INFO] Map location: " + maploc); - System.out.println("[INFO] Save location: " + saveloc); - - if (maploc.equals("C:/location/to/map/folder") || saveloc.equals("C:/location/to/save/folder")) { - System.out.println("[ERROR] Looks like you are using the default map or save location. Please change in your config file."); - return false; - } - - MapGen.showDeeds = Boolean.parseBoolean(prop.getProperty("showDeeds", Boolean.toString(MapGen.showDeeds))); - MapGen.showGuardTowers = Boolean.parseBoolean(prop.getProperty("showGuardTowers", Boolean.toString(MapGen.showGuardTowers))); - MapGen.showStructures = Boolean.parseBoolean(prop.getProperty("showStructures", Boolean.toString(MapGen.showStructures))); - - MapGen.gen_map_shading = Boolean.parseBoolean(prop.getProperty("mapGenerateShading", Boolean.toString(MapGen.gen_map_shading))); - MapGen.gen_map_shade_paths = Boolean.parseBoolean(prop.getProperty("mapShadePaths", Boolean.toString(MapGen.gen_map_shade_paths))); - MapGen.gen_map_water = Boolean.parseBoolean(prop.getProperty("mapGenerateWater", Boolean.toString(MapGen.gen_map_water))); - MapGen.gen_map_bridges = Boolean.parseBoolean(prop.getProperty("mapGenerateBridges", Boolean.toString(MapGen.gen_map_bridges))); - - MapGen.wurmMapLocation = new File(maploc); - MapGen.saveLocation = new File(saveloc); - - MapGen.replaceFiles = Boolean.parseBoolean(prop.getProperty("replaceFiles", Boolean.toString(MapGen.replaceFiles))); - - - if (input != null) { - try { - input.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - return true; - } - -} diff --git a/src/com/imraginbro/wurm/mapgen/MapBuilder.java b/src/com/imraginbro/wurm/mapgen/MapBuilder.java new file mode 100644 index 0000000..0029f76 --- /dev/null +++ b/src/com/imraginbro/wurm/mapgen/MapBuilder.java @@ -0,0 +1,198 @@ +package com.imraginbro.wurm.mapgen; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.IntStream; + +import com.imraginbro.wurm.mapgen.filegen.DBHandler; +import com.imraginbro.wurm.mapgen.filegen.FileGeneration; +import com.imraginbro.wurm.mapgen.filegen.FileManagement; +import com.imraginbro.wurm.mapgen.filegen.PropertiesManager; +import com.wurmonline.mesh.MeshIO; +import com.wurmonline.mesh.Tiles; +import com.wurmonline.mesh.Tiles.Tile; + +public class MapBuilder { + + private final String separator = File.separator; + private int threadCounter = 0; + private int bridgeTileCount = 0; + + public final static FileManagement fileManager = new FileManagement(); + public final static PropertiesManager propertiesManager = new PropertiesManager(); + public final static FileGeneration fileGenerator = new FileGeneration(); + public final static DBHandler dbhandler = new DBHandler(); + + public static MeshIO map; + + public MapBuilder() throws Exception { + if (!propertiesManager.load()) { + return; + } + fileManager.load(); + fileManager.makeTempCopies(); + fileManager.relocateFileVars(); + map = MeshIO.open(fileManager.map_topLayer.getAbsolutePath()); + dbhandler.load(); + System.out.println("Starting map generation..."); + start(); + fileManager.extractRescources("/resources/required.zip"); + fileGenerator.generateFiles(); + dbhandler.closeConnections(); + map.close(); + System.out.println("Removing temporary files..."); + fileManager.deleteDir(new File(propertiesManager.saveLocation.getAbsolutePath() + separator + "tmp")); + } + + private void start() { + final int tileCount = (getMapSize() / 256); + final int totalProcesses = (tileCount * tileCount); + ExecutorService executor = Executors.newFixedThreadPool(propertiesManager.threadLimit); + for (int x = 0; x < tileCount; x++) { + for (int y = 0; y < tileCount; y++) { + threadCounter++; + Runnable mtt = new MapTileThreader(x, y); + executor.execute(mtt); + } + } + executor.shutdown(); + Object obj = new Object(); + while (!executor.isTerminated()) { + int percent = (int)((float)(totalProcesses - threadCounter) / (float)(totalProcesses) * 100.0f); + System.out.print("Completion percent: " + percent + "%\r"); + try { + synchronized (obj) { + obj.wait(100); + } + } catch (InterruptedException ex) { } + } + System.out.println("Completion percent: 100%"); + System.out.println("Map generation complete!"); + System.out.println("Found " + bridgeTileCount + " bridge tiles to draw!"); + } + + private class MapTileThreader implements Runnable { + + private final int x; + private final int y; + + private MapTileThreader(int x, int y) { + this.x = x; + this.y = y; + } + + @Override + public void run() { + generateImageTile(x, y); + threadCounter--; + } + + } + + private int getMapSize() { + return map.getSize(); + } + + private void generateImageTile(final int imageTileX, final int imageTileY) { + final BufferedImage imageTile = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB); + Graphics2D imageTileGraphics = imageTile.createGraphics(); + for (int x = 0; x < 256; x++) { + for (int y = 0; y < 256; y++) { + final int tileX = (imageTileX * 256) + x; + final int tileY = (imageTileY * 256) + y; + int tileEncoded = map.getTile(tileX, tileY); + byte tileType = Tiles.decodeType(tileEncoded); + short tileHeight = Tiles.decodeHeight(tileEncoded); + Tile thisTile = Tiles.getTile(tileType); + Color tileColor = thisTile.getColor(); + imageTileGraphics.setColor(tileColor); + imageTileGraphics.fillRect(x, y, 1, 1); + if (propertiesManager.gen_map_shading) { + boolean checkPath = false; + if (!propertiesManager.gen_map_shade_paths) { + final int[] path_tile_types = { + Tiles.TILE_TYPE_COBBLESTONE, Tiles.TILE_TYPE_COBBLESTONE_ROUND, + Tiles.TILE_TYPE_MARBLE_BRICKS, Tiles.TILE_TYPE_MARBLE_SLABS, + Tiles.TILE_TYPE_SANDSTONE_BRICKS, Tiles.TILE_TYPE_SANDSTONE_SLABS, + Tiles.TILE_TYPE_SLATE_BRICKS, Tiles.TILE_TYPE_SLATE_SLABS, + Tiles.TILE_TYPE_STONE_SLABS}; + checkPath = IntStream.of(path_tile_types).anyMatch(n -> n == tileType); + } + if (!checkPath) { + if (tileX < (getMapSize()-1) && tileY < (getMapSize()-1)) { + int lastTileEncoded = map.getTile(tileX + 1, tileY + 1); + short nextTileHeight = Tiles.decodeHeight(lastTileEncoded); + int calc = tileHeight - nextTileHeight; + if (calc > 0) { + int alpha = (int) Math.round(Math.pow(calc, 0.95)); + if (alpha > 255) { + alpha = 255; + } + imageTileGraphics.setColor(new Color(0,0,0,alpha)); + imageTileGraphics.fillRect(x, y, 1, 1); + } else { + calc = -calc; + int alpha = (int) Math.round(Math.pow(calc, 0.8)); + if (alpha > 255) { + alpha = 255; + } + imageTileGraphics.setColor(new Color(255,255,255,alpha)); + imageTileGraphics.fillRect(x, y, 1, 1); + } + } + } + } + if (propertiesManager.gen_map_water && tileHeight < 0) { + imageTileGraphics.setColor(new Color(20,80,180,210)); + imageTileGraphics.fillRect(x, y, 1, 1); + } + } + } + try { + drawBridges(imageTile, imageTileX, imageTileY); + } catch (SQLException e) { + e.printStackTrace(); + } + new File(propertiesManager.saveLocation.getAbsolutePath() + separator + "images").mkdirs(); + try { + fileManager.saveToFile(imageTile, new File(propertiesManager.saveLocation.getAbsolutePath() + separator + "images" + separator + imageTileX + "-" + imageTileY + ".png")); + } catch (IOException e) { + e.printStackTrace(); + } + imageTileGraphics.dispose(); + imageTile.flush(); + } + + private void drawBridges(BufferedImage imageTile, int imageTileX, int imageTileY) throws SQLException { + if (propertiesManager.gen_map_bridges) { + final int minX = (imageTileX * 256); + final int minY = (imageTileY * 256); + final int maxX = minX + 256; + final int maxY = minY + 256; + Graphics2D imageTileGraphics = imageTile.createGraphics(); + Tile thisTile = Tiles.getTile(9); + Color tileColor = thisTile.getColor(); + imageTileGraphics.setColor(tileColor); + Statement statement = dbhandler.getZonesConnection().createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT TILEX, TILEY FROM BRIDGEPARTS WHERE TILEX >= "+minX+" AND TILEY >= "+minY+" AND TILEX < "+maxX+" AND TILEY < "+maxY+";"); + while (resultSet.next()) { + int tileX = resultSet.getInt("TILEX"); + int tileY = resultSet.getInt("TILEY"); + imageTileGraphics.fillRect((tileX - minX), (tileY - minY), 1, 1); + bridgeTileCount++; + } + resultSet.close(); + statement.close(); + imageTileGraphics.dispose(); + } + } + +} diff --git a/src/com/imraginbro/wurm/mapgen/MapGen.java b/src/com/imraginbro/wurm/mapgen/MapGen.java index f2feb48..99d1cde 100644 --- a/src/com/imraginbro/wurm/mapgen/MapGen.java +++ b/src/com/imraginbro/wurm/mapgen/MapGen.java @@ -1,311 +1,15 @@ package com.imraginbro.wurm.mapgen; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.awt.image.ImagingOpException; -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.stream.IntStream; - -import com.wurmonline.mesh.MeshIO; -import com.wurmonline.mesh.Tiles; -import com.wurmonline.mesh.Tiles.Tile; - public class MapGen { - public final static String newLine = System.lineSeparator(); - public final static String separator = java.io.File.separator; - - public static int threadCounter = 0; - - public static File map_topLayer = null; - public static File db_wurmZones = null; - public static File db_wurmItems = null; - public static File db_wurmPlayers = null; - - public static File[] fileBackupArray = new File[4]; - - //vars for map gen - public static boolean gen_map_shading = true; - public static boolean gen_map_shade_paths = true; - public static boolean gen_map_water = true; - public static boolean gen_map_bridges = true; - - //marker generation - public static boolean showDeeds = true; - public static boolean showGuardTowers = true; - public static boolean showStructures = true; - - //config settings - public static boolean replaceFiles = true; - public static File wurmMapLocation = null; - public static File saveLocation = null; - public static void main(String[] args) throws Exception { - - if (!FileManagement.loadPropValues()) { - return; - } - - if (wurmMapLocation == null || saveLocation == null) { - System.out.println("[ERROR] Wurm map location or save location was not set."); - return; - } - - map_topLayer = new File(wurmMapLocation.getAbsolutePath() + separator + "top_layer.map"); - db_wurmZones = new File(wurmMapLocation.getAbsolutePath() + separator + "sqlite" + separator + "wurmzones.db"); - db_wurmItems = new File(wurmMapLocation.getAbsolutePath() + separator + "sqlite" + separator + "wurmitems.db"); - db_wurmPlayers = new File(wurmMapLocation.getAbsolutePath() + separator + "sqlite" + separator + "wurmplayers.db"); - - if (!map_topLayer.exists()) { - System.out.println("[ERROR] Could not find top_layer.map! Stopping program."); - return; - } - - fileBackupArray[0] = map_topLayer; - fileBackupArray[1] = db_wurmZones; - fileBackupArray[2] = db_wurmItems; - fileBackupArray[3] = db_wurmPlayers; - final long startTime = System.currentTimeMillis(); - - FileManagement.makeTempCopies(fileBackupArray, saveLocation); - FileManagement.relocateFileVars(); - - System.out.println("Loading top_layer.map file..."); - MeshIO map = MeshIO.open(map_topLayer.getAbsolutePath()); - - genImages(map); - map.close(); - - FileManagement.extractRescources("/resources/required.zip", saveLocation); - FileGeneration.generateFiles(map); - - System.out.println("Removing temporary files..."); - FileManagement.deleteDir(new File(saveLocation.getAbsolutePath() + separator + "tmp")); - + new MapBuilder(); final long endTime = System.currentTimeMillis(); final long totalTime = (endTime - startTime)/1000; System.out.println("Finished with map generation! " + totalTime + " seconds."); } - public static void genImages(MeshIO map) throws IllegalArgumentException, ImagingOpException, IOException, SQLException, InterruptedException { - System.out.println("Generating image for map"); - BufferedImage original = genMap(map, 1); - genTileMap(original); - original.flush(); - } - - public static BufferedImage genMap(MeshIO map, int PIXEL_SIZE) throws SQLException, InterruptedException { - - int MAP_SIZE = map.getSize(); - int IMAGE_SIZE = PIXEL_SIZE * MAP_SIZE; - - BufferedImage mapImage = new BufferedImage(IMAGE_SIZE, IMAGE_SIZE, BufferedImage.TYPE_INT_ARGB); - - ExecutorService executor = Executors.newFixedThreadPool(5); - System.out.println("Starting multi-thread image generation"); - - for (int y = 0; y < MAP_SIZE; y++) { - threadCounter++; - Runnable mt = new MapThreader(y, PIXEL_SIZE, map, mapImage); - executor.execute(mt); - } - - executor.shutdown(); - - Object obj = new Object(); - - while (!executor.isTerminated()) { - int percent = (int)((float)(MAP_SIZE - threadCounter) / (float)MAP_SIZE * 100.0f); - System.out.print("Completion percent: " + percent + "%\r"); - try { - synchronized (obj) { - obj.wait(1000); - } - } catch (InterruptedException ex) { - } - } - threadCounter = 0; - System.out.println(""); - System.out.println("Image generation complete"); - drawBridges(mapImage, PIXEL_SIZE); - return mapImage; - } - - public static class MapThreader implements Runnable { - - private final int y; - private final int PIXEL_SIZE; - private final MeshIO map; - private final BufferedImage mapImage; - - MapThreader(int y, int PIXEL_SIZE, MeshIO map, BufferedImage mapImage) { - this.y = y; - this.PIXEL_SIZE = PIXEL_SIZE; - this.map = map; - this.mapImage = mapImage; - } - - @Override - public void run() { - genMapThread(y, PIXEL_SIZE, map, mapImage); - } - } - - public static void genMapThread(int y, int PIXEL_SIZE, MeshIO map, BufferedImage mapImage) { - Graphics2D g_mapImage = mapImage.createGraphics(); - for (int x = 0; x < map.getSize(); x++) { - int newX = x * PIXEL_SIZE; - int newY = y * PIXEL_SIZE; - int tileEncoded = map.getTile(x, y); - byte tileType = Tiles.decodeType(tileEncoded); - short tileHeight = Tiles.decodeHeight(tileEncoded); - Tile thisTile = Tiles.getTile(tileType); - Color tileColor = thisTile.getColor(); - g_mapImage.setColor(tileColor); - g_mapImage.fillRect(newX, newY, PIXEL_SIZE, PIXEL_SIZE); - if (gen_map_shading) { - boolean checkPath = false; - if (!gen_map_shade_paths) { - final int[] path_tile_types = { - Tiles.TILE_TYPE_COBBLESTONE, Tiles.TILE_TYPE_COBBLESTONE_ROUND, - Tiles.TILE_TYPE_MARBLE_BRICKS, Tiles.TILE_TYPE_MARBLE_SLABS, - Tiles.TILE_TYPE_SANDSTONE_BRICKS, Tiles.TILE_TYPE_SANDSTONE_SLABS, - Tiles.TILE_TYPE_SLATE_BRICKS, Tiles.TILE_TYPE_SLATE_SLABS, - Tiles.TILE_TYPE_STONE_SLABS}; - checkPath = IntStream.of(path_tile_types).anyMatch(n -> n == tileType); - } - if (!checkPath) { - if (x < (map.getSize()-1) && y < (map.getSize()-1)) { - int lastTileEncoded = map.getTile(x + 1, y + 1); - short nextTileHeight = Tiles.decodeHeight(lastTileEncoded); - int calc = tileHeight - nextTileHeight; - if (calc > 0) { - int alpha = (int) Math.round(Math.pow(calc, 0.95)); - if (alpha > 255) { - alpha = 255; - } - g_mapImage.setColor(new Color(0,0,0,alpha)); - g_mapImage.fillRect(newX, newY, PIXEL_SIZE, PIXEL_SIZE); - } else { - calc = -calc; - int alpha = (int) Math.round(Math.pow(calc, 0.8)); - if (alpha > 255) { - alpha = 255; - } - g_mapImage.setColor(new Color(255,255,255,alpha)); - g_mapImage.fillRect(newX, newY, PIXEL_SIZE, PIXEL_SIZE); - } - } - } - } - if (gen_map_water && tileHeight < 0) { - g_mapImage.setColor(new Color(20,80,180,210)); - g_mapImage.fillRect(newX, newY, PIXEL_SIZE, PIXEL_SIZE); - } - } - g_mapImage.dispose(); - threadCounter--; - } - - public static void drawBridges(BufferedImage mapImage, int PIXEL_SIZE) throws SQLException { - if (gen_map_bridges) { - if (!db_wurmZones.exists()) { - System.out.println("[ERROR] Could not find zones.db. Skipping bridge generation."); - return; - } - Graphics2D g_mapImage = mapImage.createGraphics(); - System.out.println("Loading bridges from wurmzones.db..."); - Tile thisTile = Tiles.getTile(9); - Color tileColor = thisTile.getColor(); - g_mapImage.setColor(tileColor); - Connection connection = DriverManager.getConnection("jdbc:sqlite:"+db_wurmZones); - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery("SELECT * FROM BRIDGEPARTS;"); - int count = 0; - System.out.println("Drawing bridges..."); - while (resultSet.next()) { - int tileX = resultSet.getInt("TILEX") * PIXEL_SIZE; - int tileY = resultSet.getInt("TILEY") * PIXEL_SIZE; - g_mapImage.fillRect(tileX, tileY, PIXEL_SIZE, PIXEL_SIZE); - count++; - } - g_mapImage.dispose(); - connection.close(); - System.out.println("Finished drawing " + count + " bridge tiles"); - } - } - - public static void genTileMap(BufferedImage img) throws IOException { - System.out.println("Creating tile map from image..."); - int subImg = img.getWidth() / 256; - ExecutorService executor = Executors.newFixedThreadPool(2); - for (int x = 0; x < subImg; x++) { - for (int y = 0; y < subImg; y++) { - /*new File(saveLocation.getAbsolutePath() + separator + "images").mkdirs(); - BufferedImage newImg = img.getSubimage(x * 256, y * 256, 256, 256); - FileManagement.saveToFile(newImg, new File(saveLocation.getAbsolutePath() + separator + "images" + separator + x + "-" + y + ".png")); - newImg.flush();*/ - threadCounter++; - Runnable mt = new MapTileThreader(x, y, img); - executor.execute(mt); - } - } - - executor.shutdown(); - Object obj = new Object(); - - while (!executor.isTerminated()) { - int percent = (int)((float)((subImg*subImg) - threadCounter) / (float)(subImg*subImg) * 100.0f); - System.out.print("Completion percent: " + percent + "%\r"); - try { - synchronized (obj) { - obj.wait(1000); - } - } catch (InterruptedException ex) { - } - } - - System.out.println(""); - img.flush(); - threadCounter = 0; - } - - public static class MapTileThreader implements Runnable { - - private final int x; - private final int y; - private final BufferedImage img; - - MapTileThreader(int x, int y, BufferedImage img) { - this.x = x; - this.y = y; - this.img = img; - } - - @Override - public void run() { - new File(saveLocation.getAbsolutePath() + separator + "images").mkdirs(); - BufferedImage newImg = img.getSubimage(x * 256, y * 256, 256, 256); - try { - FileManagement.saveToFile(newImg, new File(saveLocation.getAbsolutePath() + separator + "images" + separator + x + "-" + y + ".png")); - } catch (IOException e) { - e.printStackTrace(); - } - newImg.flush(); - threadCounter--; - } - } - } diff --git a/src/com/imraginbro/wurm/mapgen/filegen/DBHandler.java b/src/com/imraginbro/wurm/mapgen/filegen/DBHandler.java new file mode 100644 index 0000000..068dcae --- /dev/null +++ b/src/com/imraginbro/wurm/mapgen/filegen/DBHandler.java @@ -0,0 +1,103 @@ +package com.imraginbro.wurm.mapgen.filegen; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +import com.imraginbro.wurm.mapgen.MapBuilder; + +public class DBHandler { + + private Connection wurmZonesConnection = null; + private Connection wurmItemsConnection = null; + private Connection wurmPlayersConnection = null; + + public void load() { + this.openConnections(); + } + + public Connection getZonesConnection() { + return this.wurmZonesConnection; + } + + public Connection getItemsConnection() { + return this.wurmItemsConnection; + } + + public Connection getPlayersConnection() { + return this.wurmPlayersConnection; + } + + public boolean checkZonesConnection() { + if (this.wurmZonesConnection != null) { + return true; + } + return false; + } + + public boolean checkItemsConnection() { + if (this.wurmItemsConnection != null) { + return true; + } + return false; + } + + public boolean checkPlayersConnection() { + if (this.wurmPlayersConnection != null) { + return true; + } + return false; + } + + public void openConnections() { + try { + if (MapBuilder.fileManager.db_wurmZones.exists() && !this.checkZonesConnection()) { + this.wurmZonesConnection = DriverManager.getConnection("jdbc:sqlite:" + MapBuilder.fileManager.db_wurmZones); + } + } catch (SQLException e) { + System.out.println("[ERROR] connecting wurmzones.db - " + e.getMessage()); + } + try { + if (MapBuilder.fileManager.db_wurmItems.exists() && !this.checkItemsConnection()) { + this.wurmItemsConnection = DriverManager.getConnection("jdbc:sqlite:" + MapBuilder.fileManager.db_wurmItems); + } + } catch (SQLException e) { + System.out.println("[ERROR] connecting wurmitems.db - " + e.getMessage()); + } + try { + if (MapBuilder.fileManager.db_wurmPlayers.exists() && !this.checkPlayersConnection()) { + this.wurmPlayersConnection = DriverManager.getConnection("jdbc:sqlite:" + MapBuilder.fileManager.db_wurmPlayers); + } + } catch (SQLException e) { + System.out.println("[ERROR] connecting wurmplayers.db - " + e.getMessage()); + } + } + + public void closeConnections() { + if (this.wurmZonesConnection != null) { + try { + this.wurmZonesConnection.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + this.wurmZonesConnection = null; + } + if (this.wurmItemsConnection != null) { + try { + this.wurmItemsConnection.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + this.wurmItemsConnection = null; + } + if (this.wurmPlayersConnection != null) { + try { + this.wurmPlayersConnection.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + this.wurmPlayersConnection = null; + } + } + +} diff --git a/src/com/imraginbro/wurm/mapgen/filegen/FileGeneration.java b/src/com/imraginbro/wurm/mapgen/filegen/FileGeneration.java new file mode 100644 index 0000000..28a7897 --- /dev/null +++ b/src/com/imraginbro/wurm/mapgen/filegen/FileGeneration.java @@ -0,0 +1,251 @@ +package com.imraginbro.wurm.mapgen.filegen; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.DecimalFormat; + +import com.imraginbro.wurm.mapgen.MapBuilder; +import com.wurmonline.mesh.MeshIO; + +public class FileGeneration { + + final static String newLine = System.lineSeparator(); + final static String separator = java.io.File.separator; + + private int html_nativeZoom = 0; + private int html_mapMinZoom = 0; + private int html_mapMaxZoom = 0; + private int html_actualMapSize = 0; + private int html_maxMapSize = 0; + + public void generateFiles() throws IOException, SQLException { + setHTMLvars(MapBuilder.map); + generateDeedsFile(); + generateGuardTowersFile(); + generateStructuresFile(); + generateConfigFile(); + } + + public void generateStructuresFile() throws IOException, SQLException { + if (!MapBuilder.propertiesManager.showStructures || !MapBuilder.dbhandler.checkZonesConnection() || !MapBuilder.dbhandler.checkPlayersConnection()) { + System.out.println("Skipping structures.js generation."); + return; + } + + System.out.println("Writing structures.js file..."); + BufferedWriter bw = new BufferedWriter(new FileWriter(MapBuilder.propertiesManager.saveLocation.getAbsolutePath() + separator + "includes" + separator + "structures.js", false)); + + System.out.println("Loading structures from wurmzones.db..."); + + Statement statement = MapBuilder.dbhandler.getZonesConnection().createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT WURMID FROM STRUCTURES WHERE FINISHED='1';"); + + bw.append("function getStructures() {" + newLine); + bw.append("\tvar structureBorders = [];" + newLine); + int count = 0; + while (resultSet.next()) { + long structureID = resultSet.getLong("WURMID"); + Structure structure = new Structure(MapBuilder.dbhandler, structureID); + bw.append("\tstructureBorders.push(L.polygon([" + + "xy("+structure.getMinX()+","+structure.getMinY()+")," + + "xy("+structure.getMaxX()+","+structure.getMinY()+")," + + "xy("+structure.getMaxX()+","+structure.getMaxY()+")," + + "xy("+structure.getMinX()+","+structure.getMaxY()+")]" + + ", {color:'blue',fillOpacity:0.1,weight:1})" + + ".bindPopup(\"
" + structure.getStructureName() + "
" + + "Created by " + structure.getOwnerName() + "
\"));" + newLine); + count++; + } + System.out.println("Added " + count + " structures to structures.js..."); + bw.append("\treturn structureBorders;" + newLine); + bw.append("}"); + bw.close(); + } + + public void generateGuardTowersFile() throws IOException, SQLException { + if (!MapBuilder.propertiesManager.showGuardTowers || !MapBuilder.dbhandler.checkItemsConnection() || !MapBuilder.dbhandler.checkPlayersConnection()) { + System.out.println("Skipping guardtowers.js generation."); + return; + } + + System.out.println("Writing guardtowers.js file..."); + BufferedWriter bw = new BufferedWriter(new FileWriter(MapBuilder.propertiesManager.saveLocation.getAbsolutePath() + separator + "includes" + separator + "guardtowers.js", false)); + StringBuilder deedBordersString = new StringBuilder(); + StringBuilder deedMarkersString = new StringBuilder(); + System.out.println("Loading guard towers from wurmitems.db..."); + Statement statement = MapBuilder.dbhandler.getItemsConnection().createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT * FROM ITEMS WHERE (TEMPLATEID='384' OR TEMPLATEID='430' OR TEMPLATEID='528' OR TEMPLATEID='638' OR TEMPLATEID='996') AND CREATIONSTATE='0';"); + + deedBordersString.append("function getGuardTowerBorders() {" + newLine); + deedBordersString.append("\tvar guardTowerBorders = [];" + newLine); + + deedMarkersString.append("function getGuardTowers() {" + newLine); + deedMarkersString.append("\tvar guardTower = [];" + newLine); + + int count = 0; + while (resultSet.next()) { + + + int x = (int) Math.floor(resultSet.getInt("POSX")/4); + int y = (int) Math.floor(resultSet.getInt("POSY")/4); + float ql = resultSet.getFloat("QUALITYLEVEL"); + float dmg = resultSet.getFloat("DAMAGE"); + long ownerID = resultSet.getLong("LASTOWNERID"); + Statement nameStatement = MapBuilder.dbhandler.getPlayersConnection().createStatement(); + ResultSet nameRes = nameStatement.executeQuery("SELECT NAME FROM PLAYERS WHERE WURMID='" + ownerID + "';"); + String pname = ""; + if (nameRes.next()) { + pname = nameRes.getString("NAME"); + } + nameStatement.close(); + + + deedBordersString.append("\tguardTowerBorders.push(L.polygon(["); + deedBordersString.append("xy("+(x-50)+","+(y-50)+"),"); + deedBordersString.append("xy("+(x+51)+","+(y-50)+"),"); + deedBordersString.append("xy("+(x+51)+","+(y+51)+"),"); + deedBordersString.append("xy("+(x-50)+","+(y+51)+")]"); + deedBordersString.append(", {color:'red',fillOpacity:0.1,weight:1}));" + newLine); + + deedMarkersString.append("\tguardTower.push(L.marker("); + deedMarkersString.append("xy("+(x+0.5)+","+(y+0.5)+"),"); + deedMarkersString.append("{icon: guardTowerIcon})"); + DecimalFormat f = new DecimalFormat("0.00"); + deedMarkersString.append(".bindPopup(\"
Guard Tower
Created by " + pname + "

QL: " + f.format(ql) + "
DMG: " + f.format(dmg) + "\"));" + newLine); + + count++; + } + System.out.println("Added " + count + " guard towers to guardtowers.js..."); + + deedBordersString.append("\treturn guardTowerBorders;" + newLine); + deedBordersString.append("}" + newLine + newLine); + + deedMarkersString.append("\treturn guardTower;" + newLine); + deedMarkersString.append("}"); + + bw.append(deedBordersString); + bw.append(deedMarkersString); + + bw.close(); + } + + public void generateDeedsFile() throws IOException, SQLException { + if (!MapBuilder.propertiesManager.showDeeds || !MapBuilder.dbhandler.checkZonesConnection()) { + System.out.println("Skipping deeds.js generation."); + return; + } + System.out.println("Writing deeds.js file..."); + BufferedWriter bw = new BufferedWriter(new FileWriter(MapBuilder.propertiesManager.saveLocation.getAbsolutePath() + separator + "includes" + separator + "deeds.js", false)); + String deedBordersString = ""; + String deedMarkersString = ""; + String mainDeedString = ""; + System.out.println("Loading deeds from wurmzones.db..."); + + Statement statement = MapBuilder.dbhandler.getZonesConnection().createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT * FROM VILLAGES WHERE DISBANDED=0;"); + + mainDeedString += ("function setViewOnMainDeed(map) {" + newLine); + + deedBordersString += ("function deedBorders() {" + newLine); + deedBordersString += ("\tvar deedBorders = [];" + newLine); + + deedMarkersString += ("function deedMarkers() {" + newLine); + deedMarkersString += ("\tvar deedMarkers = [];" + newLine); + + double mainX = 0; + double mainY = 0; + + int count = 0; + while (resultSet.next()) { + int sx = resultSet.getInt("STARTX"); + int sy = resultSet.getInt("STARTY"); + int ex = resultSet.getInt("ENDX"); + int ey = resultSet.getInt("ENDY"); + double x = (sx + ex + 1) / 2; + double y = (sy + ey + 1) / 2; + deedBordersString += ("\tdeedBorders.push(L.polygon(["); + deedBordersString += ("xy("+sx+","+sy+"),"); + deedBordersString += ("xy("+(ex+1)+","+sy+"),"); + deedBordersString += ("xy("+(ex+1)+","+(ey+1)+"),"); + deedBordersString += ("xy("+sx+","+(ey+1)+")]"); + boolean perm = resultSet.getBoolean("PERMANENT"); + if (perm) { + deedBordersString += (", {color:'orange',fillOpacity:0,weight:1})"); + if (mainX == 0 && mainY == 0) { + mainX = x; + mainY = y; + mainDeedString += ("\tmap.setView(xy("+mainX+","+mainY+"), config.mapMaxZoom-1)" + newLine); + } + } else { + deedBordersString += (", {color:'white',fillOpacity:0,weight:1})"); + } + deedBordersString += (".bindPopup(\"" + resultSet.getString("NAME") + "\"));" + newLine); + + String firstLetter = resultSet.getString("NAME").substring(0, 1).toLowerCase(); + deedMarkersString += ("\tdeedMarkers.push(L.marker("); + deedMarkersString += ("xy("+(x+0.5)+","+(y+0.5)+"),"); + if (perm) { + deedMarkersString += ("{icon: mainIcon})"); + } else { + deedMarkersString += ("{icon: letter_"+firstLetter+"Icon})"); + } + deedMarkersString += (".bindPopup(\""+resultSet.getString("NAME")+"\"));" + newLine); + count++; + } + System.out.println("Added "+count+" deeds to deeds.js..."); + deedBordersString += ("\treturn deedBorders;" + newLine); + deedBordersString += ("}" + newLine + newLine); + deedMarkersString += ("\treturn deedMarkers;" + newLine); + deedMarkersString += ("}"); + mainDeedString += ("}" + newLine + newLine); + bw.append(mainDeedString); + bw.append(deedBordersString); + bw.append(deedMarkersString); + + bw.close(); + } + + public void generateConfigFile() throws IOException { + System.out.println("Writing config.js file..."); + BufferedWriter bw = new BufferedWriter(new FileWriter(MapBuilder.propertiesManager.saveLocation.getAbsolutePath() + separator + "includes" + separator + "config.js", false)); + bw.append("function Config() {}" + newLine); + bw.append("var config = new Config();" + newLine); + bw.append("config.nativeZoom = "+html_nativeZoom+";" + newLine); + bw.append("config.mapMinZoom = "+html_mapMinZoom+";" + newLine); + bw.append("config.mapMaxZoom = "+html_mapMaxZoom+";" + newLine); + bw.append("config.actualMapSize = "+html_actualMapSize+";" + newLine); + bw.append("config.maxMapSize = "+html_maxMapSize+";" + newLine); + bw.append("" + newLine); + bw.append("var xyMulitiplier = (config.actualMapSize / 256);" + newLine); + bw.append("" + newLine); + bw.append("var yx = L.latLng;" + newLine); + bw.append("var xy = function(x, y) {" + newLine); + bw.append("\treturn yx(-(y / xyMulitiplier), (x / xyMulitiplier));" + newLine); + bw.append("};"); + bw.close(); + } + + public void setHTMLvars(MeshIO map) { + System.out.println("Generating config.js variables..."); + html_actualMapSize = map.getSize(); + html_maxMapSize = html_actualMapSize * 8; + int count = 0; + for (int i = html_actualMapSize; i > 256; i++) { + i = (i/2); + html_nativeZoom = count; + count++; + } + count = 0; + for (int i = html_maxMapSize; i > 256; i++) { + i = (i/2); + html_mapMaxZoom = count; + count++; + } + html_mapMinZoom = 1; + } + +} diff --git a/src/com/imraginbro/wurm/mapgen/filegen/FileManagement.java b/src/com/imraginbro/wurm/mapgen/filegen/FileManagement.java new file mode 100644 index 0000000..2c34413 --- /dev/null +++ b/src/com/imraginbro/wurm/mapgen/filegen/FileManagement.java @@ -0,0 +1,168 @@ +package com.imraginbro.wurm.mapgen.filegen; + +import java.awt.image.BufferedImage; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.Iterator; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.plugins.jpeg.JPEGImageWriteParam; +import javax.imageio.stream.ImageOutputStream; + +import com.imraginbro.wurm.mapgen.MapBuilder; + +public class FileManagement { + + final static String separator = java.io.File.separator; + + public File map_topLayer = null; + public File db_wurmZones = null; + public File db_wurmItems = null; + public File db_wurmPlayers = null; + + File[] fileBackupArray = null; + + public void load() { + map_topLayer = new File(MapBuilder.propertiesManager.wurmMapLocation.getAbsolutePath() + separator + "top_layer.map"); + db_wurmZones = new File(MapBuilder.propertiesManager.wurmMapLocation.getAbsolutePath() + separator + "sqlite" + separator + "wurmzones.db"); + db_wurmItems = new File(MapBuilder.propertiesManager.wurmMapLocation.getAbsolutePath() + separator + "sqlite" + separator + "wurmitems.db"); + db_wurmPlayers = new File(MapBuilder.propertiesManager.wurmMapLocation.getAbsolutePath() + separator + "sqlite" + separator + "wurmplayers.db"); + fileBackupArray = new File[]{map_topLayer, db_wurmZones, db_wurmItems, db_wurmPlayers}; + } + + public void relocateFileVars() { + map_topLayer = new File(MapBuilder.propertiesManager.saveLocation.getAbsolutePath() + separator + "tmp" + separator + map_topLayer.getName()); + db_wurmZones = new File(MapBuilder.propertiesManager.saveLocation.getAbsolutePath() + separator + "tmp" + separator + db_wurmZones.getName()); + db_wurmItems = new File(MapBuilder.propertiesManager.saveLocation.getAbsolutePath() + separator + "tmp" + separator + db_wurmItems.getName()); + db_wurmPlayers = new File(MapBuilder.propertiesManager.saveLocation.getAbsolutePath() + separator + "tmp" + separator + db_wurmPlayers.getName()); + } + + public void saveToFile(BufferedImage newImg, File file) throws IOException { + ImageWriter writer = null; + Iterator iter = ImageIO.getImageWritersByFormatName("png"); + if (iter.hasNext()) { + writer = (ImageWriter)iter.next(); + } + ImageOutputStream ios = ImageIO.createImageOutputStream(file); + writer.setOutput(ios); + ImageWriteParam param = new JPEGImageWriteParam(java.util.Locale.getDefault()); + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ; + param.setCompressionQuality(1f); + writer.write(null, new IIOImage( newImg, null, null ), param); + } + + public void copy(InputStream source , String destination) { + try { + Files.copy(source, Paths.get(destination), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + public void extractRescources(String zipFileLocation) throws Exception { + System.out.println("Copying "+zipFileLocation+" file from jar..."); + InputStream in = FileManagement.class.getResourceAsStream(zipFileLocation); + copy(in, MapBuilder.propertiesManager.saveLocation.getAbsolutePath() + separator + "tmp" + separator + "required.zip"); + in.close(); + System.out.println("Extracting resources from "+zipFileLocation+"..."); + unzip(MapBuilder.propertiesManager.saveLocation.getAbsolutePath() + separator + "tmp" + separator + "required.zip", MapBuilder.propertiesManager.saveLocation.getAbsolutePath()); + } + + public void extractFile(ZipInputStream zipIn, String filePath) throws IOException { + if (!MapBuilder.propertiesManager.replaceFiles && new File(filePath).exists()) { + return; + } + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); + byte[] bytesIn = new byte[4096]; + int read = 0; + while ((read = zipIn.read(bytesIn)) != -1) { + bos.write(bytesIn, 0, read); + } + bos.close(); + } + + public void unzip(String zipFilePath, String destDirectory) throws IOException { + File destDir = new File(destDirectory); + if (!destDir.exists()) { + destDir.mkdir(); + } + ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); + ZipEntry entry = zipIn.getNextEntry(); + while (entry != null) { + String filePath = destDirectory + separator + entry.getName(); + File checkDir = new File(destDirectory + separator + entry.getName()).getParentFile(); + if (!checkDir.exists()) { + checkDir.mkdir(); + } + new File(destDirectory).mkdirs(); + if (!entry.isDirectory()) { + extractFile(zipIn, filePath); + } else { + new File(filePath).mkdirs(); + } + zipIn.closeEntry(); + entry = zipIn.getNextEntry(); + } + zipIn.close(); + } + + @SuppressWarnings("resource") + public void copyFile(File sourceFile, File destFile) throws IOException { + if(!destFile.exists()) { + destFile.createNewFile(); + } + FileChannel source = null; + FileChannel destination = null; + try { + source = new FileInputStream(sourceFile).getChannel(); + destination = new FileOutputStream(destFile).getChannel(); + destination.transferFrom(source, 0, source.size()); + } + finally { + if(source != null) { + source.close(); + } + if(destination != null) { + destination.close(); + } + } + } + + public void makeTempCopies() { + new File(MapBuilder.propertiesManager.saveLocation.getAbsolutePath() + separator + "tmp").mkdirs(); + for (int i = 0; i < fileBackupArray.length; i++) { + final File old = fileBackupArray[i]; + System.out.println("Creating a temp copy of "+old.getName()+"..."); + try { + copyFile(old, new File(MapBuilder.propertiesManager.saveLocation.getAbsolutePath() + separator + "tmp" + separator + old.getName())); + } catch (IOException e) { + e.printStackTrace(); + } + } + relocateFileVars(); + } + + public void deleteDir(File file) { + File[] contents = file.listFiles(); + if (contents != null) { + for (File f : contents) { + deleteDir(f); + } + } + file.delete(); + } + +} diff --git a/src/com/imraginbro/wurm/mapgen/filegen/PropertiesManager.java b/src/com/imraginbro/wurm/mapgen/filegen/PropertiesManager.java new file mode 100644 index 0000000..a941c48 --- /dev/null +++ b/src/com/imraginbro/wurm/mapgen/filegen/PropertiesManager.java @@ -0,0 +1,100 @@ +package com.imraginbro.wurm.mapgen.filegen; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import com.imraginbro.wurm.mapgen.MapBuilder; + +public class PropertiesManager { + + private final String propertiesFile = "WurmMapGen.properties"; + + public Boolean showDeeds = true; + public Boolean showGuardTowers = true; + public Boolean showStructures = true; + + public int threadLimit = 2; + + public Boolean gen_map_shading = true; + public Boolean gen_map_shade_paths = true; + public Boolean gen_map_water = true; + public Boolean gen_map_bridges = true; + + public Boolean replaceFiles = true; + + public File wurmMapLocation; + public File saveLocation; + + private void copyFromJar() { + try { + InputStream in = this.getClass().getResourceAsStream("/resources/" + this.propertiesFile); + MapBuilder.fileManager.copy(in, this.propertiesFile); + in.close(); + } catch(Exception e) { + System.out.println("Error copying properties file from jar - " + e.getMessage()); + } + } + + public boolean load() { + System.out.println("Loading " + propertiesFile + " file!"); + Properties prop = new Properties(); + InputStream input = null; + + try { + input = new FileInputStream(propertiesFile); + } catch (Exception e) { + System.out.println("[ERROR] problem loading properties FileInputStream - " + e.getMessage()); + System.out.println("Copying properties file from jar... please configure and restart program."); + copyFromJar(); + return false; + } + + if (input != null) { + try { + prop.load(input); + } catch (Exception e) { + System.out.println("Error loading properties file - " + e.getMessage()); + } + } + + final String maploc = prop.getProperty("wurmMapLocation", "C:/location/to/map/folder"); + final String saveloc = prop.getProperty("saveLocation", "C:/location/to/save/folder"); + + System.out.println("[INFO] Map location: " + maploc); + System.out.println("[INFO] Save location: " + saveloc); + + if (maploc.equals("C:/location/to/map/folder") || saveloc.equals("C:/location/to/save/folder")) { + System.out.println("[ERROR] Looks like you are using the default map or save location. Please change in your config file."); + return false; + } + + this.showDeeds = Boolean.parseBoolean(prop.getProperty("showDeeds", Boolean.toString(this.showDeeds))); + this.showGuardTowers = Boolean.parseBoolean(prop.getProperty("showGuardTowers", Boolean.toString(this.showGuardTowers))); + this.showStructures = Boolean.parseBoolean(prop.getProperty("showStructures", Boolean.toString(this.showStructures))); + + this.threadLimit = Integer.parseInt(prop.getProperty("threads", Integer.toString(this.threadLimit))); + + this.gen_map_shading = Boolean.parseBoolean(prop.getProperty("mapGenerateShading", Boolean.toString(this.gen_map_shading))); + this.gen_map_shade_paths = Boolean.parseBoolean(prop.getProperty("mapShadePaths", Boolean.toString(this.gen_map_shade_paths))); + this.gen_map_water = Boolean.parseBoolean(prop.getProperty("mapGenerateWater", Boolean.toString(this.gen_map_water))); + this.gen_map_bridges = Boolean.parseBoolean(prop.getProperty("mapGenerateBridges", Boolean.toString(this.gen_map_bridges))); + + this.wurmMapLocation = new File(maploc); + this.saveLocation = new File(saveloc); + + this.replaceFiles = Boolean.parseBoolean(prop.getProperty("replaceFiles", Boolean.toString(this.replaceFiles))); + + if (input != null) { + try { + input.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return true; + } + +} diff --git a/src/com/imraginbro/wurm/mapgen/filegen/Structure.java b/src/com/imraginbro/wurm/mapgen/filegen/Structure.java new file mode 100644 index 0000000..a65b5ea --- /dev/null +++ b/src/com/imraginbro/wurm/mapgen/filegen/Structure.java @@ -0,0 +1,157 @@ +package com.imraginbro.wurm.mapgen.filegen; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +public class Structure { + + private DBHandler dbhandler; + private String structureName; + private long structureID; + private String ownerName; + private long ownerID; + private int minX = -1; + private int maxX = -1; + private int minY = -1; + private int maxY = -1; + + public Structure(DBHandler dbhandler, Long structureID) { + this.dbhandler = dbhandler; + this.structureID = structureID; + populateStructure(); + populateOwnerName(); + generateMinMax(); + } + + public String getStructureName() { + return this.structureName; + } + + public long getStructureID() { + return this.structureID; + } + + public String getOwnerName() { + return this.ownerName; + } + + public long getOwnerID() { + return this.ownerID; + } + + public int getMinX() { + return this.minX; + } + + public int getMaxX() { + return this.maxX; + } + + public int getMinY() { + return this.minY; + } + + public int getMaxY() { + return this.maxY; + } + + private void populateStructure() { + Statement statement = null; + ResultSet result = null; + try { + statement = dbhandler.getZonesConnection().createStatement(); + result = statement.executeQuery("SELECT * FROM STRUCTURES WHERE WURMID='"+this.structureID+"';"); + if (result.next()) { + this.ownerID = result.getLong("OWNERID"); + this.structureName = result.getString("NAME"); + } + } catch(SQLException e) { + System.out.println("[ERROR] " + e.getMessage()); + e.printStackTrace(); + } finally { + if (result != null) { + try { + result.close(); + } catch (SQLException e) { } + } + if (statement != null) { + try { + statement.close(); + } catch (SQLException e) { } + } + } + } + + private void populateOwnerName() { + Statement statement = null; + ResultSet result = null; + try { + statement = dbhandler.getPlayersConnection().createStatement(); + result = statement.executeQuery("SELECT NAME FROM PLAYERS WHERE WURMID='"+this.ownerID+"';"); + if (result.next()) { + this.ownerName = result.getString("NAME"); + } + } catch(SQLException e) { + System.out.println("[ERROR] " + e.getMessage()); + e.printStackTrace(); + } finally { + if (result != null) { + try { + result.close(); + } catch (SQLException e) { } + } + if (statement != null) { + try { + statement.close(); + } catch (SQLException e) { } + } + } + } + + private void generateMinMax() { + Statement statement = null; + ResultSet result = null; + try { + statement = dbhandler.getZonesConnection().createStatement(); + result = statement.executeQuery("SELECT TILEX, TILEY FROM BUILDTILES WHERE STRUCTUREID='"+this.structureID+"';"); + if (result.next()) { + minX = result.getInt("TILEX"); + maxX = result.getInt("TILEX"); + minY = result.getInt("TILEY"); + maxY = result.getInt("TILEY"); + while (result.next()) { + final int nX = result.getInt("TILEX"); + final int nY = result.getInt("TILEY"); + if (nX < minX) { + minX = nX; + } else if (nX > maxX) { + maxX = nX; + } + if (nY < minY) { + minY = nY; + } else if (nY > maxY) { + maxY = nY; + } + } + maxX++; + maxY++; + } + } catch(SQLException e) { + System.out.println("[ERROR] " + e.getMessage()); + e.printStackTrace(); + } finally { + if (result != null) { + try { + result.close(); + } catch (SQLException e) { } + } + if (statement != null) { + try { + statement.close(); + } catch (SQLException e) { } + } + } + } + +} diff --git a/src/resources/WurmMapGen.properties b/src/resources/WurmMapGen.properties index 51aa6aa..d92b396 100644 --- a/src/resources/WurmMapGen.properties +++ b/src/resources/WurmMapGen.properties @@ -15,6 +15,9 @@ replaceFiles=true ###Map generation variables +#How many concurrent threads to process? Lower=slower,less CPU - Higher=faster,more CPU usage +threads=2 + #Generate shading on map based on tile height mapGenerateShading=true diff --git a/src/resources/required.zip b/src/resources/required.zip index 9630088..cc6169d 100644 Binary files a/src/resources/required.zip and b/src/resources/required.zip differ