// Called after returning from the update parameters routine.
        // You can examine the messages created from internal validation and change them if desired.
        public void UpdateMessages(IArray paramvalues, IGPEnvironmentManager pEnvMgr, IGPMessages Messages)
        {
            // Check for error messages
            IGPMessage msg = (IGPMessage)Messages;

            if (msg.IsError())
            {
                return;
            }

            // Get the first Input Parameter
            IGPParameter parameter = (IGPParameter)paramvalues.get_Element(0);

            // UnPackGPValue. This ensures you get the value either form the dataelement or GpVariable (ModelBuilder)
            IGPValue parameterValue = m_GPUtilities.UnpackGPValue(parameter);

            // Open the Input Dataset - Use DecodeFeatureLayer as the input might be a layer file or a feature layer from ArcMap.
            IFeatureClass inputFeatureClass;
            IQueryFilter  qf;

            m_GPUtilities.DecodeFeatureLayer(parameterValue, out inputFeatureClass, out qf);

            IGPParameter3 fieldParameter = (IGPParameter3)paramvalues.get_Element(1);
            string        fieldName      = fieldParameter.Value.GetAsText();

            // Check if the field already exists and provide a warning.
            int indexA = inputFeatureClass.FindField(fieldName);

            if (indexA > 0)
            {
                Messages.ReplaceWarning(1, "Field already exists. It will be overwritten.");
            }

            return;
        }
