]> Pileus Git - grits/blob - src/plugin-radar.c
moving roadplan to todo
[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         guint rows = 1, cols = 1, cur_cols;
119         gchar row_label_str[64], col_label_str[64], button_str[64];
120         GtkWidget *row_label, *col_label, *button = NULL;
121         GtkWidget *table = gtk_table_new(rows, cols, FALSE);
122
123         for (guint vi = 0; vi < radar->h.nvolumes; vi++) {
124                 Volume *vol = radar->v[vi];
125                 if (vol == NULL) continue;
126                 rows++; cols = 1;
127
128                 /* Row label */
129                 g_snprintf(row_label_str, 64, "<b>%s:</b>", vol->h.type_str);
130                 row_label = gtk_label_new(row_label_str);
131                 gtk_label_set_use_markup(GTK_LABEL(row_label), TRUE);
132                 gtk_misc_set_alignment(GTK_MISC(row_label), 1, 0.5);
133                 gtk_table_attach(GTK_TABLE(table), row_label,
134                                 0,1, rows-1,rows, GTK_FILL,GTK_FILL, 5,0);
135
136                 for (guint si = 0; si < vol->h.nsweeps; si++) {
137                         Sweep *sweep = vol->sweep[si];
138                         if (sweep == NULL || sweep->h.elev == 0) continue;
139                         cols++;
140
141                         /* Column label */
142                         g_object_get(table, "n-columns", &cur_cols, NULL);
143                         if (cols >  cur_cols) {
144                                 g_snprintf(col_label_str, 64, "<b>%.2f°</b>", sweep->h.elev);
145                                 col_label = gtk_label_new(col_label_str);
146                                 gtk_label_set_use_markup(GTK_LABEL(col_label), TRUE);
147                                 gtk_widget_set_size_request(col_label, 40, -1);
148                                 gtk_table_attach(GTK_TABLE(table), col_label,
149                                                 cols-1,cols, 0,1, GTK_FILL,GTK_FILL, 0,0);
150                         }
151
152                         /* Button */
153                         button = gtk_radio_button_new_from_widget(GTK_RADIO_BUTTON(button));
154                         gtk_widget_set_size_request(button, -1, 22);
155                         g_object_set(button, "draw-indicator", FALSE, NULL);
156                         g_signal_connect_swapped(button, "clicked",
157                                         G_CALLBACK(load_color_table), vol->h.type_str);
158                         g_signal_connect_swapped(button, "clicked",
159                                         G_CALLBACK(load_sweep), sweep);
160                         gtk_table_attach(GTK_TABLE(table), button,
161                                         cols-1,cols, rows-1,rows, GTK_FILL,GTK_FILL, 0,0);
162                 }
163         }
164         gtk_container_add(GTK_CONTAINER(config_body), table);
165         gtk_widget_show_all(table);
166 }
167
168 /* Load a radar from a file */
169 static void load_radar_rsl(GPid pid, gint status, gpointer _path)
170 {
171         gchar *path = _path;
172         if (status != 0) {
173                 g_warning("wsr88ddec exited with status %d", status);
174                 return;
175         }
176         char *dir  = g_path_get_dirname(path);
177         char *site = g_path_get_basename(dir);
178         g_free(dir);
179         RSL_read_these_sweeps("all", NULL);
180         if (radar) {
181                 g_message("Freeing radar");
182                 RSL_free_radar(radar);
183         }
184         g_message("Allocating radar");
185         radar = RSL_wsr88d_to_radar(path, site);
186         if (radar == NULL) {
187                 g_warning("fail to load radar: path=%s, site=%s", path, site);
188                 g_free(path);
189                 g_free(site);
190                 return;
191         }
192         g_free(path);
193         g_free(site);
194
195         /* Load the first sweep by default */
196         if (radar->h.nvolumes < 1 || radar->v[0]->h.nsweeps < 1) {
197                 g_warning("No sweeps found\n");
198         } else {
199                 /* load first available sweep */
200                 for (int vi = 0; vi < radar->h.nvolumes; vi++) {
201                         if (radar->v[vi]== NULL) continue;
202                         for (int si = 0; si < radar->v[vi]->h.nsweeps; si++) {
203                                 if (radar->v[vi]->sweep[si]== NULL) continue;
204                                 load_color_table(radar->v[vi]->h.type_str);
205                                 load_sweep(radar->v[vi]->sweep[si]);
206                                 break;
207                         }
208                         break;
209                 }
210         }
211
212         load_radar_gui(radar);
213 }
214
215 /* decompress a radar file, then chain to the actuall loading function */
216 static void load_radar(char *path, gboolean updated, gpointer user_data)
217 {
218         char *raw  = g_strconcat(path, ".raw", NULL);
219         if (!updated) {
220                 load_radar_rsl(0, 0, raw);
221         } else {
222                 g_message("File updated, decompressing..");
223                 char *argv[] = {"wsr88ddec", path, raw, NULL};
224                 GPid pid;
225                 GError *error = NULL;
226                 g_spawn_async(
227                         NULL,    // const gchar *working_directory,
228                         argv,    // gchar **argv,
229                         NULL,    // gchar **envp,
230                         G_SPAWN_SEARCH_PATH|
231                         G_SPAWN_DO_NOT_REAP_CHILD, 
232                                  // GSpawnFlags flags,
233                         NULL,    // GSpawnChildSetupFunc child_setup,
234                         NULL,    // gpointer user_data,
235                         &pid,    // GPid *child_pid,
236                         &error); // GError **error
237                 if (error) {
238                         g_warning("failed to decompress WSR88D data: %s",
239                                         error->message);
240                         g_error_free(error);
241                 }
242                 g_child_watch_add(pid, load_radar_rsl, raw);
243         }
244 }
245
246 static void update_times(char *site, char **last_time)
247 {
248         char *list_uri = g_strdup_printf(
249                         "http://mesonet.agron.iastate.edu/data/nexrd2/raw/K%s/dir.list",
250                         site);
251         GFile *list    = g_file_new_for_uri(list_uri);
252         g_free(list_uri);
253
254         gchar *data;
255         gsize length;
256         GError *error = NULL;
257         g_file_load_contents(list, NULL, &data, &length, NULL, &error);
258         g_object_unref(list);
259         if (error) {
260                 g_warning("Error loading list for %s: %s", site, error->message);
261                 g_error_free(error);
262                 return;
263         }
264         gchar **lines = g_strsplit(data, "\n", -1);
265         GtkTreeView  *tview  = GTK_TREE_VIEW(aweather_gui_get_widget(gui, "time"));
266         GtkListStore *lstore = GTK_LIST_STORE(gtk_tree_view_get_model(tview));
267         gtk_list_store_clear(lstore);
268         GtkTreeIter iter;
269         for (int i = 0; lines[i] && lines[i][0]; i++) {
270                 // format: `841907 KABR_20090510_0159'
271                 //g_message("\tadding %p [%s]", lines[i], lines[i]);
272                 char **parts = g_strsplit(lines[i], " ", 2);
273                 char *time = parts[1]+5;
274                 gtk_list_store_insert(lstore, &iter, 0);
275                 gtk_list_store_set(lstore, &iter, 0, time, -1);
276                 g_strfreev(parts);
277         }
278
279         if (last_time)
280                 gtk_tree_model_get(GTK_TREE_MODEL(lstore), &iter, 0, last_time, -1);
281
282         g_free(data);
283         g_strfreev(lines);
284 }
285
286 /*************
287  * Callbacks *
288  *************/
289 static gboolean on_expose(GtkWidget *da, GdkEventExpose *event, gpointer user_data)
290 {
291         g_message("radar:expose");
292         if (cur_sweep == NULL)
293                 return FALSE;
294         Sweep *sweep = cur_sweep;
295
296         /* Draw the rays */
297
298         glMatrixMode(GL_MODELVIEW);
299         glPushMatrix();
300         glBindTexture(GL_TEXTURE_2D, sweep_tex);
301         glEnable(GL_TEXTURE_2D);
302         glDisable(GL_ALPHA_TEST);
303         glColor4f(1,1,1,1);
304         glBegin(GL_QUAD_STRIP);
305         for (int ri = 0; ri <= sweep->h.nrays; ri++) {
306                 Ray  *ray = NULL;
307                 double angle = 0;
308                 if (ri < sweep->h.nrays) {
309                         ray = sweep->ray[ri];
310                         angle = ((ray->h.azimuth - ((double)ray->h.beam_width/2.))*M_PI)/180.0; 
311                 } else {
312                         /* Do the right side of the last sweep */
313                         ray = sweep->ray[ri-1];
314                         angle = ((ray->h.azimuth + ((double)ray->h.beam_width/2.))*M_PI)/180.0; 
315                 }
316
317                 double lx = sin(angle);
318                 double ly = cos(angle);
319
320                 double near_dist = ray->h.range_bin1;
321                 double far_dist  = ray->h.nbins*ray->h.gate_size + ray->h.range_bin1;
322
323                 /* (find middle of bin) / scale for opengl */
324                 // near left
325                 glTexCoord2f(0.0, (double)ri/sweep->h.nrays);
326                 glVertex3f(lx*near_dist, ly*near_dist, 2.0);
327
328                 // far  left
329                 glTexCoord2f(1.0, (double)ri/sweep->h.nrays);
330                 glVertex3f(lx*far_dist,  ly*far_dist,  2.0);
331         }
332         //g_print("ri=%d, nr=%d, bw=%f\n", _ri, sweep->h.nrays, sweep->h.beam_width);
333         glEnd();
334         glPopMatrix();
335
336         /* Texture debug */
337         //glBegin(GL_QUADS);
338         //glTexCoord2d( 0.,  0.); glVertex3f(-1.,  0., 0.); // bot left
339         //glTexCoord2d( 0.,  1.); glVertex3f(-1.,  1., 0.); // top left
340         //glTexCoord2d( 1.,  1.); glVertex3f( 0.,  1., 0.); // top right
341         //glTexCoord2d( 1.,  0.); glVertex3f( 0.,  0., 0.); // bot right
342         //glEnd();
343
344         /* Print the color table */
345         glDisable(GL_TEXTURE_2D);
346         glDisable(GL_DEPTH_TEST);
347         glMatrixMode(GL_MODELVIEW ); glPushMatrix(); glLoadIdentity();
348         glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity();
349         glBegin(GL_QUADS);
350         int i;
351         for (i = 0; i < 256; i++) {
352                 glColor4ub(colormap->data[i][0],
353                            colormap->data[i][1],
354                            colormap->data[i][2],
355                            colormap->data[i][3]);
356                 glVertex3f(-1.0, (float)((i  ) - 256/2)/(256/2), 0.0); // bot left
357                 glVertex3f(-1.0, (float)((i+1) - 256/2)/(256/2), 0.0); // top left
358                 glVertex3f(-0.9, (float)((i+1) - 256/2)/(256/2), 0.0); // top right
359                 glVertex3f(-0.9, (float)((i  ) - 256/2)/(256/2), 0.0); // bot right
360         }
361         glEnd();
362         glEnable(GL_DEPTH_TEST);
363         glEnable(GL_ALPHA_TEST);
364         glMatrixMode(GL_PROJECTION); glPopMatrix(); 
365         glMatrixMode(GL_MODELVIEW ); glPopMatrix();
366         return FALSE;
367 }
368
369 static void on_time_changed(AWeatherView *view, char *time, gpointer user_data)
370 {
371         g_message("radar:setting time");
372         // format: http://mesonet.agron.iastate.edu/data/nexrd2/raw/KABR/KABR_20090510_0323
373         char *site = aweather_view_get_location(view);
374         char *base = "http://mesonet.agron.iastate.edu/data/";
375         char *path = g_strdup_printf("nexrd2/raw/K%s/K%s_%s", site, site, time);
376
377         radar = NULL;
378         cur_sweep = NULL; // Clear radar
379         gtk_widget_queue_draw(aweather_gui_get_widget(gui, "drawing"));
380
381         cache_file(base, path, AWEATHER_AUTOMATIC, load_radar, NULL);
382         g_free(path);
383 }
384
385 static void on_location_changed(AWeatherView *view, char *site, gpointer user_data)
386 {
387         g_message("Loading wsr88d list for %s", site);
388         char *time = NULL;
389         update_times(site, &time);
390         aweather_view_set_time(view, time);
391
392         g_free(time);
393 }
394
395 static void on_refresh(AWeatherView *view, gpointer user_data)
396 {
397         char *site = aweather_view_get_location(view);
398         char *time = NULL;
399         update_times(site, &time);
400         aweather_view_set_time(view, time);
401         g_free(time);
402 }
403
404 /* Init */
405 gboolean radar_init(AWeatherGui *_gui)
406 {
407         gui = _gui;
408         drawing = aweather_gui_get_widget(gui, "drawing");
409         GtkWidget    *config  = aweather_gui_get_widget(gui, "tabs");
410         AWeatherView *view    = aweather_gui_get_view(gui);
411
412         /* Add configuration tab */
413         config_body = gtk_alignment_new(0, 0, 1, 1);
414         gtk_container_set_border_width(GTK_CONTAINER(config_body), 5);
415         gtk_container_add(GTK_CONTAINER(config_body), gtk_label_new("No radar loaded"));
416         gtk_notebook_prepend_page(GTK_NOTEBOOK(config), config_body, gtk_label_new("Radar"));
417
418         /* Set up OpenGL Stuff */
419         g_signal_connect(drawing, "expose-event",     G_CALLBACK(on_expose),           NULL);
420         g_signal_connect(view,    "location-changed", G_CALLBACK(on_location_changed), NULL);
421         g_signal_connect(view,    "time-changed",     G_CALLBACK(on_time_changed),     NULL);
422         g_signal_connect(view,    "refresh",          G_CALLBACK(on_refresh),          NULL);
423
424         return TRUE;
425 }