2 * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
4 * Copyright (C) 2003-2008, Evan Battaglia <gtoevan@gmx.net>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32 #include <sys/types.h>
38 #include <glib/gstdio.h>
39 #include <glib/gi18n.h>
44 #define DEM_BLOCK_SIZE 1024
45 #define GET_COLUMN(dem,n) ((VikDEMColumn *)g_ptr_array_index( (dem)->columns, (n) ))
47 static gboolean get_double_and_continue ( gchar **buffer, gdouble *tmp, gboolean warn )
50 *tmp = g_strtod(*buffer, &endptr);
51 if ( endptr == NULL|| endptr == *buffer ) {
53 g_warning(_("Invalid DEM"));
61 static gboolean get_int_and_continue ( gchar **buffer, gint *tmp, gboolean warn )
64 *tmp = strtol(*buffer, &endptr, 10);
65 if ( endptr == NULL|| endptr == *buffer ) {
67 g_warning(_("Invalid DEM"));
74 static gboolean dem_parse_header ( gchar *buffer, VikDEM *dem )
81 /* incomplete header */
82 if ( strlen(buffer) != 1024 )
85 /* fix Fortran-style exponentiation 1.0D5 -> 1.0E5 */
95 /* "DEM level code, pattern code, palaimetric reference system code" -- skip */
96 get_int_and_continue(&buffer, &int_val, TRUE);
97 get_int_and_continue(&buffer, &int_val, TRUE);
98 get_int_and_continue(&buffer, &int_val, TRUE);
101 get_int_and_continue(&buffer, &int_val, TRUE);
102 dem->utm_zone = int_val;
103 /* TODO -- southern or northern hemisphere?! */
104 dem->utm_letter = 'N';
106 /* skip numbers 5-19 */
107 for ( i = 0; i < 15; i++ ) {
108 if ( ! get_double_and_continue(&buffer, &val, FALSE) ) {
109 g_warning (_("Invalid DEM header"));
114 /* number 20 -- horizontal unit code (utm/ll) */
115 get_double_and_continue(&buffer, &val, TRUE);
116 dem->horiz_units = val;
117 get_double_and_continue(&buffer, &val, TRUE);
118 /* dem->orig_vert_units = val; now done below */
120 /* TODO: do this for real. these are only for 1:24k and 1:250k USGS */
121 if ( dem->horiz_units == VIK_DEM_HORIZ_UTM_METERS ) {
122 dem->east_scale = 10.0; /* meters */
123 dem->north_scale = 10.0;
124 dem->orig_vert_units = VIK_DEM_VERT_DECIMETERS;
126 dem->east_scale = 3.0; /* arcseconds */
127 dem->north_scale = 3.0;
128 dem->orig_vert_units = VIK_DEM_VERT_METERS;
132 get_double_and_continue(&buffer, &val, TRUE);
134 /* now we get the four corner points. record the min and max. */
135 get_double_and_continue(&buffer, &val, TRUE);
136 dem->min_east = dem->max_east = val;
137 get_double_and_continue(&buffer, &val, TRUE);
138 dem->min_north = dem->max_north = val;
140 for ( i = 0; i < 3; i++ ) {
141 get_double_and_continue(&buffer, &val, TRUE);
142 if ( val < dem->min_east ) dem->min_east = val;
143 if ( val > dem->max_east ) dem->max_east = val;
144 get_double_and_continue(&buffer, &val, TRUE);
145 if ( val < dem->min_north ) dem->min_north = val;
146 if ( val > dem->max_north ) dem->max_north = val;
152 static void dem_parse_block_as_cont ( gchar *buffer, VikDEM *dem, gint *cur_column, gint *cur_row )
155 while ( *cur_row < GET_COLUMN(dem, *cur_column)->n_points ) {
156 if ( get_int_and_continue(&buffer, &tmp,FALSE) ) {
157 if ( dem->orig_vert_units == VIK_DEM_VERT_DECIMETERS )
158 GET_COLUMN(dem, *cur_column)->points[*cur_row] = (gint16) (tmp / 10);
160 GET_COLUMN(dem, *cur_column)->points[*cur_row] = (gint16) tmp;
165 *cur_row = -1; /* expecting new column */
168 static void dem_parse_block_as_header ( gchar *buffer, VikDEM *dem, gint *cur_column, gint *cur_row )
172 gdouble east_west, south;
175 /* 1 x n_rows 1 east_west south x x x DATA */
177 if ( (!get_double_and_continue(&buffer, &tmp, TRUE)) || tmp != 1 ) {
178 g_warning(_("Incorrect DEM Class B record: expected 1"));
182 /* don't need this */
183 if ( !get_double_and_continue(&buffer, &tmp, TRUE ) ) return;
186 if ( !get_double_and_continue(&buffer, &tmp, TRUE ) )
188 n_rows = (guint) tmp;
190 if ( (!get_double_and_continue(&buffer, &tmp, TRUE)) || tmp != 1 ) {
191 g_warning(_("Incorrect DEM Class B record: expected 1"));
195 if ( !get_double_and_continue(&buffer, &east_west, TRUE) )
197 if ( !get_double_and_continue(&buffer, &south, TRUE) )
200 /* next three things we don't need */
201 if ( !get_double_and_continue(&buffer, &tmp, TRUE)) return;
202 if ( !get_double_and_continue(&buffer, &tmp, TRUE)) return;
203 if ( !get_double_and_continue(&buffer, &tmp, TRUE)) return;
209 /* empty spaces for things before that were skipped */
210 (*cur_row) = (south - dem->min_north) / dem->north_scale;
211 if ( south > dem->max_north || (*cur_row) < 0 )
216 g_ptr_array_add ( dem->columns, g_malloc(sizeof(VikDEMColumn)) );
217 GET_COLUMN(dem,*cur_column)->east_west = east_west;
218 GET_COLUMN(dem,*cur_column)->south = south;
219 GET_COLUMN(dem,*cur_column)->n_points = n_rows;
220 GET_COLUMN(dem,*cur_column)->points = g_malloc(sizeof(gint16)*n_rows);
222 /* no information for things before that */
223 for ( i = 0; i < (*cur_row); i++ )
224 GET_COLUMN(dem,*cur_column)->points[i] = VIK_DEM_INVALID_ELEVATION;
226 /* now just continue */
227 dem_parse_block_as_cont ( buffer, dem, cur_column, cur_row );
232 static void dem_parse_block ( gchar *buffer, VikDEM *dem, gint *cur_column, gint *cur_row )
234 /* if haven't read anything or have read all items in a columns and are expecting a new column */
235 if ( *cur_column == -1 || *cur_row == -1 ) {
236 dem_parse_block_as_header(buffer, dem, cur_column, cur_row);
238 dem_parse_block_as_cont(buffer, dem, cur_column, cur_row);
242 /* return size of unzip data or 0 if failed */
243 /* can be made generic to uncompress zip, gzip, bzip2 data */
244 static guint uncompress_data(void *uncompressed_buffer, guint uncompressed_size, void *compressed_data, guint compressed_size)
249 stream.next_in = compressed_data;
250 stream.avail_in = compressed_size;
251 stream.next_out = uncompressed_buffer;
252 stream.avail_out = uncompressed_size;
253 stream.zalloc = (alloc_func)0;
254 stream.zfree = (free_func)0;
255 stream.opaque = (voidpf)0;
257 /* negative windowBits to inflateInit2 means "no header" */
258 if ((err = inflateInit2(&stream, -MAX_WBITS)) != Z_OK) {
259 g_warning("%s(): inflateInit2 failed", __PRETTY_FUNCTION__);
263 err = inflate(&stream, Z_FINISH);
264 if ((err != Z_OK) && (err != Z_STREAM_END) && stream.msg) {
265 g_warning("%s() inflate failed err=%d \"%s\"", __PRETTY_FUNCTION__, err, stream.msg == NULL ? "unknown" : stream.msg);
271 return(stream.total_out);
274 static void *unzip_hgt_file(gchar *zip_file, gulong *unzip_size)
276 void *unzip_data = NULL;
280 guint16 extract_version;
286 guint32 compressed_size;
287 guint32 uncompressed_size;
288 guint16 filename_len;
289 guint16 extra_field_len;
290 } __attribute__ ((__packed__)) *local_file_header = NULL;
293 local_file_header = (struct _lfh *) zip_file;
294 if (local_file_header->sig != 0x04034b50) {
295 g_warning("%s(): wrong format", __PRETTY_FUNCTION__);
300 zip_data = zip_file + sizeof(struct _lfh) + local_file_header->filename_len + local_file_header->extra_field_len;
301 unzip_data = g_malloc(local_file_header->uncompressed_size);
302 gulong uncompressed_size = local_file_header->uncompressed_size;
304 if (!(*unzip_size = uncompress_data(unzip_data, uncompressed_size, zip_data, local_file_header->compressed_size))) {
314 static VikDEM *vik_dem_read_srtm_hgt(const gchar *file_name, const gchar *basename, gboolean zip)
319 gint16 *dem_mem = NULL;
320 gchar *dem_file = NULL;
321 const gint num_rows_3sec = 1201;
322 const gint num_rows_1sec = 3601;
326 GError *error = NULL;
328 dem = g_malloc(sizeof(VikDEM));
330 dem->horiz_units = VIK_DEM_HORIZ_LL_ARCSECONDS;
331 dem->orig_vert_units = VIK_DEM_VERT_DECIMETERS;
334 dem->min_north = atoi(basename+1) * 3600;
335 dem->min_east = atoi(basename+4) * 3600;
336 if ( basename[0] == 'S' )
337 dem->min_north = - dem->min_north;
338 if ( basename[3] == 'W' )
339 dem->min_east = - dem->min_east;
341 dem->max_north = 3600 + dem->min_north;
342 dem->max_east = 3600 + dem->min_east;
344 dem->columns = g_ptr_array_new();
347 if ((mf = g_mapped_file_new(file_name, FALSE, &error)) == NULL) {
348 g_error(_("Couldn't map file %s: %s"), file_name, error->message);
353 file_size = g_mapped_file_get_length(mf);
354 dem_file = g_mapped_file_get_contents(mf);
357 void *unzip_mem = NULL;
360 if ((unzip_mem = unzip_hgt_file(dem_file, &ucsize)) == NULL) {
361 g_mapped_file_free(mf);
362 g_ptr_array_free(dem->columns, TRUE);
371 if (file_size == (num_rows_3sec * num_rows_3sec * sizeof(gint16)))
373 else if (file_size == (num_rows_1sec * num_rows_1sec * sizeof(gint16)))
376 g_warning("%s(): file %s does not have right size", __PRETTY_FUNCTION__, basename);
377 g_mapped_file_free(mf);
382 num_rows = (arcsec == 3) ? num_rows_3sec : num_rows_1sec;
383 dem->east_scale = dem->north_scale = arcsec;
385 for ( i = 0; i < num_rows; i++ ) {
387 g_ptr_array_add ( dem->columns, g_malloc(sizeof(VikDEMColumn)) );
388 GET_COLUMN(dem,i)->east_west = dem->min_east + arcsec*i;
389 GET_COLUMN(dem,i)->south = dem->min_north;
390 GET_COLUMN(dem,i)->n_points = num_rows;
391 GET_COLUMN(dem,i)->points = g_malloc(sizeof(gint16)*num_rows);
395 for ( i = (num_rows - 1); i >= 0; i-- ) {
396 for ( j = 0; j < num_rows; j++ ) {
397 GET_COLUMN(dem,j)->points[i] = GINT16_FROM_BE(dem_mem[ent]);
405 g_mapped_file_free(mf);
409 #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'))
411 VikDEM *vik_dem_new_from_file(const gchar *file)
415 gchar buffer[DEM_BLOCK_SIZE+1];
417 /* use to record state for dem_parse_block */
418 gint cur_column = -1;
420 const gchar *basename = a_file_basename(file);
422 if ( g_access ( file, R_OK ) != 0 )
425 if ( (strlen(basename)==11 || ((strlen(basename) == 15) && (basename[11] == '.' && basename[12] == 'z' && basename[13] == 'i' && basename[14] == 'p'))) &&
426 basename[7]=='.' && basename[8]=='h' && basename[9]=='g' && basename[10]=='t' &&
427 (basename[0] == 'N' || basename[0] == 'S') && (basename[3] == 'E' || basename[3] =='W')) {
428 gboolean is_zip_file = (strlen(basename) == 15);
429 rv = vik_dem_read_srtm_hgt(file, basename, is_zip_file);
433 /* Create Structure */
434 rv = g_malloc(sizeof(VikDEM));
437 f = g_fopen(file, "r");
440 buffer[fread(buffer, 1, DEM_BLOCK_SIZE, f)] = '\0';
441 if ( ! dem_parse_header ( buffer, rv ) ) {
445 /* TODO: actually use header -- i.e. GET # OF COLUMNS EXPECTED */
447 rv->columns = g_ptr_array_new();
455 buffer[fread(buffer, 1, DEM_BLOCK_SIZE, f)] = '\0';
457 /* Fix Fortran-style exponentiation */
465 dem_parse_block(buffer, rv, &cur_column, &cur_row);
468 /* TODO - class C records (right now says 'Invalid' and dies) */
474 if ( rv->horiz_units == VIK_DEM_HORIZ_UTM_METERS && rv->n_columns >= 2 )
475 rv->north_scale = rv->east_scale = GET_COLUMN(rv, 1)->east_west - GET_COLUMN(rv,0)->east_west;
477 /* FIXME bug in 10m DEM's */
478 if ( rv->horiz_units == VIK_DEM_HORIZ_UTM_METERS && rv->north_scale == 10 ) {
480 rv->min_north += 200;
487 void vik_dem_free ( VikDEM *dem )
490 for ( i = 0; i < dem->n_columns; i++)
491 g_free ( GET_COLUMN(dem, i)->points );
492 g_ptr_array_free ( dem->columns, TRUE );
496 gint16 vik_dem_get_xy ( VikDEM *dem, guint col, guint row )
498 if ( col < dem->n_columns )
499 if ( row < GET_COLUMN(dem, col)->n_points )
500 return GET_COLUMN(dem, col)->points[row];
501 return VIK_DEM_INVALID_ELEVATION;
504 gint16 vik_dem_get_east_north ( VikDEM *dem, gdouble east, gdouble north )
508 if ( east > dem->max_east || east < dem->min_east ||
509 north > dem->max_north || north < dem->min_north )
510 return VIK_DEM_INVALID_ELEVATION;
512 col = (gint) floor((east - dem->min_east) / dem->east_scale);
513 row = (gint) floor((north - dem->min_north) / dem->north_scale);
515 return vik_dem_get_xy ( dem, col, row );
518 static gboolean dem_get_ref_points_elev_dist(VikDEM *dem,
519 gdouble east, gdouble north, /* in seconds */
520 gint16 *elevs, gint16 *dists)
523 int cols[4], rows[4];
527 if ( east > dem->max_east || east < dem->min_east ||
528 north > dem->max_north || north < dem->min_north )
529 return FALSE; /* got nothing */
532 pos.lat = north/3600;
534 /* order of the data: sw, nw, ne, se */
536 cols[0] = (gint) floor((east - dem->min_east) / dem->east_scale);
537 rows[0] = (gint) floor((north - dem->min_north) / dem->north_scale);
538 ll[0].lon = (dem->min_east + dem->east_scale*cols[0])/3600;
539 ll[0].lat = (dem->min_north + dem->north_scale*rows[0])/3600;
542 rows[1] = rows[0] + 1;
543 ll[1].lon = ll[0].lon;
544 ll[1].lat = ll[0].lat + (gdouble)dem->north_scale/3600;
546 cols[2] = cols[0] + 1;
547 rows[2] = rows[0] + 1;
548 ll[2].lon = ll[0].lon + (gdouble)dem->east_scale/3600;
549 ll[2].lat = ll[0].lat + (gdouble)dem->north_scale/3600;
551 cols[3] = cols[0] + 1;
553 ll[3].lon = ll[0].lon + (gdouble)dem->east_scale/3600;
554 ll[3].lat = ll[0].lat;
556 for (i = 0; i < 4; i++) {
557 if ((elevs[i] = vik_dem_get_xy(dem, cols[i], rows[i])) == VIK_DEM_INVALID_ELEVATION)
559 dists[i] = a_coords_latlon_diff(&pos, &ll[i]);
563 for (i = 0; i < 4; i++)
564 fprintf(stderr, "%f:%f:%d:%d ", ll[i].lat, ll[i].lon, dists[i], elevs[i]);
565 fprintf(stderr, " north_scale=%f\n", dem->north_scale);
568 return TRUE; /* all OK */
571 gint16 vik_dem_get_simple_interpol ( VikDEM *dem, gdouble east, gdouble north )
574 gint16 elevs[4], dists[4];
576 if (!dem_get_ref_points_elev_dist(dem, east, north, elevs, dists))
577 return VIK_DEM_INVALID_ELEVATION;
579 for (i = 0; i < 4; i++) {
585 gdouble t = (gdouble)elevs[0]/dists[0] + (gdouble)elevs[1]/dists[1] + (gdouble)elevs[2]/dists[2] + (gdouble)elevs[3]/dists[3];
586 gdouble b = 1.0/dists[0] + 1.0/dists[1] + 1.0/dists[2] + 1.0/dists[3];
591 gint16 vik_dem_get_shepard_interpol ( VikDEM *dem, gdouble east, gdouble north )
594 gint16 elevs[4], dists[4];
599 if (!dem_get_ref_points_elev_dist(dem, east, north, elevs, dists))
600 return VIK_DEM_INVALID_ELEVATION;
603 for (i = 0; i < 4; i++) {
607 if (dists[i] > max_dist)
612 #if 0 /* derived method by Franke & Nielson. Does not seem to work too well here */
613 for (i = 0; i < 4; i++) {
614 tmp = pow((1.0*(max_dist - dists[i])/max_dist*dists[i]), 2);
620 for (i = 0; i < 4; i++) {
621 tmp = pow((1.0/dists[i]), 2);
626 // fprintf(stderr, "DEBUG: tmp=%f t=%f b=%f %f\n", tmp, t, b, t/b);
632 void vik_dem_east_north_to_xy ( VikDEM *dem, gdouble east, gdouble north, guint *col, guint *row )
634 *col = (gint) floor((east - dem->min_east) / dem->east_scale);
635 *row = (gint) floor((north - dem->min_north) / dem->north_scale);
636 if ( *col < 0 ) *col = 0;
637 if ( *row < 0 ) *row = 0;