source: josm/trunk/src/org/openstreetmap/josm/actions/SimplifyWayAction.java@ 12527

Last change on this file since 12527 was 12527, checked in by Don-vip, 7 years ago

fix #10838 - add robustness if incomplete ways are selected

  • Property svn:eol-style set to native
File size: 11.6 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
8import java.awt.event.ActionEvent;
9import java.awt.event.KeyEvent;
10import java.util.ArrayList;
11import java.util.Arrays;
12import java.util.Collection;
13import java.util.Collections;
14import java.util.HashSet;
15import java.util.LinkedList;
16import java.util.List;
17import java.util.Set;
18
19import javax.swing.JOptionPane;
20import javax.swing.SwingUtilities;
21
22import org.openstreetmap.josm.Main;
23import org.openstreetmap.josm.command.ChangeCommand;
24import org.openstreetmap.josm.command.Command;
25import org.openstreetmap.josm.command.DeleteCommand;
26import org.openstreetmap.josm.command.SequenceCommand;
27import org.openstreetmap.josm.data.osm.DataSet;
28import org.openstreetmap.josm.data.osm.Node;
29import org.openstreetmap.josm.data.osm.OsmPrimitive;
30import org.openstreetmap.josm.data.osm.Way;
31import org.openstreetmap.josm.data.projection.Ellipsoid;
32import org.openstreetmap.josm.gui.HelpAwareOptionPane;
33import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
34import org.openstreetmap.josm.gui.Notification;
35import org.openstreetmap.josm.tools.ImageProvider;
36import org.openstreetmap.josm.tools.Shortcut;
37
38/**
39 * Delete unnecessary nodes from a way
40 * @since 2575
41 */
42public class SimplifyWayAction extends JosmAction {
43
44 /**
45 * Constructs a new {@code SimplifyWayAction}.
46 */
47 public SimplifyWayAction() {
48 super(tr("Simplify Way"), "simplify", tr("Delete unnecessary nodes from a way."),
49 Shortcut.registerShortcut("tools:simplify", tr("Tool: {0}", tr("Simplify Way")), KeyEvent.VK_Y, Shortcut.SHIFT), true);
50 putValue("help", ht("/Action/SimplifyWay"));
51 }
52
53 protected boolean confirmWayWithNodesOutsideBoundingBox(List<? extends OsmPrimitive> primitives) {
54 return DeleteCommand.checkAndConfirmOutlyingDelete(primitives, null);
55 }
56
57 protected void alertSelectAtLeastOneWay() {
58 SwingUtilities.invokeLater(() ->
59 new Notification(
60 tr("Please select at least one way to simplify."))
61 .setIcon(JOptionPane.WARNING_MESSAGE)
62 .setDuration(Notification.TIME_SHORT)
63 .setHelpTopic(ht("/Action/SimplifyWay#SelectAWayToSimplify"))
64 .show()
65 );
66 }
67
68 protected boolean confirmSimplifyManyWays(int numWays) {
69 ButtonSpec[] options = new ButtonSpec[] {
70 new ButtonSpec(
71 tr("Yes"),
72 ImageProvider.get("ok"),
73 tr("Simplify all selected ways"),
74 null
75 ),
76 new ButtonSpec(
77 tr("Cancel"),
78 ImageProvider.get("cancel"),
79 tr("Cancel operation"),
80 null
81 )
82 };
83 return 0 == HelpAwareOptionPane.showOptionDialog(
84 Main.parent,
85 tr(
86 "The selection contains {0} ways. Are you sure you want to simplify them all?",
87 numWays
88 ),
89 tr("Simplify ways?"),
90 JOptionPane.WARNING_MESSAGE,
91 null, // no special icon
92 options,
93 options[0],
94 ht("/Action/SimplifyWay#ConfirmSimplifyAll")
95 );
96 }
97
98 @Override
99 public void actionPerformed(ActionEvent e) {
100 DataSet ds = getLayerManager().getEditDataSet();
101 ds.beginUpdate();
102 try {
103 List<Way> ways = OsmPrimitive.getFilteredList(ds.getSelected(), Way.class);
104 ways.removeIf(OsmPrimitive::isIncomplete);
105 if (ways.isEmpty()) {
106 alertSelectAtLeastOneWay();
107 return;
108 } else if (!confirmWayWithNodesOutsideBoundingBox(ways) || (ways.size() > 10 && !confirmSimplifyManyWays(ways.size()))) {
109 return;
110 }
111
112 Collection<Command> allCommands = new LinkedList<>();
113 for (Way way: ways) {
114 SequenceCommand simplifyCommand = simplifyWay(way);
115 if (simplifyCommand == null) {
116 continue;
117 }
118 allCommands.add(simplifyCommand);
119 }
120 if (allCommands.isEmpty()) return;
121 SequenceCommand rootCommand = new SequenceCommand(
122 trn("Simplify {0} way", "Simplify {0} ways", allCommands.size(), allCommands.size()),
123 allCommands
124 );
125 Main.main.undoRedo.add(rootCommand);
126 } finally {
127 ds.endUpdate();
128 }
129 }
130
131 /**
132 * Replies true if <code>node</code> is a required node which can't be removed
133 * in order to simplify the way.
134 *
135 * @param way the way to be simplified
136 * @param node the node to check
137 * @return true if <code>node</code> is a required node which can't be removed
138 * in order to simplify the way.
139 */
140 protected static boolean isRequiredNode(Way way, Node node) {
141 int frequency = Collections.frequency(way.getNodes(), node);
142 if ((way.getNode(0) == node) && (way.getNode(way.getNodesCount()-1) == node)) {
143 frequency = frequency - 1; // closed way closing node counted only once
144 }
145 boolean isRequired = frequency > 1;
146 if (!isRequired) {
147 List<OsmPrimitive> parents = new LinkedList<>();
148 parents.addAll(node.getReferrers());
149 parents.remove(way);
150 isRequired = !parents.isEmpty();
151 }
152 if (!isRequired) {
153 isRequired = node.isTagged();
154 }
155 return isRequired;
156 }
157
158 /**
159 * Simplifies a way with default threshold (read from preferences).
160 *
161 * @param w the way to simplify
162 * @return The sequence of commands to run
163 * @since 6411
164 */
165 public final SequenceCommand simplifyWay(Way w) {
166 return simplifyWay(w, Main.pref.getDouble("simplify-way.max-error", 3.0));
167 }
168
169 /**
170 * Simplifies a way with a given threshold.
171 *
172 * @param w the way to simplify
173 * @param threshold the max error threshold
174 * @return The sequence of commands to run
175 * @since 6411
176 */
177 public static SequenceCommand simplifyWay(Way w, double threshold) {
178 int lower = 0;
179 int i = 0;
180 List<Node> newNodes = new ArrayList<>(w.getNodesCount());
181 while (i < w.getNodesCount()) {
182 if (isRequiredNode(w, w.getNode(i))) {
183 // copy a required node to the list of new nodes. Simplify not possible
184 newNodes.add(w.getNode(i));
185 i++;
186 lower++;
187 continue;
188 }
189 i++;
190 // find the longest sequence of not required nodes ...
191 while (i < w.getNodesCount() && !isRequiredNode(w, w.getNode(i))) {
192 i++;
193 }
194 // ... and simplify them
195 buildSimplifiedNodeList(w.getNodes(), lower, Math.min(w.getNodesCount()-1, i), threshold, newNodes);
196 lower = i;
197 i++;
198 }
199
200 // Closed way, check if the first node could also be simplified ...
201 if (newNodes.size() > 3 && newNodes.get(0) == newNodes.get(newNodes.size() - 1) && !isRequiredNode(w, newNodes.get(0))) {
202 final List<Node> l1 = Arrays.asList(newNodes.get(newNodes.size() - 2), newNodes.get(0), newNodes.get(1));
203 final List<Node> l2 = new ArrayList<>(3);
204 buildSimplifiedNodeList(l1, 0, 2, threshold, l2);
205 if (!l2.contains(newNodes.get(0))) {
206 newNodes.remove(0);
207 newNodes.set(newNodes.size() - 1, newNodes.get(0)); // close the way
208 }
209 }
210
211 Set<Node> delNodes = new HashSet<>();
212 delNodes.addAll(w.getNodes());
213 delNodes.removeAll(newNodes);
214
215 if (delNodes.isEmpty()) return null;
216
217 Collection<Command> cmds = new LinkedList<>();
218 Way newWay = new Way(w);
219 newWay.setNodes(newNodes);
220 cmds.add(new ChangeCommand(w, newWay));
221 cmds.add(new DeleteCommand(w.getDataSet(), delNodes));
222 w.getDataSet().clearSelection(delNodes);
223 return new SequenceCommand(
224 trn("Simplify Way (remove {0} node)", "Simplify Way (remove {0} nodes)", delNodes.size(), delNodes.size()), cmds);
225 }
226
227 /**
228 * Builds the simplified list of nodes for a way segment given by a lower index <code>from</code>
229 * and an upper index <code>to</code>
230 *
231 * @param wnew the way to simplify
232 * @param from the lower index
233 * @param to the upper index
234 * @param threshold the max error threshold
235 * @param simplifiedNodes list that will contain resulting nodes
236 */
237 protected static void buildSimplifiedNodeList(List<Node> wnew, int from, int to, double threshold, List<Node> simplifiedNodes) {
238
239 Node fromN = wnew.get(from);
240 Node toN = wnew.get(to);
241
242 // Get max xte
243 int imax = -1;
244 double xtemax = 0;
245 for (int i = from + 1; i < to; i++) {
246 Node n = wnew.get(i);
247 // CHECKSTYLE.OFF: SingleSpaceSeparator
248 double xte = Math.abs(Ellipsoid.WGS84.a
249 * xtd(fromN.lat() * Math.PI / 180, fromN.lon() * Math.PI / 180, toN.lat() * Math.PI / 180,
250 toN.lon() * Math.PI / 180, n.lat() * Math.PI / 180, n.lon() * Math.PI / 180));
251 // CHECKSTYLE.ON: SingleSpaceSeparator
252 if (xte > xtemax) {
253 xtemax = xte;
254 imax = i;
255 }
256 }
257
258 if (imax != -1 && xtemax >= threshold) {
259 // Segment cannot be simplified - try shorter segments
260 buildSimplifiedNodeList(wnew, from, imax, threshold, simplifiedNodes);
261 buildSimplifiedNodeList(wnew, imax, to, threshold, simplifiedNodes);
262 } else {
263 // Simplify segment
264 if (simplifiedNodes.isEmpty() || simplifiedNodes.get(simplifiedNodes.size()-1) != fromN) {
265 simplifiedNodes.add(fromN);
266 }
267 if (fromN != toN) {
268 simplifiedNodes.add(toN);
269 }
270 }
271 }
272
273 /* From Aviaton Formulary v1.3
274 * http://williams.best.vwh.net/avform.htm
275 */
276 private static double dist(double lat1, double lon1, double lat2, double lon2) {
277 return 2 * Math.asin(Math.sqrt(Math.pow(Math.sin((lat1 - lat2) / 2), 2) + Math.cos(lat1) * Math.cos(lat2)
278 * Math.pow(Math.sin((lon1 - lon2) / 2), 2)));
279 }
280
281 private static double course(double lat1, double lon1, double lat2, double lon2) {
282 return Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
283 * Math.cos(lat2) * Math.cos(lon1 - lon2))
284 % (2 * Math.PI);
285 }
286
287 private static double xtd(double lat1, double lon1, double lat2, double lon2, double lat3, double lon3) {
288 double distAD = dist(lat1, lon1, lat3, lon3);
289 double crsAD = course(lat1, lon1, lat3, lon3);
290 double crsAB = course(lat1, lon1, lat2, lon2);
291 return Math.asin(Math.sin(distAD) * Math.sin(crsAD - crsAB));
292 }
293
294 @Override
295 protected void updateEnabledState() {
296 updateEnabledStateOnCurrentSelection();
297 }
298
299 @Override
300 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
301 setEnabled(selection != null && !selection.isEmpty());
302 }
303}
Note: See TracBrowser for help on using the repository browser.