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