Exemplo n.º 1
0
void OGR::writeDensity(hexer::HexGrid *grid)
{
    int counter(0);
    for (hexer::HexIter iter = grid->hexBegin(); iter != grid->hexEnd(); ++iter)
    {

        hexer::HexInfo hi = *iter;
        OGRGeometryH polygon = collectHexagon(hi, grid);
        OGRFeatureH hFeature;

        hFeature = OGR_F_Create(OGR_L_GetLayerDefn(m_layer));
        OGR_F_SetFieldInteger( hFeature, OGR_F_GetFieldIndex(hFeature, "ID"),
            counter);
        OGR_F_SetFieldInteger( hFeature, OGR_F_GetFieldIndex(hFeature, "COUNT"),
            hi.m_density);

        OGR_F_SetGeometry(hFeature, polygon);
        OGR_G_DestroyGeometry(polygon);

        if( OGR_L_CreateFeature( m_layer, hFeature ) != OGRERR_NONE )
        {
            std::ostringstream oss;
            oss << "Unable to create feature for multipolygon with error '"
                << CPLGetLastErrorMsg() << "'";
            throw pdal::pdal_error(oss.str());
        }
        OGR_F_Destroy( hFeature );
        counter++;
    }
}
Exemplo n.º 2
0
void OGR::writeBoundary(hexer::HexGrid *grid)
{
    OGRGeometryH multi = OGR_G_CreateGeometry(wkbMultiPolygon);

    const std::vector<hexer::Path *>& paths = grid->rootPaths();
    for (auto pi = paths.begin(); pi != paths.end(); ++pi)
    {
        OGRGeometryH polygon = OGR_G_CreateGeometry(wkbPolygon);
        collectPath(*pi, polygon);

        if( OGR_G_AddGeometryDirectly(multi, polygon ) != OGRERR_NONE )
        {
            std::ostringstream oss;
            oss << "Unable to add polygon to multipolygon with error '"
                << CPLGetLastErrorMsg() << "'";
            throw pdal::pdal_error(oss.str());
        }
    }

    OGRFeatureH hFeature;

    hFeature = OGR_F_Create(OGR_L_GetLayerDefn(m_layer));
    OGR_F_SetFieldInteger( hFeature, OGR_F_GetFieldIndex(hFeature, "ID"), 0);

    OGR_F_SetGeometry(hFeature, multi);
    OGR_G_DestroyGeometry(multi);

    if( OGR_L_CreateFeature( m_layer, hFeature ) != OGRERR_NONE )
    {
        std::ostringstream oss;
        oss << "Unable to create feature for multipolygon with error '"
            << CPLGetLastErrorMsg() << "'";
        throw pdal::pdal_error(oss.str());
    }
    OGR_F_Destroy( hFeature );
}
Exemplo n.º 3
0
 void Feature::set (const Geometry &geom) {
     assert(geom.geometry_type() == geom_type);
     if (OGR_F_SetGeometry(feat, geom.handle()) != OGRERR_NONE) {
         throw runtime_error("Couldn't set geometry on feature.");
     }
 }