예제 #2
0
        // Execute: Execute the function given the array of the parameters
        public void Execute(IArray paramvalues, ITrackCancel trackcancel, IGPEnvironmentManager envMgr, IGPMessages message)
        {
            IFeatureClass outputFeatureClass = null;

            try
            {
                // get the input feature class
                IGPMultiValue inputFeatureClasses_Parameter = (IGPMultiValue)m_GPUtilities.UnpackGPValue(paramvalues.get_Element(0));
                layer[]       input_featureClasses          = new layer[inputFeatureClasses_Parameter.Count];
                for (int i = 0; i < inputFeatureClasses_Parameter.Count; i++)
                {
                    IGPValue inputFeatureClass_Parameter = inputFeatureClasses_Parameter.get_Value(i);

                    IFeatureClass inputFeatureClass;
                    IQueryFilter  inputQF;

                    m_GPUtilities.DecodeFeatureLayer(inputFeatureClass_Parameter, out inputFeatureClass, out inputQF);

                    input_featureClasses[i] = new layer()
                    {
                        featureclass = inputFeatureClass, qFilter = inputQF
                    };
                }


                if (input_featureClasses.Length == 0 || input_featureClasses.Any(w => w.featureclass == null))
                {
                    message.AddError(2, "Could not open one or more input dataset.");
                    return;
                }

                //IFields additionalFields = new FieldsClass();
                //additionalFields.AddField(FEATURE_SOURCE_FIELD_NAME, esriFieldType.esriFieldTypeString);
                //additionalFields.AddField(FEATURE_ID_FIELD_NAME, esriFieldType.esriFieldTypeInteger);
                //additionalFields.AddField(
                //    input_featureClasses[0].featureclass.Fields.get_Field(
                //    input_featureClasses[0].featureclass.Fields.FindField(
                //    input_featureClasses[0].featureclass.ShapeFieldName)));

                // create the output feature class
                IGPValue outputFeatureClass_Parameter = m_GPUtilities.UnpackGPValue(paramvalues.get_Element(1));
                outputFeatureClass = GPHelperFunctions.CreateFeatureClass(outputFeatureClass_Parameter, envMgr);

                if (outputFeatureClass == null)
                {
                    message.AddError(2, "Could not create output dataset.");
                    return;
                }



                IGPString curveTypeParameter = (IGPString)m_GPUtilities.UnpackGPValue(paramvalues.get_Element(2));
                ArcConstructionMethods method;
                if (!Enum.TryParse <ArcConstructionMethods>(curveTypeParameter.Value, true, out method))
                {
                    message.AddError(2, string.Format("The value {0} is not expected.  Expected values are: {1}.",
                                                      curveTypeParameter.Value,
                                                      string.Join(",", Enum.GetNames(typeof(ArcConstructionMethods)))));
                    return;
                }

                IStepProgressor stepPro = (IStepProgressor)trackcancel;
                GPHelperFunctions.dropSpatialIndex(outputFeatureClass);

                BoostVoronoi bv = new BoostVoronoi(100);

                double          minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue;
                List <site_key> point_sites   = new List <site_key>();
                List <site_key> segment_sites = new List <site_key>();

                for (short i = 0; i < input_featureClasses.Length; i++)
                {
                    layer l         = input_featureClasses[i];
                    int   featcount = l.featureclass.FeatureCount(l.qFilter);

                    stepPro.MinRange  = 0;
                    stepPro.MaxRange  = featcount;
                    stepPro.StepValue = (1);
                    stepPro.Message   = "Reading features";
                    stepPro.Position  = 0;
                    stepPro.Show();

                    IFeatureCursor cursor = null;
                    IFeature       row    = null;

                    try
                    {
                        cursor = l.featureclass.Search(l.qFilter, false);
                        while ((row = cursor.NextFeature()) != null)
                        {
                            stepPro.Step();
                            IPoint point = row.Shape as IPoint;
                            if (point != null)
                            {
                                double X = point.X;
                                double Y = point.Y;

                                minX = Math.Min(minX, X);
                                maxX = Math.Max(maxX, X);

                                minY = Math.Min(minY, Y);
                                maxY = Math.Max(maxY, Y);

                                bv.AddPoint(point.X, point.Y);
                                point_sites.Add(new site_key(i, row.OID));
                            }

                            IMultipoint multipoint = row.Shape as IMultipoint;
                            if (multipoint != null)
                            {
                                IPointCollection pointCollection = (IPointCollection)multipoint;
                                IEnumVertex      vertices        = pointCollection.EnumVertices;

                                IPoint vertex = null; int part, index;
                                vertices.Next(out vertex, out part, out index);

                                minX = Math.Min(minX, multipoint.Envelope.XMin);
                                maxX = Math.Max(maxX, multipoint.Envelope.XMax);

                                minY = Math.Min(minY, multipoint.Envelope.YMin);
                                maxY = Math.Max(maxY, multipoint.Envelope.YMax);

                                while (vertex != null)
                                {
                                    bv.AddPoint(vertex.X, vertex.Y);
                                    point_sites.Add(new site_key(i, row.OID));

                                    vertices.Next(out vertex, out part, out index);
                                }
                            }

                            IPolyline polyline = row.Shape as IPolyline;
                            if (polyline != null)
                            {
                                double fromX = polyline.FromPoint.X;
                                double fromY = polyline.FromPoint.Y;
                                double toX   = polyline.ToPoint.X;
                                double toY   = polyline.ToPoint.Y;

                                if (toX < fromX)
                                {
                                    minX = Math.Min(minX, toX);
                                    maxX = Math.Max(maxX, fromX);
                                }
                                else
                                {
                                    minX = Math.Min(minX, fromX);
                                    maxX = Math.Max(maxX, toX);
                                }

                                if (toY < fromY)
                                {
                                    minY = Math.Min(minY, toY);
                                    maxY = Math.Max(maxY, fromY);
                                }
                                else
                                {
                                    minY = Math.Min(minY, fromY);
                                    maxY = Math.Max(maxY, toY);
                                }

                                bv.AddSegment(
                                    polyline.FromPoint.X, polyline.FromPoint.Y,
                                    polyline.ToPoint.X, polyline.ToPoint.Y
                                    );


                                segment_sites.Add(new site_key(i, row.OID));
                            }

                            Marshal.ReleaseComObject(row);
                        }
                    }
                    finally
                    {
                        if (row != null)
                        {
                            Marshal.ReleaseComObject(row);
                        }
                        if (cursor != null)
                        {
                            Marshal.ReleaseComObject(cursor);
                        }

                        stepPro.Hide();
                    }
                }

                message.AddMessage(String.Format("{0}, {1} -> {2}, {3}", minX, minY, maxX, maxY));

                int width  = Math.Max((int)((maxX - minX) * 0.1), 1);
                int height = Math.Max((int)((maxY - minY) * 0.1), 1);

                maxX = maxX + width;
                minX = minX - width;
                maxY = maxY + height;
                minY = minY - height;

                message.AddMessage(String.Format("{0}, {1} -> {2}, {3}", minX, minY, maxX, maxY));
                bv.AddSegment(minX, minY, maxX, minY);
                segment_sites.Add(new site_key(-1, -1));
                bv.AddSegment(maxX, minY, maxX, maxY);
                segment_sites.Add(new site_key(-1, -1));
                bv.AddSegment(maxX, maxY, minX, maxY);
                segment_sites.Add(new site_key(-1, -1));
                bv.AddSegment(minX, maxY, minX, minY);
                segment_sites.Add(new site_key(-1, -1));

                stepPro.Message  = "Solve Voronoi";
                stepPro.MaxRange = 0;
                stepPro.MaxRange = 0;
                stepPro.Show();

                bv.Construct();

                stepPro.Hide();

                int featureSourceIndx = outputFeatureClass.Fields.FindField(FEATURE_SOURCE_FIELD_NAME);
                int featureIDIndx     = outputFeatureClass.Fields.FindField(FEATURE_ID_FIELD_NAME);

                IFeatureCursor inserts = null;
                IFeatureBuffer buffer  = null;
                try
                {
                    object            missing          = Type.Missing;
                    ISpatialReference spatialReference = ((IGeoDataset)outputFeatureClass).SpatialReference;
                    inserts = outputFeatureClass.Insert(false);
                    buffer  = outputFeatureClass.CreateFeatureBuffer();

                    List <Cell> cells = bv.Cells;
                    message.AddMessage(string.Format("{0} cells calculated", cells.Count));
                    List <Edge> edges = bv.Edges;
                    message.AddMessage(string.Format("{0} edges calculated", edges.Count));
                    List <Vertex> vertices = bv.Vertices;
                    message.AddMessage(string.Format("{0} vertexes calculated", vertices.Count));

                    stepPro.Message  = "Write cells";
                    stepPro.MaxRange = 0;
                    stepPro.MaxRange = cells.Count;
                    stepPro.Show();


                    for (int cellIndex = 0; cellIndex < cells.Count; cellIndex++)
                    {
                        try
                        {
                            if (cellIndex % 5000 == 0)
                            {
                                message.AddMessage(String.Format("{0}. {1} cells processed.", DateTime.Now, cellIndex));
                            }

                            Cell cell        = cells[cellIndex];
                            int  currentSite = cell.Site;
                            IGeometryCollection geometryCollection = new GeometryBagClass()
                            {
                                SpatialReference = spatialReference
                            };

                            //ignores any sliver cells
                            if (cell.IsOpen || cell.EdgesIndex.Count < 3)
                            {
                                continue;
                            }

                            ISegmentCollection segmentCollection = createSegments(cell, bv, method, spatialReference);

                            if (((IArea)segmentCollection).Area <= 0)
                            {
                                message.AddMessage("A invalid geometry has been detected, try reversing the orientation.");
                                ISegmentCollection reversed_segmentCollection = new PolygonClass()
                                {
                                    SpatialReference = spatialReference
                                };
                                for (int i = segmentCollection.SegmentCount - 1; i >= 0; i--)
                                {
                                    ISegment segment = (ISegment)segmentCollection.get_Segment(i);
                                    segment.ReverseOrientation();
                                    reversed_segmentCollection.AddSegment(segment);
                                }
                                segmentCollection = reversed_segmentCollection;
                            }

                            ((IPolygon)segmentCollection).SpatialReference = spatialReference;
                            if (((IArea)segmentCollection).Area <= 0)
                            {
                                message.AddWarning("An empty shell has been created");

                                for (int i = 0; i < segmentCollection.SegmentCount; i++)
                                {
                                    ISegment segment = (ISegment)segmentCollection.get_Segment(i);
                                    message.AddMessage(String.Format("From {0}, {1} To {2},{3}",
                                                                     segment.FromPoint.X, segment.FromPoint.Y,
                                                                     segment.ToPoint.X, segment.ToPoint.Y));
                                }
                            }


                            //set attributes
                            site_key sk = (currentSite >= point_sites.Count) ? segment_sites[currentSite - point_sites.Count] : point_sites[currentSite];
                            if (!sk.isEmpty)
                            {
                                buffer.set_Value(featureSourceIndx, input_featureClasses[sk.featureClassIndex].featureclass.AliasName);
                                buffer.set_Value(featureIDIndx, sk.objectID);
                            }
                            else
                            {
                                buffer.set_Value(featureSourceIndx, DBNull.Value);
                                buffer.set_Value(featureIDIndx, DBNull.Value);
                            }


                            IPolygon voronoiPolygon = (IPolygon)segmentCollection;
                            buffer.Shape = (IPolygon)voronoiPolygon;
                            inserts.InsertFeature(buffer);
                        }
                        catch (Exception e)
                        {
                            message.AddWarning("Failed to create a cell");
                        }
                    }
                }
                finally
                {
                    if (buffer != null)
                    {
                        Marshal.ReleaseComObject(buffer);
                    }
                    if (inserts != null)
                    {
                        Marshal.ReleaseComObject(inserts);
                    }
                }

                GPHelperFunctions.createSpatialIndex(outputFeatureClass);
            }
            catch (Exception exx)
            {
                message.AddError(2, exx.Message);
                message.AddMessage(exx.ToString());
            }
            finally
            {
                if (outputFeatureClass != null)
                {
                    Marshal.ReleaseComObject(outputFeatureClass);
                }

                ((IProgressor)trackcancel).Hide();
            }
        }
