void Rast_align_window(struct Cell_head *window, const struct Cell_head *ref) { int preserve; window->ns_res = ref->ns_res; window->ew_res = ref->ew_res; window->zone = ref->zone; window->proj = ref->proj; preserve = window->proj == PROJECTION_LL && window->east == (window->west + 360); window->south = Rast_row_to_northing(ceil(Rast_northing_to_row(window->south, ref)), ref); window->north = Rast_row_to_northing(floor(Rast_northing_to_row(window->north, ref)), ref); window->east = Rast_col_to_easting(ceil(Rast_easting_to_col(window->east, ref)), ref); window->west = Rast_col_to_easting(floor(Rast_easting_to_col(window->west, ref)), ref); if (window->proj == PROJECTION_LL) { while (window->north > 90.0) window->north -= window->ns_res; while (window->south < -90.0) window->south += window->ns_res; if (preserve) window->east = window->west + 360; else while (window->east - window->west > 360.0) window->east -= window->ew_res; } G_adjust_Cell_head(window, 0, 0); }
int zoom_pan_update(void *closure, int sxn, int syn, int button) { G_debug(2, "button = %d x = %d y = %d", button, sxn, syn); if (button == 3) return 1; if (button == 1) { double x = D_d_to_u_col(sxn); double y = D_d_to_u_row(syn); double dx = (window.east - window.west) / 2; double dy = (window.north - window.south) / 2; window.north = y + dy; window.south = y - dy; window.east = x + dx; window.west = x - dx; G_debug(2, "w = %f e = %f n = %f s = %f", window.west, window.east, window.north, window.south); G_adjust_Cell_head(&window, 0, 0); G_put_window(&window); G_set_window(&window); display_redraw(); } return 0; }
int main( int argc, char **argv ) { char *mapset; char *name; int fp; struct GModule *module; struct Option *map; struct Option *win; struct Cell_head window; /* Initialize the GIS calls */ G_gisinit( argv[0] ); module = G_define_module(); module->keywords = ( "display, raster" ); module->description = ( "Output raster map layers in a format suitable for display in QGIS" ); map = G_define_standard_option( G_OPT_R_MAP ); map->description = ( "Raster map to be displayed" ); win = G_define_option(); win->key = "window"; win->type = TYPE_DOUBLE; win->multiple = YES; win->description = "xmin,ymin,xmax,ymax,ncols,nrows"; if ( G_parser( argc, argv ) ) exit( EXIT_FAILURE ); name = map->answer; /* Make sure map is available */ mapset = G_find_cell2( name, "" ); if ( mapset == NULL ) G_fatal_error(( "Raster map <%s> not found" ), name ); /* It can happen that GRASS data set is 'corrupted' and zone differs in WIND and * cellhd, and G_open_cell_old fails, so it is better to read window from map */ /* G_get_window( &window ); */ G_get_cellhd( name, mapset, &window ); window.west = atof( win->answers[0] ); window.south = atof( win->answers[1] ); window.east = atof( win->answers[2] ); window.north = atof( win->answers[3] ); window.cols = atoi( win->answers[4] ); window.rows = atoi( win->answers[5] ); G_adjust_Cell_head( &window, 1, 1 ); G_set_window( &window ); fp = G_raster_map_is_fp( name, mapset ); /* use DCELL even if the map is FCELL */ if ( fp ) display( name, mapset, DCELL_TYPE ); else display( name, mapset, CELL_TYPE ); exit( EXIT_SUCCESS ); }
void QgsGrassRegion::adjust() { int rc = 0; if ( mRowsColsRadio->isChecked() ) { rc = 1; } G_adjust_Cell_head( &mWindow, rc, rc ); }
/*! \brief Establishes 'window' as the current working window. \param window window to become operative window */ void G_set_window(struct Cell_head *window) { /* adjust window, check for valid window */ G_adjust_Cell_head(window, 0, 0); /* copy the window to the current window */ G__.window = *window; G__.window_set = 1; }
int zoom_window_update(void *closure, int sxn, int syn, int button) { struct zoom_window *zw = closure; if (zw->mode == 1) { i_prompt_buttons(_("1. corner"), _("2. corner"), _("Quit")); zw->next_mode = 2; } G_debug(2, "button = %d x = %d y = %d", button, sxn, syn); if (button == 3) return 1; if (zw->mode == 2 && button == 2) { double x1 = D_d_to_u_col(zw->sxo); double y1 = D_d_to_u_row(zw->syo); double x2 = D_d_to_u_col(sxn); double y2 = D_d_to_u_row(syn); G_debug(2, "x1 = %f x2 = %f y1 = %f y2 = %f", x1, x2, y1, y2); window.north = y1 > y2 ? y1 : y2; window.south = y1 < y2 ? y1 : y2; window.west = x1 < x2 ? x1 : x2; window.east = x1 > x2 ? x1 : x2; G_debug(2, "w = %f e = %f n = %f s = %f", window.west, window.east, window.north, window.south); G_adjust_Cell_head(&window, 0, 0); G_put_window(&window); G_set_window(&window); display_redraw(); i_prompt_buttons(_("1. corner"), _("1. corner"), _("Quit")); zw->next_mode = 1; } zw->sxo = sxn; zw->syo = syn; zw->mode = zw->next_mode; set_mode(zw->mode == 2 ? MOUSE_BOX : MOUSE_POINT); set_location(zw->sxo, zw->syo); return 0; }
void QgsGrassRegion::adjust() { mButtonBox->button( QDialogButtonBox::Apply )->setDisabled( false ); int rc = 0; if ( mRowsColsRadio->isChecked() ) { rc = 1; } G_TRY { G_adjust_Cell_head( &mWindow, rc, rc ); } G_CATCH( QgsGrass::Exception &e ) { QgsGrass::warning( e ); mButtonBox->button( QDialogButtonBox::Apply )->setDisabled( true ); }
/* Zoom - in / out (centre unchanged) */ int zoom_centre(double factor) { double xc, yc, dx, dy; G_debug(2, "zoom_centre()"); driver_open(); G_debug(2, "1 n = %f s = %f", window.north, window.south); dx = (window.east - window.west) / 2; dy = (window.north - window.south) / 2; xc = (window.east + window.west) / 2; yc = (window.north + window.south) / 2; G_debug(2, " yc = %f dy = %f", yc, dy); window.north = yc + dy * factor; window.south = yc - dy * factor; window.east = xc + dx * factor; window.west = xc - dx * factor; G_debug(2, "2 n = %f s = %f", window.north, window.south); G_adjust_Cell_head(&window, 0, 0); G_debug(2, "3 n = %f s = %f", window.north, window.south); G_put_window(&window); G_set_window(&window); display_redraw(); driver_close(); G_debug(3, "zoom_centre(): End"); return 1; }
int main(int argc, char **argv) { struct GModule *module; struct Option *voutput_opt, *routput_opt, *color_output_opt, *ply_opt, *zrange_opt, *trim_opt, *rotate_Z_opt, *smooth_radius_opt, *region_opt, *raster_opt, *zexag_opt, *resolution_opt, *method_opt, *calib_matrix_opt, *numscan_opt, *trim_tolerance_opt, *contours_map, *contours_step_opt, *draw_opt, *draw_vector_opt, *draw_threshold_opt; struct Flag *loop_flag, *calib_flag, *equalize_flag; struct Map_info Map; struct line_pnts *Points; struct line_cats *Cats; int cat = 1; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("vector")); G_add_keyword(_("scan")); G_add_keyword(_("points")); module->label = _("Imports a point cloud from Kinect v2"); module->description = _("Imports a point cloud from Kinect v2"); routput_opt = G_define_standard_option(G_OPT_R_OUTPUT); routput_opt->guisection = _("Output"); routput_opt->required = NO; resolution_opt = G_define_option(); resolution_opt->key = "resolution"; resolution_opt->type = TYPE_DOUBLE; resolution_opt->required = NO; resolution_opt->answer = "0.002"; resolution_opt->label = _("Raster resolution"); resolution_opt->description = _("Recommended values between 0.001-0.003"); resolution_opt->guisection = _("Output"); color_output_opt = G_define_standard_option(G_OPT_R_BASENAME_OUTPUT); color_output_opt->key = "color_output"; color_output_opt->description = _("Basename for color output"); color_output_opt->guisection = _("Output"); color_output_opt->required = NO; voutput_opt = G_define_standard_option(G_OPT_V_OUTPUT); voutput_opt->required = NO; voutput_opt->key = "vector"; voutput_opt->guisection = _("Output"); ply_opt = G_define_standard_option(G_OPT_F_OUTPUT); ply_opt->required = NO; ply_opt->key = "ply"; ply_opt->description = _("Name of output binary PLY file"); ply_opt->guisection = _("Output"); zrange_opt = G_define_option(); zrange_opt->key = "zrange"; zrange_opt->type = TYPE_DOUBLE; zrange_opt->required = NO; zrange_opt->key_desc = "min,max"; zrange_opt->label = _("Filter range for z data (min,max)"); zrange_opt->description = _("Z is distance from scanner in cm"); zrange_opt->guisection = _("Filter"); trim_opt = G_define_option(); trim_opt->key = "trim"; trim_opt->type = TYPE_DOUBLE; trim_opt->required = NO; trim_opt->key_desc = "N,S,E,W"; trim_opt->description = _("Clip box from center in cm"); trim_opt->guisection = _("Filter"); trim_tolerance_opt = G_define_option(); trim_tolerance_opt->key = "trim_tolerance"; trim_tolerance_opt->type = TYPE_DOUBLE; trim_tolerance_opt->required = NO; trim_tolerance_opt->description = _("Influences how much are model sides trimmed automatically, " " should be higher for rectangular models"); trim_tolerance_opt->label = _("Trim tolerance between 0 and 1"); trim_tolerance_opt->options = "0-1"; trim_tolerance_opt->guisection = _("Filter"); rotate_Z_opt = G_define_option(); rotate_Z_opt->key = "rotate"; rotate_Z_opt->type = TYPE_DOUBLE; rotate_Z_opt->required = NO; rotate_Z_opt->answer = "0"; rotate_Z_opt->description = _("Rotate along Z axis"); rotate_Z_opt->guisection = _("Georeferencing"); smooth_radius_opt = G_define_option(); smooth_radius_opt->key = "smooth_radius"; smooth_radius_opt->type = TYPE_DOUBLE; smooth_radius_opt->required = NO; smooth_radius_opt->label = _("Smooth radius"); smooth_radius_opt->description = _("Recommended values between 0.006-0.009"); region_opt = G_define_option(); region_opt->key = "region"; region_opt->key_desc = "name"; region_opt->required = NO; region_opt->multiple = NO; region_opt->type = TYPE_STRING; region_opt->description = _("Region of the resulting raster"); region_opt->gisprompt = "old,windows,region"; region_opt->guisection = _("Georeferencing"); raster_opt = G_define_standard_option(G_OPT_R_MAP); raster_opt->key = "raster"; raster_opt->required = NO; raster_opt->multiple = NO; raster_opt->description = _("Match resulting raster to this raster map"); raster_opt->guisection = _("Georeferencing"); zexag_opt = G_define_option(); zexag_opt->key = "zexag"; zexag_opt->type = TYPE_DOUBLE; zexag_opt->required = NO; zexag_opt->required = NO; zexag_opt->answer = "1"; zexag_opt->description = _("Vertical exaggeration"); zexag_opt->guisection = _("Georeferencing"); method_opt = G_define_option(); method_opt->key = "method"; method_opt->multiple = NO; method_opt->required = NO; method_opt->type = TYPE_STRING; method_opt->options = "interpolation,mean,min,max"; method_opt->answer = "mean"; method_opt->description = _("Surface reconstruction method"); calib_matrix_opt = G_define_option(); calib_matrix_opt->key = "calib_matrix"; calib_matrix_opt->multiple = YES; calib_matrix_opt->type = TYPE_DOUBLE; calib_matrix_opt->required = NO; calib_matrix_opt->description = _("Calibration matrix"); calib_matrix_opt->guisection = _("Calibration"); numscan_opt = G_define_option(); numscan_opt->answer = "1"; numscan_opt->key = "numscan"; numscan_opt->type = TYPE_INTEGER; numscan_opt->description = _("Number of scans to intergrate"); numscan_opt->required = NO; contours_map = G_define_standard_option(G_OPT_V_MAP); contours_map->key = "contours"; contours_map->required = NO; contours_map->description = _("Name of contour vector map"); contours_step_opt = G_define_option(); contours_step_opt->key = "contours_step"; contours_step_opt->description = _("Increment between contour levels"); contours_step_opt->type = TYPE_DOUBLE; contours_step_opt->required = NO; equalize_flag = G_define_flag(); equalize_flag->key = 'e'; equalize_flag->description = _("Histogram equalized color table"); loop_flag = G_define_flag(); loop_flag->key = 'l'; loop_flag->description = _("Keep scanning in a loop"); calib_flag = G_define_flag(); calib_flag->key = 'c'; calib_flag->description = _("Calibrate"); calib_flag->guisection = _("Calibration"); draw_opt = G_define_option(); draw_opt->key = "draw"; draw_opt->description = _("Draw with laser pointer"); draw_opt->type = TYPE_STRING; draw_opt->required = NO; draw_opt->options = "point,line,area"; draw_opt->answer = "point"; draw_opt->guisection = _("Drawing"); draw_threshold_opt = G_define_option(); draw_threshold_opt->key = "draw_threshold"; draw_threshold_opt->description = _("Brightness threshold for detecting laser pointer"); draw_threshold_opt->type = TYPE_INTEGER; draw_threshold_opt->required = YES; draw_threshold_opt->answer = "760"; draw_threshold_opt->guisection = _("Drawing"); draw_vector_opt = G_define_standard_option(G_OPT_V_OUTPUT); draw_vector_opt->key = "draw_output"; draw_vector_opt->guisection = _("Drawing"); draw_vector_opt->required = NO; G_option_required(calib_flag, routput_opt, voutput_opt, ply_opt, draw_vector_opt, NULL); G_option_requires(routput_opt, resolution_opt, NULL); G_option_requires(color_output_opt, resolution_opt, NULL); G_option_requires(contours_map, contours_step_opt, routput_opt, NULL); G_option_requires(equalize_flag, routput_opt, NULL); if (G_parser(argc, argv)) exit(EXIT_FAILURE); // initailization of variables double resolution = 0.002; if (resolution_opt->answer) resolution = atof(resolution_opt->answer); double smooth_radius = 0.008; if (smooth_radius_opt->answer) smooth_radius = atof(smooth_radius_opt->answer); char* routput = NULL; if (routput_opt->answer) routput = routput_opt->answer; /* parse zrange */ double zrange_min, zrange_max; if (zrange_opt->answer != NULL) { zrange_min = atof(zrange_opt->answers[0])/100; zrange_max = atof(zrange_opt->answers[1])/100; } /* parse trim */ double clip_N, clip_S, clip_E, clip_W; if (trim_opt->answer != NULL) { clip_N = atof(trim_opt->answers[0])/100; clip_S = atof(trim_opt->answers[1])/100; clip_E = atof(trim_opt->answers[2])/100; clip_W = atof(trim_opt->answers[3])/100; } double trim_tolerance; if (trim_tolerance_opt->answer) trim_tolerance = atof(trim_tolerance_opt->answer); double angle = pcl::deg2rad(atof(rotate_Z_opt->answer) + 180); double zexag = atof(zexag_opt->answer); Eigen::Matrix4f transform_matrix; if (calib_matrix_opt->answer) { transform_matrix = read_matrix(calib_matrix_opt); } char *method = method_opt->answer; int numscan = atoi(numscan_opt->answer); char *color_output = color_output_opt->answer; char *voutput = voutput_opt->answer; char *ply = ply_opt->answer; char *contours_output = contours_map->answer; double contours_step; if (contours_output) contours_step = atof(contours_step_opt->answer); bool use_equalized = false; if (equalize_flag->answer) use_equalized = true; // drawing int vect_type; get_draw_type(draw_opt->answer, vect_type); int draw_threshold = atoi(draw_threshold_opt->answer); char* draw_output = NULL; if (draw_vector_opt->answer) draw_output = draw_vector_opt->answer; std::vector<double> draw_x; std::vector<double> draw_y; std::vector<double> draw_z; bool drawing = false; unsigned int last_detected_loop_count = 1e6; struct Map_info Map_draw; struct line_pnts *Points_draw; struct line_cats *Cats_draw; Points_draw = Vect_new_line_struct(); Cats_draw = Vect_new_cats_struct(); Points = Vect_new_line_struct(); Cats = Vect_new_cats_struct(); pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>(512, 424)); pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_filtered_pass (new pcl::PointCloud<pcl::PointXYZRGB>(512, 424)); struct bound_box bbox; struct Cell_head cellhd, window; double offset, scale; bool region3D = false; bool paused = false; update_input_region(raster_opt->answer, region_opt->answer, window, offset, region3D); K2G k2g(OPENGL); k2g.getCloud(); cloud->sensor_orientation_.w() = 0.0; cloud->sensor_orientation_.x() = 1.0; cloud->sensor_orientation_.y() = 0.0; cloud->sensor_orientation_.z() = 0.0; int j = 0; // get terminating signals signal(SIGTERM, terminate); signal(SIGINT, terminate); signal(SIGUSR1, signal_read_new_input); while (j < 1) { if (signaled == 1) { break; } if (signal_new_input == 1) { signal_new_input = 0; read_new_input(routput, zrange_min, zrange_max, clip_N, clip_S, clip_E, clip_W, trim_tolerance, angle, zexag, method, numscan, smooth_radius, resolution, use_equalized, window, offset, region3D, color_output, voutput, ply, contours_output, contours_step, vect_type, draw_threshold, draw_output, paused); } cloud = k2g.getCloud(); if (paused) { continue; } if (!drawing) { for (int s = 0; s < numscan - 1; s++) *(cloud) += *(k2g.getCloud()); } // remove invalid points std::vector<int> index_nans; pcl::removeNaNFromPointCloud(*cloud, *cloud, index_nans); // calibration if(calib_flag->answer) { calibrate(cloud); j++; continue; } // rotation of the point cloud based on calibration if (calib_matrix_opt->answer) { rotate_with_matrix(cloud, transform_matrix); } // trim Z if (zrange_opt->answer != NULL) { trim_Z(cloud, zrange_min, zrange_max); } // rotation Z rotate_Z(cloud, angle); // specify bounding box from center if (trim_opt->answer != NULL) { clipNSEW(cloud, clip_N, clip_S, clip_E, clip_W); } // drawing if (draw_output) { int maxbright = 0; int maxbright_idx = 0; for (int i=0; i < cloud->points.size(); i++) { Eigen::Vector3i rgbv = cloud->points[i].getRGBVector3i(); int sum = rgbv[0] + rgbv[1] + rgbv[2]; if (sum > maxbright) { maxbright = sum; maxbright_idx = i; } } if (maxbright >= draw_threshold) { drawing = true; draw_x.push_back(cloud->points[maxbright_idx].x); draw_y.push_back(cloud->points[maxbright_idx].y); draw_z.push_back(cloud->points[maxbright_idx].z); last_detected_loop_count = 0; continue; } else { last_detected_loop_count++; if (last_detected_loop_count <= 2) { continue; } } } pcl::StatisticalOutlierRemoval<pcl::PointXYZRGB> sor; sor.setInputCloud(cloud); sor.setMeanK(20); sor.setStddevMulThresh(0.5); sor.filter(*cloud_filtered_pass); cloud_filtered_pass.swap (cloud); if (trim_tolerance_opt->answer != NULL) { double autoclip_N, autoclip_S, autoclip_E, autoclip_W; autotrim(cloud, autoclip_N, autoclip_S, autoclip_E, autoclip_W, trim_tolerance); if (autoclip_E > 0 || autoclip_N > 0 || autoclip_S > 0 || autoclip_W > 0) trimNSEW(cloud, autoclip_N, autoclip_S, autoclip_E, autoclip_W); } if (drawing) { // get Z scaling getMinMax(*cloud, bbox); if ((vect_type == GV_AREA && draw_x.size() > 2) || (vect_type == GV_LINE && draw_x.size() > 1) || (vect_type == GV_POINT && draw_x.size() > 0)) { save_vector(draw_output, Map_draw, Points_draw, Cats_draw, bbox, window, draw_x, draw_y, draw_z, vect_type, offset, zexag); } else G_warning(_("Tolopogically incorrect vector feature")); drawing = false; draw_x.clear(); draw_y.clear(); draw_z.clear(); last_detected_loop_count = 1e6; } if (voutput|| routput || ply || color_output) { if (smooth_radius_opt->answer) smooth(cloud, smooth_radius); // get Z scaling getMinMax(*cloud, bbox); scale = ((window.north - window.south) / (bbox.N - bbox.S) + (window.east - window.west) / (bbox.E - bbox.W)) / 2; } // write to vector if (voutput|| (routput && strcmp(method, "interpolation") == 0)) { double z; if (voutput) { if (Vect_open_new(&Map, voutput, WITH_Z) < 0) G_fatal_error(_("Unable to create temporary vector map <%s>"), voutput); } else { if (Vect_open_tmp_new(&Map, routput, WITH_Z) < 0) G_fatal_error(_("Unable to create temporary vector map <%s>"), routput); } for (int i=0; i < cloud->points.size(); i++) { Vect_reset_line(Points); Vect_reset_cats(Cats); if (region3D) z = (cloud->points[i].z + zrange_max) * scale / zexag + offset; else z = (cloud->points[i].z - bbox.B) * scale / zexag + offset; Vect_append_point(Points, cloud->points[i].x, cloud->points[i].y, z); Vect_cat_set(Cats, 1, cat); Vect_write_line(&Map, GV_POINT, Points, Cats); } if (strcmp(method, "interpolation") == 0) { // interpolate Vect_rewind(&Map); interpolate(&Map, routput, 20, 2, 50, 40, -1, &bbox, resolution); } Vect_close(&Map); } if (routput || color_output) { if (routput) { if (strcmp(method, "interpolation") != 0) { binning(cloud, routput, &bbox, resolution, scale, zexag, region3D ? -zrange_max : bbox.B, offset, method); } Rast_get_cellhd(routput, "", &cellhd); } if (color_output) { binning_color(cloud, color_output, &bbox, resolution); Rast_get_cellhd(get_color_name(color_output, "r"), "", &cellhd); } // georeference horizontally window.rows = cellhd.rows; window.cols = cellhd.cols; G_adjust_Cell_head(&window, 1, 1); cellhd.north = window.north; cellhd.south = window.south; cellhd.east = window.east; cellhd.west = window.west; if (routput) Rast_put_cellhd(routput, &cellhd); if (color_output) { char* output_r = get_color_name(color_output, "r"); char* output_g = get_color_name(color_output, "g"); char* output_b = get_color_name(color_output, "b"); Rast_put_cellhd(output_r, &cellhd); Rast_put_cellhd(output_g, &cellhd); Rast_put_cellhd(output_b, &cellhd); } set_default_color(routput); if (contours_output) { contours(routput, contours_output, atof(contours_step_opt->answer)); } if (use_equalized) { equalized(routput); } } // write to PLY if (ply) { pcl::PLYWriter writer; for (int i=0; i < cloud->points.size(); i++) { if (region3D) cloud->points[i].z = (cloud->points[i].z + zrange_max) * scale / zexag + offset; else cloud->points[i].z = (cloud->points[i].z - bbox.B) * scale / zexag + offset; cloud->points[i].x = (cloud->points[i].x - bbox.W) * scale + window.west; cloud->points[i].y = (cloud->points[i].y - bbox.S) * scale + window.south; } writer.write<pcl::PointXYZRGB>(ply, *cloud, true, true); } if (!loop_flag->answer) j++; } k2g.shutDown(); return EXIT_SUCCESS; }
int E_edit_cellhd(struct Cell_head *cellhd, int type) { char ll_north[20]; char ll_south[20]; char ll_east[20]; char ll_west[20]; char ll_nsres[20]; char ll_ewres[20]; char ll_def_north[20]; char ll_def_south[20]; char ll_def_east[20]; char ll_def_west[20]; char ll_def_ewres[20]; char ll_def_nsres[20]; char projection[80]; char **screen; struct Cell_head def_wind; double north, south, east, west; double nsres, ewres; char buf[64], buf2[30], *p; short ok; int line; char *prj; char *err; if (type == AS_CELLHD && (cellhd->rows <= 0 || cellhd->cols <= 0)) { G_message("E_edit_cellhd() - programmer error"); G_message(" ** rows and cols must be positive **"); return -1; } if (type != AS_DEF_WINDOW) { if (G_get_default_window(&def_wind) != 1) return -1; if (cellhd->proj < 0) { cellhd->proj = def_wind.proj; cellhd->zone = def_wind.zone; } else if (cellhd->zone < 0) cellhd->zone = def_wind.zone; } prj = G__projection_name(cellhd->proj); if (!prj) prj = "** unknown **"; sprintf(projection, "%d (%s)", cellhd->proj, prj); if (type != AS_DEF_WINDOW) { if (cellhd->west >= cellhd->east || cellhd->south >= cellhd->north) { cellhd->north = def_wind.north; cellhd->south = def_wind.south; cellhd->west = def_wind.west; cellhd->east = def_wind.east; if (type != AS_CELLHD) { cellhd->ew_res = def_wind.ew_res; cellhd->ns_res = def_wind.ns_res; cellhd->rows = def_wind.rows; cellhd->cols = def_wind.cols; } } if (cellhd->proj != def_wind.proj) { if (type == AS_CELLHD) G_message ("header projection %d differs from default projection %d", cellhd->proj, def_wind.proj); else G_message ("region projection %d differs from default projection %d", cellhd->proj, def_wind.proj); if (!G_yes("do you want to make them match? ", 1)) return -1; cellhd->proj = def_wind.proj; cellhd->zone = def_wind.zone; } if (cellhd->zone != def_wind.zone) { if (type == AS_CELLHD) G_message("header zone %d differs from default zone %d", cellhd->zone, def_wind.zone); else G_message("region zone %d differs from default zone %d", cellhd->zone, def_wind.zone); if (!G_yes("do you want to make them match? ", 1)) return -1; cellhd->zone = def_wind.zone; } *ll_def_north = 0; *ll_def_south = 0; *ll_def_east = 0; *ll_def_west = 0; *ll_def_ewres = 0; *ll_def_nsres = 0; format_northing(def_wind.north, ll_def_north, def_wind.proj); format_northing(def_wind.south, ll_def_south, def_wind.proj); format_easting(def_wind.east, ll_def_east, def_wind.proj); format_easting(def_wind.west, ll_def_west, def_wind.proj); format_resolution(def_wind.ew_res, ll_def_ewres, def_wind.proj); format_resolution(def_wind.ns_res, ll_def_nsres, def_wind.proj); } *ll_north = 0; *ll_south = 0; *ll_east = 0; *ll_west = 0; *ll_ewres = 0; *ll_nsres = 0; format_northing(cellhd->north, ll_north, cellhd->proj); format_northing(cellhd->south, ll_south, cellhd->proj); format_easting(cellhd->east, ll_east, cellhd->proj); format_easting(cellhd->west, ll_west, cellhd->proj); format_resolution(cellhd->ew_res, ll_ewres, cellhd->proj); format_resolution(cellhd->ns_res, ll_nsres, cellhd->proj); while (1) { ok = 1; /* List window options on the screen for the user to answer */ switch (type) { case AS_CELLHD: screen = cellhd_screen; break; case AS_DEF_WINDOW: screen = def_window_screen; break; default: screen = window_screen; break; } V_clear(); line = 0; while (*screen) V_line(line++, *screen++); /* V_ques ( variable, type, row, col, length) ; */ V_ques(ll_north, 's', 6, 36, 10); V_ques(ll_south, 's', 10, 36, 10); V_ques(ll_west, 's', 9, 12, 10); V_ques(ll_east, 's', 9, 52, 10); if (type != AS_CELLHD) { V_ques(ll_ewres, 's', 18, 48, 10); V_ques(ll_nsres, 's', 19, 48, 10); } if (type != AS_DEF_WINDOW) { V_const(ll_def_north, 's', 3, 36, 10); V_const(ll_def_south, 's', 13, 36, 10); V_const(ll_def_west, 's', 9, 1, 10); V_const(ll_def_east, 's', 9, 65, 10); if (type != AS_CELLHD) { V_const(ll_def_ewres, 's', 18, 21, 10); V_const(ll_def_nsres, 's', 19, 21, 10); } } V_const(projection, 's', 15, 23, (int)strlen(projection)); V_const(&cellhd->zone, 'i', 15, 60, 3); V_intrpt_ok(); if (!V_call()) return -1; G_squeeze(ll_north); G_squeeze(ll_south); G_squeeze(ll_east); G_squeeze(ll_west); if (type != AS_CELLHD) { G_squeeze(ll_ewres); G_squeeze(ll_nsres); } if (!G_scan_northing(ll_north, &cellhd->north, cellhd->proj)) { G_warning("Illegal value for north: %s", ll_north); ok = 0; } if (!G_scan_northing(ll_south, &cellhd->south, cellhd->proj)) { G_warning("Illegal value for south: %s", ll_south); ok = 0; } if (!G_scan_easting(ll_east, &cellhd->east, cellhd->proj)) { G_warning("Illegal value for east: %s", ll_east); ok = 0; } if (!G_scan_easting(ll_west, &cellhd->west, cellhd->proj)) { G_warning("Illegal value for west: %s", ll_west); ok = 0; } if (type != AS_CELLHD) { if (!G_scan_resolution(ll_ewres, &cellhd->ew_res, cellhd->proj)) { G_warning("Illegal east-west resolution: %s", ll_ewres); ok = 0; } if (!G_scan_resolution(ll_nsres, &cellhd->ns_res, cellhd->proj)) { G_warning("Illegal north-south resolution: %s", ll_nsres); ok = 0; } } if (!ok) { hitreturn(); continue; } /* Adjust and complete the cell header */ north = cellhd->north; south = cellhd->south; east = cellhd->east; west = cellhd->west; nsres = cellhd->ns_res; ewres = cellhd->ew_res; if ((err = G_adjust_Cell_head(cellhd, type == AS_CELLHD, type == AS_CELLHD))) { G_message("%s", err); hitreturn(); continue; } if (type == AS_CELLHD) { nsres = cellhd->ns_res; ewres = cellhd->ew_res; } SHOW: fprintf(stderr, "\n\n"); G_message(" projection: %s", projection); G_message(" zone: %d", cellhd->zone); G_format_northing(cellhd->north, buf, cellhd->proj); G_format_northing(north, buf2, cellhd->proj); fprintf(stderr, " north: %s", buf); if (strcmp(buf, buf2) != 0) { ok = 0; fprintf(stderr, " (Changed to match resolution)"); } fprintf(stderr, "\n"); G_format_northing(cellhd->south, buf, cellhd->proj); G_format_northing(south, buf2, cellhd->proj); fprintf(stderr, " south: %s", buf); if (strcmp(buf, buf2) != 0) { ok = 0; fprintf(stderr, " (Changed to match resolution)"); } fprintf(stderr, "\n"); G_format_easting(cellhd->east, buf, cellhd->proj); G_format_easting(east, buf2, cellhd->proj); fprintf(stderr, " east: %s", buf); if (strcmp(buf, buf2) != 0) { ok = 0; fprintf(stderr, " (Changed to match resolution)"); } fprintf(stderr, "\n"); G_format_easting(cellhd->west, buf, cellhd->proj); G_format_easting(west, buf2, cellhd->proj); fprintf(stderr, " west: %s", buf); if (strcmp(buf, buf2) != 0) { ok = 0; fprintf(stderr, " (Changed to match resolution)"); } fprintf(stderr, "\n\n"); G_format_resolution(cellhd->ew_res, buf, cellhd->proj); G_format_resolution(ewres, buf2, cellhd->proj); fprintf(stderr, " e-w res: %s", buf); if (strcmp(buf, buf2) != 0) { ok = 0; fprintf(stderr, " (Changed to conform to grid)"); } fprintf(stderr, "\n"); G_format_resolution(cellhd->ns_res, buf, cellhd->proj); G_format_resolution(nsres, buf2, cellhd->proj); fprintf(stderr, " n-s res: %s", buf); if (strcmp(buf, buf2) != 0) { ok = 0; fprintf(stderr, " (Changed to conform to grid)"); } fprintf(stderr, "\n\n"); G_message(" total rows: %15d", cellhd->rows); G_message(" total cols: %15d", cellhd->cols); sprintf(buf, "%lf", (double)cellhd->rows * cellhd->cols); *(p = strchr(buf, '.')) = 0; G_insert_commas(buf); G_message(" total cells: %15s", buf); fprintf(stderr, "\n"); if (type != AS_DEF_WINDOW) { if (cellhd->north > def_wind.north) { G_warning("north falls outside the default region"); ok = 0; } if (cellhd->south < def_wind.south) { G_warning("south falls outside the default region"); ok = 0; } if (cellhd->proj != PROJECTION_LL) { if (cellhd->east > def_wind.east) { G_warning("east falls outside the default region"); ok = 0; } if (cellhd->west < def_wind.west) { G_warning("west falls outside the default region"); ok = 0; } } } ASK: fflush(stdin); if (type == AS_CELLHD) fprintf(stderr, "\nDo you accept this header? (y/n) [%s] > ", ok ? "y" : "n"); else fprintf(stderr, "\nDo you accept this region? (y/n) [%s] > ", ok ? "y" : "n"); if (!G_gets(buf)) goto SHOW; G_strip(buf); switch (*buf) { case 0: break; case 'y': case 'Y': ok = 1; break; case 'n': case 'N': ok = 0; break; default: goto ASK; } if (ok) return 0; } }
int main(int argc, char **argv) { char *mapname, /* ptr to name of output layer */ *setname, /* ptr to name of input mapset */ *ipolname; /* name of interpolation method */ int fdi, /* input map file descriptor */ fdo, /* output map file descriptor */ method, /* position of method in table */ permissions, /* mapset permissions */ cell_type, /* output celltype */ cell_size, /* size of a cell in bytes */ row, col, /* counters */ irows, icols, /* original rows, cols */ orows, ocols, have_colors, /* Input map has a colour table */ overwrite, /* Overwrite */ curr_proj; /* output projection (see gis.h) */ void *obuffer, /* buffer that holds one output row */ *obufptr; /* column ptr in output buffer */ struct cache *ibuffer; /* buffer that holds the input map */ func interpolate; /* interpolation routine */ double xcoord1, xcoord2, /* temporary x coordinates */ ycoord1, ycoord2, /* temporary y coordinates */ col_idx, /* column index in input matrix */ row_idx, /* row index in input matrix */ onorth, osouth, /* save original border coords */ oeast, owest, inorth, isouth, ieast, iwest; char north_str[30], south_str[30], east_str[30], west_str[30]; struct Colors colr; /* Input map colour table */ struct History history; struct pj_info iproj, /* input map proj parameters */ oproj; /* output map proj parameters */ struct Key_Value *in_proj_info, /* projection information of */ *in_unit_info, /* input and output mapsets */ *out_proj_info, *out_unit_info; struct GModule *module; struct Flag *list, /* list files in source location */ *nocrop, /* don't crop output map */ *print_bounds, /* print output bounds and exit */ *gprint_bounds; /* same but print shell style */ struct Option *imapset, /* name of input mapset */ *inmap, /* name of input layer */ *inlocation, /* name of input location */ *outmap, /* name of output layer */ *indbase, /* name of input database */ *interpol, /* interpolation method: nearest neighbor, bilinear, cubic */ *memory, /* amount of memory for cache */ *res; /* resolution of target map */ struct Cell_head incellhd, /* cell header of input map */ outcellhd; /* and output map */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("projection")); G_add_keyword(_("transformation")); module->description = _("Re-projects a raster map from given location to the current location."); inmap = G_define_standard_option(G_OPT_R_INPUT); inmap->description = _("Name of input raster map to re-project"); inmap->required = NO; inmap->guisection = _("Source"); inlocation = G_define_option(); inlocation->key = "location"; inlocation->type = TYPE_STRING; inlocation->required = YES; inlocation->description = _("Location containing input raster map"); inlocation->gisprompt = "old,location,location"; inlocation->key_desc = "name"; imapset = G_define_standard_option(G_OPT_M_MAPSET); imapset->label = _("Mapset containing input raster map"); imapset->description = _("default: name of current mapset"); imapset->guisection = _("Source"); indbase = G_define_option(); indbase->key = "dbase"; indbase->type = TYPE_STRING; indbase->required = NO; indbase->description = _("Path to GRASS database of input location"); indbase->gisprompt = "old,dbase,dbase"; indbase->key_desc = "path"; indbase->guisection = _("Source"); outmap = G_define_standard_option(G_OPT_R_OUTPUT); outmap->required = NO; outmap->description = _("Name for output raster map (default: same as 'input')"); outmap->guisection = _("Target"); ipolname = make_ipol_list(); interpol = G_define_option(); interpol->key = "method"; interpol->type = TYPE_STRING; interpol->required = NO; interpol->answer = "nearest"; interpol->options = ipolname; interpol->description = _("Interpolation method to use"); interpol->guisection = _("Target"); interpol->descriptions = make_ipol_desc(); memory = G_define_option(); memory->key = "memory"; memory->type = TYPE_INTEGER; memory->required = NO; memory->description = _("Cache size (MiB)"); res = G_define_option(); res->key = "resolution"; res->type = TYPE_DOUBLE; res->required = NO; res->description = _("Resolution of output raster map"); res->guisection = _("Target"); list = G_define_flag(); list->key = 'l'; list->description = _("List raster maps in input location and exit"); nocrop = G_define_flag(); nocrop->key = 'n'; nocrop->description = _("Do not perform region cropping optimization"); print_bounds = G_define_flag(); print_bounds->key = 'p'; print_bounds->description = _("Print input map's bounds in the current projection and exit"); print_bounds->guisection = _("Target"); gprint_bounds = G_define_flag(); gprint_bounds->key = 'g'; gprint_bounds->description = _("Print input map's bounds in the current projection and exit (shell style)"); gprint_bounds->guisection = _("Target"); /* The parser checks if the map already exists in current mapset, we switch out the check and do it in the module after the parser */ overwrite = G_check_overwrite(argc, argv); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get the method */ for (method = 0; (ipolname = menu[method].name); method++) if (strcmp(ipolname, interpol->answer) == 0) break; if (!ipolname) G_fatal_error(_("<%s=%s> unknown %s"), interpol->key, interpol->answer, interpol->key); interpolate = menu[method].method; mapname = outmap->answer ? outmap->answer : inmap->answer; if (mapname && !list->answer && !overwrite && G_find_raster(mapname, G_mapset())) G_fatal_error(_("option <%s>: <%s> exists."), "output", mapname); setname = imapset->answer ? imapset->answer : G_store(G_mapset()); if (strcmp(inlocation->answer, G_location()) == 0 && (!indbase->answer || strcmp(indbase->answer, G_gisdbase()) == 0)) #if 0 G_fatal_error(_("Input and output locations can not be the same")); #else G_warning(_("Input and output locations are the same")); #endif G_get_window(&outcellhd); if(gprint_bounds->answer && !print_bounds->answer) print_bounds->answer = gprint_bounds->answer; curr_proj = G_projection(); /* Get projection info for output mapset */ if ((out_proj_info = G_get_projinfo()) == NULL) G_fatal_error(_("Unable to get projection info of output raster map")); if ((out_unit_info = G_get_projunits()) == NULL) G_fatal_error(_("Unable to get projection units of output raster map")); if (pj_get_kv(&oproj, out_proj_info, out_unit_info) < 0) G_fatal_error(_("Unable to get projection key values of output raster map")); /* Change the location */ G__create_alt_env(); G__setenv("GISDBASE", indbase->answer ? indbase->answer : G_gisdbase()); G__setenv("LOCATION_NAME", inlocation->answer); permissions = G__mapset_permissions(setname); if (permissions < 0) /* can't access mapset */ G_fatal_error(_("Mapset <%s> in input location <%s> - %s"), setname, inlocation->answer, permissions == 0 ? _("permission denied") : _("not found")); /* if requested, list the raster maps in source location - MN 5/2001 */ if (list->answer) { int i; char **list; G_verbose_message(_("Checking location <%s> mapset <%s>"), inlocation->answer, setname); list = G_list(G_ELEMENT_RASTER, G__getenv("GISDBASE"), G__getenv("LOCATION_NAME"), setname); for (i = 0; list[i]; i++) { fprintf(stdout, "%s\n", list[i]); } fflush(stdout); exit(EXIT_SUCCESS); /* leave r.proj after listing */ } if (!inmap->answer) G_fatal_error(_("Required parameter <%s> not set"), inmap->key); if (!G_find_raster(inmap->answer, setname)) G_fatal_error(_("Raster map <%s> in location <%s> in mapset <%s> not found"), inmap->answer, inlocation->answer, setname); /* Read input map colour table */ have_colors = Rast_read_colors(inmap->answer, setname, &colr); /* Get projection info for input mapset */ if ((in_proj_info = G_get_projinfo()) == NULL) G_fatal_error(_("Unable to get projection info of input map")); if ((in_unit_info = G_get_projunits()) == NULL) G_fatal_error(_("Unable to get projection units of input map")); if (pj_get_kv(&iproj, in_proj_info, in_unit_info) < 0) G_fatal_error(_("Unable to get projection key values of input map")); G_free_key_value(in_proj_info); G_free_key_value(in_unit_info); G_free_key_value(out_proj_info); G_free_key_value(out_unit_info); if (G_verbose() > G_verbose_std()) pj_print_proj_params(&iproj, &oproj); /* this call causes r.proj to read the entire map into memeory */ Rast_get_cellhd(inmap->answer, setname, &incellhd); Rast_set_input_window(&incellhd); if (G_projection() == PROJECTION_XY) G_fatal_error(_("Unable to work with unprojected data (xy location)")); /* Save default borders so we can show them later */ inorth = incellhd.north; isouth = incellhd.south; ieast = incellhd.east; iwest = incellhd.west; irows = incellhd.rows; icols = incellhd.cols; onorth = outcellhd.north; osouth = outcellhd.south; oeast = outcellhd.east; owest = outcellhd.west; orows = outcellhd.rows; ocols = outcellhd.cols; if (print_bounds->answer) { G_message(_("Input map <%s@%s> in location <%s>:"), inmap->answer, setname, inlocation->answer); if (pj_do_proj(&iwest, &isouth, &iproj, &oproj) < 0) G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)")); if (pj_do_proj(&ieast, &inorth, &iproj, &oproj) < 0) G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)")); G_format_northing(inorth, north_str, curr_proj); G_format_northing(isouth, south_str, curr_proj); G_format_easting(ieast, east_str, curr_proj); G_format_easting(iwest, west_str, curr_proj); if(gprint_bounds->answer) { fprintf(stdout, "n=%s s=%s w=%s e=%s rows=%d cols=%d\n", north_str, south_str, west_str, east_str, irows, icols); } else { fprintf(stdout, "Source cols: %d\n", icols); fprintf(stdout, "Source rows: %d\n", irows); fprintf(stdout, "Local north: %s\n", north_str); fprintf(stdout, "Local south: %s\n", south_str); fprintf(stdout, "Local west: %s\n", west_str); fprintf(stdout, "Local east: %s\n", east_str); } /* somehow approximate local ewres, nsres ?? (use 'g.region -m' on lat/lon side) */ exit(EXIT_SUCCESS); } /* Cut non-overlapping parts of input map */ if (!nocrop->answer) bordwalk(&outcellhd, &incellhd, &oproj, &iproj); /* Add 2 cells on each side for bilinear/cubic & future interpolation methods */ /* (should probably be a factor based on input and output resolution) */ incellhd.north += 2 * incellhd.ns_res; incellhd.east += 2 * incellhd.ew_res; incellhd.south -= 2 * incellhd.ns_res; incellhd.west -= 2 * incellhd.ew_res; if (incellhd.north > inorth) incellhd.north = inorth; if (incellhd.east > ieast) incellhd.east = ieast; if (incellhd.south < isouth) incellhd.south = isouth; if (incellhd.west < iwest) incellhd.west = iwest; Rast_set_input_window(&incellhd); /* And switch back to original location */ G__switch_env(); /* Adjust borders of output map */ if (!nocrop->answer) bordwalk(&incellhd, &outcellhd, &iproj, &oproj); #if 0 outcellhd.west = outcellhd.south = HUGE_VAL; outcellhd.east = outcellhd.north = -HUGE_VAL; for (row = 0; row < incellhd.rows; row++) { ycoord1 = Rast_row_to_northing((double)(row + 0.5), &incellhd); for (col = 0; col < incellhd.cols; col++) { xcoord1 = Rast_col_to_easting((double)(col + 0.5), &incellhd); pj_do_proj(&xcoord1, &ycoord1, &iproj, &oproj); if (xcoord1 > outcellhd.east) outcellhd.east = xcoord1; if (ycoord1 > outcellhd.north) outcellhd.north = ycoord1; if (xcoord1 < outcellhd.west) outcellhd.west = xcoord1; if (ycoord1 < outcellhd.south) outcellhd.south = ycoord1; } } #endif if (res->answer != NULL) /* set user defined resolution */ outcellhd.ns_res = outcellhd.ew_res = atof(res->answer); G_adjust_Cell_head(&outcellhd, 0, 0); Rast_set_output_window(&outcellhd); G_message(" "); G_message(_("Input:")); G_message(_("Cols: %d (%d)"), incellhd.cols, icols); G_message(_("Rows: %d (%d)"), incellhd.rows, irows); G_message(_("North: %f (%f)"), incellhd.north, inorth); G_message(_("South: %f (%f)"), incellhd.south, isouth); G_message(_("West: %f (%f)"), incellhd.west, iwest); G_message(_("East: %f (%f)"), incellhd.east, ieast); G_message(_("EW-res: %f"), incellhd.ew_res); G_message(_("NS-res: %f"), incellhd.ns_res); G_message(" "); G_message(_("Output:")); G_message(_("Cols: %d (%d)"), outcellhd.cols, ocols); G_message(_("Rows: %d (%d)"), outcellhd.rows, orows); G_message(_("North: %f (%f)"), outcellhd.north, onorth); G_message(_("South: %f (%f)"), outcellhd.south, osouth); G_message(_("West: %f (%f)"), outcellhd.west, owest); G_message(_("East: %f (%f)"), outcellhd.east, oeast); G_message(_("EW-res: %f"), outcellhd.ew_res); G_message(_("NS-res: %f"), outcellhd.ns_res); G_message(" "); /* open and read the relevant parts of the input map and close it */ G__switch_env(); Rast_set_input_window(&incellhd); fdi = Rast_open_old(inmap->answer, setname); cell_type = Rast_get_map_type(fdi); ibuffer = readcell(fdi, memory->answer); Rast_close(fdi); G__switch_env(); Rast_set_output_window(&outcellhd); if (strcmp(interpol->answer, "nearest") == 0) { fdo = Rast_open_new(mapname, cell_type); obuffer = (CELL *) Rast_allocate_output_buf(cell_type); } else { fdo = Rast_open_fp_new(mapname); cell_type = FCELL_TYPE; obuffer = (FCELL *) Rast_allocate_output_buf(cell_type); } cell_size = Rast_cell_size(cell_type); xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2); /**/ ycoord1 = ycoord2 = outcellhd.north - (outcellhd.ns_res / 2); /**/ G_important_message(_("Projecting...")); G_percent(0, outcellhd.rows, 2); for (row = 0; row < outcellhd.rows; row++) { obufptr = obuffer; for (col = 0; col < outcellhd.cols; col++) { /* project coordinates in output matrix to */ /* coordinates in input matrix */ if (pj_do_proj(&xcoord1, &ycoord1, &oproj, &iproj) < 0) Rast_set_null_value(obufptr, 1, cell_type); else { /* convert to row/column indices of input matrix */ col_idx = (xcoord1 - incellhd.west) / incellhd.ew_res; row_idx = (incellhd.north - ycoord1) / incellhd.ns_res; /* and resample data point */ interpolate(ibuffer, obufptr, cell_type, &col_idx, &row_idx, &incellhd); } obufptr = G_incr_void_ptr(obufptr, cell_size); xcoord2 += outcellhd.ew_res; xcoord1 = xcoord2; ycoord1 = ycoord2; } Rast_put_row(fdo, obuffer, cell_type); xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2); ycoord2 -= outcellhd.ns_res; ycoord1 = ycoord2; G_percent(row, outcellhd.rows - 1, 2); } Rast_close(fdo); if (have_colors > 0) { Rast_write_colors(mapname, G_mapset(), &colr); Rast_free_colors(&colr); } Rast_short_history(mapname, "raster", &history); Rast_command_history(&history); Rast_write_history(mapname, &history); G_done_msg(NULL); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int out_fd, base_raster; char *infile, *outmap; int percent; double zrange_min, zrange_max, d_tmp; double irange_min, irange_max; unsigned long estimated_lines; RASTER_MAP_TYPE rtype, base_raster_data_type; struct History history; char title[64]; SEGMENT base_segment; struct PointBinning point_binning; void *base_array; void *raster_row; struct Cell_head region; struct Cell_head input_region; int rows, last_rows, row0, cols; /* scan box size */ int row; /* counters */ int pass, npasses; unsigned long line, line_total; unsigned int counter; unsigned long n_invalid; char buff[BUFFSIZE]; double x, y, z; double intensity; int arr_row, arr_col; unsigned long count, count_total; int point_class; double zscale = 1.0; double iscale = 1.0; double res = 0.0; struct BinIndex bin_index_nodes; bin_index_nodes.num_nodes = 0; bin_index_nodes.max_nodes = 0; bin_index_nodes.nodes = 0; struct GModule *module; struct Option *input_opt, *output_opt, *percent_opt, *type_opt, *filter_opt, *class_opt; struct Option *method_opt, *base_raster_opt; struct Option *zrange_opt, *zscale_opt; struct Option *irange_opt, *iscale_opt; struct Option *trim_opt, *pth_opt, *res_opt; struct Option *file_list_opt; struct Flag *print_flag, *scan_flag, *shell_style, *over_flag, *extents_flag; struct Flag *intens_flag, *intens_import_flag; struct Flag *set_region_flag; struct Flag *base_rast_res_flag; struct Flag *only_valid_flag; /* LAS */ LASReaderH LAS_reader; LASHeaderH LAS_header; LASSRSH LAS_srs; LASPointH LAS_point; int return_filter; const char *projstr; struct Cell_head cellhd, loc_wind; unsigned int n_filtered; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("import")); G_add_keyword(_("LIDAR")); G_add_keyword(_("statistics")); G_add_keyword(_("conversion")); G_add_keyword(_("aggregation")); G_add_keyword(_("binning")); module->description = _("Creates a raster map from LAS LiDAR points using univariate statistics."); input_opt = G_define_standard_option(G_OPT_F_BIN_INPUT); input_opt->required = NO; input_opt->label = _("LAS input file"); input_opt->description = _("LiDAR input files in LAS format (*.las or *.laz)"); input_opt->guisection = _("Input"); output_opt = G_define_standard_option(G_OPT_R_OUTPUT); output_opt->required = NO; output_opt->guisection = _("Output"); file_list_opt = G_define_standard_option(G_OPT_F_INPUT); file_list_opt->key = "file"; file_list_opt->label = _("File containing names of LAS input files"); file_list_opt->description = _("LiDAR input files in LAS format (*.las or *.laz)"); file_list_opt->required = NO; file_list_opt->guisection = _("Input"); method_opt = G_define_option(); method_opt->key = "method"; method_opt->type = TYPE_STRING; method_opt->required = NO; method_opt->description = _("Statistic to use for raster values"); method_opt->options = "n,min,max,range,sum,mean,stddev,variance,coeff_var,median,percentile,skewness,trimmean"; method_opt->answer = "mean"; method_opt->guisection = _("Statistic"); G_asprintf((char **)&(method_opt->descriptions), "n;%s;" "min;%s;" "max;%s;" "range;%s;" "sum;%s;" "mean;%s;" "stddev;%s;" "variance;%s;" "coeff_var;%s;" "median;%s;" "percentile;%s;" "skewness;%s;" "trimmean;%s", _("Number of points in cell"), _("Minimum value of point values in cell"), _("Maximum value of point values in cell"), _("Range of point values in cell"), _("Sum of point values in cell"), _("Mean (average) value of point values in cell"), _("Standard deviation of point values in cell"), _("Variance of point values in cell"), _("Coefficient of variance of point values in cell"), _("Median value of point values in cell"), _("pth (nth) percentile of point values in cell"), _("Skewness of point values in cell"), _("Trimmed mean of point values in cell")); type_opt = G_define_standard_option(G_OPT_R_TYPE); type_opt->required = NO; type_opt->answer = "FCELL"; base_raster_opt = G_define_standard_option(G_OPT_R_INPUT); base_raster_opt->key = "base_raster"; base_raster_opt->required = NO; base_raster_opt->label = _("Subtract raster values from the Z coordinates"); base_raster_opt->description = _("The scale for Z is applied beforehand, the range filter for" " Z afterwards"); base_raster_opt->guisection = _("Transform"); zrange_opt = G_define_option(); zrange_opt->key = "zrange"; zrange_opt->type = TYPE_DOUBLE; zrange_opt->required = NO; zrange_opt->key_desc = "min,max"; zrange_opt->description = _("Filter range for Z data (min,max)"); zrange_opt->guisection = _("Selection"); zscale_opt = G_define_option(); zscale_opt->key = "zscale"; zscale_opt->type = TYPE_DOUBLE; zscale_opt->required = NO; zscale_opt->answer = "1.0"; zscale_opt->description = _("Scale to apply to Z data"); zscale_opt->guisection = _("Transform"); irange_opt = G_define_option(); irange_opt->key = "intensity_range"; irange_opt->type = TYPE_DOUBLE; irange_opt->required = NO; irange_opt->key_desc = "min,max"; irange_opt->description = _("Filter range for intensity values (min,max)"); irange_opt->guisection = _("Selection"); iscale_opt = G_define_option(); iscale_opt->key = "intensity_scale"; iscale_opt->type = TYPE_DOUBLE; iscale_opt->required = NO; iscale_opt->answer = "1.0"; iscale_opt->description = _("Scale to apply to intensity values"); iscale_opt->guisection = _("Transform"); percent_opt = G_define_option(); percent_opt->key = "percent"; percent_opt->type = TYPE_INTEGER; percent_opt->required = NO; percent_opt->answer = "100"; percent_opt->options = "1-100"; percent_opt->description = _("Percent of map to keep in memory"); /* I would prefer to call the following "percentile", but that has too * much namespace overlap with the "percent" option above */ pth_opt = G_define_option(); pth_opt->key = "pth"; pth_opt->type = TYPE_INTEGER; pth_opt->required = NO; pth_opt->options = "1-100"; pth_opt->description = _("pth percentile of the values"); pth_opt->guisection = _("Statistic"); trim_opt = G_define_option(); trim_opt->key = "trim"; trim_opt->type = TYPE_DOUBLE; trim_opt->required = NO; trim_opt->options = "0-50"; trim_opt->label = _("Discard given percentage of the smallest and largest values"); trim_opt->description = _("Discard <trim> percent of the smallest and <trim> percent of the largest observations"); trim_opt->guisection = _("Statistic"); res_opt = G_define_option(); res_opt->key = "resolution"; res_opt->type = TYPE_DOUBLE; res_opt->required = NO; res_opt->description = _("Output raster resolution"); res_opt->guisection = _("Output"); filter_opt = G_define_option(); filter_opt->key = "return_filter"; filter_opt->type = TYPE_STRING; filter_opt->required = NO; filter_opt->label = _("Only import points of selected return type"); filter_opt->description = _("If not specified, all points are imported"); filter_opt->options = "first,last,mid"; filter_opt->guisection = _("Selection"); class_opt = G_define_option(); class_opt->key = "class_filter"; class_opt->type = TYPE_INTEGER; class_opt->multiple = YES; class_opt->required = NO; class_opt->label = _("Only import points of selected class(es)"); class_opt->description = _("Input is comma separated integers. " "If not specified, all points are imported."); class_opt->guisection = _("Selection"); print_flag = G_define_flag(); print_flag->key = 'p'; print_flag->description = _("Print LAS file info and exit"); extents_flag = G_define_flag(); extents_flag->key = 'e'; extents_flag->label = _("Use the extent of the input for the raster extent"); extents_flag->description = _("Set internally computational region extents based on the" " point cloud"); extents_flag->guisection = _("Output"); set_region_flag = G_define_flag(); set_region_flag->key = 'n'; set_region_flag->label = _("Set computation region to match the new raster map"); set_region_flag->description = _("Set computation region to match the 2D extent and resolution" " of the newly created new raster map"); set_region_flag->guisection = _("Output"); over_flag = G_define_flag(); over_flag->key = 'o'; over_flag->label = _("Override projection check (use current location's projection)"); over_flag->description = _("Assume that the dataset has same projection as the current location"); scan_flag = G_define_flag(); scan_flag->key = 's'; scan_flag->description = _("Scan data file for extent then exit"); shell_style = G_define_flag(); shell_style->key = 'g'; shell_style->description = _("In scan mode, print using shell script style"); intens_flag = G_define_flag(); intens_flag->key = 'i'; intens_flag->label = _("Use intensity values rather than Z values"); intens_flag->description = _("Uses intensity values everywhere as if they would be Z" " coordinates"); intens_import_flag = G_define_flag(); intens_import_flag->key = 'j'; intens_import_flag->description = _("Use Z values for filtering, but intensity values for statistics"); base_rast_res_flag = G_define_flag(); base_rast_res_flag->key = 'd'; base_rast_res_flag->label = _("Use base raster resolution instead of computational region"); base_rast_res_flag->description = _("For getting values from base raster, use its actual" " resolution instead of computational region resolution"); only_valid_flag = G_define_flag(); only_valid_flag->key = 'v'; only_valid_flag->label = _("Use only valid points"); only_valid_flag->description = _("Points invalid according to APSRS LAS specification will be" " filtered out"); only_valid_flag->guisection = _("Selection"); G_option_required(input_opt, file_list_opt, NULL); G_option_exclusive(input_opt, file_list_opt, NULL); G_option_required(output_opt, print_flag, scan_flag, shell_style, NULL); G_option_exclusive(intens_flag, intens_import_flag, NULL); G_option_requires(base_rast_res_flag, base_raster_opt, NULL); if (G_parser(argc, argv)) exit(EXIT_FAILURE); int only_valid = FALSE; n_invalid = 0; if (only_valid_flag->answer) only_valid = TRUE; /* we could use rules but this gives more info and allows continuing */ if (set_region_flag->answer && !(extents_flag->answer || res_opt->answer)) { G_warning(_("Flag %c makes sense only with %s option or -%c flag"), set_region_flag->key, res_opt->key, extents_flag->key); /* avoid the call later on */ set_region_flag->answer = '\0'; } struct StringList infiles; if (file_list_opt->answer) { if (access(file_list_opt->answer, F_OK) != 0) G_fatal_error(_("File <%s> does not exist"), file_list_opt->answer); string_list_from_file(&infiles, file_list_opt->answer); } else { string_list_from_one_item(&infiles, input_opt->answer); } /* parse input values */ outmap = output_opt->answer; if (shell_style->answer && !scan_flag->answer) { scan_flag->answer = 1; /* pointer not int, so set = shell_style->answer ? */ } /* check zrange and extent relation */ if (scan_flag->answer || extents_flag->answer) { if (zrange_opt->answer) G_warning(_("zrange will not be taken into account during scan")); } Rast_get_window(®ion); /* G_get_window seems to be unreliable if the location has been changed */ G_get_set_window(&loc_wind); /* TODO: v.in.lidar uses G_get_default_window() */ estimated_lines = 0; int i; for (i = 0; i < infiles.num_items; i++) { infile = infiles.items[i]; /* don't if file not found */ if (access(infile, F_OK) != 0) G_fatal_error(_("Input file <%s> does not exist"), infile); /* Open LAS file*/ LAS_reader = LASReader_Create(infile); if (LAS_reader == NULL) G_fatal_error(_("Unable to open file <%s> as a LiDAR point cloud"), infile); LAS_header = LASReader_GetHeader(LAS_reader); if (LAS_header == NULL) { G_fatal_error(_("Unable to read LAS header of <%s>"), infile); } LAS_srs = LASHeader_GetSRS(LAS_header); /* print info or check projection if we are actually importing */ if (print_flag->answer) { /* print filename when there is more than one file */ if (infiles.num_items > 1) fprintf(stdout, "File: %s\n", infile); /* Print LAS header */ print_lasinfo(LAS_header, LAS_srs); } else { /* report that we are checking more files */ if (i == 1) G_message(_("First file's projection checked," " checking projection of the other files...")); /* Fetch input map projection in GRASS form. */ projstr = LASSRS_GetWKT_CompoundOK(LAS_srs); /* we are printing the non-warning messages only for first file */ projection_check_wkt(cellhd, loc_wind, projstr, over_flag->answer, shell_style->answer || i); /* if there is a problem in some other file, first OK message * is printed but than a warning, this is not ideal but hopefully * not so confusing when importing multiple files */ } if (scan_flag->answer || extents_flag->answer) { /* we assign to the first one (i==0) but update for the rest */ scan_bounds(LAS_reader, shell_style->answer, extents_flag->answer, i, zscale, ®ion); } /* number of estimated point across all files */ /* TODO: this should be ull which won't work with percent report */ estimated_lines += LASHeader_GetPointRecordsCount(LAS_header); /* We are closing all again and we will be opening them later, * so we don't have to worry about limit for open files. */ LASSRS_Destroy(LAS_srs); LASHeader_Destroy(LAS_header); LASReader_Destroy(LAS_reader); } /* if we are not importing, end */ if (print_flag->answer || scan_flag->answer) exit(EXIT_SUCCESS); return_filter = LAS_ALL; if (filter_opt->answer) { if (strcmp(filter_opt->answer, "first") == 0) return_filter = LAS_FIRST; else if (strcmp(filter_opt->answer, "last") == 0) return_filter = LAS_LAST; else if (strcmp(filter_opt->answer, "mid") == 0) return_filter = LAS_MID; else G_fatal_error(_("Unknown filter option <%s>"), filter_opt->answer); } struct ReturnFilter return_filter_struct; return_filter_struct.filter = return_filter; struct ClassFilter class_filter; class_filter_create_from_strings(&class_filter, class_opt->answers); percent = atoi(percent_opt->answer); /* TODO: we already used zscale */ /* TODO: we don't report intensity range */ if (zscale_opt->answer) zscale = atof(zscale_opt->answer); if (iscale_opt->answer) iscale = atof(iscale_opt->answer); /* parse zrange */ if (zrange_opt->answer != NULL) { if (zrange_opt->answers[0] == NULL) G_fatal_error(_("Invalid zrange")); sscanf(zrange_opt->answers[0], "%lf", &zrange_min); sscanf(zrange_opt->answers[1], "%lf", &zrange_max); if (zrange_min > zrange_max) { d_tmp = zrange_max; zrange_max = zrange_min; zrange_min = d_tmp; } } /* parse irange */ if (irange_opt->answer != NULL) { if (irange_opt->answers[0] == NULL) G_fatal_error(_("Invalid %s"), irange_opt->key); sscanf(irange_opt->answers[0], "%lf", &irange_min); sscanf(irange_opt->answers[1], "%lf", &irange_max); if (irange_min > irange_max) { d_tmp = irange_max; irange_max = irange_min; irange_min = d_tmp; } } point_binning_set(&point_binning, method_opt->answer, pth_opt->answer, trim_opt->answer, FALSE); base_array = NULL; if (strcmp("CELL", type_opt->answer) == 0) rtype = CELL_TYPE; else if (strcmp("DCELL", type_opt->answer) == 0) rtype = DCELL_TYPE; else rtype = FCELL_TYPE; if (point_binning.method == METHOD_N) rtype = CELL_TYPE; if (res_opt->answer) { /* align to resolution */ res = atof(res_opt->answer); if (!G_scan_resolution(res_opt->answer, &res, region.proj)) G_fatal_error(_("Invalid input <%s=%s>"), res_opt->key, res_opt->answer); if (res <= 0) G_fatal_error(_("Option '%s' must be > 0.0"), res_opt->key); region.ns_res = region.ew_res = res; region.north = ceil(region.north / res) * res; region.south = floor(region.south / res) * res; region.east = ceil(region.east / res) * res; region.west = floor(region.west / res) * res; G_adjust_Cell_head(®ion, 0, 0); } else if (extents_flag->answer) { /* align to current region */ Rast_align_window(®ion, &loc_wind); } Rast_set_output_window(®ion); rows = last_rows = region.rows; npasses = 1; if (percent < 100) { rows = (int)(region.rows * (percent / 100.0)); npasses = region.rows / rows; last_rows = region.rows - npasses * rows; if (last_rows) npasses++; else last_rows = rows; } cols = region.cols; G_debug(2, "region.n=%f region.s=%f region.ns_res=%f", region.north, region.south, region.ns_res); G_debug(2, "region.rows=%d [box_rows=%d] region.cols=%d", region.rows, rows, region.cols); /* using row-based chunks (used for output) when input and output * region matches and using segment library when they don't */ int use_segment = 0; int use_base_raster_res = 0; /* TODO: see if the input region extent is smaller than the raster * if yes, the we need to load the whole base raster if the -e * flag was defined (alternatively clip the regions) */ if (base_rast_res_flag->answer) use_base_raster_res = 1; if (base_raster_opt->answer && (res_opt->answer || use_base_raster_res || extents_flag->answer)) use_segment = 1; if (base_raster_opt->answer && !use_segment) { /* TODO: do we need to test existence first? mapset? */ base_raster = Rast_open_old(base_raster_opt->answer, ""); base_raster_data_type = Rast_get_map_type(base_raster); base_array = G_calloc((size_t)rows * (cols + 1), Rast_cell_size(base_raster_data_type)); } if (base_raster_opt->answer && use_segment) { if (use_base_raster_res) { /* read raster actual extent and resolution */ Rast_get_cellhd(base_raster_opt->answer, "", &input_region); /* TODO: make it only as small as the output is or points are */ Rast_set_input_window(&input_region); /* we have split window */ } else { Rast_get_input_window(&input_region); } rast_segment_open(&base_segment, base_raster_opt->answer, &base_raster_data_type); } if (!scan_flag->answer) { if (!check_rows_cols_fit_to_size_t(rows, cols)) G_fatal_error(_("Unable to process the hole map at once. " "Please set the '%s' option to some value lower than 100."), percent_opt->key); point_binning_memory_test(&point_binning, rows, cols, rtype); } /* open output map */ out_fd = Rast_open_new(outmap, rtype); /* allocate memory for a single row of output data */ raster_row = Rast_allocate_output_buf(rtype); G_message(_("Reading data ...")); count_total = line_total = 0; /* main binning loop(s) */ for (pass = 1; pass <= npasses; pass++) { if (npasses > 1) G_message(_("Pass #%d (of %d) ..."), pass, npasses); /* figure out segmentation */ row0 = (pass - 1) * rows; if (pass == npasses) { rows = last_rows; } if (base_array) { G_debug(2, "filling base raster array"); for (row = 0; row < rows; row++) { Rast_get_row(base_raster, base_array + ((size_t) row * cols * Rast_cell_size(base_raster_data_type)), row, base_raster_data_type); } } G_debug(2, "pass=%d/%d rows=%d", pass, npasses, rows); point_binning_allocate(&point_binning, rows, cols, rtype); line = 0; count = 0; counter = 0; G_percent_reset(); /* loop of input files */ for (i = 0; i < infiles.num_items; i++) { infile = infiles.items[i]; /* we already know file is there, so just do basic checks */ LAS_reader = LASReader_Create(infile); if (LAS_reader == NULL) G_fatal_error(_("Unable to open file <%s>"), infile); while ((LAS_point = LASReader_GetNextPoint(LAS_reader)) != NULL) { line++; counter++; if (counter == 100000) { /* speed */ if (line < estimated_lines) G_percent(line, estimated_lines, 3); counter = 0; } /* We always count them and report because behavior * changed in between 7.0 and 7.2 from undefined (but skipping * invalid points) to filtering them out only when requested. */ if (!LASPoint_IsValid(LAS_point)) { n_invalid++; if (only_valid) continue; } x = LASPoint_GetX(LAS_point); y = LASPoint_GetY(LAS_point); if (intens_flag->answer) /* use intensity as z here to allow all filters (and * modifications) below to be applied for intensity */ z = LASPoint_GetIntensity(LAS_point); else z = LASPoint_GetZ(LAS_point); int return_n = LASPoint_GetReturnNumber(LAS_point); int n_returns = LASPoint_GetNumberOfReturns(LAS_point); if (return_filter_is_out(&return_filter_struct, return_n, n_returns)) { n_filtered++; continue; } point_class = (int) LASPoint_GetClassification(LAS_point); if (class_filter_is_out(&class_filter, point_class)) continue; if (y <= region.south || y > region.north) { continue; } if (x < region.west || x >= region.east) { continue; } /* find the bin in the current array box */ arr_row = (int)((region.north - y) / region.ns_res) - row0; if (arr_row < 0 || arr_row >= rows) continue; arr_col = (int)((x - region.west) / region.ew_res); z = z * zscale; if (base_array) { double base_z; if (row_array_get_value_row_col(base_array, arr_row, arr_col, cols, base_raster_data_type, &base_z)) z -= base_z; else continue; } else if (use_segment) { double base_z; if (rast_segment_get_value_xy(&base_segment, &input_region, base_raster_data_type, x, y, &base_z)) z -= base_z; else continue; } if (zrange_opt->answer) { if (z < zrange_min || z > zrange_max) { continue; } } if (intens_import_flag->answer || irange_opt->answer) { intensity = LASPoint_GetIntensity(LAS_point); intensity *= iscale; if (irange_opt->answer) { if (intensity < irange_min || intensity > irange_max) { continue; } } /* use intensity for statistics */ if (intens_import_flag->answer) z = intensity; } count++; /* G_debug(5, "x: %f, y: %f, z: %f", x, y, z); */ update_value(&point_binning, &bin_index_nodes, cols, arr_row, arr_col, rtype, x, y, z); } /* while !EOF of one input file */ /* close input LAS file */ LASReader_Destroy(LAS_reader); } /* end of loop for all input files files */ G_percent(1, 1, 1); /* flush */ G_debug(2, "pass %d finished, %lu coordinates in box", pass, count); count_total += count; line_total += line; /* calc stats and output */ G_message(_("Writing to map ...")); for (row = 0; row < rows; row++) { /* potentially vector writing can be independent on the binning */ write_values(&point_binning, &bin_index_nodes, raster_row, row, cols, rtype, NULL); /* write out line of raster data */ Rast_put_row(out_fd, raster_row, rtype); } /* free memory */ point_binning_free(&point_binning, &bin_index_nodes); } /* passes loop */ if (base_array) Rast_close(base_raster); if (use_segment) Segment_close(&base_segment); G_percent(1, 1, 1); /* flush */ G_free(raster_row); /* close raster file & write history */ Rast_close(out_fd); sprintf(title, "Raw X,Y,Z data binned into a raster grid by cell %s", method_opt->answer); Rast_put_cell_title(outmap, title); Rast_short_history(outmap, "raster", &history); Rast_command_history(&history); Rast_set_history(&history, HIST_DATSRC_1, infile); Rast_write_history(outmap, &history); /* set computation region to the new raster map */ /* TODO: should be in the done message */ if (set_region_flag->answer) G_put_window(®ion); if (n_invalid && only_valid) G_message(_("%lu input points were invalid and filtered out"), n_invalid); if (n_invalid && !only_valid) G_message(_("%lu input points were invalid, use -%c flag to filter" " them out"), n_invalid, only_valid_flag->key); if (infiles.num_items > 1) { sprintf(buff, _("Raster map <%s> created." " %lu points from %d files found in region."), outmap, count_total, infiles.num_items); } else { sprintf(buff, _("Raster map <%s> created." " %lu points found in region."), outmap, count_total); } G_done_msg("%s", buff); G_debug(1, "Processed %lu points.", line_total); string_list_free(&infiles); exit(EXIT_SUCCESS); }
CPLErr GRASSRasterBand::IRasterIO ( GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, void * pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { /* GRASS library does that, we have only calculate and reset the region in map units * and if the region has changed, reopen the raster */ /* Calculate the region */ struct Cell_head sWindow; struct Cell_head *psDsWindow; if ( ! this->valid ) return CE_Failure; psDsWindow = &(((GRASSDataset *)poDS)->sCellInfo); sWindow.north = psDsWindow->north - nYOff * psDsWindow->ns_res; sWindow.south = sWindow.north - nYSize * psDsWindow->ns_res; sWindow.west = psDsWindow->west + nXOff * psDsWindow->ew_res; sWindow.east = sWindow.west + nXSize * psDsWindow->ew_res; sWindow.proj = psDsWindow->proj; sWindow.zone = psDsWindow->zone; sWindow.cols = nBufXSize; sWindow.rows = nBufYSize; /* Reset resolution */ G_adjust_Cell_head ( &sWindow, 1, 1); if ( ResetReading ( &sWindow ) != CE_None ) { return CE_Failure; } /* Read Data */ CELL *cbuf = NULL; FCELL *fbuf = NULL; DCELL *dbuf = NULL; bool direct = false; /* Reset space if default (0) */ if ( nPixelSpace == 0 ) nPixelSpace = GDALGetDataTypeSize ( eBufType ) / 8; if ( nLineSpace == 0 ) nLineSpace = nBufXSize * nPixelSpace; if ( nGRSType == CELL_TYPE && ( !nativeNulls || eBufType != GDT_Int32 || sizeof(CELL) != 4 || nPixelSpace != sizeof(CELL) ) ) { cbuf = G_allocate_c_raster_buf(); } else if( nGRSType == FCELL_TYPE && ( eBufType != GDT_Float32 || nPixelSpace != sizeof(FCELL) ) ) { fbuf = G_allocate_f_raster_buf(); } else if( nGRSType == DCELL_TYPE && ( eBufType != GDT_Float64 || nPixelSpace != sizeof(DCELL) ) ) { dbuf = G_allocate_d_raster_buf(); } else { direct = true; } for ( int row = 0; row < nBufYSize; row++ ) { char *pnt = (char *)pData + row * nLineSpace; if ( nGRSType == CELL_TYPE ) { if ( direct ) { G_get_c_raster_row ( hCell, (CELL *) pnt, row ); } else { G_get_c_raster_row ( hCell, cbuf, row ); /* Reset NULLs */ for ( int col = 0; col < nBufXSize; col++ ) { if ( G_is_c_null_value(&(cbuf[col])) ) cbuf[col] = (CELL) dfNoData; } GDALCopyWords ( (void *) cbuf, GDT_Int32, sizeof(CELL), (void *) pnt, eBufType, nPixelSpace, nBufXSize ); } } else if( nGRSType == FCELL_TYPE ) { if ( direct ) { G_get_f_raster_row ( hCell, (FCELL *) pnt, row ); } else { G_get_f_raster_row ( hCell, fbuf, row ); GDALCopyWords ( (void *) fbuf, GDT_Float32, sizeof(FCELL), (void *) pnt, eBufType, nPixelSpace, nBufXSize ); } } else if( nGRSType == DCELL_TYPE ) { if ( direct ) { G_get_d_raster_row ( hCell, (DCELL *) pnt, row ); } else { G_get_d_raster_row ( hCell, dbuf, row ); GDALCopyWords ( (void *) dbuf, GDT_Float64, sizeof(DCELL), (void *) pnt, eBufType, nPixelSpace, nBufXSize ); } } } if ( cbuf ) G_free ( cbuf ); if ( fbuf ) G_free ( fbuf ); if ( dbuf ) G_free ( dbuf ); return CE_None; }
int GRASS_LIB_EXPORT QgsGrassGisLib::G__gisinit( const char * version, const char * programName ) { Q_UNUSED( version ); // We use this function also to init our fake lib QgsDebugMsg( QString( "version = %1 programName = %2" ).arg( version ).arg( programName ) ); // Init providers path int argc = 1; char **argv = new char*[1]; argv[0] = qstrdup( programName ); // unfortunately it seems impossible to get QGIS prefix // QCoreApplication::applicationDirPath() returns $GISBASE/lib on Linux #if 0 QDir dir( QCoreApplication::applicationDirPath() ); dir.cdUp(); QString prefixPath = dir.absolutePath(); #endif //QCoreApplication app( argc, argv ); // to init paths QgsApplication app( argc, argv, false ); // to init paths // TODO: WCS (network) fails with: "QTimer can only be used with threads started // with QThread" because QCoreApplication::exec() was not called, but // QCoreApplication::exec() goes to loop. We need to start QThread somehow. // QGIS_PREFIX_PATH should be loaded by QgsApplication //QString prefixPath = getenv( "QGIS_PREFIX_PATH" ); //if ( prefixPath.isEmpty() ) //{ // fatal( "Cannot get QGIS_PREFIX_PATH" ); //} //QgsApplication::setPrefixPath( prefixPath, true ); QgsDebugMsg( "Plugin path: " + QgsApplication::pluginPath() ); QgsProviderRegistry::instance( QgsApplication::pluginPath() ); QgsDebugMsg( "qgisSettingsDirPath = " + app.qgisSettingsDirPath() ); G_set_error_routine( &errorRoutine ); G_set_gisrc_mode( G_GISRC_MODE_MEMORY ); G_setenv( "OVERWRITE", "1" ); // avoid checking if map exists G_suppress_masking(); #if GRASS_VERSION_MAJOR<6 || (GRASS_VERSION_MAJOR == 6 && GRASS_VERSION_MINOR <= 4) G__init_null_patterns(); #endif // Read projection if set //mCrs.createFromOgcWmsCrs( "EPSG:900913" ); QString crsStr = getenv( "QGIS_GRASS_CRS" ); QgsDebugMsg( "Setting CRS to " + crsStr ); if ( !crsStr.isEmpty() ) { if ( !mCrs.createFromProj4( crsStr ) ) { fatal( "Cannot create CRS from QGIS_GRASS_CRS: " + crsStr ); } //TODO: createFromProj4 used to save to the user database any new CRS // this behavior was changed in order to separate creation and saving. // Not sure if it necessary to save it here, should be checked by someone // familiar with the code (should also give a more descriptive name to the generated CRS) if ( mCrs.srsid() == 0 ) { QString myName = QString( " * %1 (%2)" ) .arg( QObject::tr( "Generated CRS", "A CRS automatically generated from layer info get this prefix for description" ) ) .arg( mCrs.toProj4() ); mCrs.saveAsUserCRS( myName ); } } mDistanceArea.setSourceCrs( mCrs.srsid() ); // Read region fron environment variable // QGIS_GRASS_REGION=west,south,east,north,cols,rows #if 0 QString regionStr = getenv( "QGIS_GRASS_REGION" ); QStringList regionList = regionStr.split( "," ); if ( regionList.size() != 6 ) { fatal( "Cannot read region from QGIS_GRASS_REGION environment variable" ); } double xMin, yMin, xMax, yMax; int cols, rows; bool xMinOk, yMinOk, xMaxOk, yMaxOk, colsOk, rowsOk; xMin = regionList.value( 0 ).toDouble( &xMinOk ); yMin = regionList.value( 1 ).toDouble( &yMinOk ); xMax = regionList.value( 2 ).toDouble( &xMaxOk ); yMax = regionList.value( 3 ).toDouble( &yMaxOk ); cols = regionList.value( 4 ).toInt( &colsOk ); rows = regionList.value( 5 ).toInt( &rowsOk ); if ( !xMinOk || !yMinOk || !xMaxOk || !yMaxOk || !colsOk || !rowsOk ) { fatal( "Cannot parse QGIS_GRASS_REGION" ); } struct Cell_head window; window.west = xMin; window.south = yMin; window.east = xMax; window.north = yMax; window.rows = rows; window.cols = cols; char* err = G_adjust_Cell_head( &window, 1, 1 ); if ( err ) { fatal( QString( err ) ); } G_set_window( &window ); #endif QString regionStr = getenv( "GRASS_REGION" ); if ( regionStr.isEmpty() ) { fatal( "GRASS_REGION environment variable not set" ); } QgsDebugMsg( "Getting region via true lib from GRASS_REGION: " + regionStr ); // GRASS true lib reads GRASS_REGION environment variable G_get_window( &mWindow ); mExtent = QgsRectangle( mWindow.west, mWindow.south, mWindow.east, mWindow.north ); mRows = mWindow.rows; mColumns = mWindow.cols; mXRes = mExtent.width() / mColumns; mYRes = mExtent.height() / mColumns; QgsDebugMsg( "End" ); return 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 i; double x; struct Cell_head cellhd, window; const char *value; const char *name; struct GModule *module; struct { struct Flag *dflt, *cur; } flag; struct { struct Option *map, *north, *south, *east, *west, *raster, *vect, *region, *align; } parm; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("metadata")); module->description = _("Sets the boundary definitions for a raster map."); /* flags */ flag.cur = G_define_flag(); flag.cur->key = 'c'; flag.cur->description = _("Set from current region"); flag.cur->guisection = _("Existing"); flag.dflt = G_define_flag(); flag.dflt->key = 'd'; flag.dflt->description = _("Set from default region"); flag.dflt->guisection = _("Existing"); /* parameters */ parm.map = G_define_standard_option(G_OPT_R_MAP); parm.map->description = _("Name of raster map to change"); parm.region = G_define_option(); parm.region->key = "region"; parm.region->key_desc = "name"; parm.region->required = NO; parm.region->multiple = NO; parm.region->type = TYPE_STRING; parm.region->description = _("Set region from named region"); parm.region->gisprompt = "old,windows,region"; parm.region->guisection = _("Existing"); parm.raster = G_define_standard_option(G_OPT_R_MAP); parm.raster->key = "raster"; parm.raster->required = NO; parm.raster->multiple = NO; parm.raster->description = _("Set region to match this raster map"); parm.raster->guisection = _("Existing"); parm.vect = G_define_standard_option(G_OPT_V_MAP); parm.vect->key = "vector"; parm.vect->required = NO; parm.vect->multiple = NO; parm.vect->description = _("Set region to match this vector map"); parm.vect->guisection = _("Existing"); parm.north = G_define_option(); parm.north->key = "n"; parm.north->key_desc = "value"; parm.north->required = NO; parm.north->multiple = NO; parm.north->type = TYPE_STRING; parm.north->description = _("Value for the northern edge"); parm.north->guisection = _("Bounds"); parm.south = G_define_option(); parm.south->key = "s"; parm.south->key_desc = "value"; parm.south->required = NO; parm.south->multiple = NO; parm.south->type = TYPE_STRING; parm.south->description = _("Value for the southern edge"); parm.south->guisection = _("Bounds"); parm.east = G_define_option(); parm.east->key = "e"; parm.east->key_desc = "value"; parm.east->required = NO; parm.east->multiple = NO; parm.east->type = TYPE_STRING; parm.east->description = _("Value for the eastern edge"); parm.east->guisection = _("Bounds"); parm.west = G_define_option(); parm.west->key = "w"; parm.west->key_desc = "value"; parm.west->required = NO; parm.west->multiple = NO; parm.west->type = TYPE_STRING; parm.west->description = _("Value for the western edge"); parm.west->guisection = _("Bounds"); parm.align = G_define_standard_option(G_OPT_R_MAP); parm.align->key = "align"; parm.align->required = NO; parm.align->multiple = NO; parm.align->description = _("Raster map to align to"); parm.align->guisection = _("Existing"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_get_window(&window); name = parm.map->answer; Rast_get_cellhd(name, G_mapset(), &cellhd); window = cellhd; if (flag.dflt->answer) G_get_default_window(&window); if (flag.cur->answer) G_get_window(&window); if ((name = parm.region->answer)) /* region= */ G__get_window(&window, "windows", name, ""); if ((name = parm.raster->answer)) { /* raster= */ Rast_get_cellhd(name, "", &window); } if ((name = parm.vect->answer)) { /* vect= */ struct Map_info Map; struct bound_box box; Vect_set_open_level(1); if (Vect_open_old(&Map, name, "") != 1) G_fatal_error(_("Unable to open vector map <%s>"), name); Vect_get_map_box(&Map, &box); window.north = box.N; window.south = box.S; window.west = box.W; window.east = box.E; Rast_align_window(&window, &cellhd); Vect_close(&Map); } if ((value = parm.north->answer)) { /* n= */ if ((i = nsew(value, "n+", "n-", "s+"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.north); switch (i) { case 1: window.north += x; break; case 2: window.north -= x; break; case 3: window.north = window.south + x; break; } } else if (G_scan_northing(value, &x, window.proj)) window.north = x; else die(parm.north); } if ((value = parm.south->answer)) { /* s= */ if ((i = nsew(value, "s+", "s-", "n-"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.south); switch (i) { case 1: window.south += x; break; case 2: window.south -= x; break; case 3: window.south = window.north - x; break; } } else if (G_scan_northing(value, &x, window.proj)) window.south = x; else die(parm.south); } if ((value = parm.east->answer)) { /* e= */ if ((i = nsew(value, "e+", "e-", "w+"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.east); switch (i) { case 1: window.east += x; break; case 2: window.east -= x; break; case 3: window.east = window.west + x; break; } } else if (G_scan_easting(value, &x, window.proj)) window.east = x; else die(parm.east); } if ((value = parm.west->answer)) { /* w= */ if ((i = nsew(value, "w+", "w-", "e-"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.west); switch (i) { case 1: window.west += x; break; case 2: window.west -= x; break; case 3: window.west = window.east - x; break; } } else if (G_scan_easting(value, &x, window.proj)) window.west = x; else die(parm.west); } if ((name = parm.align->answer)) { /* align= */ struct Cell_head temp_window; Rast_get_cellhd(name, "", &temp_window); Rast_align_window(&window, &temp_window); } window.rows = cellhd.rows; window.cols = cellhd.cols; G_adjust_Cell_head(&window, 1, 1); cellhd.north = window.north; cellhd.south = window.south; cellhd.east = window.east; cellhd.west = window.west; Rast_put_cellhd(parm.map->answer, &cellhd); G_done_msg(" "); return 0; }
int main(int argc, char *argv[]) { int m1; struct FPRange range; DCELL cellmin, cellmax; FCELL *cellrow, fcellmin; struct GModule *module; struct { struct Option *input, *elev, *slope, *aspect, *pcurv, *tcurv, *mcurv, *smooth, *maskmap, *zmult, *fi, *segmax, *npmin, *res_ew, *res_ns, *overlap, *theta, *scalex; } parm; struct { struct Flag *deriv, *cprght; } flag; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("resample")); module->description = _("Reinterpolates and optionally computes topographic analysis from " "input raster map to a new raster map (possibly with " "different resolution) using regularized spline with " "tension and smoothing."); parm.input = G_define_standard_option(G_OPT_R_INPUT); parm.res_ew = G_define_option(); parm.res_ew->key = "ew_res"; parm.res_ew->type = TYPE_DOUBLE; parm.res_ew->required = YES; parm.res_ew->description = _("Desired east-west resolution"); parm.res_ns = G_define_option(); parm.res_ns->key = "ns_res"; parm.res_ns->type = TYPE_DOUBLE; parm.res_ns->required = YES; parm.res_ns->description = _("Desired north-south resolution"); parm.elev = G_define_option(); parm.elev->key = "elev"; parm.elev->type = TYPE_STRING; parm.elev->required = NO; parm.elev->gisprompt = "new,cell,raster"; parm.elev->description = _("Output z-file (elevation) map"); parm.elev->guisection = _("Output"); parm.slope = G_define_option(); parm.slope->key = "slope"; parm.slope->type = TYPE_STRING; parm.slope->required = NO; parm.slope->gisprompt = "new,cell,raster"; parm.slope->description = _("Output slope map (or fx)"); parm.slope->guisection = _("Output"); parm.aspect = G_define_option(); parm.aspect->key = "aspect"; parm.aspect->type = TYPE_STRING; parm.aspect->required = NO; parm.aspect->gisprompt = "new,cell,raster"; parm.aspect->description = _("Output aspect map (or fy)"); parm.aspect->guisection = _("Output"); parm.pcurv = G_define_option(); parm.pcurv->key = "pcurv"; parm.pcurv->type = TYPE_STRING; parm.pcurv->required = NO; parm.pcurv->gisprompt = "new,cell,raster"; parm.pcurv->description = _("Output profile curvature map (or fxx)"); parm.pcurv->guisection = _("Output"); parm.tcurv = G_define_option(); parm.tcurv->key = "tcurv"; parm.tcurv->type = TYPE_STRING; parm.tcurv->required = NO; parm.tcurv->gisprompt = "new,cell,raster"; parm.tcurv->description = _("Output tangential curvature map (or fyy)"); parm.tcurv->guisection = _("Output"); parm.mcurv = G_define_option(); parm.mcurv->key = "mcurv"; parm.mcurv->type = TYPE_STRING; parm.mcurv->required = NO; parm.mcurv->gisprompt = "new,cell,raster"; parm.mcurv->description = _("Output mean curvature map (or fxy)"); parm.mcurv->guisection = _("Output"); parm.smooth = G_define_option(); parm.smooth->key = "smooth"; parm.smooth->type = TYPE_STRING; parm.smooth->required = NO; parm.smooth->gisprompt = "old,cell,raster"; parm.smooth->description = _("Name of raster map containing smoothing"); parm.smooth->guisection = _("Settings"); parm.maskmap = G_define_option(); parm.maskmap->key = "maskmap"; parm.maskmap->type = TYPE_STRING; parm.maskmap->required = NO; parm.maskmap->gisprompt = "old,cell,raster"; parm.maskmap->description = _("Name of raster map to be used as mask"); parm.maskmap->guisection = _("Settings"); parm.overlap = G_define_option(); parm.overlap->key = "overlap"; parm.overlap->type = TYPE_INTEGER; parm.overlap->required = NO; parm.overlap->answer = OVERLAP; parm.overlap->description = _("Rows/columns overlap for segmentation"); parm.overlap->guisection = _("Settings"); parm.zmult = G_define_option(); parm.zmult->key = "zmult"; parm.zmult->type = TYPE_DOUBLE; parm.zmult->answer = ZMULT; parm.zmult->required = NO; parm.zmult->description = _("Multiplier for z-values"); parm.zmult->guisection = _("Settings"); parm.fi = G_define_option(); parm.fi->key = "tension"; parm.fi->type = TYPE_DOUBLE; parm.fi->answer = TENSION; parm.fi->required = NO; parm.fi->description = _("Spline tension value"); parm.fi->guisection = _("Settings"); parm.theta = G_define_option(); parm.theta->key = "theta"; parm.theta->type = TYPE_DOUBLE; parm.theta->required = NO; parm.theta->description = _("Anisotropy angle (in degrees)"); parm.theta->guisection = _("Anisotropy"); parm.scalex = G_define_option(); parm.scalex->key = "scalex"; parm.scalex->type = TYPE_DOUBLE; parm.scalex->required = NO; parm.scalex->description = _("Anisotropy scaling factor"); parm.scalex->guisection = _("Anisotropy"); flag.cprght = G_define_flag(); flag.cprght->key = 't'; flag.cprght->description = _("Use dnorm independent tension"); flag.deriv = G_define_flag(); flag.deriv->key = 'd'; flag.deriv->description = _("Output partial derivatives instead of topographic parameters"); flag.deriv->guisection = _("Output"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_get_set_window(&winhd); inp_ew_res = winhd.ew_res; inp_ns_res = winhd.ns_res; inp_cols = winhd.cols; inp_rows = winhd.rows; inp_x_orig = winhd.west; inp_y_orig = winhd.south; input = parm.input->answer; smooth = parm.smooth->answer; maskmap = parm.maskmap->answer; elev = parm.elev->answer; slope = parm.slope->answer; aspect = parm.aspect->answer; pcurv = parm.pcurv->answer; tcurv = parm.tcurv->answer; mcurv = parm.mcurv->answer; cond2 = ((pcurv != NULL) || (tcurv != NULL) || (mcurv != NULL)); cond1 = ((slope != NULL) || (aspect != NULL) || cond2); deriv = flag.deriv->answer; dtens = flag.cprght->answer; ertre = 0.1; if (!G_scan_resolution(parm.res_ew->answer, &ew_res, winhd.proj)) G_fatal_error(_("Unable to read ew_res value")); if (!G_scan_resolution(parm.res_ns->answer, &ns_res, winhd.proj)) G_fatal_error(_("Unable to read ns_res value")); if (sscanf(parm.fi->answer, "%lf", &fi) != 1) G_fatal_error(_("Invalid value for tension")); if (sscanf(parm.zmult->answer, "%lf", &zmult) != 1) G_fatal_error(_("Invalid value for zmult")); if (sscanf(parm.overlap->answer, "%d", &overlap) != 1) G_fatal_error(_("Invalid value for overlap")); if (parm.theta->answer) { if (sscanf(parm.theta->answer, "%lf", &theta) != 1) G_fatal_error(_("Invalid value for theta")); } if (parm.scalex->answer) { if (sscanf(parm.scalex->answer, "%lf", &scalex) != 1) G_fatal_error(_("Invalid value for scalex")); if (!parm.theta->answer) G_fatal_error(_("When using anisotropy both theta and scalex must be specified")); } /* * G_set_embedded_null_value_mode(1); */ outhd.ew_res = ew_res; outhd.ns_res = ns_res; outhd.east = winhd.east; outhd.west = winhd.west; outhd.north = winhd.north; outhd.south = winhd.south; outhd.proj = winhd.proj; outhd.zone = winhd.zone; G_adjust_Cell_head(&outhd, 0, 0); ew_res = outhd.ew_res; ns_res = outhd.ns_res; nsizc = outhd.cols; nsizr = outhd.rows; disk = nsizc * nsizr * sizeof(int); az = G_alloc_vector(nsizc + 1); if (cond1) { adx = G_alloc_vector(nsizc + 1); ady = G_alloc_vector(nsizc + 1); if (cond2) { adxx = G_alloc_vector(nsizc + 1); adyy = G_alloc_vector(nsizc + 1); adxy = G_alloc_vector(nsizc + 1); } } if (smooth != NULL) { fdsmooth = Rast_open_old(smooth, ""); Rast_get_cellhd(smooth, "", &smhd); if ((winhd.ew_res != smhd.ew_res) || (winhd.ns_res != smhd.ns_res)) G_fatal_error(_("Map <%s> is the wrong resolution"), smooth); if (Rast_read_fp_range(smooth, "", &range) >= 0) Rast_get_fp_range_min_max(&range, &cellmin, &cellmax); fcellmin = (float)cellmin; if (Rast_is_f_null_value(&fcellmin) || fcellmin < 0.0) G_fatal_error(_("Smoothing values can not be negative or NULL")); } Rast_get_cellhd(input, "", &inphd); if ((winhd.ew_res != inphd.ew_res) || (winhd.ns_res != inphd.ns_res)) G_fatal_error(_("Input map resolution differs from current region resolution!")); fdinp = Rast_open_old(input, ""); sdisk = 0; if (elev != NULL) sdisk += disk; if (slope != NULL) sdisk += disk; if (aspect != NULL) sdisk += disk; if (pcurv != NULL) sdisk += disk; if (tcurv != NULL) sdisk += disk; if (mcurv != NULL) sdisk += disk; G_message(_("Processing all selected output files will require")); if (sdisk > 1024) { if (sdisk > 1024 * 1024) { if (sdisk > 1024 * 1024 * 1024) { G_message(_("%.2f GB of disk space for temp files."), sdisk / (1024. * 1024. * 1024.)); } else G_message(_("%.2f MB of disk space for temp files."), sdisk / (1024. * 1024.)); } else G_message(_("%.2f KB of disk space for temp files."), sdisk / 1024.); } else G_message(_("%d bytes of disk space for temp files."), sdisk); fstar2 = fi * fi / 4.; tfsta2 = fstar2 + fstar2; deltx = winhd.east - winhd.west; delty = winhd.north - winhd.south; xmin = winhd.west; xmax = winhd.east; ymin = winhd.south; ymax = winhd.north; if (smooth != NULL) smc = -9999; else smc = 0.01; if (Rast_read_fp_range(input, "", &range) >= 0) { Rast_get_fp_range_min_max(&range, &cellmin, &cellmax); } else { cellrow = Rast_allocate_f_buf(); for (m1 = 0; m1 < inp_rows; m1++) { Rast_get_f_row(fdinp, cellrow, m1); Rast_row_update_fp_range(cellrow, m1, &range, FCELL_TYPE); } Rast_get_fp_range_min_max(&range, &cellmin, &cellmax); } fcellmin = (float)cellmin; if (Rast_is_f_null_value(&fcellmin)) G_fatal_error(_("Maximum value of a raster map is NULL.")); zmin = (double)cellmin *zmult; zmax = (double)cellmax *zmult; G_debug(1, "zmin=%f, zmax=%f", zmin, zmax); if (fd4 != NULL) fprintf(fd4, "deltx,delty %f %f \n", deltx, delty); create_temp_files(); IL_init_params_2d(¶ms, NULL, 1, 1, zmult, KMIN, KMAX, maskmap, outhd.rows, outhd.cols, az, adx, ady, adxx, adyy, adxy, fi, MAXPOINTS, SCIK1, SCIK2, SCIK3, smc, elev, slope, aspect, pcurv, tcurv, mcurv, dmin, inp_x_orig, inp_y_orig, deriv, theta, scalex, Tmp_fd_z, Tmp_fd_dx, Tmp_fd_dy, Tmp_fd_xx, Tmp_fd_yy, Tmp_fd_xy, NULL, NULL, 0, NULL); /* In the above line, the penultimate argument is supposed to be a * deviations file pointer. None is obvious, so I used NULL. */ /* The 3rd and 4th argument are int-s, elatt and smatt (from the function * definition. The value 1 seemed like a good placeholder... or not. */ IL_init_func_2d(¶ms, IL_grid_calc_2d, IL_matrix_create, IL_check_at_points_2d, IL_secpar_loop_2d, IL_crst, IL_crstg, IL_write_temp_2d); G_message(_("Temporarily changing the region to desired resolution ...")); Rast_set_window(&outhd); bitmask = IL_create_bitmask(¶ms); /* change region to initial region */ G_message(_("Changing back to the original region ...")); Rast_set_window(&winhd); ertot = 0.; cursegm = 0; G_message(_("Percent complete: ")); NPOINT = IL_resample_interp_segments_2d(¶ms, bitmask, zmin, zmax, &zminac, &zmaxac, &gmin, &gmax, &c1min, &c1max, &c2min, &c2max, &ertot, nsizc, &dnorm, overlap, inp_rows, inp_cols, fdsmooth, fdinp, ns_res, ew_res, inp_ns_res, inp_ew_res, dtens); G_message(_("dnorm in mainc after grid before out1= %f"), dnorm); if (NPOINT < 0) { clean(); G_fatal_error(_("split_and_interpolate() failed")); } if (fd4 != NULL) fprintf(fd4, "max. error found = %f \n", ertot); G_free_vector(az); if (cond1) { G_free_vector(adx); G_free_vector(ady); if (cond2) { G_free_vector(adxx); G_free_vector(adyy); G_free_vector(adxy); } } G_message(_("dnorm in mainc after grid before out2= %f"), dnorm); if (IL_resample_output_2d(¶ms, zmin, zmax, zminac, zmaxac, c1min, c1max, c2min, c2max, gmin, gmax, ertot, input, &dnorm, &outhd, &winhd, smooth, NPOINT) < 0) { clean(); G_fatal_error(_("Unable to write raster maps -- try increasing cell size")); } G_free(zero_array_cell); clean(); if (fd4) fclose(fd4); Rast_close(fdinp); if (smooth != NULL) Rast_close(fdsmooth); G_done_msg(" "); exit(EXIT_SUCCESS); }
int main( int argc, char **argv ) { char *mapset = 0; char *name = 0; struct GModule *module; struct Option *map; struct Option *win; struct Option *format; struct Cell_head window; RASTER_MAP_TYPE raster_type; /* Initialize the GIS calls */ G_gisinit( argv[0] ); module = G_define_module(); module->description = ( "Output raster map layers in a format suitable for display in QGIS" ); map = G_define_standard_option( G_OPT_R_MAP ); map->description = ( "Raster map to be displayed" ); format = G_define_option(); format->key = "format"; format->type = TYPE_STRING; format->description = "format"; format->options = "color,value"; win = G_define_option(); win->key = "window"; win->type = TYPE_DOUBLE; win->multiple = YES; win->description = "xmin,ymin,xmax,ymax,ncols,nrows"; if ( G_parser( argc, argv ) ) exit( EXIT_FAILURE ); name = map->answer; /* Make sure map is available */ #if GRASS_VERSION_MAJOR < 7 mapset = G_find_cell2( name, "" ); if ( !mapset ) G_fatal_error( ( "Raster map <%s> not found" ), name ); #else mapset = ""; #endif /* It can happen that GRASS data set is 'corrupted' and zone differs in WIND and * cellhd, and G_open_cell_old fails, so it is better to read window from map */ /* G_get_window( &window ); */ G_get_cellhd( name, mapset, &window ); window.west = atof( win->answers[0] ); window.south = atof( win->answers[1] ); window.east = atof( win->answers[2] ); window.north = atof( win->answers[3] ); window.cols = atoi( win->answers[4] ); window.rows = atoi( win->answers[5] ); G_adjust_Cell_head( &window, 1, 1 ); G_set_window( &window ); G_suppress_masking(); // must be after G_set_window() raster_type = G_raster_map_type( name, "" ); display( name, mapset, raster_type, format->answer ); exit( EXIT_SUCCESS ); }