Пример #1
0
/*!
 * \brief Read floating-point range
 *
 * Read the floating point range file <i>drange</i>. This file is
 * written in binary using XDR format.
 *
 * An empty range file indicates that the min, max are undefined. This
 * is a valid case, and the result should be an initialized range
 * struct with no defined min/max.  If the range file is missing and
 * the map is a floating-point map, this function will create a
 * default range by calling G_construct_default_range().
 *
 * \param name map name
 * \param mapset mapset name
 * \param drange pointer to FPRange structure which holds fp range
 *
 * \return 1 on success
 * \return 2 range is empty
 * \return -1 on error
 */
int Rast_read_fp_range(const char *name, const char *mapset,
		       struct FPRange *drange)
{
    struct Range range;
    int fd;
    char xdr_buf[2][XDR_DOUBLE_NBYTES];
    DCELL dcell1, dcell2;

    Rast_init();
    Rast_init_fp_range(drange);

    if (Rast_map_type(name, mapset) == CELL_TYPE) {
	/* if map is integer
	   read integer range and convert it to double */

	if (Rast_read_range(name, mapset, &range) >= 0) {
	    /* if the integer range is empty */
	    if (range.first_time)
		return 2;

	    Rast_update_fp_range((DCELL) range.min, drange);
	    Rast_update_fp_range((DCELL) range.max, drange);
	    return 1;
	}
	return -1;
    }

    fd = -1;

    if (G_find_file2_misc("cell_misc", "f_range", name, mapset)) {
	fd = G_open_old_misc("cell_misc", "f_range", name, mapset);
	if (fd < 0) {
	    G_warning(_("Unable to read fp range file for <%s>"),
		      G_fully_qualified_name(name, mapset));
	    return -1;
	}

	if (read(fd, xdr_buf, sizeof(xdr_buf)) != sizeof(xdr_buf)) {
	    /* if the f_range file exists, but empty file, meaning Nulls */
	    close(fd);
	    G_debug(1, "Empty fp range file meaning Nulls for <%s>",
		      G_fully_qualified_name(name, mapset));
	    return 2;
	}

	G_xdr_get_double(&dcell1, xdr_buf[0]);
	G_xdr_get_double(&dcell2, xdr_buf[1]);

	Rast_update_fp_range(dcell1, drange);
	Rast_update_fp_range(dcell2, drange);
	close(fd);
    }

    return 1;
}
Пример #2
0
void parse(int argc, char *argv[], struct Parms *parms)
{
    struct Option *maps, *fs;
    struct Flag *labels, *overlap;
    const char *name, *mapset;

    maps = G_define_option();

    maps->key = "maps";
    maps->key_desc = "map1,map2";
    maps->required = YES;
    maps->multiple = NO;
    maps->type = TYPE_STRING;
    maps->description = _("Maps for computing inter-class distances");
    maps->gisprompt = "old,cell,raster";

    fs = G_define_option();
    fs->key = "fs";
    fs->required = NO;
    fs->multiple = NO;
    fs->answer = ":";		/* colon is default output fs */
    fs->type = TYPE_STRING;
    fs->description = _("Output field separator");

    labels = G_define_flag();
    labels->key = 'l';
    labels->description = _("Include category labels in the output");

    overlap = G_define_flag();
    overlap->key = 'o';
    overlap->description =
	_("Report zero distance if rasters are overlapping");

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

    name = parms->map1.name = maps->answers[0];
    mapset = parms->map1.mapset = G_find_raster2(name, "");
    if (mapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), name);

    parms->map1.fullname = G_fully_qualified_name(name, mapset);

    name = parms->map2.name = maps->answers[1];
    mapset = parms->map2.mapset = G_find_raster2(name, "");
    if (mapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), name);

    parms->map2.fullname = G_fully_qualified_name(name, mapset);

    parms->labels = labels->answer ? 1 : 0;
    parms->fs = fs->answer;
    parms->overlap = overlap->answer ? 1 : 0;
}
Пример #3
0
Файл: Gs3.c Проект: caomw/grass
/*!
   \brief Pack color table (floating-point map)

   Passed a array of floats that will be converted from cell values
   to packed colors (0xbbggrr) and float to int 
   Floating point data not freed here, use: 
   gsds_free_data_buff(id, ATTY_FLOAT)

   \param filename raster map name
   \param fbuf
   \param ibuf
   \param rows number of rows
   \param cols number of cols
 */
void Gs_pack_colors_float(const char *filename, float *fbuf, int *ibuf,
			  int rows, int cols)
{
    const char *mapset;
    struct Colors colrules;
    unsigned char *r, *g, *b, *set;
    int i, j, *icur;
    FCELL *fcur;

    mapset = G_find_raster2(filename, "");
    if (!mapset) {
	G_warning(_("Raster map <%s> not found"), filename);
	return;
    }

    r = (unsigned char *)G_malloc(cols);
    g = (unsigned char *)G_malloc(cols);
    b = (unsigned char *)G_malloc(cols);
    set = (unsigned char *)G_malloc(cols);

    Rast_read_colors(filename, mapset, &colrules);

    fcur = fbuf;
    icur = ibuf;

    G_message(_("Translating colors from raster map <%s>..."),
	      G_fully_qualified_name(filename, mapset));
    
    for (i = 0; i < rows; i++) {
	Rast_lookup_f_colors(fcur, r, g, b, set, cols, &colrules);
	G_percent(i, rows, 2);

	for (j = 0; j < cols; j++) {
	    if (set[j]) {
		icur[j] =
		    (r[j] & 0xff) | ((g[j] & 0xff) << 8) | ((b[j] & 0xff) <<
							    16);
	    }
	    else {
		icur[j] = NO_DATA_COL;
	    }
	}

	icur = &(icur[cols]);
	fcur = &(fcur[cols]);
    }
    G_percent(1, 1, 1);
    
    Rast_free_colors(&colrules);

    G_free(r);
    G_free(g);
    G_free(b);
    G_free(set);

    return;
}
Пример #4
0
/*!
   \brief Load raster map as integer map

   Calling function must have already allocated space in buff for
   struct BM of wind->rows & wind->cols.

   This routine simply loads the map into the bitmap by repetitve calls
   to get_map_row.  Any value other than 0 in the map will set the bitmap.
   (may want to change later to allow specific value to set)

   Changed to use null.

   \param wind current window
   \param map_name raster map name
   \param[out] buff data buffer

   \returns 1 on success
   \return -1 on failure
 */
int Gs_loadmap_as_bitmap(struct Cell_head *wind, const char *map_name,
			 struct BM *buff)
{
    FILEDESC cellfile;
    const char *map_set;
    char *nullflags;
    int *tmp_buf;
    int row, col;

    G_debug(3, "Gs_loadmap_as_bitmap");

    map_set = G_find_cell2(map_name, "");
    if (!map_set) {
	G_warning(_("Raster map <%s> not found"), map_name);
	return -1;
    }

    if ((cellfile = G_open_cell_old(map_name, map_set)) == -1) {
	G_fatal_error(_("Unable to open raster map <%s>"), map_name);
    }

    tmp_buf = (int *)G_malloc(wind->cols * sizeof(int));	/* G_fatal_error */
    if (!tmp_buf) {
	return -1;
    }

    nullflags = G_allocate_null_buf();
    if (!nullflags) {
	G_fatal_error(_("Unable to allocate memory for a null buffer"));
    }

    G_message(_("Loading raster map <%s>..."),
	      G_fully_qualified_name(map_name, map_set));

    for (row = 0; row < wind->rows; row++) {
	G_get_null_value_row(cellfile, nullflags, row);

	for (col = 0; col < wind->cols; col++) {
	    if (nullflags[col]) {
		/* no data */
		BM_set(buff, col, row, 1);
	    }
	    else {
		BM_set(buff, col, row, 0);
	    }
	}
    }

    G_close_cell(cellfile);

    G_free(tmp_buf);
    G_free(nullflags);

    return (1);
}
Пример #5
0
/*!
   \brief Load raster map as floating point map

   Calling function must have already allocated space in buff for
   wind->rows * wind->cols floats.

   This routine simply loads the map into a 2d array by repetitve calls
   to get_f_raster_row.

   \param wind current window
   \param map_name raster map name
   \param[out] buff data buffer
   \param[out] nullmap null map buffer
   \param[out] has_null indicates if raster map contains null-data

   \return 1 on success
   \return 0 on failure
 */
int Gs_loadmap_as_float(struct Cell_head *wind, const char *map_name,
			float *buff, struct BM *nullmap, int *has_null)
{
    FILEDESC cellfile;
    const char *map_set;
    char *nullflags;
    int offset, row, col;

    G_debug(3, "Gs_loadmap_as_float(): name=%s", map_name);

    map_set = G_find_cell2(map_name, "");
    if (!map_set) {
	G_warning(_("Raster map <%s> not found"), map_name);
	return 0;
    }
    *has_null = 0;

    nullflags = G_allocate_null_buf();	/* G_fatal_error */
    if (!nullflags) {
	G_fatal_error(_("Unable to allocate memory for a null buffer"));
    }

    if ((cellfile = G_open_cell_old(map_name, map_set)) == -1) {
	G_fatal_error(_("Unable to open raster map <%s>"), map_name);
    }

    G_message(_("Loading raster map <%s>..."),
	      G_fully_qualified_name(map_name, map_set));

    for (row = 0; row < wind->rows; row++) {
	offset = row * wind->cols;
	G_get_f_raster_row(cellfile, &(buff[offset]), row);
	G_get_null_value_row(cellfile, nullflags, row);

	G_percent(row, wind->rows, 2);

	for (col = 0; col < wind->cols; col++) {
	    if (nullflags[col] || G_is_f_null_value(buff + offset + col)) {
		*has_null = 1;
		BM_set(nullmap, col, row, 1);
	    }
	    /* set nm */
	}
    }
    G_percent(1, 1, 1);

    G_debug(4, "  has_null=%d", *has_null);

    G_close_cell(cellfile);

    G_free(nullflags);

    return (1);
}
Пример #6
0
int load_vectors(const struct Option *elev_map,
		 const struct Option *elev_const, const struct Option *vect,
		 const struct Option *position,
		 int map_obj_type, nv_data * data)
{
    int i, id;
    int nvects;

    const char *mapset;

    double x, y, z;
    
    if ((!elev_map->answer || elev_const->answer) && GS_num_surfs() == 0) {	/* load base surface if no loaded */
	int *surf_list, nsurf;

	Nviz_new_map_obj(MAP_OBJ_SURF, NULL, 0.0, data);

	surf_list = GS_get_surf_list(&nsurf);
	GS_set_att_const(surf_list[0], ATT_TRANSP, 255);
    }

    nvects = 0;

    for (i = 0; vect->answers[i]; i++) {
	mapset = G_find_vector2(vect->answers[i], "");
	if (mapset == NULL) {
	    G_fatal_error(_("Vector map <%s> not found"), vect->answers[i]);
	}
	id = Nviz_new_map_obj(map_obj_type,
			      G_fully_qualified_name(vect->answers[i], mapset),
			      0.0, data);

	/* set position */
	x = atof(position->answers[i*3+0]);
	y = atof(position->answers[i*3+1]);
	z = atof(position->answers[i*3+2]);

	if (map_obj_type == MAP_OBJ_VECT)
	    GV_set_trans(id, x, y, z);
	else
	    GP_set_trans(id, x, y, z);

	nvects++;
    }

    return nvects;
}
Пример #7
0
Файл: Gs3.c Проект: caomw/grass
/*!
   \brief Load raster map as integer map

   Calling function must have already allocated space in buff for
   struct BM of wind->rows & wind->cols.

   This routine simply loads the map into the bitmap by repetitve calls
   to get_map_row.  Any value other than 0 in the map will set the bitmap.
   (may want to change later to allow specific value to set)

   Changed to use null.

   \param wind current window
   \param map_name raster map name
   \param[out] buff data buffer

   \returns 1 on success
   \return -1 on failure
 */
int Gs_loadmap_as_bitmap(struct Cell_head *wind, const char *map_name,
			 struct BM *buff)
{
    FILEDESC cellfile;
    const char *map_set;
    int *tmp_buf;
    int row, col;

    G_debug(3, "Gs_loadmap_as_bitmap");

    map_set = G_find_raster2(map_name, "");
    if (!map_set) {
	G_warning(_("Raster map <%s> not found"), map_name);
	return -1;
    }

    cellfile = Rast_open_old(map_name, map_set);

    tmp_buf = (int *)G_malloc(wind->cols * sizeof(int));	/* G_fatal_error */
    if (!tmp_buf) {
	return -1;
    }

    G_message(_("Loading raster map <%s>..."),
	      G_fully_qualified_name(map_name, map_set));

    for (row = 0; row < wind->rows; row++) {
	Rast_get_c_row(cellfile, tmp_buf, row);

	for (col = 0; col < wind->cols; col++) {
	    if (Rast_is_c_null_value(&tmp_buf[col])) {
		/* no data */
		BM_set(buff, col, row, 1);
	    }
	    else {
		BM_set(buff, col, row, 0);
	    }
	}
    }

    Rast_close(cellfile);

    G_free(tmp_buf);

    return (1);
}
Пример #8
0
Файл: Gs3.c Проект: caomw/grass
/*!
   \brief Load raster map as floating point map

   Calling function must have already allocated space in buff for
   wind->rows * wind->cols floats.

   This routine simply loads the map into a 2d array by repetitve calls
   to get_f_raster_row.

   \param wind current window
   \param map_name raster map name
   \param[out] buff data buffer
   \param[out] nullmap null map buffer
   \param[out] has_null indicates if raster map contains null-data

   \return 1 on success
   \return 0 on failure
 */
