]> gerrit.simantics Code Review - simantics/district.git/blobdiff - org.simantics.district.network.ui/src/org/simantics/district/network/ui/DNEdgeBuilder.java
Elimination of compiler warnings.
[simantics/district.git] / org.simantics.district.network.ui / src / org / simantics / district / network / ui / DNEdgeBuilder.java
index 687ca337b85689f6dd749fcba1fbfde04a9bec7b..e47e9a8743f8f66557cbbcf8a228fe846621a168 100644 (file)
@@ -2,26 +2,37 @@ package org.simantics.district.network.ui;
 
 import java.awt.geom.Rectangle2D;
 import java.util.Collection;
+import java.util.List;
+import java.util.Optional;
 
 import org.simantics.databoard.Bindings;
 import org.simantics.db.Resource;
 import org.simantics.db.WriteGraph;
 import org.simantics.db.common.request.ObjectsWithType;
+import org.simantics.db.exception.BindingException;
 import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;
+import org.simantics.db.exception.ServiceException;
 import org.simantics.db.layer0.util.Layer0Utils;
 import org.simantics.diagram.stubs.DiagramResource;
 import org.simantics.diagram.synchronization.IModifiableSynchronizationContext;
 import org.simantics.diagram.synchronization.SynchronizationHints;
-import org.simantics.diagram.synchronization.graph.AddElement;
 import org.simantics.diagram.synchronization.graph.GraphSynchronizationHints;
 import org.simantics.diagram.synchronization.graph.layer.GraphLayerManager;
 import org.simantics.district.network.DistrictNetworkUtil;
 import org.simantics.district.network.ontology.DistrictNetworkResource;
 import org.simantics.g2d.diagram.IDiagram;
 import org.simantics.layer0.Layer0;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.vividsolutions.jts.geom.Envelope;
