source: josm/trunk/src/org/openstreetmap/josm/actions/CreateCircleAction.java@ 12726

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

see #13036 - deprecate Command() default constructor, fix unit tests and java warnings

  • Property svn:eol-style set to native
File size: 10.9 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;
6
7import java.awt.event.ActionEvent;
8import java.awt.event.KeyEvent;
9import java.io.Serializable;
10import java.util.ArrayList;
11import java.util.Arrays;
12import java.util.Collection;
13import java.util.Collections;
14import java.util.Comparator;
15import java.util.LinkedList;
16import java.util.List;
17
18import javax.swing.JOptionPane;
19
20import org.openstreetmap.josm.Main;
21import org.openstreetmap.josm.command.AddCommand;
22import org.openstreetmap.josm.command.ChangeCommand;
23import org.openstreetmap.josm.command.Command;
24import org.openstreetmap.josm.command.SequenceCommand;
25import org.openstreetmap.josm.data.coor.EastNorth;
26import org.openstreetmap.josm.data.coor.LatLon;
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.gui.MainApplication;
32import org.openstreetmap.josm.gui.Notification;
33import org.openstreetmap.josm.tools.Geometry;
34import org.openstreetmap.josm.tools.RightAndLefthandTraffic;
35import org.openstreetmap.josm.tools.Shortcut;
36
37/**
38 * - Create a new circle from two selected nodes or a way with 2 nodes which represent the diameter of the circle.
39 * - Create a new circle from three selected nodes--or a way with 3 nodes.
40 * - Useful for roundabouts
41 *
42 * Notes:
43 * * If a way is selected, it is changed. If nodes are selected a new way is created.
44 * So if you've got a way with nodes it makes a difference between running this on the way or the nodes!
45 * * The existing nodes are retained, and additional nodes are inserted regularly
46 * to achieve the desired number of nodes (`createcircle.nodecount`).
47 * BTW: Someone might want to implement projection corrections for this...
48 *
49 * @author Henry Loenwind
50 * @author Sebastian Masch
51 * @author Alain Delplanque
52 *
53 * @since 996
54 */
55public final class CreateCircleAction extends JosmAction {
56
57 /**
58 * Constructs a new {@code CreateCircleAction}.
59 */
60 public CreateCircleAction() {
61 super(tr("Create Circle"), "aligncircle", tr("Create a circle from three selected nodes."),
62 Shortcut.registerShortcut("tools:createcircle", tr("Tool: {0}", tr("Create Circle")),
63 KeyEvent.VK_O, Shortcut.SHIFT), true, "createcircle", true);
64 putValue("help", ht("/Action/CreateCircle"));
65 }
66
67 /**
68 * Distributes nodes according to the algorithm of election with largest remainder.
69 * @param angles Array of PolarNode ordered by increasing angles
70 * @param nodesCount Number of nodes to be distributed
71 * @return Array of number of nodes to put in each arc
72 */
73 private static int[] distributeNodes(PolarNode[] angles, int nodesCount) {
74 int[] count = new int[angles.length];
75 double[] width = new double[angles.length];
76 double[] remainder = new double[angles.length];
77 for (int i = 0; i < angles.length; i++) {
78 width[i] = angles[(i+1) % angles.length].a - angles[i].a;
79 if (width[i] < 0)
80 width[i] += 2*Math.PI;
81 }
82 int assign = 0;
83 for (int i = 0; i < angles.length; i++) {
84 double part = width[i] / 2.0 / Math.PI * nodesCount;
85 count[i] = (int) Math.floor(part);
86 remainder[i] = part - count[i];
87 assign += count[i];
88 }
89 while (assign < nodesCount) {
90 int imax = 0;
91 for (int i = 1; i < angles.length; i++) {
92 if (remainder[i] > remainder[imax])
93 imax = i;
94 }
95 count[imax]++;
96 remainder[imax] = 0;
97 assign++;
98 }
99 return count;
100 }
101
102 /**
103 * Class designed to create a couple between a node and its angle relative to the center of the circle.
104 */
105 private static class PolarNode {
106 private final double a;
107 private final Node node;
108
109 PolarNode(EastNorth center, Node n) {
110 EastNorth pt = n.getEastNorth();
111 this.a = Math.atan2(pt.north() - center.north(), pt.east() - center.east());
112 this.node = n;
113 }
114 }
115
116 /**
117 * Comparator used to order PolarNode relative to their angle.
118 */
119 private static class PolarNodeComparator implements Comparator<PolarNode>, Serializable {
120 private static final long serialVersionUID = 1L;
121
122 @Override
123 public int compare(PolarNode pc1, PolarNode pc2) {
124 return Double.compare(pc1.a, pc2.a);
125 }
126 }
127
128 @Override
129 public void actionPerformed(ActionEvent e) {
130 if (!isEnabled())
131 return;
132
133 int numberOfNodesInCircle = Main.pref.getInteger("createcircle.nodecount", 16);
134 if (numberOfNodesInCircle < 1) {
135 numberOfNodesInCircle = 1;
136 } else if (numberOfNodesInCircle > 100) {
137 numberOfNodesInCircle = 100;
138 }
139
140 DataSet ds = getLayerManager().getEditDataSet();
141 Collection<OsmPrimitive> sel = ds.getSelected();
142 List<Node> nodes = OsmPrimitive.getFilteredList(sel, Node.class);
143 List<Way> ways = OsmPrimitive.getFilteredList(sel, Way.class);
144
145 Way existingWay = null;
146
147 // special case if no single nodes are selected and exactly one way is:
148 // then use the way's nodes
149 if (nodes.isEmpty() && (ways.size() == 1)) {
150 existingWay = ways.get(0);
151 for (Node n : existingWay.getNodes()) {
152 if (!nodes.contains(n)) {
153 nodes.add(n);
154 }
155 }
156 }
157
158 if (nodes.size() < 2 || nodes.size() > 3) {
159 new Notification(
160 tr("Please select exactly two or three nodes or one way with exactly two or three nodes."))
161 .setIcon(JOptionPane.INFORMATION_MESSAGE)
162 .setDuration(Notification.TIME_LONG)
163 .show();
164 return;
165 }
166
167 EastNorth center;
168
169 if (nodes.size() == 2) {
170 // diameter: two single nodes needed or a way with two nodes
171 Node n1 = nodes.get(0);
172 double x1 = n1.getEastNorth().east();
173 double y1 = n1.getEastNorth().north();
174 Node n2 = nodes.get(1);
175 double x2 = n2.getEastNorth().east();
176 double y2 = n2.getEastNorth().north();
177
178 // calculate the center (xc/yc)
179 double xc = 0.5 * (x1 + x2);
180 double yc = 0.5 * (y1 + y2);
181 center = new EastNorth(xc, yc);
182 } else {
183 // triangle: three single nodes needed or a way with three nodes
184 center = Geometry.getCenter(nodes);
185 if (center == null) {
186 notifyNodesNotOnCircle();
187 return;
188 }
189 }
190
191 // calculate the radius (r)
192 EastNorth n1 = nodes.get(0).getEastNorth();
193 double r = Math.sqrt(Math.pow(center.east()-n1.east(), 2) +
194 Math.pow(center.north()-n1.north(), 2));
195
196 // Order nodes by angle
197 PolarNode[] angles = new PolarNode[nodes.size()];
198 for (int i = 0; i < nodes.size(); i++) {
199 angles[i] = new PolarNode(center, nodes.get(i));
200 }
201 Arrays.sort(angles, new PolarNodeComparator());
202 int[] count = distributeNodes(angles,
203 numberOfNodesInCircle >= nodes.size() ? (numberOfNodesInCircle - nodes.size()) : 0);
204
205 // now we can start doing things to OSM data
206 Collection<Command> cmds = new LinkedList<>();
207
208 // build a way for the circle
209 List<Node> nodesToAdd = new ArrayList<>();
210 for (int i = 0; i < nodes.size(); i++) {
211 nodesToAdd.add(angles[i].node);
212 double delta = angles[(i+1) % nodes.size()].a - angles[i].a;
213 if (delta < 0)
214 delta += 2*Math.PI;
215 for (int j = 0; j < count[i]; j++) {
216 double alpha = angles[i].a + (j+1)*delta/(count[i]+1);
217 double x = center.east() + r*Math.cos(alpha);
218 double y = center.north() + r*Math.sin(alpha);
219 LatLon ll = Main.getProjection().eastNorth2latlon(new EastNorth(x, y));
220 if (ll.isOutSideWorld()) {
221 notifyNodesNotOnCircle();
222 return;
223 }
224 Node n = new Node(ll);
225 nodesToAdd.add(n);
226 cmds.add(new AddCommand(ds, n));
227 }
228 }
229 nodesToAdd.add(nodesToAdd.get(0)); // close the circle
230 if (existingWay != null && existingWay.getNodesCount() >= 3) {
231 nodesToAdd = orderNodesByWay(nodesToAdd, existingWay);
232 } else {
233 nodesToAdd = orderNodesByTrafficHand(nodesToAdd);
234 }
235 if (existingWay == null) {
236 Way newWay = new Way();
237 newWay.setNodes(nodesToAdd);
238 cmds.add(new AddCommand(ds, newWay));
239 } else {
240 Way newWay = new Way(existingWay);
241 newWay.setNodes(nodesToAdd);
242 cmds.add(new ChangeCommand(ds, existingWay, newWay));
243 }
244
245 MainApplication.undoRedo.add(new SequenceCommand(tr("Create Circle"), cmds));
246 }
247
248 /**
249 * Order nodes according to left/right hand traffic.
250 * @param nodes Nodes list to be ordered.
251 * @return Modified nodes list ordered according hand traffic.
252 */
253 private static List<Node> orderNodesByTrafficHand(List<Node> nodes) {
254 boolean rightHandTraffic = true;
255 for (Node n: nodes) {
256 if (!RightAndLefthandTraffic.isRightHandTraffic(n.getCoor())) {
257 rightHandTraffic = false;
258 break;
259 }
260 }
261 if (rightHandTraffic == Geometry.isClockwise(nodes)) {
262 Collections.reverse(nodes);
263 }
264 return nodes;
265 }
266
267 /**
268 * Order nodes according to way direction.
269 * @param nodes Nodes list to be ordered.
270 * @param way Way used to determine direction.
271 * @return Modified nodes list with same direction as way.
272 */
273 private static List<Node> orderNodesByWay(List<Node> nodes, Way way) {
274 List<Node> wayNodes = way.getNodes();
275 if (!way.isClosed()) {
276 wayNodes.add(wayNodes.get(0));
277 }
278 if (Geometry.isClockwise(wayNodes) != Geometry.isClockwise(nodes)) {
279 Collections.reverse(nodes);
280 }
281 return nodes;
282 }
283
284 private static void notifyNodesNotOnCircle() {
285 new Notification(
286 tr("Those nodes are not in a circle. Aborting."))
287 .setIcon(JOptionPane.WARNING_MESSAGE)
288 .show();
289 }
290
291 @Override
292 protected void updateEnabledState() {
293 updateEnabledStateOnCurrentSelection();
294 }
295
296 @Override
297 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
298 setEnabled(selection != null && !selection.isEmpty());
299 }
300}
Note: See TracBrowser for help on using the repository browser.