]> Pileus Git - grits/blob - src/plugin-radar.c
355f93d0431dec7e78fae315f167342625af81a3
[grits] / src / plugin-radar.c
1 /*
2  * Copyright (C) 2009 Andy Spencer <spenceal@rose-hulman.edu>
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 <gtk/gtk.h>
20 #include <gtk/gtkgl.h>
21 #include <GL/gl.h>
22 #include <math.h>
23 #include <rsl.h>
24
25 #include "aweather-gui.h"
26 #include "plugin-radar.h"
27 #include "data.h"
28
29 /****************
30  * GObject code *
31  ****************/
32 static void aweather_radar_plugin_init(AWeatherPluginInterface *iface);
33 static void _aweather_radar_expose(AWeatherPlugin *_radar);
34 G_DEFINE_TYPE_WITH_CODE(AWeatherRadar, aweather_radar, G_TYPE_OBJECT,
35                 G_IMPLEMENT_INTERFACE(AWEATHER_TYPE_PLUGIN,
36                         aweather_radar_plugin_init));
37 static void aweather_radar_class_init(AWeatherRadarClass *klass)
38 {
39         GObjectClass *object_class = (GObjectClass*)klass;
40 }
41 static void aweather_radar_plugin_init(AWeatherPluginInterface *iface)
42 {
43         /* Add methods to the interface */
44         iface->expose = _aweather_radar_expose;
45 }
46 static void aweather_radar_init(AWeatherRadar *radar)
47 {
48         /* Set defaults */
49         radar->gui = NULL;
50 }
51
52 /**************************
53  * Data loading functions *
54  **************************/
55 /* Convert a sweep to an 2d array of data points */
56 static void bscan_sweep(AWeatherRadar *self, Sweep *sweep, colormap_t *colormap,
57                 guint8 **data, int *width, int *height)
58 {
59         /* Calculate max number of bins */
60         int i, max_bins = 0;
61         for (i = 0; i < sweep->h.nrays; i++)
62                 max_bins = MAX(max_bins, sweep->ray[i]->h.nbins);
63
64         /* Allocate buffer using max number of bins for each ray */
65         guint8 *buf = g_malloc0(sweep->h.nrays * max_bins * 4);
66
67         /* Fill the data */
68         int ri, bi;
69         for (ri = 0; ri < sweep->h.nrays; ri++) {
70                 Ray *ray  = sweep->ray[ri];
71                 for (bi = 0; bi < ray->h.nbins; bi++) {
72                         /* copy RGBA into buffer */
73                         //guint val   = dz_f(ray->range[bi]);
74                         guint8 val   = (guint8)ray->h.f(ray->range[bi]);
75                         guint  buf_i = (ri*max_bins+bi)*4;
76                         buf[buf_i+0] = colormap->data[val][0];
77                         buf[buf_i+1] = colormap->data[val][1];
78                         buf[buf_i+2] = colormap->data[val][2];
79                         buf[buf_i+3] = colormap->data[val][3];
80                         if (val == BADVAL     || val == RFVAL      || val == APFLAG ||
81                             val == NOTFOUND_H || val == NOTFOUND_V || val == NOECHO) {
82                                 buf[buf_i+3] = 0x00; // transparent
83                         }
84                 }
85         }
86
87         /* set output */
88         *width  = max_bins;
89         *height = sweep->h.nrays;
90         *data   = buf;
91 }
92
93 /* Load a sweep as the active texture */
94 static void load_sweep(AWeatherRadar *self, Sweep *sweep)
95 {
96         aweather_gui_gl_begin(self->gui);
97         self->cur_sweep = sweep;
98         int height, width;
99         guint8 *data;
100         bscan_sweep(self, sweep, self->cur_colormap, &data, &width, &height);
101         glDeleteTextures(1, &self->cur_sweep_tex);
102         glGenTextures(1, &self->cur_sweep_tex);
103         glBindTexture(GL_TEXTURE_2D, self->cur_sweep_tex);
104         glPixelStorei(GL_PACK_ALIGNMENT, 1);
105         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
106         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
107         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
108         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0,
109                         GL_RGBA, GL_UNSIGNED_BYTE, data);
110         g_free(data);
111         aweather_gui_gl_redraw(self->gui);
112         aweather_gui_gl_end(self->gui);
113 }
114
115 static void load_colormap(AWeatherRadar *self, gchar *table)
116 {
117         /* Set colormap so we can draw it on expose */
118         for (int i = 0; colormaps[i].name; i++)
119                 if (g_str_equal(colormaps[i].name, table))
120                         self->cur_colormap = &colormaps[i];
121 }
122
123 /* Add selectors to the config area for the sweeps */
124 static void on_sweep_clicked(GtkRadioButton *button, gpointer _self);
125 static void load_radar_gui(AWeatherRadar *self, Radar *radar)
126 {
127         /* Clear existing items */
128         GtkWidget *child = gtk_bin_get_child(GTK_BIN(self->config_body));
129         if (child)
130                 gtk_widget_destroy(child);
131
132         gdouble elev;
133         guint rows = 1, cols = 1, cur_cols;
134         gchar row_label_str[64], col_label_str[64], button_str[64];
135         GtkWidget *row_label, *col_label, *button = NULL, *elev_box;
136         GtkWidget *table = gtk_table_new(rows, cols, FALSE);
137
138         for (guint vi = 0; vi < radar->h.nvolumes; vi++) {
139                 Volume *vol = radar->v[vi];
140                 if (vol == NULL) continue;
141                 rows++; cols = 1; elev = 0;
142
143                 /* Row label */
144                 g_snprintf(row_label_str, 64, "<b>%s:</b>", vol->h.type_str);
145                 row_label = gtk_label_new(row_label_str);
146                 gtk_label_set_use_markup(GTK_LABEL(row_label), TRUE);
147                 gtk_misc_set_alignment(GTK_MISC(row_label), 1, 0.5);
148                 gtk_table_attach(GTK_TABLE(table), row_label,
149                                 0,1, rows-1,rows, GTK_FILL,GTK_FILL, 5,0);
150
151                 for (guint si = 0; si < vol->h.nsweeps; si++) {
152                         Sweep *sweep = vol->sweep[si];
153                         if (sweep == NULL || sweep->h.elev == 0) continue;
154                         if (sweep->h.elev != elev) {
155                                 cols++;
156                                 elev = sweep->h.elev;
157
158                                 /* Column label */
159                                 g_object_get(table, "n-columns", &cur_cols, NULL);
160                                 if (cols >  cur_cols) {
161                                         g_snprintf(col_label_str, 64, "<b>%.2f°</b>", elev);
162                                         col_label = gtk_label_new(col_label_str);
163                                         gtk_label_set_use_markup(GTK_LABEL(col_label), TRUE);
164                                         gtk_widget_set_size_request(col_label, 40, -1);
165                                         gtk_table_attach(GTK_TABLE(table), col_label,
166                                                         cols-1,cols, 0,1, GTK_FILL,GTK_FILL, 0,0);
167                                 }
168
169                                 elev_box = gtk_hbox_new(TRUE, 0);
170                                 gtk_table_attach(GTK_TABLE(table), elev_box,
171                                                 cols-1,cols, rows-1,rows, GTK_FILL,GTK_FILL, 0,0);
172                         }
173
174
175                         /* Button */
176                         g_snprintf(button_str, 64, "%3.2f", elev);
177                         button = gtk_radio_button_new_with_label_from_widget(
178                                         GTK_RADIO_BUTTON(button), button_str);
179                         gtk_widget_set_size_request(button, -1, 26);
180                         //button = gtk_radio_button_new_from_widget(GTK_RADIO_BUTTON(button));
181                         //gtk_widget_set_size_request(button, -1, 22);
182                         g_object_set(button, "draw-indicator", FALSE, NULL);
183                         gtk_box_pack_end(GTK_BOX(elev_box), button, TRUE, TRUE, 0);
184
185                         g_object_set_data(G_OBJECT(button), "type",  vol->h.type_str);
186                         g_object_set_data(G_OBJECT(button), "sweep", sweep);
187                         g_signal_connect(button, "clicked", G_CALLBACK(on_sweep_clicked), self);
188                 }
189         }
190         gtk_container_add(GTK_CONTAINER(self->config_body), table);
191         gtk_widget_show_all(table);
192 }
193
194 /* Load a radar from a decompressed file */
195 static void load_radar(AWeatherRadar *self, gchar *radar_file)
196 {
197         char *dir  = g_path_get_dirname(radar_file);
198         char *site = g_path_get_basename(dir);
199         g_free(dir);
200         g_debug("AWeatherRadar: load_radar - Loading new radar");
201         RSL_read_these_sweeps("all", NULL);
202         Radar *radar = self->cur_radar = RSL_wsr88d_to_radar(radar_file, site);
203         if (radar == NULL) {
204                 g_warning("fail to load radar: path=%s, site=%s", radar_file, site);
205                 g_free(site);
206                 return;
207         }
208         g_free(site);
209
210         /* Load the first sweep by default */
211         if (radar->h.nvolumes < 1 || radar->v[0]->h.nsweeps < 1) {
212                 g_warning("No sweeps found\n");
213         } else {
214                 /* load first available sweep */
215                 for (int vi = 0; vi < radar->h.nvolumes; vi++) {
216                         if (radar->v[vi]== NULL) continue;
217                         for (int si = 0; si < radar->v[vi]->h.nsweeps; si++) {
218                                 if (radar->v[vi]->sweep[si]== NULL) continue;
219                                 load_colormap(self, radar->v[vi]->h.type_str);
220                                 load_sweep(self, radar->v[vi]->sweep[si]);
221                                 break;
222                         }
223                         break;
224                 }
225         }
226
227         load_radar_gui(self, radar);
228 }
229
230 static void update_times(AWeatherRadar *self, char *site, char **last_time)
231 {
232         char *list_uri = g_strdup_printf(
233                         "http://mesonet.agron.iastate.edu/data/nexrd2/raw/K%s/dir.list",
234                         site);
235         GFile *list    = g_file_new_for_uri(list_uri);
236         g_free(list_uri);
237
238         gchar *data;
239         gsize length;
240         GError *error = NULL;
241         g_file_load_contents(list, NULL, &data, &length, NULL, &error);
242         g_object_unref(list);
243         if (error) {
244                 g_warning("Error loading list for %s: %s", site, error->message);
245                 g_error_free(error);
246                 return;
247         }
248         gchar **lines = g_strsplit(data, "\n", -1);
249         GtkTreeView  *tview  = GTK_TREE_VIEW(aweather_gui_get_widget(self->gui, "time"));
250         GtkListStore *lstore = GTK_LIST_STORE(gtk_tree_view_get_model(tview));
251         gtk_list_store_clear(lstore);
252         GtkTreeIter iter;
253         for (int i = 0; lines[i] && lines[i][0]; i++) {
254                 // format: `841907 KABR_20090510_0159'
255                 //g_message("\tadding %p [%s]", lines[i], lines[i]);
256                 char **parts = g_strsplit(lines[i], " ", 2);
257                 char *time = parts[1]+5;
258                 gtk_list_store_insert(lstore, &iter, 0);
259                 gtk_list_store_set(lstore, &iter, 0, time, -1);
260                 g_strfreev(parts);
261         }
262
263         if (last_time)
264                 gtk_tree_model_get(GTK_TREE_MODEL(lstore), &iter, 0, last_time, -1);
265
266         g_free(data);
267         g_strfreev(lines);
268 }
269
270 /*****************
271  * ASync helpers *
272  *****************/
273 typedef struct {
274         AWeatherRadar *self;
275         gchar *radar_file;
276 } decompressed_t;
277
278 static void decompressed_cb(GPid pid, gint status, gpointer _udata)
279 {
280         decompressed_t *udata = _udata;
281         if (status != 0) {
282                 g_warning("wsr88ddec exited with status %d", status);
283                 return;
284         }
285         load_radar(udata->self, udata->radar_file);
286         g_spawn_close_pid(pid);
287         g_free(udata->radar_file);
288         g_free(udata);
289 }
290
291 static void cached_cb(char *path, gboolean updated, gpointer _self)
292 {
293         AWeatherRadar *self = AWEATHER_RADAR(_self);
294         char *decompressed = g_strconcat(path, ".raw", NULL);
295         if (!updated) {
296                 load_radar(self, decompressed);
297                 return;
298         }
299
300         decompressed_t *udata = g_malloc(sizeof(decompressed_t));
301         udata->self       = self;
302         udata->radar_file = decompressed;
303         g_debug("AWeatherRadar: cached_cb - File updated, decompressing..");
304         char *argv[] = {"wsr88ddec", path, decompressed, NULL};
305         GPid pid;
306         GError *error = NULL;
307         g_spawn_async(
308                 NULL,    // const gchar *working_directory,
309                 argv,    // gchar **argv,
310                 NULL,    // gchar **envp,
311                 G_SPAWN_SEARCH_PATH|
312                 G_SPAWN_DO_NOT_REAP_CHILD, 
313                          // GSpawnFlags flags,
314                 NULL,    // GSpawnChildSetupFunc child_setup,
315                 NULL,    // gpointer user_data,
316                 &pid,    // GPid *child_pid,
317                 &error); // GError **error
318         if (error) {
319                 g_warning("failed to decompress WSR88D data: %s",
320                                 error->message);
321                 g_error_free(error);
322         }
323         g_child_watch_add(pid, decompressed_cb, udata);
324 }
325
326 /*************
327  * Callbacks *
328  *************/
329 static void on_sweep_clicked(GtkRadioButton *button, gpointer _self)
330 {
331         AWeatherRadar *self = AWEATHER_RADAR(_self);
332         load_colormap(self, g_object_get_data(G_OBJECT(button), "type" ));
333         load_sweep   (self, g_object_get_data(G_OBJECT(button), "sweep"));
334 }
335
336 static void on_time_changed(AWeatherView *view, char *time, gpointer _self)
337 {
338         AWeatherRadar *self = AWEATHER_RADAR(_self);
339         g_debug("AWeatherRadar: on_time_changed - setting time");
340         // format: http://mesonet.agron.iastate.edu/data/nexrd2/raw/KABR/KABR_20090510_0323
341         char *site = aweather_view_get_site(view);
342         char *base = "http://mesonet.agron.iastate.edu/data/";
343         char *path = g_strdup_printf("nexrd2/raw/K%s/K%s_%s", site, site, time);
344
345         /* Clear out children */
346         GtkWidget *child = gtk_bin_get_child(GTK_BIN(self->config_body));
347         if (child)
348                 gtk_widget_destroy(child);
349         gtk_container_add(GTK_CONTAINER(self->config_body),
350                 gtk_label_new("Loading radar..."));
351         gtk_widget_show_all(self->config_body);
352         if (self->cur_radar)
353                 RSL_free_radar(self->cur_radar);
354         self->cur_radar = NULL;
355         self->cur_sweep = NULL;
356         aweather_gui_gl_redraw(self->gui);
357
358         /* Start loading the new radar */
359         cache_file(base, path, AWEATHER_AUTOMATIC, cached_cb, self);
360         g_free(path);
361 }
362
363 static void on_site_changed(AWeatherView *view, char *site, gpointer _self)
364 {
365         AWeatherRadar *self = AWEATHER_RADAR(_self);
366         g_debug("AWeatherRadar: on_site_changed - Loading wsr88d list for %s", site);
367         char *time = NULL;
368         update_times(self, site, &time);
369         aweather_view_set_time(view, time);
370
371         g_free(time);
372 }
373
374 static void on_refresh(AWeatherView *view, gpointer user_data, gpointer _self)
375 {
376         AWeatherRadar *self = AWEATHER_RADAR(_self);
377         char *site = aweather_view_get_site(view);
378         char *time = NULL;
379         update_times(self, site, &time);
380         aweather_view_set_time(view, time);
381         g_free(time);
382 }
383
384 /***********
385  * Methods *
386  ***********/
387 AWeatherRadar *aweather_radar_new(AWeatherGui *gui)
388 {
389         g_debug("AWeatherRadar: new");
390         AWeatherRadar *self = g_object_new(AWEATHER_TYPE_RADAR, NULL);
391         self->gui = gui;
392
393         GtkWidget    *config  = aweather_gui_get_widget(gui, "tabs");
394         AWeatherView *view    = aweather_gui_get_view(gui);
395
396         /* Add configuration tab */
397         self->config_body = gtk_alignment_new(0, 0, 1, 1);
398         gtk_container_set_border_width(GTK_CONTAINER(self->config_body), 5);
399         gtk_container_add(GTK_CONTAINER(self->config_body), gtk_label_new("No radar loaded"));
400         gtk_notebook_prepend_page(GTK_NOTEBOOK(config), self->config_body, gtk_label_new("Radar"));
401
402         /* Set up OpenGL Stuff */
403         g_signal_connect(view,    "site-changed", G_CALLBACK(on_site_changed), self);
404         g_signal_connect(view,    "time-changed", G_CALLBACK(on_time_changed), self);
405         g_signal_connect(view,    "refresh",      G_CALLBACK(on_refresh),      self);
406
407         return self;
408 }
409
410 static void _aweather_radar_expose(AWeatherPlugin *_self)
411 {
412         AWeatherRadar *self = AWEATHER_RADAR(_self);
413         g_debug("AWeatherRadar: expose");
414         if (self->cur_sweep == NULL)
415                 return;
416         Sweep *sweep = self->cur_sweep;
417
418         /* Draw the rays */
419
420         glMatrixMode(GL_MODELVIEW);
421         glPushMatrix();
422         glBindTexture(GL_TEXTURE_2D, self->cur_sweep_tex);
423         glEnable(GL_TEXTURE_2D);
424         glDisable(GL_ALPHA_TEST);
425         glColor4f(1,1,1,1);
426         glBegin(GL_QUAD_STRIP);
427         for (int ri = 0; ri <= sweep->h.nrays; ri++) {
428                 Ray  *ray = NULL;
429                 double angle = 0;
430                 if (ri < sweep->h.nrays) {
431                         ray = sweep->ray[ri];
432                         angle = ((ray->h.azimuth - ((double)ray->h.beam_width/2.))*M_PI)/180.0; 
433                 } else {
434                         /* Do the right side of the last sweep */
435                         ray = sweep->ray[ri-1];
436                         angle = ((ray->h.azimuth + ((double)ray->h.beam_width/2.))*M_PI)/180.0; 
437                 }
438
439                 double lx = sin(angle);
440                 double ly = cos(angle);
441
442                 double near_dist = ray->h.range_bin1;
443                 double far_dist  = ray->h.nbins*ray->h.gate_size + ray->h.range_bin1;
444
445                 /* (find middle of bin) / scale for opengl */
446                 // near left
447                 glTexCoord2f(0.0, (double)ri/sweep->h.nrays-0.01);
448                 glVertex3f(lx*near_dist, ly*near_dist, 2.0);
449
450                 // far  left
451                 glTexCoord2f(1.0, (double)ri/sweep->h.nrays-0.01);
452                 glVertex3f(lx*far_dist,  ly*far_dist,  2.0);
453         }
454         //g_print("ri=%d, nr=%d, bw=%f\n", _ri, sweep->h.nrays, sweep->h.beam_width);
455         glEnd();
456         glPopMatrix();
457
458         /* Texture debug */
459         //glBegin(GL_QUADS);
460         //glTexCoord2d( 0.,  0.); glVertex3f(-500.,   0., 0.); // bot left
461         //glTexCoord2d( 0.,  1.); glVertex3f(-500., 500., 0.); // top left
462         //glTexCoord2d( 1.,  1.); glVertex3f( 0.,   500., 3.); // top right
463         //glTexCoord2d( 1.,  0.); glVertex3f( 0.,     0., 3.); // bot right
464         //glEnd();
465
466         /* Print the color table */
467         glDisable(GL_TEXTURE_2D);
468         glDisable(GL_DEPTH_TEST);
469         glMatrixMode(GL_MODELVIEW ); glPushMatrix(); glLoadIdentity();
470         glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity();
471         glBegin(GL_QUADS);
472         int i;
473         for (i = 0; i < 256; i++) {
474                 glColor4ub(self->cur_colormap->data[i][0],
475                            self->cur_colormap->data[i][1],
476                            self->cur_colormap->data[i][2],
477                            self->cur_colormap->data[i][3]);
478                 glVertex3f(-1.0, (float)((i  ) - 256/2)/(256/2), 0.0); // bot left
479                 glVertex3f(-1.0, (float)((i+1) - 256/2)/(256/2), 0.0); // top left
480                 glVertex3f(-0.9, (float)((i+1) - 256/2)/(256/2), 0.0); // top right
481                 glVertex3f(-0.9, (float)((i  ) - 256/2)/(256/2), 0.0); // bot right
482         }
483         glEnd();
484         glEnable(GL_DEPTH_TEST);
485         glEnable(GL_ALPHA_TEST);
486         glMatrixMode(GL_PROJECTION); glPopMatrix(); 
487         glMatrixMode(GL_MODELVIEW ); glPopMatrix();
488 }