int Gs_loadmap_as_float(struct Cell_head *wind, const char *map_name,
			float *buff, struct BM *nullmap, int *has_null)
{
    FILEDESC cellfile;
    const char *map_set;
    int offset, row, col;

    G_debug(3, "Gs_loadmap_as_float(): name=%s", map_name);

    map_set = G_find_raster2(map_name, "");
    if (!map_set) {
	G_warning(_("Raster map <%s> not found"), map_name);
	return 0;
    }
    *has_null = 0;

    cellfile = Rast_open_old(map_name, map_set);

    G_message(_("Loading raster map <%s>..."),
	      G_fully_qualified_name(map_name, map_set));

    for (row = 0; row < wind->rows; row++) {
	offset = row * wind->cols;
	Rast_get_f_row(cellfile, &(buff[offset]), row);

	G_percent(row, wind->rows, 2);

	for (col = 0; col < wind->cols; col++) {
	    if (Rast_is_f_null_value(buff + offset + col)) {
		*has_null = 1;
		BM_set(nullmap, col, row, 1);
	    }
	    /* set nm */
	}
    }
    G_percent(1, 1, 1);

    G_debug(4, "  has_null=%d", *has_null);

    Rast_close(cellfile);

    return (1);
}
Пример #9
0
int stats(void)
{
    char buf[1024];
    char mname[GNAME_MAX], rname[GMAPSET_MAX];
    const char *mmapset, *rmapset;
    int i, nl;
    size_t ns;
    FILE *fd;
    char **tokens;
    const char *argv[9];
    int argc = 0;

    strcpy(mname, maps[0]);
    mmapset = G_find_raster2(mname, "");
    if (mmapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), maps[0]);

    strcpy(rname, maps[1]);
    rmapset = G_find_raster2(rname, "");
    if (rmapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), maps[1]);

    stats_file = G_tempfile();

    argv[argc++] = "r.stats";

    argv[argc++] = "-cin";

    argv[argc++] = "fs=:";

    sprintf(buf, "input=%s,%s",
	    G_fully_qualified_name(maps[1], mmapset),
	    G_fully_qualified_name(maps[0], rmapset));
    argv[argc++] = buf;

    argv[argc++] = SF_REDIRECT_FILE;
    argv[argc++] = SF_STDOUT;
    argv[argc++] = SF_MODE_OUT;
    argv[argc++] = stats_file;

    argv[argc++] = NULL;

    if (G_vspawn_ex(argv[0], argv) != 0) {
	remove(stats_file);
	G_fatal_error("error running r.stats");
    }

    fd = fopen(stats_file, "r");
    if (fd == NULL) {
	unlink(stats_file);
	sprintf(buf, "Unable to open result file <%s>\n", stats_file);
    }

    while (G_getl(buf, sizeof buf, fd)) {
	tokens = G_tokenize(buf, ":");
	i = 0;
	ns = nstats++;
	Gstats = (GSTATS *) G_realloc(Gstats, nstats * sizeof(GSTATS));
	Gstats[ns].cats = (long *)G_calloc(nlayers, sizeof(long));
	for (nl = 0; nl < nlayers; nl++) {
	    if (sscanf(tokens[i++], "%ld", &Gstats[ns].cats[nl]) != 1)
		die();
	}
	if (sscanf(tokens[i++], "%ld", &Gstats[ns].count) != 1)
	    die();
	G_free_tokens(tokens);
    }
    fclose(fd);
    unlink(stats_file);

    return 0;
}
Пример #10
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct GParams params;
    struct Map_info Map;
    struct Map_info **BgMap;	/* backgroud vector maps */
    int nbgmaps;		/* number of registrated background maps */
    enum mode action_mode;
    FILE *ascii;

    int i;
    int move_first, snap;
    int ret, layer;
    double move_x, move_y, move_z, thresh[3];

    struct line_pnts *coord;

    struct ilist *List;

    struct cat_list *Clist;

    ascii = NULL;
    List = NULL;
    BgMap = NULL;
    nbgmaps = 0;
    coord = NULL;
    Clist = NULL;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->overwrite = TRUE;
    G_add_keyword(_("vector"));
    G_add_keyword(_("editing"));
    G_add_keyword(_("geometry"));
    module->description = _("Edits a vector map, allows adding, deleting "
			    "and modifying selected vector features.");

    if (!parser(argc, argv, &params, &action_mode))
	exit(EXIT_FAILURE);

    /* get list of categories */
    Clist = Vect_new_cat_list();
    if (params.cat->answer && Vect_str_to_cat_list(params.cat->answer, Clist)) {
	G_fatal_error(_("Unable to get category list <%s>"),
		      params.cat->answer);
    }

    /* open input file */
    if (params.in->answer) {
	if (strcmp(params.in->answer, "-") != 0) {
	    ascii = fopen(params.in->answer, "r");
	    if (ascii == NULL)
		G_fatal_error(_("Unable to open file <%s>"),
			      params.in->answer);
	}
	else {
	    ascii = stdin;
	}
    }
    if (!ascii && action_mode == MODE_ADD)
	G_fatal_error(_("Required parameter <%s> not set"), params.in->key);
    
    if (action_mode == MODE_CREATE) {
	int overwrite;

	overwrite = G_check_overwrite(argc, argv);
	if (G_find_vector2(params.map->answer, G_mapset())) {
	    if (!overwrite)
		G_fatal_error(_("Vector map <%s> already exists"),
			      params.map->answer);
	}

	/* 3D vector maps? */
	ret = Vect_open_new(&Map, params.map->answer, WITHOUT_Z);
	if (Vect_maptype(&Map) == GV_FORMAT_OGR_DIRECT) {
	    int type;
	    type = Vect_option_to_types(params.type);
	    if (type != GV_POINT && type != GV_LINE &&
		type != GV_BOUNDARY)
		G_fatal_error(_("Supported feature type for OGR layer: "
				"%s, %s or %s"), "point", "line", "boundary");
	    V2_open_new_ogr(&Map, type);
	}
	if (ret == -1) {
	    G_fatal_error(_("Unable to create vector map <%s>"),
			  params.map->answer);
	}

	G_debug(1, "Map created");

	if (ascii) {
	    /* also add new vector features */
	    action_mode = MODE_ADD;
	}
    }
    else {			/* open selected vector file */
	if (action_mode == MODE_ADD)	/* write */
	    ret = Vect_open_update2(&Map, params.map->answer, G_mapset(), params.fld->answer);
	else			/* read-only -- select features */
	    ret = Vect_open_old2(&Map, params.map->answer, G_mapset(), params.fld->answer);

	if (ret < 2)
	    G_fatal_error(_("Unable to open vector map <%s> at topological level %d"),
			  params.map->answer, 2);
    }

    G_debug(1, "Map opened");

    /* open backgroud maps */
    if (params.bmaps->answer) {
	i = 0;

	while (params.bmaps->answers[i]) {
	    const char *bmap = params.bmaps->answers[i];
	    const char *mapset = G_find_vector2(bmap, "");
	    if (!mapset)
		G_fatal_error(_("Vector map <%s> not found"), bmap);

	    if (strcmp(
		    G_fully_qualified_name(params.map->answer, G_mapset()),
		    G_fully_qualified_name(bmap, mapset)) == 0) {
		G_fatal_error(_("Unable to open vector map <%s> as the background map. "
			       "It is given as vector map to be edited."),
			      bmap);
	    }
	    nbgmaps++;
	    BgMap = (struct Map_info **)G_realloc(
		BgMap, nbgmaps * sizeof(struct Map_info *));
	    BgMap[nbgmaps - 1] =
		(struct Map_info *)G_malloc(sizeof(struct Map_info));
	    if (Vect_open_old(BgMap[nbgmaps - 1], bmap, "") == -1)
		G_fatal_error(_("Unable to open vector map <%s>"), bmap);
	    G_verbose_message(_("Background vector map <%s> registered"), bmap);
	    i++;
	}
    }

    layer = Vect_get_field_number(&Map, params.fld->answer);
    i = 0;
    while (params.maxdist->answers[i]) {
	switch (i) {
	case THRESH_COORDS:
	    thresh[THRESH_COORDS] =
		max_distance(atof(params.maxdist->answers[THRESH_COORDS]));
	    thresh[THRESH_SNAP] = thresh[THRESH_QUERY] =
		thresh[THRESH_COORDS];
	    break;
	case THRESH_SNAP:
	    thresh[THRESH_SNAP] =
		max_distance(atof(params.maxdist->answers[THRESH_SNAP]));
	    break;
	case THRESH_QUERY:
	    thresh[THRESH_QUERY] =
		atof(params.maxdist->answers[THRESH_QUERY]);
	    break;
	default:
	    break;
	}
	i++;
    }

    move_first = params.move_first->answer ? 1 : 0;
    snap = NO_SNAP;
    if (strcmp(params.snap->answer, "node") == 0)
	snap = SNAP;
    else if (strcmp(params.snap->answer, "vertex") == 0)
	snap = SNAPVERTEX;
    if (snap != NO_SNAP && thresh[THRESH_SNAP] <= 0) {
	G_warning(_("Threshold for snapping must be > 0. No snapping applied."));
	snap = NO_SNAP;
    }
    
    if (action_mode != MODE_CREATE && action_mode != MODE_ADD) {
	/* select lines */
	List = Vect_new_list();
	G_message(_("Selecting features..."));
	if (action_mode == MODE_COPY && BgMap && BgMap[0]) {
	    List = select_lines(BgMap[0], action_mode, &params, thresh, List);
	}
	else {
	    List = select_lines(&Map, action_mode, &params, thresh, List);
	}
    }

    if ((action_mode != MODE_CREATE && action_mode != MODE_ADD &&
	 action_mode != MODE_SELECT)) {
	if (List->n_values < 1) {
	    G_warning(_("No features selected, nothing to edit"));
	    action_mode = MODE_NONE;
	    ret = 0;
	}
	else {
	    /* reopen the map for updating */
	    if (action_mode == MODE_ZBULK && !Vect_is_3d(&Map)) {
		Vect_close(&Map);
		G_fatal_error(_("Vector map <%s> is not 3D. Tool '%s' requires 3D vector map. "
			       "Please convert the vector map "
			       "to 3D using e.g. %s."), params.map->answer,
			      params.tool->answer, "v.extrude");
	    }
	    Vect_close(&Map);

	    Vect_open_update2(&Map, params.map->answer, G_mapset(), params.fld->answer);
	}
    }

    /* coords option -> array */
    if (params.coord->answers) {
	coord = Vect_new_line_struct();
	int i = 0;
	double east, north;

	while (params.coord->answers[i]) {
	    east = atof(params.coord->answers[i]);
	    north = atof(params.coord->answers[i + 1]);
	    Vect_append_point(coord, east, north, 0.0);
	    i += 2;
	}
    }

    /* perform requested editation */
    switch (action_mode) {
    case MODE_CREATE:
	break;
    case MODE_ADD:
	if (!params.header->answer)
	    Vect_read_ascii_head(ascii, &Map);
	int num_lines;
	num_lines = Vect_get_num_lines(&Map);
	
	ret = Vect_read_ascii(ascii, &Map);
	G_message(_("%d features added"), ret);
	if (ret > 0) {
	    int iline;
	    struct ilist *List_added;
	    
	    List_added = Vect_new_list();
	    for (iline = num_lines + 1; iline <= Vect_get_num_lines(&Map); iline++)
		Vect_list_append(List_added, iline);
	    
	    G_verbose_message(_("Threshold value for snapping is %.2f"),
			      thresh[THRESH_SNAP]);
	    if (snap != NO_SNAP) { /* apply snapping */
		/* snap to vertex ? */
		Vedit_snap_lines(&Map, BgMap, nbgmaps, List_added,
				 thresh[THRESH_SNAP],
				 snap == SNAP ? FALSE : TRUE); 
	    }
	    if (params.close->answer) {	/* close boundaries */
		int nclosed;

		nclosed = close_lines(&Map, GV_BOUNDARY, thresh[THRESH_SNAP]);
		G_message(_("%d boundaries closed"), nclosed);
	    }
	    Vect_destroy_list(List_added);
	}
	break;
    case MODE_DEL:
	ret = Vedit_delete_lines(&Map, List);
	G_message(_("%d features deleted"), ret);
	break;
    case MODE_MOVE:
	move_x = atof(params.move->answers[0]);
	move_y = atof(params.move->answers[1]);
	move_z = atof(params.move->answers[2]);
	G_verbose_message(_("Threshold value for snapping is %.2f"),
			  thresh[THRESH_SNAP]);
	ret = Vedit_move_lines(&Map, BgMap, nbgmaps, List, move_x, move_y, move_z, snap, thresh[THRESH_SNAP]);
	G_message(_("%d features moved"), ret);
	break;
    case MODE_VERTEX_MOVE:
	move_x = atof(params.move->answers[0]);
	move_y = atof(params.move->answers[1]);
	move_z = atof(params.move->answers[2]);
	G_verbose_message(_("Threshold value for snapping is %.2f"),
			  thresh[THRESH_SNAP]);
	ret = Vedit_move_vertex(&Map, BgMap, nbgmaps, List, coord, thresh[THRESH_COORDS], thresh[THRESH_SNAP], move_x, move_y, move_z, move_first, snap);
	G_message(_("%d vertices moved"), ret);
	break;
    case MODE_VERTEX_ADD:
	ret = Vedit_add_vertex(&Map, List, coord, thresh[THRESH_COORDS]);
	G_message(_("%d vertices added"), ret);
	break;
    case MODE_VERTEX_DELETE:
	ret = Vedit_remove_vertex(&Map, List, coord, thresh[THRESH_COORDS]);
	G_message(_("%d vertices removed"), ret);
	break;
    case MODE_BREAK:
	if (params.coord->answer) {
	    ret = Vedit_split_lines(&Map, List,
				    coord, thresh[THRESH_COORDS], NULL);
	}
	else {
	    ret = Vect_break_lines_list(&Map, List, NULL, GV_LINES, NULL);
	}
	G_message(_("%d lines broken"), ret);
	break;
    case MODE_CONNECT:
	G_verbose_message(_("Threshold value for snapping is %.2f"),
			  thresh[THRESH_SNAP]);
	ret = Vedit_connect_lines(&Map, List, thresh[THRESH_SNAP]);
	G_message(_("%d lines connected"), ret);
	break;
    case MODE_MERGE:
	ret = Vedit_merge_lines(&Map, List);
	G_message(_("%d lines merged"), ret);
	break;
    case MODE_SELECT:
	ret = print_selected(List);
	break;
    case MODE_CATADD:
	ret = Vedit_modify_cats(&Map, List, layer, 0, Clist);
	G_message(_("%d features modified"), ret);
	break;
    case MODE_CATDEL:
	ret = Vedit_modify_cats(&Map, List, layer, 1, Clist);
	G_message(_("%d features modified"), ret);
	break;
    case MODE_COPY:
	if (BgMap && BgMap[0]) {
	    if (nbgmaps > 1)
		G_warning(_("Multiple background maps were given. "
			    "Selected features will be copied only from "
			    "vector map <%s>."),
			  Vect_get_full_name(BgMap[0]));

	    ret = Vedit_copy_lines(&Map, BgMap[0], List);
	}
	else {
	    ret = Vedit_copy_lines(&Map, NULL, List);
	}
	G_message(_("%d features copied"), ret);
	break;
    case MODE_SNAP:
	G_verbose_message(_("Threshold value for snapping is %.2f"),
			  thresh[THRESH_SNAP]);
	ret = snap_lines(&Map, List, thresh[THRESH_SNAP]);
	break;
    case MODE_FLIP:
	ret = Vedit_flip_lines(&Map, List);
	G_message(_("%d lines flipped"), ret);
	break;
    case MODE_NONE:
	break;
    case MODE_ZBULK:{
	    double start, step;
	    double x1, y1, x2, y2;

	    start = atof(params.zbulk->answers[0]);
	    step = atof(params.zbulk->answers[1]);

	    x1 = atof(params.bbox->answers[0]);
	    y1 = atof(params.bbox->answers[1]);
	    x2 = atof(params.bbox->answers[2]);
	    y2 = atof(params.bbox->answers[3]);

	    ret = Vedit_bulk_labeling(&Map, List,
				      x1, y1, x2, y2, start, step);

	    G_message(_("%d lines labeled"), ret);
	    break;
	}
    case MODE_CHTYPE:{
	    ret = Vedit_chtype_lines(&Map, List);

	    if (ret > 0) {
		G_message(_("%d features converted"), ret);
	    }
	    else {
		G_message(_("No feature modified"));
	    }
	    break;
	}
    default:
	G_warning(_("Operation not implemented"));
	ret = -1;
	break;
    }
    
    Vect_hist_command(&Map);

    /* build topology only if requested or if tool!=select */
    if (!(action_mode == MODE_SELECT || params.topo->answer == 1 ||
	 !MODE_NONE)) {
	Vect_build_partial(&Map, GV_BUILD_NONE);
	Vect_build(&Map);
    }

    if (List)
	Vect_destroy_list(List);

    Vect_close(&Map);

    G_debug(1, "Map closed");

    /* close background maps */
    for (i = 0; i < nbgmaps; i++) {
	Vect_close(BgMap[i]);
	G_free((void *)BgMap[i]);
    }
    G_free((void *)BgMap);

    if (coord)
	Vect_destroy_line_struct(coord);

    if (Clist)
	Vect_destroy_cat_list(Clist);

    G_done_msg(" ");

    if (ret > -1) {
	exit(EXIT_SUCCESS);
    }
    else {
	exit(EXIT_FAILURE);
    }
}
Пример #11
0
int main(int argc, char *argv[])
{
    char *name, *mapset;
    char rname[GNAME_MAX], rmapset[GMAPSET_MAX];
    char path[GPATH_MAX];
    int row, col, null_fd;
    unsigned char *null_bits;
    RASTER_MAP_TYPE map_type;
    int change_null = 0, create, remove, only_int, only_fp, only_null;
    int is_reclass;

    struct GModule *module;
    struct
    {
	struct Option *map;
	struct Option *setnull;
	struct Option *null;
    } parms;
    struct
    {
	struct Flag *f;
	struct Flag *n;
	struct Flag *i;
	struct Flag *c;
	struct Flag *r;
    } flags;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, null data");
    module->description = _("Manages NULL-values of given raster map.");

    parms.map = G_define_standard_option(G_OPT_R_MAP);
    parms.map->description = _("Name of raster map for which to edit null file");

    parms.setnull = G_define_option();
    parms.setnull->key = "setnull";
    parms.setnull->key_desc = "val[-val]";
    parms.setnull->type = TYPE_STRING;
    parms.setnull->required = NO;
    parms.setnull->multiple = YES;
    parms.setnull->description = _("List of cell values to be set to NULL");
    parms.setnull->guisection = _("Modify");
 
    parms.null = G_define_option();
    parms.null->key = "null";
    parms.null->type = TYPE_DOUBLE;
    parms.null->required = NO;
    parms.null->multiple = NO;
    parms.null->description = _("The value to replace the null value by");
    parms.null->guisection = _("Modify");

    flags.f = G_define_flag();
    flags.f->key = 'f';
    flags.f->description = _("Only do the work if the map is floating-point");
    flags.f->guisection = _("Check");

    flags.i = G_define_flag();
    flags.i->key = 'i';
    flags.i->description = _("Only do the work if the map is integer");
    flags.i->guisection = _("Check");

    flags.n = G_define_flag();
    flags.n->key = 'n';
    flags.n->description =
	_("Only do the work if the map doesn't have a NULL-value bitmap file");
    flags.n->guisection = _("Check");

    flags.c = G_define_flag();
    flags.c->key = 'c';
    flags.c->description =
	_("Create NULL-value bitmap file validating all data cells");

    flags.r = G_define_flag();
    flags.r->key = 'r';
    flags.r->description = _("Remove NULL-value bitmap file");
    flags.r->guisection = _("Remove");

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

    only_int = flags.i->answer;
    only_fp = flags.f->answer;
    only_null = flags.n->answer;
    create = flags.c->answer;
    remove = flags.r->answer;

    name = parms.map->answer;
    mapset = G_find_cell2(name, "");
    if (mapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), name);

    is_reclass = (G_is_reclass(name, mapset, rname, rmapset) > 0);
    if (is_reclass)
	G_fatal_error(_("Raster map <%s> is a reclass of map <%s@%s>. "
			"Consider to generate a copy with r.mapcalc. Exiting."),
		      name, rname, rmapset);


    if (strcmp(mapset, G_mapset()) != 0)
	G_fatal_error(_("Raster map <%s> is not in your mapset <%s>"),
		      name, G_mapset());
    
    if (parms.null->answer) {
	if (sscanf(parms.null->answer, "%lf", &new_null) == 1)
	    change_null = 1;
	else
	    G_fatal_error(_("%s is illegal entry for null"),
			  parms.null->answer);
    }

    map_type = G_raster_map_type(name, mapset);

    if (only_null && G_find_file_misc("cell_misc", "null", name, mapset))
	G_fatal_error(_("Raster map <%s> already has a null bitmap file"), name);

    if (map_type == CELL_TYPE) {
	if (only_fp)
	    G_fatal_error(_("<%s> is integer raster map (CELL)"),
			  name);

	if ((double)((int)new_null) != new_null) {
	    G_warning(_("<%s> is integer raster map (CELL). Using null=%d."),
		      name, (int)new_null);
	    new_null = (double)((int)new_null);
	}
    }
    else if (only_int)
	G_fatal_error(_("<%s> is floating pointing raster map"),
		      name);

    parse_vallist(parms.setnull->answers, &d_mask);

    if (G_get_cellhd(name, mapset, &cellhd) < 0)
	G_fatal_error(_("Unable to read header of raster map <%s>"),
		      G_fully_qualified_name(name, mapset));

    if (create) {
	/* write a file of no-nulls */
	null_bits = (unsigned char *)G__allocate_null_bits(cellhd.cols);
	/* init all cells to 0's */
	for (col = 0; col < G__null_bitstream_size(cellhd.cols); col++)
	    null_bits[col] = 0;

	null_fd = G_open_new_misc("cell_misc", "null", name);

	G_verbose_message(_("Writing new null file for raster map <%s>..."),
			  name);

	for (row = 0; row < cellhd.rows; row++) {
	    G_percent(row, cellhd.rows, 1);
	    if (G__write_null_bits(null_fd, null_bits, row, cellhd.cols, 0) <
		0)
		G_fatal_error(_("Error writing null row %d"), row);
	}
	G_percent(row, cellhd.rows, 1);
	close(null_fd);

	G_done_msg(_("Raster map <%s> modified."), name);

	exit(EXIT_SUCCESS);
    }

    if (remove) {
	/* write a file of no-nulls */
	G_verbose_message(_("Removing null file for raster map <%s>..."),
			   name);
	null_fd = G_open_new_misc("cell_misc", "null", name);
	G__file_name_misc(path, "cell_misc", "null", name, mapset);
	unlink(path);

	G_done_msg(_("Raster map <%s> modified."), name);

	exit(EXIT_SUCCESS);
    }

    process(name, mapset, change_null, map_type);

    exit(EXIT_SUCCESS);
}
Пример #12
0
/*!
   \brief Load to points to memory

   The other alternative may be to load to a tmp file.

   \param name name of vector map to be loaded
   \param[out] nsites number of loaded points
   \param[out] has_z 2D or 3D points data loaded?

   \return pointer to geopoint struct (array)
   \return NULL on failure
 */
