3 // dem.c -- DEM management class
5 // Written by Curtis Olson, started March 1998.
7 // Copyright (C) 1998 Curtis L. Olson - curt@me.umn.edu
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // General Public License for more details.
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 // (Log is kept at end of this file)
27 #include <ctype.h> // isspace()
28 #include <math.h> // rint()
30 #include <stdlib.h> // atoi()
32 #include <sys/stat.h> // stat()
33 #include <unistd.h> // stat()
36 #include "leastsqs.hxx"
38 #include <Include/fg_constants.h>
42 # define MKDIR(a) mkdir(a,S_IRWXU) // I am just guessing at this flag (NHV)
46 fgDEM::fgDEM( void ) {
47 // printf("class fgDEM CONstructor called.\n");
48 dem_data = new float[DEM_SIZE_1][DEM_SIZE_1];
49 output_data = new float[DEM_SIZE_1][DEM_SIZE_1];
55 // return the file path name ( foo/bar/file.ext = foo/bar )
56 void extract_path (char *in, char *base) {
63 while ( (i >= 0) && (in[i] != '/') ) {
71 // Make a subdirectory
72 int my_mkdir (char *dir) {
78 result = stat (dir, &stat_buf);
82 result = stat (dir, &stat_buf);
84 printf ("problem creating %s\n", dir);
86 printf ("%s created\n", dir);
89 printf ("%s already exists\n", dir);
99 int fgDEM::open ( char *file ) {
100 // open input file (or read from stdin)
101 if ( strcmp(file, "-") == 0 ) {
102 printf("Loading DEM data file: stdin\n");
105 if ( (fd = fopen(file, "r")) == NULL ) {
106 printf("Cannot open %s\n", file);
109 printf("Loading DEM data file: %s\n", file);
117 int fgDEM::close ( void ) {
124 // return next token from input stream
125 static void next_token(FILE *fd, char *token) {
128 result = fscanf(fd, "%s", token);
130 if ( result == EOF ) {
131 strcpy(token, "__END_OF_FILE__");
132 printf(" Warning: Reached end of file!\n");
135 // printf(" returning %s\n", token);
139 // return next integer from input stream
140 static int next_int(FILE *fd) {
143 next_token(fd, token);
144 return ( atoi(token) );
148 // return next double from input stream
149 static double next_double(FILE *fd) {
152 next_token(fd, token);
153 return ( atof(token) );
157 // return next exponential num from input stream
158 static int next_exp(FILE *fd) {
163 fscanf(fd, "%lfD%d", &mantissa, &exp);
165 // printf(" Mantissa = %.4f Exp = %d\n", mantissa, exp);
169 for ( i = 1; i <= exp; i++ ) {
172 } else if ( exp < 0 ) {
173 for ( i = -1; i >= exp; i-- ) {
178 return( (int)rint(mantissa * (double)acc) );
182 // read and parse DEM "A" record
183 void fgDEM::read_a_record( void ) {
190 // get the name field (144 characters)
191 for ( i = 0; i < 144; i++ ) {
196 // clean off the whitespace at the end
197 for ( i = strlen(name)-2; i > 0; i-- ) {
198 if ( !isspace(name[i]) ) {
204 printf(" Quad name field: %s\n", name);
206 // DEM level code, 3 reflects processing by DMA
208 printf(" DEM level code = %d\n", inum);
210 // Pattern code, 1 indicates a regular elevation pattern
212 printf(" Pattern code = %d\n", inum);
214 // Planimetric reference system code, 0 indicates geographic
215 // coordinate system.
217 printf(" Planimetric reference code = %d\n", inum);
221 printf(" Zone code = %d\n", inum);
223 // Map projection parameters (ignored)
224 for ( i = 0; i < 15; i++ ) {
225 dnum = next_double(fd);
226 // printf("%d: %f\n",i,dnum);
229 // Units code, 3 represents arc-seconds as the unit of measure for
230 // ground planimetric coordinates throughout the file.
233 printf(" Unknown (X,Y) units code = %d!\n", inum);
237 // Units code; 2 represents meters as the unit of measure for
238 // elevation coordinates throughout the file.
241 printf(" Unknown (Z) units code = %d!\n", inum);
245 // Number (n) of sides in the polygon which defines the coverage of
246 // the DEM file (usually equal to 4).
249 printf(" Unknown polygon dimension = %d!\n", inum);
253 // Ground coordinates of bounding box in arc-seconds
254 dem_x1 = originx = next_exp(fd);
255 dem_y1 = originy = next_exp(fd);
256 printf(" Origin = (%.2f,%.2f)\n", originx, originy);
258 dem_x2 = next_exp(fd);
259 dem_y2 = next_exp(fd);
261 dem_x3 = next_exp(fd);
262 dem_y3 = next_exp(fd);
264 dem_x4 = next_exp(fd);
265 dem_y4 = next_exp(fd);
267 // Minimum/maximum elevations in meters
268 dem_z1 = next_exp(fd);
269 dem_z2 = next_exp(fd);
270 printf(" Elevation range %.4f %.4f\n", dem_z1, dem_z2);
272 // Counterclockwise angle from the primary axis of ground
273 // planimetric referenced to the primary axis of the DEM local
275 next_token(fd, token);
277 // Accuracy code; 0 indicates that a record of accuracy does not
278 // exist and that no record type C will follow.
280 // DEM spacial resolution. Usually (3,3,1) (3,6,1) or (3,9,1)
281 // depending on latitude
283 // I will eventually have to do something with this for data at
284 // higher latitudes */
285 next_token(fd, token);
286 printf(" accuracy & spacial resolution string = %s\n", token);
288 printf(" length = %d\n", i);
290 ptr = token + i - 12;
291 printf(" last field = %s = %.2f\n", ptr, atof(ptr));
295 col_step = atof(ptr);
296 printf(" last field = %s = %.2f\n", ptr, col_step);
300 row_step = atof(ptr);
301 printf(" last field = %s = %.2f\n", ptr, row_step);
304 // accuracy code = atod(token)
306 printf(" Accuracy code = %d\n", inum);
308 printf(" column step = %.2f row step = %.2f\n",
310 // dimension of arrays to follow (1)
311 next_token(fd, token);
313 // number of profiles
314 dem_num_profiles = cols = next_int(fd);
315 printf(" Expecting %d profiles\n", dem_num_profiles);
319 // read and parse DEM "B" record
320 void fgDEM::read_b_record( void ) {
324 // row / column id of this profile
325 prof_row = next_int(fd);
326 prof_col = next_int(fd);
327 // printf("col id = %d row id = %d\n", prof_col, prof_row);
329 // Number of columns and rows (elevations) in this profile
330 prof_num_rows = rows = next_int(fd);
331 prof_num_cols = next_int(fd);
332 // printf(" profile num rows = %d\n", prof_num_rows);
334 // Ground planimetric coordinates (arc-seconds) of the first
335 // elevation in the profile
336 prof_x1 = next_exp(fd);
337 prof_y1 = next_exp(fd);
338 // printf(" Starting at %.2f %.2f\n", prof_x1, prof_y1);
340 // Elevation of local datum for the profile. Always zero for
341 // 1-degree DEM, the reference is mean sea level.
342 next_token(fd, token);
344 // Minimum and maximum elevations for the profile.
345 next_token(fd, token);
346 next_token(fd, token);
348 // One (usually) dimensional array (prof_num_cols,1) of elevations
349 for ( i = 0; i < prof_num_rows; i++ ) {
350 prof_data = next_int(fd);
351 dem_data[cur_col][i] = (float)prof_data;
357 int fgDEM::parse( void ) {
364 for ( i = 0; i < dem_num_profiles; i++ ) {
365 // printf("Ready to read next b record\n");
369 if ( cur_col % 100 == 0 ) {
370 printf(" loaded %d profiles of data\n", cur_col);
374 printf(" Done parsing\n");
380 // return the current altitude based on mesh data. We should rewrite
381 // this to interpolate exact values, but for now this is good enough
382 double fgDEM::interpolate_altitude( double lon, double lat ) {
383 // we expect incoming (lon,lat) to be in arcsec for now
385 double xlocal, ylocal, dx, dy, zA, zB, elev;
386 int x1, x2, x3, y1, y2, y3;
390 /* determine if we are in the lower triangle or the upper triangle
398 then calculate our end points
401 xlocal = (lon - originx) / col_step;
402 ylocal = (lat - originy) / row_step;
404 xindex = (int)(xlocal);
405 yindex = (int)(ylocal);
407 // printf("xindex = %d yindex = %d\n", xindex, yindex);
409 if ( xindex + 1 == cols ) {
413 if ( yindex + 1 == rows ) {
417 if ( (xindex < 0) || (xindex + 1 >= cols) ||
418 (yindex < 0) || (yindex + 1 >= rows) ) {
422 dx = xlocal - xindex;
423 dy = ylocal - yindex;
427 // printf(" Lower triangle\n");
431 z1 = dem_data[x1][y1];
435 z2 = dem_data[x2][y2];
439 z3 = dem_data[x3][y3];
441 // printf(" dx = %.2f dy = %.2f\n", dx, dy);
442 // printf(" (x1,y1,z1) = (%d,%d,%d)\n", x1, y1, z1);
443 // printf(" (x2,y2,z2) = (%d,%d,%d)\n", x2, y2, z2);
444 // printf(" (x3,y3,z3) = (%d,%d,%d)\n", x3, y3, z3);
446 zA = dx * (z2 - z1) + z1;
447 zB = dx * (z3 - z1) + z1;
449 // printf(" zA = %.2f zB = %.2f\n", zA, zB);
451 if ( dx > FG_EPSILON ) {
452 elev = dy * (zB - zA) / dx + zA;
458 // printf(" Upper triangle\n");
462 z1 = dem_data[x1][y1];
466 z2 = dem_data[x2][y2];
470 z3 = dem_data[x3][y3];
472 // printf(" dx = %.2f dy = %.2f\n", dx, dy);
473 // printf(" (x1,y1,z1) = (%d,%d,%d)\n", x1, y1, z1);
474 // printf(" (x2,y2,z2) = (%d,%d,%d)\n", x2, y2, z2);
475 // printf(" (x3,y3,z3) = (%d,%d,%d)\n", x3, y3, z3);
477 zA = dy * (z2 - z1) + z1;
478 zB = dy * (z3 - z1) + z1;
480 // printf(" zA = %.2f zB = %.2f\n", zA, zB );
481 // printf(" xB - xA = %.2f\n", col_step * dy / row_step);
483 if ( dy > FG_EPSILON ) {
484 elev = dx * (zB - zA) / dy + zA;
494 // Use least squares to fit a simpler data set to dem data
495 void fgDEM::fit( char *fg_root, double error, struct fgBUCKET *p ) {
496 double x[DEM_SIZE_1], y[DEM_SIZE_1];
497 double m, b, ave_error, max_error;
499 int n, row, start, end, good_fit;
500 int colmin, colmax, rowmin, rowmax;
501 // FILE *dem, *fit, *fit1;
503 printf("Initializing output mesh structure\n");
506 // determine dimensions
507 colmin = p->x * ( (cols - 1) / 8);
508 colmax = colmin + ( (cols - 1) / 8);
509 rowmin = p->y * ( (rows - 1) / 8);
510 rowmax = rowmin + ( (rows - 1) / 8);
511 printf("Fitting region = %d,%d to %d,%d\n", colmin, rowmin, colmax, rowmax);
513 // include the corners explicitly
514 outputmesh_set_pt(colmin, rowmin, dem_data[colmin][rowmin]);
515 outputmesh_set_pt(colmin, rowmax, dem_data[colmin][rowmax]);
516 outputmesh_set_pt(colmax, rowmax, dem_data[colmax][rowmax]);
517 outputmesh_set_pt(colmax, rowmin, dem_data[colmax][rowmin]);
519 printf("Beginning best fit procedure\n");
521 for ( row = rowmin; row <= rowmax; row++ ) {
522 // fit = fopen("fit.dat", "w");
523 // fit1 = fopen("fit1.dat", "w");
527 // printf(" fitting row = %d\n", row);
529 while ( start < colmax ) {
533 x[(end - start) - 1] = 0.0 + ( start * col_step );
534 y[(end - start) - 1] = dem_data[start][row];
536 while ( (end <= colmax) && good_fit ) {
537 n = (end - start) + 1;
538 // printf("Least square of first %d points\n", n);
539 x[end - start] = 0.0 + ( end * col_step );
540 y[end - start] = dem_data[end][row];
541 least_squares(x, y, n, &m, &b);
542 ave_error = least_squares_error(x, y, n, m, b);
543 max_error = least_squares_max_error(x, y, n, m, b);
546 printf("%d - %d ave error = %.2f max error = %.2f y = %.2f*x + %.2f\n",
547 start, end, ave_error, max_error, m, b);
549 f = fopen("gnuplot.dat", "w");
550 for ( j = 0; j <= end; j++) {
551 fprintf(f, "%.2f %.2f\n", 0.0 + ( j * col_step ),
554 for ( j = start; j <= end; j++) {
555 fprintf(f, "%.2f %.2f\n", 0.0 + ( j * col_step ),
560 printf("Please hit return: "); gets(junk);
563 if ( max_error > error ) {
571 // error exceeded the threshold, back up
572 end -= 2; // back "end" up to the last good enough fit
573 n--; // back "n" up appropriately too
575 // we popped out of the above loop while still within
576 // the error threshold, so we must be at the end of
581 least_squares(x, y, n, &m, &b);
582 ave_error = least_squares_error(x, y, n, m, b);
583 max_error = least_squares_max_error(x, y, n, m, b);
587 printf("%d - %d ave error = %.2f max error = %.2f y = %.2f*x + %.2f\n",
588 start, end, ave_error, max_error, m, b);
591 fprintf(fit1, "%.2f %.2f\n", x[0], m * x[0] + b);
592 fprintf(fit1, "%.2f %.2f\n", x[end-start], m * x[end-start] + b);
595 if ( start > colmin ) {
596 // skip this for the first line segment
598 outputmesh_set_pt(start, row, (lasty + cury) / 2);
599 // fprintf(fit, "%.2f %.2f\n", x[0], (lasty + cury) / 2);
602 lasty = m * x[end-start] + b;
610 dem = fopen("gnuplot.dat", "w");
611 for ( j = 0; j < DEM_SIZE_1; j++) {
612 fprintf(dem, "%.2f %.2f\n", 0.0 + ( j * col_step ),
618 // NOTICE, this is for testing only. This instance of
619 // output_nodes should be removed. It should be called only
620 // once at the end once all the nodes have been generated.
621 // newmesh_output_nodes(&nm, "mesh.node");
622 // printf("Please hit return: "); gets(junk);
625 outputmesh_output_nodes(fg_root, p);
629 // Initialize output mesh structure
630 void fgDEM::outputmesh_init( void ) {
633 for ( j = 0; j < DEM_SIZE_1; j++ ) {
634 for ( i = 0; i < DEM_SIZE_1; i++ ) {
635 output_data[i][j] = -9999.0;
641 // Get the value of a mesh node
642 double fgDEM::outputmesh_get_pt( int i, int j ) {
643 return ( output_data[i][j] );
647 // Set the value of a mesh node
648 void fgDEM::outputmesh_set_pt( int i, int j, double value ) {
649 // printf("Setting data[%d][%d] = %.2f\n", i, j, value);
650 output_data[i][j] = value;
654 // Write out a node file that can be used by the "triangle" program
655 void fgDEM::outputmesh_output_nodes( char *fg_root, struct fgBUCKET *p ) {
656 struct stat stat_buf;
657 char base_path[256], dir[256], file[256];
664 int colmin, colmax, rowmin, rowmax;
665 int i, j, count, result;
667 // determine dimensions
668 colmin = p->x * ( (cols - 1) / 8);
669 colmax = colmin + ( (cols - 1) / 8);
670 rowmin = p->y * ( (rows - 1) / 8);
671 rowmax = rowmin + ( (rows - 1) / 8);
672 printf(" dumping region = %d,%d to %d,%d\n",
673 colmin, rowmin, colmax, rowmax);
675 // generate the base directory
676 fgBucketGenBasePath(p, base_path);
677 printf("fg_root = %s Base Path = %s\n", fg_root, base_path);
678 sprintf(dir, "%s/Scenery/%s", fg_root, base_path);
679 printf("Dir = %s\n", dir);
681 // stat() directory and create if needed
682 result = stat(dir, &stat_buf);
684 printf("Stat error need to create directory\n");
688 sprintf(command, "mkdir -p %s\n", dir);
693 // Cygwin crashes when trying to output to node file
694 // explicitly making directory structure seems OK on Win95
696 extract_path (base_path, tmp_path);
698 sprintf (dir, "%s/Scenery", fg_root);
699 if (my_mkdir (dir)) { exit (-1); }
701 sprintf (dir, "%s/Scenery/%s", fg_root, tmp_path);
702 if (my_mkdir (dir)) { exit (-1); }
704 sprintf (dir, "%s/Scenery/%s", fg_root, base_path);
705 if (my_mkdir (dir)) { exit (-1); }
710 // assume directory exists
713 // get index and generate output file name
714 index = fgBucketGenIndex(p);
715 sprintf(file, "%s/%ld.node", dir, index);
717 printf("Creating node file: %s\n", file);
718 fd = fopen(file, "w");
720 // first count nodes to generate header
722 for ( j = rowmin; j <= rowmax; j++ ) {
723 for ( i = colmin; i <= colmax; i++ ) {
724 if ( output_data[i][j] > -9000.0 ) {
728 // printf(" count = %d\n", count);
730 fprintf(fd, "%d 2 1 0\n", count);
732 // now write out actual node data
734 for ( j = rowmin; j <= rowmax; j++ ) {
735 for ( i = colmin; i <= colmax; i++ ) {
736 if ( output_data[i][j] > -9000.0 ) {
737 fprintf(fd, "%d %.2f %.2f %.2f\n",
739 originx + (double)i * col_step,
740 originy + (double)j * row_step,
744 // printf(" count = %d\n", count);
751 fgDEM::~fgDEM( void ) {
752 // printf("class fgDEM DEstructor called.\n");
757 // Revision 1.2 1998/04/14 02:43:27 curt
758 // Used "new" to auto-allocate large DEM parsing arrays in class constructor.
760 // Revision 1.1 1998/04/08 22:57:22 curt
761 // Adopted Gnu automake/autoconf system.
763 // Revision 1.3 1998/04/06 21:09:41 curt
764 // Additional win32 support.
765 // Fixed a bad bug in dem file parsing that was causing the output to be
766 // flipped about x = y.
768 // Revision 1.2 1998/03/23 20:35:41 curt
769 // Updated to use FG_EPSILON
771 // Revision 1.1 1998/03/19 02:54:47 curt
772 // Reorganized into a class lib called fgDEM.
774 // Revision 1.1 1998/03/19 01:46:28 curt