]> Pileus Git - aweather/blob - src/plugins/level2.c
Add iso-surface rendering to level 2 radars
[aweather] / src / plugins / level2.c
1 /*
2  * Copyright (C) 2009-2010 Andy Spencer <andy753421@gmail.com>
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 #include <config.h>
19 #include <math.h>
20 #include <GL/gl.h>
21 #include <glib/gstdio.h>
22 #include <grits.h>
23 #include <rsl.h>
24
25 #include "level2.h"
26
27 #define ISO_MIN 30
28 #define ISO_MAX 80
29
30 /**************************
31  * Data loading functions *
32  **************************/
33 /* Convert a sweep to an 2d array of data points */
34 static void _bscan_sweep(Sweep *sweep, AWeatherColormap *colormap,
35                 guint8 **data, int *width, int *height)
36 {
37         g_debug("AWeatherLevel2: _bscan_sweep - %p, %p, %p",
38                         sweep, colormap, data);
39         /* Calculate max number of bins */
40         int max_bins = 0;
41         for (int i = 0; i < sweep->h.nrays; i++)
42                 max_bins = MAX(max_bins, sweep->ray[i]->h.nbins);
43
44         /* Allocate buffer using max number of bins for each ray */
45         guint8 *buf = g_malloc0(sweep->h.nrays * max_bins * 4);
46
47         /* Fill the data */
48         for (int ri = 0; ri < sweep->h.nrays; ri++) {
49                 Ray *ray  = sweep->ray[ri];
50                 for (int bi = 0; bi < ray->h.nbins; bi++) {
51                         guint  buf_i = (ri*max_bins+bi)*4;
52                         float  value = ray->h.f(ray->range[bi]);
53
54                         /* Check for bad values */
55                         if (value == BADVAL     || value == RFVAL      || value == APFLAG ||
56                             value == NOTFOUND_H || value == NOTFOUND_V || value == NOECHO) {
57                                 buf[buf_i+3] = 0x00; // transparent
58                                 continue;
59                         }
60
61                         /* Convert data value to index */
62                         gint idx = value * colormap->scale + colormap->shift;
63                         idx = CLAMP(idx, 0, colormap->len);
64
65                         /* Copy color to buffer */
66                         buf[buf_i+0] = colormap->data[idx][0];
67                         buf[buf_i+1] = colormap->data[idx][1];
68                         buf[buf_i+2] = colormap->data[idx][2];
69                         buf[buf_i+3] = colormap->data[idx][3]*0.75; // TESTING
70                 }
71         }
72
73         /* set output */
74         *width  = max_bins;
75         *height = sweep->h.nrays;
76         *data   = buf;
77 }
78
79 /* Load a sweep into an OpenGL texture */
80 static void _load_sweep_gl(AWeatherLevel2 *self)
81 {
82         g_debug("AWeatherLevel2: _load_sweep_gl");
83         guint8 *data;
84         gint width, height;
85         _bscan_sweep(self->sweep, self->sweep_colors, &data, &width, &height);
86         gint tex_width  = pow(2, ceil(log(width )/log(2)));
87         gint tex_height = pow(2, ceil(log(height)/log(2)));
88         self->sweep_coords[0] = (double)width  / tex_width;
89         self->sweep_coords[1] = (double)height / tex_height;
90
91         if (!self->sweep_tex)
92                  glGenTextures(1, &self->sweep_tex);
93         glBindTexture(GL_TEXTURE_2D, self->sweep_tex);
94         glPixelStorei(GL_PACK_ALIGNMENT, 1);
95         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
96         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, tex_width, tex_height, 0,
97                         GL_RGBA, GL_UNSIGNED_BYTE, NULL);
98         glTexSubImage2D(GL_TEXTURE_2D, 0, 0,0, width,height,
99                         GL_RGBA, GL_UNSIGNED_BYTE, data);
100         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
101         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
102
103         g_free(data);
104 }
105
106 /* Decompress a radar file using wsr88dec */
107 static gboolean _decompress_radar(const gchar *file, const gchar *raw)
108 {
109         g_debug("AWeatherLevel2: _decompress_radar - \n\t%s\n\t%s", file, raw);
110         char *argv[] = {"wsr88ddec", (gchar*)file, (gchar*)raw, NULL};
111         gint status;
112         GError *error = NULL;
113         g_spawn_sync(
114                 NULL,    // const gchar *working_directory
115                 argv,    // gchar **argv
116                 NULL,    // gchar **envp
117                 G_SPAWN_SEARCH_PATH, // GSpawnFlags flags
118                 NULL,    // GSpawnChildSetupFunc child_setup
119                 NULL,    // gpointer user_data
120                 NULL,    // gchar *standard_output
121                 NULL,    // gchar *standard_output
122                 &status, // gint *exit_status
123                 &error); // GError **error
124         if (error) {
125                 g_warning("AWeatherLevel2: _decompress_radar - %s", error->message);
126                 g_error_free(error);
127                 return FALSE;
128         }
129         if (status != 0) {
130                 gchar *msg = g_strdup_printf("wsr88ddec exited with status %d", status);
131                 g_warning("AWeatherLevel2: _decompress_radar - %s", msg);
132                 g_free(msg);
133                 return FALSE;
134         }
135         return TRUE;
136 }
137
138 /* Load the radar into a Grits Volume */
139 static void _cart_to_sphere(VolCoord *out, VolCoord *in)
140 {
141         gdouble angle = in->x;
142         gdouble dist  = in->y;
143         gdouble tilt  = in->z;
144         gdouble lx    = sin(angle);
145         gdouble ly    = cos(angle);
146         gdouble lz    = sin(tilt);
147         //out->x = (ly*dist)/20000;
148         //out->y = (lz*dist)/10000-0.5;
149         //out->z = (lx*dist)/20000-1.5;
150         out->x = (lx*dist);
151         out->y = (ly*dist);
152         out->z = (lz*dist);
153 }
154
155 static VolGrid *_load_grid(Volume *vol)
156 {
157         g_debug("AWeatherLevel2: _load_grid");
158
159         Sweep *sweep   = vol->sweep[0];
160         Ray   *ray     = sweep->ray[0];
161         gint nsweeps   = vol->h.nsweeps;
162         gint nrays     = sweep->h.nrays/(1/sweep->h.beam_width)+1;
163         gint nbins     = ray->h.nbins  /(1000/ray->h.gate_size);
164         nbins = MIN(nbins, 100);
165
166         VolGrid  *grid = vol_grid_new(nrays, nbins, nsweeps);
167
168         gint rs, bs, val;
169         gint si=0, ri=0, bi=0;
170         for (si = 0; si < nsweeps; si++) {
171                 sweep = vol->sweep[si];
172                 rs    = 1.0/sweep->h.beam_width;
173         for (ri = 0; ri < nrays; ri++) {
174                 /* TODO: missing rays, pick ri based on azmith */
175                 ray   = sweep->ray[(ri*rs) % sweep->h.nrays];
176                 bs    = 1000/ray->h.gate_size;
177         for (bi = 0; bi < nbins; bi++) {
178                 if (bi*bs >= ray->h.nbins)
179                         break;
180                 val   = ray->h.f(ray->range[bi*bs]);
181                 if (val == BADVAL     || val == RFVAL      ||
182                     val == APFLAG     || val == NOECHO     ||
183                     val == NOTFOUND_H || val == NOTFOUND_V ||
184                     val > 80)
185                         val = 0;
186                 VolPoint *point = vol_grid_get(grid, ri, bi, si);
187                 point->value = val;
188                 point->c.x = deg2rad(ray->h.azimuth);
189                 point->c.y = bi*bs*ray->h.gate_size + ray->h.range_bin1;
190                 point->c.z = deg2rad(ray->h.elev);
191         } } }
192
193         for (si = 0; si < nsweeps; si++)
194         for (ri = 0; ri < nrays; ri++)
195         for (bi = 0; bi < nbins; bi++) {
196                 VolPoint *point = vol_grid_get(grid, ri, bi, si);
197                 if (point->c.y == 0)
198                         point->value = nan("");
199                 else
200                         _cart_to_sphere(&point->c, &point->c);
201         }
202         return grid;
203 }
204
205
206 /*********************
207  * Drawing functions *
208  *********************/
209 void aweather_level2_draw(GritsObject *_self, GritsOpenGL *opengl)
210 {
211         AWeatherLevel2 *self = AWEATHER_LEVEL2(_self);
212         if (!self->sweep || !self->sweep_tex)
213                 return;
214
215         /* Draw wsr88d */
216         Sweep *sweep = self->sweep;
217         glDisable(GL_ALPHA_TEST);
218         glDisable(GL_CULL_FACE);
219         glDisable(GL_LIGHTING);
220         glEnable(GL_TEXTURE_2D);
221         glEnable(GL_POLYGON_OFFSET_FILL);
222         glPolygonOffset(1.0, -2.0);
223         glColor4f(1,1,1,1);
224
225         /* Draw the rays */
226         gdouble xscale = self->sweep_coords[0];
227         gdouble yscale = self->sweep_coords[1];
228         glBindTexture(GL_TEXTURE_2D, self->sweep_tex);
229         glBegin(GL_TRIANGLE_STRIP);
230         for (int ri = 0; ri <= sweep->h.nrays; ri++) {
231                 Ray  *ray = NULL;
232                 double angle = 0;
233                 if (ri < sweep->h.nrays) {
234                         ray = sweep->ray[ri];
235                         angle = deg2rad(ray->h.azimuth - ((double)ray->h.beam_width/2.));
236                 } else {
237                         /* Do the right side of the last sweep */
238                         ray = sweep->ray[ri-1];
239                         angle = deg2rad(ray->h.azimuth + ((double)ray->h.beam_width/2.));
240                 }
241
242                 double lx = sin(angle);
243                 double ly = cos(angle);
244
245                 double near_dist = ray->h.range_bin1 - ((double)ray->h.gate_size/2.);
246                 double far_dist  = near_dist + (double)ray->h.nbins*ray->h.gate_size;
247
248                 /* (find middle of bin) / scale for opengl */
249                 // near left
250                 glTexCoord2f(0.0, ((double)ri/sweep->h.nrays)*yscale);
251                 glVertex3f(lx*near_dist, ly*near_dist, 2.0);
252
253                 // far  left
254                 // todo: correct range-height function
255                 double height = sin(deg2rad(ray->h.elev)) * far_dist;
256                 glTexCoord2f(xscale, ((double)ri/sweep->h.nrays)*yscale);
257                 glVertex3f(lx*far_dist,  ly*far_dist, height);
258         }
259         glEnd();
260         //g_print("ri=%d, nr=%d, bw=%f\n", _ri, sweep->h.nrays, sweep->h.beam_width);
261
262         /* Texture debug */
263         //glBegin(GL_QUADS);
264         //glTexCoord2d( 0.,  0.); glVertex3f(-500.,   0., 0.); // bot left
265         //glTexCoord2d( 0.,  1.); glVertex3f(-500., 500., 0.); // top left
266         //glTexCoord2d( 1.,  1.); glVertex3f( 0.,   500., 3.); // top right
267         //glTexCoord2d( 1.,  0.); glVertex3f( 0.,     0., 3.); // bot right
268         //glEnd();
269 }
270
271
272 /***********
273  * Methods *
274  ***********/
275 static gboolean _set_sweep_cb(gpointer _self)
276 {
277         g_debug("AWeatherLevel2: _set_sweep_cb");
278         AWeatherLevel2 *self = _self;
279         _load_sweep_gl(self);
280         grits_object_queue_draw(_self);
281         g_object_unref(self);
282         return FALSE;
283 }
284 void aweather_level2_set_sweep(AWeatherLevel2 *self,
285                 int type, float elev)
286 {
287         g_debug("AWeatherLevel2: set_sweep - %d %f", type, elev);
288
289         /* Find sweep */
290         Volume *volume = RSL_get_volume(self->radar, type);
291         if (!volume) return;
292         self->sweep = RSL_get_closest_sweep(volume, elev, 90);
293         if (!self->sweep) return;
294
295         /* Find colormap */
296         self->sweep_colors = NULL;
297         for (int i = 0; self->colormap[i].file; i++)
298                 if (self->colormap[i].type == type)
299                         self->sweep_colors = &self->colormap[i];
300         if (!self->sweep_colors) {
301                 g_warning("AWeatherLevel2: set_sweep - missing colormap[%d]", type);
302                 self->sweep_colors = &self->colormap[0];
303         }
304
305         /* Load data */
306         g_object_ref(self);
307         g_idle_add(_set_sweep_cb, self);
308 }
309
310 void aweather_level2_set_iso(AWeatherLevel2 *level2, gfloat level)
311 {
312         g_debug("AWeatherLevel2: set_iso - %f", level);
313
314         if (!level2->volume) {
315                 g_debug("AWeatherLevel2: set_iso - creating new volume");
316                 Volume      *rvol = RSL_get_volume(level2->radar, DZ_INDEX);
317                 VolGrid     *grid = _load_grid(rvol);
318                 GritsVolume *vol  = grits_volume_new(grid);
319                 vol->proj = GRITS_VOLUME_CARTESIAN;
320                 vol->disp = GRITS_VOLUME_SURFACE;
321                 GRITS_OBJECT(vol)->center = GRITS_OBJECT(level2)->center;
322                 grits_viewer_add(GRITS_OBJECT(level2)->viewer,
323                                 GRITS_OBJECT(vol), GRITS_LEVEL_WORLD, TRUE);
324                 level2->volume = vol;
325         }
326         if (ISO_MIN < level && level < ISO_MAX) {
327                 AWeatherColormap *cm = &level2->colormap[0];
328                 level2->volume->color[0] = cm->data[(gint)level][0];
329                 level2->volume->color[1] = cm->data[(gint)level][1];
330                 level2->volume->color[2] = cm->data[(gint)level][2];
331                 level2->volume->color[3] = cm->data[(gint)level][3];
332                 grits_volume_set_level(level2->volume, level);
333                 GRITS_OBJECT(level2->volume)->hidden = FALSE;
334         } else {
335                 GRITS_OBJECT(level2->volume)->hidden = TRUE;
336         }
337 }
338
339 AWeatherLevel2 *aweather_level2_new(Radar *radar, AWeatherColormap *colormap)
340 {
341         g_debug("AWeatherLevel2: new - %s", radar->h.radar_name);
342         RSL_sort_radar(radar);
343         AWeatherLevel2 *self = g_object_new(AWEATHER_TYPE_LEVEL2, NULL);
344         self->radar    = radar;
345         self->colormap = colormap;
346         aweather_level2_set_sweep(self, DZ_INDEX, 0);
347
348         GritsPoint center;
349         Radar_header *h = &radar->h;
350         center.lat  = (double)h->latd + (double)h->latm/60 + (double)h->lats/(60*60);
351         center.lon  = (double)h->lond + (double)h->lonm/60 + (double)h->lons/(60*60);
352         center.elev = h->height;
353         GRITS_OBJECT(self)->center = center;
354         return self;
355 }
356
357 AWeatherLevel2 *aweather_level2_new_from_file(const gchar *file, const gchar *site,
358                 AWeatherColormap *colormap)
359 {
360         g_debug("AWeatherLevel2: new_from_file %s %s", site, file);
361
362         /* Decompress radar */
363         gchar *raw = g_strconcat(file, ".raw", NULL);
364         if (g_file_test(raw, G_FILE_TEST_EXISTS)) {
365                 struct stat files, raws;
366                 g_stat(file, &files);
367                 g_stat(raw,  &raws);
368                 if (files.st_mtime > raws.st_mtime)
369                         if (!_decompress_radar(file, raw))
370                                 return NULL;
371         } else {
372                 if (!_decompress_radar(file, raw))
373                         return NULL;
374         }
375
376         /* Load the radar file */
377         RSL_read_these_sweeps("all", NULL);
378         g_message("read start");
379         Radar *radar = RSL_wsr88d_to_radar(raw, (gchar*)site);
380         g_message("read done");
381         g_free(raw);
382         if (!radar)
383                 return NULL;
384
385         return aweather_level2_new(radar, colormaps);
386 }
387
388 static void _on_sweep_clicked(GtkRadioButton *button, gpointer _level2)
389 {
390         AWeatherLevel2 *level2 = _level2;
391         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button))) {
392                 gint type = (gint)g_object_get_data(G_OBJECT(button), "type");
393                 gint elev = (gint)g_object_get_data(G_OBJECT(button), "elev");
394                 aweather_level2_set_sweep(level2, type, (float)elev/100);
395                 //self->colormap = level2->sweep_colors;
396         }
397 }
398
399 static void _on_iso_changed(GtkRange *range, gpointer _level2)
400 {
401         AWeatherLevel2 *level2 = _level2;
402         gfloat level = gtk_range_get_value(range);
403         aweather_level2_set_iso(level2, level);
404 }
405
406 GtkWidget *aweather_level2_get_config(AWeatherLevel2 *level2)
407 {
408         Radar *radar = level2->radar;
409         g_debug("AWeatherLevel2: get_config - %p, %p", level2, radar);
410         /* Clear existing items */
411         gfloat elev;
412         guint rows = 1, cols = 1, cur_cols;
413         gchar row_label_str[64], col_label_str[64], button_str[64];
414         GtkWidget *row_label, *col_label, *button = NULL, *elev_box = NULL;
415         GtkWidget *table = gtk_table_new(rows, cols, FALSE);
416
417         /* Add date */
418         gchar *date_str = g_strdup_printf("<b><i>%04d-%02d-%02d %02d:%02d</i></b>",
419                         radar->h.year, radar->h.month, radar->h.day,
420                         radar->h.hour, radar->h.minute);
421         GtkWidget *date_label = gtk_label_new(date_str);
422         gtk_label_set_use_markup(GTK_LABEL(date_label), TRUE);
423         gtk_table_attach(GTK_TABLE(table), date_label,
424                         0,1, 0,1, GTK_FILL,GTK_FILL, 5,0);
425         g_free(date_str);
426
427         /* Add sweeps */
428         for (guint vi = 0; vi < radar->h.nvolumes; vi++) {
429                 Volume *vol = radar->v[vi];
430                 if (vol == NULL) continue;
431                 rows++; cols = 1; elev = 0;
432
433                 /* Row label */
434                 g_snprintf(row_label_str, 64, "<b>%s:</b>", vol->h.type_str);
435                 row_label = gtk_label_new(row_label_str);
436                 gtk_label_set_use_markup(GTK_LABEL(row_label), TRUE);
437                 gtk_misc_set_alignment(GTK_MISC(row_label), 1, 0.5);
438                 gtk_table_attach(GTK_TABLE(table), row_label,
439                                 0,1, rows-1,rows, GTK_FILL,GTK_FILL, 5,0);
440
441                 for (guint si = 0; si < vol->h.nsweeps; si++) {
442                         Sweep *sweep = vol->sweep[si];
443                         if (sweep == NULL || sweep->h.elev == 0) continue;
444                         if (sweep->h.elev != elev) {
445                                 cols++;
446                                 elev = sweep->h.elev;
447
448                                 /* Column label */
449                                 g_object_get(table, "n-columns", &cur_cols, NULL);
450                                 if (cols >  cur_cols) {
451                                         g_snprintf(col_label_str, 64, "<b>%.2f°</b>", elev);
452                                         col_label = gtk_label_new(col_label_str);
453                                         gtk_label_set_use_markup(GTK_LABEL(col_label), TRUE);
454                                         gtk_widget_set_size_request(col_label, 50, -1);
455                                         gtk_table_attach(GTK_TABLE(table), col_label,
456                                                         cols-1,cols, 0,1, GTK_FILL,GTK_FILL, 0,0);
457                                 }
458
459                                 elev_box = gtk_hbox_new(TRUE, 0);
460                                 gtk_table_attach(GTK_TABLE(table), elev_box,
461                                                 cols-1,cols, rows-1,rows, GTK_FILL,GTK_FILL, 0,0);
462                         }
463
464
465                         /* Button */
466                         g_snprintf(button_str, 64, "%3.2f", elev);
467                         button = gtk_radio_button_new_with_label_from_widget(
468                                         GTK_RADIO_BUTTON(button), button_str);
469                         gtk_widget_set_size_request(button, -1, 26);
470                         //button = gtk_radio_button_new_from_widget(GTK_RADIO_BUTTON(button));
471                         //gtk_widget_set_size_request(button, -1, 22);
472                         g_object_set(button, "draw-indicator", FALSE, NULL);
473                         gtk_box_pack_end(GTK_BOX(elev_box), button, TRUE, TRUE, 0);
474
475                         g_object_set_data(G_OBJECT(button), "level2", (gpointer)level2);
476                         g_object_set_data(G_OBJECT(button), "type",   (gpointer)vi);
477                         g_object_set_data(G_OBJECT(button), "elev",   (gpointer)(int)(elev*100));
478                         g_signal_connect(button, "clicked", G_CALLBACK(_on_sweep_clicked), level2);
479                 }
480         }
481
482         /* Add Iso-surface volume */
483         g_object_get(table, "n-columns", &cols, NULL);
484         row_label = gtk_label_new("<b>Isosurface:</b>");
485         gtk_label_set_use_markup(GTK_LABEL(row_label), TRUE);
486         gtk_misc_set_alignment(GTK_MISC(row_label), 1, 0.5);
487         gtk_table_attach(GTK_TABLE(table), row_label,
488                         0,1, rows,rows+1, GTK_FILL,GTK_FILL, 5,0);
489         GtkWidget *scale = gtk_hscale_new_with_range(ISO_MIN, ISO_MAX, 0.5);
490         gtk_widget_set_size_request(scale, -1, 26);
491         gtk_scale_set_value_pos(GTK_SCALE(scale), GTK_POS_LEFT);
492         gtk_range_set_inverted(GTK_RANGE(scale), TRUE);
493         gtk_range_set_value(GTK_RANGE(scale), ISO_MAX);
494         g_signal_connect(scale, "value-changed", G_CALLBACK(_on_iso_changed), level2);
495         gtk_table_attach(GTK_TABLE(table), scale,
496                         1,cols+1, rows,rows+1, GTK_FILL|GTK_EXPAND,GTK_FILL, 0,0);
497         /* Shove all the buttons to the left, but keep the slider expanded */
498         gtk_table_attach(GTK_TABLE(table), gtk_label_new(""),
499                         cols,cols+1, 0,1, GTK_FILL|GTK_EXPAND,GTK_FILL, 0,0);
500         return table;
501 }
502
503 /****************
504  * GObject code *
505  ****************/
506 G_DEFINE_TYPE(AWeatherLevel2, aweather_level2, GRITS_TYPE_OBJECT);
507 static void aweather_level2_init(AWeatherLevel2 *self)
508 {
509 }
510 static void aweather_level2_finalize(GObject *_self)
511 {
512         AWeatherLevel2 *self = AWEATHER_LEVEL2(_self);
513         g_debug("AWeatherLevel2: finalize - %p", _self);
514         RSL_free_radar(self->radar);
515         if (self->sweep_tex)
516                 glDeleteTextures(1, &self->sweep_tex);
517         G_OBJECT_CLASS(aweather_level2_parent_class)->finalize(_self);
518 }
519 static void aweather_level2_class_init(AWeatherLevel2Class *klass)
520 {
521         G_OBJECT_CLASS(klass)->finalize = aweather_level2_finalize;
522         GRITS_OBJECT_CLASS(klass)->draw   = aweather_level2_draw;
523 }