]> gerrit.simantics Code Review - simantics/district.git/blob
ef2e21fed709518ca5c7c21075018526f0474dc6
[simantics/district.git] /
1 package org.simantics.district.network.ui.adapters;
2
3 import java.awt.Color;
4 import java.awt.Shape;
5 import java.awt.geom.AffineTransform;
6 import java.awt.geom.Line2D;
7 import java.awt.geom.Path2D;
8 import java.awt.geom.PathIterator;
9 import java.awt.geom.Point2D;
10 import java.awt.geom.Rectangle2D;
11 import java.util.Collection;
12 import java.util.Collections;
13
14 import org.simantics.district.network.ModelledCRS;
15 import org.simantics.district.network.ui.DistrictNetworkEdge;
16 import org.simantics.district.network.ui.nodes.DistrictNetworkEdgeNode;
17 import org.simantics.g2d.connection.handler.ConnectionHandler;
18 import org.simantics.g2d.diagram.handler.PickRequest.PickPolicy;
19 import org.simantics.g2d.diagram.handler.Topology.Connection;
20 import org.simantics.g2d.element.ElementClass;
21 import org.simantics.g2d.element.ElementUtils;
22 import org.simantics.g2d.element.IElement;
23 import org.simantics.g2d.element.SceneGraphNodeKey;
24 import org.simantics.g2d.element.handler.InternalSize;
25 import org.simantics.g2d.element.handler.Outline;
26 import org.simantics.g2d.element.handler.Pick;
27 import org.simantics.g2d.element.handler.SceneGraph;
28 import org.simantics.g2d.element.handler.impl.ConnectionSelectionOutline;
29 import org.simantics.g2d.element.handler.impl.DefaultTransform;
30 import org.simantics.g2d.element.handler.impl.SimpleElementLayers;
31 import org.simantics.maps.MapScalingTransform;
32 import org.simantics.scenegraph.g2d.G2DParentNode;
33 import org.simantics.scenegraph.g2d.nodes.SVGNode;
34 import org.simantics.scenegraph.utils.NodeUtil;
35 import org.simantics.utils.datastructures.hints.IHintContext.Key;
36 import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public class DistrictNetworkEdgeElement {
41
42     public static final Key KEY_DN_EDGE = new KeyOf(DistrictNetworkEdge.class, "DN_EDGE");
43     public static final Key KEY_DN_EDGE_NODE = new SceneGraphNodeKey(DistrictNetworkEdgeNode.class, "DN_EDGE_NODE");
44     public static final Key KEY_DN_EDGE_SYMBOL_NODE = new SceneGraphNodeKey(DistrictNetworkEdgeNode.class, "DN_EDGE_SYMBOL_NODE");
45
46     public static final ElementClass CLASS =
47             ElementClass.compile(
48                     DefaultTransform.INSTANCE,
49                     DNEdgeInternalSize.INSTANCE,
50                     DNEdgeSceneGraph.INSTANCE,
51                     DNEdgeConnectionHandler.INSTANCE,
52                     SimpleElementLayers.INSTANCE,
53                     // TODO: do we need this and does it work?
54                     ConnectionSelectionOutline.INSTANCE,
55                     DistrictNetworkAdditionalColor.INSTANCE
56             ).setId(DistrictNetworkEdgeElement.class.getSimpleName());
57
58     static final class DNEdgeSceneGraph implements SceneGraph {
59
60         public static final DNEdgeSceneGraph INSTANCE = new DNEdgeSceneGraph();
61
62         private static final long serialVersionUID = 68135568495835923L;
63
64         @Override
65         public void init(IElement edgeElement, G2DParentNode parent) {
66             DistrictNetworkEdge edge = edgeElement.getHint(KEY_DN_EDGE);
67             if (edge == null) {
68                 cleanup(edgeElement);
69             } else {
70                 DistrictNetworkEdgeNode node = edgeElement.getHint(KEY_DN_EDGE_NODE);
71                 if (node == null) {
72                     node = parent.addNode(ElementUtils.generateNodeId(edgeElement), DistrictNetworkEdgeNode.class);
73                     edgeElement.setHint(KEY_DN_EDGE_NODE, node);
74                     
75                     SVGNode symbol = node.addNode(ElementUtils.generateNodeId(edgeElement), SVGNode.class);
76                     edgeElement.setHint(KEY_DN_EDGE_SYMBOL_NODE, symbol);
77                 }
78                 
79                 node.setColor(ElementUtils.getAdditionalColor(edgeElement, Color.BLUE));
80                 
81                 node.setDNEdge(edge);
82                 AffineTransform at = ElementUtils.getTransform(edgeElement);
83                 if (at != null)
84                     node.setTransform(at);
85             }
86         }
87
88         @Override
89         public void cleanup(IElement edge) {
90             ElementUtils.removePossibleNode(edge, KEY_DN_EDGE_SYMBOL_NODE);
91             ElementUtils.removePossibleNode(edge, KEY_DN_EDGE_NODE);
92             edge.removeHint(KEY_DN_EDGE_NODE);
93             edge.removeHint(KEY_DN_EDGE_SYMBOL_NODE);
94         }
95     }
96
97     static final class DNEdgeInternalSize implements InternalSize, Outline, Pick {
98
99         private static final Logger LOGGER = LoggerFactory.getLogger(DNEdgeInternalSize.class);
100
101         private static final long serialVersionUID = -7346653820911240628L;
102
103         public static final DNEdgeInternalSize INSTANCE = new DNEdgeInternalSize();
104
105         @Override
106         public Rectangle2D getBounds(IElement e, Rectangle2D size) {
107             DistrictNetworkEdge edge = e.getHint(KEY_DN_EDGE);
108             if (size == null)
109                 size = new Rectangle2D.Double();
110             if (edge != null)
111                 size.setFrame(DistrictNetworkEdgeNode.calculatePath(edge, null, false).getBounds2D());
112             else
113                 LOGGER.debug("Element {} does not have edge!", e);
114
115             return size;
116         }
117
118         @Override
119         public Shape getElementShape(IElement e) {
120             DistrictNetworkEdge edge = e.getHint(KEY_DN_EDGE);
121             if (edge != null) {
122                 return DistrictNetworkEdgeNode.calculatePath(edge, null, false);
123             } else {
124                 return getBounds(e, null);
125             }
126         }
127
128         @Override
129         public boolean pickTest(IElement e, Shape s, PickPolicy policy) {
130             DistrictNetworkEdge edge = e.getHint(KEY_DN_EDGE);
131             if (edge != null) {
132                 Rectangle2D bounds = getBounds(s);
133                 switch (policy) {
134                 case PICK_CONTAINED_OBJECTS:    return pickContainedObjects(edge, bounds);
135                 case PICK_INTERSECTING_OBJECTS: return pickIntersectingObjects(e, edge, bounds);
136                 }
137                 return false;
138             }
139
140             return false;
141         }
142
143         private boolean pickContainedObjects(DistrictNetworkEdge edge, Rectangle2D bounds) {
144             double bminx = bounds.getMinX() / MapScalingTransform.getScaleX();
145             double bminy = bounds.getMinY() / MapScalingTransform.getScaleY();
146             double bmaxx = bounds.getMaxX() / MapScalingTransform.getScaleX();
147             double bmaxy = bounds.getMaxY() / MapScalingTransform.getScaleY();
148
149             double bsminx = ModelledCRS.xToLongitude(bminx);
150             double bsminy = ModelledCRS.yToLatitude(-bminy); // Invert for Simantics diagram coordinate system
151             double bsmaxx = ModelledCRS.xToLongitude(bmaxx);
152             double bsmaxy = ModelledCRS.yToLatitude(-bmaxy); // Invert for Simantics diagram coordinate system
153
154             double boundsMinY = Math.min(bsminy, bsmaxy);
155             double boundsMaxY = Math.max(bsminy, bsmaxy);
156
157             Point2D start = edge.getStartPoint();
158             Point2D end = edge.getEndPoint();
159
160             double eminx = Math.min(start.getX(), end.getX());
161             double eminy = Math.min(start.getY(), end.getY());
162             double emaxx = Math.max(start.getX(), end.getX());
163             double emaxy = Math.max(start.getY(), end.getY());
164
165             return eminx >= bsminx && eminy >= boundsMinY && emaxx <= bsmaxx && emaxy <= boundsMaxY;
166         }
167
168         private boolean pickIntersectingObjects(IElement e, DistrictNetworkEdge edge, Rectangle2D bounds) {
169             double dx = bounds.getWidth() / MapScalingTransform.getScaleX();
170             double dy = bounds.getHeight() / MapScalingTransform.getScaleY();
171             
172             // Half the diagonal + half of the line width
173             DistrictNetworkEdgeNode node = e.getHint(KEY_DN_EDGE_NODE);
174             AffineTransform at = NodeUtil.getLocalToGlobalTransform(node);
175             
176             Path2D path = node.getPath();
177             if (path == null)
178                 return false;
179             
180             double lineWidth = node.getStrokeWidth(at, true);
181             double tolerance = Math.sqrt(dx * dx + dy * dy) / 2 + lineWidth / 2;
182             
183             double sx = bounds.getCenterX() / MapScalingTransform.getScaleX();
184             double sy = bounds.getCenterY() / MapScalingTransform.getScaleY();
185             
186             double coords[] = new double[6];
187             Point2D prevPoint = new Point2D.Double(), curPoint = new Point2D.Double();
188             Line2D line = new Line2D.Double();
189             for (PathIterator it = path.getPathIterator(null); !it.isDone(); it.next()) {
190                 int type = it.currentSegment(coords);
191                 switch (type) {
192                 case PathIterator.SEG_MOVETO:
193                     curPoint.setLocation(coords[0], coords[1]);
194                     break;
195                 case PathIterator.SEG_LINETO:
196                     prevPoint.setLocation(curPoint);
197                     curPoint.setLocation(coords[0], coords[1]);
198                     line.setLine(prevPoint, curPoint);
199                     double distSq = line.ptSegDistSq(sx, sy);
200 //                    System.out.println("s: " + sx + ", " + sy);
201 //                    System.out.println("ss: " + ssx + ", " + ssy);
202 //                    System.out.println("p1: " + edge.getStartPoint());
203 //                    System.out.println("p2: " + edge.getEndPoint());
204 //                    System.out.println("line: " + "(" + line.getX1() + ", " + line.getY1() + ", " + line.getX2() + ", " + line.getY2() + ")");
205 //                    System.out.println("distance from line is " + Math.sqrt(distSq) + " with tolerance " + tolerance);
206                     if (distSq <= tolerance * tolerance)
207                         return true; 
208                     break;
209                 default:
210                     LOGGER.error("Invalid edge path", new IllegalStateException());
211                     return false;
212                 }
213             }
214             
215             return false;
216         }
217
218         private Rectangle2D getBounds(Shape shape) {
219             if (shape instanceof Rectangle2D)
220                 return (Rectangle2D) shape;
221             return shape.getBounds2D();
222         }
223
224     }
225
226     static class DNEdgeConnectionHandler implements ConnectionHandler {
227
228         private static final long serialVersionUID = -6882671891381761687L;
229
230         public static final DNEdgeConnectionHandler INSTANCE = new DNEdgeConnectionHandler();
231
232         @Override
233         public Collection<IElement> getChildren(IElement connection, Collection<IElement> result) {
234             return Collections.emptyList();
235         }
236
237         @Override
238         public Collection<IElement> getBranchPoints(IElement connection, Collection<IElement> result) {
239             return Collections.emptyList();
240         }
241
242         @Override
243         public Collection<IElement> getSegments(IElement connection, Collection<IElement> result) {
244             return Collections.emptyList();
245         }
246
247         @Override
248         public Collection<Connection> getTerminalConnections(IElement connection, Collection<Connection> result) {
249             return Collections.emptyList();
250         }
251     }
252
253 }