예제 #3
0
        public void Execute(IArray paramvalues,
                            ITrackCancel trackcancel,
                            IGPEnvironmentManager envMgr,
                            IGPMessages messages)
        {
            // Re-validate.
            IGPMessages ms = m_util.InternalValidate(ParameterInfo,
                                                     paramvalues,
                                                     false, false,
                                                     envMgr);


            messages.AddMessage("MWSW Boundary Generator, v. 0.0");

            if (((IGPMessage)(ms)).IsError())
            {
                messages.AddMessages(ms);
                return;
            }
            if (!AoGPParameter.ValidateAll(m_parms, paramvalues, messages))
            {
                return;
            }

            try {
                IGPValue  inlyr    = m_util.UnpackGPValue((paramvalues.get_Element(0) as IGPParameter).Value);
                IGPDouble ang_tol  = m_util.UnpackGPValue((paramvalues.get_Element(1) as IGPParameter).Value) as IGPDouble;
                IGPDouble dist_tol = m_util.UnpackGPValue((paramvalues.get_Element(2) as IGPParameter).Value) as IGPDouble;
                IGPValue  outlyr   = m_util.UnpackGPValue((paramvalues.get_Element(3) as IGPParameter).Value);

                //		DumpIt("In layer",inlyr,messages);
                //		DumpIt("Out layer",outlyr,typeof(IGPValue),messages);

                IFeatureClass inputfc;
                IQueryFilter  inputqf;
                m_util.DecodeFeatureLayer(inlyr, out inputfc, out inputqf);

                //			DumpIt("In Featureclass",inputfc,typeof(IFeatureClass),messages);
                //			DumpIt("In QF",inputqf,typeof(IQueryFilter),messages);

                messages.AddMessage("In angle tolerance: " + ang_tol.Value);
                messages.AddMessage("In distance tolerance: " + dist_tol.Value);
                messages.AddMessage("Input featureclass: " + inputfc.AliasName);
                messages.AddMessage("Output path: " + outlyr.GetAsText());

                trackcancel.Progressor.Show();
                trackcancel.Progressor.Message = "Processing...";

                string             outp_txt = outlyr.GetAsText();
                AoFeatureClassName fcname   = new AoFeatureClassName(outp_txt);
                ISpatialReference  spref    = AoTable.From(inputfc)[inputfc.ShapeFieldName].Field.GeometryDef.SpatialReference;

                string shapename = fcname.ShapeFieldName != "" ? fcname.ShapeFieldName : "Shape";
                m_outp_schema[shapename] = AoField.Shape(shapename,
                                                         esriGeometryType.esriGeometryPolyline,
                                                         spref);


                // TODO: shapefiles seem to get an FID automatically,
                //   while geodb needs an 'OBJECTID',
                //   who knows about other workspace types?
                // Is there a way to figure this out w/o looking at the type?

                IFeatureClass outputfc =
                    fcname.Workspace.CreateFeatureClass(fcname.Basename,
                                                        m_outp_schema.Fields,
                                                        null,
                                                        null,
                                                        esriFeatureType.esriFTSimple,
                                                        shapename,
                                                        "");

                IStepProgressor progressor = trackcancel.Progressor as IStepProgressor;
                progressor.MaxRange = 200;

                BGenImp implementation = new BGenImp(spref, ang_tol.Value, dist_tol.Value);
                implementation.Run(inputfc, outputfc, delegate(double howfar) {
                    progressor.Position = (int)(200.0 * howfar);
                });

                messages.AddMessage("Finished, worked through " + implementation.TotalSegments + " line segments total.");
                return;
            } catch (Exception e) {
                while (e != null)
                {
                    messages.AddError(1, "Exception: " + e.Message);
                    e = e.InnerException;
                }
            }
        }
