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()
31 #include <sys/stat.h> // stat()
32 #include <unistd.h> // stat()
37 #include <Include/fg_constants.h>
40 fgDEM::fgDEM( void ) {
41 // printf("class fgDEM CONstructor called.\n");
46 int fgDEM::open ( char *file ) {
47 // open input file (or read from stdin)
48 if ( strcmp(file, "-") == 0 ) {
49 printf("Loading DEM data file: stdin\n");
52 if ( (fd = fopen(file, "r")) == NULL ) {
53 printf("Cannot open %s\n", file);
56 printf("Loading DEM data file: %s\n", file);
64 int fgDEM::close ( void ) {
71 // return next token from input stream
72 static void next_token(FILE *fd, char *token) {
75 result = fscanf(fd, "%s", token);
77 if ( result == EOF ) {
78 strcpy(token, "__END_OF_FILE__");
79 printf(" Warning: Reached end of file!\n");
82 // printf(" returning %s\n", token);
86 // return next integer from input stream
87 static int next_int(FILE *fd) {
90 next_token(fd, token);
91 return ( atoi(token) );
95 // return next double from input stream
96 double next_double(FILE *fd) {
99 next_token(fd, token);
100 return ( atof(token) );
104 // return next exponential num from input stream
105 int next_exp(FILE *fd) {
110 fscanf(fd, "%lfD%d", &mantissa, &exp);
112 // printf(" Mantissa = %.4f Exp = %d\n", mantissa, exp);
116 for ( i = 1; i <= exp; i++ ) {
119 } else if ( exp < 0 ) {
120 for ( i = -1; i >= exp; i-- ) {
125 return( (int)rint(mantissa * (double)acc) );
129 // read and parse DEM "A" record
130 void fgDEM::read_a_record( void ) {
137 // get the name field (144 characters)
138 for ( i = 0; i < 144; i++ ) {
143 // clean off the whitespace at the end
144 for ( i = strlen(name)-2; i > 0; i-- ) {
145 if ( !isspace(name[i]) ) {
151 printf(" Quad name field: %s\n", name);
153 // DEM level code, 3 reflects processing by DMA
155 printf(" DEM level code = %d\n", inum);
157 // Pattern code, 1 indicates a regular elevation pattern
159 printf(" Pattern code = %d\n", inum);
161 // Planimetric reference system code, 0 indicates geographic
162 // coordinate system.
164 printf(" Planimetric reference code = %d\n", inum);
168 printf(" Zone code = %d\n", inum);
170 // Map projection parameters (ignored)
171 for ( i = 0; i < 15; i++ ) {
172 dnum = next_double(fd);
173 // printf("%d: %f\n",i,dnum);
176 // Units code, 3 represents arc-seconds as the unit of measure for
177 // ground planimetric coordinates throughout the file.
180 printf(" Unknown (X,Y) units code = %d!\n", inum);
184 // Units code; 2 represents meters as the unit of measure for
185 // elevation coordinates throughout the file.
188 printf(" Unknown (Z) units code = %d!\n", inum);
192 // Number (n) of sides in the polygon which defines the coverage of
193 // the DEM file (usually equal to 4).
196 printf(" Unknown polygon dimension = %d!\n", inum);
200 // Ground coordinates of bounding box in arc-seconds
201 dem_x1 = originx = next_exp(fd);
202 dem_y1 = originy = next_exp(fd);
203 printf(" Origin = (%.2f,%.2f)\n", originx, originy);
205 dem_x2 = next_exp(fd);
206 dem_y2 = next_exp(fd);
208 dem_x3 = next_exp(fd);
209 dem_y3 = next_exp(fd);
211 dem_x4 = next_exp(fd);
212 dem_y4 = next_exp(fd);
214 // Minimum/maximum elevations in meters
215 dem_z1 = next_exp(fd);
216 dem_z2 = next_exp(fd);
217 printf(" Elevation range %.4f %.4f\n", dem_z1, dem_z2);
219 // Counterclockwise angle from the primary axis of ground
220 // planimetric referenced to the primary axis of the DEM local
222 next_token(fd, token);
224 // Accuracy code; 0 indicates that a record of accuracy does not
225 // exist and that no record type C will follow.
227 // DEM spacial resolution. Usually (3,3,1) (3,6,1) or (3,9,1)
228 // depending on latitude
230 // I will eventually have to do something with this for data at
231 // higher latitudes */
232 next_token(fd, token);
233 printf(" accuracy & spacial resolution string = %s\n", token);
235 printf(" length = %d\n", i);
237 ptr = token + i - 12;
238 printf(" last field = %s = %.2f\n", ptr, atof(ptr));
242 col_step = atof(ptr);
243 printf(" last field = %s = %.2f\n", ptr, col_step);
247 row_step = atof(ptr);
248 printf(" last field = %s = %.2f\n", ptr, row_step);
251 // accuracy code = atod(token)
253 printf(" Accuracy code = %d\n", inum);
255 printf(" column step = %.2f row step = %.2f\n",
257 // dimension of arrays to follow (1)
258 next_token(fd, token);
260 // number of profiles
261 dem_num_profiles = rows = next_int(fd);
262 printf(" Expecting %d profiles\n", dem_num_profiles);
266 // read and parse DEM "B" record
267 void fgDEM::read_b_record(float dem_data[DEM_SIZE_1][DEM_SIZE_1])
272 // row / column id of this profile
273 prof_col = next_int(fd);
274 prof_row = next_int(fd);
275 // printf("col id = %d row id = %d\n", prof_col, prof_row);
277 // Number of columns and rows (elevations) in this profile
278 prof_num_cols = cols = next_int(fd);
279 prof_num_rows = next_int(fd);
280 // printf(" profile num rows = %d\n", prof_num_cols);
282 // Ground planimetric coordinates (arc-seconds) of the first
283 // elevation in the profile
284 prof_x1 = next_exp(fd);
285 prof_y1 = next_exp(fd);
286 // printf(" Starting at %.2f %.2f\n", prof_x1, prof_y1);
288 // Elevation of local datum for the profile. Always zero for
289 // 1-degree DEM, the reference is mean sea level.
290 next_token(fd, token);
292 // Minimum and maximum elevations for the profile.
293 next_token(fd, token);
294 next_token(fd, token);
296 // One (usually) dimensional array (prof_num_cols,1) of elevations
297 for ( i = 0; i < prof_num_cols; i++ ) {
298 prof_data = next_int(fd);
299 dem_data[i][cur_row] = (float)prof_data;
305 int fgDEM::parse( float dem_data[DEM_SIZE_1][DEM_SIZE_1] ) {
312 for ( i = 0; i < dem_num_profiles; i++ ) {
313 read_b_record( dem_data );
316 if ( cur_row % 100 == 0 ) {
317 printf(" loaded %d profiles of data\n", cur_row);
321 printf(" Done parsing\n");
327 // return the current altitude based on mesh data. We should rewrite
328 // this to interpolate exact values, but for now this is good enough
329 double fgDEM::interpolate_altitude( float dem_data[DEM_SIZE_1][DEM_SIZE_1],
330 double lon, double lat)
332 // we expect incoming (lon,lat) to be in arcsec for now
334 double xlocal, ylocal, dx, dy, zA, zB, elev;
335 int x1, x2, x3, y1, y2, y3;
339 /* determine if we are in the lower triangle or the upper triangle
347 then calculate our end points
350 xlocal = (lon - originx) / col_step;
351 ylocal = (lat - originy) / row_step;
353 xindex = (int)(xlocal);
354 yindex = (int)(ylocal);
356 // printf("xindex = %d yindex = %d\n", xindex, yindex);
358 if ( xindex + 1 == cols ) {
362 if ( yindex + 1 == rows ) {
366 if ( (xindex < 0) || (xindex + 1 >= cols) ||
367 (yindex < 0) || (yindex + 1 >= rows) ) {
371 dx = xlocal - xindex;
372 dy = ylocal - yindex;
376 // printf(" Lower triangle\n");
380 z1 = dem_data[x1][y1];
384 z2 = dem_data[x2][y2];
388 z3 = dem_data[x3][y3];
390 // printf(" dx = %.2f dy = %.2f\n", dx, dy);
391 // printf(" (x1,y1,z1) = (%d,%d,%d)\n", x1, y1, z1);
392 // printf(" (x2,y2,z2) = (%d,%d,%d)\n", x2, y2, z2);
393 // printf(" (x3,y3,z3) = (%d,%d,%d)\n", x3, y3, z3);
395 zA = dx * (z2 - z1) + z1;
396 zB = dx * (z3 - z1) + z1;
398 // printf(" zA = %.2f zB = %.2f\n", zA, zB);
400 if ( dx > FG_EPSILON ) {
401 elev = dy * (zB - zA) / dx + zA;
407 // printf(" Upper triangle\n");
411 z1 = dem_data[x1][y1];
415 z2 = dem_data[x2][y2];
419 z3 = dem_data[x3][y3];
421 // printf(" dx = %.2f dy = %.2f\n", dx, dy);
422 // printf(" (x1,y1,z1) = (%d,%d,%d)\n", x1, y1, z1);
423 // printf(" (x2,y2,z2) = (%d,%d,%d)\n", x2, y2, z2);
424 // printf(" (x3,y3,z3) = (%d,%d,%d)\n", x3, y3, z3);
426 zA = dy * (z2 - z1) + z1;
427 zB = dy * (z3 - z1) + z1;
429 // printf(" zA = %.2f zB = %.2f\n", zA, zB );
430 // printf(" xB - xA = %.2f\n", col_step * dy / row_step);
432 if ( dy > FG_EPSILON ) {
433 elev = dx * (zB - zA) / dy + zA;
443 // Use least squares to fit a simpler data set to dem data
444 void fgDEM::fit( float dem_data[DEM_SIZE_1][DEM_SIZE_1],
445 float output_data[DEM_SIZE_1][DEM_SIZE_1],
446 char *fg_root, double error, struct fgBUCKET *p )
448 double x[DEM_SIZE_1], y[DEM_SIZE_1];
449 double m, b, ave_error, max_error;
451 int n, row, start, end, good_fit;
452 int colmin, colmax, rowmin, rowmax;
453 // FILE *dem, *fit, *fit1;
455 printf("Initializing output mesh structure\n");
456 outputmesh_init( output_data );
458 // determine dimensions
459 colmin = p->x * ( (cols - 1) / 8);
460 colmax = colmin + ( (cols - 1) / 8);
461 rowmin = p->y * ( (rows - 1) / 8);
462 rowmax = rowmin + ( (rows - 1) / 8);
463 printf("Fitting region = %d,%d to %d,%d\n", colmin, rowmin, colmax, rowmax);
465 // include the corners explicitly
466 outputmesh_set_pt(output_data, colmin, rowmin, dem_data[colmin][rowmin]);
467 outputmesh_set_pt(output_data, colmin, rowmax, dem_data[colmin][rowmax]);
468 outputmesh_set_pt(output_data, colmax, rowmax, dem_data[colmax][rowmax]);
469 outputmesh_set_pt(output_data, colmax, rowmin, dem_data[colmax][rowmin]);
471 printf("Beginning best fit procedure\n");
473 for ( row = rowmin; row <= rowmax; row++ ) {
474 // fit = fopen("fit.dat", "w");
475 // fit1 = fopen("fit1.dat", "w");
479 // printf(" fitting row = %d\n", row);
481 while ( start < colmax ) {
485 x[(end - start) - 1] = 0.0 + ( start * col_step );
486 y[(end - start) - 1] = dem_data[start][row];
488 while ( (end <= colmax) && good_fit ) {
489 n = (end - start) + 1;
490 // printf("Least square of first %d points\n", n);
491 x[end - start] = 0.0 + ( end * col_step );
492 y[end - start] = dem_data[end][row];
493 least_squares(x, y, n, &m, &b);
494 ave_error = least_squares_error(x, y, n, m, b);
495 max_error = least_squares_max_error(x, y, n, m, b);
498 printf("%d - %d ave error = %.2f max error = %.2f y = %.2f*x + %.2f\n",
499 start, end, ave_error, max_error, m, b);
501 f = fopen("gnuplot.dat", "w");
502 for ( j = 0; j <= end; j++) {
503 fprintf(f, "%.2f %.2f\n", 0.0 + ( j * col_step ),
506 for ( j = start; j <= end; j++) {
507 fprintf(f, "%.2f %.2f\n", 0.0 + ( j * col_step ),
512 printf("Please hit return: "); gets(junk);
515 if ( max_error > error ) {
523 // error exceeded the threshold, back up
524 end -= 2; // back "end" up to the last good enough fit
525 n--; // back "n" up appropriately too
527 // we popped out of the above loop while still within
528 // the error threshold, so we must be at the end of
533 least_squares(x, y, n, &m, &b);
534 ave_error = least_squares_error(x, y, n, m, b);
535 max_error = least_squares_max_error(x, y, n, m, b);
539 printf("%d - %d ave error = %.2f max error = %.2f y = %.2f*x + %.2f\n",
540 start, end, ave_error, max_error, m, b);
543 fprintf(fit1, "%.2f %.2f\n", x[0], m * x[0] + b);
544 fprintf(fit1, "%.2f %.2f\n", x[end-start], m * x[end-start] + b);
547 if ( start > colmin ) {
548 // skip this for the first line segment
550 outputmesh_set_pt(output_data, start, row, (lasty + cury) / 2);
551 // fprintf(fit, "%.2f %.2f\n", x[0], (lasty + cury) / 2);
554 lasty = m * x[end-start] + b;
562 dem = fopen("gnuplot.dat", "w");
563 for ( j = 0; j < DEM_SIZE_1; j++) {
564 fprintf(dem, "%.2f %.2f\n", 0.0 + ( j * col_step ),
570 // NOTICE, this is for testing only. This instance of
571 // output_nodes should be removed. It should be called only
572 // once at the end once all the nodes have been generated.
573 // newmesh_output_nodes(&nm, "mesh.node");
574 // printf("Please hit return: "); gets(junk);
577 outputmesh_output_nodes(output_data, fg_root, p);
581 // Initialize output mesh structure
582 void fgDEM::outputmesh_init( float output_data[DEM_SIZE_1][DEM_SIZE_1] ) {
585 for ( i = 0; i < DEM_SIZE_1; i++ ) {
586 for ( j = 0; j < DEM_SIZE_1; j++ ) {
587 output_data[i][j] = -9999.0;
593 // Get the value of a mesh node
594 double fgDEM::outputmesh_get_pt( float output_data[DEM_SIZE_1][DEM_SIZE_1],
597 return ( output_data[i][j] );
601 // Set the value of a mesh node
602 void fgDEM::outputmesh_set_pt( float output_data[DEM_SIZE_1][DEM_SIZE_1],
603 int i, int j, double value )
605 // printf("Setting data[%d][%d] = %.2f\n", i, j, value);
606 output_data[i][j] = value;
610 // Write out a node file that can be used by the "triangle" program
611 void fgDEM::outputmesh_output_nodes( float output_data[DEM_SIZE_1][DEM_SIZE_1],
612 char *fg_root, struct fgBUCKET *p )
614 struct stat stat_buf;
615 char base_path[256], dir[256], file[256];
619 int colmin, colmax, rowmin, rowmax;
620 int i, j, count, result;
622 // determine dimensions
623 colmin = p->x * ( (cols - 1) / 8);
624 colmax = colmin + ( (cols - 1) / 8);
625 rowmin = p->y * ( (rows - 1) / 8);
626 rowmax = rowmin + ( (rows - 1) / 8);
627 printf(" dumping region = %d,%d to %d,%d\n",
628 colmin, rowmin, colmax, rowmax);
630 // generate the base directory
631 fgBucketGenBasePath(p, base_path);
632 printf("fg_root = %s Base Path = %s\n", fg_root, base_path);
633 sprintf(dir, "%s/Scenery/%s", fg_root, base_path);
634 printf("Dir = %s\n", dir);
636 // stat() directory and create if needed
637 result = stat(dir, &stat_buf);
639 printf("Stat error need to create directory\n");
640 sprintf(command, "mkdir -p %s\n", dir);
643 // assume directory exists
646 // get index and generate output file name
647 index = fgBucketGenIndex(p);
648 sprintf(file, "%s/%ld.node", dir, index);
650 printf("Creating node file: %s\n", file);
651 fd = fopen(file, "w");
653 // first count nodes to generate header
655 for ( j = rowmin; j <= rowmax; j++ ) {
656 for ( i = colmin; i <= colmax; i++ ) {
657 if ( output_data[i][j] > -9000.0 ) {
661 // printf(" count = %d\n", count);
663 fprintf(fd, "%d 2 1 0\n", count);
665 // now write out actual node data
667 for ( j = rowmin; j <= rowmax; j++ ) {
668 for ( i = colmin; i <= colmax; i++ ) {
669 if ( output_data[i][j] > -9000.0 ) {
670 fprintf(fd, "%d %.2f %.2f %.2f\n",
672 originx + (double)i * col_step,
673 originy + (double)j * row_step,
677 // printf(" count = %d\n", count);
684 fgDEM::~fgDEM( void ) {
685 // printf("class fgDEM DEstructor called.\n");
690 // Revision 1.2 1998/03/23 20:35:41 curt
691 // Updated to use FG_EPSILON
693 // Revision 1.1 1998/03/19 02:54:47 curt
694 // Reorganized into a class lib called fgDEM.
696 // Revision 1.1 1998/03/19 01:46:28 curt