Search in sources :

Example 1 with FileSave

use of tools.image.FileSave 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 FileSave

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

the class MapCreator method createPart1Panel.

private void createPart1Panel() {
    panel1.removeAll();
    panel1.setLayout(new BoxLayout(panel1, BoxLayout.PAGE_AXIS));
    panel1.add(Box.createVerticalStrut(30));
    final JTextArea text = new JTextArea(12, 10);
    text.setWrapStyleWord(true);
    text.setLineWrap(true);
    text.setText("Welcome to Veqryn's map creator program for TripleA." + "\r\nThis program just runs utilities inside the triplea.jar file for you, and you could easily " + "run them yourself from the command line by reading the docs/developer_documentation.html" + "\r\n\r\nBefore you begin, go create a folder in your directory: Users\\yourname\\triplea\\maps" + "\r\nName the folder with a short name of your map, do not use any special characters in the name." + "\r\nNext, create 5 folders inside your map folder, with these names: " + "flags, units, baseTiles, reliefTiles, games" + "\r\nThen, create a text file and rename it \"map.properties\" or use one created by this utility." + "\r\n\r\nTo start the Map Utilities, have a png image of your map with just the territory borders " + "and nothing else. The borders must be in black (hex: 000000) and there should not be any " + "anti-aliasing (smoothing) of the lines or edges that stick out." + "\r\nCreate a small image of the map (approx 250 pixels wide) and name it \"smallMap.jpeg\"." + "\r\nPut these in the map's root folder. You can now start the map maker by clicking and filling " + "in the details below, before moving on to 'Step 2' and running the map utilities.");
    final JScrollPane scrollText = new JScrollPane(text);
    panel1.add(scrollText);
    panel1.add(Box.createVerticalStrut(30));
    panel1.add(new JLabel("Click button open up the readme file on how to make maps:"));
    final JButton helpButton = new JButton("Start Tutorial  /  Show Help Document");
    helpButton.addActionListener(e -> OpenFileUtility.openUrl(UrlConstants.MAP_MAKER_HELP.toString()));
    panel1.add(helpButton);
    panel1.add(Box.createVerticalStrut(30));
    panel1.add(new JLabel("Click button to select where your map folder is:"));
    final JButton mapFolderButton = new JButton("Select Map Folder");
    mapFolderButton.addActionListener(SwingAction.of("Select Map Folder", e -> {
        final String path = new FileSave("Where is your map's folder?", null, mapFolderLocation).getPathString();
        if (path != null) {
            final File mapFolder = new File(path);
            if (mapFolder.exists()) {
                mapFolderLocation = mapFolder;
                System.setProperty(ToolArguments.MAP_FOLDER, mapFolderLocation.getPath());
            }
        }
    }));
    panel1.add(mapFolderButton);
    panel1.add(Box.createVerticalStrut(30));
    panel1.add(new JLabel("Set the unit scaling (unit image zoom): "));
    panel1.add(new JLabel("Choose one of: 1.25, 1, 0.875, 0.8333, 0.75, 0.6666, 0.5625, 0.5"));
    final JTextField unitZoomText = new JTextField("" + unitZoom);
    unitZoomText.setMaximumSize(new Dimension(100, 20));
    unitZoomText.addFocusListener(new FocusListener() {

        @Override
        public void focusGained(final FocusEvent e) {
        }

        @Override
        public void focusLost(final FocusEvent e) {
            try {
                unitZoom = Math.min(4.0, Math.max(0.1, Double.parseDouble(unitZoomText.getText())));
                System.setProperty(ToolArguments.UNIT_ZOOM, "" + unitZoom);
            } catch (final Exception ex) {
            // ignore malformed input
            }
            unitZoomText.setText("" + unitZoom);
        }
    });
    panel1.add(unitZoomText);
    panel1.add(Box.createVerticalStrut(30));
    panel1.add(new JLabel("Set the width of the unit images: "));
    final JTextField unitWidthText = new JTextField("" + unitWidth);
    unitWidthText.setMaximumSize(new Dimension(100, 20));
    unitWidthText.addFocusListener(new FocusListener() {

        @Override
        public void focusGained(final FocusEvent e) {
        }

        @Override
        public void focusLost(final FocusEvent e) {
            try {
                unitWidth = Math.min(400, Math.max(1, Integer.parseInt(unitWidthText.getText())));
                System.setProperty(ToolArguments.UNIT_WIDTH, "" + unitWidth);
            } catch (final Exception ex) {
            // ignore malformed input
            }
            unitWidthText.setText("" + unitWidth);
        }
    });
    panel1.add(unitWidthText);
    panel1.add(Box.createVerticalStrut(30));
    panel1.add(new JLabel("Set the height of the unit images: "));
    final JTextField unitHeightText = new JTextField("" + unitHeight);
    unitHeightText.setMaximumSize(new Dimension(100, 20));
    unitHeightText.addFocusListener(new FocusListener() {

        @Override
        public void focusGained(final FocusEvent e) {
        }

        @Override
        public void focusLost(final FocusEvent e) {
            try {
                unitHeight = Math.min(400, Math.max(1, Integer.parseInt(unitHeightText.getText())));
                System.setProperty(ToolArguments.UNIT_HEIGHT, "" + unitHeight);
            } catch (final Exception ex) {
            // ignore malformed input
            }
            unitHeightText.setText("" + unitHeight);
        }
    });
    panel1.add(unitHeightText);
    panel1.add(Box.createVerticalStrut(30));
    panel1.add(new JLabel("<html>Here you can set the 'max memory' that utilities like the Polygon Grabber will use.<br>" + "This is useful is you have a very large map, or ever get any Java Heap Space errors.</html>"));
    panel1.add(new JLabel("Set the amount of memory to use when running new processes (in megabytes [mb]):"));
    final JTextField memoryText = new JTextField("" + (memoryInBytes / (1024 * 1024)));
    memoryText.setMaximumSize(new Dimension(100, 20));
    memoryText.addFocusListener(new FocusListener() {

        @Override
        public void focusGained(final FocusEvent e) {
        }

        @Override
        public void focusLost(final FocusEvent e) {
            try {
                memoryInBytes = (long) 1024 * 1024 * Math.min(4096, Math.max(256, Integer.parseInt(memoryText.getText())));
            } catch (final Exception ex) {
            // ignore malformed input
            }
            memoryText.setText("" + (memoryInBytes / (1024 * 1024)));
        }
    });
    panel1.add(memoryText);
    panel1.add(Box.createVerticalStrut(30));
    panel1.validate();
}
Also used : JScrollPane(javax.swing.JScrollPane) FocusListener(java.awt.event.FocusListener) JTextField(javax.swing.JTextField) ReliefImageBreaker(tools.image.ReliefImageBreaker) LookAndFeel(games.strategy.engine.framework.lookandfeel.LookAndFeel) Action(javax.swing.Action) PolygonGrabber(tools.image.PolygonGrabber) JMenuItem(javax.swing.JMenuItem) DecorationPlacer(tools.image.DecorationPlacer) TileImageBreaker(tools.image.TileImageBreaker) BorderLayout(java.awt.BorderLayout) JFrame(javax.swing.JFrame) ClientSetting(games.strategy.triplea.settings.ClientSetting) BoxLayout(javax.swing.BoxLayout) JMenuBar(javax.swing.JMenuBar) TileImageReconstructor(tools.image.TileImageReconstructor) JButton(javax.swing.JButton) CenterPicker(tools.image.CenterPicker) UnitImageFactory(games.strategy.triplea.image.UnitImageFactory) JMenu(javax.swing.JMenu) Component(java.awt.Component) File(java.io.File) FileSave(tools.image.FileSave) Box(javax.swing.Box) Consumer(java.util.function.Consumer) JScrollPane(javax.swing.JScrollPane) AutoPlacementFinder(tools.image.AutoPlacementFinder) Dimension(java.awt.Dimension) ToolArguments(tools.util.ToolArguments) OpenFileUtility(games.strategy.net.OpenFileUtility) FocusEvent(java.awt.event.FocusEvent) JLabel(javax.swing.JLabel) UrlConstants(games.strategy.triplea.UrlConstants) JTextArea(javax.swing.JTextArea) JPanel(javax.swing.JPanel) WindowConstants(javax.swing.WindowConstants) SwingAction(games.strategy.ui.SwingAction) JTextArea(javax.swing.JTextArea) BoxLayout(javax.swing.BoxLayout) JButton(javax.swing.JButton) JLabel(javax.swing.JLabel) Dimension(java.awt.Dimension) JTextField(javax.swing.JTextField) FocusEvent(java.awt.event.FocusEvent) FileSave(tools.image.FileSave) File(java.io.File) FocusListener(java.awt.event.FocusListener)