geopoint *Gp_load_sites(const char *name, int *nsites, int *has_z)
{
    struct Map_info map;
    static struct line_pnts *Points = NULL;
    struct line_cats *Cats = NULL;
    geopoint *top, *gpt, *prev;
    int np, ltype, eof;
    struct Cell_head wind;
    int ndim;
    const char *mapset;

    np = 0;
    eof = 0;
    
    mapset = G_find_vector2(name, "");
    if (!mapset) {
	G_warning(_("Vector map <%s> not found"), name);
	return NULL;
    }
    
    Vect_set_open_level(1);
    if (Vect_open_old(&map, name, "") == -1) {
	G_fatal_error(_("Unable to open vector map <%s>"),
		      G_fully_qualified_name(name, mapset));
    }
    
    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();
    
    top = gpt = (geopoint *) G_malloc(sizeof(geopoint));
    G_zero(gpt, sizeof(geopoint));
    if (!top) {
	return NULL;
    }

    G_get_set_window(&wind);
    Vect_set_constraint_region(&map, wind.north, wind.south, wind.east,
			       wind.west, PORT_DOUBLE_MAX, -PORT_DOUBLE_MAX);

    /* get ndim */
    *has_z = 0;
    ndim = 2;
    if (Vect_is_3d(&map)) {
	*has_z = 1;
	ndim = 3;
    }

    while (eof == 0) {
	ltype = Vect_read_next_line(&map, Points, Cats);
	switch (ltype) {
	case -1:
	    {
		G_warning(_("Unable to read vector map <%s>"),
			  G_fully_qualified_name(name, mapset));
		return NULL;
	    }
	case -2:		/* EOF */
	    {
		eof = 1;
		continue;
	    }
	}
	if ((ltype & GV_POINTS)) {
	    np++;
	    gpt->p3[X] = Points->x[0];
	    gpt->p3[Y] = Points->y[0];

	    if (ndim > 2) {
		gpt->dims = 3;
		gpt->p3[Z] = Points->z[0];
	    }
	    else {
		gpt->dims = 2;
	    }

	    /* Store category info for thematic display */
	    if (Cats->n_cats > 0) {
		gpt->cats = Cats;
		Cats = Vect_new_cats_struct();
	    }
	    else {
		Vect_reset_cats(Cats);
	    }
	    /* initialize style */
	    gpt->highlighted = 0;
	    
	    G_debug(5, "loading vector point %d x=%f y=%f ncats=%d",
		    np, Points->x[0], Points->y[0], Cats->n_cats);

	    gpt->next = (geopoint *) G_malloc(sizeof(geopoint));	/* G_fatal_error */
	    G_zero(gpt->next, sizeof(geopoint));
	    if (!gpt->next) {
		return NULL;
	    }

	    prev = gpt;
	    gpt = gpt->next;
	}

    }
    if (np > 0) {
	prev->next = NULL;
	G_free(gpt);
    }

    Vect_close(&map);

    if (!np) {
	G_warning(_("No points from vector map <%s> fall within current region"),
		  G_fully_qualified_name(name, mapset));
	return (NULL);
    }
    else {
	G_message(_("Vector map <%s> loaded (%d points)"),
		  G_fully_qualified_name(name, mapset), np);
    }

    *nsites = np;

    return top;
}
Пример #13
0
/*!
   \brief Load vector map to memory

   The other alternative may be to load to a tmp file

   \param grassname vector map name
   \param[out] number of loaded features

   \return pointer to geoline struct
   \return NULL on failure
 */
geoline *Gv_load_vect(const char *grassname, int *nlines)
{
    struct Map_info map;
    struct line_pnts *points;
    struct line_cats *Cats = NULL;
    geoline *top, *gln, *prev;
    int np, i, n, nareas, nl = 0, area, type, is3d;
    struct Cell_head wind;
    float vect[2][3];
    const char *mapset;

    mapset = G_find_vector2(grassname, "");
    if (!mapset) {
	G_warning(_("Vector map <%s> not found"), grassname);
	return NULL;
    }

    Vect_set_open_level(2);
    if (Vect_open_old(&map, grassname, "") == -1) {
	G_warning(_("Unable to open vector map <%s>"),
		  G_fully_qualified_name(grassname, mapset));
	return NULL;
    }

    top = gln = (geoline *) G_malloc(sizeof(geoline));	/* G_fatal_error */
    if (!top) {
	return NULL;
    }

    prev = top;

#ifdef TRAK_MEM
    Tot_mem += sizeof(geoline);
#endif

    points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();

    G_get_set_window(&wind);
    Vect_set_constraint_region(&map, wind.north, wind.south, wind.east,
			       wind.west, PORT_DOUBLE_MAX, -PORT_DOUBLE_MAX);

    is3d = Vect_is_3d(&map);

    /* Read areas */
    n = Vect_get_num_areas(&map);
    nareas = 0;
    G_debug(3, "Reading vector areas (nareas = %d)", n);
    for (area = 1; area <= n; area++) {
	G_debug(3, " area %d", area);
	Vect_get_area_points(&map, area, points);
	if (points->n_points < 3)
	    continue;

	/* initialize style */
	gln->highlighted = 0;

	gln->type = OGSF_POLYGON;
	gln->npts = np = points->n_points;
	G_debug(3, "  np = %d", np);

	if (is3d) {
	    gln->dims = 3;
	    gln->p3 = (Point3 *) G_calloc(np, sizeof(Point3));	/* G_fatal_error */
	    if (!gln->p3) {
		return (NULL);
	    }
#ifdef TRAK_MEM
	    Tot_mem += (np * sizeof(Point3));
#endif
	}
	else {
	    gln->dims = 2;
	    gln->p2 = (Point2 *) G_calloc(np, sizeof(Point2));	/* G_fatal_error */
	    if (!gln->p2) {
		return (NULL);
	    }
#ifdef TRAK_MEM
	    Tot_mem += (np * sizeof(Point2));
#endif
	}

	for (i = 0; i < np; i++) {
	    if (is3d) {
		gln->p3[i][X] = points->x[i];
		gln->p3[i][Y] = points->y[i];
		gln->p3[i][Z] = points->z[i];
	    }
	    else {
		gln->p2[i][X] = points->x[i];
		gln->p2[i][Y] = points->y[i];
	    }
	}
	/* Calc normal (should be average) */
	if (is3d) {
	    vect[0][X] = (float)(gln->p3[0][X] - gln->p3[1][X]);
	    vect[0][Y] = (float)(gln->p3[0][Y] - gln->p3[1][Y]);
	    vect[0][Z] = (float)(gln->p3[0][Z] - gln->p3[1][Z]);
	    vect[1][X] = (float)(gln->p3[2][X] - gln->p3[1][X]);
	    vect[1][Y] = (float)(gln->p3[2][Y] - gln->p3[1][Y]);
	    vect[1][Z] = (float)(gln->p3[2][Z] - gln->p3[1][Z]);
	    GS_v3cross(vect[1], vect[0], gln->norm);

	}

	gln->cats = NULL;
	gln->next = (geoline *) G_malloc(sizeof(geoline));	/* G_fatal_error */
	if (!gln->next) {
	    return (NULL);
	}

#ifdef TRAK_MEM
	Tot_mem += sizeof(geoline);
#endif

	prev = gln;
	gln = gln->next;
	nareas++;
    }
    G_debug(3, "%d areas loaded", nareas);

    /* Read all lines */
    G_debug(3, "Reading vector lines ...");
    while (-1 < (type = Vect_read_next_line(&map, points, Cats))) {
	G_debug(3, "line type = %d", type);
	if (type & (GV_LINES | GV_FACE)) {
	    if (type & (GV_LINES)) {
		gln->type = OGSF_LINE;
	    }
	    else {
		gln->type = OGSF_POLYGON;
		/* Vect_append_point ( points, points->x[0], points->y[0], points->z[0] ); */
	    }

	    /* initialize style */
	    gln->highlighted = 0;

	    gln->npts = np = points->n_points;
	    G_debug(3, "  np = %d", np);

	    if (is3d) {
		gln->dims = 3;
		gln->p3 = (Point3 *) G_calloc(np, sizeof(Point3));	/* G_fatal_error */
		if (!gln->p3) {
		    return (NULL);
		}
#ifdef TRAK_MEM
		Tot_mem += (np * sizeof(Point3));
#endif
	    }
	    else {
		gln->dims = 2;
		gln->p2 = (Point2 *) G_calloc(np, sizeof(Point2));	/* G_fatal_error */
		if (!gln->p2) {
		    return (NULL);
		}
#ifdef TRAK_MEM
		Tot_mem += (np * sizeof(Point2));
#endif
	    }

	    for (i = 0; i < np; i++) {
		if (is3d) {
		    gln->p3[i][X] = points->x[i];
		    gln->p3[i][Y] = points->y[i];
		    gln->p3[i][Z] = points->z[i];
		}
		else {
		    gln->p2[i][X] = points->x[i];
		    gln->p2[i][Y] = points->y[i];
		}
	    }
	    /* Calc normal (should be average) */
	    if (is3d && gln->type == OGSF_POLYGON) {
		vect[0][X] = (float)(gln->p3[0][X] - gln->p3[1][X]);
		vect[0][Y] = (float)(gln->p3[0][Y] - gln->p3[1][Y]);
		vect[0][Z] = (float)(gln->p3[0][Z] - gln->p3[1][Z]);
		vect[1][X] = (float)(gln->p3[2][X] - gln->p3[1][X]);
		vect[1][Y] = (float)(gln->p3[2][Y] - gln->p3[1][Y]);
		vect[1][Z] = (float)(gln->p3[2][Z] - gln->p3[1][Z]);
		GS_v3cross(vect[1], vect[0], gln->norm);
		G_debug(3, "norm %f %f %f", gln->norm[0], gln->norm[1],
			gln->norm[2]);
	    }

	    /* Store category info for thematic display */
	    if (Cats->n_cats > 0) {
		gln->cats = Cats;
		Cats = Vect_new_cats_struct();
	    }
	    else {
		gln->cats = NULL;
		Vect_reset_cats(Cats);
	    }

	    gln->next = (geoline *) G_malloc(sizeof(geoline));	/* G_fatal_error */
	    if (!gln->next) {
		return (NULL);
	    }
#ifdef TRAK_MEM
	    Tot_mem += sizeof(geoline);
#endif

	    prev = gln;
	    gln = gln->next;
	    nl++;
	}
    }
    G_debug(3, "%d lines loaded", nl);

    nl += nareas;

    prev->next = NULL;
    G_free(gln);

#ifdef TRAK_MEM
    Tot_mem -= sizeof(geoline);
#endif

    Vect_close(&map);

    if (!nl) {
	G_warning(_("No features from vector map <%s> fall within current region"),
		  G_fully_qualified_name(grassname, mapset));
	return (NULL);
    }
    else {
	G_message(_("Vector map <%s> loaded (%d features)"),
		  G_fully_qualified_name(grassname, mapset), nl);
    }

    *nlines = nl;

#ifdef TRAK_MEM
    G_debug(3, "Total vect memory = %d Kbytes", Tot_mem / 1000);
#endif

    return (top);
}
Пример #14
0
/*!
 * \brief Read raster range (CELL)
 *
 * This routine reads the range information for the raster map
 * <i>name</i> in <i>mapset</i> into the <i>range</i> structure.
 *
 * A diagnostic message is printed and -1 is returned if there is an error
 * reading the range file. Otherwise, 0 is returned.
 *
 * Old range file (those with 4 numbers) should treat zeros in this
 * file as NULL-values. New range files (those with just 2 numbers)
 * should treat these numbers as real data (zeros are real data in
 * this case).  An empty range file indicates that the min, max are
 * undefined. This is a valid case, and the result should be an
 * initialized range struct with no defined min/max. If the range file
 * is missing and the map is a floating-point map, this function will
 * create a default range by calling G_construct_default_range().
 *
 * \param name map name
 * \param mapset mapset name
 * \param[out] range pointer to Range structure which holds range info
 *
 * \return -1 on error
 * \return 1 on success
 * \return 2 if range is empty
 * \return 3 if raster map is floating-point, get range from quant rules
 */
