]> git.street.me.uk Git - andy/viking.git/blob - src/dem.c
Only allow JPGs in the file selector for Geotagging.
[andy/viking.git] / src / dem.c
1 /*
2  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
3  *
4  * Copyright (C) 2003-2008, Evan Battaglia <gtoevan@gmx.net>
5  * Copyright (C) 2007, Quy Tonthat <qtonthat@gmail.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include <stdio.h>
28 #ifdef HAVE_STRING_H
29 #include <string.h>
30 #endif
31 #include <glib.h>
32 #ifdef HAVE_MATH_H
33 #include <math.h>
34 #endif
35 #ifdef HAVE_STDLIB_H
36 #include <stdlib.h>
37 #endif
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>
42 #endif
43
44 #include <glib/gstdio.h>
45 #include <glib/gi18n.h>
46
47 #include "compression.h"
48 #include "dem.h"
49 #include "file.h"
50
51 /* Compatibility */
52 #if ! GLIB_CHECK_VERSION(2,22,0)
53 #define g_mapped_file_unref g_mapped_file_free
54 #endif
55
56 #define DEM_BLOCK_SIZE 1024
57 #define GET_COLUMN(dem,n) ((VikDEMColumn *)g_ptr_array_index( (dem)->columns, (n) ))
58
59 static gboolean get_double_and_continue ( gchar **buffer, gdouble *tmp, gboolean warn )
60 {
61   gchar *endptr;
62   *tmp = g_strtod(*buffer, &endptr);
63   if ( endptr == NULL|| endptr == *buffer ) {
64     if ( warn )
65       g_warning(_("Invalid DEM"));
66     return FALSE;
67   }
68   *buffer=endptr;
69   return TRUE;
70 }
71
72
73 static gboolean get_int_and_continue ( gchar **buffer, gint *tmp, gboolean warn )
74 {
75   gchar *endptr;
76   *tmp = strtol(*buffer, &endptr, 10);
77   if ( endptr == NULL|| endptr == *buffer ) {
78     if ( warn )
79       g_warning(_("Invalid DEM"));
80     return FALSE;
81   }
82   *buffer=endptr;
83   return TRUE;
84 }
85
86 static gboolean dem_parse_header ( gchar *buffer, VikDEM *dem )
87 {
88   gdouble val;
89   gint int_val;
90   guint i;
91   gchar *tmp = buffer;
92
93   /* incomplete header */
94   if ( strlen(buffer) != 1024 )
95     return FALSE;
96
97   /* fix Fortran-style exponentiation 1.0D5 -> 1.0E5 */
98   while (*tmp) {
99     if ( *tmp=='D')
100       *tmp='E';
101     tmp++;
102   }
103
104   /* skip name */
105   buffer += 149;
106
107   /* "DEM level code, pattern code, palaimetric reference system code" -- skip */
108   get_int_and_continue(&buffer, &int_val, TRUE);
109   get_int_and_continue(&buffer, &int_val, TRUE);
110   get_int_and_continue(&buffer, &int_val, TRUE);
111
112   /* zone */
113   get_int_and_continue(&buffer, &int_val, TRUE);
114   dem->utm_zone = int_val;
115   /* TODO -- southern or northern hemisphere?! */
116   dem->utm_letter = 'N';
117
118   /* skip numbers 5-19  */
119   for ( i = 0; i < 15; i++ ) {
120     if ( ! get_double_and_continue(&buffer, &val, FALSE) ) {
121       g_warning (_("Invalid DEM header"));
122       return FALSE;
123     }
124   }
125
126   /* number 20 -- horizontal unit code (utm/ll) */
127   get_double_and_continue(&buffer, &val, TRUE);
128   dem->horiz_units = val;
129   get_double_and_continue(&buffer, &val, TRUE);
130   /* dem->orig_vert_units = val; now done below */
131
132   /* TODO: do this for real. these are only for 1:24k and 1:250k USGS */
133   if ( dem->horiz_units == VIK_DEM_HORIZ_UTM_METERS ) {
134     dem->east_scale = 10.0; /* meters */
135     dem->north_scale = 10.0;
136     dem->orig_vert_units = VIK_DEM_VERT_DECIMETERS;
137   } else {
138     dem->east_scale = 3.0; /* arcseconds */
139     dem->north_scale = 3.0;
140     dem->orig_vert_units = VIK_DEM_VERT_METERS;
141   }
142
143   /* skip next */
144   get_double_and_continue(&buffer, &val, TRUE);
145
146   /* now we get the four corner points. record the min and max. */
147   get_double_and_continue(&buffer, &val, TRUE);
148   dem->min_east = dem->max_east = val;
149   get_double_and_continue(&buffer, &val, TRUE);
150   dem->min_north = dem->max_north = val;
151
152   for ( i = 0; i < 3; i++ ) {
153     get_double_and_continue(&buffer, &val, TRUE);
154     if ( val < dem->min_east ) dem->min_east = val;
155     if ( val > dem->max_east ) dem->max_east = val;
156     get_double_and_continue(&buffer, &val, TRUE);
157     if ( val < dem->min_north ) dem->min_north = val;
158     if ( val > dem->max_north ) dem->max_north = val;
159   }
160
161   return TRUE;
162 }
163
164 static void dem_parse_block_as_cont ( gchar *buffer, VikDEM *dem, gint *cur_column, gint *cur_row )
165 {
166   gint tmp;
167   while ( *cur_row < GET_COLUMN(dem, *cur_column)->n_points ) {
168     if ( get_int_and_continue(&buffer, &tmp,FALSE) ) {
169       if ( dem->orig_vert_units == VIK_DEM_VERT_DECIMETERS )
170         GET_COLUMN(dem, *cur_column)->points[*cur_row] = (gint16) (tmp / 10);
171       else
172         GET_COLUMN(dem, *cur_column)->points[*cur_row] = (gint16) tmp;
173     } else
174       return;
175     (*cur_row)++;
176   }
177   *cur_row = -1; /* expecting new column */
178 }
179
180 static void dem_parse_block_as_header ( gchar *buffer, VikDEM *dem, gint *cur_column, gint *cur_row )
181 {
182   guint n_rows;
183   gint i;
184   gdouble east_west, south;
185   gdouble tmp;
186
187   /* 1 x n_rows 1 east_west south x x x DATA */
188
189   if ( (!get_double_and_continue(&buffer, &tmp, TRUE)) || tmp != 1 ) {
190     g_warning(_("Incorrect DEM Class B record: expected 1"));
191     return;
192   }
193
194   /* don't need this */
195   if ( !get_double_and_continue(&buffer, &tmp, TRUE ) ) return;
196
197   /* n_rows */
198   if ( !get_double_and_continue(&buffer, &tmp, TRUE ) )
199     return;
200   n_rows = (guint) tmp;
201
202   if ( (!get_double_and_continue(&buffer, &tmp, TRUE)) || tmp != 1 ) {
203     g_warning(_("Incorrect DEM Class B record: expected 1"));
204     return;
205   }
206   
207   if ( !get_double_and_continue(&buffer, &east_west, TRUE) )
208     return;
209   if ( !get_double_and_continue(&buffer, &south, TRUE) )
210     return;
211
212   /* next three things we don't need */
213   if ( !get_double_and_continue(&buffer, &tmp, TRUE)) return;
214   if ( !get_double_and_continue(&buffer, &tmp, TRUE)) return;
215   if ( !get_double_and_continue(&buffer, &tmp, TRUE)) return;
216
217
218   dem->n_columns ++;
219   (*cur_column) ++;
220
221   /* empty spaces for things before that were skipped */
222   (*cur_row) = (south - dem->min_north) / dem->north_scale;
223   if ( south > dem->max_north || (*cur_row) < 0 )
224     (*cur_row) = 0;
225
226   n_rows += *cur_row;
227
228   g_ptr_array_add ( dem->columns, g_malloc(sizeof(VikDEMColumn)) );
229   GET_COLUMN(dem,*cur_column)->east_west = east_west;
230   GET_COLUMN(dem,*cur_column)->south = south;
231   GET_COLUMN(dem,*cur_column)->n_points = n_rows;
232   GET_COLUMN(dem,*cur_column)->points = g_malloc(sizeof(gint16)*n_rows);
233
234   /* no information for things before that */
235   for ( i = 0; i < (*cur_row); i++ )
236     GET_COLUMN(dem,*cur_column)->points[i] = VIK_DEM_INVALID_ELEVATION;
237
238   /* now just continue */
239   dem_parse_block_as_cont ( buffer, dem, cur_column, cur_row );
240
241
242 }
243
244 static void dem_parse_block ( gchar *buffer, VikDEM *dem, gint *cur_column, gint *cur_row )
245 {
246   /* if haven't read anything or have read all items in a columns and are expecting a new column */
247   if ( *cur_column == -1 || *cur_row == -1 ) {
248     dem_parse_block_as_header(buffer, dem, cur_column, cur_row);
249   } else {
250     dem_parse_block_as_cont(buffer, dem, cur_column, cur_row);
251   }
252 }
253
254 static VikDEM *vik_dem_read_srtm_hgt(const gchar *file_name, const gchar *basename, gboolean zip)
255 {
256   gint i, j;
257   VikDEM *dem;
258   off_t file_size;
259   gint16 *dem_mem = NULL;
260   gchar *dem_file = NULL;
261   const gint num_rows_3sec = 1201;
262   const gint num_rows_1sec = 3601;
263   gint num_rows;
264   GMappedFile *mf;
265   gint arcsec;
266   GError *error = NULL;
267
268   dem = g_malloc(sizeof(VikDEM));
269
270   dem->horiz_units = VIK_DEM_HORIZ_LL_ARCSECONDS;
271   dem->orig_vert_units = VIK_DEM_VERT_DECIMETERS;
272
273   /* TODO */
274   dem->min_north = atoi(basename+1) * 3600;
275   dem->min_east = atoi(basename+4) * 3600;
276   if ( basename[0] == 'S' )
277     dem->min_north = - dem->min_north;
278   if ( basename[3] == 'W' )
279     dem->min_east = - dem->min_east;
280
281   dem->max_north = 3600 + dem->min_north;
282   dem->max_east = 3600 + dem->min_east;
283
284   dem->columns = g_ptr_array_new();
285   dem->n_columns = 0;
286
287   if ((mf = g_mapped_file_new(file_name, FALSE, &error)) == NULL) {
288     g_critical(_("Couldn't map file %s: %s"), file_name, error->message);
289     g_error_free(error);
290     g_free(dem);
291     return NULL;
292   }
293   file_size = g_mapped_file_get_length(mf);
294   dem_file = g_mapped_file_get_contents(mf);
295   
296   if (zip) {
297     void *unzip_mem = NULL;
298     gulong ucsize;
299
300     if ((unzip_mem = unzip_file(dem_file, &ucsize)) == NULL) {
301       g_mapped_file_unref(mf);
302       g_ptr_array_foreach ( dem->columns, (GFunc)g_free, NULL );
303       g_ptr_array_free(dem->columns, TRUE);
304       g_free(dem);
305       return NULL;
306     }
307
308     dem_mem = unzip_mem;
309     file_size = ucsize;
310   }
311   else
312     dem_mem = (gint16 *)dem_file;
313
314   if (file_size == (num_rows_3sec * num_rows_3sec * sizeof(gint16)))
315     arcsec = 3;
316   else if (file_size == (num_rows_1sec * num_rows_1sec * sizeof(gint16)))
317     arcsec = 1;
318   else {
319     g_warning("%s(): file %s does not have right size", __PRETTY_FUNCTION__, basename);
320     g_mapped_file_unref(mf);
321     g_free(dem);
322     return NULL;
323   }
324
325   num_rows = (arcsec == 3) ? num_rows_3sec : num_rows_1sec;
326   dem->east_scale = dem->north_scale = arcsec;
327
328   for ( i = 0; i < num_rows; i++ ) {
329     dem->n_columns++;
330     g_ptr_array_add ( dem->columns, g_malloc(sizeof(VikDEMColumn)) );
331     GET_COLUMN(dem,i)->east_west = dem->min_east + arcsec*i;
332     GET_COLUMN(dem,i)->south = dem->min_north;
333     GET_COLUMN(dem,i)->n_points = num_rows;
334     GET_COLUMN(dem,i)->points = g_malloc(sizeof(gint16)*num_rows);
335   }
336
337   int ent = 0;
338   for ( i = (num_rows - 1); i >= 0; i-- ) {
339     for ( j = 0; j < num_rows; j++ ) {
340       GET_COLUMN(dem,j)->points[i] = GINT16_FROM_BE(dem_mem[ent]);
341       ent++;
342     }
343
344   }
345
346   if (zip)
347     g_free(dem_mem);
348   g_mapped_file_unref(mf);
349   return dem;
350 }
351
352 #define IS_SRTM_HGT(fn) (strlen((fn))==11 && (fn)[7]=='.' && (fn)[8]=='h' && (fn)[9]=='g' && (fn)[10]=='t' && ((fn)[0]=='N' || (fn)[0]=='S') && ((fn)[3]=='E' || (fn)[3]=='W'))
353
354 VikDEM *vik_dem_new_from_file(const gchar *file)
355 {
356   FILE *f=NULL;
357   VikDEM *rv;
358   gchar buffer[DEM_BLOCK_SIZE+1];
359
360   /* use to record state for dem_parse_block */
361   gint cur_column = -1;
362   gint cur_row = -1;
363   const gchar *basename = a_file_basename(file);
364
365   if ( g_access ( file, R_OK ) != 0 )
366     return NULL;
367
368   if ( (strlen(basename)==11 || ((strlen(basename) == 15) && (basename[11] == '.' && basename[12] == 'z' && basename[13] == 'i' && basename[14] == 'p'))) &&
369        basename[7]=='.' && basename[8]=='h' && basename[9]=='g' && basename[10]=='t' &&
370        (basename[0] == 'N' || basename[0] == 'S') && (basename[3] == 'E' || basename[3] =='W')) {
371     gboolean is_zip_file = (strlen(basename) == 15);
372     rv = vik_dem_read_srtm_hgt(file, basename, is_zip_file);
373     return(rv);
374   }
375
376       /* Create Structure */
377   rv = g_malloc(sizeof(VikDEM));
378
379       /* Header */
380   f = g_fopen(file, "r");
381   if ( !f ) {
382     g_free ( rv );
383     return NULL;
384   }
385   buffer[fread(buffer, 1, DEM_BLOCK_SIZE, f)] = '\0';
386   if ( ! dem_parse_header ( buffer, rv ) ) {
387     g_free ( rv );
388     fclose(f);
389     return NULL;
390   }
391   /* TODO: actually use header -- i.e. GET # OF COLUMNS EXPECTED */
392
393   rv->columns = g_ptr_array_new();
394   rv->n_columns = 0;
395
396       /* Column -- Data */
397   while (! feof(f) ) {
398      gchar *tmp;
399
400      /* read block */
401      buffer[fread(buffer, 1, DEM_BLOCK_SIZE, f)] = '\0';
402
403      /* Fix Fortran-style exponentiation */
404      tmp = buffer;
405      while (*tmp) {
406        if ( *tmp=='D')
407          *tmp='E';
408        tmp++;
409      }
410
411      dem_parse_block(buffer, rv, &cur_column, &cur_row);
412   }
413
414      /* TODO - class C records (right now says 'Invalid' and dies) */
415
416   fclose(f);
417   f = NULL;
418
419   /* 24k scale */
420   if ( rv->horiz_units == VIK_DEM_HORIZ_UTM_METERS && rv->n_columns >= 2 )
421     rv->north_scale = rv->east_scale = GET_COLUMN(rv, 1)->east_west - GET_COLUMN(rv,0)->east_west;
422
423   /* FIXME bug in 10m DEM's */
424   if ( rv->horiz_units == VIK_DEM_HORIZ_UTM_METERS && rv->north_scale == 10 ) {
425     rv->min_east -= 100;
426     rv->min_north += 200;
427   }
428
429
430   return rv;
431 }
432
433 void vik_dem_free ( VikDEM *dem )
434 {
435   guint i;
436   for ( i = 0; i < dem->n_columns; i++)
437     g_free ( GET_COLUMN(dem, i)->points );
438   g_ptr_array_foreach ( dem->columns, (GFunc)g_free, NULL );
439   g_ptr_array_free ( dem->columns, TRUE );
440   g_free ( dem );
441 }
442
443 gint16 vik_dem_get_xy ( VikDEM *dem, guint col, guint row )
444 {
445   if ( col < dem->n_columns )
446     if ( row < GET_COLUMN(dem, col)->n_points )
447       return GET_COLUMN(dem, col)->points[row];
448   return VIK_DEM_INVALID_ELEVATION;
449 }
450
451 gint16 vik_dem_get_east_north ( VikDEM *dem, gdouble east, gdouble north )
452 {
453   gint col, row;
454
455   if ( east > dem->max_east || east < dem->min_east ||
456       north > dem->max_north || north < dem->min_north )
457     return VIK_DEM_INVALID_ELEVATION;
458
459   col = (gint) floor((east - dem->min_east) / dem->east_scale);
460   row = (gint) floor((north - dem->min_north) / dem->north_scale);
461
462   return vik_dem_get_xy ( dem, col, row );
463 }
464
465 static gboolean dem_get_ref_points_elev_dist(VikDEM *dem,
466     gdouble east, gdouble north, /* in seconds */
467     gint16 *elevs, gint16 *dists)
468 {
469   int i;
470   int cols[4], rows[4];
471   struct LatLon ll[4];
472   struct LatLon pos;
473
474   if ( east > dem->max_east || east < dem->min_east ||
475       north > dem->max_north || north < dem->min_north )
476     return FALSE;  /* got nothing */
477
478   pos.lon = east/3600;
479   pos.lat = north/3600;
480
481   /* order of the data: sw, nw, ne, se */
482   /* sw */
483   cols[0] = (gint) floor((east - dem->min_east) / dem->east_scale);
484   rows[0] = (gint) floor((north - dem->min_north) / dem->north_scale);
485   ll[0].lon = (dem->min_east + dem->east_scale*cols[0])/3600;
486   ll[0].lat = (dem->min_north + dem->north_scale*rows[0])/3600;
487   /* nw */
488   cols[1] = cols[0];
489   rows[1] = rows[0] + 1;
490   ll[1].lon = ll[0].lon;
491   ll[1].lat = ll[0].lat + (gdouble)dem->north_scale/3600;
492   /* ne */
493   cols[2] = cols[0] + 1;
494   rows[2] = rows[0] + 1;
495   ll[2].lon = ll[0].lon + (gdouble)dem->east_scale/3600;
496   ll[2].lat = ll[0].lat + (gdouble)dem->north_scale/3600;
497   /* se */
498   cols[3] = cols[0] + 1;
499   rows[3] = rows[0];
500   ll[3].lon = ll[0].lon + (gdouble)dem->east_scale/3600;
501   ll[3].lat = ll[0].lat;
502
503   for (i = 0; i < 4; i++) {
504     if ((elevs[i] = vik_dem_get_xy(dem, cols[i], rows[i])) == VIK_DEM_INVALID_ELEVATION)
505       return FALSE;
506     dists[i] = a_coords_latlon_diff(&pos, &ll[i]);
507   }
508
509 #if 0  /* debug */
510   for (i = 0; i < 4; i++)
511     fprintf(stderr, "%f:%f:%d:%d  ", ll[i].lat, ll[i].lon, dists[i], elevs[i]);
512   fprintf(stderr, "   north_scale=%f\n", dem->north_scale);
513 #endif
514
515   return TRUE;  /* all OK */
516 }
517
518 gint16 vik_dem_get_simple_interpol ( VikDEM *dem, gdouble east, gdouble north )
519 {
520   int i;
521   gint16 elevs[4], dists[4];
522
523   if (!dem_get_ref_points_elev_dist(dem, east, north, elevs, dists))
524     return VIK_DEM_INVALID_ELEVATION;
525
526   for (i = 0; i < 4; i++) {
527     if (dists[i] < 1) {
528       return(elevs[i]);
529     }
530   }
531
532   gdouble t = (gdouble)elevs[0]/dists[0] + (gdouble)elevs[1]/dists[1] + (gdouble)elevs[2]/dists[2] + (gdouble)elevs[3]/dists[3];
533   gdouble b = 1.0/dists[0] + 1.0/dists[1] + 1.0/dists[2] + 1.0/dists[3];
534
535   return(t/b);
536 }
537
538 gint16 vik_dem_get_shepard_interpol ( VikDEM *dem, gdouble east, gdouble north )
539 {
540   int i;
541   gint16 elevs[4], dists[4];
542   gint16 max_dist;
543   gdouble t = 0.0;
544   gdouble b = 0.0;
545
546   if (!dem_get_ref_points_elev_dist(dem, east, north, elevs, dists))
547     return VIK_DEM_INVALID_ELEVATION;
548
549   max_dist = 0;
550   for (i = 0; i < 4; i++) {
551     if (dists[i] < 1) {
552       return(elevs[i]);
553     }
554     if (dists[i] > max_dist)
555       max_dist = dists[i];
556   }
557
558   gdouble tmp;
559 #if 0 /* derived method by Franke & Nielson. Does not seem to work too well here */
560   for (i = 0; i < 4; i++) {
561     tmp = pow((1.0*(max_dist - dists[i])/max_dist*dists[i]), 2);
562     t += tmp*elevs[i];
563     b += tmp;
564   }
565 #endif
566
567   for (i = 0; i < 4; i++) {
568     tmp = pow((1.0/dists[i]), 2);
569     t += tmp*elevs[i];
570     b += tmp;
571   }
572
573   // fprintf(stderr, "DEBUG: tmp=%f t=%f b=%f %f\n", tmp, t, b, t/b);
574
575   return(t/b);
576
577 }
578
579 void vik_dem_east_north_to_xy ( VikDEM *dem, gdouble east, gdouble north, guint *col, guint *row )
580 {
581   *col = (gint) floor((east - dem->min_east) / dem->east_scale);
582   *row = (gint) floor((north - dem->min_north) / dem->north_scale);
583   if ( *col < 0 ) *col = 0;
584   if ( *row < 0 ) *row = 0;
585 }
586