]> git.mxchange.org Git - flightgear.git/blob - DEM/dem.cxx
8fce8cc977c6bce31c7dac294dee7d3e22831d37
[flightgear.git] / DEM / dem.cxx
1 // -*- Mode: C++ -*-
2 //
3 // dem.c -- DEM management class
4 //
5 // Written by Curtis Olson, started March 1998.
6 //
7 // Copyright (C) 1998  Curtis L. Olson  - curt@me.umn.edu
8 //
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.
13 //
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.
18 //
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.
22 //
23 // $Id$
24 // (Log is kept at end of this file)
25
26
27 #ifdef HAVE_CONFIG_H
28 #  include <config.h>
29 #endif
30
31 #include <Include/compiler.h>
32
33 #include <ctype.h>    // isspace()
34 #include <stdlib.h>   // atoi()
35 #include <math.h>     // rint()
36 #include <stdio.h>
37 #include <string.h>
38 #ifdef HAVE_SYS_STAT_H
39 #  include <sys/stat.h> // stat()
40 #endif
41 #ifdef FG_HAVE_STD_INCLUDES
42 #  include <cerrno>
43 #else
44 #  include <errno.h>
45 #endif
46 #ifdef HAVE_UNISTD_H
47 # include <unistd.h>   // stat()
48 #endif
49 #include <string>
50
51 #include STL_IOSTREAM
52
53 // #include <zlib/zlib.h>
54 #include <Misc/fgstream.hxx>
55 #include <Misc/strutils.hxx>
56 #include <Include/compiler.h>
57 FG_USING_NAMESPACE(std);
58
59 #include "dem.hxx"
60 #include "leastsqs.hxx"
61
62 #include <Include/fg_constants.h>
63
64
65 #define MAX_EX_NODES 10000
66
67 #if 0
68 #ifdef WIN32
69 # ifdef __BORLANDC__
70 #  include <dir.h>
71 #  define MKDIR(a) mkdir(a)
72 # else
73 #  define MKDIR(a) mkdir(a,S_IRWXU)  // I am just guessing at this flag (NHV)
74 # endif // __BORLANDC__
75 #endif // WIN32
76 #endif //0
77
78
79 fgDEM::fgDEM( void ) {
80     // printf("class fgDEM CONstructor called.\n");
81     dem_data = new float[DEM_SIZE_1][DEM_SIZE_1];
82     output_data = new float[DEM_SIZE_1][DEM_SIZE_1];
83 }
84
85
86 #if 0
87 #ifdef WIN32
88
89 // return the file path name ( foo/bar/file.ext = foo/bar )
90 static void extract_path ( const char *in, char *base) {
91     int len, i;
92     
93     len = strlen (in);
94     strcpy (base, in);
95
96     i = len - 1;
97     while ( (i >= 0) && (in[i] != '/') ) {
98         i--;
99     }
100
101     base[i] = '\0';
102 }
103
104
105 // Make a subdirectory
106 static int my_mkdir (const char *dir) {
107     struct stat stat_buf;
108     int result;
109
110     printf ("mk_dir() ");
111
112     result = stat (dir, &stat_buf);
113
114     if (result != 0) {
115         MKDIR (dir);
116         result = stat (dir, &stat_buf);
117         if (result != 0) {
118             printf ("problem creating %s\n", dir);
119         } else {
120             printf ("%s created\n", dir);
121         }
122     } else {
123         printf ("%s already exists\n", dir);
124     }
125
126     return (result);
127 }
128
129 #endif // WIN32
130 #endif //0
131
132
133 // open a DEM file
134 int fgDEM::open ( const string& file ) {
135     // open input file (or read from stdin)
136     if ( file ==  "-" ) {
137         printf("Loading DEM data file: stdin\n");
138         // fd = stdin;
139         // fd = gzdopen(STDIN_FILENO, "r");
140         printf("Not yet ported ...\n");
141         return 0;
142     } else {
143         in = new fg_gzifstream( file );
144         if ( !(*in) ) {
145             cout << "Cannot open " << file << endl;
146             return 0;
147         }
148         cout << "Loading DEM data file: " << file << endl;
149     }
150
151     return 1;
152 }
153
154
155 // close a DEM file
156 int fgDEM::close () {
157     // the fg_gzifstream doesn't seem to have a close()
158
159     delete in;
160
161     return 1;
162 }
163
164
165 // return next token from input stream
166 string fgDEM::next_token() {
167     string token;
168
169     *in >> token;
170
171     // cout << "    returning " + token + "\n";
172
173     return token;
174 }
175
176
177 // return next integer from input stream
178 int fgDEM::next_int() {
179     int result;
180     
181     *in >> result;
182
183     return result;
184 }
185
186
187 // return next double from input stream
188 double fgDEM::next_double() {
189     double result;
190
191     *in >> result;
192
193     return result;
194 }
195
196
197 // return next exponential num from input stream
198 double fgDEM::next_exp() {
199     string token;
200     double mantissa;
201     int exp, acc;
202     int i;
203
204     token = next_token();
205
206 #if 1
207     const char* p = token.c_str();
208     char buf[64];
209     char* bp = buf;
210     
211     for ( ; *p != 0; ++p )
212     {
213         if ( *p == 'D' )
214             *bp++ = 'E';
215         else
216             *bp++ = *p;
217     }
218     *bp = 0;
219     return ::atof( buf );
220 #else
221     sscanf(token.c_str(), "%lfD%d", &mantissa, &exp);
222
223     // cout << "    Mantissa = " << mantissa << "  Exp = " << exp << "\n";
224
225     acc = 1;
226     if ( exp > 0 ) {
227         for ( i = 1; i <= exp; i++ ) {
228             acc *= 10;
229         }
230     } else if ( exp < 0 ) {
231         for ( i = -1; i >= exp; i-- ) {
232             acc /= 10;
233         }
234     }
235
236     return( (int)rint(mantissa * (double)acc) );
237 #endif
238 }
239
240
241 // read and parse DEM "A" record
242 int fgDEM::read_a_record() {
243     int i, inum;
244     double dnum;
245     string name, token;
246     char c;
247     char *ptr;
248
249     // get the name field (144 characters)
250     for ( i = 0; i < 144; i++ ) {
251         in->get(c);
252         name += c;
253     }
254   
255     // clean off the trailing whitespace
256     name = trim(name);
257     cout << "    Quad name field: " << name << endl;
258
259     // DEM level code, 3 reflects processing by DMA
260     inum = next_int();
261     cout << "    DEM level code = " << inum << "\n";
262
263     if ( inum > 3 ) {
264         return 0;
265     }
266
267     // Pattern code, 1 indicates a regular elevation pattern
268     inum = next_int();
269     cout << "    Pattern code = " << inum << "\n";
270
271     // Planimetric reference system code, 0 indicates geographic
272     // coordinate system.
273     inum = next_int();
274     cout << "    Planimetric reference code = " << inum << "\n";
275
276     // Zone code
277     inum = next_int();
278     cout << "    Zone code = " << inum << "\n";
279
280     // Map projection parameters (ignored)
281     for ( i = 0; i < 15; i++ ) {
282         dnum = next_exp();
283         // printf("%d: %f\n",i,dnum);
284     }
285
286     // Units code, 3 represents arc-seconds as the unit of measure for
287     // ground planimetric coordinates throughout the file.
288     inum = next_int();
289     if ( inum != 3 ) {
290         cout << "    Unknown (X,Y) units code = " << inum << "!\n";
291         exit(-1);
292     }
293
294     // Units code; 2 represents meters as the unit of measure for
295     // elevation coordinates throughout the file.
296     inum = next_int();
297     if ( inum != 2 ) {
298         cout << "    Unknown (Z) units code = " << inum << "!\n";
299         exit(-1);
300     }
301
302     // Number (n) of sides in the polygon which defines the coverage of
303     // the DEM file (usually equal to 4).
304     inum = next_int();
305     if ( inum != 4 ) {
306         cout << "    Unknown polygon dimension = " << inum << "!\n";
307         exit(-1);
308     }
309
310     // Ground coordinates of bounding box in arc-seconds
311     dem_x1 = originx = next_exp();
312     dem_y1 = originy = next_exp();
313     cout << "    Origin = (" << originx << "," << originy << ")\n";
314
315     dem_x2 = next_exp();
316     dem_y2 = next_exp();
317
318     dem_x3 = next_exp();
319     dem_y3 = next_exp();
320
321     dem_x4 = next_exp();
322     dem_y4 = next_exp();
323
324     // Minimum/maximum elevations in meters
325     dem_z1 = next_exp();
326     dem_z2 = next_exp();
327     cout << "    Elevation range " << dem_z1 << " to " << dem_z2 << "\n";
328
329     // Counterclockwise angle from the primary axis of ground
330     // planimetric referenced to the primary axis of the DEM local
331     // reference system.
332     token = next_token();
333
334     // Accuracy code; 0 indicates that a record of accuracy does not
335     // exist and that no record type C will follow.
336
337     // DEM spacial resolution.  Usually (3,3,1) (3,6,1) or (3,9,1)
338     // depending on latitude
339
340     // I will eventually have to do something with this for data at
341     // higher latitudes */
342     token = next_token();
343     cout << "    accuracy & spacial resolution string = " << token << endl;
344     i = token.length();
345     cout << "    length = " << i << "\n";
346
347 #if 1
348     inum = atoi( token.substr( 0, i - 36 ) );
349     row_step = atof( token.substr( i - 36, 12 ) );
350     col_step = atof( token.substr( i - 24, 12 ) );
351     //token.substr( 25, 12 )
352 #else
353     ptr = token.c_str() + i - 12;
354     cout << "    last field = " << ptr << " = " << atof(ptr) << "\n";
355     ptr[0] = '\0';
356
357     ptr = ptr - 12;
358     col_step = atof(ptr);
359     cout << "    last field = " << ptr << " = " << col_step << "\n";
360     ptr[0] = '\0';
361
362     ptr = ptr - 12;
363     row_step = atof(ptr);
364     cout << "    last field = " << ptr << " = " << row_step << "\n";
365     ptr[0] = '\0';
366
367     // accuracy code = atod(token)
368     ptr = ptr - 12;
369     inum = atoi(ptr);
370 #endif
371     cout << "    Accuracy code = " << inum << "\n";
372
373     cout << "    column step = " << col_step << 
374         "  row step = " << row_step << "\n";
375
376     // dimension of arrays to follow (1)
377     token = next_token();
378
379     // number of profiles
380     dem_num_profiles = cols = next_int();
381     cout << "    Expecting " << dem_num_profiles << " profiles\n";
382
383     return 1;
384 }
385
386
387 // read and parse DEM "B" record
388 void fgDEM::read_b_record( ) {
389     string token;
390     int i;
391
392     // row / column id of this profile
393     prof_row = next_int();
394     prof_col = next_int();
395     // printf("col id = %d  row id = %d\n", prof_col, prof_row);
396
397     // Number of columns and rows (elevations) in this profile
398     prof_num_rows = rows = next_int();
399     prof_num_cols = next_int();
400     // printf("    profile num rows = %d\n", prof_num_rows);
401
402     // Ground planimetric coordinates (arc-seconds) of the first
403     // elevation in the profile
404     prof_x1 = next_exp();
405     prof_y1 = next_exp();
406     // printf("    Starting at %.2f %.2f\n", prof_x1, prof_y1);
407
408     // Elevation of local datum for the profile.  Always zero for
409     // 1-degree DEM, the reference is mean sea level.
410     token = next_token();
411
412     // Minimum and maximum elevations for the profile.
413     token = next_token();
414     token = next_token();
415
416     // One (usually) dimensional array (prof_num_cols,1) of elevations
417     for ( i = 0; i < prof_num_rows; i++ ) {
418         prof_data = next_int();
419         dem_data[cur_col][i] = (float)prof_data;
420     }
421 }
422
423
424 // parse dem file
425 int fgDEM::parse( ) {
426     int i;
427
428     cur_col = 0;
429
430     if ( !read_a_record() ) {
431         return(0);
432     }
433
434     for ( i = 0; i < dem_num_profiles; i++ ) {
435         // printf("Ready to read next b record\n");
436         read_b_record();
437         cur_col++;
438
439         if ( cur_col % 100 == 0 ) {
440             cout << "    loaded " << cur_col << " profiles of data\n";
441         }
442     }
443
444     cout << "    Done parsing\n";
445
446     return 1;
447 }
448
449
450 // return the current altitude based on mesh data.  We should rewrite
451 // this to interpolate exact values, but for now this is good enough
452 double fgDEM::interpolate_altitude( double lon, double lat ) {
453     // we expect incoming (lon,lat) to be in arcsec for now
454
455     double xlocal, ylocal, dx, dy, zA, zB, elev;
456     int x1, x2, x3, y1, y2, y3;
457     float z1, z2, z3;
458     int xindex, yindex;
459
460     /* determine if we are in the lower triangle or the upper triangle 
461        ______
462        |   /|
463        |  / |
464        | /  |
465        |/   |
466        ------
467
468        then calculate our end points
469      */
470
471     xlocal = (lon - originx) / col_step;
472     ylocal = (lat - originy) / row_step;
473
474     xindex = (int)(xlocal);
475     yindex = (int)(ylocal);
476
477     // printf("xindex = %d  yindex = %d\n", xindex, yindex);
478
479     if ( xindex + 1 == cols ) {
480         xindex--;
481     }
482
483     if ( yindex + 1 == rows ) {
484         yindex--;
485     }
486
487     if ( (xindex < 0) || (xindex + 1 >= cols) ||
488          (yindex < 0) || (yindex + 1 >= rows) ) {
489         return(-9999);
490     }
491
492     dx = xlocal - xindex;
493     dy = ylocal - yindex;
494
495     if ( dx > dy ) {
496         // lower triangle
497         // printf("  Lower triangle\n");
498
499         x1 = xindex; 
500         y1 = yindex; 
501         z1 = dem_data[x1][y1];
502
503         x2 = xindex + 1; 
504         y2 = yindex; 
505         z2 = dem_data[x2][y2];
506                                   
507         x3 = xindex + 1; 
508         y3 = yindex + 1; 
509         z3 = dem_data[x3][y3];
510
511         // printf("  dx = %.2f  dy = %.2f\n", dx, dy);
512         // printf("  (x1,y1,z1) = (%d,%d,%d)\n", x1, y1, z1);
513         // printf("  (x2,y2,z2) = (%d,%d,%d)\n", x2, y2, z2);
514         // printf("  (x3,y3,z3) = (%d,%d,%d)\n", x3, y3, z3);
515
516         zA = dx * (z2 - z1) + z1;
517         zB = dx * (z3 - z1) + z1;
518         
519         // printf("  zA = %.2f  zB = %.2f\n", zA, zB);
520
521         if ( dx > FG_EPSILON ) {
522             elev = dy * (zB - zA) / dx + zA;
523         } else {
524             elev = zA;
525         }
526     } else {
527         // upper triangle
528         // printf("  Upper triangle\n");
529
530         x1 = xindex; 
531         y1 = yindex; 
532         z1 = dem_data[x1][y1];
533
534         x2 = xindex; 
535         y2 = yindex + 1; 
536         z2 = dem_data[x2][y2];
537                                   
538         x3 = xindex + 1; 
539         y3 = yindex + 1; 
540         z3 = dem_data[x3][y3];
541
542         // printf("  dx = %.2f  dy = %.2f\n", dx, dy);
543         // printf("  (x1,y1,z1) = (%d,%d,%d)\n", x1, y1, z1);
544         // printf("  (x2,y2,z2) = (%d,%d,%d)\n", x2, y2, z2);
545         // printf("  (x3,y3,z3) = (%d,%d,%d)\n", x3, y3, z3);
546  
547         zA = dy * (z2 - z1) + z1;
548         zB = dy * (z3 - z1) + z1;
549         
550         // printf("  zA = %.2f  zB = %.2f\n", zA, zB );
551         // printf("  xB - xA = %.2f\n", col_step * dy / row_step);
552
553         if ( dy > FG_EPSILON ) {
554             elev = dx * (zB - zA) / dy    + zA;
555         } else {
556             elev = zA;
557         }
558     }
559
560     return(elev);
561 }
562
563
564 // Use least squares to fit a simpler data set to dem data
565 void fgDEM::fit( double error, fgBUCKET *p ) {
566     double x[DEM_SIZE_1], y[DEM_SIZE_1];
567     double m, b, ave_error, max_error;
568     double cury, lasty;
569     int n, row, start, end;
570     int colmin, colmax, rowmin, rowmax;
571     bool good_fit;
572     // FILE *dem, *fit, *fit1;
573
574     printf("Initializing output mesh structure\n");
575     outputmesh_init();
576
577     // determine dimensions
578     colmin = p->x * ( (cols - 1) / 8);
579     colmax = colmin + ( (cols - 1) / 8);
580     rowmin = p->y * ( (rows - 1) / 8);
581     rowmax = rowmin + ( (rows - 1) / 8);
582     printf("Fitting region = %d,%d to %d,%d\n", colmin, rowmin, colmax, rowmax);
583     
584     // include the corners explicitly
585     outputmesh_set_pt(colmin, rowmin, dem_data[colmin][rowmin]);
586     outputmesh_set_pt(colmin, rowmax, dem_data[colmin][rowmax]);
587     outputmesh_set_pt(colmax, rowmax, dem_data[colmax][rowmax]);
588     outputmesh_set_pt(colmax, rowmin, dem_data[colmax][rowmin]);
589
590     printf("Beginning best fit procedure\n");
591
592     for ( row = rowmin; row <= rowmax; row++ ) {
593         // fit  = fopen("fit.dat",  "w");
594         // fit1 = fopen("fit1.dat", "w");
595
596         start = colmin;
597
598         // printf("    fitting row = %d\n", row);
599
600         while ( start < colmax ) {
601             end = start + 1;
602             good_fit = true;
603
604             x[(end - start) - 1] = 0.0 + ( start * col_step );
605             y[(end - start) - 1] = dem_data[start][row];
606
607             while ( (end <= colmax) && good_fit ) {
608                 n = (end - start) + 1;
609                 // printf("Least square of first %d points\n", n);
610                 x[end - start] = 0.0 + ( end * col_step );
611                 y[end - start] = dem_data[end][row];
612                 least_squares(x, y, n, &m, &b);
613                 ave_error = least_squares_error(x, y, n, m, b);
614                 max_error = least_squares_max_error(x, y, n, m, b);
615
616                 /*
617                 printf("%d - %d  ave error = %.2f  max error = %.2f  y = %.2f*x + %.2f\n", 
618                 start, end, ave_error, max_error, m, b);
619                 
620                 f = fopen("gnuplot.dat", "w");
621                 for ( j = 0; j <= end; j++) {
622                     fprintf(f, "%.2f %.2f\n", 0.0 + ( j * col_step ), 
623                             dem_data[row][j]);
624                 }
625                 for ( j = start; j <= end; j++) {
626                     fprintf(f, "%.2f %.2f\n", 0.0 + ( j * col_step ), 
627                             dem_data[row][j]);
628                 }
629                 fclose(f);
630
631                 printf("Please hit return: "); gets(junk);
632                 */
633
634                 if ( max_error > error ) {
635                     good_fit = false;
636                 }
637                 
638                 end++;
639             }
640
641             if ( !good_fit ) {
642                 // error exceeded the threshold, back up
643                 end -= 2;  // back "end" up to the last good enough fit
644                 n--;       // back "n" up appropriately too
645             } else {
646                 // we popped out of the above loop while still within
647                 // the error threshold, so we must be at the end of
648                 // the data set
649                 end--;
650             }
651             
652             least_squares(x, y, n, &m, &b);
653             ave_error = least_squares_error(x, y, n, m, b);
654             max_error = least_squares_max_error(x, y, n, m, b);
655
656             /*
657             printf("\n");
658             printf("%d - %d  ave error = %.2f  max error = %.2f  y = %.2f*x + %.2f\n", 
659                    start, end, ave_error, max_error, m, b);
660             printf("\n");
661
662             fprintf(fit1, "%.2f %.2f\n", x[0], m * x[0] + b);
663             fprintf(fit1, "%.2f %.2f\n", x[end-start], m * x[end-start] + b);
664             */
665
666             if ( start > colmin ) {
667                 // skip this for the first line segment
668                 cury = m * x[0] + b;
669                 outputmesh_set_pt(start, row, (lasty + cury) / 2);
670                 // fprintf(fit, "%.2f %.2f\n", x[0], (lasty + cury) / 2);
671             }
672
673             lasty = m * x[end-start] + b;
674             start = end;
675         }
676
677         /*
678         fclose(fit);
679         fclose(fit1);
680
681         dem = fopen("gnuplot.dat", "w");
682         for ( j = 0; j < DEM_SIZE_1; j++) {
683             fprintf(dem, "%.2f %.2f\n", 0.0 + ( j * col_step ), 
684                     dem_data[j][row]);
685         } 
686         fclose(dem);
687         */
688
689         // NOTICE, this is for testing only.  This instance of
690         // output_nodes should be removed.  It should be called only
691         // once at the end once all the nodes have been generated.
692         // newmesh_output_nodes(&nm, "mesh.node");
693         // printf("Please hit return: "); gets(junk);
694     }
695
696     // outputmesh_output_nodes(fg_root, p);
697 }
698
699
700 // Initialize output mesh structure
701 void fgDEM::outputmesh_init( void ) {
702     int i, j;
703     
704     for ( j = 0; j < DEM_SIZE_1; j++ ) {
705         for ( i = 0; i < DEM_SIZE_1; i++ ) {
706             output_data[i][j] = -9999.0;
707         }
708     }
709 }
710
711
712 // Get the value of a mesh node
713 double fgDEM::outputmesh_get_pt( int i, int j ) {
714     return ( output_data[i][j] );
715 }
716
717
718 // Set the value of a mesh node
719 void fgDEM::outputmesh_set_pt( int i, int j, double value ) {
720     // printf("Setting data[%d][%d] = %.2f\n", i, j, value);
721    output_data[i][j] = value;
722 }
723
724
725 // Write out a node file that can be used by the "triangle" program.
726 // Check for an optional "index.node.ex" file in case there is a .poly
727 // file to go along with this node file.  Include these nodes first
728 // since they are referenced by position from the .poly file.
729 void fgDEM::outputmesh_output_nodes( const string& fg_root, fgBUCKET *p ) {
730     double exnodes[MAX_EX_NODES][3];
731     struct stat stat_buf;
732     string dir;
733     char base_path[256], file[256], exfile[256];
734 #ifdef WIN32
735     char tmp_path[256];
736 #endif
737     string command;
738     FILE *fd;
739     long int index;
740     int colmin, colmax, rowmin, rowmax;
741     int i, j, count, excount, result;
742
743     // determine dimensions
744     colmin = p->x * ( (cols - 1) / 8);
745     colmax = colmin + ( (cols - 1) / 8);
746     rowmin = p->y * ( (rows - 1) / 8);
747     rowmax = rowmin + ( (rows - 1) / 8);
748     cout << "  dumping region = " << colmin << "," << rowmin << " to " <<
749         colmax << "," << rowmax << "\n";
750
751     // generate the base directory
752     fgBucketGenBasePath(p, base_path);
753     cout << "fg_root = " << fg_root << "  Base Path = " << base_path << endl;
754     dir = fg_root + "/Scenery/" + base_path;
755     cout << "Dir = " << dir << endl;
756     
757     // stat() directory and create if needed
758     errno = 0;
759     result = stat(dir.c_str(), &stat_buf);
760     if ( result != 0 && errno == ENOENT ) {
761         cout << "Creating directory\n";
762
763 // #ifndef WIN32
764
765         command = "mkdir -p " + dir + "\n";
766         system( command.c_str() );
767
768 #if 0
769 // #else // WIN32
770
771         // Cygwin crashes when trying to output to node file
772         // explicitly making directory structure seems OK on Win95
773
774         extract_path (base_path, tmp_path);
775
776         dir = fg_root + "/Scenery";
777         if (my_mkdir ( dir.c_str() )) { exit (-1); }
778
779         dir = fg_root + "/Scenery/" + tmp_path;
780         if (my_mkdir ( dir.c_str() )) { exit (-1); }
781
782         dir = fg_root + "/Scenery/" + base_path;
783         if (my_mkdir ( dir.c_str() )) { exit (-1); }
784
785 // #endif // WIN32
786 #endif //0
787
788     } else {
789         // assume directory exists
790     }
791
792     // get index and generate output file name
793     index = fgBucketGenIndex(p);
794     sprintf(file, "%s/%ld.node", dir.c_str(), index);
795
796     // get (optional) extra node file name (in case there is matching
797     // .poly file.
798     strcpy(exfile, file);
799     strcat(exfile, ".ex");
800
801     // load extra nodes if they exist
802     excount = 0;
803     if ( (fd = fopen(exfile, "r")) != NULL ) {
804         int junki;
805         fscanf(fd, "%d %d %d %d", &excount, &junki, &junki, &junki);
806
807         if ( excount > MAX_EX_NODES - 1 ) {
808             printf("Error, too many 'extra' nodes, increase array size\n");
809             exit(-1);
810         } else {
811             printf("    Expecting %d 'extra' nodes\n", excount);
812         }
813
814         for ( i = 1; i <= excount; i++ ) {
815             fscanf(fd, "%d %lf %lf %lf\n", &junki, 
816                    &exnodes[i][0], &exnodes[i][1], &exnodes[i][2]);
817             printf("(extra) %d %.2f %.2f %.2f\n", 
818                     i, exnodes[i][0], exnodes[i][1], exnodes[i][2]);
819         }
820         fclose(fd);
821     }
822
823     printf("Creating node file:  %s\n", file);
824     fd = fopen(file, "w");
825
826     // first count regular nodes to generate header
827     count = 0;
828     for ( j = rowmin; j <= rowmax; j++ ) {
829         for ( i = colmin; i <= colmax; i++ ) {
830             if ( output_data[i][j] > -9000.0 ) {
831                 count++;
832             }
833         }
834         // printf("    count = %d\n", count);
835     }
836     fprintf(fd, "%d 2 1 0\n", count + excount);
837
838     // now write out extra node data
839     for ( i = 1; i <= excount; i++ ) {
840         fprintf(fd, "%d %.2f %.2f %.2f\n", 
841                 i, exnodes[i][0], exnodes[i][1], exnodes[i][2]);
842     }
843
844     // write out actual node data
845     count = excount + 1;
846     for ( j = rowmin; j <= rowmax; j++ ) {
847         for ( i = colmin; i <= colmax; i++ ) {
848             if ( output_data[i][j] > -9000.0 ) {
849                 fprintf(fd, "%d %.2f %.2f %.2f\n", 
850                         count++, 
851                         originx + (double)i * col_step, 
852                         originy + (double)j * row_step,
853                         output_data[i][j]);
854             }
855         }
856         // printf("    count = %d\n", count);
857     }
858
859     fclose(fd);
860 }
861
862
863 fgDEM::~fgDEM( void ) {
864     // printf("class fgDEM DEstructor called.\n");
865     delete [] dem_data;
866     delete [] output_data;
867 }
868
869
870 // $Log$
871 // Revision 1.22  1999/01/19 20:56:56  curt
872 // MacOS portability changes contributed by "Robert Puyol" <puyol@abvent.fr>
873 //
874 // Revision 1.21  1998/11/06 14:04:32  curt
875 // Changes due to updates in fgstream.
876 //
877 // Revision 1.20  1998/10/28 19:38:20  curt
878 // Elliminate some unnecessary win32 specific stuff (by Norman Vine)
879 //
880 // Revision 1.19  1998/10/22 21:59:19  curt
881 // Fixed a couple subtle bugs that resulted from some of my c++ conversions.
882 // One bug could cause a segfault on certain input, and the other bug could
883 // cause the whole procedure to go balistic and generate huge files (also only
884 // on rare input combinations.)
885 //
886 // Revision 1.18  1998/10/18 01:17:09  curt
887 // Point3D tweaks.
888 //
889 // Revision 1.17  1998/10/16 19:08:12  curt
890 // Portability updates from Bernie Bright.
891 //
892 // Revision 1.16  1998/10/02 21:41:39  curt
893 // Fixes for win32.
894 //
895 // Revision 1.15  1998/09/21 20:53:59  curt
896 // minor tweaks to clean a few additional things up after the rewrite.
897 //
898 // Revision 1.14  1998/09/19 17:59:45  curt
899 // Use c++ streams (fg_gzifstream).  Also converted many character arrays to
900 // the string class.
901 //
902 // Revision 1.13  1998/09/09 16:24:04  curt
903 // Fixed a bug in the handling of exclude files which was causing
904 // a crash by calling fclose() on an invalid file handle.
905 //
906 // Revision 1.12  1998/08/24 20:03:31  curt
907 // Eliminated a possible memory overrun error.
908 // Use the proper free() rather than the incorrect delete().
909 //
910 // Revision 1.11  1998/07/20 12:46:11  curt
911 // When outputing to a .node file, first check for an optional
912 // "index.node.ex" file in case there is a .poly file to go along with this
913 // node file.  Include these nodes first since they are referenced by position
914 // from the .poly file.  This is my first pass at adding an area "cutout"
915 // feature to the terrain generation pipeline.
916 //
917 // Revision 1.10  1998/07/13 20:58:02  curt
918 // .
919 //
920 // Revision 1.9  1998/07/13 15:29:49  curt
921 // Added #ifdef HAVE_CONFIG_H
922 //
923 // Revision 1.8  1998/07/04 00:47:18  curt
924 // typedef'd struct fgBUCKET.
925 //
926 // Revision 1.7  1998/06/05 18:14:39  curt
927 // Abort out early when reading the "A" record if it doesn't look like
928 // a proper DEM file.
929 //
930 // Revision 1.6  1998/05/02 01:49:21  curt
931 // Fixed a bug where the wrong variable was being initialized.
932 //
933 // Revision 1.5  1998/04/25 15:00:32  curt
934 // Changed "r" to "rb" in gzopen() options.  This fixes bad behavior in win32.
935 //
936 // Revision 1.4  1998/04/22 13:14:46  curt
937 // Fixed a bug in zlib usage.
938 //
939 // Revision 1.3  1998/04/18 03:53:05  curt
940 // Added zlib support.
941 //
942 // Revision 1.2  1998/04/14 02:43:27  curt
943 // Used "new" to auto-allocate large DEM parsing arrays in class constructor.
944 //
945 // Revision 1.1  1998/04/08 22:57:22  curt
946 // Adopted Gnu automake/autoconf system.
947 //
948 // Revision 1.3  1998/04/06 21:09:41  curt
949 // Additional win32 support.
950 // Fixed a bad bug in dem file parsing that was causing the output to be
951 // flipped about x = y.
952 //
953 // Revision 1.2  1998/03/23 20:35:41  curt
954 // Updated to use FG_EPSILON
955 //
956 // Revision 1.1  1998/03/19 02:54:47  curt
957 // Reorganized into a class lib called fgDEM.
958 //
959 // Revision 1.1  1998/03/19 01:46:28  curt
960 // Initial revision.
961 //