Exemplo n.º 4
0
int main(int argc, char* argv[])
{
    int rc = 0;

#ifdef HAVE_GDAL
    try
    {
        ::OGRRegisterAll();

        // Parse command-line options
        std::string in_file;
        std::string out_file;
        std::string out_frmt;
        {
            int on_arg = 1;
            while (on_arg < argc)
            {
                std::string arg(argv[on_arg]);
                if (arg == "-h")
                {
                    usage();
                    return 0;
                }
                else if (arg == "-formats")
                {
                    report_ogr_formats(std::cout);
                    return 0;
                }
                else if (arg == "-i" && (on_arg + 1 < argc))
                {
                    ++on_arg;
                    assert(on_arg < argc);
                    in_file = argv[on_arg];
                }
                else if (arg == "-o" && (on_arg + 1 < argc))
                {
                    ++on_arg;
                    assert(on_arg < argc);
                    out_file = argv[on_arg];
                    out_frmt = "ESRI Shapefile"; // default output format
                }
                else if (arg == "-f" && (on_arg + 1 < argc))
                {
                    ++on_arg;
                    assert(on_arg < argc);
                    out_frmt = argv[on_arg];
                }
                else
                {
                    throw std::runtime_error(std::string("unrecognized parameter: ") + arg);
                }
                ++on_arg;
            }

            if (in_file.empty() || out_file.empty() || out_frmt.empty())
            {
                throw std::runtime_error("missing input paremeters");
            }
        }

        //
        // Source
        //
        std::cout << "Source:" << "\n - dataset: " << in_file << std::endl;

        std::ifstream ifs;
        if (!liblas::Open(ifs, in_file.c_str()))
        {
            throw std::runtime_error(std::string("Can not open \'") + in_file + "\'");
        }
        liblas::Reader reader(ifs);

        //
        // Target
        //
        std::string const lyrname(out_file.substr(0, out_file.find_last_of('.')));

        std::cout << "Target:"
                  << "\n - format: " << out_frmt
                  << "\n - dataset: " << out_file
                  << "\n - layer: " << lyrname
                  << std::endl;

        OGRSFDriverH drv = OGRGetDriverByName(out_frmt.c_str());
        if (0 == drv)
        {
            throw std::runtime_error(out_frmt + " driver not available");
        }

        ogr_wrapper<OGRDataSourceH> ds(OGR_Dr_CreateDataSource(drv, out_file.c_str(), 0), OGR_DS_Destroy);
        if (0 == ds.get())
        {
            throw std::runtime_error(out_file + " datasource creation failed");
        }

        OGRLayerH lyr = OGR_DS_CreateLayer(ds, lyrname.c_str(), 0, wkbPoint25D, 0);
        if (0 == lyr)
        {
            throw std::runtime_error(out_file + " layer creation failed");
        }

        // Prepare layer schema
        create_layer_def(lyr);

        //
        // Translation of points cloud to features set
        //
        boost::uint32_t i = 0;
        boost::uint32_t const size = reader.GetHeader().GetPointRecordsCount();

        std::cout << "Translating " << size << " points:\n";

        ogr_wrapper<OGRFeatureH> feat(OGR_F_Create(OGR_L_GetLayerDefn(lyr)), OGR_F_Destroy);

        while (reader.ReadNextPoint())
        {
            liblas::Point const& p = reader.GetPoint();

            OGR_F_SetFieldInteger(feat, 0, p.GetReturnNumber());
            OGR_F_SetFieldInteger(feat, 1, p.GetScanAngleRank());
            OGR_F_SetFieldInteger(feat, 2, p.GetIntensity());

            std::ostringstream os;
            os << p.GetClassification();
            OGR_F_SetFieldString(feat, 3, os.str().c_str());

            OGR_F_SetFieldInteger(feat, 4, p.GetNumberOfReturns());
            OGR_F_SetFieldDouble(feat, 5, p.GetTime());

            ogr_wrapper<OGRGeometryH> geom(OGR_G_CreateGeometry(wkbPoint25D), OGR_G_DestroyGeometry);
            OGR_G_SetPoint(geom, 0, p.GetX(), p.GetY(), p.GetZ());
            if (OGRERR_NONE != OGR_F_SetGeometry(feat, geom))
            {
                throw std::runtime_error("geometry creation failed");
            }

            if (OGRERR_NONE != OGR_L_CreateFeature(lyr, feat))
            {
                throw std::runtime_error("feature creation failed");
            }

            term_progress(std::cout, (i + 1) / static_cast<double>(size));
            i++;
        }

        std::cout << std::endl;
    }
    catch (std::exception const& e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
        rc = -1;
    }
    catch (...)
    {
        std::cerr << "Unknown error\n";
        rc = -1;
    }
#else
    std::cout << "Missing GDAL/OGR support built-in las2ogr. Aborted." << std::endl;
#endif // #ifdef HAVE_GDAL

    ::OGRCleanupAll();
    return rc;
}
Exemplo n.º 5
0
/*!
  \brief Writes feature on level 1 (OGR interface)

  \param Map pointer to Map_info structure
  \param type feature type
  \param points pointer to line_pnts structure (feature geometry)
  \param cats pointer to line_cats structure (feature categories)

  \return feature offset into file
  \return -1 on error
*/
off_t V1_write_line_ogr(struct Map_info *Map, int type,
                        const struct line_pnts *points,
                        const struct line_cats *cats)
{
    int i, cat, ret;

    struct field_info *Fi;
    struct Format_info_ogr *fInfo;

    OGRGeometryH       Ogr_geometry;
    OGRFeatureH        Ogr_feature;
    OGRFeatureDefnH    Ogr_featuredefn;
    OGRwkbGeometryType Ogr_geom_type;

    if (!Map->fInfo.ogr.layer) {
        if (V2_open_new_ogr(Map, type) < 0)
            return -1;
    }

    cat = -1; /* no attributes to be written */
    if (cats->n_cats > 0) {
        /* check for attributes */
        Fi = Vect_get_dblink(Map, 0);
        if (Fi) {
            if (!Vect_cat_get(cats, Fi->number, &cat))
                G_warning(_("No category defined for layer %d"), Fi->number);
            if (cats->n_cats > 1) {
                G_warning(_("Feature has more categories, using "
                            "category %d (from layer %d)"),
                          cat, cats->field[0]);
            }
        }
    }

    fInfo = &(Map->fInfo.ogr);
    Ogr_featuredefn = OGR_L_GetLayerDefn(fInfo->layer);
    Ogr_geom_type = OGR_FD_GetGeomType(Ogr_featuredefn);

    /* determine matching OGR feature geometry type */
    /* NOTE: centroids are not supported in OGR,
     *       pseudotopo holds virtual centroids */
    /* NOTE: boundaries are not supported in OGR,
     *       pseudotopo treats polygons as boundaries */

    if (type & (GV_POINT | GV_KERNEL)) {
        if (Ogr_geom_type != wkbPoint &&
                Ogr_geom_type != wkbPoint25D) {
            G_warning(_("Feature is not a point. Skipping."));
            return -1;
        }
        Ogr_geometry = OGR_G_CreateGeometry(wkbPoint);
    }
    else if (type & GV_LINE) {
        if (Ogr_geom_type != wkbLineString &&
                Ogr_geom_type != wkbLineString25D) {
            G_warning(_("Feature is not a line. Skipping."));
            return -1;
        }
        Ogr_geometry = OGR_G_CreateGeometry(wkbLineString);
    }
    else if (type & GV_BOUNDARY) {
        if (Ogr_geom_type != wkbPolygon) {
            G_warning(_("Feature is not a polygon. Skipping."));
            return -1;
        }
        Ogr_geometry = OGR_G_CreateGeometry(wkbPolygon);
    }
    else if (type & GV_FACE) {
        if (Ogr_geom_type != wkbPolygon25D) {
            G_warning(_("Feature is not a face. Skipping."));
            return -1;
        }
        Ogr_geometry = OGR_G_CreateGeometry(wkbPolygon25D);
    }
    else {
        G_warning(_("Unsupported feature type (%d)"), type);
        return -1;
    }

    G_debug(3, "V1_write_line_ogr(): type = %d", type);

    if (Ogr_geom_type == wkbPolygon || Ogr_geom_type == wkbPolygon25D) {
        /* create exterior ring */
        OGRGeometryH Ogr_ring;
        int npoints;

        npoints = points->n_points - 1;
        Ogr_ring = OGR_G_CreateGeometry(wkbLinearRing);
        if (points->x[0] != points->x[npoints] ||
                points->y[0] != points->y[npoints] ||
                points->z[0] != points->z[npoints]) {
            G_warning(_("Boundary is not closed. Skipping."));
            return -1;
        }

        /* add points */
        for (i = 0; i < points->n_points; i++) {
            OGR_G_AddPoint(Ogr_ring, points->x[i], points->y[i],
                           points->z[i]);
        }
        OGR_G_AddGeometry(Ogr_geometry, Ogr_ring);
    }
    else {
        for (i = 0; i < points->n_points; i++) {
            OGR_G_AddPoint(Ogr_geometry, points->x[i], points->y[i],
                           points->z[i]);
        }
    }

    G_debug(4, "   n_points = %d", points->n_points);

    /* create feature & set geometry */
    Ogr_feature = OGR_F_Create(Ogr_featuredefn);
    OGR_F_SetGeometry(Ogr_feature, Ogr_geometry);

    /* write attributes */
    if (cat > -1 && fInfo->dbdriver) {
        write_attributes(fInfo->dbdriver,
                         cat, Fi, fInfo->layer, Ogr_feature);
        G_free(Fi);
    }
    /* write feature into layer */
    ret = OGR_L_CreateFeature(fInfo->layer, Ogr_feature);

    /* update offset array */
    if (fInfo->offset_num >= fInfo->offset_alloc) {
        fInfo->offset_alloc += 1000;
        fInfo->offset = (int *) G_realloc(fInfo->offset,
                                          fInfo->offset_alloc *
                                          sizeof(int));
    }
    /* how to deal with OGRNullFID ? */
    fInfo->offset[fInfo->offset_num] = (int)OGR_F_GetFID(Ogr_feature);

    /* destroy */
    OGR_G_DestroyGeometry(Ogr_geometry);
    OGR_F_Destroy(Ogr_feature);

    if (ret != OGRERR_NONE)
        return -1;

    return fInfo->offset_num++;
}
Exemplo n.º 6
0
int export_areas_single(struct Map_info *In, int field, int donocat,
                        OGRFeatureDefnH Ogr_featuredefn,OGRLayerH Ogr_layer,
                        struct field_info *Fi, dbDriver *driver, int ncol, int *colctype,
                        const char **colname, int doatt, int nocat,
                        int *n_noatt, int *n_nocat)
{
    int i, j;
    int centroid, cat, area, n_areas;
    int n_exported;
    
    struct line_pnts *Points;
    struct line_cats *Cats;

    OGRGeometryH Ogr_geometry;
    OGRFeatureH Ogr_feature;

    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();

    n_exported = 0;

    n_areas = Vect_get_num_areas(In);
    for (i = 1; i <= n_areas; i++) {
        G_percent(i, n_areas, 5);
        
        /* get centroid's category */
        centroid = Vect_get_area_centroid(In, i);
        cat = -1;
        if (centroid > 0) {
            Vect_read_line(In, NULL, Cats, centroid);
            Vect_cat_get(Cats, field, &cat);
        }
        G_debug(3, "area = %d centroid = %d ncats = %d", i, centroid,
                Cats->n_cats);
        if (cat < 0 && !donocat) {
            (*n_nocat)++;
            continue; /* skip areas without category, do not export
                       * not labeled */
        }
        
        /* find correspoding area */
        area = Vect_get_centroid_area(In, centroid);
        if (area == 0)
            continue;

        /* create polygon from area */
        Ogr_geometry = create_polygon(In, area, Points);

        /* add feature */
        Ogr_feature = OGR_F_Create(Ogr_featuredefn);
        OGR_F_SetGeometry(Ogr_feature, Ogr_geometry);
        
        /* output one feature for each category */
        for (j = -1; j < Cats->n_cats; j++) {
            if (j == -1) {
                if (cat >= 0)
                    continue;	/* cat(s) exists */
		(*n_nocat)++;
            }
            else {
                if (Cats->field[j] == field)
                    cat = Cats->cat[j];
                else
                    continue;
            }
            
            mk_att(cat, Fi, driver, ncol, colctype, colname, doatt, nocat,
                   Ogr_feature, n_noatt);
            OGR_L_CreateFeature(Ogr_layer, Ogr_feature);
            
            n_exported++;
        }
        OGR_G_DestroyGeometry(Ogr_geometry);
        OGR_F_Destroy(Ogr_feature);
    }

    Vect_destroy_line_struct(Points);
    Vect_destroy_cats_struct(Cats);

    return n_exported;
}
Exemplo n.º 7
0
int export_areas_multi(struct Map_info *In, int field, int donocat,
                       OGRFeatureDefnH Ogr_featuredefn,OGRLayerH Ogr_layer,
                       struct field_info *Fi, dbDriver *driver, int ncol, int *colctype,
                       const char **colname, int doatt, int nocat,
                       int *n_noatt, int *n_nocat)
{
    int i, n_exported, area;
    int cat, ncats_field, line, type, findex, ipart;

    struct line_pnts *Points;
    struct line_cats *Cats;
    struct ilist *cat_list, *line_list, *lcats;

    OGRGeometryH Ogr_geometry, Ogr_geometry_part;
    OGRFeatureH Ogr_feature;
    OGRwkbGeometryType wkbtype, wkbtype_part;
    
    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();
    cat_list = Vect_new_list();
    line_list = Vect_new_list();
    lcats = Vect_new_list();

    n_exported = 0;

    /* check if category index is available for given field */
    findex = Vect_cidx_get_field_index(In, field);
    if (findex == -1)
        G_fatal_error(_("Unable to export multi-features. No category index for layer %d."),
                      field);
    
    /* determine type */
    wkbtype_part = wkbPolygon;
    wkbtype = get_multi_wkbtype(wkbtype_part);
    
    ncats_field = Vect_cidx_get_unique_cats_by_index(In, findex, cat_list);
    G_debug(1, "n_cats = %d for layer %d", ncats_field, field);

    if (donocat)
	G_message(_("Exporting features with category..."));

    for (i = 0; i < cat_list->n_values; i++) {
        G_percent(i, cat_list->n_values - 1, 5);

        cat = cat_list->value[i];
        /* find all centroids with given category */
        Vect_cidx_find_all(In, field, GV_CENTROID, cat, line_list);

        /* create multi-feature */
        Ogr_geometry = OGR_G_CreateGeometry(wkbtype);

        /* build simple features geometry, go through all parts */
        for (ipart = 0; ipart < line_list->n_values; ipart++) {
            line = line_list->value[ipart];
            G_debug(3, "cat=%d, line=%d -> part=%d", cat, line, ipart);

            /* get centroid's category */
            Vect_read_line(In, NULL, Cats, line);
            /* check for category consistency */
            Vect_field_cat_get(Cats, field, lcats);
	    if (!Vect_val_in_list(lcats, cat))
                G_fatal_error(_("Unable to create multi-feature. "
                                "Category %d not found in line %d, field %d"),
                              cat, line, field);
            
            /* find correspoding area */
            area = Vect_get_centroid_area(In, line);
            if (area == 0)
                continue;
                
            /* create polygon from area */
            Ogr_geometry_part = create_polygon(In, area, Points);

            /* add part */
            OGR_G_AddGeometryDirectly(Ogr_geometry, Ogr_geometry_part);
        }

        if (!OGR_G_IsEmpty(Ogr_geometry)) {
            /* write multi-feature */
            Ogr_feature = OGR_F_Create(Ogr_featuredefn);
            OGR_F_SetGeometry(Ogr_feature, Ogr_geometry);
            
            mk_att(cat, Fi, driver, ncol, colctype, colname, doatt, nocat,
                   Ogr_feature, n_noatt);
            OGR_L_CreateFeature(Ogr_layer, Ogr_feature);

            OGR_F_Destroy(Ogr_feature);

            n_exported++;
        }
        else {
            /* skip empty features */
            G_debug(3, "multi-feature is empty -> skipped");
        }
        
        OGR_G_DestroyGeometry(Ogr_geometry);
    }

    if (donocat)
	G_message(_("Exporting features without category..."));

    /* check lines without category, if -c flag is given write them as
     * one multi-feature */
    Ogr_geometry = OGR_G_CreateGeometry(wkbtype);
    
    Vect_rewind(In);
    Vect_set_constraint_type(In, GV_CENTROID);
    while(TRUE) {
        type = Vect_read_next_line(In, NULL, Cats);
        if (type < 0)
            break;

        /* get centroid's category */
        Vect_cat_get(Cats, field, &cat);
        if (cat > 0)
            continue; /* skip features with category */
        if (cat < 0 && !donocat) {
            (*n_nocat)++;
            continue; /* skip lines without category, do not export
                       * not labeled */
        }

        /* find correspoding area */
	line = Vect_get_next_line_id(In);
        area = Vect_get_centroid_area(In, line);
        if (area == 0)
            continue;
                
        /* create polygon from area */
        Ogr_geometry_part = create_polygon(In, area, Points);
        
        /* add part */
        OGR_G_AddGeometryDirectly(Ogr_geometry, Ogr_geometry_part);

        (*n_nocat)++;
    }

    if (!OGR_G_IsEmpty(Ogr_geometry)) {
        /* write multi-feature */
        Ogr_feature = OGR_F_Create(Ogr_featuredefn);
        OGR_F_SetGeometry(Ogr_feature, Ogr_geometry);
        
        mk_att(cat, Fi, driver, ncol, colctype, colname, doatt, nocat,
               Ogr_feature, n_noatt);
        OGR_L_CreateFeature(Ogr_layer, Ogr_feature);

        OGR_F_Destroy(Ogr_feature);
        
        n_exported++;
    }
    else {
        /* skip empty features */
        G_debug(3, "multi-feature is empty -> skipped");
    }
    
    OGR_G_DestroyGeometry(Ogr_geometry);
    
    Vect_destroy_line_struct(Points);
    Vect_destroy_cats_struct(Cats);
    Vect_destroy_list(cat_list);
    Vect_destroy_list(line_list);
    Vect_destroy_list(lcats);
    
    return n_exported;
}
Exemplo n.º 8
0
int create_grid(char *infile, char *outfile, int gridsize, char *format, char *layer) {

	OGRSFDriverH out_driver;
	OGRDataSourceH out_ds;
	OGRLayerH out_layer;
	OGRFieldDefnH field;
	OGRFeatureH feat;
	OGRGeometryH geom;
	morph *mgrid;
	int xstep, ystep, step;
	double topleftx, toplefty, weres, nsres, rot1, rot2;
	int i,j, fid, row, col;
	
	
	OGRRegisterAll();
	
	// Read the morph grid file.
	mgrid = read_grid(infile);
	if (mgrid == NULL) {
		fprintf(stderr, "Error. Unable to read input morph file '%s'.\n", infile);
		exit(1);
	}
	
	// Create the ouptut layer.
	out_driver = OGRGetDriverByName(format);
	if (out_driver == NULL) {
		fprintf(stderr, "Error. Driver for format '%s' not available.\n", format);
		exit(1);
	}
	out_ds = OGR_Dr_CreateDataSource(out_driver, outfile, NULL);
	if (out_ds == NULL) {
		fprintf(stderr, "Error. Unable to create output data source.\n");
		exit(1);
	}
	out_layer = OGR_DS_CreateLayer(out_ds, layer, NULL, wkbLineString, NULL);
	if (out_layer == NULL) {
		fprintf(stderr, "Error. Unable to create output layer.\n");
		exit(1);
	}
	
	// Add the attributes to the new layer.
	field = OGR_Fld_Create("ID", OFTInteger);
	OGR_Fld_SetWidth(field, 11);
	if (OGR_L_CreateField(out_layer, field, TRUE) != OGRERR_NONE) {
		fprintf(stderr, "Error. Creating ID attribute failed.\n");
		exit(1);
	}
	OGR_Fld_Destroy(field);
	
	field = OGR_Fld_Create("ROW", OFTInteger);
	OGR_Fld_SetWidth(field, 6);
	if (OGR_L_CreateField(out_layer, field, TRUE) != OGRERR_NONE) {
		fprintf(stderr, "Error. Creating ROW attribute failed.\n");
		exit(1);
	}
	OGR_Fld_Destroy(field);
	
	field = OGR_Fld_Create("COL", OFTInteger);
	OGR_Fld_SetWidth(field, 6);
	if (OGR_L_CreateField(out_layer, field, TRUE) != OGRERR_NONE) {
		fprintf(stderr, "Error. Creating COL attribute failed.\n");
		exit(1);
	}
	OGR_Fld_Destroy(field);
	
	// Compute the step size.
	xstep = mgrid->xsize / gridsize;
	if (xstep < 1) {
		xstep = 1;
	}
	if (xstep > (mgrid->xsize / 2)) {
		xstep = mgrid->xsize / 2;
	}
	ystep = mgrid->ysize / gridsize;
	if (ystep < 1) {
		ystep = 1;
	}
	if (ystep > (mgrid->ysize / 2)) {
		ystep = mgrid->ysize / 2;
	}
	if (xstep < ystep) {
		step = ystep;
	} else {
		step = xstep;
	}
	
	// Read the georeference
	topleftx = mgrid->georef[0];
	weres = mgrid->georef[1];
	rot1 = mgrid->georef[2];
	toplefty = mgrid->georef[3];
	rot2 = mgrid->georef[4];
	nsres = mgrid->georef[5];
	
	// Write all horizontal lines.
	fid = 1;
	row = 1;
	for (j = 0; j < mgrid->ysize; j += step) {
		// Create a new Feature with the projected coordinates.
		feat = OGR_F_Create(OGR_L_GetLayerDefn(out_layer));
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ID"), fid);
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ROW"), row);
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "COL"), 0);

		// Create a new geometry object.
		geom = OGR_G_CreateGeometry(wkbLineString);
		for (i = 0; i < mgrid->xsize; i++) {
			OGR_G_SetPoint_2D(
							  geom, 
							  i, 
							  topleftx + mgrid->x[i][j]*weres + mgrid->y[i][j]*rot1, 
							  toplefty + mgrid->x[i][j]*rot2 + mgrid->y[i][j]*nsres);
		}
		OGR_F_SetGeometry(feat, geom);
		OGR_G_DestroyGeometry(geom);
		
		// Write the feature to the output vector layer.
		if (OGR_L_CreateFeature(out_layer, feat) != OGRERR_NONE) {
			fprintf(stderr, "Error. Unable to create new feature.\n");
			exit(1);
		}
		OGR_F_Destroy(feat);
		
		row++;
		fid++;
	}
	
	// Write all vertical lines.
	col = 1;
	for (i = 0; i < mgrid->xsize; i += step) {
		// Create a new Feature with the projected coordinates.
		feat = OGR_F_Create(OGR_L_GetLayerDefn(out_layer));
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ID"), fid);
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ROW"), 0);
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "COL"), col);
		
		// Create a new geometry object.
		geom = OGR_G_CreateGeometry(wkbLineString);
		for (j = 0; j < mgrid->ysize; j++) {
			OGR_G_SetPoint_2D(
							  geom, 
							  j, 
							  topleftx + mgrid->x[i][j]*weres + mgrid->y[i][j]*rot1, 
							  toplefty + mgrid->x[i][j]*rot2 + mgrid->y[i][j]*nsres);
		}
		OGR_F_SetGeometry(feat, geom);
		OGR_G_DestroyGeometry(geom);
		
		// Write the feature to the output vector layer.
		if (OGR_L_CreateFeature(out_layer, feat) != OGRERR_NONE) {
			fprintf(stderr, "Error. Unable to create new feature.\n");
			exit(1);
		}
		OGR_F_Destroy(feat);
		
		col++;
		fid++;
	}

	// Close the datasources and free the memory.
	OGR_DS_Destroy(out_ds);
	free_morph(mgrid);
	
	return 0;
}
Exemplo n.º 9
0
  int Delaunay(maps*& conf,maps*& inputs,maps*& outputs){
#ifdef DEBUG
    fprintf(stderr,"\nService internal print\nStarting\n");
#endif
    maps* cursor=inputs;
    OGRGeometryH geometry,res;
    int bufferDistance;
    map* tmpm=NULL;
    OGRRegisterAll();

    std::vector<Point> points;
    if(int res=parseInput(conf,inputs,&points,"/vsimem/tmp")!=SERVICE_SUCCEEDED)
      return res;

    DelaunayT T;
    T.insert(points.begin(), points.end());

    /* -------------------------------------------------------------------- */
    /*      Try opening the output datasource as an existing, writable      */
    /* -------------------------------------------------------------------- */
#if GDAL_VERSION_MAJOR >= 2
    GDALDataset *poODS;
    GDALDriverManager* poR=GetGDALDriverManager();
    GDALDriver          *poDriver = NULL;
#else
    OGRDataSource       *poODS;    
    OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar();
    OGRSFDriver          *poDriver = NULL;
#endif
    int                  iDriver;
    map *tmpMap=getMapFromMaps(outputs,"Result","mimeType");
    const char *oDriver;
    oDriver="GeoJSON";
    if(tmpMap!=NULL){
      if(strcmp(tmpMap->value,"text/xml")==0){
	oDriver="GML";
      }
    }
    
    for( iDriver = 0;
	 iDriver < poR->GetDriverCount() && poDriver == NULL;
	 iDriver++ )
      {
#ifdef DEBUG
#if GDAL_VERSION_MAJOR >= 2
	fprintf(stderr,"D:%s\n",poR->GetDriver(iDriver)->GetDescription());
#else
	fprintf(stderr,"D:%s\n",poR->GetDriver(iDriver)->GetName());
#endif
#endif
	if( EQUAL(
#if GDAL_VERSION_MAJOR >= 2
		  poR->GetDriver(iDriver)->GetDescription()
#else
		  poR->GetDriver(iDriver)->GetName()
#endif
		  ,
		  oDriver) )
	  {
	    poDriver = poR->GetDriver(iDriver);
	  }
      }

    if( poDriver == NULL )
      {
	char emessage[8192];
	sprintf( emessage, "Unable to find driver `%s'.\n", oDriver );
	sprintf( emessage,  "%sThe following drivers are available:\n",emessage );
        
	for( iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ )
	  {
#if GDAL_VERSION_MAJOR >= 2
	    sprintf( emessage,  "%s  -> `%s'\n", emessage, poR->GetDriver(iDriver)->GetDescription() );
#else
	    sprintf( emessage,  "%s  -> `%s'\n", emessage, poR->GetDriver(iDriver)->GetName() );
#endif
	  }

	setMapInMaps(conf,"lenv","message",emessage);
	return SERVICE_FAILED;

      }

#if GDAL_VERSION_MAJOR >=2
    if( !CPLTestBool( CSLFetchNameValueDef(poDriver->GetMetadata(), GDAL_DCAP_CREATE, "FALSE") ) )
#else
    if( !poDriver->TestCapability( ODrCCreateDataSource ) )
#endif
      {
	char emessage[1024];
	sprintf( emessage,  "%s driver does not support data source creation.\n",
		 "json" );
	setMapInMaps(conf,"lenv","message",emessage);
	return SERVICE_FAILED;
      }

    /* -------------------------------------------------------------------- */
    /*      Create the output data source.                                  */
    /* -------------------------------------------------------------------- */
    char *pszDestDataSource=(char*)malloc(100);
    char **papszDSCO=NULL;
    sprintf(pszDestDataSource,"/vsimem/result_%d",getpid());
#if GDAL_VERSION_MAJOR >=2
    poODS = poDriver->Create( pszDestDataSource, 0, 0, 0, GDT_Unknown, papszDSCO );
#else
    poODS = poDriver->CreateDataSource( pszDestDataSource, papszDSCO );
#endif
    if( poODS == NULL ){
      char emessage[1024];      
      sprintf( emessage,  "%s driver failed to create %s\n", 
	       "json", pszDestDataSource );
      setMapInMaps(conf,"lenv","message",emessage);
      return SERVICE_FAILED;
    }

    /* -------------------------------------------------------------------- */
    /*      Create the layer.                                               */
    /* -------------------------------------------------------------------- */
    if( !poODS->TestCapability( ODsCCreateLayer ) )
      {
	char emessage[1024];
	sprintf( emessage, 
		 "Layer %s not found, and CreateLayer not supported by driver.", 
		 "Result" );
	setMapInMaps(conf,"lenv","message",emessage);
	return SERVICE_FAILED;
      }
    
    CPLErrorReset();
    
    OGRLayer *poDstLayer = poODS->CreateLayer( "Result", NULL,wkbPolygon,NULL);
    if( poDstLayer == NULL ){
      setMapInMaps(conf,"lenv","message","Layer creation failed.\n");
      return SERVICE_FAILED;
    }


    for(DelaunayT::Finite_faces_iterator fit = T.finite_faces_begin();
	fit != T.finite_faces_end(); ++fit) {
      DelaunayT::Face_handle face = fit;
      OGRFeatureH hFeature = OGR_F_Create( OGR_L_GetLayerDefn( poDstLayer ) );
      OGRGeometryH hCollection = OGR_G_CreateGeometry( wkbGeometryCollection );
      OGRGeometryH currLine=OGR_G_CreateGeometry(wkbLinearRing);
      OGRGeometryH currPoly=OGR_G_CreateGeometry(wkbPolygon);
      OGR_G_AddPoint_2D(currLine,T.triangle(face)[0].x(),T.triangle(face)[0].y());
      OGR_G_AddPoint_2D(currLine,T.triangle(face)[1].x(),T.triangle(face)[1].y());
      OGR_G_AddPoint_2D(currLine,T.triangle(face)[2].x(),T.triangle(face)[2].y());
      OGR_G_AddPoint_2D(currLine,T.triangle(face)[0].x(),T.triangle(face)[0].y());
      OGR_G_AddGeometryDirectly( currPoly, currLine ); 
      OGR_G_AddGeometryDirectly( hCollection, currPoly ); 
      OGR_F_SetGeometry( hFeature, hCollection ); 
      OGR_G_DestroyGeometry(hCollection);
      if( OGR_L_CreateFeature( poDstLayer, hFeature ) != OGRERR_NONE ){
	setMapInMaps(conf,"lenv","message","Failed to create feature in file.\n");
	return SERVICE_FAILED;
      }
      OGR_F_Destroy( hFeature );
    }
    OGR_DS_Destroy( poODS );

#ifdef DEBUG
    std::cerr << "The Voronoi diagram has " << ns << " finite edges "
	      << " and " << nr << " rays" << std::endl;
#endif

    char *res1=readVSIFile(conf,pszDestDataSource);
    if(res1==NULL)
      return SERVICE_FAILED;

    setMapInMaps(outputs,"Result","value",res1);
    free(res1);

    if(strcmp(oDriver,"GML")==0)
      setMapInMaps(outputs,"Result","mimeType","text/xml");
    else
      setMapInMaps(outputs,"Result","mimeType","application/json");

    setMapInMaps(outputs,"Result","encoding","UTF-8");
    OGRCleanupAll();
    
    return SERVICE_SUCCEEDED;
  }