Example 3 with FileSave

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

the class MapPropertiesMaker method runInternal.

private void runInternal(final String[] args) {
    handleCommandLineArgs(args);
    if (mapFolderLocation == null) {
        ToolLogger.info("Select the map folder");
        final String path = new FileSave("Where is your map's folder?", null, mapFolderLocation).getPathString();
        if (path != null) {
            final File mapFolder = new File(path);
            if (mapFolder.exists()) {
                mapFolderLocation = mapFolder;
                System.setProperty(ToolArguments.MAP_FOLDER, mapFolderLocation.getPath());
            }
        }
    }
    if (mapFolderLocation != null) {
        final MapPropertiesMakerFrame frame = new MapPropertiesMakerFrame();
        frame.setSize(800, 800);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    } else {
        ToolLogger.info("No Map Folder Selected. Shutting down.");
    }
}
Also used : FileSave(tools.image.FileSave) File(java.io.File)

Aggregations

File (java.io.File)3 FileSave (tools.image.FileSave)3 JLabel (javax.swing.JLabel)2 LookAndFeel (games.strategy.engine.framework.lookandfeel.LookAndFeel)1 OpenFileUtility (games.strategy.net.OpenFileUtility)1 UrlConstants (games.strategy.triplea.UrlConstants)1 UnitImageFactory (games.strategy.triplea.image.UnitImageFactory)1 ClientSetting (games.strategy.triplea.settings.ClientSetting)1 SwingAction (games.strategy.ui.SwingAction)1 AlphanumComparator (games.strategy.util.AlphanumComparator)1 BorderLayout (java.awt.BorderLayout)1 Component (java.awt.Component)1 Dimension (java.awt.Dimension)1 Polygon (java.awt.Polygon)1 Shape (java.awt.Shape)1 FocusEvent (java.awt.event.FocusEvent)1 FocusListener (java.awt.event.FocusListener)1 Area (java.awt.geom.Area)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1