]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network.ui/src/org/simantics/district/network/ui/DNEdgeBuilder.java
7ed99c363be31a83dd139534f08b71be812b33d3
[simantics/district.git] / org.simantics.district.network.ui / src / org / simantics / district / network / ui / DNEdgeBuilder.java
1 package org.simantics.district.network.ui;
2
3 import java.awt.geom.Rectangle2D;
4 import java.util.ArrayList;
5 import java.util.Collection;
6 import java.util.List;
7 import java.util.Optional;
8
9 import org.simantics.databoard.Bindings;
10 import org.simantics.db.Resource;
11 import org.simantics.db.WriteGraph;
12 import org.simantics.db.common.request.ObjectsWithType;
13 import org.simantics.db.exception.BindingException;
14 import org.simantics.db.exception.DatabaseException;
15 import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;
16 import org.simantics.db.exception.ServiceException;
17 import org.simantics.db.layer0.util.Layer0Utils;
18 import org.simantics.diagram.stubs.DiagramResource;
19 import org.simantics.diagram.synchronization.IModifiableSynchronizationContext;
20 import org.simantics.diagram.synchronization.SynchronizationHints;
21 import org.simantics.diagram.synchronization.graph.GraphSynchronizationHints;
22 import org.simantics.diagram.synchronization.graph.layer.GraphLayerManager;
23 import org.simantics.district.network.DistrictNetworkUtil;
24 import org.simantics.district.network.ontology.DistrictNetworkResource;
25 import org.simantics.g2d.diagram.IDiagram;
26 import org.simantics.layer0.Layer0;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 import com.vividsolutions.jts.geom.Envelope;
31 import com.vividsolutions.jts.index.quadtree.Quadtree;
32
33 public class DNEdgeBuilder {
34
35     private static final Logger LOGGER = LoggerFactory.getLogger(DNEdgeBuilder.class);
36
37     private Resource diagramResource;
38     private IDiagram diagram;
39     private GraphLayerManager glm;
40
41     public DNEdgeBuilder(Resource diagramResource, IDiagram diagram) {
42         this.diagramResource = diagramResource;
43         this.diagram = diagram;
44         
45         IModifiableSynchronizationContext context = diagram.getHint(SynchronizationHints.CONTEXT);
46         glm = context.get(GraphSynchronizationHints.GRAPH_LAYER_MANAGER);
47     }
48
49     public static Optional<Resource> create(WriteGraph graph, Resource diagramResource, double[] start, double startElevation, double[] end, double endElevation, double padding) throws DatabaseException {
50         Collection<Resource> vertices = graph.syncRequest(new ObjectsWithType(diagramResource, Layer0.getInstance(graph).ConsistsOf, DistrictNetworkResource.getInstance(graph).Vertex));
51         double halfPadding = padding / 2;
52
53         Quadtree vv = new Quadtree();
54         for (Resource vertex : vertices) {
55             double[] coords = graph.getRelatedValue2(vertex, DiagramResource.getInstance(graph).HasLocation, Bindings.DOUBLE_ARRAY);
56             double x1 = coords[0] - halfPadding;
57             double y1= coords[1] - halfPadding;
58             double x2 = coords[0] + halfPadding;
59             double y2= coords[1] + halfPadding;
60             Envelope e = new Envelope(x1, x2, y1, y2);
61             vv.insert(e, new ResourceVertex(vertex, coords, false));
62         }
63         return create(graph, vv, diagramResource, null, start, startElevation, end, endElevation, padding, false);
64     }
65     
66     public static Optional<Resource> create(WriteGraph graph, Quadtree vertices, Resource diagramResource, Resource mapping, double[] start, double startElevation, double[] end, double endElevation, double padding, boolean writeElevationToEdgeFromPoints) throws DatabaseException {
67         
68         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
69
70      // 2. Add vertices
71         Resource startVertex = getOrCreateVertex(graph, diagramResource, vertices, start, startElevation, padding);
72         Resource endVertex = getOrCreateVertex(graph, diagramResource, vertices, end, endElevation, padding);
73         if (startVertex.equals(endVertex)) {
74             LOGGER.info("Circular edges are not supported, startVertex: {}, endVertex: {}", startVertex, endVertex);
75             return Optional.empty();
76         }
77         
78         // 1. Get diagram edge to construct
79         Resource edge = getOrCreateEdge(graph, diagramResource, mapping);
80         
81         if (writeElevationToEdgeFromPoints) {
82             graph.claimLiteral(edge, DN.Edge_HasElevation, calculateElevationFromVertices(graph, startVertex, endVertex), Bindings.DOUBLE);
83         }
84         
85         graph.claim(edge, DN.HasStartVertex, startVertex);
86         graph.claim(edge, DN.HasEndVertex, endVertex);
87         
88         // We need to put GraphLayer to newLayers so...
89 //        for (Resource layer : graph.getObjects(diagramResource, DiagramResource.getInstance(graph).HasLayer)) {
90 //            IGraphLayerUtil layerUtil = graph.adapt(graph.getSingleObject(layer, Layer0.getInstance(graph).InstanceOf), IGraphLayerUtil.class);
91 //            
92 //            GraphLayer gl = layerUtil.loadLayer(graph, layer);
93 //            gl.forEachTag(tag -> {
94 //                DiagramGraphUtil.tag(graph, startVertex, tag, true);
95 //                DiagramGraphUtil.tag(graph, endVertex, tag, true);
96 //            });
97 //        }
98 //        
99         return Optional.of(edge);
100     }
101     private static double calculateElevationFromVertices(WriteGraph graph, Resource startVertex, Resource endVertex) throws ManyObjectsForFunctionalRelationException, BindingException, ServiceException {
102         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
103         Double startElevation = graph.getPossibleRelatedValue(startVertex, DN.Vertex_HasElevation, Bindings.DOUBLE);
104         Double endElevation = graph.getPossibleRelatedValue(endVertex, DN.Vertex_HasElevation, Bindings.DOUBLE);
105         if (startElevation != null && endElevation != null) {
106             return (startElevation + endElevation) / 2;
107         }
108         return 0;
109     }
110
111     public void create(WriteGraph graph,  double[] start, double startElevation, double[] end, double endElevation, double padding) throws DatabaseException {
112         
113         Optional<Resource> edge = create(graph, diagramResource, start, startElevation, end, endElevation, padding);
114         // 7. Put the element on all the currently active layers if possible.
115         if (glm != null) {
116             putOnActiveLayer(graph, edge.get());
117         }
118         
119         Layer0Utils.addCommentMetadata(graph, "Added edge " + edge.get());
120         graph.markUndoPoint();
121     }
122     
123     private void putOnActiveLayer(WriteGraph graph, Resource res) throws DatabaseException {
124         glm.removeFromAllLayers(graph, res);
125         glm.putElementOnVisibleLayers(diagram, graph, res);
126     }
127
128     private static Resource getOrCreateVertex(WriteGraph graph, Resource diagramResource, Quadtree qtree, double[] coords, double elevation, double padding) throws DatabaseException {
129         Resource vertex = null;
130         double halfPadding = padding / 2;
131         double maxDistance = Double.MAX_VALUE;
132         double x1 = coords[0] - halfPadding;
133         double y1= coords[1] - halfPadding;
134         double x2 = coords[0] + halfPadding;
135         double y2= coords[1] + halfPadding;
136         Envelope e = new Envelope(x1, x2, y1, y2);
137         
138         List result = qtree.query(e);
139         List<ResourceVertex> vertices = (List<ResourceVertex>) result;
140         for (ResourceVertex vertx : vertices) {
141             Rectangle2D existing = new Rectangle2D.Double(vertx.coords[0] - halfPadding, vertx.coords[1] - halfPadding, padding, padding);
142             Rectangle2D tobecreated = new Rectangle2D.Double(x1, y1, padding, padding);
143             if (existing.intersects(tobecreated)) {
144                 double dist = Math.sqrt((Math.pow(coords[0] - vertx.coords[0], 2) + (Math.pow(coords[1] - vertx.coords[1], 2))));
145                 if (dist <= maxDistance) {
146                     vertex = vertx.vertex;
147                     maxDistance = dist;
148                 }
149             }
150         }
151         if (vertex == null) {
152             vertex = DistrictNetworkUtil.createVertex(graph, diagramResource, coords, elevation); 
153             qtree.insert(e, new ResourceVertex(vertex, coords, false));
154         }
155         return vertex;
156     }
157
158     private static Resource getOrCreateEdge(WriteGraph graph, Resource diagramResource, Resource mapping) throws DatabaseException {
159         return DistrictNetworkUtil.createEdge(graph, diagramResource, mapping);
160     }
161
162     public static class ResourceVertex {
163         
164         final boolean isConsumer;
165         final Resource vertex;
166         final double[] coords;
167         
168         public ResourceVertex(Resource vertex, double[] coords, boolean isConsumer) {
169             this.vertex = vertex;
170             this.coords = coords;
171             this.isConsumer = isConsumer;
172         }
173     }
174 }