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; }
int open_map(MAPS* rast) { int row, col; int fd; char* mapset; struct Cell_head cellhd; int bufsize; void* tmp_buf; mapset = (char*)G_find_raster2(rast->elevname, ""); if (mapset == NULL) G_fatal_error(_("Raster map <%s> not found"), rast->elevname); rast->fd = Rast_open_old(rast->elevname, mapset); Rast_get_cellhd(rast->elevname, mapset, &cellhd); rast->raster_type = Rast_map_type(rast->elevname, mapset); if (window.ew_res < cellhd.ew_res || window.ns_res < cellhd.ns_res) G_warning(_("Region resolution shoudn't be lesser than map %s resolution. Run g.region rast=%s to set proper resolution"), rast->elevname, rast->elevname); tmp_buf=Rast_allocate_buf(rast->raster_type); rast->elev = (FCELL**) G_malloc((row_buffer_size+1) * sizeof(FCELL*)); for (row = 0; row < row_buffer_size+1; ++row) { rast->elev[row] = Rast_allocate_buf(FCELL_TYPE); Rast_get_row(rast->fd, tmp_buf,row, rast->raster_type); for (col=0;col<ncols;++col) get_cell(col, rast->elev[row], tmp_buf, rast->raster_type); } /* end elev */ G_free(tmp_buf); return 0; }
/*! \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; }
/*! \brief Build color table (256) Calling function must have already allocated space in buff for range of data (256 for now) - simply calls get_color for each cat in color range \param filename raster map name \param[out] buff data buffer \return 1 on success \return 0 on failure */ int Gs_build_256lookup(const char *filename, int *buff) { const char *mapset; struct Colors colrules; CELL min, max, cats[256]; int i; unsigned char r[256], g[256], b[256], set[256]; G_debug(3, "building color table"); mapset = G_find_raster2(filename, ""); if (!mapset) { G_warning(_("Raster map <%s> not found"), filename); return 0; } Rast_read_colors(filename, mapset, &colrules); Rast_get_c_color_range(&min, &max, &colrules); if (min < 0 || max > 255) { G_warning(_("Color table range doesn't match data (mincol=%d, maxcol=%d"), min, max); min = min < 0 ? 0 : min; max = max > 255 ? 255 : max; } G_zero(cats, 256 * sizeof(CELL)); for (i = min; i <= max; i++) { cats[i] = i; } Rast_lookup_c_colors(cats, r, g, b, set, 256, &colrules); for (i = 0; i < 256; i++) { if (set[i]) { buff[i] = (r[i] & 0xff) | ((g[i] & 0xff) << 8) | ((b[i] & 0xff) << 16); } else { buff[i] = NO_DATA_COL; } } return (1); }
/*! \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); }
/*! \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); }
int parse_layer(char *s) { char name[GNAME_MAX]; const char *mapset; struct FPRange fp_range; int n; strcpy(name, s); mapset = G_find_raster2(name, ""); if (mapset == NULL) G_fatal_error(_("Raster map <%s> not found"), s); n = nlayers++; layers = (LAYER *) G_realloc(layers, nlayers * sizeof(LAYER)); is_fp = (int *)G_realloc(is_fp, (nlayers + 1) * sizeof(int)); DMAX = (DCELL *) G_realloc(DMAX, (nlayers + 1) * sizeof(DCELL)); DMIN = (DCELL *) G_realloc(DMIN, (nlayers + 1) * sizeof(DCELL)); if (!as_int) is_fp[n] = Rast_map_is_fp(name, mapset); else is_fp[n] = 0; if (is_fp[n]) { if (Rast_read_fp_range(name, mapset, &fp_range) < 0) G_fatal_error(_("Unable to read fp range for raster map <%s>"), name); Rast_get_fp_range_min_max(&fp_range, &DMIN[n], &DMAX[n]); } layers[n].name = G_store(name); layers[n].mapset = mapset; if (Rast_read_cats(name, mapset, &layers[n].labels) < 0) G_fatal_error(_("Unable to read category file of raster map <%s@%s>"), name, mapset); return 0; }
int main(int argc, char *argv[]) { /* variables */ DCELL *data_buf; CELL *clump_buf; CELL i, max; int row, col, rows, cols; int out_mode, use_MASK, *n, *e; long int *count; int fd_data, fd_clump; const char *datamap, *clumpmap, *centroidsmap; double avg, vol, total_vol, east, north, *sum; struct Cell_head window; struct Map_info *fd_centroids; struct line_pnts *Points; struct line_cats *Cats; struct field_info *Fi; char buf[DB_SQL_MAX]; dbString sql; dbDriver *driver; struct GModule *module; struct { struct Option *input, *clump, *centroids, *output; } opt; struct { struct Flag *report; } flag; /* define parameters and flags */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("volume")); G_add_keyword(_("clumps")); module->label = _("Calculates the volume of data \"clumps\"."); module->description = _("Optionally produces a GRASS vector points map " "containing the calculated centroids of these clumps."); opt.input = G_define_standard_option(G_OPT_R_INPUT); opt.input->description = _("Name of input raster map representing data that will be summed within clumps"); opt.clump = G_define_standard_option(G_OPT_R_INPUT); opt.clump->key = "clump"; opt.clump->required = NO; opt.clump->label = _("Name of input clump raster map"); opt.clump->description = _("Preferably the output of r.clump. " "If no clump map is given than MASK is used."); opt.centroids = G_define_standard_option(G_OPT_V_OUTPUT); opt.centroids->key = "centroids"; opt.centroids->required = NO; opt.centroids->description = _("Name for output vector points map to contain clump centroids"); opt.output = G_define_standard_option(G_OPT_F_OUTPUT); opt.output->required = NO; opt.output->label = _("Name for output file to hold the report"); opt.output->description = _("If no output file given report is printed to standard output"); flag.report = G_define_flag(); flag.report->key = 'f'; flag.report->description = _("Generate unformatted report (items separated by colon)"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get arguments */ datamap = opt.input->answer; clumpmap = NULL; if (opt.clump->answer) clumpmap = opt.clump->answer; centroidsmap = NULL; fd_centroids = NULL; Points = NULL; Cats = NULL; driver = NULL; if (opt.centroids->answer) { centroidsmap = opt.centroids->answer; fd_centroids = G_malloc(sizeof(struct Map_info)); } out_mode = (!flag.report->answer); /* * see if MASK or a separate "clumpmap" raster map is to be used * -- it must(!) be one of those two choices. */ use_MASK = 0; if (!clumpmap) { clumpmap = "MASK"; use_MASK = 1; if (!G_find_raster2(clumpmap, G_mapset())) G_fatal_error(_("No MASK found. If no clump map is given than the MASK is required. " "You need to define a clump raster map or create a MASK by r.mask command.")); G_important_message(_("No clump map given, using MASK")); } /* open input and clump raster maps */ fd_data = Rast_open_old(datamap, ""); fd_clump = Rast_open_old(clumpmap, use_MASK ? G_mapset() : ""); /* initialize vector map (for centroids) if needed */ if (centroidsmap) { if (Vect_open_new(fd_centroids, centroidsmap, WITHOUT_Z) < 0) G_fatal_error(_("Unable to create vector map <%s>"), centroidsmap); Points = Vect_new_line_struct(); Cats = Vect_new_cats_struct(); /* initialize data structures */ Vect_append_point(Points, 0., 0., 0.); Vect_cat_set(Cats, 1, 1); } /* initialize output file */ if (opt.output->answer && strcmp(opt.output->answer, "-") != 0) { if (freopen(opt.output->answer, "w", stdout) == NULL) { perror(opt.output->answer); exit(EXIT_FAILURE); } } /* initialize data accumulation arrays */ max = Rast_get_max_c_cat(clumpmap, use_MASK ? G_mapset() : ""); sum = (double *)G_malloc((max + 1) * sizeof(double)); count = (long int *)G_malloc((max + 1) * sizeof(long int)); G_zero(sum, (max + 1) * sizeof(double)); G_zero(count, (max + 1) * sizeof(long int)); data_buf = Rast_allocate_d_buf(); clump_buf = Rast_allocate_c_buf(); /* get window size */ G_get_window(&window); rows = window.rows; cols = window.cols; /* now get the data -- first pass */ for (row = 0; row < rows; row++) { G_percent(row, rows, 2); Rast_get_d_row(fd_data, data_buf, row); Rast_get_c_row(fd_clump, clump_buf, row); for (col = 0; col < cols; col++) { i = clump_buf[col]; if (i > max) G_fatal_error(_("Invalid category value %d (max=%d): row=%d col=%d"), i, max, row, col); if (i < 1) { G_debug(3, "row=%d col=%d: zero or negs ignored", row, col); continue; /* ignore zeros and negs */ } if (Rast_is_d_null_value(&data_buf[col])) { G_debug(3, "row=%d col=%d: NULL ignored", row, col); continue; } sum[i] += data_buf[col]; count[i]++; } } G_percent(1, 1, 1); /* free some buffer space */ G_free(data_buf); G_free(clump_buf); /* data lists for centroids of clumps */ e = (int *)G_malloc((max + 1) * sizeof(int)); n = (int *)G_malloc((max + 1) * sizeof(int)); i = centroids(fd_clump, e, n, 1, max); /* close raster maps */ Rast_close(fd_data); Rast_close(fd_clump); /* got everything, now do output */ if (centroidsmap) { G_message(_("Creating vector point map <%s>..."), centroidsmap); /* set comment */ sprintf(buf, _("From '%s' on raster map <%s> using clumps from <%s>"), argv[0], datamap, clumpmap); Vect_set_comment(fd_centroids, buf); /* create attribute table */ Fi = Vect_default_field_info(fd_centroids, 1, NULL, GV_1TABLE); driver = db_start_driver_open_database(Fi->driver, Vect_subst_var(Fi->database, fd_centroids)); if (driver == NULL) { G_fatal_error(_("Unable to open database <%s> by driver <%s>"), Vect_subst_var(Fi->database, fd_centroids), Fi->driver); } db_set_error_handler_driver(driver); db_begin_transaction(driver); db_init_string(&sql); sprintf(buf, "create table %s (cat integer, volume double precision, " "average double precision, sum double precision, count integer)", Fi->table); db_set_string(&sql, buf); Vect_map_add_dblink(fd_centroids, 1, NULL, Fi->table, GV_KEY_COLUMN, Fi->database, Fi->driver); G_debug(3, "%s", db_get_string(&sql)); if (db_execute_immediate(driver, &sql) != DB_OK) { G_fatal_error(_("Unable to create table: %s"), db_get_string(&sql)); } } /* print header */ if (out_mode) { fprintf(stdout, _("\nVolume report on data from <%s> using clumps on <%s> raster map"), datamap, clumpmap); fprintf(stdout, "\n\n"); fprintf(stdout, _("Category Average Data # Cells Centroid Total\n")); fprintf(stdout, _("Number in clump Total in clump Easting Northing Volume")); fprintf(stdout, "\n%s\n", SEP); } total_vol = 0.0; /* print output, write centroids */ for (i = 1; i <= max; i++) { if (count[i]) { avg = sum[i] / (double)count[i]; vol = sum[i] * window.ew_res * window.ns_res; total_vol += vol; east = window.west + (e[i] + 0.5) * window.ew_res; north = window.north - (n[i] + 0.5) * window.ns_res; if (fd_centroids) { /* write centroids if requested */ Points->x[0] = east; Points->y[0] = north; Cats->cat[0] = i; Vect_write_line(fd_centroids, GV_POINT, Points, Cats); sprintf(buf, "insert into %s values (%d, %f, %f, %f, %ld)", Fi->table, i, vol, avg, sum[i], count[i]); db_set_string(&sql, buf); if (db_execute_immediate(driver, &sql) != DB_OK) G_fatal_error(_("Cannot insert new row: %s"), db_get_string(&sql)); } if (out_mode) fprintf(stdout, "%8d%10.2f%10.0f %7ld %10.2f %10.2f %16.2f\n", i, avg, sum[i], count[i], east, north, vol); else fprintf(stdout, "%d:%.2f:%.0f:%ld:%.2f:%.2f:%.2f\n", i, avg, sum[i], count[i], east, north, vol); } } /* write centroid attributes and close the map*/ if (fd_centroids) { db_commit_transaction(driver); Vect_close(fd_centroids); } /* print total value */ if (total_vol > 0.0 && out_mode) { fprintf(stdout, "%s\n", SEP); fprintf(stdout, "%60s = %14.2f", _("Total Volume"), total_vol); fprintf(stdout, "\n"); } exit(EXIT_SUCCESS); }
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; }
int INPUT(struct Map_info *In, char *column, char *scol, char *wheresql) { struct quadruple *point; double x, y, z, w, nz = 0., sm; double c1, c2, c3, c4, c5, c6, nsg; int i, j, k = 0, a, irev, cfmask; int ddisk = 0; double deltx, delty, deltz; int first_time = 1; CELL *cellmask; const char *mapsetm; char buf[500]; int cat, intval; struct field_info *Fi; dbDriver *Driver; dbCatValArray cvarr, sarray; int nrec, nrec1, ctype, sctype; struct line_pnts *Points; struct line_cats *Cats; OUTRANGE = 0; NPOINT = 0; dmin = dmin * dmin; /* Read attributes */ db_CatValArray_init(&cvarr); if (scol != NULL) db_CatValArray_init(&sarray); Fi = Vect_get_field(In, 1); if (Fi == NULL) G_fatal_error(_("Unable to get layer info for vector map")); Driver = db_start_driver_open_database(Fi->driver, Fi->database); if (Driver == NULL) G_fatal_error(_("Unable to open database <%s> by driver <%s>"), Fi->database, Fi->driver); nrec = db_select_CatValArray(Driver, Fi->table, Fi->key, column, wheresql, &cvarr); ctype = cvarr.ctype; G_debug(3, "nrec = %d", nrec); if (ctype != DB_C_TYPE_INT && ctype != DB_C_TYPE_DOUBLE) G_fatal_error(_("Column type of wcolumn is not supported (must be integer or double)")); if (nrec < 0) G_fatal_error(_("Unable to select data from table")); G_message("%d records selected from table", nrec); if (scol != NULL) { nrec1 = db_select_CatValArray(Driver, Fi->table, Fi->key, scol, wheresql, &sarray); sctype = cvarr.ctype; if (sctype == -1) G_fatal_error(_("Cannot read column type of smooth column")); if (sctype == DB_C_TYPE_DATETIME) G_fatal_error (_("Column type of smooth column (datetime) is not supported")); if (sctype != DB_C_TYPE_INT && sctype != DB_C_TYPE_DOUBLE) G_fatal_error(_("Column type of smooth column is not supported (must be integer or double)")); } Points = Vect_new_line_struct(); Cats = Vect_new_cats_struct(); Vect_rewind(In); while (1) { int ival, type, ret; if (-1 == (type = Vect_read_next_line(In, Points, Cats))) G_fatal_error(_("Unable to read vector map")); if (type == -2) break; /* EOF */ if (!(type & GV_POINTS)) continue; Vect_cat_get(Cats, 1, &cat); if (cat < 0) { G_warning(_("Point without category")); continue; } x = Points->x[0]; y = Points->y[0]; z = Points->z[0]; if (ctype == DB_C_TYPE_INT) { ret = db_CatValArray_get_value_int(&cvarr, cat, &ival); w = ival; } else { /* DB_C_TYPE_DOUBLE */ ret = db_CatValArray_get_value_double(&cvarr, cat, &w); } if (ret != DB_OK) { if (wheresql != NULL) /* G_message(_("Database record for cat %d not used due to SQL statement")); */ /* do nothing in this case to not confuse user. Or implement second cat list */ ; else G_warning(_("No record for category %d in table <%s>"), cat, Fi->table); continue; } if (rsm == -1 && scol != NULL) { if (sctype == DB_C_TYPE_INT) { ret = db_CatValArray_get_value_int(&sarray, cat, &intval); sm = intval; } else { /* DB_C_TYPE_DOUBLE */ ret = db_CatValArray_get_value_double(&sarray, cat, &sm); } } G_debug(3, "%f %f %f %f", x, y, z, w); k++; w = w * wmult; z = z * zmult; c1 = x - ((struct octdata *)(root->data))->x_orig; c2 = ((struct octdata *)(root->data))->x_orig + ((struct octdata *)(root->data))->n_cols * ew_res - x; c3 = y - ((struct octdata *)(root->data))->y_orig; c4 = ((struct octdata *)(root->data))->y_orig + ((struct octdata *)(root->data))->n_rows * ns_res - y; c5 = z - ((struct octdata *)(root->data))->z_orig; c6 = ((struct octdata *)(root->data))->z_orig + ((struct octdata *)(root->data))->n_levs * tb_res - z; if (! ((c1 >= 0) && (c2 >= 0) && (c3 >= 0) && (c4 >= 0) && (c5 >= 0) && (c6 >= 0))) { if (!OUTRANGE) { G_warning(_("Some points outside of region -- will ignore...")); } OUTRANGE++; } else { if (!(point = point_new(x, y, z, w, sm))) { clean(); G_fatal_error(_("Cannot allocate memory for point")); } a = OT_insert_oct(point, root); if (a == 0) { NPOINT++; } if (a < 0) { G_warning(_("Can't insert %lf,%lf,%lf,%lf,%lf a=%d"), x, y, z, w, sm, a); return -1; } if (first_time) { first_time = 0; xmin = x; ymin = y; zmin = z; wmin = w; xmax = x; ymax = y; zmax = z; wmax = w; } xmin = amin1(xmin, x); ymin = amin1(ymin, y); zmin = amin1(zmin, z); wmin = amin1(wmin, w); xmax = amax1(xmax, x); ymax = amax1(ymax, y); zmax = amax1(zmax, z); wmax = amax1(wmax, w); } } /* while */ db_CatValArray_free(&cvarr); c1 = xmin - ((struct octdata *)(root->data))->x_orig; c2 = ((struct octdata *)(root->data))->x_orig + ((struct octdata *)(root->data))->n_cols * ew_res - xmax; c3 = ymin - ((struct octdata *)(root->data))->y_orig; c4 = ((struct octdata *)(root->data))->y_orig + ((struct octdata *)(root->data))->n_rows * ns_res - ymax; c5 = zmin - ((struct octdata *)(root->data))->z_orig; c6 = ((struct octdata *)(root->data))->z_orig + ((struct octdata *)(root->data))->n_levs * tb_res - zmax; if ((c1 > 5 * ew_res) || (c2 > 5 * ew_res) || (c3 > 5 * ns_res) || (c4 > 5 * ns_res) || (c5 > 5 * tb_res) || (c6 > 5 * tb_res)) { static int once = 0; if (!once) { once = 1; G_warning(_("Strip exists with insufficient data")); } } nz = wmin; totsegm = translate_oct(root, ((struct octdata *)(root->data))->x_orig, ((struct octdata *)(root->data))->y_orig, ((struct octdata *)(root->data))->z_orig, nz); if (!totsegm) { clean(); G_fatal_error(_("Zero segments!")); } ((struct octdata *)(root->data))->x_orig = 0; ((struct octdata *)(root->data))->y_orig = 0; ((struct octdata *)(root->data))->z_orig = 0; /* was commented out */ if (outz != NULL) ddisk += disk; if (gradient != NULL) ddisk += disk; if (aspect1 != NULL) ddisk += disk; if (ncurv != NULL) ddisk += disk; if (gcurv != NULL) ddisk += disk; if (mcurv != NULL) ddisk += disk; G_message ("Processing all selected output files will require %d bytes of disk space for temp files", ddisk); /* fprintf(stderr,"xmin=%lf,xmax=%lf,ymin=%lf,ymax=%lf,zmin=%lf,zmax=%lf,wmin=%lf,wmax=%lf\n",xmin,xmax,ymin,ymax,zmin,zmax,wmin,wmax); */ fprintf(stderr, "\n"); if (OUTRANGE > 0) G_warning (_("There are points outside specified 2D/3D region--ignored %d points (total points: %d)"), OUTRANGE, k); if (NPOINT > 0) G_warning (_("Points are more dense than specified 'DMIN'--ignored %d points (remain %d)"), NPOINT, k - NPOINT); NPOINT = k - NPOINT - NPT - OUTRANGE; if (NPOINT < KMIN) { if (NPOINT != 0) { G_warning (_("%d points given for interpolation (after thinning) is less than given NPMIN=%d"), NPOINT, KMIN); KMIN = NPOINT; } else { fprintf(stderr, "ERROR: zero points in the given region!\n"); return -1; } } if (NPOINT > KMAXPOINTS && KMIN <= KMAX) { fprintf(stderr, "ERROR: segmentation parameters set to invalid values: npmin = %d, segmax = %d \n", KMIN, KMAX); fprintf(stderr, "for smooth connection of segments, npmin > segmax (see manual) \n"); return -1; } if (NPOINT < KMAXPOINTS && KMAX != KMAXPOINTS) G_warning (_("There is less than %d points for interpolation, no segmentation is necessary, to run the program faster, set segmax=%d (see manual)"), KMAXPOINTS, KMAXPOINTS); deltx = xmax - xmin; delty = ymax - ymin; deltz = zmax - zmin; nsg = (double)NPOINT / (double)KMIN; dnorm = deltx * delty * deltz / nsg; nsg = 3.0; nsg = 1. / nsg; dnorm = pow(dnorm, nsg); /* DEBUG if (fd4 != NULL) fprintf (fd4, "deltx,delty %f %f \n", deltx, delty); */ nsizc = current_region.cols; /* ((int)(deltx/ew_res))+1; */ nsizr = current_region.rows; /* ((int)(delty/ns_res))+1; */ NPT = k; x0utm = 0.; y0utm = 0.; z0utm = 0.; /** create a bitmap mask from given raster map **/ if (maskmap != NULL) { mapsetm = G_find_raster2(maskmap, ""); if (!mapsetm) { clean(); G_fatal_error(_("Mask raster map [%s] not found"), maskmap); } bitmask = BM_create(nsizc, nsizr); cellmask = Rast_allocate_c_buf(); cfmask = Rast_open_old(maskmap, mapsetm); for (i = 0; i < nsizr; i++) { irev = nsizr - i - 1; Rast_get_c_row(cfmask, cellmask, i); for (j = 0; j < nsizc; j++) { if ((cellmask[j] == 0) || Rast_is_c_null_value(&cellmask[j])) BM_set(bitmask, j, irev, 0); else BM_set(bitmask, j, irev, 1); } } G_message(_("Bitmap mask created")); } return 1; }
int main(int argc, char *argv[]) { int i; int print_flag = 0; int flat_flag; int set_flag; double x; int ival; int row_flag = 0, col_flag = 0; struct Cell_head window, temp_window; const char *value; const char *name; const char *mapset; char **rast_ptr, **vect_ptr; struct GModule *module; struct { struct Flag *update, *print, *gprint, *flprint, *lprint, *eprint, *nangle, *center, *res_set, *dist_res, *dflt, *z, *savedefault, *bbox, *gmt_style, *wms_style; } flag; struct { struct Option *north, *south, *east, *west, *top, *bottom, *res, *nsres, *ewres, *res3, *tbres, *rows, *cols, *save, *region, *raster, *raster3d, *align, *zoom, *vect; } parm; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("general")); G_add_keyword(_("settings")); module->description = _("Manages the boundary definitions for the " "geographic region."); /* flags */ flag.dflt = G_define_flag(); flag.dflt->key = 'd'; flag.dflt->description = _("Set from default region"); flag.dflt->guisection = _("Existing"); flag.savedefault = G_define_flag(); flag.savedefault->key = 's'; flag.savedefault->label = _("Save as default region"); flag.savedefault->description = _("Only possible from the PERMANENT mapset"); flag.savedefault->guisection = _("Existing"); flag.print = G_define_flag(); flag.print->key = 'p'; flag.print->description = _("Print the current region"); flag.print->guisection = _("Print"); flag.lprint = G_define_flag(); flag.lprint->key = 'l'; flag.lprint->description = _("Print the current region in lat/long " "using the current ellipsoid/datum"); flag.lprint->guisection = _("Print"); flag.eprint = G_define_flag(); flag.eprint->key = 'e'; flag.eprint->description = _("Print the current region extent"); flag.eprint->guisection = _("Print"); flag.center = G_define_flag(); flag.center->key = 'c'; flag.center->description = _("Print the current region map center coordinates"); flag.center->guisection = _("Print"); flag.gmt_style = G_define_flag(); flag.gmt_style->key = 't'; flag.gmt_style->description = _("Print the current region in GMT style"); flag.gmt_style->guisection = _("Print"); flag.wms_style = G_define_flag(); flag.wms_style->key = 'w'; flag.wms_style->description = _("Print the current region in WMS style"); flag.wms_style->guisection = _("Print"); flag.dist_res = G_define_flag(); flag.dist_res->key = 'm'; flag.dist_res->description = _("Print region resolution in meters (geodesic)"); flag.dist_res->guisection = _("Print"); flag.nangle = G_define_flag(); flag.nangle->key = 'n'; flag.nangle->label = _("Print the convergence angle (degrees CCW)"); flag.nangle->description = _("The difference between the projection's grid north and true north, " "measured at the center coordinates of the current region."); flag.nangle->guisection = _("Print"); flag.z = G_define_flag(); flag.z->key = '3'; flag.z->description = _("Print also 3D settings"); flag.z->guisection = _("Print"); flag.bbox = G_define_flag(); flag.bbox->key = 'b'; flag.bbox->description = _("Print the maximum bounding box in lat/long on WGS84"); flag.bbox->guisection = _("Print"); flag.gprint = G_define_flag(); flag.gprint->key = 'g'; flag.gprint->description = _("Print in shell script style"); flag.gprint->guisection = _("Print"); flag.flprint = G_define_flag(); flag.flprint->key = 'f'; flag.flprint->description = _("Print in shell script style, but in one line (flat)"); flag.flprint->guisection = _("Print"); flag.res_set = G_define_flag(); flag.res_set->key = 'a'; flag.res_set->description = _("Align region to resolution (default = align to bounds, " "works only for 2D resolution)"); flag.res_set->guisection = _("Bounds"); flag.update = G_define_flag(); flag.update->key = 'u'; flag.update->description = _("Do not update the current region"); flag.update->guisection = _("Effects"); /* parameters */ parm.region = G_define_standard_option(G_OPT_M_REGION); parm.region->description = _("Set current region from named region"); parm.region->guisection = _("Existing"); parm.raster = G_define_standard_option(G_OPT_R_MAP); parm.raster->key = "raster"; parm.raster->required = NO; parm.raster->multiple = YES; parm.raster->description = _("Set region to match raster map(s)"); parm.raster->guisection = _("Existing"); parm.raster3d = G_define_standard_option(G_OPT_R3_MAP); parm.raster3d->key = "raster_3d"; parm.raster3d->required = NO; parm.raster3d->multiple = NO; parm.raster3d->description = _("Set region to match 3D raster map(s) (both 2D and 3D " "values)"); parm.raster3d->guisection = _("Existing"); parm.vect = G_define_standard_option(G_OPT_V_MAP); parm.vect->key = "vector"; parm.vect->required = NO; parm.vect->multiple = YES; parm.vect->label = _("Set region to match vector map(s)"); parm.vect->description = NULL; parm.vect->guisection = _("Existing"); parm.north = G_define_option(); parm.north->key = "n"; parm.north->key_desc = "value"; parm.north->required = NO; parm.north->multiple = NO; parm.north->type = TYPE_STRING; parm.north->description = _("Value for the northern edge"); parm.north->guisection = _("Bounds"); parm.south = G_define_option(); parm.south->key = "s"; parm.south->key_desc = "value"; parm.south->required = NO; parm.south->multiple = NO; parm.south->type = TYPE_STRING; parm.south->description = _("Value for the southern edge"); parm.south->guisection = _("Bounds"); parm.east = G_define_option(); parm.east->key = "e"; parm.east->key_desc = "value"; parm.east->required = NO; parm.east->multiple = NO; parm.east->type = TYPE_STRING; parm.east->description = _("Value for the eastern edge"); parm.east->guisection = _("Bounds"); parm.west = G_define_option(); parm.west->key = "w"; parm.west->key_desc = "value"; parm.west->required = NO; parm.west->multiple = NO; parm.west->type = TYPE_STRING; parm.west->description = _("Value for the western edge"); parm.west->guisection = _("Bounds"); parm.top = G_define_option(); parm.top->key = "t"; parm.top->key_desc = "value"; parm.top->required = NO; parm.top->multiple = NO; parm.top->type = TYPE_STRING; parm.top->description = _("Value for the top edge"); parm.top->guisection = _("Bounds"); parm.bottom = G_define_option(); parm.bottom->key = "b"; parm.bottom->key_desc = "value"; parm.bottom->required = NO; parm.bottom->multiple = NO; parm.bottom->type = TYPE_STRING; parm.bottom->description = _("Value for the bottom edge"); parm.bottom->guisection = _("Bounds"); parm.rows = G_define_option(); parm.rows->key = "rows"; parm.rows->key_desc = "value"; parm.rows->required = NO; parm.rows->multiple = NO; parm.rows->type = TYPE_INTEGER; parm.rows->description = _("Number of rows in the new region"); parm.rows->guisection = _("Resolution"); parm.cols = G_define_option(); parm.cols->key = "cols"; parm.cols->key_desc = "value"; parm.cols->required = NO; parm.cols->multiple = NO; parm.cols->type = TYPE_INTEGER; parm.cols->description = _("Number of columns in the new region"); parm.cols->guisection = _("Resolution"); parm.res = G_define_option(); parm.res->key = "res"; parm.res->key_desc = "value"; parm.res->required = NO; parm.res->multiple = NO; parm.res->type = TYPE_STRING; parm.res->description = _("2D grid resolution (north-south and east-west)"); parm.res->guisection = _("Resolution"); parm.res3 = G_define_option(); parm.res3->key = "res3"; parm.res3->key_desc = "value"; parm.res3->required = NO; parm.res3->multiple = NO; parm.res3->type = TYPE_STRING; parm.res3->description = _("3D grid resolution (north-south, east-west and top-bottom)"); parm.res3->guisection = _("Resolution"); parm.nsres = G_define_option(); parm.nsres->key = "nsres"; parm.nsres->key_desc = "value"; parm.nsres->required = NO; parm.nsres->multiple = NO; parm.nsres->type = TYPE_STRING; parm.nsres->description = _("North-south 2D grid resolution"); parm.nsres->guisection = _("Resolution"); parm.ewres = G_define_option(); parm.ewres->key = "ewres"; parm.ewres->key_desc = "value"; parm.ewres->required = NO; parm.ewres->multiple = NO; parm.ewres->type = TYPE_STRING; parm.ewres->description = _("East-west 2D grid resolution"); parm.ewres->guisection = _("Resolution"); parm.tbres = G_define_option(); parm.tbres->key = "tbres"; parm.tbres->key_desc = "value"; parm.tbres->required = NO; parm.tbres->multiple = NO; parm.tbres->type = TYPE_STRING; parm.tbres->description = _("Top-bottom 3D grid resolution"); parm.tbres->guisection = _("Resolution"); parm.zoom = G_define_option(); parm.zoom->key = "zoom"; parm.zoom->key_desc = "name"; parm.zoom->required = NO; parm.zoom->multiple = NO; parm.zoom->type = TYPE_STRING; parm.zoom->description = _("Shrink region until it meets non-NULL data from this raster map"); parm.zoom->gisprompt = "old,cell,raster"; parm.zoom->guisection = _("Bounds"); parm.align = G_define_option(); parm.align->key = "align"; parm.align->key_desc = "name"; parm.align->required = NO; parm.align->multiple = NO; parm.align->type = TYPE_STRING; parm.align->description = _("Adjust region cells to cleanly align with this raster map"); parm.align->gisprompt = "old,cell,raster"; parm.align->guisection = _("Bounds"); parm.save = G_define_option(); parm.save->key = "save"; parm.save->key_desc = "name"; parm.save->required = NO; parm.save->multiple = NO; parm.save->type = TYPE_STRING; parm.save->description = _("Save current region settings in named region file"); parm.save->gisprompt = "new,windows,region"; parm.save->guisection = _("Effects"); G_option_required(flag.dflt, flag.savedefault, flag.print, flag.lprint, flag.eprint, flag.center, flag.gmt_style, flag.wms_style, flag.dist_res, flag.nangle, flag. z, flag.bbox, flag.gprint, flag.res_set, flag.update, parm.region, parm.raster, parm.raster3d, parm.vect, parm.north, parm.south, parm.east, parm.west, parm.top, parm.bottom, parm.rows, parm.cols, parm.res, parm.res3, parm.nsres, parm.ewres, parm.tbres, parm.zoom, parm.align, parm.save, NULL); if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_get_default_window(&window); set_flag = !flag.update->answer; flat_flag = flag.flprint->answer; if (flag.print->answer) print_flag |= PRINT_REG; if (flag.gprint->answer) print_flag |= PRINT_SH; if (flag.lprint->answer) print_flag |= PRINT_LL; if (flag.eprint->answer) print_flag |= PRINT_EXTENT; if (flag.center->answer) print_flag |= PRINT_CENTER; if (flag.gmt_style->answer) print_flag |= PRINT_GMT; if (flag.wms_style->answer) print_flag |= PRINT_WMS; if (flag.nangle->answer) print_flag |= PRINT_NANGLE; if (flag.dist_res->answer) print_flag |= PRINT_METERS; if (flag.z->answer) print_flag |= PRINT_3D; if (flag.bbox->answer) print_flag |= PRINT_MBBOX; if (print_flag == PRINT_METERS) print_flag |= PRINT_SH; if (print_flag == PRINT_SH || print_flag & PRINT_3D || print_flag == PRINT_METERS + PRINT_SH) { print_flag |= PRINT_REG; } if (!flag.dflt->answer) G_get_window(&window); /* region= */ if ((name = parm.region->answer)) { mapset = G_find_file2("windows", name, ""); if (!mapset) G_fatal_error(_("Region <%s> not found"), name); G_get_element_window(&window, "windows", name, mapset); } /* raster= */ if (parm.raster->answer) { int first = 0; rast_ptr = parm.raster->answers; for (; *rast_ptr != NULL; rast_ptr++) { char rast_name[GNAME_MAX]; strcpy(rast_name, *rast_ptr); mapset = G_find_raster2(rast_name, ""); if (!mapset) G_fatal_error(_("Raster map <%s> not found"), rast_name); Rast_get_cellhd(rast_name, mapset, &temp_window); if (!first) { window = temp_window; first = 1; } else { window.north = (window.north > temp_window.north) ? window.north : temp_window.north; window.south = (window.south < temp_window.south) ? window.south : temp_window.south; window.east = (window.east > temp_window.east) ? window.east : temp_window.east; window.west = (window.west < temp_window.west) ? window.west : temp_window.west; } } G_adjust_Cell_head3(&window, 0, 0, 0); } /* raster3d= */ if ((name = parm.raster3d->answer)) { RASTER3D_Region win; if ((mapset = G_find_raster3d(name, "")) == NULL) G_fatal_error(_("3D raster map <%s> not found"), name); if (Rast3d_read_region_map(name, mapset, &win) < 0) G_fatal_error(_("Unable to read header of 3D raster map <%s@%s>"), name, mapset); Rast3d_region_to_cell_head(&win, &window); } /* vector= */ if (parm.vect->answer) { int first = 0; vect_ptr = parm.vect->answers; for (; *vect_ptr != NULL; vect_ptr++) { struct Map_info Map; struct bound_box box; char vect_name[GNAME_MAX]; struct Cell_head map_window; strcpy(vect_name, *vect_ptr); mapset = G_find_vector2(vect_name, ""); if (!mapset) G_fatal_error(_("Vector map <%s> not found"), vect_name); temp_window = window; Vect_set_open_level(2); if (2 > Vect_open_old_head(&Map, vect_name, mapset)) G_fatal_error(_("Unable to open vector map <%s> on topological level"), vect_name); Vect_get_map_box(&Map, &box); map_window = window; map_window.north = box.N; map_window.south = box.S; map_window.west = box.W; map_window.east = box.E; map_window.top = box.T; map_window.bottom = box.B; if (!first) { window = map_window; first = 1; } else { window.north = (window.north > map_window.north) ? window.north : map_window.north; window.south = (window.south < map_window.south) ? window.south : map_window.south; window.east = (window.east > map_window.east) ? window.east : map_window.east; window.west = (window.west < map_window.west) ? window.west : map_window.west; if (map_window.top > window.top) window.top = map_window.top; if (map_window.bottom < window.bottom) window.bottom = map_window.bottom; } if (window.north == window.south) { window.north = window.north + 0.5 * temp_window.ns_res; window.south = window.south - 0.5 * temp_window.ns_res; } if (window.east == window.west) { window.west = window.west - 0.5 * temp_window.ew_res; window.east = window.east + 0.5 * temp_window.ew_res; } if (window.top == window.bottom) { window.bottom = (window.bottom - 0.5 * temp_window.tb_res); window.top = (window.top + 0.5 * temp_window.tb_res); } if (flag.res_set->answer) Rast_align_window(&window, &temp_window); Vect_close(&Map); } } /* n= */ if ((value = parm.north->answer)) { if ((i = nsew(value, "n+", "n-", "s+"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.north); switch (i) { case 1: window.north += x; break; case 2: window.north -= x; break; case 3: window.north = window.south + x; break; } } else if (G_scan_northing(value, &x, window.proj)) window.north = x; else die(parm.north); } /* s= */ if ((value = parm.south->answer)) { if ((i = nsew(value, "s+", "s-", "n-"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.south); switch (i) { case 1: window.south += x; break; case 2: window.south -= x; break; case 3: window.south = window.north - x; break; } } else if (G_scan_northing(value, &x, window.proj)) window.south = x; else die(parm.south); } /* e= */ if ((value = parm.east->answer)) { if ((i = nsew(value, "e+", "e-", "w+"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.east); switch (i) { case 1: window.east += x; break; case 2: window.east -= x; break; case 3: window.east = window.west + x; break; } } else if (G_scan_easting(value, &x, window.proj)) window.east = x; else die(parm.east); } /* w= */ if ((value = parm.west->answer)) { if ((i = nsew(value, "w+", "w-", "e-"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.west); switch (i) { case 1: window.west += x; break; case 2: window.west -= x; break; case 3: window.west = window.east - x; break; } } else if (G_scan_easting(value, &x, window.proj)) window.west = x; else die(parm.west); } /* t= */ if ((value = parm.top->answer)) { if ((i = nsew(value, "t+", "t-", "b+"))) { if (sscanf(value + 2, "%lf", &x) != 1) die(parm.top); switch (i) { case 1: window.top += x; break; case 2: window.top -= x; break; case 3: window.top = window.bottom + x; break; } } else if (sscanf(value, "%lf", &x) == 1) window.top = x; else die(parm.top); } /* b= */ if ((value = parm.bottom->answer)) { if ((i = nsew(value, "b+", "b-", "t-"))) { if (sscanf(value + 2, "%lf", &x) != 1) die(parm.bottom); switch (i) { case 1: window.bottom += x; break; case 2: window.bottom -= x; break; case 3: window.bottom = window.top - x; break; } } else if (sscanf(value, "%lf", &x) == 1) window.bottom = x; else die(parm.bottom); } /* res= */ if ((value = parm.res->answer)) { if (!G_scan_resolution(value, &x, window.proj)) die(parm.res); window.ns_res = x; window.ew_res = x; if (flag.res_set->answer) { window.north = ceil(window.north / x) * x; window.south = floor(window.south / x) * x; window.east = ceil(window.east / x) * x; window.west = floor(window.west / x) * x; } } /* res3= */ if ((value = parm.res3->answer)) { if (!G_scan_resolution(value, &x, window.proj)) die(parm.res); window.ns_res3 = x; window.ew_res3 = x; window.tb_res = x; } /* nsres= */ if ((value = parm.nsres->answer)) { if (!G_scan_resolution(value, &x, window.proj)) die(parm.nsres); window.ns_res = x; if (flag.res_set->answer) { window.north = ceil(window.north / x) * x; window.south = floor(window.south / x) * x; } } /* ewres= */ if ((value = parm.ewres->answer)) { if (!G_scan_resolution(value, &x, window.proj)) die(parm.ewres); window.ew_res = x; if (flag.res_set->answer) { window.east = ceil(window.east / x) * x; window.west = floor(window.west / x) * x; } } /* tbres= */ if ((value = parm.tbres->answer)) { if (sscanf(value, "%lf", &x) != 1) die(parm.tbres); window.tb_res = x; if (flag.res_set->answer) { window.top = ceil(window.top / x) * x; window.bottom = floor(window.bottom / x) * x; } } /* rows= */ if ((value = parm.rows->answer)) { if (sscanf(value, "%i", &ival) != 1) die(parm.rows); window.rows = ival; row_flag = 1; } /* cols= */ if ((value = parm.cols->answer)) { if (sscanf(value, "%i", &ival) != 1) die(parm.cols); window.cols = ival; col_flag = 1; } /* zoom= */ if ((name = parm.zoom->answer)) { mapset = G_find_raster2(name, ""); if (!mapset) G_fatal_error(_("Raster map <%s> not found"), name); zoom(&window, name, mapset); } /* align= */ if ((name = parm.align->answer)) { mapset = G_find_raster2(name, ""); if (!mapset) G_fatal_error(_("Raster map <%s> not found"), name); Rast_get_cellhd(name, mapset, &temp_window); Rast_align_window(&window, &temp_window); } /* save= */ if ((name = parm.save->answer)) { temp_window = window; G_adjust_Cell_head3(&temp_window, 0, 0, 0); if (G_put_element_window(&temp_window, "windows", name) < 0) G_fatal_error(_("Unable to set region <%s>"), name); } G_adjust_Cell_head3(&window, row_flag, col_flag, 0); if (set_flag) { if (G_put_window(&window) < 0) G_fatal_error(_("Unable to update current region")); } if (flag.savedefault->answer) { if (strcmp(G_mapset(), "PERMANENT") == 0) { G_put_element_window(&window, "", "DEFAULT_WIND"); } else { G_fatal_error(_("Unable to change default region. " "The current mapset is not <PERMANENT>.")); } } /* / flag.savedefault->answer */ if (print_flag) print_window(&window, print_flag, flat_flag); exit(EXIT_SUCCESS); }
/* ************************************************************************* */ int main(int argc, char *argv[]) { RASTER3D_Region region, inputmap_bounds; struct Cell_head region2d; struct GModule *module; struct History history; void *map = NULL; /*The 3D Rastermap */ int i = 0, changemask = 0; int *fd = NULL, output_type, cols, rows; char *RasterFileName; int overwrite = 0; /* Initialize GRASS */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster3d")); G_add_keyword(_("conversion")); G_add_keyword(_("raster")); G_add_keyword(_("voxel")); module->description = _("Converts 3D raster maps to 2D raster maps"); /* Get parameters from user */ set_params(); /* Have GRASS get inputs */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_debug(3, "Open 3D raster map <%s>", param.input->answer); if (NULL == G_find_raster3d(param.input->answer, "")) Rast3d_fatal_error(_("3D raster map <%s> not found"), param.input->answer); /*Set the defaults */ Rast3d_init_defaults(); /*Set the resolution of the output maps */ if (param.res->answer) { /*Open the map with current region */ map = Rast3d_open_cell_old(param.input->answer, G_find_raster3d(param.input->answer, ""), RASTER3D_DEFAULT_WINDOW, RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT); if (map == NULL) Rast3d_fatal_error(_("Unable to open 3D raster map <%s>"), param.input->answer); /*Get the region of the map */ Rast3d_get_region_struct_map(map, ®ion); /*set this region as current 3D window for map */ Rast3d_set_window_map(map, ®ion); /*Set the 2d region appropriate */ Rast3d_extract2d_region(®ion, ®ion2d); /*Make the new 2d region the default */ Rast_set_window(®ion2d); } else { /* Figure out the region from the map */ Rast3d_get_window(®ion); /*Open the 3d raster map */ map = Rast3d_open_cell_old(param.input->answer, G_find_raster3d(param.input->answer, ""), ®ion, RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT); if (map == NULL) Rast3d_fatal_error(_("Unable to open 3D raster map <%s>"), param.input->answer); } /*Check if the g3d-region is equal to the 2D rows and cols */ rows = Rast_window_rows(); cols = Rast_window_cols(); /*If not equal, set the 3D window correct */ if (rows != region.rows || cols != region.cols) { G_message(_("The 2D and 3D region settings are different. " "Using the 2D window settings to adjust the 2D part of the 3D region.")); G_get_set_window(®ion2d); region.ns_res = region2d.ns_res; region.ew_res = region2d.ew_res; region.rows = region2d.rows; region.cols = region2d.cols; Rast3d_adjust_region(®ion); Rast3d_set_window_map(map, ®ion); } /* save the input map region for later use (history meta-data) */ Rast3d_get_region_struct_map(map, &inputmap_bounds); /*Get the output type */ output_type = Rast3d_file_type_map(map); /*prepare the filehandler */ fd = (int *) G_malloc(region.depths * sizeof (int)); if (fd == NULL) fatal_error(map, NULL, 0, _("Out of memory")); G_message(_("Creating %i raster maps"), region.depths); /*Loop over all output maps! open */ for (i = 0; i < region.depths; i++) { /*Create the outputmaps */ G_asprintf(&RasterFileName, "%s_%05d", param.output->answer, i + 1); G_message(_("Raster map %i Filename: %s"), i + 1, RasterFileName); overwrite = G_check_overwrite(argc, argv); if (G_find_raster2(RasterFileName, "") && !overwrite) G_fatal_error(_("Raster map %d Filename: %s already exists. Use the flag --o to overwrite."), i + 1, RasterFileName); if (output_type == FCELL_TYPE) fd[i] = open_output_map(RasterFileName, FCELL_TYPE); else if (output_type == DCELL_TYPE) fd[i] = open_output_map(RasterFileName, DCELL_TYPE); } /*if requested set the Mask on */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) { changemask = 0; if (Rast3d_mask_is_off(map)) { Rast3d_mask_on(map); changemask = 1; } } } /*Create the Rastermaps */ g3d_to_raster(map, region, fd); /*Loop over all output maps! close */ for (i = 0; i < region.depths; i++) { close_output_map(fd[i]); /* write history */ G_asprintf(&RasterFileName, "%s_%i", param.output->answer, i + 1); G_debug(4, "Raster map %d Filename: %s", i + 1, RasterFileName); Rast_short_history(RasterFileName, "raster", &history); Rast_set_history(&history, HIST_DATSRC_1, "3D Raster map:"); Rast_set_history(&history, HIST_DATSRC_2, param.input->answer); Rast_append_format_history(&history, "Level %d of %d", i + 1, region.depths); Rast_append_format_history(&history, "Level z-range: %f to %f", region.bottom + (i * region.tb_res), region.bottom + (i + 1 * region.tb_res)); Rast_append_format_history(&history, "Input map full z-range: %f to %f", inputmap_bounds.bottom, inputmap_bounds.top); Rast_append_format_history(&history, "Input map z-resolution: %f", inputmap_bounds.tb_res); if (!param.res->answer) { Rast_append_format_history(&history, "GIS region full z-range: %f to %f", region.bottom, region.top); Rast_append_format_history(&history, "GIS region z-resolution: %f", region.tb_res); } Rast_command_history(&history); Rast_write_history(RasterFileName, &history); } /*We set the Mask off, if it was off before */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) if (Rast3d_mask_is_on(map) && changemask) Rast3d_mask_off(map); } /*Cleaning */ if (RasterFileName) G_free(RasterFileName); if (fd) G_free(fd); /* Close files and exit */ if (!Rast3d_close(map)) fatal_error(map, NULL, 0, _("Unable to close 3D raster map")); map = NULL; return (EXIT_SUCCESS); }
int main(int argc, char **argv) { char name[128] = ""; struct Option *map; struct GModule *module; char *mapset; char buff[500]; /* must run in a term window */ G_putenv("GRASS_UI_TERM", "1"); /* Initialize the GIS calls */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("display")); G_add_keyword(_("raster")); module->description = "Allows the user to interactively change the color table " "of a raster map layer displayed on the graphics monitor."; map = G_define_option(); map->key = "map"; map->type = TYPE_STRING; if (*name) map->answer = name; if (*name) map->required = NO; else map->required = YES; map->gisprompt = "old,cell,raster"; map->description = "Name of raster map"; if (G_parser(argc, argv)) exit(1); /* Make sure map is available */ if (map->answer == NULL) exit(0); mapset = G_find_raster2(map->answer, ""); if (mapset == NULL) { char msg[256]; sprintf(msg, "Raster file [%s] not available", map->answer); G_fatal_error(msg); } if (Rast_map_is_fp(map->answer, mapset)) { sprintf(buff, "Raster file [%s] is floating point! \nd.colors only works with integer maps", map->answer); G_fatal_error(buff); } /* connect to the driver */ if (R_open_driver() != 0) G_fatal_error("No graphics device selected"); /* Read in the map region associated with graphics window */ D_setup(0); get_map_info(map->answer, mapset); R_close_driver(); exit(0); }
int main(int argc, char *argv[]) { struct GModule *module; int infile; const char *mapset; size_t cell_size; int ytile, xtile, y, overlap; int *outfiles; void *inbuf; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("tiling")); module->description = _("Splits a raster map into tiles."); parm.rastin = G_define_standard_option(G_OPT_R_INPUT); parm.rastout = G_define_option(); parm.rastout->key = "output"; parm.rastout->type = TYPE_STRING; parm.rastout->required = YES; parm.rastout->multiple = NO; parm.rastout->description = _("Output base name"); parm.width = G_define_option(); parm.width->key = "width"; parm.width->type = TYPE_INTEGER; parm.width->required = YES; parm.width->multiple = NO; parm.width->description = _("Width of tiles (columns)"); parm.height = G_define_option(); parm.height->key = "height"; parm.height->type = TYPE_INTEGER; parm.height->required = YES; parm.height->multiple = NO; parm.height->description = _("Height of tiles (rows)"); parm.overlap = G_define_option(); parm.overlap->key = "overlap"; parm.overlap->type = TYPE_INTEGER; parm.overlap->required = NO; parm.overlap->multiple = NO; parm.overlap->description = _("Overlap of tiles"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_get_set_window(&src_w); overlap = parm.overlap->answer ? atoi(parm.overlap->answer) : 0; mapset = G_find_raster2(parm.rastin->answer, ""); if (mapset == NULL) G_fatal_error(_("Raster map <%s> not found"), parm.rastin->answer); /* set window to old map */ Rast_get_cellhd(parm.rastin->answer, "", &src_w); dst_w = src_w; dst_w.cols = atoi(parm.width->answer); dst_w.rows = atoi(parm.height->answer); G_adjust_Cell_head(&dst_w, 1, 1); xtiles = (src_w.cols + dst_w.cols - 1) / dst_w.cols; ytiles = (src_w.rows + dst_w.rows - 1) / dst_w.rows; G_debug(1, "X: %d * %d, Y: %d * %d", xtiles, dst_w.cols, ytiles, dst_w.rows); src_w.cols = xtiles * dst_w.cols + 2 * overlap; src_w.rows = ytiles * dst_w.rows + 2 * overlap; src_w.west = src_w.west - overlap * src_w.ew_res; src_w.east = src_w.west + (src_w.cols + 2 * overlap) * src_w.ew_res; src_w.north = src_w.north + overlap * src_w.ns_res; src_w.south = src_w.north - (src_w.rows + 2 * overlap) * src_w.ns_res; Rast_set_input_window(&src_w); /* set the output region */ ovl_w = dst_w; ovl_w.cols = ovl_w.cols + 2 * overlap; ovl_w.rows = ovl_w.rows + 2 * overlap; G_adjust_Cell_head(&ovl_w, 1, 1); Rast_set_output_window(&ovl_w); infile = Rast_open_old(parm.rastin->answer, ""); map_type = Rast_get_map_type(infile); cell_size = Rast_cell_size(map_type); inbuf = Rast_allocate_input_buf(map_type); outfiles = G_malloc(xtiles * sizeof(int)); G_debug(1, "X: %d * %d, Y: %d * %d", xtiles, dst_w.cols, ytiles, dst_w.rows); G_message(_("Generating %d x %d = %d tiles..."), xtiles, ytiles, xtiles * ytiles); for (ytile = 0; ytile < ytiles; ytile++) { G_debug(1, "reading y tile: %d", ytile); G_percent(ytile, ytiles, 2); for (xtile = 0; xtile < xtiles; xtile++) { char name[GNAME_MAX]; sprintf(name, "%s-%03d-%03d", parm.rastout->answer, ytile, xtile); outfiles[xtile] = Rast_open_new(name, map_type); } for (y = 0; y < ovl_w.rows; y++) { int row = ytile * dst_w.rows + y; G_debug(1, "reading row: %d", row); Rast_get_row(infile, inbuf, row, map_type); for (xtile = 0; xtile < xtiles; xtile++) { int cells = xtile * dst_w.cols; void *ptr = G_incr_void_ptr(inbuf, cells * cell_size); Rast_put_row(outfiles[xtile], ptr, map_type); } } for (xtile = 0; xtile < xtiles; xtile++) { Rast_close(outfiles[xtile]); write_support_files(xtile, ytile, overlap); } } Rast_close(infile); return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { int fd[NFILES]; int outfd; int i; const char *name; const char *output; const char *mapset; int non_zero; struct Range range; CELL ncats, max_cats; int primary; struct Categories pcats; struct Colors pcolr; char buf[1024]; CELL result; struct GModule *module; struct { struct Option *input, *output; } parm; struct { struct Flag *z; } flag; G_gisinit(argv[0]); /* Define the different options */ module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("statistics")); module->description = _("Creates a cross product of the category values from " "multiple raster map layers."); parm.input = G_define_option(); parm.input->key = "input"; parm.input->type = TYPE_STRING; parm.input->required = YES; parm.input->multiple = YES; parm.input->gisprompt = "old,cell,raster"; sprintf(buf, _("Names of 2-%d input raster maps"), NFILES); parm.input->description = G_store(buf); parm.output = G_define_standard_option(G_OPT_R_OUTPUT); /* Define the different flags */ flag.z = G_define_flag(); flag.z->key = 'z'; flag.z->description = _("Non-zero data only"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); nrows = Rast_window_rows(); ncols = Rast_window_cols(); nfiles = 0; non_zero = flag.z->answer; for (nfiles = 0; (name = parm.input->answers[nfiles]); nfiles++) { if (nfiles >= NFILES) G_fatal_error(_("More than %d files not allowed"), NFILES); mapset = G_find_raster2(name, ""); if (!mapset) G_fatal_error(_("Raster map <%s> not found"), name); names[nfiles] = name; fd[nfiles] = Rast_open_old(name, mapset); Rast_read_range(name, mapset, &range); ncats = range.max - range.min; if (nfiles == 0 || ncats > max_cats) { primary = nfiles; max_cats = ncats; } } if (nfiles <= 1) G_fatal_error(_("Must specify 2 or more input maps")); output = parm.output->answer; outfd = Rast_open_c_new(output); sprintf(buf, "Cross of %s", names[0]); for (i = 1; i < nfiles - 1; i++) { strcat(buf, ", "); strcat(buf, names[i]); } strcat(buf, " and "); strcat(buf, names[i]); Rast_init_cats(buf, &pcats); /* first step is cross product, but un-ordered */ result = cross(fd, non_zero, primary, outfd); /* print message STEP mesage */ G_message(_("%s: STEP 2 ..."), G_program_name()); /* now close all files */ for (i = 0; i < nfiles; i++) Rast_close(fd[i]); Rast_close(outfd); if (result <= 0) exit(0); /* build the renumbering/reclass and the new cats file */ qsort(reclass, result + 1, sizeof(RECLASS), cmp); table = (CELL *) G_calloc(result + 1, sizeof(CELL)); for (i = 0; i < nfiles; i++) { mapset = G_find_raster2(names[i], ""); Rast_read_cats(names[i], mapset, &labels[i]); } for (ncats = 0; ncats <= result; ncats++) { table[reclass[ncats].result] = ncats; set_cat(ncats, reclass[ncats].cat, &pcats); } for (i = 0; i < nfiles; i++) Rast_free_cats(&labels[i]); /* reopen the output cell for reading and for writing */ fd[0] = Rast_open_old(output, G_mapset()); outfd = Rast_open_c_new(output); renumber(fd[0], outfd); G_message(_("Creating support files for <%s>..."), output); Rast_close(fd[0]); Rast_close(outfd); Rast_write_cats(output, &pcats); Rast_free_cats(&pcats); if (result > 0) { Rast_make_random_colors(&pcolr, (CELL) 1, result); Rast_write_colors(output, G_mapset(), &pcolr); } G_message(_("%ld categories"), (long)result); exit(EXIT_SUCCESS); }
/*! \brief Get GDAL link settings for given raster map \param name map name \param mapset name of mapset \return pointer to GDAL_link structure \return NULL if link not found */ struct GDAL_link *Rast_get_gdal_link(const char *name, const char *mapset) { #ifdef GDAL_LINK GDALDatasetH data; GDALRasterBandH band; GDALDataType type; RASTER_MAP_TYPE req_type; #endif const char *filename; int band_num; struct GDAL_link *gdal; RASTER_MAP_TYPE map_type; FILE *fp; struct Key_Value *key_val; const char *p; DCELL null_val; int hflip, vflip; if (!G_find_raster2(name, mapset)) return NULL; map_type = Rast_map_type(name, mapset); if (map_type < 0) return NULL; fp = G_fopen_old_misc("cell_misc", "gdal", name, mapset); if (!fp) return NULL; key_val = G_fread_key_value(fp); fclose(fp); if (!key_val) return NULL; filename = G_find_key_value("file", key_val); if (!filename) return NULL; p = G_find_key_value("band", key_val); if (!p) return NULL; band_num = atoi(p); if (!band_num) return NULL; p = G_find_key_value("null", key_val); if (!p) return NULL; if (strcmp(p, "none") == 0) Rast_set_d_null_value(&null_val, 1); else null_val = atof(p); hflip = G_find_key_value("hflip", key_val) ? 1 : 0; vflip = G_find_key_value("vflip", key_val) ? 1 : 0; #ifdef GDAL_LINK p = G_find_key_value("type", key_val); if (!p) return NULL; type = atoi(p); switch (type) { case GDT_Byte: case GDT_Int16: case GDT_UInt16: case GDT_Int32: case GDT_UInt32: req_type = CELL_TYPE; break; case GDT_Float32: req_type = FCELL_TYPE; break; case GDT_Float64: req_type = DCELL_TYPE; break; default: return NULL; } if (req_type != map_type) return NULL; Rast_init_gdal(); data = (*pGDALOpen) (filename, GA_ReadOnly); if (!data) return NULL; band = (*pGDALGetRasterBand) (data, band_num); if (!band) { (*pGDALClose) (data); return NULL; } #endif gdal = G_calloc(1, sizeof(struct GDAL_link)); gdal->filename = G_store(filename); gdal->band_num = band_num; gdal->null_val = null_val; gdal->hflip = hflip; gdal->vflip = vflip; #ifdef GDAL_LINK gdal->data = data; gdal->band = band; gdal->type = type; #endif return gdal; }
int null_distance(const char *name1, const char *name2, int *zerro_row, int *zerro_col) { RASTER_MAP_TYPE maptype1, maptype2; const char *mapset; int mapd1, mapd2; void *inrast1, *inrast2; int nrows, ncols, row, col; void *cell1, *cell2; /* NOTE: no need to controll, if the map exists. it should be checked in edge.c */ mapset = G_find_raster2(name1, ""); maptype1 = Rast_map_type(name1, mapset); mapd1 = Rast_open_old(name1, mapset); inrast1 = Rast_allocate_buf(maptype1); mapset = G_find_raster2(name2, ""); maptype2 = Rast_map_type(name2, mapset); mapd2 = Rast_open_old(name2, mapset); inrast2 = Rast_allocate_buf(maptype2); G_message(_("Reading maps <%s,%s> while finding 0 distance ..."), name1, name2); ncols = Rast_window_cols(); nrows = Rast_window_rows(); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_get_row(mapd1, inrast1, row, maptype1); Rast_get_row(mapd2, inrast2, row, maptype2); for (col = 0; col < ncols; col++) { /* first raster */ switch (maptype1) { case CELL_TYPE: cell1 = ((CELL **) inrast1)[col]; break; case FCELL_TYPE: cell1 = ((FCELL **) inrast1)[col]; break; case DCELL_TYPE: cell1 = ((DCELL **) inrast1)[col]; break; } /* second raster */ switch (maptype2) { case CELL_TYPE: cell2 = ((CELL **) inrast2)[col]; break; case FCELL_TYPE: cell2 = ((FCELL **) inrast2)[col]; break; case DCELL_TYPE: cell2 = ((DCELL **) inrast2)[col]; break; } if (!Rast_is_null_value(&cell1, maptype1) && !Rast_is_null_value(&cell2, maptype2)) { *zerro_row = row; *zerro_col = col; /* memory cleanup */ G_free(inrast1); G_free(inrast2); /* closing raster maps */ Rast_close(mapd1); Rast_close(mapd2); return 1; } } } /* memory cleanup */ G_free(inrast1); G_free(inrast2); /* closing raster maps */ Rast_close(mapd1); Rast_close(mapd2); return 0; }
/*! \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); }
/*! \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); }
/*! \brief Get map data type \param filename raster map name \param negflag \return -1 if map is integer and Rast_read_range() fails \return data type (ARRY_*) */ int Gs_numtype(const char *filename, int *negflag) { CELL max = 0, min = 0; struct Range range; const char *mapset; int shortbits, charbits, bitplace; static int max_short, max_char; static int first = 1; if (first) { max_short = max_char = 1; shortbits = 8 * sizeof(short); for (bitplace = 1; bitplace < shortbits; ++bitplace) { /*1 bit for sign */ max_short *= 2; } max_short -= 1; /* NO bits for sign, using unsigned char */ charbits = 8 * sizeof(unsigned char); for (bitplace = 0; bitplace < charbits; ++bitplace) { max_char *= 2; } max_char -= 1; first = 0; } mapset = G_find_raster2(filename, ""); if (!mapset) { G_warning(_("Raster map <%s> not found"), filename); return -1; } if (Rast_map_is_fp(filename, mapset)) { G_debug(3, "Gs_numtype(): fp map detected"); return (ATTY_FLOAT); } if (-1 == Rast_read_range(filename, mapset, &range)) { return (-1); } Rast_get_range_min_max(&range, &min, &max); *negflag = (min < 0); if (max < max_char && min > 0) { return (ATTY_CHAR); } if (max < max_short && min > -max_short) { return (ATTY_SHORT); } return (ATTY_INT); }
/* ************************************************************************* */ int main(int argc, char *argv[]) { RASTER3D_Region region; struct Cell_head window2d; struct GModule *module; void *map = NULL; /*The 3D Rastermap */ int changemask = 0; int elevfd = -1, outfd = -1; /*file descriptors */ int output_type, cols, rows; /* Initialize GRASS */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster3d")); G_add_keyword(_("profile")); G_add_keyword(_("raster")); G_add_keyword(_("voxel")); module->description = _("Creates cross section 2D raster map from 3D raster map based on 2D elevation map"); /* Get parameters from user */ set_params(); /* Have GRASS get inputs */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_debug(3, "Open 3D raster map %s", param.input->answer); if (NULL == G_find_raster3d(param.input->answer, "")) Rast3d_fatal_error(_("3D raster map <%s> not found"), param.input->answer); /* Figure out the region from the map */ Rast3d_init_defaults(); Rast3d_get_window(®ion); /*Check if the g3d-region is equal to the 2d rows and cols */ rows = Rast_window_rows(); cols = Rast_window_cols(); /*If not equal, set the 2D windows correct */ if (rows != region.rows || cols != region.cols) { G_message (_("The 2D and 3D region settings are different. Using the 3D raster map settings to adjust the 2D region.")); G_get_set_window(&window2d); window2d.ns_res = region.ns_res; window2d.ew_res = region.ew_res; window2d.rows = region.rows; window2d.cols = region.cols; Rast_set_window(&window2d); } /*******************/ /*Open the 3d raster map */ /*******************/ map = Rast3d_open_cell_old(param.input->answer, G_find_raster3d(param.input->answer, ""), ®ion, RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT); if (map == NULL) Rast3d_fatal_error(_("Unable to open 3D raster map <%s>"), param.input->answer); /*Get the output type */ output_type = Rast3d_file_type_map(map); if (output_type == FCELL_TYPE || output_type == DCELL_TYPE) { /********************************/ /*Open the elevation raster map */ /********************************/ elevfd = Rast_open_old(param.elevation->answer, ""); globalElevMapType = Rast_get_map_type(elevfd); /**********************/ /*Open the Outputmap */ /**********************/ if (G_find_raster2(param.output->answer, "")) G_message(_("Output map already exists. Will be overwritten!")); if (output_type == FCELL_TYPE) outfd = Rast_open_new(param.output->answer, FCELL_TYPE); else if (output_type == DCELL_TYPE) outfd = Rast_open_new(param.output->answer, DCELL_TYPE); /*if requested set the Mask on */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) { changemask = 0; if (Rast3d_mask_is_off(map)) { Rast3d_mask_on(map); changemask = 1; } } } /************************/ /*Create the Rastermaps */ /************************/ rast3d_cross_section(map, region, elevfd, outfd); /*We set the Mask off, if it was off before */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) if (Rast3d_mask_is_on(map) && changemask) Rast3d_mask_off(map); } Rast_close(outfd); Rast_close(elevfd); } else { fatal_error(map, -1, -1, _("Wrong 3D raster datatype! Cannot create raster map")); } /* Close files and exit */ if (!Rast3d_close(map)) Rast3d_fatal_error(_("Unable to close 3D raster map <%s>"), param.input->answer); return (EXIT_SUCCESS); }
int main(int argc, char *argv[]) { char name[GNAME_MAX], mapset[GMAPSET_MAX], xmapset[GMAPSET_MAX]; struct Cell_head cellhd; struct GModule *module; struct Option *grp; /* must run in a term window */ G_putenv("GRASS_UI_TERM", "1"); G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("geometry")); module->description = _("Mark ground control points on image to be rectified."); grp = G_define_option(); grp->key = "group"; grp->type = TYPE_STRING; grp->required = YES; grp->gisprompt = "old,group,group"; grp->description = _("Name of imagery group to be registered"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); Rast_suppress_masking(); /* need to do this for target location */ interrupt_char = G_intr_char(); tempfile1 = G_tempfile(); tempfile2 = G_tempfile(); cell_list = G_tempfile(); vect_list = G_tempfile(); group_list = G_tempfile(); digit_points = G_tempfile(); digit_results = G_tempfile(); if (R_open_driver() != 0) G_fatal_error(_("No graphics device selected")); /* parse group name */ /* only enforce local-mapset-only due to I_get_group_ref() not liking "@mapset" */ if (G_name_is_fully_qualified(grp->answer, group.name, xmapset)) { if (0 != strcmp(G_mapset(), xmapset)) G_fatal_error(_("[%s] Only local groups may be used"), grp->answer); } else { strncpy(group.name, grp->answer, GNAME_MAX - 1); group.name[GNAME_MAX - 1] = '\0'; /* strncpy() doesn't null terminate on overflow */ } if (!I_get_group_ref(group.name, &group.ref)) G_fatal_error(_("Group [%s] contains no maps, run i.group"), group.name); if (group.ref.nfiles <= 0) G_fatal_error(_("Group [%s] contains no maps, run i.group"), group.name); /* write group files to group list file */ prepare_group_list(); /* get target info and environment */ get_target(); find_target_files(); /* read group control points, if any */ G_suppress_warnings(1); if (!I_get_control_points(group.name, &group.points)) group.points.count = 0; G_suppress_warnings(0); /* determine transformation equation */ Compute_equation(); signal(SIGINT, SIG_IGN); /* signal (SIGQUIT, SIG_IGN); */ Init_graphics(); display_title(VIEW_MAP1); select_target_env(); display_title(VIEW_MAP2); select_current_env(); Begin_curses(); G_set_error_routine(error); /* #ifdef SIGTSTP signal (SIGTSTP, SIG_IGN); #endif */ /* ask user for group file to be displayed */ do { if (!choose_groupfile(name, mapset)) quit(0); /* display this file in "map1" */ } while (!G_find_raster2(name, mapset)); Rast_get_cellhd(name, mapset, &cellhd); G_adjust_window_to_box(&cellhd, &VIEW_MAP1->cell.head, VIEW_MAP1->nrows, VIEW_MAP1->ncols); Configure_view(VIEW_MAP1, name, mapset, cellhd.ns_res, cellhd.ew_res); drawcell(VIEW_MAP1); display_points(1); Curses_clear_window(PROMPT_WINDOW); /* determine initial input method. */ setup_digitizer(); if (use_digitizer) { from_digitizer = 1; from_keyboard = 0; from_flag = 1; } /* go do the work */ driver(); quit(0); }
/*! * \brief Check input and output file names. * * Check: * 1) output is legal map name, * 2) if can find input map, and * 3) if input was found in current mapset, check if input != output. * * \param input input map name * \param output output map name * \param error error type: G_FATAL_EXIT, G_FATAL_PRINT, G_FATAL_RETURN * * \return 0 OK * \return 1 error */ int G_check_input_output_name(const char *input, const char *output, int error) { const char *mapset; if (output == NULL) return 0; /* don't die on undefined parameters */ if (G_legal_filename(output) == -1) { if (error == G_FATAL_EXIT) { G_fatal_error(_("Output raster map name <%s> is not valid map name"), output); } else if (error == G_FATAL_PRINT) { G_warning(_("Output raster map name <%s> is not valid map name"), output); return 1; } else { /* G_FATAL_RETURN */ return 1; } } mapset = G_find_raster2(input, ""); if (mapset == NULL) { if (error == G_FATAL_EXIT) { G_fatal_error(_("Raster map <%s> not found"), input); } else if (error == G_FATAL_PRINT) { G_warning(_("Raster map <%s> not found"), input); return 1; } else { /* G_FATAL_RETURN */ return 1; } } if (strcmp(mapset, G_mapset()) == 0) { char nm[1000], ms[1000]; const char *in; if (G_name_is_fully_qualified(input, nm, ms)) { in = nm; } else { in = input; } if (strcmp(in, output) == 0) { if (error == G_FATAL_EXIT) { G_fatal_error(_("Output raster map <%s> is used as input"), output); } else if (error == G_FATAL_PRINT) { G_warning(_("Output raster map <%s> is used as input"), output); return 1; } else { /* G_FATAL_RETURN */ return 1; } } } return 0; }
/* ************************************************************************* */ void check_input_maps(void) { int i = 0; const char *mapset, *name; /*Check top and bottom if surface is requested */ if (param.structgrid->answer) { if (!param.top->answer || !param.bottom->answer) Rast3d_fatal_error(_("Specify top and bottom map")); mapset = NULL; name = NULL; name = param.top->answer; mapset = G_find_raster2(name, ""); if (mapset == NULL) { Rast3d_fatal_error(_("Top cell map <%s> not found"), param.top->answer); } mapset = NULL; name = NULL; name = param.bottom->answer; mapset = G_find_raster2(name, ""); if (mapset == NULL) { Rast3d_fatal_error(_("Bottom cell map <%s> not found"), param.bottom->answer); } } /*If input maps are provided, check them */ if (param.input->answers != NULL) { for (i = 0; param.input->answers[i] != NULL; i++) { if (NULL == G_find_raster3d(param.input->answers[i], "")) Rast3d_fatal_error(_("3D raster map <%s> not found"), param.input->answers[i]); } } /*Check for rgb maps. */ if (param.rgbmaps->answers != NULL) { for (i = 0; i < 3; i++) { if (param.rgbmaps->answers[i] != NULL) { if (NULL == G_find_raster3d(param.rgbmaps->answers[i], "")) Rast3d_fatal_error(_("3D raster map RGB map <%s> not found"), param.rgbmaps->answers[i]); } else { Rast3d_fatal_error(_("Please provide three RGB 3D raster maps")); } } } /*Check for vector maps. */ if (param.vectormaps->answers != NULL) { for (i = 0; i < 3; i++) { if (param.vectormaps->answers[i] != NULL) { if (NULL == G_find_raster3d(param.vectormaps->answers[i], "")) Rast3d_fatal_error(_("3D vector map <%s> not found"), param.vectormaps->answers[i]); } else { Rast3d_fatal_error(_("Please provide three 3D raster maps for the xyz-vector maps [x,y,z]")); } } } if (param.input->answers == NULL && param.rgbmaps->answers == NULL && param.vectormaps->answers == NULL) { G_warning(_("No 3D raster data, RGB or xyz-vector maps are provided! Will only write the geometry.")); } return; }
int main(int argc, char *argv[]) { const char *name; const char *mapset; long x, y; double dx; RASTER_MAP_TYPE map_type; int i; int from_stdin = FALSE; struct GModule *module; struct { struct Option *map, *fs, *cats, *vals, *raster, *file, *fmt_str, *fmt_coeff; } parm; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("category")); module->description = _("Manages category values and labels associated " "with user-specified raster map layers."); parm.map = G_define_standard_option(G_OPT_R_MAP); parm.cats = G_define_standard_option(G_OPT_V_CATS); parm.cats->multiple = YES; parm.cats->guisection = _("Selection"); parm.vals = G_define_option(); parm.vals->key = "vals"; parm.vals->type = TYPE_DOUBLE; parm.vals->multiple = YES; parm.vals->required = NO; parm.vals->label = _("Comma separated value list"); parm.vals->description = _("Example: 1.4,3.8,13"); parm.vals->guisection = _("Selection"); parm.fs = G_define_standard_option(G_OPT_F_SEP); parm.fs->answer = "tab"; parm.raster = G_define_standard_option(G_OPT_R_INPUT); parm.raster->key = "raster"; parm.raster->required = NO; parm.raster->description = _("Raster map from which to copy category table"); parm.raster->guisection = _("Define"); parm.file = G_define_standard_option(G_OPT_F_INPUT); parm.file->key = "rules"; parm.file->required = NO; parm.file->description = _("File containing category label rules (or \"-\" to read from stdin)"); parm.file->guisection = _("Define"); parm.fmt_str = G_define_option(); parm.fmt_str->key = "format"; parm.fmt_str->type = TYPE_STRING; parm.fmt_str->required = NO; parm.fmt_str->label = _("Default label or format string for dynamic labeling"); parm.fmt_str->description = _("Used when no explicit label exists for the category"); parm.fmt_coeff = G_define_option(); parm.fmt_coeff->key = "coefficients"; parm.fmt_coeff->type = TYPE_DOUBLE; parm.fmt_coeff->required = NO; parm.fmt_coeff->key_desc = "mult1,offset1,mult2,offset2"; /* parm.fmt_coeff->answer = "0.0,0.0,0.0,0.0"; */ parm.fmt_coeff->label = _("Dynamic label coefficients"); parm.fmt_coeff->description = _("Two pairs of category multiplier and offsets, for $1 and $2"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); name = parm.map->answer; fs = G_option_to_separator(parm.fs); mapset = G_find_raster2(name, ""); if (mapset == NULL) G_fatal_error(_("Raster map <%s> not found"), name); map_type = Rast_map_type(name, mapset); /* create category labels */ if (parm.raster->answer || parm.file->answer || parm.fmt_str->answer || parm.fmt_coeff->answer) { /* restrict editing to current mapset */ if (strcmp(mapset, G_mapset()) != 0) G_fatal_error(_("Raster map <%s> not found in current mapset"), name); /* use cats from another map */ if (parm.raster->answer) { int fd; const char *cmapset; cmapset = G_find_raster2(parm.raster->answer, ""); if (cmapset == NULL) G_fatal_error(_("Raster map <%s> not found"), parm.raster->answer); fd = Rast_open_old(name, mapset); Rast_init_cats("", &cats); if (0 > Rast_read_cats(parm.raster->answer, cmapset, &cats)) G_fatal_error(_("Unable to read category file of raster map <%s@%s>"), parm.raster->answer, cmapset); Rast_write_cats(name, &cats); G_message(_("Category table for <%s> set from <%s>"), name, parm.raster->answer); Rast_close(fd); } /* load cats from rules file */ if (parm.file->answer) { FILE *fp; char **tokens; int ntokens; char *e1; char *e2; if (strcmp("-", parm.file->answer) == 0) { from_stdin = TRUE; fp = stdin; } else { fp = fopen(parm.file->answer, "r"); if (!fp) G_fatal_error(_("Unable to open file <%s>"), parm.file->answer); } Rast_init_cats("", &cats); for (;;) { char buf[1024]; DCELL d1, d2; int parse_error = 0; if (!G_getl2(buf, sizeof(buf), fp)) break; tokens = G_tokenize(buf, fs); ntokens = G_number_of_tokens(tokens); if (ntokens == 3) { d1 = strtod(tokens[0], &e1); d2 = strtod(tokens[1], &e2); if (*e1 == 0 && *e2 == 0) Rast_set_d_cat(&d1, &d2, tokens[2], &cats); else parse_error = 1; } else if (ntokens == 2) { d1 = strtod(tokens[0], &e1); if (*e1 == 0) Rast_set_d_cat(&d1, &d1, tokens[1], &cats); else parse_error = 1; } else if (!strlen(buf)) continue; else parse_error = 1; if (parse_error) G_fatal_error(_("Incorrect format of input rules. " "Check separators. Invalid line is:\n%s"), buf); } G_free_tokens(tokens); Rast_write_cats(name, &cats); if (!from_stdin) fclose(fp); } /* set dynamic cat rules for cats without explicit labels */ if (parm.fmt_str->answer || parm.fmt_coeff->answer) { char *fmt_str; double m1, a1, m2, a2; /* read existing values */ Rast_init_cats("", &cats); if (0 > Rast_read_cats(name, G_mapset(), &cats)) G_warning(_("Unable to read category file of raster map <%s@%s>"), name, G_mapset()); if (parm.fmt_str->answer) { fmt_str = G_malloc(strlen(parm.fmt_str->answer) > strlen(cats.fmt) ? strlen(parm.fmt_str->answer) + 1 : strlen(cats.fmt) + 1); strcpy(fmt_str, parm.fmt_str->answer); } else { fmt_str = G_malloc(strlen(cats.fmt) + 1); strcpy(fmt_str, cats.fmt); } m1 = cats.m1; a1 = cats.a1; m2 = cats.m2; a2 = cats.a2; if (parm.fmt_coeff->answer) { m1 = atof(parm.fmt_coeff->answers[0]); a1 = atof(parm.fmt_coeff->answers[1]); m2 = atof(parm.fmt_coeff->answers[2]); a2 = atof(parm.fmt_coeff->answers[3]); } Rast_set_cats_fmt(fmt_str, m1, a1, m2, a2, &cats); Rast_write_cats(name, &cats); } Rast_free_cats(&cats); exit(EXIT_SUCCESS); } else { if (Rast_read_cats(name, mapset, &cats) < 0) G_fatal_error(_("Unable to read category file of raster map <%s> in <%s>"), name, mapset); } /* describe the category labels */ /* if no cats requested, use r.describe to get the cats */ if (parm.cats->answer == NULL) { if (map_type == CELL_TYPE) { get_cats(name, mapset); while (next_cat(&x)) print_label(x); exit(EXIT_SUCCESS); } } else { if (map_type != CELL_TYPE) G_warning(_("The map is floating point! Ignoring cats list, using vals list")); else { /* integer map */ for (i = 0; parm.cats->answers[i]; i++) if (!scan_cats(parm.cats->answers[i], &x, &y)) { G_usage(); exit(EXIT_FAILURE); } for (i = 0; parm.cats->answers[i]; i++) { scan_cats(parm.cats->answers[i], &x, &y); while (x <= y) print_label(x++); } exit(EXIT_SUCCESS); } } if (parm.vals->answer == NULL) G_fatal_error(_("vals argument is required for floating point map!")); for (i = 0; parm.vals->answers[i]; i++) if (!scan_vals(parm.vals->answers[i], &dx)) { G_usage(); exit(EXIT_FAILURE); } for (i = 0; parm.vals->answers[i]; i++) { scan_vals(parm.vals->answers[i], &dx); print_d_label(dx); } exit(EXIT_SUCCESS); }
/* ************************************************************************* */ int main(int argc, char *argv[]) { char *output = NULL; RASTER3D_Region region; struct Cell_head window2d; struct Cell_head default_region; FILE *fp = NULL; struct GModule *module; int dp, i, changemask = 0; int rows, cols; const char *mapset, *name; double scale = 1.0, llscale = 1.0; input_maps *in; /* Initialize GRASS */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster3d")); G_add_keyword(_("export")); G_add_keyword(_("voxel")); G_add_keyword("VTK"); module->description = _("Converts 3D raster maps into the VTK-ASCII format."); /* Get parameters from user */ set_params(); /* Have GRASS get inputs */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); /*The precision of the output */ if (param.decimals->answer) { if (sscanf(param.decimals->answer, "%d", &dp) != 1) G_fatal_error(_("failed to interpret dp as an integer")); if (dp > 20 || dp < 0) G_fatal_error(_("dp has to be from 0 to 20")); } else { dp = 8; /*This value is taken from the lib settings in G_format_easting */ } /*Check the input */ check_input_maps(); /*Correct the coordinates, so the precision of VTK is not hurt :( */ if (param.coorcorr->answer) { /*Get the default region for coordiante correction */ G_get_default_window(&default_region); /*Use the center of the current region as extent */ y_extent = (default_region.north + default_region.south) / 2; x_extent = (default_region.west + default_region.east) / 2; } else { x_extent = 0; y_extent = 0; } /*open the output */ if (param.output->answer) { fp = fopen(param.output->answer, "w"); if (fp == NULL) { perror(param.output->answer); G_usage(); exit(EXIT_FAILURE); } } else fp = stdout; /* Figure out the region from the map */ Rast3d_init_defaults(); Rast3d_get_window(®ion); /*initiate the input mpas structure */ in = create_input_maps_struct(); /* read and compute the scale factor */ sscanf(param.elevscale->answer, "%lf", &scale); /*if LL projection, convert the elevation values to degrees */ if (param.scalell->answer && region.proj == PROJECTION_LL) { llscale = M_PI / (180) * 6378137; scale /= llscale; } /*Open the top and bottom file */ if (param.structgrid->answer) { /*Check if the g3d-region is equal to the 2d rows and cols */ rows = Rast_window_rows(); cols = Rast_window_cols(); /*If not equal, set the 2D windows correct */ if (rows != region.rows || cols != region.cols) { G_message(_("The 2D and 3D region settings are different. " "Using the 2D window settings to adjust the 2D part of the 3D region.")); G_get_set_window(&window2d); window2d.ns_res = region.ns_res; window2d.ew_res = region.ew_res; window2d.rows = region.rows; window2d.cols = region.cols; Rast_set_window(&window2d); } /*open top */ mapset = NULL; name = NULL; name = param.top->answer; mapset = G_find_raster2(name, ""); in->top = open_input_map(name, mapset); in->topMapType = Rast_get_map_type(in->top); /*open bottom */ mapset = NULL; name = NULL; name = param.bottom->answer; mapset = G_find_raster2(name, ""); in->bottom = open_input_map(name, mapset); in->bottomMapType = Rast_get_map_type(in->bottom); /* Write the vtk-header and the points */ if (param.point->answer) { write_vtk_structured_grid_header(fp, output, region); write_vtk_points(in, fp, region, dp, 1, scale); } else { write_vtk_unstructured_grid_header(fp, output, region); write_vtk_points(in, fp, region, dp, 0, scale); write_vtk_unstructured_grid_cells(fp, region); } Rast_close(in->top); in->top = -1; Rast_close(in->bottom); in->bottom = -1; } else { /* Write the structured point vtk-header */ write_vtk_structured_point_header(fp, output, region, dp, scale); } /*Write the normal VTK data (cell or point data) */ /*Loop over all 3d input maps! */ if (param.input->answers != NULL) { for (i = 0; param.input->answers[i] != NULL; i++) { G_debug(3, "Open 3D raster map <%s>", param.input->answers[i]); /*Open the map */ in->map = Rast3d_open_cell_old(param.input->answers[i], G_find_raster3d(param.input->answers[i], ""), ®ion, RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT); if (in->map == NULL) { G_warning(_("Unable to open 3D raster map <%s>"), param.input->answers[i]); fatal_error(" ", in); } /*if requested set the Mask on */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) { changemask = 0; if (Rast3d_mask_is_off(in->map)) { Rast3d_mask_on(in->map); changemask = 1; } } } /* Write the point or cell data */ write_vtk_data(fp, in->map, region, param.input->answers[i], dp); /*We set the Mask off, if it was off before */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) if (Rast3d_mask_is_on(in->map) && changemask) Rast3d_mask_off(in->map); } /* Close the 3d raster map */ if (!Rast3d_close(in->map)) { in->map = NULL; fatal_error(_("Unable to close 3D raster map, the VTK file may be incomplete"), in); } in->map = NULL; } } /*Write the RGB voxel data */ open_write_rgb_maps(in, region, fp, dp); open_write_vector_maps(in, region, fp, dp); /*Close the output file */ if (param.output->answer && fp != NULL) if (fclose(fp)) fatal_error(_("Unable to close VTK-ASCII file"), in); /*close all open maps and free memory */ release_input_maps_struct(in); return 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); }
void Init() { struct Cell_head Region; int Count; int FD, row, col; double MinRes; G_debug(2, "Init()"); Rs = Rast_window_rows(); Cs = Rast_window_cols(); G_get_set_window(&Region); EW = Region.ew_res; NS = Region.ns_res; if (EW < NS) MinRes = EW; else MinRes = NS; CellBuffer = Rast_allocate_c_buf(); /* Out = FlagCreate( Rs, Cs); */ Out = (CELL **) G_malloc(sizeof(CELL *) * Rs); for (row = 0; row < Rs; row++) { Out[row] = Rast_allocate_c_buf(); Rast_zero_buf(Out[row], CELL_TYPE); } Cells = FlagCreate(Rs, Cs); CellCount = 0; if (G_find_raster2("MASK", G_mapset())) { FD = Rast_open_old("MASK", G_mapset()); { for (row = 0; row < Rs; row++) { Rast_get_c_row_nomask(FD, CellBuffer, row); for (col = 0; col < Cs; col++) { if (CellBuffer[col]) { FLAG_SET(Cells, row, col); CellCount++; } } } Rast_close(FD); } } else { for (row = 0; row < Rs; row++) { for (col = 0; col < Cs; col++) { FLAG_SET(Cells, row, col); } } CellCount = Rs * Cs; } sscanf(Distance->answer, "%lf", &MaxDist); if (MaxDist < 0.0) G_fatal_error(_("Distance must be >= 0.0")); G_debug(3, "(MaxDist):%.12lf", MaxDist); MaxDistSq = MaxDist * MaxDist; if (!SeedStuff->answer) { Seed = (int)getpid(); } else { sscanf(SeedStuff->answer, "%d", &(Seed)); } if (Seed > SEED_MAX) { Seed = Seed % SEED_MAX; } else if (Seed < SEED_MIN) { while (Seed < SEED_MIN) Seed += SEED_MAX - SEED_MIN; } G_message(_("Generating raster map <%s>..."), Output->answer); DoNext = (CELLSORTER *) G_malloc(CellCount * sizeof(CELLSORTER)); Count = 0; for (row = 0; row < Rs; row++) { G_percent(row, Rs, 2); for (col = 0; col < Cs; col++) { if (0 != FlagGet(Cells, row, col)) { DoNext[Count].R = row; DoNext[Count].C = col; DoNext[Count].Value = GasDev(); if (++Count == CellCount) { row = Rs; col = Cs; } } } } G_percent(1, 1, 1); qsort(DoNext, CellCount, sizeof(CELLSORTER), comp_array); }
/*! \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; }
/*! \brief Get categories/labels Formats label as in d.what.rast -> (catval) catlabel \param filename raster map name \param drow \param dcol \param catstr category string \return 1 on success \return 0 on failure */ int Gs_get_cat_label(const char *filename, int drow, int dcol, char *catstr) { struct Categories cats; const char *mapset; CELL *buf; DCELL *dbuf; RASTER_MAP_TYPE map_type; int fd = -1; if ((mapset = G_find_raster2(filename, "")) == NULL) { G_warning(_("Raster map <%s> not found"), filename); return 0; } if (-1 != Rast_read_cats(filename, mapset, &cats)) { fd = Rast_open_old(filename, mapset); map_type = Rast_get_map_type(fd); if (map_type == CELL_TYPE) { buf = Rast_allocate_c_buf(); Rast_get_c_row(fd, buf, drow); if (Rast_is_c_null_value(&buf[dcol])) { sprintf(catstr, "(NULL) %s", Rast_get_c_cat(&buf[dcol], &cats)); } else { sprintf(catstr, "(%d) %s", buf[dcol], Rast_get_c_cat(&buf[dcol], &cats)); } G_free(buf); } else { /* fp map */ dbuf = Rast_allocate_d_buf(); Rast_get_d_row(fd, dbuf, drow); if (Rast_is_d_null_value(&dbuf[dcol])) { sprintf(catstr, "(NULL) %s", Rast_get_d_cat(&dbuf[dcol], &cats)); } else { sprintf(catstr, "(%g) %s", dbuf[dcol], Rast_get_d_cat(&dbuf[dcol], &cats)); } G_free(dbuf); } } else { strcpy(catstr, "no category label"); return 0; } /* TODO: may want to keep these around for multiple queries */ Rast_free_cats(&cats); if (fd >= 0) Rast_close(fd); return (1); }