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