Example #1
0
        private static IEnumerable <Feature> GetFeatures([CanBeNull] BasicFeatureLayer layer,
                                                         [NotNull] List <long> oids,
                                                         bool recycling = false)
        {
            if (layer == null)
            {
                yield break;
            }

            // TODO: Use layer search (there might habe been an issue with recycling?!)
            var featureClass = layer.GetTable();

            var filter = new QueryFilter
            {
                WhereClause =
                    $"{featureClass.GetDefinition().GetObjectIDField()} IN ({StringUtils.Concatenate(oids, ", ")})"
            };

            filter.OutputSpatialReference = layer.GetSpatialReference();

            foreach (var feature in GdbQueryUtils.GetFeatures(featureClass, filter, recycling))
            {
                yield return(feature);
            }
        }
        protected override async void OnClick()
        {
            SharedFunctions.Log("Starting To Create Reservoir Polygons");
            DateTime startTime = DateTime.Now;

            surfaces = new List <ReservoirSurface>();

            try
            {
                await Project.Current.SaveEditsAsync();

                await QueuedTask.Run(async() =>
                {
                    if (!SharedFunctions.LayerExists("DamCandidates") || !SharedFunctions.LayerExists("Contours"))
                    {
                        return;
                    }
                    damLayer     = MapView.Active.Map.FindLayers("DamCandidates").FirstOrDefault() as BasicFeatureLayer;
                    contourLayer = MapView.Active.Map.FindLayers("Contours").FirstOrDefault() as BasicFeatureLayer;

                    SpatialReference       = damLayer.GetSpatialReference();
                    reservoirSurfacesLayer = await CreatePolygonFeatureClass("ReservoirSurfaces");

                    ConstructPolygons();
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                DateTime endTime = DateTime.Now;
                SharedFunctions.Log("Analysed in " + (endTime - startTime).TotalSeconds.ToString() + " seconds");
            }
        }
        protected override async void OnClick()
        {
            SharedFunctions.Log("Search for candidate dams started");
            pointsIntervalOnContour = Convert.ToInt32(Parameter.PointIntervalBox.Text);
            DateTime startTime = DateTime.Now;

            chosenCandidates    = new List <CandidateDam>();
            PotentialCandidates = 0;

            var pd = new ProgressDialog("Search for candidate dams", "Canceled", 100, false);

            cps = new CancelableProgressorSource(pd);
            cps.Progressor.Max = 100;
            PointsAnalyzed     = 0;
            TotalPointsCount   = 0;

            try
            {
                await Project.Current.SaveEditsAsync();

                BasicFeatureLayer layer = null;

                await QueuedTask.Run(async() =>
                {
                    if (!SharedFunctions.LayerExists("ContourPoints"))
                    {
                        return;
                    }

                    CancellationToken ctoken = new CancellationToken();

                    //create line feature layer if it does not exist
                    BasicFeatureLayer damCandidatesLayer = await CreateDamFeatureClass("DamCandidates");

                    var contourPointsLayer = MapView.Active.Map.FindLayers("ContourPoints").FirstOrDefault();
                    layer = contourPointsLayer as BasicFeatureLayer;

                    // store the spatial reference of the current layer
                    SpatialReference = layer.GetSpatialReference();

                    //Cursor for selected points
                    RowCursor cursor = layer.GetSelection().Search();

                    //If no selection was set, use full points layer
                    if (layer.GetSelection().GetCount() == 0)
                    {
                        cursor = layer.Search();
                    }

                    Dictionary <int, SortedDictionary <int, SortedDictionary <long, MapPoint> > > contourHeights = new Dictionary <int, SortedDictionary <int, SortedDictionary <long, MapPoint> > >();

                    cps.Progressor.Status = "Loading ContourPoints into memory";
                    SharedFunctions.Log("Loading all ContourPoints into memory");
                    while (cursor.MoveNext())
                    {
                        if (ctoken.IsCancellationRequested)
                        {
                            SharedFunctions.Log("Canceled");
                            return;
                        }
                        using (Row row = cursor.Current)
                        {
                            var point         = row[1] as MapPoint;
                            var pointID       = (int)row[0];
                            var contourHeight = (int)(double)row[4];
                            var contourID     = (int)row[2];

                            if (!ContourLengths.ContainsKey(contourID))
                            {
                                ContourLengths.Add(contourID, (double)row["Shape_Length"]);
                            }
                            if (!contourHeights.ContainsKey((int)contourHeight))
                            {
                                contourHeights.Add((int)contourHeight, new SortedDictionary <int, SortedDictionary <long, MapPoint> >());
                            }
                            if (!contourHeights[contourHeight].ContainsKey((int)contourID))
                            {
                                contourHeights[contourHeight].Add((int)contourID, new SortedDictionary <long, MapPoint>());
                            }
                            contourHeights[contourHeight][(int)contourID].Add(pointID, point);
                            TotalPointsCount++;
                        }
                    }
                    cps.Progressor.Status = "Analyze Contours";
                    SharedFunctions.Log("Analyze Contours");
                    bool multiThreading = (Parameter.MultiThreadingBox == null || !Parameter.MultiThreadingBox.IsChecked.HasValue || Parameter.MultiThreadingBox.IsChecked.Value);
                    if (multiThreading)
                    {
                        HeightsToProcess = contourHeights.Keys.ToList();
                        int ThreadCount  = Math.Min(HeightsToProcess.Count, Environment.ProcessorCount);
                        SharedFunctions.Log("Divided work into " + ThreadCount + " threads...");
                        await Task.WhenAll(Enumerable.Range(1, ThreadCount).Select(c => Task.Run(
                                                                                       () =>
                        {
                            while (HeightsToProcess.Count > 0)    // && !ctoken.IsCancellationRequested)
                            {
                                int height = -1;
                                lock (HeightsToProcess)
                                {
                                    height = HeightsToProcess.FirstOrDefault();
                                    if (height != 0)
                                    {
                                        HeightsToProcess.Remove(height);
                                    }
                                }
                                if (height != -1)
                                {
                                    var calc = new Dictionary <int, SortedDictionary <int, SortedDictionary <long, MapPoint> > >();
                                    calc.Add(height, contourHeights[height]);
                                    AnalyseContourHeights(calc, ctoken);
                                }
                            }
                        }
                                                                                       , ctoken))
                                           );
                    }
                    else
                    {
                        //Single Thread:
                        AnalyseContourHeights(contourHeights, ctoken);
                    }
                    cps.Progressor.Status = "Saving all " + chosenCandidates.Count + " candidates";
                    SharedFunctions.Log("Saving all " + chosenCandidates.Count + " candidates");
                    foreach (var candidate in chosenCandidates)
                    {
                        if (ctoken.IsCancellationRequested)
                        {
                            SharedFunctions.Log("Canceled");
                            return;
                        }
                        //Create coordinates for Polyline Feature with height ContourHeight + 5 Meters!
                        List <Coordinate3D> coordinates = new List <Coordinate3D>()
                        {
                            new Coordinate3D(candidate.StartPoint.X, candidate.StartPoint.Y, candidate.ContourHeight + 5),
                            new Coordinate3D(candidate.EndPoint.X, candidate.EndPoint.Y, candidate.ContourHeight + 5)
                        };

                        //save all selected candidates into the db
                        var attributes = new Dictionary <string, object>
                        {
                            { "Shape", PolylineBuilder.CreatePolyline(coordinates) },
                            { "ContourID", (long)candidate.ContourID },
                            { "StartPointID", (long)candidate.StartPointID },
                            { "EndPointID", (long)candidate.EndPointID },
                            { "ContourHeight", (short)candidate.ContourHeight },
                            { "LengthRating", (float)candidate.Rating },
                            { "DistanceOnLine", (long)candidate.DistanceOnLine },
                            { "Length", (short)candidate.Length },
                            { "StartPointDistance", (long)candidate.StartPointDistance },
                            { "EndPointDistance", (long)candidate.EndPointDistance },
                            { "DamSpansContourStart", (short)(candidate.DamSpansContourStart ? 1 : 0) }
                        };
                        var editOp = new EditOperation()
                        {
                            Name = "Create dam candidate", SelectNewFeatures = false
                        };
                        editOp.Create(damCandidatesLayer, attributes);
                        ////Execute the operations
                        editOp.Execute();
                    }
                }, cps.Progressor);

                //save all edits
                await Project.Current.SaveEditsAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                DateTime endTime = DateTime.Now;
                SharedFunctions.Log("Analysed " + PotentialCandidates.ToString("N0") + " candidates ( " + chosenCandidates.Count.ToString("N0") + " selected) in " + (endTime - startTime).TotalSeconds.ToString("N") + " seconds");
            }
        }
Example #4
0
        /// <summary>
        /// Write rhino object to ArcGIS feature layer
        /// </summary>
        /// <param name="mapLayer"></param>
        /// <param name="ro"></param>
        public static async void ThrowItOverTheFence(BasicFeatureLayer mapLayer, RhinoObject ro, RhinoDoc rhinoDoc)
        {
            Mesh mesh = null;

            var createOperation = new EditOperation();

            var projection = mapLayer.GetSpatialReference();
            var origin     = getOrigin(rhinoDoc);

            switch (ro.Geometry.ObjectType)
            {
            case ObjectType.Point:
            {
                Point    pt = ro.Geometry as Point;
                MapPoint mp = ptToGis(pt.Location, origin);
                createOperation.Create(mapLayer, mp);
                await createOperation.ExecuteAsync();

                break;
            }

            case ObjectType.Surface:
            {
                Surface srf = ro.Geometry as Surface;
                if (!srf.IsPlanar())
                {
                    Console.Out.WriteLine($"Unable to send non-planar surfaces: Guid: ${ro.Id}");
                    break;
                }
                goto case ObjectType.Brep;
            }

            case ObjectType.Curve:
            {
                Curve c      = ro.Geometry as Curve;
                var   ptList = getPointsFromCurves(new List <Curve>()
                    {
                        c
                    });
                var gisPts   = ptList.Select(p => ptToGis(p, origin)).ToList();
                var polyline = PolylineBuilder.CreatePolyline(gisPts, projection);
                createOperation.Create(mapLayer, polyline);
                await createOperation.ExecuteAsync();

                break;
            }

            case ObjectType.Brep:
            {
                Brep brep = ro.Geometry as Brep;
                if (brep.IsSolid)
                {
                    mesh = Mesh.CreateFromBrep(brep, MeshingParameters.Default)[0];
                    goto case ObjectType.Mesh;
                }
                else
                {
                    var crvs = new List <Curve>();
                    foreach (BrepEdge ed in brep.Edges)
                    {
                        crvs.Add(ed.EdgeCurve);
                    }
                    var pts     = getPointsFromCurves(crvs);
                    var gisPts  = pts.Select(p => ptToGis(p, origin)).ToList();
                    var polygon = new PolygonBuilder(gisPts).ToGeometry();
                    createOperation.Create(mapLayer, polygon);
                    await createOperation.ExecuteAsync();

                    break;
                }
            }

            case ObjectType.Extrusion:
            {
                mesh = (ro.Geometry as Extrusion).GetMesh(MeshType.Default);
                goto case ObjectType.Mesh;
            }

            case ObjectType.Mesh:
            {
                mesh = mesh ?? ro.Geometry as Mesh;
                break;
            }

            default:
            {
                Console.Out.WriteLine($"Unable to send geometry type: ${ro.Geometry.ObjectType}");
                break;
            }
            }
        }