Exemplo n.º 1
0
/** add points to the visibility graph
*/
void add_points(char **coor, struct Point **points, int *index_point)
{
    int i;
    double x, y;


    /* and defining the points */
    for (i = 0; coor[i] != NULL; i += 2) {
	G_scan_easting(coor[i], &x, G_projection());
	G_scan_northing(coor[i + 1], &y, G_projection());

	(*points)[*index_point].x = x;
	(*points)[*index_point].y = y;
	(*points)[*index_point].cat = -1;

	(*points)[*index_point].line1 = NULL;
	(*points)[*index_point].line2 = NULL;

	(*points)[*index_point].left_brother = NULL;
	(*points)[*index_point].right_brother = NULL;
	(*points)[*index_point].father = NULL;
	(*points)[*index_point].rightmost_son = NULL;

	(*index_point)++;

    }
}
Exemplo n.º 2
0
int get_item(FILE * fd, int *type, long *cat, double **x, double **y,
	     int *count, struct Categories *labels)
{
    static double *X = NULL;
    static double *Y = NULL;
    static int nalloc = 0;
    char buf[1024];
    char lbl[1024];
    char east[256], north[256];
    double e, n;
    long offset;

    *cat = 0;
    *count = 0;
    *type = 0;

    /* scan until we find the start of a new feature */
    while (G_getl2(buf, sizeof buf, fd)) {
	/* skip comments and blank lines */
	if ((*buf == '#') || (*buf == '\0'))
	    continue;

	G_strip(buf);
	if (*buf == 'A' || *buf == 'a') {
	    *type = 'A';
	    break;
	}
	if (*buf == 'L' || *buf == 'l') {
	    *type = 'L';
	    break;
	}
	if (*buf == 'P' || *buf == 'p') {
	    *type = 'P';
	    break;
	}
    }
    if (*type == 0)
	return 0;

    /* read the feature's data */
    while (1) {
	offset = G_ftell(fd);

	if (!G_getl2(buf, (sizeof buf) - 1, fd))
	    break;

	/* skip comments and blank lines */
	if ((*buf == '#') || (*buf == '\0'))
	    continue;

	G_strip(buf);

	/* if we've found the next feature, rewind to the start of it and complete */
	if (*buf == 'A' || *buf == 'a' ||
	    *buf == 'L' || *buf == 'l' || *buf == 'P' || *buf == 'p') {
	    G_fseek(fd, offset, 0);
	    break;
	}

	/* if we found a cat (and optionally a label), read them and continue to scan */
	if (*buf == '=') {
	    if (sscanf(buf + 1, "%ld", cat) != 1)
		continue;
	    /* probably change this as G_getl2() doesn't store the new line (?) */
	    if (sscanf(buf + 1, "%ld%[^\n]", cat, lbl) == 2) {
		G_strip(lbl);
		Rast_set_c_cat((CELL*) cat, (CELL *) cat, lbl, labels);
	    }
	    continue;
	}
	if (sscanf(buf, "%s %s", east, north) != 2) {
	    G_warning(_("Illegal coordinate <%s, %s>, skipping."), east, north);
	    continue;
	}

	if (!G_scan_northing(north, &n, G_projection())) {
	    G_warning(_("Illegal north coordinate <%s>, skipping."), north);
	    continue;
	}

	if (!G_scan_easting(east, &e, G_projection())) {
	    G_warning(_("Illegal east coordinate <%s>, skipping."), east);
	    continue;
	}

	if (*count >= nalloc) {
	    nalloc += 32;
	    X = (double *)G_realloc(X, nalloc * sizeof(double));
	    Y = (double *)G_realloc(Y, nalloc * sizeof(double));
	}
	X[*count] = e;
	Y[*count] = n;
	(*count)++;
    }
    *x = X;
    *y = Y;
    return 1;
}
Exemplo n.º 3
0
int main(int argc, char *argv[])
{
    char *terrainmap, *seedmap, *lakemap, *mapset;
    int rows, cols, in_terran_fd, out_fd, lake_fd, row, col, pases, pass;
    int lastcount, curcount, start_col = 0, start_row = 0;
    double east, north, area = 0, volume = 0;
    FCELL **in_terran, **out_water, water_level, max_depth = 0, min_depth = 0;
    FCELL water_window[3][3];
    struct Option *tmap_opt, *smap_opt, *wlvl_opt, *lake_opt, *sdxy_opt;
    struct Flag *negative_flag, *overwrite_flag;
    struct GModule *module;
    struct Colors colr;
    struct Cell_head window;
    struct History history;

    G_gisinit(argv[0]);
    
    module = G_define_module();
    module->keywords = _("raster, hydrology");
    module->description = _("Fills lake at given point to given level.");

    tmap_opt = G_define_option();
    tmap_opt->key = "dem";
    tmap_opt->key_desc = "name";
    tmap_opt->description = _("Name of terrain raster map (DEM)");
    tmap_opt->type = TYPE_STRING;
    tmap_opt->gisprompt = "old,cell,raster";
    tmap_opt->required = YES;

    wlvl_opt = G_define_option();
    wlvl_opt->key = "wl";
    wlvl_opt->description = _("Water level");
    wlvl_opt->type = TYPE_DOUBLE;
    wlvl_opt->required = YES;

    lake_opt = G_define_option();
    lake_opt->key = "lake";
    lake_opt->key_desc = "name";
    lake_opt->description = _("Name for output raster map with lake");
    lake_opt->type = TYPE_STRING;
    lake_opt->gisprompt = "new,cell,raster";
    lake_opt->required = NO;

    sdxy_opt = G_define_option();
    sdxy_opt->key = "xy";
    sdxy_opt->description = _("Seed point coordinates");
    sdxy_opt->type = TYPE_DOUBLE;
    sdxy_opt->key_desc = "east,north";
    sdxy_opt->required = NO;
    sdxy_opt->multiple = NO;

    smap_opt = G_define_option();
    smap_opt->key = "seed";
    smap_opt->key_desc = "name";
    smap_opt->description =
	_("Name of raster map with given starting point(s) (at least 1 cell > 0)");
    smap_opt->type = TYPE_STRING;
    smap_opt->gisprompt = "old,cell,raster";
    smap_opt->required = NO;

    negative_flag = G_define_flag();
    negative_flag->key = 'n';
    negative_flag->description =
	_("Use negative depth values for lake raster map");

    overwrite_flag = G_define_flag();
    overwrite_flag->key = 'o';
    overwrite_flag->description =
	_("Overwrite seed map with result (lake) map");

    if (G_parser(argc, argv))	/* Returns 0 if successful, non-zero otherwise */
	exit(EXIT_FAILURE);

    if (smap_opt->answer && sdxy_opt->answer)
	G_fatal_error(_("Both seed map and coordinates cannot be specified"));

    if (!smap_opt->answer && !sdxy_opt->answer)
	G_fatal_error(_("Seed map or seed coordinates must be set!"));

    if (sdxy_opt->answer && !lake_opt->answer)
	G_fatal_error(_("Seed coordinates and output map lake= must be set!"));

    if (lake_opt->answer && overwrite_flag->answer)
	G_fatal_error(_("Both lake and overwrite cannot be specified"));

    if (!lake_opt->answer && !overwrite_flag->answer)
	G_fatal_error(_("Output lake map or overwrite flag must be set!"));

    terrainmap = tmap_opt->answer;
    seedmap = smap_opt->answer;
    sscanf(wlvl_opt->answer, "%f", &water_level);
    lakemap = lake_opt->answer;

    /* If lakemap is set, write to it, else is set overwrite flag and we should write to seedmap. */
    if (lakemap) {
	lake_fd = G_open_raster_new(lakemap, 1);
	if (lake_fd < 0)
	    G_fatal_error(_("Unable to create raster map <%s>"), lakemap);
    }

    rows = G_window_rows();
    cols = G_window_cols();

    /* If we use x,y as seed... */
    if (sdxy_opt->answer) {
	G_get_window(&window);
	east = window.east;
	north = window.north;

	G_scan_easting(sdxy_opt->answers[0], &east, G_projection());
	G_scan_northing(sdxy_opt->answers[1], &north, G_projection());
	start_col = (int)G_easting_to_col(east, &window);
	start_row = (int)G_northing_to_row(north, &window);

	if (start_row < 0 || start_row > rows ||
	    start_col < 0 || start_col > cols)
	    G_fatal_error(_("Seed point outside the current region"));
    }

    /* Open terran map */
    mapset = G_find_cell2(terrainmap, "");
    if (mapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), terrainmap);

    in_terran_fd = G_open_cell_old(terrainmap, mapset);
    if (in_terran_fd < 0)
	G_fatal_error(_("Unable to open raster map <%s>"),
		      G_fully_qualified_name(terrainmap, mapset));

    /* Open seed map */
    if (smap_opt->answer) {
	mapset = G_find_cell2(seedmap, "");
	if (mapset == NULL)
	    G_fatal_error(_("Raster map <%s> not found"), seedmap);

	out_fd = G_open_cell_old(seedmap, mapset);
	if (out_fd < 0)
	    G_fatal_error(_("Unable to open raster map <%s>"),
			  G_fully_qualified_name(seedmap, mapset));
    }

    /* Pointers to rows. Row = ptr to 'col' size array. */
    in_terran = (FCELL **) G_malloc(rows * sizeof(FCELL *));
    out_water = (FCELL **) G_malloc(rows * sizeof(FCELL *));
    if (in_terran == NULL || out_water == NULL)
	G_fatal_error(_("G_malloc: out of memory"));


    G_debug(1, "Loading maps...");
    /* foo_rows[row] == array with data (2d array). */
    for (row = 0; row < rows; row++) {
	in_terran[row] = (FCELL *) G_malloc(cols * sizeof(FCELL));
	out_water[row] = (FCELL *) G_calloc(cols, sizeof(FCELL));

	/* In newly created space load data from file. */
	if (G_get_f_raster_row(in_terran_fd, in_terran[row], row) != 1)
	    G_fatal_error(_("Unable to read raster map <%s> row %d"),
			  terrainmap, row);

	if (smap_opt->answer)
	    if (G_get_f_raster_row(out_fd, out_water[row], row) != 1)
		G_fatal_error(_("Unable to read raster map <%s> row %d"),
			      seedmap, row);

	G_percent(row + 1, rows, 5);
    }

    /* Set seed point */
    if (sdxy_opt->answer)
	/* Check is water level higher than seed point */
	if (in_terran[start_row][start_col] >= water_level)
	    G_fatal_error(_("Given water level at seed point is below earth surface. "
			   "Increase water level or move seed point."));
    out_water[start_row][start_col] = 1;

    /* Close seed map for reading. */
    if (smap_opt->answer)
	G_close_cell(out_fd);

    /* Open output map for writing. */
    if (lakemap) {
	out_fd = lake_fd;
    }
    else {
	out_fd = G_open_raster_new(seedmap, 1);
	if (out_fd < 0)
	    G_fatal_error(_("Unable to create raster map <%s>"), seedmap);
    }

    /* More pases are renudant. Real pases count is controled by altered cell count. */
    pases = (int)(rows * cols) / 2;

    G_debug(1,
	    "Starting lake filling at level of %8.4f in %d passes. Percent done:",
	    water_level, pases);

    lastcount = 0;

    for (pass = 0; pass < pases; pass++) {
	G_debug(3, "Pass: %d", pass);
	curcount = 0;
	/* Move from left upper corner to right lower corner. */
	for (row = 0; row < rows; row++) {
	    for (col = 0; col < cols; col++) {
		/* Loading water data into window. */
		load_window_values(out_water, water_window, rows, cols, row,
				   col);

		/* Cheking presence of water. */
		if (is_near_water(water_window) == 1) {
		    if (in_terran[row][col] < water_level) {
			out_water[row][col] =
			    water_level - in_terran[row][col];
			curcount++;
		    }
		    else {
			out_water[row][col] = 0;	/* Cell is higher than water level -> NULL. */
		    }
		}
	    }
	}
	if (curcount == lastcount)
	    break;		/* We done. */
	lastcount = curcount;
	curcount = 0;
	/* Move backwards - from lower right corner to upper left corner. */
	for (row = rows - 1; row >= 0; row--) {
	    for (col = cols - 1; col >= 0; col--) {
		load_window_values(out_water, water_window, rows, cols, row,
				   col);

		if (is_near_water(water_window) == 1) {
		    if (in_terran[row][col] < water_level) {
			out_water[row][col] =
			    water_level - in_terran[row][col];
			curcount++;
		    }
		    else {
			out_water[row][col] = 0;
		    }
		}
	    }
	}
	G_percent(pass + 1, pases, 10);
	if (curcount == lastcount)
	    break;		/* We done. */
	lastcount = curcount;
    }				/*pases */

    G_percent(pases, pases, 10);	/* Show 100%. */

    save_map(out_water, out_fd, rows, cols, negative_flag->answer, &min_depth,
	     &max_depth, &area, &volume);

    G_message(_("Lake depth from %f to %f"), min_depth, max_depth);
    G_message(_("Lake area %f square meters"), area);
    G_message(_("Lake volume %f cubic meters"), volume);
    G_warning(_("Volume is correct only if lake depth (terrain raster map) is in meters"));

    /* Close all files. Lake map gets written only now. */
    G_close_cell(in_terran_fd);
    G_close_cell(out_fd);

    /* Add blue color gradient from light bank to dark depth */
    G_init_colors(&colr);
    if (negative_flag->answer == 1) {
	G_add_f_raster_color_rule(&max_depth, 0, 240, 255,
				  &min_depth, 0, 50, 170, &colr);
    }
    else {
	G_add_f_raster_color_rule(&min_depth, 0, 240, 255,
				  &max_depth, 0, 50, 170, &colr);
    }

    if (G_write_colors(lakemap, G_mapset(), &colr) != 1)
	G_fatal_error(_("Unable to read color file of raster map <%s>"),
		      lakemap);

    G_short_history(lakemap, "raster", &history);
    G_command_history(&history);
    G_write_history(lakemap, &history);

    return EXIT_SUCCESS;
}
Exemplo n.º 4
0
int main(int argc, char *argv[])
{
    int i;
    int print_flag = 0;
    int flat_flag; 
    int set_flag;
    double x;
    int ival;
    int row_flag = 0, col_flag = 0;
    struct Cell_head window, temp_window;
    const char *value;
    const char *name;
    const char *mapset;
    char **rast_ptr, **vect_ptr;

    struct GModule *module;
    struct
    {
	struct Flag
	    *update, *print, *gprint, *flprint, *lprint, *eprint, *nangle,
	    *center, *res_set, *dist_res, *dflt, *z, *savedefault,
	    *bbox, *gmt_style, *wms_style;
    } flag;
    struct
    {
	struct Option
	    *north, *south, *east, *west, *top, *bottom,
	    *res, *nsres, *ewres, *res3, *tbres, *rows, *cols,
	    *save, *region, *raster, *raster3d, *align,
	    *zoom, *vect;
    } parm;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("general"));
    G_add_keyword(_("settings"));
    module->description =
	_("Manages the boundary definitions for the " "geographic region.");

    /* flags */

    flag.dflt = G_define_flag();
    flag.dflt->key = 'd';
    flag.dflt->description = _("Set from default region");
    flag.dflt->guisection = _("Existing");

    flag.savedefault = G_define_flag();
    flag.savedefault->key = 's';
    flag.savedefault->label = _("Save as default region");
    flag.savedefault->description = _("Only possible from the PERMANENT mapset");
    flag.savedefault->guisection = _("Existing");

    flag.print = G_define_flag();
    flag.print->key = 'p';
    flag.print->description = _("Print the current region");
    flag.print->guisection = _("Print");

    flag.lprint = G_define_flag();
    flag.lprint->key = 'l';
    flag.lprint->description = _("Print the current region in lat/long "
				 "using the current ellipsoid/datum");
    flag.lprint->guisection = _("Print");

    flag.eprint = G_define_flag();
    flag.eprint->key = 'e';
    flag.eprint->description = _("Print the current region extent");
    flag.eprint->guisection = _("Print");

    flag.center = G_define_flag();
    flag.center->key = 'c';
    flag.center->description =
	_("Print the current region map center coordinates");
    flag.center->guisection = _("Print");

    flag.gmt_style = G_define_flag();
    flag.gmt_style->key = 't';
    flag.gmt_style->description =
	_("Print the current region in GMT style");
    flag.gmt_style->guisection = _("Print");

    flag.wms_style = G_define_flag();
    flag.wms_style->key = 'w';
    flag.wms_style->description =
	_("Print the current region in WMS style");
    flag.wms_style->guisection = _("Print");

    flag.dist_res = G_define_flag();
    flag.dist_res->key = 'm';
    flag.dist_res->description =
	_("Print region resolution in meters (geodesic)");
    flag.dist_res->guisection = _("Print");

    flag.nangle = G_define_flag();
    flag.nangle->key = 'n';
    flag.nangle->label = _("Print the convergence angle (degrees CCW)");
    flag.nangle->description =
	_("The difference between the projection's grid north and true north, "
	  "measured at the center coordinates of the current region.");
    flag.nangle->guisection = _("Print");

    flag.z = G_define_flag();
    flag.z->key = '3';
    flag.z->description = _("Print also 3D settings");
    flag.z->guisection = _("Print");

    flag.bbox = G_define_flag();
    flag.bbox->key = 'b';
    flag.bbox->description =
	_("Print the maximum bounding box in lat/long on WGS84");
    flag.bbox->guisection = _("Print");

    flag.gprint = G_define_flag();
    flag.gprint->key = 'g';
    flag.gprint->description = _("Print in shell script style");
    flag.gprint->guisection = _("Print");

    flag.flprint = G_define_flag();
    flag.flprint->key = 'f';
    flag.flprint->description = _("Print in shell script style, but in one line (flat)");
    flag.flprint->guisection = _("Print");

    flag.res_set = G_define_flag();
    flag.res_set->key = 'a';
    flag.res_set->description =
	_("Align region to resolution (default = align to bounds, "
	  "works only for 2D resolution)");
    flag.res_set->guisection = _("Bounds");

    flag.update = G_define_flag();
    flag.update->key = 'u';
    flag.update->description = _("Do not update the current region");
    flag.update->guisection = _("Effects");

    /* parameters */

    parm.region = G_define_standard_option(G_OPT_M_REGION);
    parm.region->description = _("Set current region from named region");
    parm.region->guisection = _("Existing");

    parm.raster = G_define_standard_option(G_OPT_R_MAP);
    parm.raster->key = "raster";
    parm.raster->required = NO;
    parm.raster->multiple = YES;
    parm.raster->description = _("Set region to match raster map(s)");
    parm.raster->guisection = _("Existing");

    parm.raster3d = G_define_standard_option(G_OPT_R3_MAP);
    parm.raster3d->key = "raster_3d";
    parm.raster3d->required = NO;
    parm.raster3d->multiple = NO;
    parm.raster3d->description =
	_("Set region to match 3D raster map(s) (both 2D and 3D "
	  "values)");
    parm.raster3d->guisection = _("Existing");

    parm.vect = G_define_standard_option(G_OPT_V_MAP);
    parm.vect->key = "vector";
    parm.vect->required = NO;
    parm.vect->multiple = YES;
    parm.vect->label = _("Set region to match vector map(s)");
    parm.vect->description = NULL;
    parm.vect->guisection = _("Existing");

    parm.north = G_define_option();
    parm.north->key = "n";
    parm.north->key_desc = "value";
    parm.north->required = NO;
    parm.north->multiple = NO;
    parm.north->type = TYPE_STRING;
    parm.north->description = _("Value for the northern edge");
    parm.north->guisection = _("Bounds");

    parm.south = G_define_option();
    parm.south->key = "s";
    parm.south->key_desc = "value";
    parm.south->required = NO;
    parm.south->multiple = NO;
    parm.south->type = TYPE_STRING;
    parm.south->description = _("Value for the southern edge");
    parm.south->guisection = _("Bounds");

    parm.east = G_define_option();
    parm.east->key = "e";
    parm.east->key_desc = "value";
    parm.east->required = NO;
    parm.east->multiple = NO;
    parm.east->type = TYPE_STRING;
    parm.east->description = _("Value for the eastern edge");
    parm.east->guisection = _("Bounds");

    parm.west = G_define_option();
    parm.west->key = "w";
    parm.west->key_desc = "value";
    parm.west->required = NO;
    parm.west->multiple = NO;
    parm.west->type = TYPE_STRING;
    parm.west->description = _("Value for the western edge");
    parm.west->guisection = _("Bounds");

    parm.top = G_define_option();
    parm.top->key = "t";
    parm.top->key_desc = "value";
    parm.top->required = NO;
    parm.top->multiple = NO;
    parm.top->type = TYPE_STRING;
    parm.top->description = _("Value for the top edge");
    parm.top->guisection = _("Bounds");

    parm.bottom = G_define_option();
    parm.bottom->key = "b";
    parm.bottom->key_desc = "value";
    parm.bottom->required = NO;
    parm.bottom->multiple = NO;
    parm.bottom->type = TYPE_STRING;
    parm.bottom->description = _("Value for the bottom edge");
    parm.bottom->guisection = _("Bounds");

    parm.rows = G_define_option();
    parm.rows->key = "rows";
    parm.rows->key_desc = "value";
    parm.rows->required = NO;
    parm.rows->multiple = NO;
    parm.rows->type = TYPE_INTEGER;
    parm.rows->description = _("Number of rows in the new region");
    parm.rows->guisection = _("Resolution");

    parm.cols = G_define_option();
    parm.cols->key = "cols";
    parm.cols->key_desc = "value";
    parm.cols->required = NO;
    parm.cols->multiple = NO;
    parm.cols->type = TYPE_INTEGER;
    parm.cols->description = _("Number of columns in the new region");
    parm.cols->guisection = _("Resolution");

    parm.res = G_define_option();
    parm.res->key = "res";
    parm.res->key_desc = "value";
    parm.res->required = NO;
    parm.res->multiple = NO;
    parm.res->type = TYPE_STRING;
    parm.res->description =
	_("2D grid resolution (north-south and east-west)");
    parm.res->guisection = _("Resolution");

    parm.res3 = G_define_option();
    parm.res3->key = "res3";
    parm.res3->key_desc = "value";
    parm.res3->required = NO;
    parm.res3->multiple = NO;
    parm.res3->type = TYPE_STRING;
    parm.res3->description =
	_("3D grid resolution (north-south, east-west and top-bottom)");
    parm.res3->guisection = _("Resolution");

    parm.nsres = G_define_option();
    parm.nsres->key = "nsres";
    parm.nsres->key_desc = "value";
    parm.nsres->required = NO;
    parm.nsres->multiple = NO;
    parm.nsres->type = TYPE_STRING;
    parm.nsres->description = _("North-south 2D grid resolution");
    parm.nsres->guisection = _("Resolution");

    parm.ewres = G_define_option();
    parm.ewres->key = "ewres";
    parm.ewres->key_desc = "value";
    parm.ewres->required = NO;
    parm.ewres->multiple = NO;
    parm.ewres->type = TYPE_STRING;
    parm.ewres->description = _("East-west 2D grid resolution");
    parm.ewres->guisection = _("Resolution");

    parm.tbres = G_define_option();
    parm.tbres->key = "tbres";
    parm.tbres->key_desc = "value";
    parm.tbres->required = NO;
    parm.tbres->multiple = NO;
    parm.tbres->type = TYPE_STRING;
    parm.tbres->description = _("Top-bottom 3D grid resolution");
    parm.tbres->guisection = _("Resolution");

    parm.zoom = G_define_option();
    parm.zoom->key = "zoom";
    parm.zoom->key_desc = "name";
    parm.zoom->required = NO;
    parm.zoom->multiple = NO;
    parm.zoom->type = TYPE_STRING;
    parm.zoom->description =
	_("Shrink region until it meets non-NULL data from this raster map");
    parm.zoom->gisprompt = "old,cell,raster";
    parm.zoom->guisection = _("Bounds");

    parm.align = G_define_option();
    parm.align->key = "align";
    parm.align->key_desc = "name";
    parm.align->required = NO;
    parm.align->multiple = NO;
    parm.align->type = TYPE_STRING;
    parm.align->description =
	_("Adjust region cells to cleanly align with this raster map");
    parm.align->gisprompt = "old,cell,raster";
    parm.align->guisection = _("Bounds");

    parm.save = G_define_option();
    parm.save->key = "save";
    parm.save->key_desc = "name";
    parm.save->required = NO;
    parm.save->multiple = NO;
    parm.save->type = TYPE_STRING;
    parm.save->description =
	_("Save current region settings in named region file");
    parm.save->gisprompt = "new,windows,region";
    parm.save->guisection = _("Effects");

    G_option_required(flag.dflt, flag.savedefault, flag.print, flag.lprint,
                      flag.eprint, flag.center, flag.gmt_style, flag.wms_style,
                      flag.dist_res, flag.nangle, flag. z, flag.bbox, flag.gprint,
                      flag.res_set, flag.update, parm.region, parm.raster,
                      parm.raster3d, parm.vect, parm.north, parm.south, parm.east,
                      parm.west, parm.top, parm.bottom, parm.rows, parm.cols,
                      parm.res, parm.res3, parm.nsres, parm.ewres, parm.tbres,
                      parm.zoom, parm.align, parm.save, NULL);

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    G_get_default_window(&window);

    set_flag = !flag.update->answer;
    flat_flag = flag.flprint->answer;

    if (flag.print->answer)
	print_flag |= PRINT_REG;

    if (flag.gprint->answer)
	print_flag |= PRINT_SH;

    if (flag.lprint->answer)
	print_flag |= PRINT_LL;

    if (flag.eprint->answer)
	print_flag |= PRINT_EXTENT;

    if (flag.center->answer)
	print_flag |= PRINT_CENTER;

    if (flag.gmt_style->answer)
	print_flag |= PRINT_GMT;

    if (flag.wms_style->answer)
	print_flag |= PRINT_WMS;

    if (flag.nangle->answer)
	print_flag |= PRINT_NANGLE;

    if (flag.dist_res->answer)
	print_flag |= PRINT_METERS;

    if (flag.z->answer)
	print_flag |= PRINT_3D;

    if (flag.bbox->answer)
	print_flag |= PRINT_MBBOX;

    if (print_flag == PRINT_METERS)
	print_flag |= PRINT_SH;

    if (print_flag == PRINT_SH ||
	print_flag & PRINT_3D || print_flag == PRINT_METERS + PRINT_SH) {
	print_flag |= PRINT_REG;
    }

    if (!flag.dflt->answer)
	G_get_window(&window);

    /* region= */
    if ((name = parm.region->answer)) {
	mapset = G_find_file2("windows", name, "");
	if (!mapset)
	    G_fatal_error(_("Region <%s> not found"), name);
	G_get_element_window(&window, "windows", name, mapset);
    }

    /* raster= */
    if (parm.raster->answer) {
	int first = 0;

	rast_ptr = parm.raster->answers;
	for (; *rast_ptr != NULL; rast_ptr++) {
	    char rast_name[GNAME_MAX];

	    strcpy(rast_name, *rast_ptr);
	    mapset = G_find_raster2(rast_name, "");
	    if (!mapset)
		G_fatal_error(_("Raster map <%s> not found"), rast_name);
	    Rast_get_cellhd(rast_name, mapset, &temp_window);
	    if (!first) {
		window = temp_window;
		first = 1;
	    }
	    else {
		window.north = (window.north > temp_window.north) ?
		    window.north : temp_window.north;
		window.south = (window.south < temp_window.south) ?
		    window.south : temp_window.south;
		window.east = (window.east > temp_window.east) ?
		    window.east : temp_window.east;
		window.west = (window.west < temp_window.west) ?
		    window.west : temp_window.west;
	    }
	}
	G_adjust_Cell_head3(&window, 0, 0, 0);
    }


    /* raster3d= */
    if ((name = parm.raster3d->answer)) {
	RASTER3D_Region win;

	if ((mapset = G_find_raster3d(name, "")) == NULL)
	    G_fatal_error(_("3D raster map <%s> not found"), name);

	if (Rast3d_read_region_map(name, mapset, &win) < 0)
	    G_fatal_error(_("Unable to read header of 3D raster map <%s@%s>"),
			  name, mapset);

	Rast3d_region_to_cell_head(&win, &window);
    }

    /* vector= */
    if (parm.vect->answer) {
	int first = 0;

	vect_ptr = parm.vect->answers;
	for (; *vect_ptr != NULL; vect_ptr++) {
	    struct Map_info Map;
	    struct bound_box box;
	    char vect_name[GNAME_MAX];
	    struct Cell_head map_window;

	    strcpy(vect_name, *vect_ptr);
	    mapset = G_find_vector2(vect_name, "");
	    if (!mapset)
		G_fatal_error(_("Vector map <%s> not found"), vect_name);

	    temp_window = window;

	    Vect_set_open_level(2);
	    if (2 > Vect_open_old_head(&Map, vect_name, mapset))
		G_fatal_error(_("Unable to open vector map <%s> on topological level"),
			      vect_name);
            
	    Vect_get_map_box(&Map, &box);
	    map_window = window;
	    map_window.north = box.N;
	    map_window.south = box.S;
	    map_window.west = box.W;
	    map_window.east = box.E;
	    map_window.top = box.T;
	    map_window.bottom = box.B;

	    if (!first) {
		window = map_window;
		first = 1;
	    }
	    else {
		window.north = (window.north > map_window.north) ?
		    window.north : map_window.north;
		window.south = (window.south < map_window.south) ?
		    window.south : map_window.south;
		window.east = (window.east > map_window.east) ?
		    window.east : map_window.east;
		window.west = (window.west < map_window.west) ?
		    window.west : map_window.west;
		if (map_window.top > window.top)
		    window.top = map_window.top;
		if (map_window.bottom < window.bottom)
		    window.bottom = map_window.bottom;
	    }

	    if (window.north == window.south) {
		window.north = window.north + 0.5 * temp_window.ns_res;
		window.south = window.south - 0.5 * temp_window.ns_res;
	    }
	    if (window.east == window.west) {
		window.west = window.west - 0.5 * temp_window.ew_res;
		window.east = window.east + 0.5 * temp_window.ew_res;
	    }
	    if (window.top == window.bottom) {
		window.bottom = (window.bottom - 0.5 * temp_window.tb_res);
		window.top = (window.top + 0.5 * temp_window.tb_res);
	    }

	    if (flag.res_set->answer)
		Rast_align_window(&window, &temp_window);

	    Vect_close(&Map);
	}
    }

    /* n= */
    if ((value = parm.north->answer)) {
	if ((i = nsew(value, "n+", "n-", "s+"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.north);
	    switch (i) {
	    case 1:
		window.north += x;
		break;
	    case 2:
		window.north -= x;
		break;
	    case 3:
		window.north = window.south + x;
		break;
	    }
	}
	else if (G_scan_northing(value, &x, window.proj))
	    window.north = x;
	else
	    die(parm.north);
    }

    /* s= */
    if ((value = parm.south->answer)) {
	if ((i = nsew(value, "s+", "s-", "n-"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.south);
	    switch (i) {
	    case 1:
		window.south += x;
		break;
	    case 2:
		window.south -= x;
		break;
	    case 3:
		window.south = window.north - x;
		break;
	    }
	}
	else if (G_scan_northing(value, &x, window.proj))
	    window.south = x;
	else
	    die(parm.south);
    }

    /* e= */
    if ((value = parm.east->answer)) {
	if ((i = nsew(value, "e+", "e-", "w+"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.east);
	    switch (i) {
	    case 1:
		window.east += x;
		break;
	    case 2:
		window.east -= x;
		break;
	    case 3:
		window.east = window.west + x;
		break;
	    }
	}
	else if (G_scan_easting(value, &x, window.proj))
	    window.east = x;
	else
	    die(parm.east);
    }

    /* w= */
    if ((value = parm.west->answer)) {
	if ((i = nsew(value, "w+", "w-", "e-"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.west);
	    switch (i) {
	    case 1:
		window.west += x;
		break;
	    case 2:
		window.west -= x;
		break;
	    case 3:
		window.west = window.east - x;
		break;
	    }
	}
	else if (G_scan_easting(value, &x, window.proj))
	    window.west = x;
	else
	    die(parm.west);
    }

    /* t= */
    if ((value = parm.top->answer)) {
	if ((i = nsew(value, "t+", "t-", "b+"))) {
	    if (sscanf(value + 2, "%lf", &x) != 1)
		die(parm.top);
	    switch (i) {
	    case 1:
		window.top += x;
		break;
	    case 2:
		window.top -= x;
		break;
	    case 3:
		window.top = window.bottom + x;
		break;
	    }
	}
	else if (sscanf(value, "%lf", &x) == 1)
	    window.top = x;
	else
	    die(parm.top);
    }

    /* b= */
    if ((value = parm.bottom->answer)) {
	if ((i = nsew(value, "b+", "b-", "t-"))) {
	    if (sscanf(value + 2, "%lf", &x) != 1)
		die(parm.bottom);
	    switch (i) {
	    case 1:
		window.bottom += x;
		break;
	    case 2:
		window.bottom -= x;
		break;
	    case 3:
		window.bottom = window.top - x;
		break;
	    }
	}
	else if (sscanf(value, "%lf", &x) == 1)
	    window.bottom = x;
	else
	    die(parm.bottom);
    }

    /* res= */
    if ((value = parm.res->answer)) {
	if (!G_scan_resolution(value, &x, window.proj))
	    die(parm.res);
	window.ns_res = x;
	window.ew_res = x;

	if (flag.res_set->answer) {
	    window.north = ceil(window.north / x) * x;
	    window.south = floor(window.south / x) * x;
	    window.east = ceil(window.east / x) * x;
	    window.west = floor(window.west / x) * x;
	}
    }

    /* res3= */
    if ((value = parm.res3->answer)) {
	if (!G_scan_resolution(value, &x, window.proj))
	    die(parm.res);
	window.ns_res3 = x;
	window.ew_res3 = x;
	window.tb_res = x;
    }

    /* nsres= */
    if ((value = parm.nsres->answer)) {
	if (!G_scan_resolution(value, &x, window.proj))
	    die(parm.nsres);
	window.ns_res = x;

	if (flag.res_set->answer) {
	    window.north = ceil(window.north / x) * x;
	    window.south = floor(window.south / x) * x;
	}
    }

    /* ewres= */
    if ((value = parm.ewres->answer)) {
	if (!G_scan_resolution(value, &x, window.proj))
	    die(parm.ewres);
	window.ew_res = x;

	if (flag.res_set->answer) {
	    window.east = ceil(window.east / x) * x;
	    window.west = floor(window.west / x) * x;
	}
    }

    /* tbres= */
    if ((value = parm.tbres->answer)) {
	if (sscanf(value, "%lf", &x) != 1)
	    die(parm.tbres);
	window.tb_res = x;

	if (flag.res_set->answer) {
	    window.top = ceil(window.top / x) * x;
	    window.bottom = floor(window.bottom / x) * x;
	}
    }

    /* rows= */
    if ((value = parm.rows->answer)) {
	if (sscanf(value, "%i", &ival) != 1)
	    die(parm.rows);
	window.rows = ival;
	row_flag = 1;
    }

    /* cols= */
    if ((value = parm.cols->answer)) {
	if (sscanf(value, "%i", &ival) != 1)
	    die(parm.cols);
	window.cols = ival;
	col_flag = 1;
    }

    /* zoom= */
    if ((name = parm.zoom->answer)) {
	mapset = G_find_raster2(name, "");
	if (!mapset)
	    G_fatal_error(_("Raster map <%s> not found"), name);
	zoom(&window, name, mapset);
    }

    /* align= */
    if ((name = parm.align->answer)) {
	mapset = G_find_raster2(name, "");
	if (!mapset)
	    G_fatal_error(_("Raster map <%s> not found"), name);
	Rast_get_cellhd(name, mapset, &temp_window);
	Rast_align_window(&window, &temp_window);
    }

    /* save= */
    if ((name = parm.save->answer)) {
	temp_window = window;
	G_adjust_Cell_head3(&temp_window, 0, 0, 0);
	if (G_put_element_window(&temp_window, "windows", name) < 0)
	    G_fatal_error(_("Unable to set region <%s>"), name);
    }

    G_adjust_Cell_head3(&window, row_flag, col_flag, 0);
    if (set_flag) {
	if (G_put_window(&window) < 0)
	    G_fatal_error(_("Unable to update current region"));
    }

    if (flag.savedefault->answer) {
	if (strcmp(G_mapset(), "PERMANENT") == 0) {
	    G_put_element_window(&window, "", "DEFAULT_WIND");
	}
	else {
	    G_fatal_error(_("Unable to change default region. "
			    "The current mapset is not <PERMANENT>."));
	}
    }				/* / flag.savedefault->answer */


    if (print_flag)
	print_window(&window, print_flag, flat_flag);

    exit(EXIT_SUCCESS);
}
Exemplo n.º 5
0
int main(int argc, char *argv[]) {
	struct GModule *module;
	struct {
		struct Option *input;
		struct Option *output;
		struct Option *null;
		struct Option *bytes;
		struct Option *order;
		struct Option *north;
		struct Option *south;
		struct Option *top;
		struct Option *bottom;
		struct Option *east;
		struct Option *west;
		struct Option *rows;
		struct Option *cols;
		struct Option *depths;
	} parm;
	struct {
		struct Flag *integer_in;
		struct Flag *sign;
		struct Flag *depth;
		struct Flag *row;
	} flag;
	const char *input;
	const char *output;
	int is_integer;
	int is_signed;
	int bytes;
	int order;
	int byte_swap;
	RASTER_MAP_TYPE map_type;
	off_t file_size;
	struct History history;
	off_t expected;
	/* Need to be allocated later */
	in_cell = NULL;

	G_gisinit(argv[0]);

	/* Set description */
	module = G_define_module();
	G_add_keyword(_("raster3d"));
	G_add_keyword(_("import"));
	G_add_keyword(_("voxel"));
	module->description =
			_("Imports a binary raster file into a GRASS 3D raster map.");

	parm.input = G_define_standard_option(G_OPT_F_BIN_INPUT);
	parm.input->description = _("Name of binary 3D raster file to be imported");

	parm.output = G_define_standard_option(G_OPT_R3_OUTPUT);

	parm.bytes = G_define_option();
	parm.bytes->key = "bytes";
	parm.bytes->type = TYPE_INTEGER;
	parm.bytes->required = YES;
	parm.bytes->options = "1,2,4,8";
	parm.bytes->description = _("Number of bytes per cell in binary file");

	parm.order = G_define_option();
	parm.order->key = "order";
	parm.order->type = TYPE_STRING;
	parm.order->required = NO;
	parm.order->options = "big,little,native,swap";
	parm.order->description = _("Byte order in binary file");
	parm.order->answer = "native";

	parm.north = G_define_option();
	parm.north->key = "north";
	parm.north->type = TYPE_DOUBLE;
	parm.north->required = YES;
	parm.north->description =
			_("Northern limit of geographic region (outer edge)");
	parm.north->guisection = _("Bounds");

	parm.south = G_define_option();
	parm.south->key = "south";
	parm.south->type = TYPE_DOUBLE;
	parm.south->required = YES;
	parm.south->description =
			_("Southern limit of geographic region (outer edge)");
	parm.south->guisection = _("Bounds");

	parm.east = G_define_option();
	parm.east->key = "east";
	parm.east->type = TYPE_DOUBLE;
	parm.east->required = YES;
	parm.east->description =
			_("Eastern limit of geographic region (outer edge)");
	parm.east->guisection = _("Bounds");

	parm.west = G_define_option();
	parm.west->key = "west";
	parm.west->type = TYPE_DOUBLE;
	parm.west->required = YES;
	parm.west->description =
			_("Western limit of geographic region (outer edge)");
	parm.west->guisection = _("Bounds");

	parm.bottom = G_define_option();
	parm.bottom->key = "bottom";
	parm.bottom->type = TYPE_DOUBLE;
	parm.bottom->required = YES;
	parm.bottom->description =
			_("Bottom limit of geographic region (outer edge)");
	parm.bottom->guisection = _("Bounds");

	parm.top = G_define_option();
	parm.top->key = "top";
	parm.top->type = TYPE_DOUBLE;
	parm.top->required = YES;
	parm.top->description = _("Top limit of geographic region (outer edge)");
	parm.top->guisection = _("Bounds");

	parm.rows = G_define_option();
	parm.rows->key = "rows";
	parm.rows->type = TYPE_INTEGER;
	parm.rows->required = YES;
	parm.rows->description = _("Number of rows");
	parm.rows->guisection = _("Bounds");

	parm.cols = G_define_option();
	parm.cols->key = "cols";
	parm.cols->type = TYPE_INTEGER;
	parm.cols->required = YES;
	parm.cols->description = _("Number of columns");
	parm.cols->guisection = _("Bounds");

	parm.depths = G_define_option();
	parm.depths->key = "depths";
	parm.depths->type = TYPE_INTEGER;
	parm.depths->required = YES;
	parm.depths->description = _("Number of depths");
	parm.depths->guisection = _("Bounds");

	parm.null = G_define_option();
	parm.null->key = "null";
	parm.null->type = TYPE_DOUBLE;
	parm.null->required = NO;
	parm.null->description = _("Set Value to NULL");

	flag.row = G_define_flag();
	flag.row->key = 'r';
	flag.row->description = _("Switch the row order in output from "
			"north->south to south->north");

	flag.depth = G_define_flag();
	flag.depth->key = 'd';
	flag.depth->description = _("Switch the depth order in output "
			"from bottom->top to top->bottom");

	flag.integer_in = G_define_flag();
	flag.integer_in->key = 'i';
	flag.integer_in->description =
			_("Binary data is of type integer");

	flag.sign = G_define_flag();
	flag.sign->key = 's';
	flag.sign->description = _("Signed data (two's complement)");

	if (G_parser(argc, argv))
		exit(EXIT_FAILURE);

	input = parm.input->answer;
	output = parm.output->answer;

	if (G_strcasecmp(parm.order->answer, "big") == 0)
		order = 0;
	else if (G_strcasecmp(parm.order->answer, "little") == 0)
		order = 1;
	else if (G_strcasecmp(parm.order->answer, "native") == 0)
		order = G_is_little_endian() ? 1 : 0;
	else if (G_strcasecmp(parm.order->answer, "swap") == 0)
		order = G_is_little_endian() ? 0 : 1;

	byte_swap = order == (G_is_little_endian() ? 0 : 1);

	is_signed = !!flag.sign->answer;

	is_integer = 0;
	bytes = 8;

	if (parm.bytes->answer)
		bytes = atoi(parm.bytes->answer);

	if (!flag.integer_in->answer) {
		if (bytes && bytes < 4)
			G_fatal_error(
					_("bytes=%d; must be 4 or 8 in case of floating point input"),
					bytes);
		if (!bytes)
			bytes = 4;
	} else {
		is_integer = 1;
	}

#ifndef HAVE_LONG_LONG_INT
	if (is_integer && bytes > 4)
	G_fatal_error(_("Integer input doesn't support size=8 in this build"));
#endif

	if (bytes != 1 && bytes != 2 && bytes != 4 && bytes != 8)
		G_fatal_error(_("bytes= must be 1, 2, 4 or 8"));

	region.zone = G_zone();
	region.proj = G_projection();
	region.rows = atoi(parm.rows->answer);
	region.cols = atoi(parm.cols->answer);
	region.depths = atoi(parm.depths->answer);
	region.top = atof(parm.top->answer);
	region.bottom = atof(parm.bottom->answer);

	if (!G_scan_northing(parm.north->answer, &region.north, region.proj))
		G_fatal_error(_("Illegal north coordinate <%s>"), parm.north->answer);
	if (!G_scan_northing(parm.south->answer, &region.south, region.proj))
		G_fatal_error(_("Illegal south coordinate <%s>"), parm.south->answer);
	if (!G_scan_easting(parm.east->answer, &region.east, region.proj))
		G_fatal_error(_("Illegal east coordinate <%s>"), parm.east->answer);
	if (!G_scan_easting(parm.west->answer, &region.west, region.proj))
		G_fatal_error(_("Illegal west coordinate <%s>"), parm.west->answer);

	Rast3d_adjust_region(&region);

	expected = (off_t) region.rows * region.cols * region.depths * bytes;

	fp = fopen(input, "rb");
	if (!fp)
		G_fatal_error(_("Unable to open <%s>"), input);

	/* Find File Size in Byte and Check against byte size */
	G_fseek(fp, 0, SEEK_END);
	file_size = G_ftell(fp);
	G_fseek(fp, 0, SEEK_SET);

	if (file_size != expected) {
		G_warning(_("File Size %lld ... Total Bytes %lld"),
				(long long int) file_size, (long long int) expected);
		G_fatal_error(_("Bytes do not match file size"));
	}

	map_type = (bytes > 4 ? DCELL_TYPE : FCELL_TYPE);

	if(is_integer && bytes >= 4)
		map_type = DCELL_TYPE;

	Rast3d_init_defaults();

	/*Open the new 3D raster map */
	map = Rast3d_open_new_opt_tile_size(output, RASTER3D_USE_CACHE_DEFAULT,
			&region, map_type, 32);

	if (map == NULL)
		G_fatal_error(_("Unable to open 3D raster map"));

	in_cell = G_malloc(bytes);

	bin_to_raster3d(parm.null->answer, map_type, is_integer, is_signed, bytes,
			byte_swap, flag.row->answer, flag.depth->answer);

	if (!Rast3d_close(map))
		G_fatal_error(_("Unable to close 3D raster map"));

	/* write input name to map history */
	Rast3d_read_history(output, G_mapset(), &history);
	Rast_set_history(&history, HIST_DATSRC_1, input);
	Rast3d_write_history(output, &history);

	fclose(fp);
	if (in_cell)
		G_free(in_cell);

	return EXIT_SUCCESS;
}
Exemplo n.º 6
0
int main(int argc, char **argv)
{
    int n, verbose = 1,
	backrow, backcol,
	col, row,
	len, flag,
	srows, scols,
	backrow_fd, backcol_fd, path_fd, in_row_fd, in_col_fd, out_fd;
    const char *current_mapset,
	*search_mapset,
	*path_mapset,
	*backrow_mapset,
	*backcol_mapset, *in_row_file, *in_col_file, *out_file;
    CELL *cell;
    POINT *PRES_PT, *PRESENT_PT, *OLD_PT;
    struct Cell_head window;
    double east, north;
    struct Option *opt1, *opt2, *opt3, *opt4;
    struct Flag *flag1;
    struct GModule *module;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("fire"));
    G_add_keyword(_("cumulative costs"));
    module->description =
	_("Recursively traces the least cost path backwards to "
	  "cells from which the cumulative cost was determined.");

    opt1 = G_define_option();
    opt1->key = "x_input";
    opt1->type = TYPE_STRING;
    opt1->required = YES;
    opt1->gisprompt = "old,cell,raster";
    opt1->description =
	_("Name of raster map containing back-path easting information");

    opt2 = G_define_option();
    opt2->key = "y_input";
    opt2->type = TYPE_STRING;
    opt2->required = YES;
    opt2->gisprompt = "old,cell,raster";
    opt2->description =
	_("Name of raster map containing back-path northing information");

    opt3 = G_define_option();
    opt3->key = "coordinate";
    opt3->type = TYPE_STRING;
    opt3->multiple = YES;
    opt3->key_desc = "x,y";
    opt3->description =
	_("The map E and N grid coordinates of starting points");

    opt4 = G_define_option();
    opt4->key = "output";
    opt4->type = TYPE_STRING;
    opt4->required = YES;
    opt4->gisprompt = "new,cell,raster";
    opt4->description = _("Name of spread path raster map");

    flag1 = G_define_flag();
    flag1->key = 'v';
    flag1->description = _("Run verbosely");

    /*   Do command line parsing    */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    current_mapset = G_mapset();
    in_row_file = G_tempfile();
    in_col_file = G_tempfile();
    out_file = G_tempfile();

    /*  Get database window parameters      */
    G_get_window(&window);

    verbose = flag1->answer;

    /*  Check if backrow layer exists in data base  */
    search_mapset = "";

    strcpy(backrow_layer, opt2->answer);
    strcpy(backcol_layer, opt1->answer);

    backrow_mapset = G_find_raster(backrow_layer, search_mapset);
    backcol_mapset = G_find_raster(backcol_layer, search_mapset);

    if (backrow_mapset == NULL)
	G_fatal_error("%s - not found", backrow_layer);

    if (backcol_mapset == NULL)
	G_fatal_error("%s - not found", backcol_layer);

    search_mapset = "";

    strcpy(path_layer, opt4->answer);

    path_mapset = G_find_raster(path_layer, search_mapset);

    /*  find number of rows and cols in window    */
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    cell = Rast_allocate_c_buf();

    /*  Open back cell layers for reading  */
    backrow_fd = Rast_open_old(backrow_layer, backrow_mapset);
    backcol_fd = Rast_open_old(backcol_layer, backcol_mapset);

    /*   Parameters for map submatrices   */
    len = sizeof(CELL);

    srows = nrows / 4 + 1;
    scols = ncols / 4 + 1;

    if (verbose)
	G_message
	    ("\nReading the input map -%s- and -%s- and creating some temporary files...",
	     backrow_layer, backcol_layer);

    /* Create segmented files for back cell and output layers  */
    in_row_fd = creat(in_row_file, 0666);
    segment_format(in_row_fd, nrows, ncols, srows, scols, len);
    close(in_row_fd);
    in_col_fd = creat(in_col_file, 0666);
    segment_format(in_col_fd, nrows, ncols, srows, scols, len);
    close(in_col_fd);

    out_fd = creat(out_file, 0666);
    segment_format(out_fd, nrows, ncols, srows, scols, len);
    close(out_fd);

    /*   Open initialize and segment all files  */
    in_row_fd = open(in_row_file, 2);
    segment_init(&in_row_seg, in_row_fd, 4);
    in_col_fd = open(in_col_file, 2);
    segment_init(&in_col_seg, in_col_fd, 4);

    out_fd = open(out_file, 2);
    segment_init(&out_seg, out_fd, 4);

    /*   Write the back cell layers in the segmented files, and  
     *   Change UTM coordinates to ROWs and COLUMNs */
    for (row = 0; row < nrows; row++) {
	Rast_get_c_row(backrow_fd, cell, row);

	for (col = 0; col < ncols; col++)
	    if (cell[col] > 0)
		cell[col] =
		    (window.north - cell[col]) / window.ns_res /* - 0.5 */ ;
	    else
		cell[col] = -1;
	segment_put_row(&in_row_seg, cell, row);
	Rast_get_c_row(backcol_fd, cell, row);

	for (col = 0; col < ncols; col++)
	    if (cell[col] > 0)
		cell[col] =
		    (cell[col] - window.west) / window.ew_res /* - 0.5 */ ;
	segment_put_row(&in_col_seg, cell, row);
    }

    /* Convert easting and northing from the command line to row and col */
    if (opt3->answer) {
	for (n = 0; opt3->answers[n] != NULL; n += 2) {
	    G_scan_easting(opt3->answers[n], &east, G_projection());
	    G_scan_northing(opt3->answers[n + 1], &north, G_projection());
	    row = (window.north - north) / window.ns_res;
	    col = (east - window.west) / window.ew_res;
	    /* ignore pt outside window */
	    if (east < window.west || east > window.east ||
		north < window.south || north > window.north) {
		G_warning("Ignoring point outside window: ");
		G_warning("   %.4f,%.4f", east, north);
		continue;
	    }

	    value = (char *)&backrow;
	    segment_get(&in_row_seg, value, row, col);
	    /* ignore pt in no-data area */
	    if (backrow < 0) {
		G_warning("Ignoring point in NO-DATA area :");
		G_warning("   %.4f,%.4f", east, north);
		continue;
	    }
	    value = (char *)&backcol;
	    segment_get(&in_col_seg, value, row, col);

	    insert(&PRESENT_PT, row, col, backrow, backcol);
	}
    }

    /*  Set flag according to input */
    if (path_mapset != NULL) {
	if (head_start_pt == NULL)
	    /*output layer exists and start pts are not given on cmd line */
	    flag = 1;

	/* output layer exists and starting pts are given on cmd line */
	else
	    flag = 2;
    }
    else
	flag = 3;		/* output layer does not previously exist */

    /* If the output layer containing the starting positions */
    /* create a linked list of of them  */
    if (flag == 1) {
	path_fd = Rast_open_old(path_layer, path_mapset);

	/*  Search for the marked starting pts and make list    */
	for (row = 0; row < nrows; row++) {
	    Rast_get_c_row(path_fd, cell, row);

	    for (col = 0; col < ncols; col++) {
		if (cell[col] > 0) {
		    value = (char *)&backrow;
		    segment_get(&in_row_seg, value, row, col);
		    /* ignore pt in no-data area */
		    if (backrow < 0) {
			G_warning("Ignoring point in NO-DATA area:");
			G_warning("   %.4f,%.4f\n",
				  window.west + window.ew_res * (col + 0.5),
				  window.north - window.ns_res * (row + 0.5));
			continue;
		    }
		    value = (char *)&backcol;
		    segment_get(&in_col_seg, value, row, col);
		    insert(&PRESENT_PT, row, col, backrow, backcol);
		}
	    }			/* loop over cols */
	}			/* loop over rows */

	Rast_close(path_fd);
    }

    /* loop over the starting points to find the least cost paths */
    if (verbose)
	G_message("\nFinding the least cost paths ...");

    PRES_PT = head_start_pt;
    while (PRES_PT != NULL) {
	path_finder(PRES_PT->row, PRES_PT->col, PRES_PT->backrow,
		    PRES_PT->backcol);

	OLD_PT = PRES_PT;
	PRES_PT = NEXT_PT;
	G_free(OLD_PT);
    }

    /* Write pending updates by segment_put() to outputmap */
    segment_flush(&out_seg);

    if (verbose)
	G_message("\nWriting the output map  -%s-...", path_layer);

    path_fd = Rast_open_c_new(path_layer);
    for (row = 0; row < nrows; row++) {
	segment_get_row(&out_seg, cell, row);
	Rast_put_row(path_fd, cell, CELL_TYPE);
    }

    if (verbose)
	G_message("finished.");

    segment_release(&in_row_seg);	/* release memory  */
    segment_release(&in_col_seg);
    segment_release(&out_seg);

    close(in_row_fd);		/* close all files */
    close(in_col_fd);
    close(out_fd);

    Rast_close(path_fd);
    Rast_close(backrow_fd);
    Rast_close(backcol_fd);

    unlink(in_row_file);	/* remove submatrix files  */
    unlink(in_col_file);
    unlink(out_file);

    exit(EXIT_SUCCESS);
}
Exemplo n.º 7
0
/* *************************************************************** */
int main(int argc, char *argv[])
{
    int i, j;
    int nfiles;
    int fd[NFILES];
    struct Categories cats[NFILES];
    struct Cell_head window;
    struct Colors ncolor[NFILES];
    struct Colors colors;
    RASTER_MAP_TYPE out_type[NFILES];
    CELL *cell[NFILES];
    DCELL *dcell[NFILES];

    /*   int row, col; */
    double drow, dcol;
    int row_in_window, in_window;
    double east, north;
    int line;
    char buffer[1024];
    char **ptr;
    struct Option *opt1, *opt2, *opt3, *opt4, *opt_fs;
    struct Flag *label_flag, *cache_flag, *int_flag, *color_flag, *header_flag;
    char fs;
    int Cache_size;
    int done = FALSE;
    int point, point_cnt;
    struct order *cache;
    int cur_row;
    int projection;
    int cache_hit = 0, cache_miss = 0;
    int cache_hit_tot = 0, cache_miss_tot = 0;
    int pass = 0;
    int cache_report = FALSE;
    char tmp_buf[500], *null_str;
    int red, green, blue;
    struct GModule *module;


    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("position"));
    G_add_keyword(_("querying"));
    module->description =
	_("Queries raster map layers on their category values and category labels.");

    opt1 = G_define_option();
    opt1->key = "input";
    opt1->type = TYPE_STRING;
    opt1->required = YES;
    opt1->multiple = YES;
    opt1->gisprompt = "old,cell,raster";
    opt1->description = _("Name of existing raster map(s) to query");

    opt2 = G_define_option();
    opt2->key = "cache";
    opt2->type = TYPE_INTEGER;
    opt2->required = NO;
    opt2->multiple = NO;
    opt2->description = _("Size of point cache");
    opt2->answer = "500";
    opt2->guisection = _("Advanced");

    opt3 = G_define_option();
    opt3->key = "null";
    opt3->type = TYPE_STRING;
    opt3->required = NO;
    opt3->answer = "*";
    opt3->description = _("Char string to represent no data cell");

    opt_fs = G_define_standard_option(G_OPT_F_SEP);

    opt4 = G_define_option();
    opt4->key = "east_north";
    opt4->type = TYPE_DOUBLE;
    opt4->key_desc = "east,north";
    opt4->required = NO;
    opt4->multiple = YES;
    opt4->description = _("Coordinates for query");

    header_flag = G_define_flag();
    header_flag->key = 'n';
    header_flag->description = _("Output header row");

    label_flag = G_define_flag();
    label_flag->key = 'f';
    label_flag->description = _("Show the category labels of the grid cell(s)");

    color_flag = G_define_flag();
    color_flag->key = 'r';
    color_flag->description = _("Output color values as RRR:GGG:BBB");

    int_flag = G_define_flag();
    int_flag->key = 'i';
    int_flag->description = _("Output integer category values, not cell values");

    cache_flag = G_define_flag();
    cache_flag->key = 'c';
    cache_flag->description = _("Turn on cache reporting");
    cache_flag->guisection = _("Advanced");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    tty = isatty(0);

    projection = G_projection();

    /* see v.in.ascii for a better solution */
    if (opt_fs->answer != NULL) {
	if (strcmp(opt_fs->answer, "space") == 0)
	    fs = ' ';
	else if (strcmp(opt_fs->answer, "tab") == 0)
	    fs = '\t';
	else if (strcmp(opt_fs->answer, "\\t") == 0)
	    fs = '\t';
	else
	    fs = opt_fs->answer[0];
    }

    null_str = opt3->answer;


    if (tty)
	Cache_size = 1;
    else
	Cache_size = atoi(opt2->answer);

    if (Cache_size < 1)
	Cache_size = 1;

    cache = (struct order *)G_malloc(sizeof(struct order) * Cache_size);

    /*enable cache report */
    if (cache_flag->answer)
	cache_report = TRUE;


    ptr = opt1->answers;
    nfiles = 0;
    for (; *ptr != NULL; ptr++) {
	char name[GNAME_MAX];

	if (nfiles >= NFILES)
	    G_fatal_error(_("can only do up to %d raster maps"),
			  NFILES);

	strcpy(name, *ptr);
	fd[nfiles] = Rast_open_old(name, "");

	out_type[nfiles] = Rast_get_map_type(fd[nfiles]);
	if (int_flag->answer)
	    out_type[nfiles] = CELL_TYPE;

	if (color_flag->answer) {
	    Rast_read_colors(name, "", &colors);
	    ncolor[nfiles] = colors;
	}

	if (label_flag->answer && Rast_read_cats(name, "", &cats[nfiles]) < 0)
	    G_fatal_error(_("Unable to read category file for <%s>"), name);

	nfiles++;
    }

    for (i = 0; i < nfiles; i++) {
	if (int_flag->answer)
	    out_type[i] = CELL_TYPE;

	cell[i] = Rast_allocate_c_buf();
	if (out_type[i] != CELL_TYPE)
	    dcell[i] = Rast_allocate_d_buf();
    }

    G_get_window(&window);


    if(header_flag->answer) {
	fprintf(stdout, "easting%cnorthing%csite_name", fs, fs);

	ptr = opt1->answers;
	for (; *ptr != NULL; ptr++) {
	    char name[GNAME_MAX];
	    strcpy(name, *ptr);

	    fprintf(stdout, "%c%s", fs, name);

	    if (label_flag->answer)
		fprintf(stdout, "%c%s_label", fs, name);
	    if (color_flag->answer)
		fprintf(stdout, "%c%s_color", fs, name);
	}

	fprintf(stdout, "\n");
    }

    line = 0;
    if (!opt4->answers && tty)
	fprintf(stderr, "enter points, \"end\" to quit\n");

    j = 0;
    done = FALSE;
    while (!done) {
	pass++;
	if (cache_report & !tty)
	    fprintf(stderr, "Pass %3d  Line %6d   - ", pass, line);

	cache_hit = cache_miss = 0;

	if (!opt4->answers && tty) {
	    fprintf(stderr, "\neast north [label] >  ");
	    Cache_size = 1;
	}
	{
	    point_cnt = 0;
	    for (i = 0; i < Cache_size; i++) {
		if (!opt4->answers && fgets(buffer, 1000, stdin) == NULL)
		    done = TRUE;
		else {
		    line++;
		    if ((!opt4->answers &&
			 (strncmp(buffer, "end\n", 4) == 0 ||
			  strncmp(buffer, "exit\n", 5) == 0)) ||
			(opt4->answers && !opt4->answers[j]))
			done = TRUE;
		    else {
			*(cache[point_cnt].lab_buf) =
			    *(cache[point_cnt].east_buf) =
			    *(cache[point_cnt].north_buf) = 0;
			if (!opt4->answers)
			    sscanf(buffer, "%s %s %[^\n]",
				   cache[point_cnt].east_buf,
				   cache[point_cnt].north_buf,
				   cache[point_cnt].lab_buf);
			else {
			    strcpy(cache[point_cnt].east_buf,
				   opt4->answers[j++]);
			    strcpy(cache[point_cnt].north_buf,
				   opt4->answers[j++]);
			}
			if (*(cache[point_cnt].east_buf) == 0)
			    continue;	/* skip blank lines */

			if (*(cache[point_cnt].north_buf) == 0) {
			    oops(line, buffer,
				 "two coordinates (east north) required");
			    continue;
			}
			if (!G_scan_northing
			    (cache[point_cnt].north_buf, &north, window.proj)
			    || !G_scan_easting(cache[point_cnt].east_buf,
					       &east, window.proj)) {
			    oops(line, buffer, "invalid coordinate(s)");
			    continue;
			}

			/* convert north, east to row and col */
			drow = Rast_northing_to_row(north, &window);
			dcol = Rast_easting_to_col(east, &window);

			/* a special case.
			 *   if north falls at southern edge, or east falls on eastern edge,
			 *   the point will appear outside the window.
			 *   So, for these edges, bring the point inside the window
			 */
			if (drow == window.rows)
			    drow--;
			if (dcol == window.cols)
			    dcol--;

			cache[point_cnt].row = (int)drow;
			cache[point_cnt].col = (int)dcol;
			cache[point_cnt].point = point_cnt;
			point_cnt++;
		    }
		}
	    }
	}

	if (Cache_size > 1)
	    qsort(cache, point_cnt, sizeof(struct order), by_row);

	/* extract data from files and store in cache */

	cur_row = -99;

	for (point = 0; point < point_cnt; point++) {
	    row_in_window = 1;
	    in_window = 1;
	    if (cache[point].row < 0 || cache[point].row >= window.rows)
		row_in_window = in_window = 0;
	    if (cache[point].col < 0 || cache[point].col >= window.cols)
		in_window = 0;

	    if (!in_window) {
		if (tty)
		    fprintf(stderr,
			    "** note ** %s %s is outside your current window\n",
			    cache[point].east_buf, cache[point].north_buf);
	    }

	    if (cur_row != cache[point].row) {
		cache_miss++;
		if (row_in_window)
		    for (i = 0; i < nfiles; i++) {
			Rast_get_c_row(fd[i], cell[i], cache[point].row);

			if (out_type[i] != CELL_TYPE)
			    Rast_get_d_row(fd[i], dcell[i], cache[point].row);
		    }

		cur_row = cache[point].row;
	    }
	    else
		cache_hit++;

	    for (i = 0; i < nfiles; i++) {
		if (in_window)
		    cache[point].value[i] = cell[i][cache[point].col];
		else
		    Rast_set_c_null_value(&(cache[point].value[i]), 1);

		if (out_type[i] != CELL_TYPE) {
		    if (in_window)
			cache[point].dvalue[i] = dcell[i][cache[point].col];
		    else
			Rast_set_d_null_value(&(cache[point].dvalue[i]), 1);
		}
		if (color_flag->answer) {
		    if (out_type[i] == CELL_TYPE)
			Rast_get_c_color(&cell[i][cache[point].col],
					     &red, &green, &blue, &ncolor[i]);
		    else
			Rast_get_d_color(&dcell[i][cache[point].col],
					     &red, &green, &blue, &ncolor[i]);

		    sprintf(cache[point].clr_buf[i], "%03d:%03d:%03d", red,
			    green, blue);
		}

	    }
	}			/* point loop */

	if (Cache_size > 1)
	    qsort(cache, point_cnt, sizeof(struct order), by_point);

	/* report data from re-ordered cache */

	for (point = 0; point < point_cnt; point++) {

	    G_debug(1, "%s|%s at col %d, row %d\n",
		    cache[point].east_buf, cache[point].north_buf,
		    cache[point].col, cache[point].row);


	    fprintf(stdout, "%s%c%s%c%s", cache[point].east_buf, fs,
		    cache[point].north_buf, fs, cache[point].lab_buf);

	    for (i = 0; i < nfiles; i++) {
		if (out_type[i] == CELL_TYPE) {
		    if (Rast_is_c_null_value(&cache[point].value[i])) {
			fprintf(stdout, "%c%s", fs, null_str);
			if (label_flag->answer)
			    fprintf(stdout, "%c", fs);
			if (color_flag->answer)
			    fprintf(stdout, "%c", fs);
			continue;
		    }
		    fprintf(stdout, "%c%ld", fs, (long)cache[point].value[i]);
		}
		else {		/* FCELL or DCELL */

		    if (Rast_is_d_null_value(&cache[point].dvalue[i])) {
			fprintf(stdout, "%c%s", fs, null_str);
			if (label_flag->answer)
			    fprintf(stdout, "%c", fs);
			if (color_flag->answer)
			    fprintf(stdout, "%c", fs);
			continue;
		    }
		    if (out_type[i] == FCELL_TYPE)
			sprintf(tmp_buf, "%.7g", cache[point].dvalue[i]);
		    else /* DCELL */
			sprintf(tmp_buf, "%.15g", cache[point].dvalue[i]);
		    G_trim_decimal(tmp_buf); /* not needed with %g? */
		    fprintf(stdout, "%c%s", fs, tmp_buf);
		}
		if (label_flag->answer)
		    fprintf(stdout, "%c%s", fs,
			    Rast_get_c_cat(&(cache[point].value[i]), &cats[i]));
		if (color_flag->answer)
		    fprintf(stdout, "%c%s", fs, cache[point].clr_buf[i]);
	    }
	    fprintf(stdout, "\n");
	}

	if (cache_report & !tty)
	    fprintf(stderr, "Cache  Hit: %6d  Miss: %6d\n",
		    cache_hit, cache_miss);

	cache_hit_tot += cache_hit;
	cache_miss_tot += cache_miss;
	cache_hit = cache_miss = 0;
    }

    if (!opt4->answers && tty)
	fprintf(stderr, "\n");
    if (cache_report & !tty)
	fprintf(stderr, "Total:    Cache  Hit: %6d  Miss: %6d\n",
		cache_hit_tot, cache_miss_tot);

    exit(EXIT_SUCCESS);
}
Exemplo n.º 8
0
int G__oldsite_get(FILE * ptr, Site * s, int fmt)

/*-
 * Reads ptr and returns 0 on success,
 *                      -1 on EOF,
 *                      -2 on other fatal error or insufficient data,
 *                       1 on format mismatch (extra data)
 */
{
    char sbuf[MAX_SITE_LEN], *buf, *last, *p1, *p2;
    char ebuf[128], nbuf[128];
    int n = 0, d = 0, c = 0, dim = 0, err = 0, tmp;

    buf = sbuf;

    if ((buf = fgets(sbuf, 1024, ptr)) == (char *)NULL)
	return EOF;

    while ((*buf == '#' || !isdigit(*buf)) && *buf != '-' && *buf != '+')
	if ((buf = fgets(sbuf, 1024, ptr)) == (char *)NULL)
	    return EOF;

    if (buf[strlen(buf) - 1] == '\n')
	buf[strlen(buf) - 1] = '\0';

    if (sscanf(buf, "%[^|]|%[^|]|%*[^\n]", ebuf, nbuf) < 2) {
	fprintf(stderr, "ERROR: ebuf %s nbuf %s\n", ebuf, nbuf);
	return -2;
    }

    if (!G_scan_northing(nbuf, &(s->north), fmt) ||
	!G_scan_easting(ebuf, &(s->east), fmt)) {
	fprintf(stderr, "ERROR: ebuf %s nbuf %s\n", ebuf, nbuf);
	return -2;
    }

    /* move pointer past easting and northing fields */
    if (NULL == (buf = G_index(buf, PIPE)))
	return -2;
    if (NULL == (buf = G_index(buf + 1, PIPE)))
	return -2;

    /* check for remaining dimensional fields */
    do {
	buf++;
	if (isnull(*buf))
	    return (FOUND_ALL(s, n, dim, c, d) ? 0 : -2);
	last = buf;
	if (dim < s->dim_alloc) {	/* should be more dims to read */
	    if (sscanf(buf, "%lf|", &(s->dim[dim++])) < 1)
		return -2;	/* no more dims, though expected */
	}
	else if (NULL != (p1 = G_index(buf, PIPE))) {
	    if (NULL == (p2 = G_index(buf, DQUOTE)))
		err = 1;	/* more dims, though none expected */
	    else if (strlen(p1) > strlen(p2))
		err = 1;	/* more dims, though none expected */
	}
    } while ((buf = G_index(buf, PIPE)) != NULL);
    buf = last;

    /* no more dimensions-now we parse attribute fields */
    while (!isnull(*buf)) {
	switch (*buf) {
	case '#':		/* category field */
	    if (n == 0) {
		switch (s->cattype) {
		case CELL_TYPE:
		    if (sscanf(buf, "#%d", &s->ccat) == 1)
			n++;
		    break;
		case FCELL_TYPE:
		    if (sscanf(buf, "#%f", &s->fcat) == 1)
			n++;
		    break;
		case DCELL_TYPE:
		    if (sscanf(buf, "#%lf", &s->dcat) == 1)
			n++;
		    break;
		default:
		    err = 1;	/* has cat, none expected */
		    break;
		}
	    }
	    else {
		err = 1;	/* extra cat */
	    }

	    /* move to beginning of next attribute */
	    if ((buf = next_att(buf)) == (char *)NULL)
		return (FOUND_ALL(s, n, dim, c, d) ? err : -2);
	    break;

	case '%':		/* decimal attribute */
	    if (d < s->dbl_alloc) {
		p1 = ++buf;
		errno = 0;
		s->dbl_att[d++] = strtod(buf, &p1);
		if (p1 == buf || errno == ERANGE) {
		    /* replace with:
		     * s->dbl_att[d - 1] = NAN
		     * when we add NULL attribute support
		     */
		    return -2;
		}
		/* err = 0; Make sure this is zeroed */
	    }
	    else {
		err = 1;	/* extra decimal */
	    }

	    if ((buf = next_att(buf)) == (char *)NULL) {
		return (FOUND_ALL(s, n, dim, c, d)) ? err : -2;
	    }
	    break;
	case '@':		/* string attribute */
	    if (isnull(*buf) || isnull(*(buf + 1)))
		return (FOUND_ALL(s, n, dim, c, d) ? err : -2);
	    else
		buf++;
	default:		/* defaults to string attribute */
	    /* allow both prefixed and unprefixed strings */
	    if (c < s->str_alloc) {
		if ((tmp = cleanse_string(buf)) > 0) {
		    G_strncpy(s->str_att[c++], buf, tmp);
		    buf += tmp;
		}
		else
		    return (FOUND_ALL(s, n, dim, c, d) ? err : -2);
	    }
	    if ((buf = next_att(buf)) == (char *)NULL) {
		return (FOUND_ALL(s, n, dim, c, d) ? err : -2);
	    }
	    break;
	}
    }

    return (FOUND_ALL(s, n, dim, c, d) ? err : -2);
}
Exemplo n.º 9
0
int E_edit_cellhd(struct Cell_head *cellhd, int type)
{
    char ll_north[20];
    char ll_south[20];
    char ll_east[20];
    char ll_west[20];
    char ll_nsres[20];
    char ll_ewres[20];
    char ll_def_north[20];
    char ll_def_south[20];
    char ll_def_east[20];
    char ll_def_west[20];
    char ll_def_ewres[20];
    char ll_def_nsres[20];
    char projection[80];
    char **screen;

    struct Cell_head def_wind;
    double north, south, east, west;
    double nsres, ewres;
    char buf[64], buf2[30], *p;
    short ok;
    int line;
    char *prj;
    char *err;

    if (type == AS_CELLHD && (cellhd->rows <= 0 || cellhd->cols <= 0)) {
	G_message("E_edit_cellhd() - programmer error");
	G_message("  ** rows and cols must be positive **");
	return -1;
    }
    if (type != AS_DEF_WINDOW) {
	if (G_get_default_window(&def_wind) != 1)
	    return -1;

	if (cellhd->proj < 0) {
	    cellhd->proj = def_wind.proj;
	    cellhd->zone = def_wind.zone;
	}
	else if (cellhd->zone < 0)
	    cellhd->zone = def_wind.zone;
    }

    prj = G__projection_name(cellhd->proj);
    if (!prj)
	prj = "** unknown **";
    sprintf(projection, "%d (%s)", cellhd->proj, prj);

    if (type != AS_DEF_WINDOW) {
	if (cellhd->west >= cellhd->east || cellhd->south >= cellhd->north) {
	    cellhd->north = def_wind.north;
	    cellhd->south = def_wind.south;
	    cellhd->west = def_wind.west;
	    cellhd->east = def_wind.east;

	    if (type != AS_CELLHD) {
		cellhd->ew_res = def_wind.ew_res;
		cellhd->ns_res = def_wind.ns_res;
		cellhd->rows = def_wind.rows;
		cellhd->cols = def_wind.cols;
	    }
	}

	if (cellhd->proj != def_wind.proj) {
	    if (type == AS_CELLHD)
		G_message
		    ("header projection %d differs from default projection %d",
		     cellhd->proj, def_wind.proj);
	    else
		G_message
		    ("region projection %d differs from default projection %d",
		     cellhd->proj, def_wind.proj);

	    if (!G_yes("do you want to make them match? ", 1))
		return -1;

	    cellhd->proj = def_wind.proj;
	    cellhd->zone = def_wind.zone;
	}

	if (cellhd->zone != def_wind.zone) {
	    if (type == AS_CELLHD)
		G_message("header zone %d differs from default zone %d",
			  cellhd->zone, def_wind.zone);
	    else
		G_message("region zone %d differs from default zone %d",
			  cellhd->zone, def_wind.zone);

	    if (!G_yes("do you want to make them match? ", 1))
		return -1;

	    cellhd->zone = def_wind.zone;
	}

	*ll_def_north = 0;
	*ll_def_south = 0;
	*ll_def_east = 0;
	*ll_def_west = 0;
	*ll_def_ewres = 0;
	*ll_def_nsres = 0;
	format_northing(def_wind.north, ll_def_north, def_wind.proj);
	format_northing(def_wind.south, ll_def_south, def_wind.proj);
	format_easting(def_wind.east, ll_def_east, def_wind.proj);
	format_easting(def_wind.west, ll_def_west, def_wind.proj);
	format_resolution(def_wind.ew_res, ll_def_ewres, def_wind.proj);
	format_resolution(def_wind.ns_res, ll_def_nsres, def_wind.proj);
    }

    *ll_north = 0;
    *ll_south = 0;
    *ll_east = 0;
    *ll_west = 0;
    *ll_ewres = 0;
    *ll_nsres = 0;
    format_northing(cellhd->north, ll_north, cellhd->proj);
    format_northing(cellhd->south, ll_south, cellhd->proj);
    format_easting(cellhd->east, ll_east, cellhd->proj);
    format_easting(cellhd->west, ll_west, cellhd->proj);
    format_resolution(cellhd->ew_res, ll_ewres, cellhd->proj);
    format_resolution(cellhd->ns_res, ll_nsres, cellhd->proj);

    while (1) {
	ok = 1;

	/* List window options on the screen for the user to answer */
	switch (type) {
	case AS_CELLHD:
	    screen = cellhd_screen;
	    break;
	case AS_DEF_WINDOW:
	    screen = def_window_screen;
	    break;
	default:
	    screen = window_screen;
	    break;
	}

	V_clear();
	line = 0;
	while (*screen)
	    V_line(line++, *screen++);

	/* V_ques ( variable, type, row, col, length) ; */
	V_ques(ll_north, 's', 6, 36, 10);
	V_ques(ll_south, 's', 10, 36, 10);
	V_ques(ll_west, 's', 9, 12, 10);
	V_ques(ll_east, 's', 9, 52, 10);

	if (type != AS_CELLHD) {
	    V_ques(ll_ewres, 's', 18, 48, 10);
	    V_ques(ll_nsres, 's', 19, 48, 10);
	}

	if (type != AS_DEF_WINDOW) {
	    V_const(ll_def_north, 's', 3, 36, 10);
	    V_const(ll_def_south, 's', 13, 36, 10);
	    V_const(ll_def_west, 's', 9, 1, 10);
	    V_const(ll_def_east, 's', 9, 65, 10);

	    if (type != AS_CELLHD) {
		V_const(ll_def_ewres, 's', 18, 21, 10);
		V_const(ll_def_nsres, 's', 19, 21, 10);
	    }
	}

	V_const(projection, 's', 15, 23, (int)strlen(projection));
	V_const(&cellhd->zone, 'i', 15, 60, 3);

	V_intrpt_ok();
	if (!V_call())
	    return -1;

	G_squeeze(ll_north);
	G_squeeze(ll_south);
	G_squeeze(ll_east);
	G_squeeze(ll_west);

	if (type != AS_CELLHD) {
	    G_squeeze(ll_ewres);
	    G_squeeze(ll_nsres);
	}

	if (!G_scan_northing(ll_north, &cellhd->north, cellhd->proj)) {
	    G_warning("Illegal value for north: %s", ll_north);
	    ok = 0;
	}

	if (!G_scan_northing(ll_south, &cellhd->south, cellhd->proj)) {
	    G_warning("Illegal value for south: %s", ll_south);
	    ok = 0;
	}

	if (!G_scan_easting(ll_east, &cellhd->east, cellhd->proj)) {
	    G_warning("Illegal value for east: %s", ll_east);
	    ok = 0;
	}

	if (!G_scan_easting(ll_west, &cellhd->west, cellhd->proj)) {
	    G_warning("Illegal value for west: %s", ll_west);
	    ok = 0;
	}

	if (type != AS_CELLHD) {
	    if (!G_scan_resolution(ll_ewres, &cellhd->ew_res, cellhd->proj)) {
		G_warning("Illegal east-west resolution: %s", ll_ewres);
		ok = 0;
	    }

	    if (!G_scan_resolution(ll_nsres, &cellhd->ns_res, cellhd->proj)) {
		G_warning("Illegal north-south resolution: %s", ll_nsres);
		ok = 0;
	    }
	}

	if (!ok) {
	    hitreturn();
	    continue;
	}

	/* Adjust and complete the cell header */
	north = cellhd->north;
	south = cellhd->south;
	east = cellhd->east;
	west = cellhd->west;
	nsres = cellhd->ns_res;
	ewres = cellhd->ew_res;

	if ((err =
	     G_adjust_Cell_head(cellhd, type == AS_CELLHD,
				type == AS_CELLHD))) {
	    G_message("%s", err);
	    hitreturn();
	    continue;
	}

	if (type == AS_CELLHD) {
	    nsres = cellhd->ns_res;
	    ewres = cellhd->ew_res;
	}

      SHOW:
	fprintf(stderr, "\n\n");
	G_message("  projection:   %s", projection);
	G_message("  zone:         %d", cellhd->zone);

	G_format_northing(cellhd->north, buf, cellhd->proj);
	G_format_northing(north, buf2, cellhd->proj);
	fprintf(stderr, "  north:       %s", buf);

	if (strcmp(buf, buf2) != 0) {
	    ok = 0;
	    fprintf(stderr, "  (Changed to match resolution)");
	}
	fprintf(stderr, "\n");

	G_format_northing(cellhd->south, buf, cellhd->proj);
	G_format_northing(south, buf2, cellhd->proj);
	fprintf(stderr, "  south:       %s", buf);
	if (strcmp(buf, buf2) != 0) {
	    ok = 0;
	    fprintf(stderr, "  (Changed to match resolution)");
	}
	fprintf(stderr, "\n");

	G_format_easting(cellhd->east, buf, cellhd->proj);
	G_format_easting(east, buf2, cellhd->proj);
	fprintf(stderr, "  east:        %s", buf);
	if (strcmp(buf, buf2) != 0) {
	    ok = 0;
	    fprintf(stderr, "  (Changed to match resolution)");
	}
	fprintf(stderr, "\n");

	G_format_easting(cellhd->west, buf, cellhd->proj);
	G_format_easting(west, buf2, cellhd->proj);
	fprintf(stderr, "  west:        %s", buf);
	if (strcmp(buf, buf2) != 0) {
	    ok = 0;
	    fprintf(stderr, "  (Changed to match resolution)");
	}
	fprintf(stderr, "\n\n");

	G_format_resolution(cellhd->ew_res, buf, cellhd->proj);
	G_format_resolution(ewres, buf2, cellhd->proj);
	fprintf(stderr, "  e-w res:     %s", buf);
	if (strcmp(buf, buf2) != 0) {
	    ok = 0;
	    fprintf(stderr, "  (Changed to conform to grid)");
	}
	fprintf(stderr, "\n");

	G_format_resolution(cellhd->ns_res, buf, cellhd->proj);
	G_format_resolution(nsres, buf2, cellhd->proj);
	fprintf(stderr, "  n-s res:     %s", buf);
	if (strcmp(buf, buf2) != 0) {
	    ok = 0;
	    fprintf(stderr, "  (Changed to conform to grid)");
	}
	fprintf(stderr, "\n\n");

	G_message("  total rows:  %15d", cellhd->rows);
	G_message("  total cols:  %15d", cellhd->cols);

	sprintf(buf, "%lf", (double)cellhd->rows * cellhd->cols);
	*(p = strchr(buf, '.')) = 0;
	G_insert_commas(buf);
	G_message("  total cells: %15s", buf);
	fprintf(stderr, "\n");

	if (type != AS_DEF_WINDOW) {
	    if (cellhd->north > def_wind.north) {
		G_warning("north falls outside the default region");
		ok = 0;
	    }

	    if (cellhd->south < def_wind.south) {
		G_warning("south falls outside the default region");
		ok = 0;
	    }

	    if (cellhd->proj != PROJECTION_LL) {
		if (cellhd->east > def_wind.east) {
		    G_warning("east falls outside the default region");
		    ok = 0;
		}

		if (cellhd->west < def_wind.west) {
		    G_warning("west falls outside the default region");
		    ok = 0;
		}
	    }
	}

      ASK:
	fflush(stdin);
	if (type == AS_CELLHD)
	    fprintf(stderr, "\nDo you accept this header? (y/n) [%s] > ",
		    ok ? "y" : "n");
	else
	    fprintf(stderr, "\nDo you accept this region? (y/n) [%s] > ",
		    ok ? "y" : "n");

	if (!G_gets(buf))
	    goto SHOW;

	G_strip(buf);
	switch (*buf) {
	case 0:
	    break;
	case 'y':
	case 'Y':
	    ok = 1;
	    break;
	case 'n':
	case 'N':
	    ok = 0;
	    break;
	default:
	    goto ASK;
	}

	if (ok)
	    return 0;
    }
}
Exemplo n.º 10
0
Arquivo: main.c Projeto: caomw/grass
int main(int argc, char *argv[])
{
    int i;
    double x;
    struct Cell_head cellhd, window;
    const char *value;
    const char *name;

    struct GModule *module;
    struct
    {
	struct Flag *dflt, *cur;
    } flag;
    struct
    {
	struct Option
	    *map,
	    *north, *south, *east, *west,
	    *raster, *vect, *region, *align;
    } parm;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("metadata"));
    module->description =
	_("Sets the boundary definitions for a raster map.");

    /* flags */

    flag.cur = G_define_flag();
    flag.cur->key = 'c';
    flag.cur->description = _("Set from current region");
    flag.cur->guisection = _("Existing");

    flag.dflt = G_define_flag();
    flag.dflt->key = 'd';
    flag.dflt->description = _("Set from default region");
    flag.dflt->guisection = _("Existing");

    /* parameters */

    parm.map = G_define_standard_option(G_OPT_R_MAP);
    parm.map->description = _("Name of raster map to change");

    parm.region = G_define_option();
    parm.region->key = "region";
    parm.region->key_desc = "name";
    parm.region->required = NO;
    parm.region->multiple = NO;
    parm.region->type = TYPE_STRING;
    parm.region->description = _("Set region from named region");
    parm.region->gisprompt = "old,windows,region";
    parm.region->guisection = _("Existing");
    
    parm.raster = G_define_standard_option(G_OPT_R_MAP);
    parm.raster->key = "raster";
    parm.raster->required = NO;
    parm.raster->multiple = NO;
    parm.raster->description = _("Set region to match this raster map");
    parm.raster->guisection = _("Existing");

    parm.vect = G_define_standard_option(G_OPT_V_MAP);
    parm.vect->key = "vector";
    parm.vect->required = NO;
    parm.vect->multiple = NO;
    parm.vect->description = _("Set region to match this vector map");
    parm.vect->guisection = _("Existing");

    parm.north = G_define_option();
    parm.north->key = "n";
    parm.north->key_desc = "value";
    parm.north->required = NO;
    parm.north->multiple = NO;
    parm.north->type = TYPE_STRING;
    parm.north->description = _("Value for the northern edge");
    parm.north->guisection = _("Bounds");

    parm.south = G_define_option();
    parm.south->key = "s";
    parm.south->key_desc = "value";
    parm.south->required = NO;
    parm.south->multiple = NO;
    parm.south->type = TYPE_STRING;
    parm.south->description = _("Value for the southern edge");
    parm.south->guisection = _("Bounds");

    parm.east = G_define_option();
    parm.east->key = "e";
    parm.east->key_desc = "value";
    parm.east->required = NO;
    parm.east->multiple = NO;
    parm.east->type = TYPE_STRING;
    parm.east->description = _("Value for the eastern edge");
    parm.east->guisection = _("Bounds");

    parm.west = G_define_option();
    parm.west->key = "w";
    parm.west->key_desc = "value";
    parm.west->required = NO;
    parm.west->multiple = NO;
    parm.west->type = TYPE_STRING;
    parm.west->description = _("Value for the western edge");
    parm.west->guisection = _("Bounds");
    
    parm.align = G_define_standard_option(G_OPT_R_MAP);
    parm.align->key = "align";
    parm.align->required = NO;
    parm.align->multiple = NO;
    parm.align->description = _("Raster map to align to");
    parm.align->guisection = _("Existing");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    G_get_window(&window);

    name = parm.map->answer;

    Rast_get_cellhd(name, G_mapset(), &cellhd);

    window = cellhd;

    if (flag.dflt->answer)
	G_get_default_window(&window);

    if (flag.cur->answer)
	G_get_window(&window);

    if ((name = parm.region->answer))	/* region= */
	G__get_window(&window, "windows", name, "");

    if ((name = parm.raster->answer)) {	/* raster= */
	Rast_get_cellhd(name, "", &window);
    }

    if ((name = parm.vect->answer)) {	/* vect= */
	struct Map_info Map;
	struct bound_box box;

	Vect_set_open_level(1);
	if (Vect_open_old(&Map, name, "") != 1)
	    G_fatal_error(_("Unable to open vector map <%s>"), name);

	Vect_get_map_box(&Map, &box);
	window.north = box.N;
	window.south = box.S;
	window.west = box.W;
	window.east = box.E;

	Rast_align_window(&window, &cellhd);

	Vect_close(&Map);
    }

    if ((value = parm.north->answer)) {	/* n= */
	if ((i = nsew(value, "n+", "n-", "s+"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.north);
	    switch (i) {
	    case 1:
		window.north += x;
		break;
	    case 2:
		window.north -= x;
		break;
	    case 3:
		window.north = window.south + x;
		break;
	    }
	}
	else if (G_scan_northing(value, &x, window.proj))
	    window.north = x;
	else
	    die(parm.north);
    }

    if ((value = parm.south->answer)) {	/* s= */
	if ((i = nsew(value, "s+", "s-", "n-"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.south);
	    switch (i) {
	    case 1:
		window.south += x;
		break;
	    case 2:
		window.south -= x;
		break;
	    case 3:
		window.south = window.north - x;
		break;
	    }
	}
	else if (G_scan_northing(value, &x, window.proj))
	    window.south = x;
	else
	    die(parm.south);
    }

    if ((value = parm.east->answer)) {	/* e= */
	if ((i = nsew(value, "e+", "e-", "w+"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.east);
	    switch (i) {
	    case 1:
		window.east += x;
		break;
	    case 2:
		window.east -= x;
		break;
	    case 3:
		window.east = window.west + x;
		break;
	    }
	}
	else if (G_scan_easting(value, &x, window.proj))
	    window.east = x;
	else
	    die(parm.east);
    }

    if ((value = parm.west->answer)) {	/* w= */
	if ((i = nsew(value, "w+", "w-", "e-"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.west);
	    switch (i) {
	    case 1:
		window.west += x;
		break;
	    case 2:
		window.west -= x;
		break;
	    case 3:
		window.west = window.east - x;
		break;
	    }
	}
	else if (G_scan_easting(value, &x, window.proj))
	    window.west = x;
	else
	    die(parm.west);
    }

    if ((name = parm.align->answer)) {	/* align= */
	struct Cell_head temp_window;

	Rast_get_cellhd(name, "", &temp_window);

	Rast_align_window(&window, &temp_window);
    }

    window.rows = cellhd.rows;
    window.cols = cellhd.cols;

    G_adjust_Cell_head(&window, 1, 1);

    cellhd.north = window.north;
    cellhd.south = window.south;
    cellhd.east = window.east;
    cellhd.west = window.west;

    Rast_put_cellhd(parm.map->answer, &cellhd);

    G_done_msg(" ");

    return 0;
}
Exemplo n.º 11
0
/*!
  \brief Read data in GRASS ASCII vector format

  \param ascii    pointer to the input ASCII file
  \param[out] Map pointer to the output Map_info structure

  \return number of read features
  \return -1 on error
*/
int Vect_read_ascii(FILE *ascii, struct Map_info *Map)
{
    char ctype;
    char buff[BUFFSIZE];
    char east_str[256], north_str[256];
    double *xarray;
    double *yarray;
    double *zarray;
    double *x, *y, *z;
    int i, n_points, n_coors, n_cats, n_lines;
    int type, with_z, skip_feat, nskipped_3d;
    int alloc_points;
    struct line_pnts *Points;
    struct line_cats *Cats;
    int catn, cat;

    /* Must always use this to create an initialized  line_pnts structure */
    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();

    /*alloc_points     = 1000 ; */
    alloc_points = 1;
    xarray = (double *)G_calloc(alloc_points, sizeof(double));
    yarray = (double *)G_calloc(alloc_points, sizeof(double));
    zarray = (double *)G_calloc(alloc_points, sizeof(double));

    n_lines = nskipped_3d = 0;

    with_z = Vect_is_3d(Map);

    while (G_getl2(buff, BUFFSIZE - 1, ascii) != 0) {
	n_cats = 0;
        skip_feat = FALSE;
	if (buff[0] == '\0') {
	    G_debug(3, "a2b: skipping blank line");
	    continue;
	}

	if (sscanf(buff, "%1c%d%d", &ctype, &n_coors, &n_cats) < 2 ||
	    n_coors < 0 || n_cats < 0) {
	    if (ctype == '#') {
		G_debug(2, "a2b: skipping commented line");
		continue;
	    }
	    G_warning(_("Error reading ASCII file: (bad type) [%s]"),
                      buff);
            return -1;
	}
	if (ctype == '#') {
	    G_debug(2, "a2b: Skipping commented line");
	    continue;
	}

	switch (ctype) {
	case 'A':
	    type = GV_BOUNDARY;
	    break;
	case 'B':
	    type = GV_BOUNDARY;
	    break;
	case 'C':
	    type = GV_CENTROID;
	    break;
	case 'L':
	    type = GV_LINE;
	    break;
	case 'P':
	    type = GV_POINT;
	    break;
	case 'F':
	    type = GV_FACE;
	    break;
	case 'K':
	    type = GV_KERNEL;
	    break;
	case 'a':
	case 'b':
	case 'c':
	case 'l':
	case 'p':
	    type = 0;		/* dead -> ignore */
	    break;
	default: {
	    G_warning(_("Error reading ASCII file: (unknown type) [%s]"),
                      buff);
            return -1;
        }
	}
	G_debug(5, "feature type = %d", type);
        
        if ((type & (GV_FACE | GV_KERNEL)) && !with_z) {
            skip_feat = TRUE;
            nskipped_3d++;
        }
        
	n_points = 0;
	x = xarray;
	y = yarray;
	z = zarray;

	/* Collect the points */
	for (i = 0; i < n_coors; i++) {
	    if (G_getl2(buff, BUFFSIZE - 1, ascii) == 0) {
		G_warning(_("End of ASCII file reached before end of coordinates"));
                return -1;
            }
	    if (buff[0] == '\0') {
		G_debug(3, "a2b: skipping blank line while reading vertices");
		i--;
		continue;
	    }

	    *z = 0;
	    if (sscanf(buff, "%lf%lf%lf", x, y, z) < 2) {
		if (sscanf(buff, " %s %s %lf", east_str, north_str, z) < 2) {
		    G_warning(_("Error reading ASCII file: (bad point) [%s]"),
                              buff);
                    return -1;
		} else {
		    if (!G_scan_easting(east_str, x, G_projection())) {
			G_warning(_("Unparsable longitude value: [%s]"),
                                  east_str);
                        return -1;
                    }
		    if (!G_scan_northing(north_str, y, G_projection())) {
			G_warning(_("Unparsable latitude value: [%s]"),
                                  north_str);
                        return -1;
                    }
		}
	    }

	    G_debug(5, "coor in: %s -> x = %f y = %f z = %f", G_chop(buff),
		    *x, *y, *z);

	    n_points++;
	    x++;
	    y++;
	    z++;

	    if (n_points >= alloc_points) {
		alloc_points = n_points + 1000;
		xarray =
		    (double *)G_realloc((void *)xarray,
					alloc_points * sizeof(double));
		yarray =
		    (double *)G_realloc((void *)yarray,
					alloc_points * sizeof(double));
		zarray =
		    (double *)G_realloc((void *)zarray,
					alloc_points * sizeof(double));
		x = xarray + n_points;
		y = yarray + n_points;
		z = zarray + n_points;
	    }
	}

	/* Collect the cats */
	Vect_reset_cats(Cats);
	for (i = 0; i < n_cats; i++) {
	    if (G_getl2(buff, BUFFSIZE - 1, ascii) == 0) {
		G_warning(_("End of ASCII file reached before end of categories"));
                return -1;
            }
	    if (buff[0] == '\0') {
		G_debug(3,
			"a2b: skipping blank line while reading category info");
		i--;
		continue;
	    }

	    if (sscanf(buff, "%u%u", &catn, &cat) != 2) {
		G_warning(_("Error reading categories: [%s]"), buff);
                return -1;
            }

	    Vect_cat_set(Cats, catn, cat);
	}

        if (skip_feat)
            continue;
        
	/* Allocation is handled for line_pnts */
	if (0 >
	    Vect_copy_xyz_to_pnts(Points, xarray, yarray, zarray, n_points)) {
	    G_warning(_("Unable to copy points"));
            return -1;
        }

	if (type > 0) {
	    if (-1 == Vect_write_line(Map, type, Points, Cats)) {
		return -1;
	    }
	    n_lines++;
	}
    }

    if (nskipped_3d > 0)
        G_warning(_("Vector map <%s> is 2D. %d 3D features (faces or kernels) skipped."),
                  Vect_get_name(Map), nskipped_3d);
    
    Vect_destroy_line_struct(Points);
    Vect_destroy_cats_struct(Cats);

    return n_lines;
}
Exemplo n.º 12
0
int main(int argc, char *argv[])
{
    char *name, *outfile;
    int fd, projection;
    FILE *fp;
    double res;
    char *null_string;
    char ebuf[256], nbuf[256], label[512], formatbuff[256];
    char b1[100], b2[100];
    int n;
    int havefirst = FALSE;
    int coords = 0, i, k = -1;
    double e1, e2, n1, n2;
    RASTER_MAP_TYPE data_type;
    struct Cell_head window;
    struct
    {
	struct Option *opt1, *profile, *res, *output, *null_str;
	struct Flag *g, *c;
    }
    parm;
    struct GModule *module;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("profile"));
    module->description =
	_("Outputs the raster map layer values lying on user-defined line(s).");

    parm.opt1 = G_define_standard_option(G_OPT_R_INPUT);

    parm.output = G_define_option();
    parm.output->key = "output";
    parm.output->type = TYPE_STRING;
    parm.output->required = NO;
    parm.output->answer = "-";
    parm.output->gisprompt = "new_file,file,output";
    parm.output->description =
	_("Name of file for output (use output=- for stdout)");

    parm.profile = G_define_option();
    parm.profile->key = "profile";
    parm.profile->type = TYPE_STRING;
    parm.profile->required = NO;
    parm.profile->multiple = YES;
    parm.profile->key_desc = "east,north";
    parm.profile->description = _("Profile coordinate pairs");

    parm.res = G_define_option();
    parm.res->key = "res";
    parm.res->type = TYPE_DOUBLE;
    parm.res->required = NO;
    parm.res->description =
	_("Resolution along profile (default = current region resolution)");

    parm.null_str = G_define_option();
    parm.null_str->key = "null";
    parm.null_str->type = TYPE_STRING;
    parm.null_str->required = NO;
    parm.null_str->answer = "*";
    parm.null_str->description = _("Character to represent no data cell");

    parm.g = G_define_flag();
    parm.g->key = 'g';
    parm.g->description =
	_("Output easting and northing in first two columns of four column output");

    parm.c = G_define_flag();
    parm.c->key = 'c';
    parm.c->description =
	_("Output RRR:GGG:BBB color values for each profile point");


    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    clr = 0;
    if (parm.c->answer)
	clr = 1;		/* color output */

    null_string = parm.null_str->answer;

    G_get_window(&window);
    projection = G_projection();
    if (parm.res->answer) {
	res = atof(parm.res->answer);
	/* Catch bad resolution ? */
	if (res <= 0)
	    G_fatal_error(_("Illegal resolution! [%g]"), res);
    }
    else {
	/* Do average of EW and NS res */
	res = (window.ew_res + window.ns_res) / 2;
    }

    G_message(_("Using resolution [%g]"), res);

    G_begin_distance_calculations();

    /* Open Input File for reading */
    /* Get Input Name */
    name = parm.opt1->answer;
    if (parm.g->answer)
	coords = 1;

    /* Open Raster File */
    fd = Rast_open_old(name, "");

    /* initialize color structure */
    if (clr)
	Rast_read_colors(name, "", &colors);

    /* Open ASCII file for output or stdout */
    outfile = parm.output->answer;

    if ((strcmp("-", outfile)) == 0) {
	fp = stdout;
    }
    else if (NULL == (fp = fopen(outfile, "w")))
	G_fatal_error(_("Unable to open file <%s>"), outfile);

    /* Get Raster Type */
    data_type = Rast_get_map_type(fd);
    /* Done with file */

    /* Show message giving output format */
    G_message(_("Output Format:"));
    if (coords == 1)
	sprintf(formatbuff,
		_("[Easting] [Northing] [Along Track Dist.(m)] [Elevation]"));
    else
	sprintf(formatbuff, _("[Along Track Dist.(m)] [Elevation]"));
    if (clr)
	strcat(formatbuff, _(" [RGB Color]"));
    G_message(formatbuff);

    /* Get Profile Start Coords */
    if (!parm.profile->answer) {
	/* Assume input from stdin */
	for (n = 1; input(b1, ebuf, b2, nbuf, label); n++) {
	    G_debug(4, "stdin line %d: ebuf=[%s]  nbuf=[%s]", n, ebuf, nbuf);
	    if (!G_scan_easting(ebuf, &e2, G_projection()) ||
		!G_scan_northing(nbuf, &n2, G_projection()))
		G_fatal_error(_("Invalid coordinates %s %s"), ebuf, nbuf);

	    if (havefirst)
		do_profile(e1, e2, n1, n2, name, coords, res, fd, data_type,
			   fp, null_string);
	    e1 = e2;
	    n1 = n2;
	    havefirst = TRUE;
	}
    }
    else {
	/* Coords from Command Line */
	for (i = 0; parm.profile->answers[i]; i += 2) {
	    /* Test for number coordinate pairs */
	    k = i;
	}

	if (k == 0) {
	    /* Only one coordinate pair supplied */
	    G_scan_easting(parm.profile->answers[0], &e1, G_projection());
	    G_scan_northing(parm.profile->answers[1], &n1, G_projection());
	    e2 = e1;
	    n2 = n1;

	    /* Get profile info */
	    do_profile(e1, e2, n1, n2, name, coords, res, fd, data_type, fp,
		       null_string);
	}
	else {
	    for (i = 0; i <= k - 2; i += 2) {
		G_scan_easting(parm.profile->answers[i], &e1, G_projection());
		G_scan_northing(parm.profile->answers[i + 1], &n1,
				G_projection());
		G_scan_easting(parm.profile->answers[i + 2], &e2,
			       G_projection());
		G_scan_northing(parm.profile->answers[i + 3], &n2,
				G_projection());

		/* Get profile info */
		do_profile(e1, e2, n1, n2, name, coords, res, fd, data_type,
			   fp, null_string);

	    }
	}
    }

    Rast_close(fd);
    fclose(fp);

    if (clr)
	Rast_free_colors(&colors);

    exit(EXIT_SUCCESS);
}				/* Done with main */
Exemplo n.º 13
0
Arquivo: main.c Projeto: caomw/grass
int main(int argc, char **argv)
{
    struct GModule *module;
    struct Option *map, *profile;
    struct Flag *stored;
    struct Cell_head window;
    struct point *points = NULL;
    int num_points, max_points = 0;
    double length;
    double t, b, l, r;
    int fd;
    int i;
    double sx;
    int last;

    /* Initialize the GIS calls */
    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("profile"));
    G_add_keyword(_("raster"));
    module->description = _("Plots profile of a transect.");

    /* set up command line */
    map = G_define_standard_option(G_OPT_R_INPUT);
    map->description = _("Raster map to be profiled");

    profile = G_define_option();
    profile->key = "profile";
    profile->type = TYPE_DOUBLE;
    profile->required = YES;
    profile->multiple = YES;
    profile->key_desc = "east,north";
    profile->description = _("Profile coordinate pairs");

    stored = G_define_flag();
    stored->key = 'r';
    stored->description = _("Use map's range recorded range");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    mapname = map->answer;

    fd = Rast_open_old(mapname, "");

    if (stored->answer)
	get_map_range();
    else
	get_region_range(fd);

    G_get_window(&window);

    num_points = 0;
    length = 0;
    for (i = 0; profile->answers[i]; i += 2) {
	struct point *p;
	double x, y;

	if (num_points >= max_points) {
	    max_points = num_points + 100;
	    points = G_realloc(points, max_points * sizeof(struct point));
	}

	p = &points[num_points];

	G_scan_easting( profile->answers[i+0], &x, G_projection());
	G_scan_northing(profile->answers[i+1], &y, G_projection());

	p->x = Rast_easting_to_col (x, &window);
	p->y = Rast_northing_to_row(y, &window);

	if (num_points > 0) {
	    const struct point *prev = &points[num_points-1];
	    double dx = fabs(p->x - prev->x);
	    double dy = fabs(p->y - prev->y);
	    double d = sqrt(dx * dx + dy * dy);
	    length += d;
	    p->d = length;
	}

	num_points++;
    }
    points[0].d = 0;

    if (num_points < 2)
	G_fatal_error(_("At least two points are required"));

    /* establish connection with graphics driver */
    if (D_open_driver() != 0)
	G_fatal_error(_("No graphics device selected. "
			"Use d.mon to select graphics device."));
    
    D_setup2(1, 0, 1.05, -0.05, -0.15, 1.05);

    plot_axes();

    D_use_color(D_translate_color(DEFAULT_FG_COLOR));

    D_get_src(&t, &b, &l, &r);
    t -= 0.1 * (t - b);
    b += 0.1 * (t - b);
    l += 0.1 * (r - l);
    r -= 0.1 * (r - l);

    D_begin();

    i = 0;
    last = 0;
    for (sx = 0; sx < 1; sx += D_get_d_to_u_xconv()) {
	double d = length * (sx - l);
	const struct point *p, *next;
	double k, sy, x, y;
	DCELL v;

	for (;;) {
	    p = &points[i];
	    next = &points[i + 1];
	    k = (d - p->d) / (next->d - p->d);
	    if (k < 1)
		break;
	    i++;
	}

	x = p->x * (1 - k) + next->x * k;
	y = p->y * (1 - k) + next->y * k;

	if (!get_cell(&v, fd, x, y)) {
	    last = 0;
	    continue;
	}

	sy = (v - min) / (max - min);

	if (last)
	    D_cont_abs(sx, sy);
	else
	    D_move_abs(sx, sy);

	last = 1;
    }

    D_end();
    D_stroke();
    
    D_close_driver();

    exit(EXIT_SUCCESS);
}
Exemplo n.º 14
0
int main(int argc, char **argv)
{
    int colorg = 0;
    int colorb = 0;
    int colort = 0;
    double size = 0., gsize = 0.;	/* initialize to zero */
    double east, north;
    int do_text, fontsize, mark_type, line_width;
    struct GModule *module;
    struct Option *opt1, *opt2, *opt3, *opt4, *fsize, *tcolor, *lwidth;
    struct Flag *noborder, *notext, *geogrid, *nogrid, *wgs84, *cross,
	*fiducial, *dot;
    struct pj_info info_in;	/* Proj structures */
    struct pj_info info_out;	/* Proj structures */

    /* Initialize the GIS calls */
    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("display, cartography");
    module->description =
	_("Overlays a user-specified grid "
	  "in the active display frame on the graphics monitor.");

    opt2 = G_define_option();
    opt2->key = "size";
    opt2->key_desc = "value";
    opt2->type = TYPE_STRING;
    opt2->required = YES;
    opt2->label = _("Size of grid to be drawn");
    opt2->description = _("In map units or DDD:MM:SS format. "
			  "Example: \"1000\" or \"0:10\"");

    opt3 = G_define_option();
    opt3->key = "origin";
    opt3->type = TYPE_STRING;
    opt3->key_desc = "easting,northing";
    opt3->answer = "0,0";
    opt3->multiple = NO;
    opt3->description = _("Lines of the grid pass through this coordinate");

    lwidth = G_define_option();
    lwidth->key = "width";
    lwidth->type = TYPE_DOUBLE;
    lwidth->required = NO;
    lwidth->description = _("Grid line width");

    opt1 = G_define_standard_option(G_OPT_C_FG);
    opt1->answer = "gray";
    opt1->label = _("Grid color");
    opt1->guisection = _("Color");

    opt4 = G_define_standard_option(G_OPT_C_FG);
    opt4->key = "bordercolor";
    opt4->label = _("Border color");
    opt4->guisection = _("Color");

    tcolor = G_define_standard_option(G_OPT_C_FG);
    tcolor->key = "textcolor";
    tcolor->answer = "gray";
    tcolor->label = _("Text color");
    tcolor->guisection = _("Color");

    fsize = G_define_option();
    fsize->key = "fontsize";
    fsize->type = TYPE_INTEGER;
    fsize->required = NO;
    fsize->answer = "9";
    fsize->options = "1-72";
    fsize->description = _("Font size for gridline coordinate labels");

    geogrid = G_define_flag();
    geogrid->key = 'g';
    geogrid->description =
	_("Draw geographic grid (referenced to current ellipsoid)");

    wgs84 = G_define_flag();
    wgs84->key = 'w';
    wgs84->description =
	_("Draw geographic grid (referenced to WGS84 ellipsoid)");

    cross = G_define_flag();
    cross->key = 'c';
    cross->description = _("Draw '+' marks instead of grid lines");

    dot = G_define_flag();
    dot->key = 'd';
    dot->description = _("Draw '.' marks instead of grid lines");

    fiducial = G_define_flag();
    fiducial->key = 'f';
    fiducial->description = _("Draw fiducial marks instead of grid lines");

    nogrid = G_define_flag();
    nogrid->key = 'n';
    nogrid->description = _("Disable grid drawing");
    nogrid->guisection = _("Disable");

    noborder = G_define_flag();
    noborder->key = 'b';
    noborder->description = _("Disable border drawing");
    noborder->guisection = _("Disable");

    notext = G_define_flag();
    notext->key = 't';
    notext->description = _("Disable text drawing");
    notext->guisection = _("Disable");

    /* Check command line */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    /* do some checking */
    if (nogrid->answer && noborder->answer)
	G_fatal_error(_("Both grid and border drawing are disabled"));
    if (wgs84->answer)
	geogrid->answer = 1;	/* -w implies -g */
    if (geogrid->answer && G_projection() == PROJECTION_LL)
	G_fatal_error(_("Geo-Grid option is not available for LL projection"));
    if (geogrid->answer && G_projection() == PROJECTION_XY)
	G_fatal_error(_("Geo-Grid option is not available for XY projection"));

    if (notext->answer)
	do_text = FALSE;
    else
	do_text = TRUE;

    if (lwidth->answer) {
	line_width = atoi(lwidth->answer);
	if(line_width < 0 || line_width > 1e3)
	    G_fatal_error("Invalid line width.");
    }
    else
	line_width = 0;

    fontsize = atoi(fsize->answer);

    mark_type = MARK_GRID;
    if (cross->answer + fiducial->answer + dot->answer > 1)
	G_fatal_error(_("Choose a single mark style"));
    if (cross->answer)
	mark_type = MARK_CROSS;
    if (fiducial->answer)
	mark_type = MARK_FIDUCIAL;
    if (dot->answer)
	mark_type = MARK_DOT;

    /* get grid size */
    if (geogrid->answer) {
	if (!G_scan_resolution(opt2->answer, &gsize, PROJECTION_LL) ||
	    gsize <= 0.0)
	    G_fatal_error(_("Invalid geo-grid size <%s>"), opt2->answer);
    }
    else {
	if (!G_scan_resolution(opt2->answer, &size, G_projection()) ||
	    size <= 0.0)
	    G_fatal_error(_("Invalid grid size <%s>"), opt2->answer);
    }

    /* get grid easting start */
    if (!G_scan_easting(opt3->answers[0], &east, G_projection())) {
	G_usage();
	G_fatal_error(_("Illegal east coordinate <%s>"), opt3->answers[0]);
    }

    /* get grid northing start */
    if (!G_scan_northing(opt3->answers[1], &north, G_projection())) {
	G_usage();
	G_fatal_error(_("Illegal north coordinate <%s>"), opt3->answers[1]);
    }

    /* Setup driver and check important information */
    if (R_open_driver() != 0)
	G_fatal_error(_("No graphics device selected"));


    /* Parse and select grid color */
    colorg = D_parse_color(opt1->answer, FALSE);
    /* Parse and select border color */
    colorb = D_parse_color(opt4->answer, FALSE);
    /* Parse and select text color */
    colort = D_parse_color(tcolor->answer, FALSE);


    D_setup(0);

    /* draw grid */
    if (!nogrid->answer) {
	if (geogrid->answer) {
	    /* initialzie proj stuff */
	    init_proj(&info_in, &info_out, wgs84->answer);
	    plot_geogrid(gsize, info_in, info_out, do_text, colorg, colort,
			 fontsize, mark_type, line_width);
	}
	else {
	    /* Do the grid plotting */
	    plot_grid(size, east, north, do_text, colorg, colort, fontsize,
		      mark_type, line_width);
	}
    }

    /* Draw border */
    if (!noborder->answer) {
	/* Set border color */
	D_raster_use_color(colorb);

	/* Do the border plotting */
	plot_border(size, east, north);
    }

    D_add_to_list(G_recreate_command());

    R_close_driver();

    exit(EXIT_SUCCESS);
}
Exemplo n.º 15
0
int main(int argc, char *argv[])
{

    struct GModule *module;
    struct Option *coord, *out_file, *min, *max, *mult;
    struct Flag *flag;
    int *int_buf;
    struct Cell_head w;
    struct History history;
    int cellfile;
    double east, north, pt[2], cur[2], row, col, fmult;
    double fmin, fmax;
    int binary;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("buffer"));
    G_add_keyword(_("geometry"));
    G_add_keyword(_("circle"));
    module->description =
	_("Creates a raster map containing concentric "
	  "rings around a given point.");

    out_file = G_define_standard_option(G_OPT_R_OUTPUT);

    coord = G_define_standard_option(G_OPT_M_COORDS);
    coord->required = YES;
    coord->description = _("The coordinate of the center (east,north)");

    min = G_define_option();
    min->key = "min";
    min->type = TYPE_DOUBLE;
    min->required = NO;
    min->description = _("Minimum radius for ring/circle map (in meters)");

    max = G_define_option();
    max->key = "max";
    max->type = TYPE_DOUBLE;
    max->required = NO;
    max->description = _("Maximum radius for ring/circle map (in meters)");

    mult = G_define_option();
    mult->key = "multiplier";
    mult->type = TYPE_DOUBLE;
    mult->required = NO;
    mult->description = _("Data value multiplier");

    flag = G_define_flag();
    flag->key = 'b';
    flag->description = _("Generate binary raster map");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    G_scan_easting(coord->answers[0], &east, G_projection());
    G_scan_northing(coord->answers[1], &north, G_projection());
    pt[0] = east;
    pt[1] = north;

    fmult = 1.0;

    if (min->answer)
	sscanf(min->answer, "%lf", &fmin);
    else
	fmin = 0;

    if (max->answer)
	sscanf(max->answer, "%lf", &fmax);
    else
	fmax = HUGE_VAL;

    if (fmin > fmax)
	G_fatal_error(_("Please specify a radius in which min < max"));

    if (mult->answer)
	if (1 != sscanf(mult->answer, "%lf", &fmult))
	    fmult = 1.0;

    /* nonsense test */
    if (flag->answer && (!min->answer && !max->answer))
	G_fatal_error(_("Please specify min and/or max radius when "
			"using the binary flag"));

    if (flag->answer)
	binary = 1;		/* generate binary pattern only, useful for MASK */
    else
	binary = 0;

    G_get_set_window(&w);

    cellfile = Rast_open_c_new(out_file->answer);

    int_buf = (int *)G_malloc(w.cols * sizeof(int));
    {
	int c;

	for (row = 0; row < w.rows; row++) {
	    G_percent(row, w.rows, 2);
	    cur[1] = Rast_row_to_northing(row + 0.5, &w);
	    for (col = 0; col < w.cols; col++) {
		c = col;
		cur[0] = Rast_col_to_easting(col + 0.5, &w);
		int_buf[c] =
		    (int)(distance(pt, cur, fmin, fmax, binary) * fmult);
		if (int_buf[c] == 0)
		    Rast_set_null_value(&int_buf[c], 1, CELL_TYPE);
	    }
	    Rast_put_row(cellfile, int_buf, CELL_TYPE);

	}
    }
    G_free(int_buf);
    Rast_close(cellfile);
    Rast_short_history(out_file->answer, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(out_file->answer, &history);

    G_done_msg(_("Raster map <%s> created."),
	       out_file->answer);
    
    return (EXIT_SUCCESS);
}
Exemplo n.º 16
0
Arquivo: main.c Projeto: caomw/grass
int main(int argc, char *argv[])
{

    /* loop */
    int i, j;

    /* store filename and path  */
    char *dig_file;
    
    char buf[2000];

    /* Other local variables */
    int attCount, nbreaks;

    struct grid_description grid_info;
    struct Cell_head window;
    struct Map_info Map;
    struct Option *vectname, *grid, *coord, *box, *angle, *position_opt, *breaks;
    struct GModule *module;
    struct Flag *points_fl, *line_fl;
    int points_p, line_p, output_type;
    char *desc;

    struct line_pnts *Points;
    struct line_cats *Cats;

    /* Attributes */
    struct field_info *Fi;
    dbDriver *Driver;
    dbString sql;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("geometry"));
    module->description = _("Creates a vector map of a user-defined grid.");

    vectname = G_define_standard_option(G_OPT_V_OUTPUT);
    vectname->key = "map";

    grid = G_define_option();
    grid->key = "grid";
    grid->key_desc = _("rows,columns");
    grid->type = TYPE_INTEGER;
    grid->required = YES;
    grid->multiple = NO;
    grid->description = _("Number of rows and columns in grid");

    position_opt = G_define_option();
    position_opt->key = "position";
    position_opt->type = TYPE_STRING;
    position_opt->required = NO;
    position_opt->multiple = NO;
    position_opt->options = "region,coor";
    position_opt->answer = "region";
    position_opt->description = _("Where to place the grid");
    desc = NULL;
    G_asprintf(&desc,
            "region;%s;coor;%s",
            _("current region"),
            _("use 'coor' and 'box' options"));
    position_opt->descriptions = desc;

    coord = G_define_option();
    coord->key = "coor";
    coord->key_desc = "x,y";
    coord->type = TYPE_DOUBLE;
    coord->required = NO;
    coord->multiple = NO;
    coord->description =
	_("Lower left easting and northing coordinates of map");

    box = G_define_option();
    box->key = "box";
    box->key_desc = _("width,height");
    box->type = TYPE_DOUBLE;
    box->required = NO;
    box->multiple = NO;
    box->description = _("Width and height of boxes in grid");

    angle = G_define_option();
    angle->key = "angle";
    angle->type = TYPE_DOUBLE;
    angle->required = NO;
    angle->description =
	_("Angle of rotation (in degrees counter-clockwise)");
    angle->answer = "0";

    breaks = G_define_option();
    breaks->key = "breaks";
    breaks->type = TYPE_INTEGER;
    breaks->required = NO;
    breaks->description =
	_("Number of vertex points per grid cell");
    breaks->options = "0-60";
    breaks->answer = "3";

    points_fl = G_define_flag();
    points_fl->key = 'p';
    points_fl->description =
	_("Create grid of points instead of areas and centroids");

    line_fl = G_define_flag();
    line_fl->key = 'l';
    line_fl->description =
	_("Create grid as lines, instead of areas");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    line_p = line_fl->answer;
    if (line_p) {
	output_type = GV_LINE;
    } else {
	output_type = GV_BOUNDARY;
    }

    points_p = points_fl->answer;

    /* get the current window  */
    G_get_window(&window);

    /*
     * information we need to collect from user: origin point x and y (lower
     * left), shift in x, shift in y,  number of rows, number of cols
     */
    dig_file = G_store(vectname->answer);

    /* Number of row and cols */
    grid_info.num_rows = atoi(grid->answers[0]);
    grid_info.num_cols = atoi(grid->answers[1]);

    grid_info.angle = M_PI / 180 * atof(angle->answer);

    nbreaks = atoi(breaks->answer);

    /* Position */
    if (position_opt->answer[0] == 'r') {	/* region */
	if (coord->answer)
	    G_fatal_error(_("'coor' and 'position=region' are exclusive options"));

	if (box->answer)
	    G_fatal_error(_("'box' and 'position=region' are exclusive options"));

	if (grid_info.angle != 0.0)
	    G_fatal_error(_("'angle' and 'position=region' are exclusive options"));

	grid_info.origin_x = window.west;
	grid_info.origin_y = window.south;

	grid_info.length = (window.east - window.west) / grid_info.num_cols;
	grid_info.width = (window.north - window.south) / grid_info.num_rows;

	G_debug(2, "x = %e y = %e l = %e w = %e", grid_info.origin_x,
		grid_info.origin_y, grid_info.length, grid_info.width);
    }
    else {
	if (!coord->answer)
	    G_fatal_error(_("'coor' option missing"));

	if (!box->answer)
	    G_fatal_error(_("'box' option missing"));

	if (!G_scan_easting
	    (coord->answers[0], &(grid_info.origin_x), window.proj))
	    G_fatal_error(_("Invalid easting"));;
	if (!G_scan_northing
	    (coord->answers[1], &(grid_info.origin_y), window.proj))
	    G_fatal_error(_("Invalid northing"));;

	if (!G_scan_resolution
	    (box->answers[0], &(grid_info.length), window.proj))
	    G_fatal_error(_("Invalid distance"));;
	if (!G_scan_resolution
	    (box->answers[1], &(grid_info.width), window.proj))
	    G_fatal_error(_("Invalid distance"));;

    }

    /*
     * vector rows are the actual number of rows of vectors to make up the
     * entire grid.   ditto for cols.
     */
    grid_info.num_vect_rows = grid_info.num_rows + 1;
    grid_info.num_vect_cols = grid_info.num_cols + 1;

    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();
    db_init_string(&sql);

    /* Open output map */
    if (0 > Vect_open_new(&Map, dig_file, 0)) {
	G_fatal_error(_("Unable to create vector map <%s>"), dig_file);
    }

    Vect_hist_command(&Map);

    /* Open database, create table */
    Fi = Vect_default_field_info(&Map, 1, NULL, GV_1TABLE);
    Vect_map_add_dblink(&Map, Fi->number, Fi->name, Fi->table, Fi->key,
			Fi->database, Fi->driver);

    Driver =
	db_start_driver_open_database(Fi->driver,
				      Vect_subst_var(Fi->database, &Map));
    if (Driver == NULL)
	G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
		      Fi->database, Fi->driver);
    db_set_error_handler_driver(Driver);

    if (grid_info.num_rows < 27 && grid_info.num_cols < 27) {
	sprintf(buf,
		"create table %s ( cat integer, row integer, col integer, "
		"rown varchar(1), coln varchar(1))", Fi->table);
    }
    else {
	sprintf(buf,
		"create table %s ( cat integer, row integer, col integer)",
		Fi->table);
    }
    db_set_string(&sql, buf);

    G_debug(1, "SQL: %s", db_get_string(&sql));

    if (db_execute_immediate(Driver, &sql) != DB_OK) {
	G_fatal_error(_("Unable to create table: %s"), db_get_string(&sql));
    }

    if (db_create_index2(Driver, Fi->table, Fi->key) != DB_OK)
	G_warning(_("Unable to create index"));

    if (db_grant_on_table
	(Driver, Fi->table, DB_PRIV_SELECT, DB_GROUP | DB_PUBLIC) != DB_OK)
	G_fatal_error(_("Unable to grant privileges on table <%s>"),
		      Fi->table);

    if (!points_p) {
	/* create areas */
	write_grid(&grid_info, &Map, nbreaks, output_type);
    }

    /* Create a grid of label points at the centres of the grid cells */
    G_verbose_message(_("Creating centroids..."));

    /* Write out centroids and attributes */
    /* If the output id is lines it skips to add centroids and attributes
       TODO decide what to write in the attribute table
     */
    if (!line_p) {
      db_begin_transaction(Driver);
      attCount = 0;
      for (i = 0; i < grid_info.num_rows; ++i) {
	  for (j = 0; j < grid_info.num_cols; ++j) {
	      double x, y;
	      const int point_type = points_p ? GV_POINT : GV_CENTROID;

	      x = grid_info.origin_x + (0.5 + j) * grid_info.length;
	      y = grid_info.origin_y + (0.5 + i) * grid_info.width;

	      rotate(&x, &y, grid_info.origin_x, grid_info.origin_y,
		    grid_info.angle);

	      Vect_reset_line(Points);
	      Vect_reset_cats(Cats);

	      Vect_append_point(Points, x, y, 0.0);
	      Vect_cat_set(Cats, 1, attCount + 1);
	      Vect_write_line(&Map, point_type, Points, Cats);

	      sprintf(buf, "insert into %s values ", Fi->table);
	      if (db_set_string(&sql, buf) != DB_OK)
		  G_fatal_error(_("Unable to fill attribute table"));

	      if (grid_info.num_rows < 27 && grid_info.num_cols < 27) {
		  sprintf(buf,
			  "( %d, %d, %d, '%c', '%c' )",
			  attCount + 1, grid_info.num_rows - i,
			  j + 1, 'A' + grid_info.num_rows - i - 1, 'A' + j);
	      }
	      else {
		  sprintf(buf, "( %d, %d, %d )",
			  attCount + 1, i + 1, j + 1);
	      }
	      if (db_append_string(&sql, buf) != DB_OK)
		      G_fatal_error(_("Unable to fill attribute table"));

	      G_debug(3, "SQL: %s", db_get_string(&sql));

	      if (db_execute_immediate(Driver, &sql) != DB_OK) {
		  G_fatal_error(_("Unable to insert new record: %s"),
			      db_get_string(&sql));
	      }
	      attCount++;
	  }
      }
    }
    db_commit_transaction(Driver);

    db_close_database_shutdown_driver(Driver);

    Vect_build(&Map);
    Vect_close(&Map);

    exit(EXIT_SUCCESS);
}
Exemplo n.º 17
0
int main(int argc, char *argv[])
{
    int line_color;
    int text_color;
    double lon1, lat1, lon2, lat2;
    char *deftcolor;
    struct GModule *module;
    struct
    {
	struct Option *lcolor, *tcolor, *coor;
    } parm;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("distance"));
    module->description =
	_("Displays a geodesic line, tracing the shortest distance "
	"between two geographic points along a great circle, in "
	"a longitude/latitude data set.");

    parm.coor = G_define_option();
    parm.coor->key = "coor";
    parm.coor->key_desc = "lon1,lat1,lon2,lat2";
    parm.coor->type = TYPE_STRING;
    parm.coor->required = YES;
    parm.coor->description = _("Starting and ending coordinates");

    parm.lcolor = G_define_option();
    parm.lcolor->key = "lcolor";
    parm.lcolor->type = TYPE_STRING;
    parm.lcolor->required = NO;
    parm.lcolor->description = _("Line color");
    parm.lcolor->gisprompt = "old_color,color,color";
    parm.lcolor->answer = DEFAULT_FG_COLOR;

    parm.tcolor = G_define_option();
    parm.tcolor->key = "tcolor";
    parm.tcolor->type = TYPE_STRING;
    parm.tcolor->required = NO;
    parm.tcolor->description = _("Text color or \"none\"");
    parm.tcolor->gisprompt = "old_color,color,color";

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    if (G_projection() != PROJECTION_LL)
	G_fatal_error(_("Location is not %s"), G__projection_name(PROJECTION_LL));

    if (parm.coor->answers[0] == NULL)
	G_fatal_error(_("No coordinates given"));

    if (!G_scan_easting(parm.coor->answers[0], &lon1, G_projection()))
	G_fatal_error(_("%s - illegal longitude"), parm.coor->answers[0]);

    if (!G_scan_northing(parm.coor->answers[1], &lat1, G_projection()))
	G_fatal_error(_("%s - illegal longitude"), parm.coor->answers[1]);

    if (!G_scan_easting(parm.coor->answers[2], &lon2, G_projection()))
	G_fatal_error(_("%s - illegal longitude"), parm.coor->answers[2]);

    if (!G_scan_northing(parm.coor->answers[3], &lat2, G_projection()))
	G_fatal_error(_("%s - illegal longitude"), parm.coor->answers[3]);


    if (D_open_driver() != 0)
      	G_fatal_error(_("No graphics device selected. "
			"Use d.mon to select graphics device."));
    
    line_color = D_translate_color(parm.lcolor->answer);
    if (!line_color)
	line_color = D_translate_color(parm.lcolor->answer =
				       DEFAULT_FG_COLOR);

    if (strcmp(parm.lcolor->answer, DEFAULT_FG_COLOR) == 0)
	deftcolor = "red";
    else
	deftcolor = DEFAULT_FG_COLOR;

    if (parm.tcolor->answer == NULL)
	text_color = D_translate_color(deftcolor);
    else if (strcmp(parm.tcolor->answer, "none") == 0)
	text_color = -1;
    else
	text_color = D_translate_color(parm.tcolor->answer);

    plot(lon1, lat1, lon2, lat2, line_color, text_color);
    
    D_save_command(G_recreate_command());
    D_close_driver();

    exit(EXIT_SUCCESS);
}
Exemplo n.º 18
0
int main(int argc, char **argv)
{
    int colorg = 0;
    int colorb = 0;
    int colort = 0;
    int colorbg = 0;
    double size = 0., gsize = 0.;       /* initialize to zero */
    double east, north;
    int do_text, fontsize, mark_type, line_width, dirn;
    struct GModule *module;
    struct Option *opt1, *opt2, *opt3, *opt4, *fsize, *tcolor, *lwidth,
        *direction, *bgcolor;
    struct Flag *noborder, *notext, *geogrid, *nogrid, *wgs84, *cross,
        *fiducial, *dot, *align;
    struct pj_info info_in;     /* Proj structures */
    struct pj_info info_out;    /* Proj structures */
    struct Cell_head wind;

    /* Initialize the GIS calls */
    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("cartography"));
    G_add_keyword(_("graticule"));
    module->description =
        _("Overlays a user-specified grid "
          "in the active display frame on the graphics monitor.");

    opt2 = G_define_option();
    opt2->key = "size";
    opt2->key_desc = "value";
    opt2->type = TYPE_STRING;
    opt2->required = YES;
    opt2->label = _("Size of grid to be drawn (in map units)");
    opt2->description =
        _("0 for north-south resolution of the current region. "
          "In map units or DDD:MM:SS format. "
          "Example: \"1000\" or \"0:10\"");

    opt3 = G_define_standard_option(G_OPT_M_COORDS);
    opt3->key = "origin";
    opt3->answer = "0,0";
    opt3->multiple = NO;
    opt3->description = _("Lines of the grid pass through this coordinate");

    direction = G_define_option();
    direction->key = "direction";
    direction->type = TYPE_STRING;
    direction->required = NO;
    direction->answer = "both";
    direction->options = "both,east-west,north-south";
    direction->description =
        _("Draw only east-west lines, north-south lines, or both ");
    direction->guisection = _("Disable");

    lwidth = G_define_option();
    lwidth->key = "width";
    lwidth->type = TYPE_DOUBLE;
    lwidth->required = NO;
    lwidth->description = _("Grid line width");

    opt1 = G_define_standard_option(G_OPT_C);
    opt1->answer = "gray";
    opt1->label = _("Grid color");
    opt1->guisection = _("Color");

    opt4 = G_define_standard_option(G_OPT_C);
    opt4->key = "border_color";
    opt4->label = _("Border color");
    opt4->guisection = _("Color");

    tcolor = G_define_standard_option(G_OPT_C);
    tcolor->key = "text_color";
    tcolor->answer = "gray";
    tcolor->label = _("Text color");
    tcolor->guisection = _("Color");

    bgcolor = G_define_standard_option(G_OPT_CN);
    bgcolor->key = "bgcolor";
    bgcolor->answer = "none";
    bgcolor->label = _("Background color");
    bgcolor->guisection = _("Color");

    fsize = G_define_option();
    fsize->key = "fontsize";
    fsize->type = TYPE_INTEGER;
    fsize->required = NO;
    fsize->answer = "9";
    fsize->options = "1-72";
    fsize->description = _("Font size for gridline coordinate labels");

    align = G_define_flag();
    align->key = 'a';
    align->description =
        _("Align the origin to the east-north corner of the current region");

    geogrid = G_define_flag();
    geogrid->key = 'g';
    geogrid->description =
        _("Draw geographic grid (referenced to current ellipsoid)");
    geogrid->guisection = _("Draw");

    wgs84 = G_define_flag();
    wgs84->key = 'w';
    wgs84->description =
        _("Draw geographic grid (referenced to WGS84 ellipsoid)");
    wgs84->guisection = _("Draw");

    cross = G_define_flag();
    cross->key = 'c';
    cross->description = _("Draw '+' marks instead of grid lines");
    cross->guisection = _("Draw");

    dot = G_define_flag();
    dot->key = 'd';
    dot->description = _("Draw '.' marks instead of grid lines");
    dot->guisection = _("Draw");

    fiducial = G_define_flag();
    fiducial->key = 'f';
    fiducial->description = _("Draw fiducial marks instead of grid lines");
    fiducial->guisection = _("Draw");

    nogrid = G_define_flag();
    nogrid->key = 'n';
    nogrid->description = _("Disable grid drawing");
    nogrid->guisection = _("Disable");

    noborder = G_define_flag();
    noborder->key = 'b';
    noborder->description = _("Disable border drawing");
    noborder->guisection = _("Disable");

    notext = G_define_flag();
    notext->key = 't';
    notext->description = _("Disable text drawing");
    notext->guisection = _("Disable");

    /* Check command line */
    if (G_parser(argc, argv))
        exit(EXIT_FAILURE);


    /* do some checking */
    if (nogrid->answer && noborder->answer)
        G_fatal_error(_("Both grid and border drawing are disabled"));
    if (wgs84->answer)
        geogrid->answer = 1;    /* -w implies -g */
    if (geogrid->answer && G_projection() == PROJECTION_LL)
        G_fatal_error(_("Geo-grid option not available for LL projection, use without -g/-w"));
    if (geogrid->answer && G_projection() == PROJECTION_XY)
        G_fatal_error(_("Geo-grid option not available for XY projection, use without -g/-w"));

    if (notext->answer)
        do_text = FALSE;
    else
        do_text = TRUE;

    if (lwidth->answer) {
        line_width = atoi(lwidth->answer);
        if (line_width < 0 || line_width > 1e3)
            G_fatal_error("Invalid line width");
    }
    else
        line_width = 0;

    fontsize = atoi(fsize->answer);

    mark_type = MARK_GRID;
    if (cross->answer + fiducial->answer + dot->answer > 1)
        G_fatal_error(_("Choose a single mark style"));
    if (cross->answer)
        mark_type = MARK_CROSS;
    if (fiducial->answer)
        mark_type = MARK_FIDUCIAL;
    if (dot->answer)
        mark_type = MARK_DOT;

    if (G_strcasecmp(direction->answer, "both") == 0)
        dirn = DIRN_BOTH;
    else if (G_strcasecmp(direction->answer, "east-west") == 0)
        dirn = DIRN_LAT;
    else if (G_strcasecmp(direction->answer, "north-south") == 0)
        dirn = DIRN_LON;
    else
        G_fatal_error("Invalid direction: %s", direction->answer);

    if (align->answer || strcmp(opt2->answer, "0") == 0)
        G_get_element_window(&wind, "", "WIND", G_mapset());

    if (strcmp(opt2->answer, "0") == 0) {
        if (geogrid->answer)
            gsize = wind.ns_res;
        else
            size = wind.ns_res;
    }
    else {
        /* get grid size */
        if (geogrid->answer) {
            if (!G_scan_resolution(opt2->answer, &gsize, PROJECTION_LL) ||
                gsize <= 0.0)
                G_fatal_error(_("Invalid geo-grid size <%s>"), opt2->answer);
        }
        else {
            if (!G_scan_resolution(opt2->answer, &size, G_projection()) ||
                size <= 0.0)
                G_fatal_error(_("Invalid grid size <%s>"), opt2->answer);
        }
    }

    if (align->answer) {
        /* reduce accumulated errors when ew_res is not the same as ns_res. */
        struct Cell_head w;

        G_get_set_window(&w);
        east =
            wind.west +
            (int)((w.west - wind.west) / wind.ew_res) * wind.ew_res;
        north =
            wind.south +
            (int)((w.south - wind.south) / wind.ns_res) * wind.ns_res;
    }
    else {
        /* get grid easting start */
        if (!G_scan_easting(opt3->answers[0], &east, G_projection())) {
            G_usage();
            G_fatal_error(_("Illegal east coordinate <%s>"),
                          opt3->answers[0]);
        }

        /* get grid northing start */
        if (!G_scan_northing(opt3->answers[1], &north, G_projection())) {
            G_usage();
            G_fatal_error(_("Illegal north coordinate <%s>"),
                          opt3->answers[1]);
        }
    }

    /* Setup driver and check important information */
    D_open_driver();

    /* Parse and select grid color */
    colorg = D_parse_color(opt1->answer, FALSE);
    /* Parse and select border color */
    colorb = D_parse_color(opt4->answer, FALSE);
    /* Parse and select text color */
    colort = D_parse_color(tcolor->answer, FALSE);
    /* Parse and select background color */
    colorbg = D_parse_color(bgcolor->answer, TRUE);


    D_setup(0);

    /* draw grid */
    if (!nogrid->answer) {
        if (geogrid->answer) {
            /* initialzie proj stuff */
            init_proj(&info_in, &info_out, wgs84->answer);
            plot_geogrid(gsize, info_in, info_out, do_text, colorg, colort,
                         colorbg, fontsize, mark_type, line_width, dirn);
        }
        else {
            /* Do the grid plotting */
            plot_grid(size, east, north, do_text, colorg, colort, colorbg,
                      fontsize, mark_type, line_width, dirn);
        }
    }

    /* Draw border */
    if (!noborder->answer) {
        /* Set border color */
        D_use_color(colorb);

        /* Do the border plotting */
        plot_border(size, east, north, dirn);
    }

    D_save_command(G_recreate_command());
    D_close_driver();

    exit(EXIT_SUCCESS);
}
Exemplo n.º 19
0
Arquivo: main.c Projeto: caomw/grass
int main(int argc, char *argv[])
{
    char *name, *outfile;
    const char *unit;
    int unit_id;
    double factor;
    int fd, projection;
    FILE *fp, *coor_fp;
    double res;
    char *null_string;
    char ebuf[256], nbuf[256], label[512], formatbuff[256];
    char b1[100], b2[100];
    int n;
    int havefirst = FALSE;
    int coords = 0, i, k = -1;
    double e1, e2, n1, n2;
    RASTER_MAP_TYPE data_type;
    struct Cell_head window;
    struct
    {
	struct Option *opt1, *profile, *res, *output, *null_str, *coord_file, *units;
	struct Flag *g, *c, *m;
    }
    parm;
    struct GModule *module;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("profile"));
    module->description =
	_("Outputs the raster map layer values lying on user-defined line(s).");

    parm.opt1 = G_define_standard_option(G_OPT_R_INPUT);

    parm.output = G_define_standard_option(G_OPT_F_OUTPUT);
    parm.output->required = NO;
    parm.output->answer = "-";
    parm.output->description =
	_("Name of file for output (use output=- for stdout)");

    parm.profile = G_define_standard_option(G_OPT_M_COORDS);
    parm.profile->required = NO;
    parm.profile->multiple = YES;
    parm.profile->description = _("Profile coordinate pairs");

    parm.coord_file = G_define_standard_option(G_OPT_F_INPUT);
    parm.coord_file->key = "file";
    parm.coord_file->required = NO;
    parm.coord_file->label =
	_("Name of input file containing coordinate pairs");
    parm.coord_file->description =
	_("Use instead of the 'coordinates' option. "
	  "\"-\" reads from stdin.");

    parm.res = G_define_option();
    parm.res->key = "resolution";
    parm.res->type = TYPE_DOUBLE;
    parm.res->required = NO;
    parm.res->description =
	_("Resolution along profile (default = current region resolution)");

    parm.null_str = G_define_option();
    parm.null_str->key = "null";
    parm.null_str->type = TYPE_STRING;
    parm.null_str->required = NO;
    parm.null_str->answer = "*";
    parm.null_str->description = _("Character to represent no data cell");

    parm.g = G_define_flag();
    parm.g->key = 'g';
    parm.g->description =
	_("Output easting and northing in first two columns of four column output");

    parm.c = G_define_flag();
    parm.c->key = 'c';
    parm.c->description =
	_("Output RRR:GGG:BBB color values for each profile point");

    parm.units = G_define_standard_option(G_OPT_M_UNITS);
    parm.units->options = "meters,kilometers,feet,miles";
    parm.units->label = parm.units->description;
    parm.units->description = _("If units are not specified, current location units are used. "
                                "Meters are used by default in geographic (latlon) locations.");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    clr = 0;
    if (parm.c->answer)
	clr = 1;		/* color output */

    null_string = parm.null_str->answer;

    if ((parm.profile->answer && parm.coord_file->answer) ||
	(!parm.profile->answer && !parm.coord_file->answer))
	G_fatal_error(_("Either use profile option or coordinate_file "
			" option, but not both"));

    G_get_window(&window);
    projection = G_projection();

    /* get conversion factor and units name */
    if (parm.units->answer) {
        unit_id = G_units(parm.units->answer);
        factor = 1. / G_meters_to_units_factor(unit_id);
        unit = G_get_units_name(unit_id, 1, 0);
    }
    /* keep meters in case of latlon */
    else if (projection == PROJECTION_LL) {
        factor = 1;
        unit = "meters";
    } 
    else {
        /* get conversion factor to current units */
        unit = G_database_unit_name(1);
        factor = G_database_units_to_meters_factor();
    }

    if (parm.res->answer) {
	res = atof(parm.res->answer);
	/* Catch bad resolution ? */
	if (res <= 0)
	    G_fatal_error(_("Illegal resolution %g [%s]"), res / factor, unit);
    }
    else {
	/* Do average of EW and NS res */
	res = (window.ew_res + window.ns_res) / 2;
    }

    G_message(_("Using resolution: %g [%s]"), res / factor, unit);

    G_begin_distance_calculations();

    /* Open Input File for reading */
    /* Get Input Name */
    name = parm.opt1->answer;
    if (parm.g->answer)
	coords = 1;

    /* Open Raster File */
    fd = Rast_open_old(name, "");

    /* initialize color structure */
    if (clr)
	Rast_read_colors(name, "", &colors);

    /* Open ASCII file for output or stdout */
    outfile = parm.output->answer;

    if ((strcmp("-", outfile)) == 0) {
	fp = stdout;
    }
    else if (NULL == (fp = fopen(outfile, "w")))
	G_fatal_error(_("Unable to open file <%s>"), outfile);

    /* Get Raster Type */
    data_type = Rast_get_map_type(fd);
    /* Done with file */

    /* Show message giving output format */
    G_message(_("Output columns:"));
    if (coords == 1)
	sprintf(formatbuff,
		_("Easting, Northing, Along track dist. [%s], Elevation"), unit);
    else
	sprintf(formatbuff, _("Along track dist. [%s], Elevation"), unit);
    if (clr)
	strcat(formatbuff, _(" RGB color"));
    G_message(formatbuff);

    /* Get Profile Start Coords */
    if (parm.coord_file->answer) {
	if (strcmp("-", parm.coord_file->answer) == 0)
	    coor_fp = stdin;
	else
	    coor_fp = fopen(parm.coord_file->answer, "r");

	if (coor_fp == NULL)
	    G_fatal_error(_("Could not open <%s>"), parm.coord_file->answer);


	for (n = 1; input(b1, ebuf, b2, nbuf, label, coor_fp); n++) {
	    G_debug(4, "stdin line %d: ebuf=[%s]  nbuf=[%s]", n, ebuf, nbuf);
	    if (!G_scan_easting(ebuf, &e2, G_projection()) ||
		!G_scan_northing(nbuf, &n2, G_projection()))
		G_fatal_error(_("Invalid coordinates %s %s"), ebuf, nbuf);

	    if (havefirst)
		do_profile(e1, e2, n1, n2, coords, res, fd, data_type,
			   fp, null_string, unit, factor);
	    e1 = e2;
	    n1 = n2;
	    havefirst = TRUE;
	}

	if (coor_fp != stdin)
	    fclose(coor_fp);
    }
    else {
	/* Coords given on the Command Line using the profile= option */
	for (i = 0; parm.profile->answers[i]; i += 2) {
	    /* Test for number coordinate pairs */
	    k = i;
	}

	if (k == 0) {
	    /* Only one coordinate pair supplied */
	    G_scan_easting(parm.profile->answers[0], &e1, G_projection());
	    G_scan_northing(parm.profile->answers[1], &n1, G_projection());
	    e2 = e1;
	    n2 = n1;

	    /* Get profile info */
	    do_profile(e1, e2, n1, n2, coords, res, fd, data_type, fp,
		       null_string, unit, factor);
	}
	else {
	    for (i = 0; i <= k - 2; i += 2) {
		G_scan_easting(parm.profile->answers[i], &e1, G_projection());
		G_scan_northing(parm.profile->answers[i + 1], &n1,
				G_projection());
		G_scan_easting(parm.profile->answers[i + 2], &e2,
			       G_projection());
		G_scan_northing(parm.profile->answers[i + 3], &n2,
				G_projection());

		/* Get profile info */
		do_profile(e1, e2, n1, n2, coords, res, fd, data_type,
			   fp, null_string, unit, factor);

	    }
	}
    }

    Rast_close(fd);
    fclose(fp);

    if (clr)
	Rast_free_colors(&colors);

    exit(EXIT_SUCCESS);
}				/* Done with main */
Exemplo n.º 20
0
int scan_easting(char *buf, double *f)
{
    if (scan_percent(buf, f, PS.w.west, PS.w.east))
	return 1;
    return G_scan_easting(buf, f, PS.w.proj);
}