예제 #4
0
        public void Execute(IArray paramvalues, ITrackCancel trackcancel, IGPEnvironmentManager envMgr, IGPMessages message)
        {
            // Get Parameters
            IGPParameter3 inputParameter   = (IGPParameter3)paramvalues.get_Element(0);
            IGPParameter3 polygonParameter = (IGPParameter3)paramvalues.get_Element(1);
            IGPParameter3 outputParameter  = (IGPParameter3)paramvalues.get_Element(2);
            IGPParameter3 fieldParameter   = (IGPParameter3)paramvalues.get_Element(3);

            // UnPackGPValue. This ensures you get the value from either the dataelement or GpVariable (ModelBuilder)
            IGPValue inputParameterValue   = m_GPUtilities.UnpackGPValue(inputParameter);
            IGPValue polygonParameterValue = m_GPUtilities.UnpackGPValue(polygonParameter);
            IGPValue outputParameterValue  = m_GPUtilities.UnpackGPValue(outputParameter);
            IGPValue fieldParameterValue   = m_GPUtilities.UnpackGPValue(fieldParameter);

            // Decode Input Feature Layers
            IFeatureClass inputFeatureClass;
            IFeatureClass polygonFeatureClass;

            IQueryFilter inputFeatureClassQF;
            IQueryFilter polygonFeatureClassQF;

            m_GPUtilities.DecodeFeatureLayer(inputParameterValue, out inputFeatureClass, out inputFeatureClassQF);
            m_GPUtilities.DecodeFeatureLayer(polygonParameterValue, out polygonFeatureClass, out polygonFeatureClassQF);

            if (inputFeatureClass == null)
            {
                message.AddError(2, "Could not open input dataset.");
                return;
            }

            if (polygonFeatureClass == null)
            {
                message.AddError(2, "Could not open clipping polygon dataset.");
                return;
            }

            if (polygonFeatureClass.FeatureCount(null) > 1)
            {
                message.AddWarning("Clipping polygon feature class contains more than one feature.");
            }

            // Create the Geoprocessor
            Geoprocessor gp = new Geoprocessor();

            // Create Output Polygon Feature Class
            CreateFeatureclass cfc      = new CreateFeatureclass();
            IName               name    = m_GPUtilities.CreateFeatureClassName(outputParameterValue.GetAsText());
            IDatasetName        dsName  = name as IDatasetName;
            IFeatureClassName   fcName  = dsName as IFeatureClassName;
            IFeatureDatasetName fdsName = fcName.FeatureDatasetName as IFeatureDatasetName;

            // Check if output is in a FeatureDataset or not. Set the output path parameter for CreateFeatureClass tool.
            if (fdsName != null)
            {
                cfc.out_path = fdsName;
            }
            else
            {
                cfc.out_path = dsName.WorkspaceName.PathName;
            }

            // Set the output Coordinate System for CreateFeatureClass tool.
            // ISpatialReference3 sr = null;
            IGPEnvironment env = envMgr.FindEnvironment("outputCoordinateSystem");

            // Same as Input
            if (env.Value.IsEmpty())
            {
                IGeoDataset ds = inputFeatureClass as IGeoDataset;
                cfc.spatial_reference = ds.SpatialReference as ISpatialReference3;
            }
            // Use the environment setting
            else
            {
                IGPCoordinateSystem cs = env.Value as IGPCoordinateSystem;
                cfc.spatial_reference = cs.SpatialReference as ISpatialReference3;
            }

            // Remaining properties for Create Feature Class Tool
            cfc.out_name      = dsName.Name;
            cfc.geometry_type = "POLYGON";

            // Execute Geoprocessor
            gp.Execute(cfc, null);

            // Get Unique Field
            int    iField      = inputFeatureClass.FindField(fieldParameterValue.GetAsText());
            IField uniqueField = inputFeatureClass.Fields.get_Field(iField);

            // Extract Clipping Polygon Geometry
            IFeature polygonFeature  = polygonFeatureClass.GetFeature(0);
            IPolygon clippingPolygon = (IPolygon)polygonFeature.Shape;

            // Spatial Filter
            ISpatialFilter spatialFilter = new SpatialFilterClass();

            spatialFilter.Geometry   = polygonFeature.ShapeCopy;
            spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains;

            // Debug Message
            message.AddMessage("Generating TIN...");

            // Create TIN
            ITinEdit tinEdit = new TinClass();

            // Advanced TIN Functions
            ITinAdvanced2 tinAdv = (ITinAdvanced2)tinEdit;

            try
            {
                // Initialize New TIN
                IGeoDataset gds = inputFeatureClass as IGeoDataset;
                tinEdit.InitNew(gds.Extent);

                // Add Mass Points to TIN
                tinEdit.StartEditing();
                tinEdit.AddFromFeatureClass(inputFeatureClass, spatialFilter, uniqueField, uniqueField, esriTinSurfaceType.esriTinMassPoint);
                tinEdit.Refresh();

                // Get TIN Nodes
                ITinNodeCollection tinNodeCollection = (ITinNodeCollection)tinEdit;

                // Report Node Count
                message.AddMessage("Input Node Count: " + inputFeatureClass.FeatureCount(null).ToString());
                message.AddMessage("TIN Node Count: " + tinNodeCollection.NodeCount.ToString());

                // Open Output Feature Class
                IFeatureClass outputFeatureClass = m_GPUtilities.OpenFeatureClassFromString(outputParameterValue.GetAsText());

                // Debug Message
                message.AddMessage("Generating Polygons...");

                // Create Voronoi Polygons
                tinNodeCollection.ConvertToVoronoiRegions(outputFeatureClass, null, clippingPolygon, "", "");

                // Release COM Objects
                tinEdit.StopEditing(false);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(tinNodeCollection);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(tinEdit);
            }
            catch (Exception ex)
            {
                message.AddError(2, ex.Message);
            }
        }