int Rast_read_range(const char *name, const char *mapset, struct Range *range)
{
    FILE *fd;
    CELL x[4];
    char buf[200];
    int n, count;
    struct Quant quant;
    struct FPRange drange;
    Rast_init_range(range);
    fd = NULL;

    /* if map is not integer, read quant rules, and get limits */
    if (Rast_map_type(name, mapset) != CELL_TYPE) {
	DCELL dmin, dmax;

	if (Rast_read_quant(name, mapset, &quant) < 0) {
	    G_warning(_("Unable to read quant rules for raster map <%s>"),
		      G_fully_qualified_name(name, mapset));
	    return -1;
	}
	if (Rast_quant_is_truncate(&quant) || Rast_quant_is_round(&quant)) {
	    if (Rast_read_fp_range(name, mapset, &drange) >= 0) {
		Rast_get_fp_range_min_max(&drange, &dmin, &dmax);
		if (Rast_quant_is_truncate(&quant)) {
		    x[0] = (CELL) dmin;
		    x[1] = (CELL) dmax;
		}
		else {		/* round */

		    if (dmin > 0)
			x[0] = (CELL) (dmin + .5);
		    else
			x[0] = (CELL) (dmin - .5);
		    if (dmax > 0)
			x[1] = (CELL) (dmax + .5);
		    else
			x[1] = (CELL) (dmax - .5);
		}
	    }
	    else
		return -1;
	}
	else
	    Rast_quant_get_limits(&quant, &dmin, &dmax, &x[0], &x[1]);

	Rast_update_range(x[0], range);
	Rast_update_range(x[1], range);
	return 3;
    }

    if (G_find_file2_misc("cell_misc", "range", name, mapset)) {
	fd = G_fopen_old_misc("cell_misc", "range", name, mapset);
	if (!fd) {
	    G_warning(_("Unable to read range file for <%s>"),
		      G_fully_qualified_name(name, mapset));
	    return -1;
	}

	/* if range file exists but empty */
        if (!fgets(buf, sizeof buf, fd)) {
            if (fd)
                fclose(fd);
	    return 2;
        }

	x[0] = x[1] = x[2] = x[3] = 0;
	count = sscanf(buf, "%d%d%d%d", &x[0], &x[1], &x[2], &x[3]);

	/* if wrong format */
	if (count <= 0) {
	    if (fd)
		fclose(fd);

	    G_warning(_("Unable to read range file for <%s>"),
		      G_fully_qualified_name(name, mapset));
	    return -1;
	}

	for (n = 0; n < count; n++) {
	    /* if count==4, the range file is old (4.1) and 0's in it
	       have to be ignored */
	    if (count < 4 || x[n])
		Rast_update_range((CELL) x[n], range);
	}
	fclose(fd);
    }

    return 1;
}
Пример #15
0
int main(int argc, char *argv[])
{
    struct Map_info in, out, vis;
    struct GModule *module;	/* GRASS module for parsing arguments */
    struct Option *input, *output;	/* The input map */
    struct Option *coor, *ovis;
    char *mapset;

    struct Point *points;
    struct Line *lines;
    int num_points, num_lines;
    int n = 0;



    /* initialize GIS environment */
    G_gisinit(argv[0]);		/* reads grass env, stores program name to G_program_name() */

    /* initialize module */
    module = G_define_module();
    module->keywords = _("vector, path, visibility");
    module->description = _("Visibility graph construction.");

    /* define the arguments needed */
    input = G_define_standard_option(G_OPT_V_INPUT);
    output = G_define_standard_option(G_OPT_V_OUTPUT);

    coor = G_define_option();
    coor->key = "coordinate";
    coor->key_desc = "x,y";
    coor->type = TYPE_STRING;
    coor->required = NO;
    coor->multiple = YES;
    coor->description = _("One or more coordinates");

    ovis = G_define_option();
    ovis->key = "vis";
    ovis->type = TYPE_STRING;
    ovis->required = NO;
    ovis->description = _("Add points after computing the vis graph");

    /* options and flags parser */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    Vect_check_input_output_name(input->answer, output->answer,
				 GV_FATAL_EXIT);

    Vect_set_open_level(2);

    mapset = G_find_vector2(input->answer, NULL);	/* finds the map */

    if (mapset == NULL)
	G_fatal_error("Vector map <%s> not found", input->answer);

    if (Vect_open_old(&in, input->answer, mapset) < 1)	/* opens the map */
	G_fatal_error(_("Unable to open vector map <%s>"),
		      G_fully_qualified_name(input->answer, mapset));

    if (Vect_open_new(&out, output->answer, WITHOUT_Z) < 0) {
	Vect_close(&in);
	G_fatal_error(_("Unable to create vector map <%s>"), output->answer);
    }

    if (ovis->answer != NULL) {
	mapset = G_find_vector2(ovis->answer, NULL);

	if (Vect_open_old(&vis, ovis->answer, mapset) < 1)
	    G_fatal_error(_("Unable to open vector map <%s>"),
			  G_fully_qualified_name(ovis->answer, mapset));

	if (Vect_copy_map_lines(&vis, &out) > 0)
	    G_fatal_error(_("Unable to copy elements from vector map <%s>"),
			  G_fully_qualified_name(ovis->answer, mapset));
    }


    if (G_projection() == PROJECTION_LL)
	G_warning(_("Lat-long projection"));


    /* counting how many points and lines we have to allocate */
    count(&in, &num_points, &num_lines);

    /* modify the number if we have new points to add */
    if (coor->answers != NULL)
	num_points += count_new(coor->answers);

    /* and allocate */
    points = G_malloc(num_points * sizeof(struct Point));
    lines = G_malloc(num_lines * sizeof(struct Line));

    /* and finally set the lines */
    load_lines(&in, &points, &num_points, &lines, &num_lines);

    if (coor->answers != NULL)
	add_points(coor->answers, &points, &num_points);

    if (ovis->answer == NULL)
	construct_visibility(points, num_points, lines, num_lines, &out);
    else
	visibility_points(points, num_points, lines, num_lines, &out, n);

    G_free(points);
    G_free(lines);

    Vect_build(&out);
    Vect_close(&out);
    Vect_close(&in);

    exit(EXIT_SUCCESS);
}
Пример #16
0
int main(int argc, char *argv[])
{
    char file[GPATH_MAX], name[GNAME_MAX], *mapset;
    char *search_mapset;
    struct GModule *module;
    struct Option *elem_opt;
    struct Option *mapset_opt;
    struct Option *file_opt;
    struct Flag *n_flag;

    module = G_define_module();
    module->keywords = _("general, map management");
    module->description =
	_("Searches for GRASS data base files "
	  "and sets variables for the shell.");

    G_gisinit(argv[0]);

    /* Define the different options */

    elem_opt = G_define_option();
    elem_opt->key = "element";
    elem_opt->type = TYPE_STRING;
    elem_opt->required = YES;
    elem_opt->description = _("Name of an element");

    file_opt = G_define_option();
    file_opt->key = "file";
    file_opt->type = TYPE_STRING;
    file_opt->required = YES;
    file_opt->description = _("Name of an existing map");

    mapset_opt = G_define_option();
    mapset_opt->key = "mapset";
    mapset_opt->type = TYPE_STRING;
    mapset_opt->required = NO;
    mapset_opt->description = _("Name of a mapset");
    mapset_opt->answer = "";

    n_flag = G_define_flag();
    n_flag->key = 'n';
    n_flag->description = _("Don't add quotes");

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

    search_mapset = mapset_opt->answer;
    if (strcmp(".", search_mapset) == 0)
	search_mapset = G_mapset();
    
    if (mapset_opt->answer && strlen(mapset_opt->answer) > 0) {
	char **map_mapset = G_tokenize(file_opt->answer, "@");

	if (G_number_of_tokens(map_mapset) > 1) {
	    if (strcmp(map_mapset[1], mapset_opt->answer))
		G_fatal_error(_("Parameter 'file' contains reference to <%s> mapset, "
				"but mapset parameter <%s> does not correspond"),
			      map_mapset[1], mapset_opt->answer);
	    else
		strcpy(name, file_opt->answer);
	}
	if (G_number_of_tokens(map_mapset) == 1)
	    strcpy(name, file_opt->answer);
	G_free_tokens(map_mapset);
    }
    else
	strcpy(name, file_opt->answer);

    mapset = G_find_file2(elem_opt->answer, name, search_mapset);
    if (mapset) {
	const char *qchar = n_flag->answer ? "" : "'";
	const char *qual = G_fully_qualified_name(name, mapset);
	G__file_name(file, elem_opt->answer, name, mapset);
	fprintf(stdout, "name=%s%s%s\n", qchar, name, qchar);
	fprintf(stdout, "mapset=%s%s%s\n", qchar, mapset, qchar);
	fprintf(stdout, "fullname=%s%s%s\n", qchar, qual, qchar);
	fprintf(stdout, "file=%s%s%s\n", qchar, file, qchar);
    }
    else {
	fprintf(stdout, "name=\n");
	fprintf(stdout, "mapset=\n");
	fprintf(stdout, "fullname=\n");
	fprintf(stdout, "file=\n");
    }
    
    exit(mapset == NULL);
}
Пример #17
0
/*!
  \brief Load raster maps/constants and set surface attributes
  
  \param params module parameters
  \param data nviz data
*/
int load_rasters(const struct GParams *params, nv_data * data)
{
    const char *mapset;
    int i;
    int nelevs, nelev_map, nelev_const, ncolor_map, ncolor_const, nmask_map;
    int ntransp_map, ntransp_const, nshine_map, nshine_const;
    int nemit_map, nemit_const;
    int *surf_list, nsurfs;
    int id;

    double x, y, z;

    nelev_map = opt_get_num_answers(params->elev_map);
    nelev_const = opt_get_num_answers(params->elev_const);

    nelevs = nelev_const + nelev_map;
    /* topography (required) */
    for (i = 0; i < nelevs; i++) {
	/* check maps */
	if (i < nelev_map && strcmp(params->elev_map->answers[i], "")) {
	    mapset = G_find_raster2(params->elev_map->answers[i], "");
	    if (mapset == NULL) {
		G_fatal_error(_("Raster map <%s> not found"),
			      params->elev_map->answers[i]);
	    }

	    id = Nviz_new_map_obj(MAP_OBJ_SURF,
				  G_fully_qualified_name(params->elev_map->
							 answers[i], mapset),
				  0.0, data);
	}
	else {
	    if (i-nelev_map < nelev_const && strcmp(params->elev_const->answers[i-nelev_map], "")) {
		id = Nviz_new_map_obj(MAP_OBJ_SURF,
				      NULL,
				      atof(params->elev_const->answers[i-nelev_map]),
				      data);
	    }
	    else {
		G_fatal_error(_("Missing topography attribute for surface %d"),
			      i + 1);
	    }
	}

	/* set position */
    if (opt_get_num_answers(params->surface_pos) != 3 * nelevs){
        x = atof(params->surface_pos->answers[0]);
        y = atof(params->surface_pos->answers[1]);
        z = atof(params->surface_pos->answers[2]);
    }
    else{
        x = atof(params->surface_pos->answers[i*3+0]);
        y = atof(params->surface_pos->answers[i*3+1]);
        z = atof(params->surface_pos->answers[i*3+2]);
    }

	GS_set_trans(id, x, y, z);
    }

    /* set surface attributes */
    surf_list = GS_get_surf_list(&nsurfs);

    ncolor_map = opt_get_num_answers(params->color_map);
    ncolor_const = opt_get_num_answers(params->color_const);
    nmask_map = opt_get_num_answers(params->mask_map);
    ntransp_map = opt_get_num_answers(params->transp_map);
    ntransp_const = opt_get_num_answers(params->transp_const);
    nshine_map = opt_get_num_answers(params->shine_map);
    nshine_const = opt_get_num_answers(params->shine_const);
    nemit_map = opt_get_num_answers(params->emit_map);
    nemit_const = opt_get_num_answers(params->emit_const);

    for (i = 0; i < nsurfs; i++) {
	id = surf_list[i];
	/* color */
	/* check for color map */
	if (i < ncolor_map && strcmp(params->color_map->answers[i], "")) {
	    mapset = G_find_raster2(params->color_map->answers[i], "");
	    if (mapset == NULL) {
		G_fatal_error(_("Raster map <%s> not found"),
			      params->color_map->answers[i]);
	    }

	    Nviz_set_attr(id, MAP_OBJ_SURF, ATT_COLOR, MAP_ATT,
			  G_fully_qualified_name(params->color_map->
						 answers[i], mapset), -1.0,
			  data);
	}
	/* check for color value */
	else if (i-ncolor_map < ncolor_const &&
		 strcmp(params->color_const->answers[i-ncolor_map], "")) {
	    Nviz_set_attr(id, MAP_OBJ_SURF, ATT_COLOR, CONST_ATT, NULL,
			  Nviz_color_from_str(params->color_const->
					      answers[i-ncolor_map]), data);
	}
	else {			/* use by default elevation map for coloring */
        if (nelev_map > 0){
            Nviz_set_attr(id, MAP_OBJ_SURF, ATT_COLOR, MAP_ATT,
                G_fully_qualified_name(params->elev_map->answers[i],
                            mapset), -1.0, data);
            G_verbose_message(_("Color attribute not defined, using default <%s>"),
                G_fully_qualified_name(params->elev_map->
                                 answers[i], mapset));
        }
        else{
            G_fatal_error(_("Missing color attribute for surface %d"),
			      i + 1);
        }
	}
	/* mask */
	if (i < nmask_map && strcmp(params->mask_map->answers[i], "")) {
	    Nviz_set_attr(id, MAP_OBJ_SURF, ATT_MASK, MAP_ATT,
			  G_fully_qualified_name(params->mask_map->answers[i],
						 mapset), -1.0, data);
	}

	/* transparency */
	if (i < ntransp_map && strcmp(params->transp_map->answers[i], "")) {
	    Nviz_set_attr(id, MAP_OBJ_SURF, ATT_TRANSP, MAP_ATT,
			  G_fully_qualified_name(params->transp_map->
						 answers[i], mapset), -1.0,
			  data);
	}
	else if (i-ntransp_map < ntransp_const &&
		 strcmp(params->transp_const->answers[i-ntransp_map], "")) {
	    Nviz_set_attr(id, MAP_OBJ_SURF, ATT_TRANSP, CONST_ATT, NULL,
			  atof(params->transp_const->answers[i-ntransp_map]), data);
	}

	/* shininess */
	if (i < nshine_map && strcmp(params->shine_map->answers[i], "")) {
	    Nviz_set_attr(id, MAP_OBJ_SURF, ATT_SHINE, MAP_ATT,
			  G_fully_qualified_name(params->shine_map->
						 answers[i], mapset), -1.0,
			  data);
	}
	else if (i-nshine_map < nshine_const &&
		 strcmp(params->shine_const->answers[i-nshine_map], "")) {
	    Nviz_set_attr(id, MAP_OBJ_SURF, ATT_SHINE, CONST_ATT, NULL,
			  atof(params->shine_const->answers[i-nshine_map]), data);
	}

	/* emission */
	if (i < nemit_map && strcmp(params->emit_map->answers[i], "")) {
	    Nviz_set_attr(id, MAP_OBJ_SURF, ATT_EMIT, MAP_ATT,
			  G_fully_qualified_name(params->emit_map->answers[i],
						 mapset), -1.0, data);
	}
	else if (i-nemit_map < nemit_const &&
		 strcmp(params->emit_const->answers[i-nemit_map], "")) {
	    Nviz_set_attr(id, MAP_OBJ_SURF, ATT_EMIT, CONST_ATT, NULL,
			  atof(params->emit_const->answers[i-nemit_map]), data);
	}

	/*
	   if (i > 1)
	   set_default_wirecolors(data, i);
	 */
    }

    return nsurfs;
}
Пример #18
0
Файл: Gs3.c Проект: caomw/grass
/*!
   \brief Load raster map as integer map

   Calling function must have already allocated space in buff for
   wind->rows * wind->cols unsigned chars.  

   This routine simply loads the map into a 2d array by repetitve calls
   to get_map_row.

   Since signs of chars can be tricky, we only load positive chars
   between 0-255.

   \todo fn body Gs_loadmap_as_float()

   \param wind current window
   \param map_name raster map name
   \param[out] buff data buffer
   \param[out] nullmap null map buffer
   \param[out] has_null indicates if raster map contains null-data

   \return 1 on success
   \return -1 on failure
   \return -2 if read ok, but 1 or more values
   were too large (small) to fit into an unsigned char.
   (in which case the max (min) char is used)
 */
