Search in sources :

Example 1 with FileOpen

use of tools.image.FileOpen in project triplea by triplea-game.

the class ConnectionFinder method runInternal.

private void runInternal(final String[] args) {
    handleCommandLineArgs(args);
    JOptionPane.showMessageDialog(null, new JLabel("<html>" + "This is the ConnectionFinder. " + "<br>It will create a file containing the connections between territories, and optionally the territory " + "definitions as well. " + "<br>Copy and paste everything from this file into your game xml file (the 'map' section). " + "<br>The connections file can and Should Be Deleted when finished, because it is Not Needed and not read " + "by the engine. " + "</html>"));
    ToolLogger.info("Select polygons.txt");
    File polyFile = null;
    if (mapFolderLocation != null && mapFolderLocation.exists()) {
        polyFile = new File(mapFolderLocation, "polygons.txt");
    }
    if (polyFile != null && polyFile.exists() && JOptionPane.showConfirmDialog(null, "A polygons.txt file was found in the map's folder, do you want to use it?", "File Suggestion", JOptionPane.YES_NO_CANCEL_OPTION) == 0) {
    // yay
    } else {
        polyFile = new FileOpen("Select The polygons.txt file", mapFolderLocation, ".txt").getFile();
    }
    if (polyFile == null || !polyFile.exists()) {
        ToolLogger.info("No polygons.txt Selected. Shutting down.");
        return;
    }
    if (mapFolderLocation == null && polyFile != null) {
        mapFolderLocation = polyFile.getParentFile();
    }
    final Map<String, List<Area>> territoryAreas = new HashMap<>();
    Map<String, List<Polygon>> mapOfPolygons = null;
    try (InputStream in = new FileInputStream(polyFile)) {
        mapOfPolygons = PointFileReaderWriter.readOneToManyPolygons(in);
        for (final String territoryName : mapOfPolygons.keySet()) {
            final List<Polygon> listOfPolygons = mapOfPolygons.get(territoryName);
            final List<Area> listOfAreas = new ArrayList<>();
            for (final Polygon p : listOfPolygons) {
                listOfAreas.add(new Area(p));
            }
            territoryAreas.put(territoryName, listOfAreas);
        }
    } catch (final IOException e) {
        ToolLogger.error("Failed to load polygons: " + polyFile.getAbsolutePath(), e);
        return;
    }
    if (!dimensionsSet) {
        final String lineWidth = JOptionPane.showInputDialog(null, "Enter the width of territory border lines on your map? \r\n(eg: 1, or 2, etc.)");
        try {
            final int lineThickness = Integer.parseInt(lineWidth);
            scalePixels = lineThickness * 4;
            minOverlap = scalePixels * 4;
            dimensionsSet = true;
        } catch (final NumberFormatException ex) {
        // ignore malformed input
        }
    }
    if (JOptionPane.showConfirmDialog(null, "Scale set to " + scalePixels + " pixels larger, and minimum overlap set to " + minOverlap + " pixels. \r\n" + "Do you wish to continue with this? \r\n" + "Select Yes to continue, Select No to override and change the size.", "Scale and Overlap Size", JOptionPane.YES_NO_OPTION) == 1) {
        final String scale = JOptionPane.showInputDialog(null, "Enter the number of pixels larger each territory should become? \r\n" + "(Normally 4x bigger than the border line width. eg: 4, or 8, etc)");
        try {
            scalePixels = Integer.parseInt(scale);
        } catch (final NumberFormatException ex) {
        // ignore malformed input
        }
        final String overlap = JOptionPane.showInputDialog(null, "Enter the minimum number of overlapping pixels for a connection? \r\n" + "(Normally 16x bigger than the border line width. eg: 16, or 32, etc.)");
        try {
            minOverlap = Integer.parseInt(overlap);
        } catch (final NumberFormatException ex) {
        // ignore malformed input
        }
    }
    ToolLogger.info("Now Scanning for Connections");
    // sort so that they are in alphabetic order (makes xml's prettier and easier to update in future)
    final List<String> allTerritories = mapOfPolygons == null ? new ArrayList<>() : new ArrayList<>(mapOfPolygons.keySet());
    allTerritories.sort(new AlphanumComparator());
    final List<String> allAreas = new ArrayList<>(territoryAreas.keySet());
    allAreas.sort(new AlphanumComparator());
    final Map<String, Collection<String>> connections = new HashMap<>();
    for (final String territory : allTerritories) {
        final Set<String> thisTerritoryConnections = new LinkedHashSet<>();
        final List<Polygon> currentPolygons = mapOfPolygons.get(territory);
        for (final Polygon currentPolygon : currentPolygons) {
            final Shape scaledShape = scale(currentPolygon, scalePixels);
            for (final String otherTerritory : allAreas) {
                if (otherTerritory.equals(territory)) {
                    continue;
                }
                if (thisTerritoryConnections.contains(otherTerritory)) {
                    continue;
                }
                if (connections.get(otherTerritory) != null && connections.get(otherTerritory).contains(territory)) {
                    continue;
                }
                for (final Area otherArea : territoryAreas.get(otherTerritory)) {
                    final Area testArea = new Area(scaledShape);
                    testArea.intersect(otherArea);
                    if (!testArea.isEmpty() && sizeOfArea(testArea) > minOverlap) {
                        thisTerritoryConnections.add(otherTerritory);
                    }
                }
            }
            connections.put(territory, thisTerritoryConnections);
        }
    }
    if (JOptionPane.showConfirmDialog(null, "Do you also want to create the Territory Definitions?", "Territory Definitions", JOptionPane.YES_NO_CANCEL_OPTION) == 0) {
        final String waterString = JOptionPane.showInputDialog(null, "Enter a string or regex that determines if the territory is Water? \r\n(e.g.: " + Util.TERRITORY_SEA_ZONE_INFIX + ")", Util.TERRITORY_SEA_ZONE_INFIX);
        territoryDefinitions = doTerritoryDefinitions(allTerritories, waterString);
    }
    try {
        final String fileName = new FileSave("Where To Save connections.txt ? (cancel to print to console)", "connections.txt", mapFolderLocation).getPathString();
        final StringBuilder connectionsString = convertToXml(connections);
        if (fileName == null) {
            if (territoryDefinitions != null) {
                ToolLogger.info(territoryDefinitions.toString());
            }
            ToolLogger.info(connectionsString.toString());
        } else {
            try (OutputStream out = new FileOutputStream(fileName)) {
                if (territoryDefinitions != null) {
                    out.write(String.valueOf(territoryDefinitions).getBytes(StandardCharsets.UTF_8));
                }
                out.write(String.valueOf(connectionsString).getBytes(StandardCharsets.UTF_8));
            }
            ToolLogger.info("Data written to :" + new File(fileName).getCanonicalPath());
        }
    } catch (final Exception e) {
        ToolLogger.error("Failed to write connections", e);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Shape(java.awt.Shape) HashMap(java.util.HashMap) FileOpen(tools.image.FileOpen) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Polygon(java.awt.Polygon) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JLabel(javax.swing.JLabel) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) Area(java.awt.geom.Area) AlphanumComparator(games.strategy.util.AlphanumComparator) FileOutputStream(java.io.FileOutputStream) Collection(java.util.Collection) FileSave(tools.image.FileSave) File(java.io.File)

Example 2 with FileOpen

use of tools.image.FileOpen in project triplea by triplea-game.

the class PlacementPicker method runInternal.

private void runInternal(final String[] args) throws IOException {
    handleCommandLineArgs(args);
    JOptionPane.showMessageDialog(null, new JLabel("<html>" + "This is the PlacementPicker, it will create a place.txt file for you. " + "<br>In order to run this, you must already have created a centers.txt file and a polygons.txt file. " + "<br><br>The program will ask for unit scale (unit zoom) level [normally between 0.5 and 1.0], " + "<br>Then it will ask for the unit image size when not zoomed [normally 48x48]. " + "<br><br>If you want to have less, or more, room around the edges of your units, you can change the unit " + "size. " + "<br><br>After it starts, you may Load an existing place.txt file, that way you can make changes to it " + "then save it. " + "<br><br>LEFT CLICK = Select a new territory. " + "<br><br>Holding CTRL/SHIFT + LEFT CLICK = Create a new placement for that territory. " + "<br><br>RIGHT CLICK = Remove last placement for that territory. " + "<br><br>Holding CTRL/SHIFT + RIGHT CLICK = Save all placements for that territory. " + "<br><br>Pressing the 'O' key = Toggle the direction for placement overflow for that territory. " + "<br><br>It is a very good idea to check each territory using the PlacementPicker after running the " + "AutoPlacementFinder " + "<br>to make sure there are enough placements for each territory. If not, you can always add more then " + "save it. " + "<br><br>IF there are not enough placements, by default the units will Overflow to the RIGHT of the " + "very LAST placement made, " + "<br>so be sure that the last placement is on the right side of the territory " + "<br>or that it doesn't overflow directly on top of other placements. Can instead toggle the overflow " + "direction." + "<br><br>To show all placements, or see the overflow direction, or see which territories you have not " + "yet completed enough, " + "<br>placements for, turn on the mode options in the 'edit' menu. " + "</html>"));
    ToolLogger.info("Select the map");
    final FileOpen mapSelection = new FileOpen("Select The Map", mapFolderLocation, ".gif", ".png");
    final String mapName = mapSelection.getPathString();
    if (mapFolderLocation == null && mapSelection.getFile() != null) {
        mapFolderLocation = mapSelection.getFile().getParentFile();
    }
    if (mapName != null) {
        final PlacementPickerFrame frame = new PlacementPickerFrame(mapName);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    } else {
        ToolLogger.info("No Image Map Selected. Shutting down.");
    }
}
Also used : FileOpen(tools.image.FileOpen) JLabel(javax.swing.JLabel)

Example 3 with FileOpen

use of tools.image.FileOpen in project triplea by triplea-game.

the class ImageShrinker method runInternal.

private void runInternal(final String[] args) throws IOException {
    handleCommandLineArgs(args);
    JOptionPane.showMessageDialog(null, new JLabel("<html>" + "This is the ImageShrinker, it will create a smallMap.jpeg file for you. " + "<br>Put in your base map or relief map, and it will spit out a small scaled copy of it." + "<br>Please note that the quality of the image will be worse than if you use a real painting program." + "<br>So we suggest you instead shrink the image with paint.net or photoshop or gimp, etc, then clean it " + "up before saving." + "</html>"));
    final File mapFile = new FileOpen("Select The Large Image", mapFolderLocation, ".gif", ".png").getFile();
    if (mapFile == null || !mapFile.exists()) {
        throw new IllegalStateException(mapFile + "File does not exist");
    }
    if (mapFolderLocation == null) {
        mapFolderLocation = mapFile.getParentFile();
    }
    final String input = JOptionPane.showInputDialog(null, "Select scale");
    final float scale = Float.parseFloat(input);
    final Image baseImg = ImageIO.read(mapFile);
    final int thumbWidth = (int) (baseImg.getWidth(null) * scale);
    final int thumbHeight = (int) (baseImg.getHeight(null) * scale);
    // based on code from
    // http://www.geocities.com/marcoschmidt.geo/java-save-jpeg-thumbnail.html
    // draw original image to thumbnail image object and
    // scale it to the new size on-the-fly
    final BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
    final Graphics2D graphics2D = thumbImage.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.drawImage(baseImg, 0, 0, thumbWidth, thumbHeight, null);
    // save thumbnail image to OUTFILE
    final File file = new File(new File(mapFile.getPath()).getParent() + File.separatorChar + "smallMap.jpeg");
    try (ImageOutputStream out = new FileImageOutputStream(file)) {
        final ImageWriter encoder = ImageIO.getImageWritersByFormatName("JPEG").next();
        final JPEGImageWriteParam param = new JPEGImageWriteParam(null);
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality((float) 1.0);
        encoder.setOutput(out);
        encoder.write(null, new IIOImage(thumbImage, null, null), param);
    }
    ToolLogger.info("Image successfully written to " + file.getPath());
}
Also used : FileOpen(tools.image.FileOpen) FileImageOutputStream(javax.imageio.stream.FileImageOutputStream) ImageWriter(javax.imageio.ImageWriter) JLabel(javax.swing.JLabel) IIOImage(javax.imageio.IIOImage) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) BufferedImage(java.awt.image.BufferedImage) Graphics2D(java.awt.Graphics2D) IIOImage(javax.imageio.IIOImage) JPEGImageWriteParam(javax.imageio.plugins.jpeg.JPEGImageWriteParam) File(java.io.File) ImageOutputStream(javax.imageio.stream.ImageOutputStream) FileImageOutputStream(javax.imageio.stream.FileImageOutputStream)

Aggregations

JLabel (javax.swing.JLabel)3 FileOpen (tools.image.FileOpen)3 File (java.io.File)2 AlphanumComparator (games.strategy.util.AlphanumComparator)1 Graphics2D (java.awt.Graphics2D)1 Image (java.awt.Image)1 Polygon (java.awt.Polygon)1 Shape (java.awt.Shape)1 Area (java.awt.geom.Area)1 BufferedImage (java.awt.image.BufferedImage)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 LinkedHashSet (java.util.LinkedHashSet)1 List (java.util.List)1