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