int Gs_loadmap_as_char(struct Cell_head *wind, const char *map_name,
		       unsigned char *buff, struct BM *nullmap, int *has_null)
{
    FILEDESC cellfile;
    const char *map_set;
    int *ti, *tmp_buf;
    int offset, row, col, val, max_char, overflow, charsize, bitplace;
    unsigned char *tc;

    G_debug(3, "Gs_loadmap_as_char");

    overflow = 0;
    charsize = 8 * sizeof(unsigned char);

    /* 0 bits for sign! */
    max_char = 1;

    for (bitplace = 0; bitplace < charsize; ++bitplace) {
	max_char *= 2;
    }

    max_char -= 1;

    map_set = G_find_raster2(map_name, "");
    if (!map_set) {
	G_warning(_("Raster map <%s> not found"), map_name);
	return -1;
    }
    *has_null = 0;

    cellfile = Rast_open_old(map_name, map_set);

    tmp_buf = (int *)G_malloc(wind->cols * sizeof(int));	/* G_fatal_error */
    if (!tmp_buf) {
	return -1;
    }

    G_message(_("Loading raster map <%s>..."),
	      G_fully_qualified_name(map_name, map_set));

    for (row = 0; row < wind->rows; row++) {
	offset = row * wind->cols;
	Rast_get_c_row(cellfile, tmp_buf, row);
	tc = (unsigned char *)&(buff[offset]);
	ti = tmp_buf;

	G_percent(row, wind->rows, 2);

	for (col = 0; col < wind->cols; col++) {
	    if (Rast_is_c_null_value(&tmp_buf[col])) {
		*has_null = 1;
		BM_set(nullmap, col, row, 1);
	    }
	    else {
		val = *ti;
		if (val > max_char) {
		    overflow = 1;
		    *tc = (unsigned char)max_char;
		}
		else if (val < 0) {
		    overflow = 1;
		    *tc = 0;
		}
		else {
		    *tc = (unsigned char)val;
		}
	    }

	    ti++;
	    tc++;
	}
    }
    G_percent(1, 1, 1);
    
    Rast_close(cellfile);

    G_free(tmp_buf);

    return (overflow ? -2 : 1);
}
Пример #19
0
Файл: Gs3.c Проект: caomw/grass
/*!
   \brief Load raster map as integer map

   Calling function must have already allocated space in buff for
   wind->rows * wind->cols shorts.  

   This routine simply loads the map into a 2d array by repetitve calls
   to get_map_row.

   \param wind current window
   \param map_name raster map name
   \param[out] buff data buffer
   \param[out] nullmap null map buffer
   \param[out] has_null indicates if raster map contains null-data

   \return 1 on success
   \return -1 on failure,
   \return -2 if read ok, but 1 or more values were too large (small)
   to fit into a short (in which case the max (min) short is used)
 */
int Gs_loadmap_as_short(struct Cell_head *wind, const char *map_name,
			short *buff, struct BM *nullmap, int *has_null)
{
    FILEDESC cellfile;
    const char *map_set;
    int *ti, *tmp_buf;
    int offset, row, col, val, max_short, overflow, shortsize, bitplace;
    short *ts;

    G_debug(3, "Gs_loadmap_as_short");

    overflow = 0;
    shortsize = 8 * sizeof(short);

    /* 1 bit for sign */
    /* same as 2 << (shortsize-1) */
    for (max_short = bitplace = 1; bitplace < shortsize; ++bitplace) {
	max_short *= 2;
    }

    max_short -= 1;

    map_set = G_find_raster2(map_name, "");
    if (!map_set) {
	G_warning(_("Raster map <%s> not found"), map_name);
	return -1;
    }
    *has_null = 0;

    cellfile = Rast_open_old(map_name, map_set);

    tmp_buf = (int *)G_malloc(wind->cols * sizeof(int));	/* G_fatal_error */
    if (!tmp_buf) {
	return -1;
    }

    G_message(_("Loading raster map <%s>..."),
	      G_fully_qualified_name(map_name, map_set));

    for (row = 0; row < wind->rows; row++) {
	offset = row * wind->cols;
	Rast_get_c_row(cellfile, tmp_buf, row);

	G_percent(row, wind->rows, 2);

	ts = &(buff[offset]);
	ti = tmp_buf;

	for (col = 0; col < wind->cols; col++) {
	    if (Rast_is_c_null_value(&tmp_buf[col])) {
		*has_null = 1;
		BM_set(nullmap, col, row, 1);
	    }
	    else {
		val = *ti;
		if (abs(val) > max_short) {
		    overflow = 1;
		    /* assign floor/ceiling value?
		     */
		    *ts = (short)(max_short * val / abs(val));
		}
		else {
		    *ts = (short)val;
		}
	    }

	    ti++;
	    ts++;
	}
    }
    G_percent(1, 1, 1);
    
    Rast_close(cellfile);

    G_free(tmp_buf);

    return (overflow ? -2 : 1);
}
Пример #20
0
#include "list.h"

/*
 *  returns 0 - success
 *          1 - error
 */
