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