+import com.vividsolutions.jts.index.quadtree.Quadtree;
 
 public class DNEdgeBuilder {
-    
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(DNEdgeBuilder.class);
+
     private Resource diagramResource;
     private IDiagram diagram;
     private GraphLayerManager glm;
@@ -34,32 +45,77 @@ public class DNEdgeBuilder {
         glm = context.get(GraphSynchronizationHints.GRAPH_LAYER_MANAGER);
     }
 
-    public void create(WriteGraph graph, double[] start, double[] end) throws DatabaseException {
+    public static Optional<Resource> create(WriteGraph graph, Resource diagramResource, double[] start, double startElevation, double[] end, double endElevation, double padding) throws DatabaseException {
+        Collection<Resource> vertices = graph.syncRequest(new ObjectsWithType(diagramResource, Layer0.getInstance(graph).ConsistsOf, DistrictNetworkResource.getInstance(graph).Vertex));
+        double halfPadding = padding / 2;
+
+        Quadtree vv = new Quadtree();
+        for (Resource vertex : vertices) {
+            double[] coords = graph.getRelatedValue2(vertex, DiagramResource.getInstance(graph).HasLocation, Bindings.DOUBLE_ARRAY);
+            double x1 = coords[0] - halfPadding;
+            double y1= coords[1] - halfPadding;
+            double x2 = coords[0] + halfPadding;
+            double y2= coords[1] + halfPadding;
+            Envelope e = new Envelope(x1, x2, y1, y2);
+            vv.insert(e, new ResourceVertex(vertex, coords, false));
+        }
+        return create(graph, vv, diagramResource, null, start, startElevation, end, endElevation, padding, false);
+    }
+    
+    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 {
         
         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
+
+     // 2. Add vertices
+        Resource startVertex = getOrCreateVertex(graph, diagramResource, vertices, start, startElevation, padding);
+        Resource endVertex = getOrCreateVertex(graph, diagramResource, vertices, end, endElevation, padding);
+        if (startVertex.equals(endVertex)) {
+            LOGGER.info("Circular edges are not supported, startVertex: {}, endVertex: {}", startVertex, endVertex);
+            return Optional.empty();
+        }
         
         // 1. Get diagram edge to construct
-        Resource edge = getOrCreateEdge(graph);
-        
-        // 1.1 Give running name to connection and increment the counter attached to the diagram.
-        AddElement.claimFreshElementName(graph, diagramResource, edge);
+        Resource edge = getOrCreateEdge(graph, diagramResource, mapping);
         
-        // 2. Add vertices
-        Collection<Resource> vertices = graph.syncRequest(new ObjectsWithType(diagramResource, Layer0.getInstance(graph).ConsistsOf, DistrictNetworkResource.getInstance(graph).Vertex));
-        Resource startVertex = getOrCreateVertex(graph, vertices, start);
-        Resource endVertex = getOrCreateVertex(graph, vertices, end);
+        if (writeElevationToEdgeFromPoints) {
+            graph.claimLiteral(edge, DN.Edge_HasElevation, calculateElevationFromVertices(graph, startVertex, endVertex), Bindings.DOUBLE);
+        }
         
         graph.claim(edge, DN.HasStartVertex, startVertex);
         graph.claim(edge, DN.HasEndVertex, endVertex);
         
+        // We need to put GraphLayer to newLayers so...
+//        for (Resource layer : graph.getObjects(diagramResource, DiagramResource.getInstance(graph).HasLayer)) {
+//            IGraphLayerUtil layerUtil = graph.adapt(graph.getSingleObject(layer, Layer0.getInstance(graph).InstanceOf), IGraphLayerUtil.class);
+//            
+//            GraphLayer gl = layerUtil.loadLayer(graph, layer);
+//            gl.forEachTag(tag -> {
+//                DiagramGraphUtil.tag(graph, startVertex, tag, true);
+//                DiagramGraphUtil.tag(graph, endVertex, tag, true);
+//            });
+//        }
+//        
+        return Optional.of(edge);
+    }
+    private static double calculateElevationFromVertices(WriteGraph graph, Resource startVertex, Resource endVertex) throws ManyObjectsForFunctionalRelationException, BindingException, ServiceException {
+        DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
+        Double startElevation = graph.getPossibleRelatedValue(startVertex, DN.Vertex_HasElevation, Bindings.DOUBLE);
+        Double endElevation = graph.getPossibleRelatedValue(endVertex, DN.Vertex_HasElevation, Bindings.DOUBLE);
+        if (startElevation != null && endElevation != null) {
+            return (startElevation + endElevation) / 2;
+        }
+        return 0;
+    }
+
+    public void create(WriteGraph graph,  double[] start, double startElevation, double[] end, double endElevation, double padding) throws DatabaseException {
+        
+        Optional<Resource> edge = create(graph, diagramResource, start, startElevation, end, endElevation, padding);
         // 7. Put the element on all the currently active layers if possible.
         if (glm != null) {
-            putOnActiveLayer(graph, edge);
-            putOnActiveLayer(graph, startVertex);
-            putOnActiveLayer(graph, endVertex);
+            putOnActiveLayer(graph, edge.get());
         }
         
-        Layer0Utils.addCommentMetadata(graph, "Added edge " + edge);
+        Layer0Utils.addCommentMetadata(graph, "Added edge " + edge.get());
         graph.markUndoPoint();
     }
     
@@ -68,26 +124,51 @@ public class DNEdgeBuilder {
         glm.putElementOnVisibleLayers(diagram, graph, res);
     }
 
-    private Resource getOrCreateVertex(WriteGraph graph, Collection<Resource> vertices, double[] coords) throws DatabaseException {
+    private static Resource getOrCreateVertex(WriteGraph graph, Resource diagramResource, Quadtree qtree, double[] coords, double elevation, double padding) throws DatabaseException {
         Resource vertex = null;
-        for (Resource vertx : vertices) {
-            double[] existingCoords = graph.getRelatedValue2(vertx, DiagramResource.getInstance(graph).HasLocation, Bindings.DOUBLE_ARRAY);
-            Rectangle2D existing = new Rectangle2D.Double(existingCoords[0], existingCoords[1], 1, 1);
-            Rectangle2D tobecreated = new Rectangle2D.Double(coords[0], coords[1], 1, 1);
+        double halfPadding = padding / 2;
+        double maxDistance = Double.MAX_VALUE;
+        double x1 = coords[0] - halfPadding;
+        double y1= coords[1] - halfPadding;
+        double x2 = coords[0] + halfPadding;
+        double y2= coords[1] + halfPadding;
+        Envelope e = new Envelope(x1, x2, y1, y2);
+        
+        List<?> result = qtree.query(e);
+        @SuppressWarnings("unchecked")
+        List<ResourceVertex> vertices = (List<ResourceVertex>) result;
+        for (ResourceVertex vertx : vertices) {
+            Rectangle2D existing = new Rectangle2D.Double(vertx.coords[0] - halfPadding, vertx.coords[1] - halfPadding, padding, padding);
+            Rectangle2D tobecreated = new Rectangle2D.Double(x1, y1, padding, padding);
             if (existing.intersects(tobecreated)) {
-                vertex = vertx;
-                break;
+                double dist = Math.sqrt((Math.pow(coords[0] - vertx.coords[0], 2) + (Math.pow(coords[1] - vertx.coords[1], 2))));
+                if (dist <= maxDistance) {
+                    vertex = vertx.vertex;
+                    maxDistance = dist;
+                }
             }
         }
         if (vertex == null) {
-            vertex = DistrictNetworkUtil.createVertex(graph, diagramResource, coords); 
-            AddElement.claimFreshElementName(graph, diagramResource, vertex);
+            vertex = DistrictNetworkUtil.createVertex(graph, diagramResource, coords, elevation); 
+            qtree.insert(e, new ResourceVertex(vertex, coords, false));
         }
         return vertex;
     }
 
-    private Resource getOrCreateEdge(WriteGraph graph) throws DatabaseException {
-        return DistrictNetworkUtil.createEdge(graph, diagramResource);
+    private static Resource getOrCreateEdge(WriteGraph graph, Resource diagramResource, Resource mapping) throws DatabaseException {
+        return DistrictNetworkUtil.createEdge(graph, diagramResource, mapping);
     }
 
+    public static class ResourceVertex {
+        
+        final boolean isConsumer;
+        final Resource vertex;
+        final double[] coords;
+        
+        public ResourceVertex(Resource vertex, double[] coords, boolean isConsumer) {
+            this.vertex = vertex;
+            this.coords = coords;
+            this.isConsumer = isConsumer;
+        }
+    }
 }