int do_copy(int n, char *old, char *mapset, char *new)
{
    int i, ret, len;
    char path[GPATH_MAX], path2[GPATH_MAX];
    int result = 0;

    G_debug(3, "Copy %s", list[n].alias);

    G_message(_("Copy %s <%s> to current mapset as <%s>"),
	      list[n].maindesc, G_fully_qualified_name(old, mapset), new);

    len = get_description_len(n);

    hold_signals(1);
    if (G_strcasecmp(list[n].alias, "vect") == 0) {
	ret = Vect_copy(old, mapset, new);
	if (ret == -1) {
	    G_warning("Cannot copy <%s> to current mapset as <%s>",
		      G_fully_qualified_name(old, mapset), new);
	    result = 1;
	}
    }
    else {
	for (i = 0; i < list[n].nelem; i++) {
	    G__make_mapset_element(list[n].element[i]);
Пример #21
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;
}
Пример #22
0
int main(int argc, char *argv[])
{
    char file[GPATH_MAX], name[GNAME_MAX];
    const char *search_mapset, *mapset;
    struct GModule *module;
    struct Option *elem_opt;
    struct Option *mapset_opt;
    struct Option *file_opt;
    struct Flag *n_flag, *l_flag;

    module = G_define_module();
    G_add_keyword(_("general"));
    G_add_keyword(_("map management"));
    G_add_keyword(_("data base files"));
    module->description =
	_("Searches for GRASS data base files "
	  "and sets variables for the shell.");

    G_gisinit(argv[0]);

    /* Define the different options */

    elem_opt = G_define_option();
    elem_opt->key = "element";
    elem_opt->type = TYPE_STRING;
    elem_opt->required = YES;
    elem_opt->description = _("Name of an element");

    file_opt = G_define_option();
    file_opt->key = "file";
    file_opt->type = TYPE_STRING;
    file_opt->required = YES;
    file_opt->description = _("Name of an existing map");

    mapset_opt = G_define_option();
    mapset_opt->key = "mapset";
    mapset_opt->type = TYPE_STRING;
    mapset_opt->required = NO;
    mapset_opt->label = _("Name of a mapset (default: search path)");
    mapset_opt->description = _("'.' for current mapset");

    n_flag = G_define_flag();
    n_flag->key = 'n';
    n_flag->description = _("Don't add quotes");

    l_flag = G_define_flag();
    l_flag->key = 'l';
    l_flag->description = _("List available elements and exit");
    l_flag->suppress_required = YES;

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

    if (l_flag->answer) {
	list_elements();
	return EXIT_SUCCESS;
    }

    search_mapset = mapset_opt->answer;
    if (!search_mapset) {
	search_mapset = G_store("");
    }
    if (strcmp(".", search_mapset) == 0)
	search_mapset = G_mapset();
    
    if (mapset_opt->answer && strlen(mapset_opt->answer) > 0) {
	char **map_mapset = G_tokenize(file_opt->answer, "@");

	if (G_number_of_tokens(map_mapset) > 1) {
	    if (strcmp(map_mapset[1], mapset_opt->answer))
		G_fatal_error(_("Parameter 'file' contains reference to <%s> mapset, "
				"but mapset parameter <%s> does not correspond"),
			      map_mapset[1], mapset_opt->answer);
	    else
		strcpy(name, file_opt->answer);
	}
	if (G_number_of_tokens(map_mapset) == 1)
	    strcpy(name, file_opt->answer);
	G_free_tokens(map_mapset);
    }
    else
	strcpy(name, file_opt->answer);

    mapset = G_find_file2(elem_opt->answer, name, search_mapset);
    if (mapset) {
	char xname[GNAME_MAX], xmapset[GMAPSET_MAX];
	const char *qchar = n_flag->answer ? "" : "'";
	const char *qual = G_fully_qualified_name(name, mapset);
	G_unqualified_name(name, mapset, xname, xmapset);
	G_file_name(file, elem_opt->answer, name, mapset);
	fprintf(stdout, "name=%s%s%s\n", qchar, xname, qchar);
	fprintf(stdout, "mapset=%s%s%s\n", qchar, xmapset, qchar);
	fprintf(stdout, "fullname=%s%s%s\n", qchar, qual, qchar);
	fprintf(stdout, "file=%s%s%s\n", qchar, file, qchar);

	return EXIT_SUCCESS;
    }
    else {
	fprintf(stdout, "name=\n");
	fprintf(stdout, "mapset=\n");
	fprintf(stdout, "fullname=\n");
	fprintf(stdout, "file=\n");
    }
    
    return EXIT_FAILURE;
}
Пример #23
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct {
	struct Flag *r, *w, *l, *g, *a, *n, *c;
    } flag; 

    struct {
	struct Option *map, *field, *colr, *rast, *volume, *rules,
          *attrcol, *rgbcol, *range, *use;
    } opt;

    int layer;
    int overwrite, remove, is_from_stdin, stat, have_colors, convert, use;
    const char *mapset, *cmapset;
    const char *style, *rules, *cmap, *attrcolumn, *rgbcolumn;
    char *name;
    
    struct Map_info Map;
    struct FPRange range;
    struct Colors colors, colors_tmp;
    /* struct Cell_stats statf; */
    
    G_gisinit(argv[0]);
    
    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("color table"));
    module->description =
	_("Creates/modifies the color table associated with a vector map.");

    opt.map = G_define_standard_option(G_OPT_V_MAP);

    opt.field = G_define_standard_option(G_OPT_V_FIELD);

    opt.use = G_define_option();
    opt.use->key = "use";
    opt.use->type = TYPE_STRING;
    opt.use->required = YES;
    opt.use->multiple = NO;
    opt.use->options = "attr,cat,z";
    opt.use->description = _("Source values");
    G_asprintf((char **) &(opt.use->descriptions),
	       "attr;%s;cat;%s;z;%s",
	       _("read values from attribute table (requires <column> option)"),
	       _("use category values"),
	       _("use z coordinate (3D points or centroids only)"));
    opt.use->answer = "cat";
    
    opt.attrcol = G_define_standard_option(G_OPT_DB_COLUMN);
    opt.attrcol->label = _("Name of column containing numeric data");
    opt.attrcol->description = _("Required for use=attr");
    opt.attrcol->guisection = _("Define");

    opt.range = G_define_option();
    opt.range->key = "range";
    opt.range->type = TYPE_DOUBLE;
    opt.range->required = NO;
    opt.range->label = _("Manually set range (refers to 'column' option)");
    opt.range->description = _("Ignored when 'rules' given");
    opt.range->key_desc = "min,max";

    opt.colr = G_define_standard_option(G_OPT_M_COLR);
    opt.colr->guisection = _("Define");

    opt.rast = G_define_standard_option(G_OPT_R_INPUT);
    opt.rast->key = "raster";
    opt.rast->required = NO;
    opt.rast->description =
        _("Raster map from which to copy color table");
    opt.rast->guisection = _("Define");

    opt.volume = G_define_standard_option(G_OPT_R3_INPUT);
    opt.volume->key = "raster_3d";
    opt.volume->required = NO;
    opt.volume->description =
        _("3D raster map from which to copy color table");
    opt.volume->guisection = _("Define");

    opt.rules = G_define_standard_option(G_OPT_F_INPUT);
    opt.rules->key = "rules";
    opt.rules->required = NO;
    opt.rules->description = _("Path to rules file");
    opt.rules->guisection = _("Define");

    opt.rgbcol = G_define_standard_option(G_OPT_DB_COLUMN);
    opt.rgbcol->key = "rgb_column";
    opt.rgbcol->label = _("Name of color column to populate RGB values");
    opt.rgbcol->description = _("If not given writes color table");
    
    flag.r = G_define_flag();
    flag.r->key = 'r';
    flag.r->description = _("Remove existing color table");
    flag.r->guisection = _("Remove");

    flag.w = G_define_flag();
    flag.w->key = 'w';
    flag.w->description =
        _("Only write new color table if it does not already exist");

    flag.l = G_define_flag();
    flag.l->key = 'l';
    flag.l->description = _("List available rules then exit");
    flag.l->suppress_required = YES;
    flag.l->guisection = _("Print");

    flag.n = G_define_flag();
    flag.n->key = 'n';
    flag.n->description = _("Invert colors");
    flag.n->guisection = _("Define");

    flag.g = G_define_flag();
    flag.g->key = 'g';
    flag.g->description = _("Logarithmic scaling");
    flag.g->guisection = _("Define");

    flag.a = G_define_flag();
    flag.a->key = 'a';
    flag.a->description = _("Logarithmic-absolute scaling");
    flag.a->guisection = _("Define");

    flag.c = G_define_flag();
    flag.c->key = 'c';
    flag.c->label = _("Convert color rules from RGB values to color table");
    flag.c->description = _("Option 'rgb_column' with valid RGB values required");
	
    /* TODO ?
    flag.e = G_define_flag();
    flag.e->key = 'e';
    flag.e->description = _("Histogram equalization");
    flag.e->guisection = _("Define");
    */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    if (flag.l->answer) {
	G_list_color_rules(stdout);
	return EXIT_SUCCESS;
    }

    overwrite = !flag.w->answer;
    remove = flag.r->answer;
    name = opt.map->answer;
    style = opt.colr->answer;
    rules = opt.rules->answer;
    attrcolumn = opt.attrcol->answer;
    rgbcolumn = opt.rgbcol->answer;
    convert = flag.c->answer;
    use = USE_CAT;
    if (opt.use->answer) {
        switch (opt.use->answer[0]) {
        case 'a':
            use = USE_ATTR;
            break;
        case 'c':
            use = USE_CAT;
            break;
        case 'z':
            use = USE_Z;
            break;
        default:
            break;
        }
    }
    G_debug(1, "use=%d", use);
    
    if (!name)
        G_fatal_error(_("No vector map specified"));

    if (use == USE_ATTR && !attrcolumn)
        G_fatal_error(_("Option <%s> required"), opt.attrcol->key); 
    if (use != USE_ATTR && attrcolumn) {
        G_important_message(_("Option <%s> given, assuming <use=attr>..."), opt.attrcol->key);
        use = USE_ATTR;
    }

    if (opt.rast->answer && opt.volume->answer)
        G_fatal_error(_("%s= and %s= are mutually exclusive"),
		      opt.rast->key, opt.volume->key);

    cmap = NULL;
    if (opt.rast->answer)
        cmap = opt.rast->answer;
    if (opt.volume->answer)
        cmap = opt.volume->answer;
    
    if (!cmap && !style && !rules && !remove && !convert)
        G_fatal_error(_("One of -%c, -%c or %s=, %s= or %s= "
			"must be specified"), flag.r->key, flag.c->key, 
		      opt.colr->key, opt.rast->key, opt.rules->key);
    
    if (!!style + !!cmap + !!rules > 1)
        G_fatal_error(_("%s=, %s= and %s= are mutually exclusive"),
			opt.colr->key, opt.rules->key, opt.rast->key);

    if (flag.g->answer && flag.a->answer)
        G_fatal_error(_("-%c and -%c are mutually exclusive"),
		      flag.g->key, flag.a->key);

    if (flag.c->answer && !rgbcolumn) 
	G_fatal_error(_("%s= required for -%c"),
		      opt.rgbcol->key, flag.c->key);

    is_from_stdin = rules && strcmp(rules, "-") == 0;
    if (is_from_stdin)
        G_fatal_error(_("Reading rules from standard input is not implemented yet, please provide path to rules file instead."));

    mapset = G_find_vector(name, "");
    if (!mapset)
	G_fatal_error(_("Vector map <%s> not found"), name);
    
    stat = -1;
    if (remove) {
	stat = Vect_remove_colors(name, mapset);
        if (stat < 0)
            G_fatal_error(_("Unable to remove color table of vector map <%s>"), name);
        if (stat == 0)
            G_warning(_("Color table of vector map <%s> not found"), name);
        return EXIT_SUCCESS;
    }

    G_suppress_warnings(TRUE);
    have_colors = Vect_read_colors(name, mapset, NULL);

    if (have_colors > 0 && !overwrite) {
        G_fatal_error(_("Color table exists. Exiting."));
    }

    G_suppress_warnings(FALSE);

    /* open map and get min/max values */
    Vect_set_open_level(1); /* no topology required */
    if (Vect_open_old2(&Map, name, mapset, opt.field->answer) < 0)
	G_fatal_error(_("Unable to open vector map <%s>"), name);

    Vect_set_error_handler_io(&Map, NULL);
    if (use == USE_Z && !Vect_is_3d(&Map))
        G_fatal_error(_("Vector map <%s> is not 3D"), Vect_get_full_name(&Map));
    
    layer = Vect_get_field_number(&Map, opt.field->answer);
    if (layer < 1)
	G_fatal_error(_("Layer <%s> not found"), opt.field->answer);
    
    if (opt.range->answer) {
	range.min = atof(opt.range->answers[0]);
	range.max = atof(opt.range->answers[1]);
	if (range.min > range.max)
	    G_fatal_error(_("Option <%s>: min must be greater or equal to max"),
			  opt.range->key);
    }

    Rast_init_colors(&colors);
    if (is_from_stdin) {
        G_fatal_error(_("Reading color rules from standard input is currently not supported"));
	/*
        if (!read_color_rules(stdin, &colors, min, max, fp))
            exit(EXIT_FAILURE);
	*/
    } else if (style || rules) {	
	if (style && !G_find_color_rule(style))
	    G_fatal_error(_("Color table <%s> not found"), style);
	
	if (use == USE_CAT) {
	    scan_cats(&Map, layer, style, rules,
		      opt.range->answer ? &range : NULL,
		      &colors);
        }
        else if (use == USE_Z) {
	    scan_z(&Map, layer, style, rules,
		      opt.range->answer ? &range : NULL,
		      &colors);
        }
        else {
	    scan_attr(&Map, layer, attrcolumn, style, rules,
		      opt.range->answer ? &range : NULL,
		      &colors);
	}
    }
    else {
	/* use color from another map (cmap) */
	if (opt.rast->answer) {
            cmapset = G_find_raster2(cmap, "");
            if (!cmapset)
                G_fatal_error(_("Raster map <%s> not found"), cmap);

            if (Rast_read_colors(cmap, cmapset, &colors) < 0)
                G_fatal_error(_("Unable to read color table for raster map <%s>"), cmap);
        } else if (opt.volume->answer) {
            cmapset = G_find_raster3d(cmap, "");
            if (!cmapset)
                G_fatal_error(_("3D raster map <%s> not found"), cmap);

            if (Rast3d_read_colors(cmap, cmapset, &colors) < 0)
                G_fatal_error(_("Unable to read color table for 3D raster map <%s>"), cmap);
        }
    }

    if (flag.n->answer)
        Rast_invert_colors(&colors);

    /* TODO ?
    if (flag.e->answer) {
    if (!have_stats)
    have_stats = get_stats(name, mapset, &statf);
    Rast_histogram_eq_colors(&colors_tmp, &colors, &statf);
    colors = colors_tmp;
    }
    */
    if (flag.g->answer) {
        Rast_log_colors(&colors_tmp, &colors, 100);
        colors = colors_tmp;
    }

    if (flag.a->answer) {
        Rast_abs_log_colors(&colors_tmp, &colors, 100);
        colors = colors_tmp;
    }

    G_important_message(_("Writing color rules..."));
    
    if (style || rules || opt.rast->answer || opt.volume->answer) {
	if (rgbcolumn)
	    write_rgb_values(&Map, layer, rgbcolumn, &colors);
	else
	    Vect_write_colors(name, mapset, &colors);
    }
    
    if (convert) {
	/* convert RGB values to color tables */
	rgb2colr(&Map, layer, rgbcolumn, &colors);
	Vect_write_colors(name, mapset, &colors);
    }
    Vect_close(&Map);
    
    G_message(_("Color table for vector map <%s> set to '%s'"), 
	      G_fully_qualified_name(name, mapset), 
              is_from_stdin || convert ? "rules" : style ? style : rules ? rules :
              cmap);
    
    exit(EXIT_SUCCESS);
}
Пример #24
0
/*!
  \brief Load styles for geolines based on thematic mapping

  \param gv pointer to geovect structure
  \param colors pointer to Colors structure or NULL

  \return number of features defined by thematic mapping
  \return -1 on error
*/
int Gv_load_vect_thematic(geovect *gv, struct Colors *colors)
{
    geoline *gvt;

    struct Map_info Map;
    struct field_info *Fi;
    
    int nvals, cat, nlines, nskipped;
    int red, blu, grn;
    const char *str;
    const char *mapset;

    dbDriver *driver;
    dbValue value;
    
    if(!gv || !gv->tstyle || !gv->filename)
	return -1;

    mapset = G_find_vector2(gv->filename, "");
    if (!mapset) {
	G_fatal_error(_("Vector map <%s> not found"), gv->filename);
    }
    
    Vect_set_open_level(1);
    if (Vect_open_old(&Map, gv->filename, "") == -1) {
	G_fatal_error(_("Unable to open vector map <%s>"),
		      G_fully_qualified_name(gv->filename, mapset));
    }
    
    Fi = Vect_get_field(&Map, gv->tstyle->layer);
    if (!Fi) {
	G_warning(_("Database connection not defined for layer %d"),
		  gv->tstyle->layer);
    }
    else {
      driver = db_start_driver_open_database(Fi->driver, Fi->database);
      if (!driver)
	  G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
			Fi->database, Fi->driver);
    }
    G_message(_("Loading thematic vector layer <%s>..."),
	      G_fully_qualified_name(gv->filename, mapset));
    nlines = nskipped = 0;
    for(gvt = gv->lines; gvt; gvt = gvt->next) {
	gvt->style = (gvstyle *) G_malloc(sizeof(gvstyle));
	G_zero(gvt->style, sizeof(gvstyle));
	
	/* use default style */
	gvt->style->color  = gv->style->color;
	gvt->style->symbol = gv->style->symbol;
	gvt->style->size   = gv->style->size;
	gvt->style->width  = gv->style->width;

	cat = -1;
	if (gvt->cats)
	    Vect_cat_get(gvt->cats, gv->tstyle->layer, &cat);
	if (cat < 0) {
	    nskipped++;
	    continue;
	}
	
	/* color */
	if (colors) {
	    if (!Rast_get_c_color((const CELL *) &cat, &red, &grn, &blu, colors)) {
		G_warning(_("No color rule defined for category %d"), cat);
		gvt->style->color = gv->style->color;
	    }
	    gvt->style->color = (red & RED_MASK) + ((int)((grn) << 8) & GRN_MASK) +
		((int)((blu) << 16) & BLU_MASK);
	}
	
	if (gv->tstyle->color_column) {
	    nvals = db_select_value(driver, Fi->table, Fi->key, cat, gv->tstyle->color_column, &value);
	    if (nvals < 1)
		continue;
	    str = db_get_value_string(&value);
	    if (!str)
		continue;
	    if (G_str_to_color(str, &red, &grn, &blu) != 1) {
		G_warning(_("Invalid color definition (%s)"),
			  str);
		gvt->style->color = gv->style->color;
	    }
	    else {
		gvt->style->color = (red & RED_MASK) + ((int)((grn) << 8) & GRN_MASK) +
		    ((int)((blu) << 16) & BLU_MASK);
	    }
	}
	
	/* width */
	if (gv->tstyle->width_column) {
	    nvals = db_select_value(driver, Fi->table, Fi->key, cat, gv->tstyle->width_column, &value);
	    if (nvals < 1)
		continue;
	    gvt->style->width = db_get_value_int(&value);
	}

	nlines++;
    }

    if (nskipped > 0)
	G_warning(_("%d features without category. "
		    "Unable to determine color rules for features without category."),
		  nskipped);
    
    return nlines;
}
Пример #25
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct
    {
	struct Option *base, *cover, *output;
    } parm;
    char *basemap, *base_mapset;
    char *covermap, *cover_mapset;
    char *outmap;
    char command[1024];
    struct Categories cover_cats;
    FILE *stats_fd, *reclass_fd;
    int first;
    long basecat, covercat, catb, catc;
    double area;
    struct stats stats;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, statistics");
    module->description =
	_("Finds the median of values in a cover map within "
	  "areas assigned the same category value in a "
	  "user-specified base map.");

    parm.base = G_define_standard_option(G_OPT_R_INPUT);
    parm.base->key = "base";
    parm.base->description = _("Name of base raster map");

    parm.cover = G_define_standard_option(G_OPT_R_INPUT);
    parm.cover->key = "cover";
    parm.cover->description = _("Name of cover raster map");

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

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

    basemap = parm.base->answer;
    covermap = parm.cover->answer;
    outmap = parm.output->answer;

    base_mapset = G_find_cell2(basemap, "");
    if (base_mapset == NULL)
	G_fatal_error(_("Base raster map <%s> not found"), basemap);

    cover_mapset = G_find_cell2(covermap, "");
    if (cover_mapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), covermap);
    if (G_legal_filename(outmap) < 0)
	G_fatal_error(_("<%s> is an illegal file name"), outmap);
    if (strcmp(G_mapset(), base_mapset) == 0 && strcmp(basemap, outmap) == 0)
	G_fatal_error(_("Base map and output map <%s> must be different"),
		      outmap);
    if (G_read_cats(covermap, cover_mapset, &cover_cats) < 0)
	G_fatal_error(_("Unable to read category labels of raster map <%s>"),
		      covermap);

    strcpy(command, "r.stats -an \"");
    strcat(command, G_fully_qualified_name(basemap, base_mapset));
    strcat(command, ",");
    strcat(command, G_fully_qualified_name(covermap, cover_mapset));
    strcat(command, "\"");

    /* strcpy (command,"cat /tmp/t"); */
    G_debug(3, "command: %s", command);
    stats_fd = popen(command, "r");

    G_debug(3, "r.reclass i=\"%s\" o=\"%s\"",
	    G_fully_qualified_name(basemap, base_mapset), outmap);
    sprintf(command, "r.reclass i=\"%s\" o=\"%s\"",
	    G_fully_qualified_name(basemap, base_mapset), outmap);

    reclass_fd = popen(command, "w");

    first = 1;
    while (read_stats(stats_fd, &basecat, &covercat, &area)) {
	if (first) {
	    stats.n = 0;
	    stats.nalloc = 16;
	    stats.cat = (long *)
		G_calloc(stats.nalloc, sizeof(long));
	    stats.area = (double *)
		G_calloc(stats.nalloc, sizeof(double));
	    first = 0;
	    catb = basecat;
	}
	if (basecat != catb) {
	    catc = median(&stats);
	    write_reclass(reclass_fd, catb, catc,
			  G_get_cat(catc, &cover_cats));
	    catb = basecat;
	    stats.n = 0;
	}
	stats.n++;
	if (stats.n > stats.nalloc) {
	    stats.nalloc *= 2;
	    stats.cat = (long *)
		G_realloc(stats.cat, stats.nalloc * sizeof(long));
	    stats.area = (double *)
		G_realloc(stats.area, stats.nalloc * sizeof(double));
	}
	stats.cat[stats.n - 1] = covercat;
	stats.area[stats.n - 1] = area;
    }
    if (!first) {
	catc = median(&stats);
	write_reclass(reclass_fd, catb, catc, G_get_cat(catc, &cover_cats));
    }

    pclose(stats_fd);
    pclose(reclass_fd);

    exit(EXIT_SUCCESS);
}
Пример #26
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct
    {
	struct Option *base, *cover, *output;
    } parm;
    char *basemap, *base_mapset;
    char *covermap, *cover_mapset;
    char *outmap;
    char command[1024];
    struct Categories cover_cats;
    FILE *stats, *reclass;
    int first;
    long basecat, covercat, catb, catc;
    double value, max;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, statistics");
    module->description =
	_("Finds the mode of values in a cover map within "
	  "areas assigned the same category value in a "
	  "user-specified base map.");

    parm.base = G_define_option();
    parm.base->key = "base";
    parm.base->description = _("Base map to be reclassified");
    parm.base->required = YES;
    parm.base->type = TYPE_STRING;
    parm.base->gisprompt = "old,cell,raster";

    parm.cover = G_define_option();
    parm.cover->key = "cover";
    parm.cover->description = _("Coverage map");
    parm.cover->required = YES;
    parm.cover->type = TYPE_STRING;
    parm.cover->gisprompt = "old,cell,raster";

    parm.output = G_define_option();
    parm.output->key = "output";
    parm.output->description = _("Output map");
    parm.output->required = YES;
    parm.output->type = TYPE_STRING;
    parm.output->gisprompt = "new,cell,raster";

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

    basemap = parm.base->answer;
    covermap = parm.cover->answer;
    outmap = parm.output->answer;

    base_mapset = G_find_cell2(basemap, "");
    if (base_mapset == NULL) {
	G_fatal_error(_("%s: base raster map not found"), basemap);
    }

    cover_mapset = G_find_cell2(covermap, "");
    if (cover_mapset == NULL) {
	G_fatal_error(_("%s: cover raster map not found"), covermap);
    }
    if (G_legal_filename(outmap) < 0) {
	G_fatal_error(_("<%s> is an illegal file name"), outmap);
    }
    if (strcmp(G_mapset(), base_mapset) == 0 && strcmp(basemap, outmap) == 0) {
	G_fatal_error(_("%s: base map and output map must be different"),
		      outmap);
    }
    if (G_read_cats(covermap, cover_mapset, &cover_cats) < 0) {
	G_fatal_error(_("%s: Unable to read category labels"), covermap);
    }

    strcpy(command, "r.stats -an \"");
    strcat(command, G_fully_qualified_name(basemap, base_mapset));
    strcat(command, ",");
    strcat(command, G_fully_qualified_name(covermap, cover_mapset));
    strcat(command, "\"");

    /* printf(command); */
    stats = popen(command, "r");

    sprintf(command, "r.reclass i=\"%s\" o=\"%s\"",
	    G_fully_qualified_name(basemap, base_mapset), outmap);

    /* printf(command); */
    reclass = popen(command, "w");

    first = 1;
    while (read_stats(stats, &basecat, &covercat, &value)) {
	if (first) {
	    first = 0;
	    catb = basecat;
	    catc = covercat;
	    max = value;
	}
	if (basecat != catb) {
	    write_reclass(reclass, catb, catc, G_get_cat(catc, &cover_cats));
	    catb = basecat;
	    catc = covercat;
	    max = value;
	}
	if (value > max) {
	    catc = covercat;
	    max = value;
	}
    }
    if (first) {
	catb = catc = 0;
    }
    write_reclass(reclass, catb, catc, G_get_cat(catc, &cover_cats));

    pclose(stats);
    pclose(reclass);

    exit(0);
}
Пример #27
0
int read_input_map(char *input, char *mapset, int ZEROFLAG)
{
    int fd;
    int row;
    int hit;
    register int col;
    register CELL *cell;
    register MAPTYPE *ptr;

    map = (MAPTYPE *) G_malloc((size_t) window.rows * window.cols * sizeof(MAPTYPE));

    fd = Rast_open_old(input, mapset);

    cell = Rast_allocate_c_buf();

    ptr = map;

    minrow = -1;
    maxrow = -1;
    mincol = window.cols;
    maxcol = 0;

    G_message(_("Reading input raster map <%s>..."),
	      G_fully_qualified_name(input, mapset));

    count_rows_with_data = 0;

    for (row = 0; row < window.rows; row++) {
	hit = 0;
	G_percent(row, window.rows, 2);

	Rast_get_c_row(fd, cell, row);

	for (col = 0; col < window.cols; col++) {
	    if (ZEROFLAG) {
		if ((*ptr++ = (*cell++ != 0))) {
		    if (minrow < 0)
			minrow = row;
		    maxrow = row;
		    if (col < mincol)
			mincol = col;
		    if (col > maxcol)
			maxcol = col;
		    if (!hit) {
			count_rows_with_data++;
			hit = 1;
		    }
		}
	    }
	    else {		/* use NULL */

		if ((*ptr++ = !Rast_is_c_null_value(cell++))) {
		    if (minrow < 0)
			minrow = row;
		    maxrow = row;
		    if (col < mincol)
			mincol = col;
		    if (col > maxcol)
			maxcol = col;
		    if (!hit) {
			count_rows_with_data++;
			hit = 1;
		    }
		}
	    }
	}
	cell -= window.cols;
    }
    G_percent(row, window.rows, 2);
    Rast_close(fd);
    G_free(cell);

    return 0;
}
Пример #28
0
int main(int argc, char **argv)
{
    char *mapset;
    int ret, level;
    int i, stat = 0, type, display;
    int chcat = 0;
    int r, g, b;
    int has_color, has_fcolor;
    struct color_rgb color, fcolor;
    double size;
    int default_width;
    double width_scale;
    int verbose = FALSE;
    double minreg, maxreg, reg;
    char map_name[128];
    struct GModule *module;
    struct Option *map_opt;
    struct Option *color_opt, *fcolor_opt, *rgbcol_opt, *zcol_opt;
    struct Option *type_opt, *display_opt;
    struct Option *icon_opt, *size_opt, *sizecolumn_opt, *rotcolumn_opt;
    struct Option *where_opt;
    struct Option *field_opt, *cat_opt, *lfield_opt;
    struct Option *lcolor_opt, *bgcolor_opt, *bcolor_opt;
    struct Option *lsize_opt, *font_opt, *xref_opt, *yref_opt;
    struct Option *attrcol_opt, *maxreg_opt, *minreg_opt;
    struct Option *width_opt, *wcolumn_opt, *wscale_opt;
    struct Option *render_opt;
    struct Flag *verbose_flag;	/* please remove before GRASS 7 released */
    struct Flag *id_flag, *table_acolors_flag, *cats_acolors_flag, *x_flag,
	*zcol_flag;
    struct cat_list *Clist;
    int *cats, ncat;
    LATTR lattr;
    struct Map_info Map;
    struct field_info *fi;
    dbDriver *driver;
    dbHandle handle;
    struct Cell_head window;
    BOUND_BOX box;
    double overlap;

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

    module = G_define_module();
    module->keywords = _("display, vector");
    module->description = _("Displays user-specified vector map "
			    "in the active graphics frame.");
    
    map_opt = G_define_standard_option(G_OPT_V_MAP);

    display_opt = G_define_option();
    display_opt->key = "display";
    display_opt->type = TYPE_STRING;
    display_opt->required = YES;
    display_opt->multiple = YES;
    display_opt->answer = "shape";
    display_opt->options = "shape,cat,topo,dir,attr,zcoor";
    display_opt->description = _("Display");
    display_opt->descriptions = _("shape;Display geometry of features;"
				  "cat;Display category numbers of features;"
				  "topo;Display topology information (nodes, edges);"
				  "dir;Display direction of linear features;"
				  "attr;Display selected attribute based on 'attrcol';"
				  "zcoor;Display z-coordinate of features (only for 3D vector maps)");
    
    /* Query */
    type_opt = G_define_standard_option(G_OPT_V_TYPE);
    type_opt->answer = "point,line,boundary,centroid,area,face";
    type_opt->options = "point,line,boundary,centroid,area,face";
    type_opt->guisection = _("Selection");

    field_opt = G_define_standard_option(G_OPT_V_FIELD);
    field_opt->label =
	_("Layer number (if -1, all layers are displayed)");
    field_opt->gisprompt = "old_layer,layer,layer_all";
    field_opt->guisection = _("Selection");

    cat_opt = G_define_standard_option(G_OPT_V_CATS);
    cat_opt->guisection = _("Selection");

    where_opt = G_define_standard_option(G_OPT_WHERE);
    where_opt->guisection = _("Selection");

    /* Colors */
    color_opt = G_define_option();
    color_opt->key = "color";
    color_opt->type = TYPE_STRING;
    color_opt->answer = DEFAULT_FG_COLOR;
    color_opt->label = _("Feature color");
    color_opt->guisection = _("Colors");
    color_opt->gisprompt = "old_color,color,color_none";
    color_opt->description =
	_("Either a standard GRASS color, R:G:B triplet, or \"none\"");

    fcolor_opt = G_define_option();
    fcolor_opt->key = "fcolor";
    fcolor_opt->type = TYPE_STRING;
    fcolor_opt->answer = "200:200:200";
    fcolor_opt->label = _("Area fill color");
    fcolor_opt->guisection = _("Colors");
    fcolor_opt->gisprompt = "old_color,color,color_none";
    fcolor_opt->description =
	_("Either a standard GRASS color, R:G:B triplet, or \"none\"");

    rgbcol_opt = G_define_standard_option(G_OPT_COLUMN);
    rgbcol_opt->key = "rgb_column";
    rgbcol_opt->guisection = _("Colors");
    rgbcol_opt->description = _("Name of color definition column (for use with -a flag)");
    rgbcol_opt->answer = "GRASSRGB";

    zcol_opt = G_define_option();
    zcol_opt->key = "zcolor";
    zcol_opt->key_desc = "style";
    zcol_opt->type = TYPE_STRING;
    zcol_opt->required = NO;
    zcol_opt->description = _("Type of color table (for use with -z flag)");
    zcol_opt->answer = "terrain";
    zcol_opt->guisection = _("Colors");

    /* Lines */
    width_opt = G_define_option();
    width_opt->key = "width";
    width_opt->type = TYPE_INTEGER;
    width_opt->answer = "0";
    width_opt->guisection = _("Lines");
    width_opt->description = _("Line width");

    wcolumn_opt = G_define_standard_option(G_OPT_COLUMN);
    wcolumn_opt->key = "wcolumn";
    wcolumn_opt->guisection = _("Lines");
    wcolumn_opt->description =
	_("Name of column for line widths (these values will be scaled by wscale)");

    wscale_opt = G_define_option();
    wscale_opt->key = "wscale";
    wscale_opt->type = TYPE_DOUBLE;
    wscale_opt->answer = "1";
    wscale_opt->guisection = _("Lines");
    wscale_opt->description = _("Scale factor for wcolumn");

    /* Symbols */
    icon_opt = G_define_option();
    icon_opt->key = "icon";
    icon_opt->type = TYPE_STRING;
    icon_opt->required = NO;
    icon_opt->multiple = NO;
    icon_opt->guisection = _("Symbols");
    icon_opt->answer = "basic/x";
    /* This could also use ->gisprompt = "old,symbol,symbol" instead of ->options */
    icon_opt->options = icon_files();
    icon_opt->description = _("Point and centroid symbol");

    size_opt = G_define_option();
    size_opt->key = "size";
    size_opt->type = TYPE_DOUBLE;
    size_opt->answer = "5";
    size_opt->guisection = _("Symbols");
    size_opt->label = _("Symbol size");
    size_opt->description =
	_("When used with the size_column option this becomes the scale factor");

    sizecolumn_opt = G_define_standard_option(G_OPT_COLUMN);
    sizecolumn_opt->key = "size_column";
    sizecolumn_opt->guisection = _("Symbols");
    sizecolumn_opt->description =
	_("Name of numeric column containing symbol size");

    rotcolumn_opt = G_define_standard_option(G_OPT_COLUMN);
    rotcolumn_opt->key = "rot_column";
    rotcolumn_opt->guisection = _("Symbols");
    rotcolumn_opt->label =
	_("Name of numeric column containing symbol rotation angle");
    rotcolumn_opt->description =
	_("Measured in degrees CCW from east");

    /* Labels */
    lfield_opt = G_define_standard_option(G_OPT_V_FIELD);
    lfield_opt->key = "llayer";
    lfield_opt->guisection = _("Labels");
    lfield_opt->description =
	_("Layer number for labels (default: the given layer number)");

    attrcol_opt = G_define_standard_option(G_OPT_COLUMN);
    attrcol_opt->key = "attrcol";
    attrcol_opt->multiple = NO;	/* or fix attr.c, around line 102 */
    attrcol_opt->guisection = _("Labels");
    attrcol_opt->description = _("Name of column to be displayed");

    lcolor_opt = G_define_option();
    lcolor_opt->key = "lcolor";
    lcolor_opt->type = TYPE_STRING;
    lcolor_opt->answer = "red";
    lcolor_opt->label = _("Label color");
    lcolor_opt->guisection = _("Labels");
    lcolor_opt->gisprompt = "old_color,color,color";
    lcolor_opt->description = _("Either a standard color name or R:G:B triplet");

    bgcolor_opt = G_define_option();
    bgcolor_opt->key = "bgcolor";
    bgcolor_opt->type = TYPE_STRING;
    bgcolor_opt->answer = "none";
    bgcolor_opt->guisection = _("Labels");
    bgcolor_opt->label = _("Label background color");
    bgcolor_opt->gisprompt = "old_color,color,color_none";
    bgcolor_opt->description =
	_("Either a standard GRASS color, R:G:B triplet, or \"none\"");

    bcolor_opt = G_define_option();
    bcolor_opt->key = "bcolor";
    bcolor_opt->type = TYPE_STRING;
    bcolor_opt->answer = "none";
    bcolor_opt->guisection = _("Labels");
    bcolor_opt->label = _("Label border color");
    bcolor_opt->gisprompt = "old_color,color,color_none";
    bcolor_opt->description =
	_("Either a standard GRASS color, R:G:B triplet, or \"none\"");

    lsize_opt = G_define_option();
    lsize_opt->key = "lsize";
    lsize_opt->type = TYPE_INTEGER;
    lsize_opt->answer = "8";
    lsize_opt->guisection = _("Labels");
    lsize_opt->description = _("Label size (pixels)");

    font_opt = G_define_option();
    font_opt->key = "font";
    font_opt->type = TYPE_STRING;
    font_opt->guisection = _("Labels");
    font_opt->description = _("Font name");

    xref_opt = G_define_option();
    xref_opt->key = "xref";
    xref_opt->type = TYPE_STRING;
    xref_opt->guisection = _("Labels");
    xref_opt->answer = "left";
    xref_opt->options = "left,center,right";
    xref_opt->description = _("Label horizontal justification");

    yref_opt = G_define_option();
    yref_opt->key = "yref";
    yref_opt->type = TYPE_STRING;
    yref_opt->guisection = _("Labels");
    yref_opt->answer = "center";
    yref_opt->options = "top,center,bottom";
    yref_opt->description = _("Label vertical justification");

    minreg_opt = G_define_option();
    minreg_opt->key = "minreg";
    minreg_opt->type = TYPE_DOUBLE;
    minreg_opt->required = NO;
    minreg_opt->description =
	_("Minimum region size (average from height and width) "
	  "when map is displayed");

    maxreg_opt = G_define_option();
    maxreg_opt->key = "maxreg";
    maxreg_opt->type = TYPE_DOUBLE;
    maxreg_opt->required = NO;
    maxreg_opt->description =
	_("Maximum region size (average from height and width) "
	  "when map is displayed");

    render_opt = G_define_option();
    render_opt->key = "render";
    render_opt->type = TYPE_STRING;
    render_opt->required = NO;
    render_opt->multiple = NO;
    render_opt->answer = "c";
    render_opt->options = "g,r,d,c,l";
    render_opt->description = _("Rendering method for filled polygons");
    render_opt->descriptions =
	_("g;use the libgis render functions (features: clipping);"
	  "r;use the raster graphics library functions (features: polylines);"
	  "d;use the display library basic functions (features: polylines);"
	  "c;use the display library clipping functions (features: clipping);"
	  "l;use the display library culling functions (features: culling, polylines)");

    /* please remove before GRASS 7 released */
    verbose_flag = G_define_flag();
    verbose_flag->key = 'v';
    verbose_flag->description = _("Run verbosely");

    /* Colors */
    table_acolors_flag = G_define_flag();
    table_acolors_flag->key = 'a';
    table_acolors_flag->guisection = _("Colors");
    table_acolors_flag->description =
	_("Get colors from map table column (of form RRR:GGG:BBB)");

    cats_acolors_flag = G_define_flag();
    cats_acolors_flag->key = 'c';
    cats_acolors_flag->guisection = _("Colors");
    cats_acolors_flag->description =
	_("Random colors according to category number "
	  "(or layer number if 'layer=-1' is given)");

    /* Query */
    id_flag = G_define_flag();
    id_flag->key = 'i';
    id_flag->guisection = _("Selection");
    id_flag->description = _("Use values from 'cats' option as feature id");

    x_flag = G_define_flag();
    x_flag->key = 'x';
    x_flag->description =
	_("Don't add to list of vectors and commands in monitor "
	  "(it won't be drawn if the monitor is refreshed)");

    zcol_flag = G_define_flag();
    zcol_flag->key = 'z';
    zcol_flag->description = _("Colorize polygons according to z height");
    zcol_flag->guisection = _("Colors");

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

    if (G_strcasecmp(render_opt->answer, "g") == 0)
	render = RENDER_GPP;
    else if (G_strcasecmp(render_opt->answer, "r") == 0)
	render = RENDER_RPA;
    else if (G_strcasecmp(render_opt->answer, "d") == 0)
	render = RENDER_DP;
    else if (G_strcasecmp(render_opt->answer, "c") == 0)
	render = RENDER_DPC;
    else if (G_strcasecmp(render_opt->answer, "l") == 0)
	render = RENDER_DPL;
    else
	render = RENDER_GPP;

    /* please remove -v flag before GRASS 7 released */
    if (verbose_flag->answer) {
	G_putenv("GRASS_VERBOSE", "3");
	G_warning(_("The '-v' flag is superseded and will be removed "
		    "in future. Please use '--verbose' instead."));
    }
    /* but keep this */
    if (G_verbose() > G_verbose_std())
	verbose = TRUE;

    G_get_set_window(&window);

    if (R_open_driver() != 0)
	G_fatal_error(_("No graphics device selected"));

    /* Read map options */

    /* Check min/max region */
    reg = ((window.east - window.west) + (window.north - window.south)) / 2;
    if (minreg_opt->answer) {
	minreg = atof(minreg_opt->answer);

	if (reg < minreg) {
	    G_message(_("Region size is lower than minreg, nothing displayed."));
	    D_add_to_list(G_recreate_command());
	    exit(EXIT_SUCCESS);
	}
    }
    if (maxreg_opt->answer) {
	maxreg = atof(maxreg_opt->answer);

	if (reg > maxreg) {
	    G_message(_("Region size is greater than maxreg, nothing displayed."));
	    D_add_to_list(G_recreate_command());
	    exit(EXIT_SUCCESS);
	}
    }

    G_strcpy(map_name, map_opt->answer);

    default_width = atoi(width_opt->answer);
    if (default_width < 0)
	default_width = 0;
    width_scale = atof(wscale_opt->answer);

    if (table_acolors_flag->answer && cats_acolors_flag->answer) {
	cats_acolors_flag->answer = '\0';
	G_warning(_("The '-c' and '-a' flags cannot be used together, "
		    "the '-c' flag will be ignored!"));
    }

    color = G_standard_color_rgb(WHITE);
    ret = G_str_to_color(color_opt->answer, &r, &g, &b);
    if (ret == 1) {
	has_color = 1;
	color.r = r;
	color.g = g;
	color.b = b;
    }
    else if (ret == 2) {	/* none */
	has_color = 0;
    }
    else if (ret == 0) {	/* error */
	G_fatal_error(_("Unknown color: [%s]"), color_opt->answer);
    }

    fcolor = G_standard_color_rgb(WHITE);
    ret = G_str_to_color(fcolor_opt->answer, &r, &g, &b);
    if (ret == 1) {
	has_fcolor = 1;
	fcolor.r = r;
	fcolor.g = g;
	fcolor.b = b;
    }
    else if (ret == 2) {	/* none */
	has_fcolor = 0;
    }
    else if (ret == 0) {	/* error */
	G_fatal_error(_("Unknown color: '%s'"), fcolor_opt->answer);
    }

    size = atof(size_opt->answer);

    /* Make sure map is available */
    mapset = G_find_vector2(map_name, "");

    if (mapset == NULL)
	G_fatal_error(_("Vector map <%s> not found"), map_name);

    /* if where_opt was specified select categories from db 
     * otherwise parse cat_opt */
    Clist = Vect_new_cat_list();
    Clist->field = atoi(field_opt->answer);

    /* open vector */
    level = Vect_open_old(&Map, map_name, mapset);

    if (where_opt->answer) {
	if (Clist->field < 1)
	    G_fatal_error(_("'layer' must be > 0 for 'where'."));
	chcat = 1;
	if ((fi = Vect_get_field(&Map, Clist->field)) == NULL)
	    G_fatal_error(_("Database connection not defined"));
	if (fi != NULL) {
	    driver = db_start_driver(fi->driver);
	    if (driver == NULL)
		G_fatal_error(_("Unable to start driver <%s>"), fi->driver);

	    db_init_handle(&handle);
	    db_set_handle(&handle, fi->database, NULL);
	    if (db_open_database(driver, &handle) != DB_OK)
		G_fatal_error(_("Unable to open database <%s>"),
			      fi->database);

	    ncat =
		db_select_int(driver, fi->table, fi->key, where_opt->answer,
			      &cats);

	    db_close_database(driver);
	    db_shutdown_driver(driver);

	    Vect_array_to_cat_list(cats, ncat, Clist);
	}
    }
    else if (cat_opt->answer) {
	if (Clist->field < 1)
	    G_fatal_error(_("'layer' must be > 0 for 'cats'."));
	chcat = 1;
	ret = Vect_str_to_cat_list(cat_opt->answer, Clist);
	if (ret > 0)
	    G_warning(_("%d errors in cat option"), ret);
    }

    type = Vect_option_to_types(type_opt); 

    i = 0;
    display = 0;
    while (display_opt->answers[i]) {
	switch (display_opt->answers[i][0]) {
	case 's':
	    display |= DISP_SHAPE;
	    break;
	case 'c':
	    display |= DISP_CAT;
	    break;
	case 't':
	    display |= DISP_TOPO;
	    break;
	case 'd':
	    display |= DISP_DIR;
	    break;
	case 'a':
	    display |= DISP_ATTR;
	    break;
	case 'z':
	    display |= DISP_ZCOOR;
	    break;
	}
	i++;
    }

    /* Read label options */
    if (lfield_opt->answer != NULL)
	lattr.field = atoi(lfield_opt->answer);
    else
	lattr.field = Clist->field;

    lattr.color.R = lattr.color.G = lattr.color.B = 255;
    if (G_str_to_color(lcolor_opt->answer, &r, &g, &b)) {
	lattr.color.R = r;
	lattr.color.G = g;
	lattr.color.B = b;
    }
    lattr.has_bgcolor = 0;
    if (G_str_to_color(bgcolor_opt->answer, &r, &g, &b) == 1) {
	lattr.has_bgcolor = 1;
	lattr.bgcolor.R = r;
	lattr.bgcolor.G = g;
	lattr.bgcolor.B = b;
    }
    lattr.has_bcolor = 0;
    if (G_str_to_color(bcolor_opt->answer, &r, &g, &b) == 1) {
	lattr.has_bcolor = 1;
	lattr.bcolor.R = r;
	lattr.bcolor.G = g;
	lattr.bcolor.B = b;
    }

    lattr.size = atoi(lsize_opt->answer);
    lattr.font = font_opt->answer;
    switch (xref_opt->answer[0]) {
    case 'l':
	lattr.xref = LLEFT;
	break;
    case 'c':
	lattr.xref = LCENTER;
	break;
    case 'r':
	lattr.xref = LRIGHT;
	break;
    }
    switch (yref_opt->answer[0]) {
    case 't':
	lattr.yref = LTOP;
	break;
    case 'c':
	lattr.yref = LCENTER;
	break;
    case 'b':
	lattr.yref = LBOTTOM;
	break;
    }

    D_setup(0);

    G_setup_plot(D_get_d_north(), D_get_d_south(),
		 D_get_d_west(), D_get_d_east(), D_move_abs, D_cont_abs);

    if (verbose)
	G_message(_("Plotting ..."));

    if (level >= 2)
	Vect_get_map_box(&Map, &box);

    if (level >= 2 && (window.north < box.S || window.south > box.N ||
		       window.east < box.W ||
		       window.west > G_adjust_easting(box.E, &window))) {
	G_message(_("The bounding box of the map is outside the current region, "
		   "nothing drawn."));
	stat = 0;
    }
    else {
	overlap =
	    G_window_percentage_overlap(&window, box.N, box.S, box.E, box.W);
	G_debug(1, "overlap = %f \n", overlap);
	if (overlap < 1)
	    Vect_set_constraint_region(&Map, window.north, window.south,
				       window.east, window.west,
				       PORT_DOUBLE_MAX, -PORT_DOUBLE_MAX);

	/* default line width */
	if (!wcolumn_opt->answer)
	    D_line_width(default_width);

	if (type & GV_AREA) {
	    if (level >= 2) {
		if (display & DISP_SHAPE) {
		    stat = darea(&Map, Clist,
				 has_color ? &color : NULL,
				 has_fcolor ? &fcolor : NULL, chcat,
				 (int)id_flag->answer,
				 table_acolors_flag->answer,
				 cats_acolors_flag->answer, &window,
				 rgbcol_opt->answer, default_width,
				 wcolumn_opt->answer, width_scale,
				 zcol_flag->answer, zcol_opt->answer);
		}
		if (wcolumn_opt->answer)
		    D_line_width(default_width);
	    }
	    else
		G_warning(_("Unable to display areas, topology not available"));
	}

	if (display & DISP_SHAPE) {
	    if (id_flag->answer && level < 2) {
		G_warning(_("Unable to display lines by id, topology not available"));
	    }
	    else {
		stat = plot1(&Map, type, Clist,
			     has_color ? &color : NULL,
			     has_fcolor ? &fcolor : NULL, chcat, icon_opt->answer,
			     size, sizecolumn_opt->answer, rotcolumn_opt->answer,
			     (int)id_flag->answer, table_acolors_flag->answer,
			     cats_acolors_flag->answer, rgbcol_opt->answer,
			     default_width, wcolumn_opt->answer, width_scale,
			     zcol_flag->answer, zcol_opt->answer);
		if (wcolumn_opt->answer)
		    D_line_width(default_width);
	    }
	}

	if (has_color) {
	    R_RGB_color(color.r, color.g, color.b);
	    if (display & DISP_DIR)
                stat = dir(&Map, type, Clist, chcat, size);
	}

	/* reset line width: Do we need to get line width from display
	 * driver (not implemented)?  It will help restore previous line
	 * width (not just 0) determined by another module (e.g.,
	 * d.linewidth). */
	if (!wcolumn_opt->answer)
	    R_line_width(0);

	if (display & DISP_CAT)
	    stat = label(&Map, type, Clist, &lattr, chcat);

	if (display & DISP_ATTR)
	    stat =
		attr(&Map, type, attrcol_opt->answer, Clist, &lattr, chcat);

	if (display & DISP_ZCOOR)
	    stat = zcoor(&Map, type, &lattr);

	if (display & DISP_TOPO) {
	    if (level >= 2)
		stat = topo(&Map, type, &lattr);
	    else
		G_warning(_("Unable to display topology, not available"));
	}
    }

    if (!x_flag->answer) {
	D_add_to_list(G_recreate_command());

	D_set_dig_name(G_fully_qualified_name(map_name, mapset));
	D_add_to_dig_list(G_fully_qualified_name(map_name, mapset));
    }

    R_close_driver();

    if (verbose)
	G_done_msg(" ");

    Vect_close(&Map);
    Vect_destroy_cat_list(Clist);

    exit(stat);
}