Exemplo n.º 10
0
/*!
  \brief Write OGR feature

   \param Map pointer to Map_info structure
   \param type feature type (GV_POINT, GV_LINE, ...)
   \param bpoints feature geometry
   \param cats feature categories
   \param ipoints isle geometry for polygons on NULL
   \param nisles number of isles
   
   \return feature offset into file
   \return -1 on error
*/
off_t write_feature(struct Map_info *Map, int type,
                    const struct line_pnts **p_points, int nparts,
                    const struct line_cats *cats)
{
    int i, cat, ret;

    struct field_info *Fi;
    const struct line_pnts *points;
    struct Format_info_ogr *ogr_info;
    struct Format_info_offset *offset_info;
    
    off_t offset;
    
    OGRGeometryH       Ogr_geometry;
    OGRFeatureH        Ogr_feature;
    OGRFeatureDefnH    Ogr_featuredefn;
    OGRwkbGeometryType Ogr_geom_type;

    ogr_info = &(Map->fInfo.ogr);
    offset_info = &(ogr_info->offset);
    
    if (nparts < 1)
        return -1;
    
    points = p_points[0]; /* feature geometry */
    
    if (!ogr_info->layer) {
	/* create OGR layer if doesn't exist */
	if (create_ogr_layer(Map, type) < 0)
	    return -1;
    }

    if (!points)
        return 0;

    cat = -1; /* no attributes to be written */
    if (cats->n_cats > 0 && Vect_get_num_dblinks(Map) > 0) {
	/* check for attributes */
	Fi = Vect_get_dblink(Map, 0);
	if (Fi) {
	    if (!Vect_cat_get(cats, Fi->number, &cat))
		G_warning(_("No category defined for layer %d"), Fi->number);
	    if (cats->n_cats > 1) {
		G_warning(_("Feature has more categories, using "
			    "category %d (from layer %d)"),
			  cat, cats->field[0]);
	    }
	}
    }
    
    Ogr_featuredefn = OGR_L_GetLayerDefn(ogr_info->layer);
    Ogr_geom_type = OGR_FD_GetGeomType(Ogr_featuredefn);
    
    /* determine matching OGR feature geometry type */
    if (type & (GV_POINT | GV_KERNEL)) {
	if (Ogr_geom_type != wkbPoint &&
	    Ogr_geom_type != wkbPoint25D) {
	    G_warning(_("Feature is not a point. Skipping."));
	    return -1;
	}
	Ogr_geometry = OGR_G_CreateGeometry(wkbPoint);
    }
    else if (type & GV_LINE) {
	if (Ogr_geom_type != wkbLineString &&
	    Ogr_geom_type != wkbLineString25D) {
	    G_warning(_("Feature is not a line. Skipping."));
	    return -1;
	}
	Ogr_geometry = OGR_G_CreateGeometry(wkbLineString);
    }
    else if (type & GV_BOUNDARY) {
	if (Ogr_geom_type != wkbPolygon) {
	    G_warning(_("Feature is not a polygon. Skipping."));
	    return -1;
	}
	Ogr_geometry = OGR_G_CreateGeometry(wkbPolygon);
    }
    else if (type & GV_FACE) {
	if (Ogr_geom_type != wkbPolygon25D) {
	    G_warning(_("Feature is not a face. Skipping."));
	    return -1;
	}
	Ogr_geometry = OGR_G_CreateGeometry(wkbPolygon25D);
    }
    else {
	G_warning(_("Unsupported feature type (%d)"), type);
	return -1;
    }

    G_debug(3, "V1_write_line_ogr(): type = %d", type);

    if (Ogr_geom_type == wkbPolygon || Ogr_geom_type == wkbPolygon25D) {
	int iring, npoints;
	
        /* add rings (first is exterior ring) */
        for (iring = 0; iring < nparts; iring++) {
            OGRGeometryH Ogr_ring;
            
            points = p_points[iring];
            npoints = points->n_points - 1;
            Ogr_ring = OGR_G_CreateGeometry(wkbLinearRing);
            if (points->x[0] != points->x[npoints] ||
                points->y[0] != points->y[npoints] ||
                points->z[0] != points->z[npoints]) {
                G_warning(_("Boundary is not closed. Feature skipped."));
                return -1;
            }
	
            /* add points */
            for (i = 0; i < npoints; i++) {
                OGR_G_AddPoint(Ogr_ring, points->x[i], points->y[i],
                               points->z[i]);
            }
            G_debug(4, "   ring(%d): n_points = %d", iring, npoints);
            OGR_G_AddGeometry(Ogr_geometry, Ogr_ring);
        }
    }
    else {
	for (i = 0; i < points->n_points; i++) {
	    OGR_G_AddPoint(Ogr_geometry, points->x[i], points->y[i],
			   points->z[i]);
	}
        G_debug(4, "   n_points = %d", points->n_points);
    }
    
    /* create feature & set geometry */
    Ogr_feature = OGR_F_Create(Ogr_featuredefn);
    OGR_F_SetGeometry(Ogr_feature, Ogr_geometry);

    /* write attributes */
    if (cat > -1 && ogr_info->dbdriver) {
	if (0 > write_attributes(ogr_info->dbdriver,
                                 cat, Fi, ogr_info->layer, Ogr_feature))
            G_warning(_("Unable to writes feature attributes"));
	G_free(Fi);
    }
    /* write feature into layer */
    ret = OGR_L_CreateFeature(ogr_info->layer, Ogr_feature);

    /* update offset array */
    if (offset_info->array_num >= offset_info->array_alloc) {
	offset_info->array_alloc += 1000;
	offset_info->array = (int *) G_realloc(offset_info->array,
						offset_info->array_alloc *
						sizeof(int));
    }

    offset = offset_info->array_num;
    
    offset_info->array[offset_info->array_num++] = (int) OGR_F_GetFID(Ogr_feature);
    if (Ogr_geom_type == wkbPolygon || Ogr_geom_type == wkbPolygon25D) {
	/* register exterior ring in offset array */
	offset_info->array[offset_info->array_num++] = 0; 
    }
      
    /* destroy */
    OGR_G_DestroyGeometry(Ogr_geometry);
    OGR_F_Destroy(Ogr_feature);
    
    if (ret != OGRERR_NONE)
	return -1;
    
    G_debug(3, "write_feature(): -> offset = %lu offset_num = %d cat = %d",
	    (unsigned long) offset, offset_info->array_num, cat);

    return offset;
}