]> Pileus Git - grits/blob - src/plugin-radar.c
4d75c73db6785810c403e176ad2a9ec7a44ea052
[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
24 #include "rsl.h"
25
26 #include "aweather-gui.h"
27 #include "plugin-radar.h"
28 #include "data.h"
29
30 GtkWidget *drawing;
31 GtkWidget *config_body;
32 static Sweep *cur_sweep = NULL;  // make this not global
33 //static int nred, ngreen, nblue;
34 //static char red[256], green[256], blue[256];
35 static colormap_t *colormap;
36 static guint sweep_tex = 0;
37 static Radar *radar = NULL;
38
39 static AWeatherGui *gui = NULL;
40
41 /**************************
42  * Data loading functions *
43  **************************/
44 /* Convert a sweep to an 2d array of data points */
45 static void bscan_sweep(Sweep *sweep, guint8 **data, int *width, int *height)
46 {
47         /* Calculate max number of bins */
48         int i, max_bins = 0;
49         for (i = 0; i < sweep->h.nrays; i++)
50                 max_bins = MAX(max_bins, sweep->ray[i]->h.nbins);
51
52         /* Allocate buffer using max number of bins for each ray */
53         guint8 *buf = g_malloc0(sweep->h.nrays * max_bins * 4);
54
55         /* Fill the data */
56         int ri, bi;
57         for (ri = 0; ri < sweep->h.nrays; ri++) {
58                 Ray *ray  = sweep->ray[ri];
59                 for (bi = 0; bi < ray->h.nbins; bi++) {
60                         /* copy RGBA into buffer */
61                         //guint val   = dz_f(ray->range[bi]);
62                         guint8 val   = (guint8)ray->h.f(ray->range[bi]);
63                         guint  buf_i = (ri*max_bins+bi)*4;
64                         buf[buf_i+0] = colormap->data[val][0];
65                         buf[buf_i+1] = colormap->data[val][1];
66                         buf[buf_i+2] = colormap->data[val][2];
67                         buf[buf_i+3] = colormap->data[val][3];
68                         if (val == BADVAL     || val == RFVAL      || val == APFLAG ||
69                             val == NOTFOUND_H || val == NOTFOUND_V || val == NOECHO) {
70                                 buf[buf_i+3] = 0x00; // transparent
71                         }
72                 }
73         }
74
75         /* set output */
76         *width  = max_bins;
77         *height = sweep->h.nrays;
78         *data   = buf;
79 }
80
81 static void load_color_table(char *table)
82 {
83         for (int i = 0; colormaps[i].name; i++)
84                 if (g_str_equal(colormaps[i].name, table))
85                         colormap = &colormaps[i];
86 }
87
88 /* Load a sweep as the active texture */
89 static void load_sweep(Sweep *sweep)
90 {
91         aweather_gui_gl_begin(gui);
92         cur_sweep = sweep;
93         int height, width;
94         guint8 *data;
95         bscan_sweep(sweep, &data, &width, &height);
96         glDeleteTextures(1, &sweep_tex);
97         glGenTextures(1, &sweep_tex);
98         glBindTexture(GL_TEXTURE_2D, sweep_tex);
99         glPixelStorei(GL_PACK_ALIGNMENT, 1);
100         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
101         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
102         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
103         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0,
104                         GL_RGBA, GL_UNSIGNED_BYTE, data);
105         g_free(data);
106         gtk_widget_queue_draw(aweather_gui_get_widget(gui, "drawing"));
107         aweather_gui_gl_end(gui);
108 }
109
110 /* Add selectors to the config area for the sweeps */
111 static void load_radar_gui(Radar *radar)
112 {
113         /* Clear existing items */
114         GtkWidget *child = gtk_bin_get_child(GTK_BIN(config_body));
115         if (child)
116                 gtk_widget_destroy(child);
117
118         GtkWidget *hbox = gtk_hbox_new(TRUE, 0);
119         GtkWidget *button = NULL;
120         int vi = 0, si = 0;
121         for (vi = 0; vi < radar->h.nvolumes; vi++) {
122                 Volume *vol = radar->v[vi];
123                 if (vol == NULL) continue;
124                 GtkWidget *vbox = gtk_vbox_new(FALSE, 0);
125                 for (si = 0; si < vol->h.nsweeps; si++) {
126                         Sweep *sweep = vol->sweep[si];
127                         if (sweep == NULL) continue;
128                         char *label = g_strdup_printf("Tilt: %.2f (%s)",
129                                         sweep->h.elev, vol->h.type_str);
130                         button = gtk_radio_button_new_with_label_from_widget(
131                                         GTK_RADIO_BUTTON(button), label);
132                         g_object_set(button, "draw-indicator", FALSE, NULL);
133                         g_signal_connect_swapped(button, "clicked",
134                                         G_CALLBACK(load_color_table), vol->h.type_str);
135                         g_signal_connect_swapped(button, "clicked",
136                                         G_CALLBACK(load_sweep), sweep);
137                         gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, TRUE, 0);
138                         g_free(label);
139                 }
140                 gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);
141         }
142         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(config_body), hbox);
143         gtk_widget_show_all(hbox);
144 }
145
146 /* Load a radar from a file */
147 static void load_radar_rsl(GPid pid, gint status, gpointer _path)
148 {
149         gchar *path = _path;
150         if (status != 0) {
151                 g_warning("wsr88ddec exited with status %d", status);
152                 return;
153         }
154         char *dir  = g_path_get_dirname(path);
155         char *site = g_path_get_basename(dir);
156         g_free(dir);
157         RSL_read_these_sweeps("all", NULL);
158         if (radar) {
159                 g_message("Freeing radar");
160                 RSL_free_radar(radar);
161         }
162         g_message("Allocating radar");
163         radar = RSL_wsr88d_to_radar(path, site);
164         if (radar == NULL) {
165                 g_warning("fail to load radar: path=%s, site=%s", path, site);
166                 g_free(path);
167                 g_free(site);
168                 return;
169         }
170         g_free(path);
171         g_free(site);
172
173         /* Load the first sweep by default */
174         if (radar->h.nvolumes < 1 || radar->v[0]->h.nsweeps < 1) {
175                 g_warning("No sweeps found\n");
176         } else {
177                 /* load first available sweep */
178                 for (int vi = 0; vi < radar->h.nvolumes; vi++) {
179                         if (radar->v[vi]== NULL) continue;
180                         for (int si = 0; si < radar->v[vi]->h.nsweeps; si++) {
181                                 if (radar->v[vi]->sweep[si]== NULL) continue;
182                                 load_color_table(radar->v[vi]->h.type_str);
183                                 load_sweep(radar->v[vi]->sweep[si]);
184                                 break;
185                         }
186                         break;
187                 }
188         }
189
190         load_radar_gui(radar);
191 }
192
193 /* decompress a radar file, then chain to the actuall loading function */
194 static void load_radar(char *path, gboolean updated, gpointer user_data)
195 {
196         char *raw  = g_strconcat(path, ".raw", NULL);
197         if (!updated) {
198                 load_radar_rsl(0, 0, raw);
199         } else {
200                 g_message("File updated, decompressing..");
201                 char *argv[] = {"wsr88ddec", path, raw, NULL};
202                 GPid pid;
203                 GError *error = NULL;
204                 g_spawn_async(
205                         NULL,    // const gchar *working_directory,
206                         argv,    // gchar **argv,
207                         NULL,    // gchar **envp,
208                         G_SPAWN_SEARCH_PATH|
209                         G_SPAWN_DO_NOT_REAP_CHILD, 
210                                  // GSpawnFlags flags,
211                         NULL,    // GSpawnChildSetupFunc child_setup,
212                         NULL,    // gpointer user_data,
213                         &pid,    // GPid *child_pid,
214                         &error); // GError **error
215                 if (error) {
216                         g_warning("failed to decompress WSR88D data: %s",
217                                         error->message);
218                         g_error_free(error);
219                 }
220                 g_child_watch_add(pid, load_radar_rsl, raw);
221         }
222 }
223
224 static void update_times(char *site, char **last_time)
225 {
226         char *list_uri = g_strdup_printf(
227                         "http://mesonet.agron.iastate.edu/data/nexrd2/raw/K%s/dir.list",
228                         site);
229         GFile *list    = g_file_new_for_uri(list_uri);
230         g_free(list_uri);
231
232         gchar *data;
233         gsize length;
234         GError *error = NULL;
235         g_file_load_contents(list, NULL, &data, &length, NULL, &error);
236         g_object_unref(list);
237         if (error) {
238                 g_warning("Error loading list for %s: %s", site, error->message);
239                 g_error_free(error);
240                 return;
241         }
242         gchar **lines = g_strsplit(data, "\n", -1);
243         GtkTreeView  *tview  = GTK_TREE_VIEW(aweather_gui_get_widget(gui, "time"));
244         GtkListStore *lstore = GTK_LIST_STORE(gtk_tree_view_get_model(tview));
245         gtk_list_store_clear(lstore);
246         GtkTreeIter iter;
247         for (int i = 0; lines[i] && lines[i][0]; i++) {
248                 // format: `841907 KABR_20090510_0159'
249                 //g_message("\tadding %p [%s]", lines[i], lines[i]);
250                 char **parts = g_strsplit(lines[i], " ", 2);
251                 char *time = parts[1]+5;
252                 gtk_list_store_insert(lstore, &iter, 0);
253                 gtk_list_store_set(lstore, &iter, 0, time, -1);
254                 g_strfreev(parts);
255         }
256
257         if (last_time)
258                 gtk_tree_model_get(GTK_TREE_MODEL(lstore), &iter, 0, last_time, -1);
259
260         g_free(data);
261         g_strfreev(lines);
262 }
263
264 /*************
265  * Callbacks *
266  *************/
267 static gboolean on_expose(GtkWidget *da, GdkEventExpose *event, gpointer user_data)
268 {
269         g_message("radar:expose");
270         if (cur_sweep == NULL)
271                 return FALSE;
272         Sweep *sweep = cur_sweep;
273
274         /* Draw the rays */
275
276         glMatrixMode(GL_MODELVIEW);
277         glPushMatrix();
278         glBindTexture(GL_TEXTURE_2D, sweep_tex);
279         glEnable(GL_TEXTURE_2D);
280         glDisable(GL_ALPHA_TEST);
281         glColor4f(1,1,1,1);
282         glBegin(GL_QUAD_STRIP);
283         for (int ri = 0; ri <= sweep->h.nrays; ri++) {
284                 Ray  *ray = NULL;
285                 double angle = 0;
286                 if (ri < sweep->h.nrays) {
287                         ray = sweep->ray[ri];
288                         angle = ((ray->h.azimuth - ((double)ray->h.beam_width/2.))*M_PI)/180.0; 
289                 } else {
290                         /* Do the right side of the last sweep */
291                         ray = sweep->ray[ri-1];
292                         angle = ((ray->h.azimuth + ((double)ray->h.beam_width/2.))*M_PI)/180.0; 
293                 }
294
295                 double lx = sin(angle);
296                 double ly = cos(angle);
297
298                 double near_dist = ray->h.range_bin1;
299                 double far_dist  = ray->h.nbins*ray->h.gate_size + ray->h.range_bin1;
300
301                 /* (find middle of bin) / scale for opengl */
302                 // near left
303                 glTexCoord2f(0.0, (double)ri/sweep->h.nrays);
304                 glVertex3f(lx*near_dist, ly*near_dist, 2.0);
305
306                 // far  left
307                 glTexCoord2f(1.0, (double)ri/sweep->h.nrays);
308                 glVertex3f(lx*far_dist,  ly*far_dist,  2.0);
309         }
310         //g_print("ri=%d, nr=%d, bw=%f\n", _ri, sweep->h.nrays, sweep->h.beam_width);
311         glEnd();
312         glPopMatrix();
313
314         /* Texture debug */
315         //glBegin(GL_QUADS);
316         //glTexCoord2d( 0.,  0.); glVertex3f(-1.,  0., 0.); // bot left
317         //glTexCoord2d( 0.,  1.); glVertex3f(-1.,  1., 0.); // top left
318         //glTexCoord2d( 1.,  1.); glVertex3f( 0.,  1., 0.); // top right
319         //glTexCoord2d( 1.,  0.); glVertex3f( 0.,  0., 0.); // bot right
320         //glEnd();
321
322         /* Print the color table */
323         glDisable(GL_TEXTURE_2D);
324         glDisable(GL_DEPTH_TEST);
325         glMatrixMode(GL_MODELVIEW ); glPushMatrix(); glLoadIdentity();
326         glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity();
327         glBegin(GL_QUADS);
328         int i;
329         for (i = 0; i < 256; i++) {
330                 glColor4ub(colormap->data[i][0],
331                            colormap->data[i][1],
332                            colormap->data[i][2],
333                            colormap->data[i][3]);
334                 glVertex3f(-1.0, (float)((i  ) - 256/2)/(256/2), 0.0); // bot left
335                 glVertex3f(-1.0, (float)((i+1) - 256/2)/(256/2), 0.0); // top left
336                 glVertex3f(-0.9, (float)((i+1) - 256/2)/(256/2), 0.0); // top right
337                 glVertex3f(-0.9, (float)((i  ) - 256/2)/(256/2), 0.0); // bot right
338         }
339         glEnd();
340         glEnable(GL_DEPTH_TEST);
341         glEnable(GL_ALPHA_TEST);
342         glMatrixMode(GL_PROJECTION); glPopMatrix(); 
343         glMatrixMode(GL_MODELVIEW ); glPopMatrix();
344         return FALSE;
345 }
346
347 static void on_time_changed(AWeatherView *view, char *time, gpointer user_data)
348 {
349         g_message("radar:setting time");
350         // format: http://mesonet.agron.iastate.edu/data/nexrd2/raw/KABR/KABR_20090510_0323
351         char *site = aweather_view_get_location(view);
352         char *base = "http://mesonet.agron.iastate.edu/data/";
353         char *path = g_strdup_printf("nexrd2/raw/K%s/K%s_%s", site, site, time);
354
355         radar = NULL;
356         cur_sweep = NULL; // Clear radar
357         gtk_widget_queue_draw(aweather_gui_get_widget(gui, "drawing"));
358
359         cache_file(base, path, AWEATHER_AUTOMATIC, load_radar, NULL);
360         g_free(path);
361 }
362
363 static void on_location_changed(AWeatherView *view, char *site, gpointer user_data)
364 {
365         g_message("Loading wsr88d list for %s", site);
366         char *time = NULL;
367         update_times(site, &time);
368         aweather_view_set_time(view, time);
369
370         g_free(time);
371 }
372
373 static void on_refresh(AWeatherView *view, gpointer user_data)
374 {
375         char *site = aweather_view_get_location(view);
376         char *time = NULL;
377         update_times(site, &time);
378         aweather_view_set_time(view, time);
379         g_free(time);
380 }
381
382 /* Init */
383 gboolean radar_init(AWeatherGui *_gui)
384 {
385         gui = _gui;
386         drawing = aweather_gui_get_widget(gui, "drawing");
387         GtkWidget    *config  = aweather_gui_get_widget(gui, "tabs");
388         AWeatherView *view    = aweather_gui_get_view(gui);
389
390         /* Add configuration tab */
391         config_body = gtk_scrolled_window_new(NULL, NULL);
392         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(config_body),
393                         gtk_label_new("No radar loaded"));
394         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(config_body),
395                         GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
396         gtk_notebook_prepend_page(GTK_NOTEBOOK(config),
397                         config_body, gtk_label_new("Radar"));
398
399         /* Set up OpenGL Stuff */
400         g_signal_connect(drawing, "expose-event",     G_CALLBACK(on_expose),           NULL);
401         g_signal_connect(view,    "location-changed", G_CALLBACK(on_location_changed), NULL);
402         g_signal_connect(view,    "time-changed",     G_CALLBACK(on_time_changed),     NULL);
403         g_signal_connect(view,    "refresh",          G_CALLBACK(on_refresh),          NULL);
404
405         return TRUE;
406 }