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