]> Pileus Git - grits/blob - src/plugins/radar.c
forgot glade file
[grits] / src / plugins / 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 "misc.h"
27 #include "aweather-gui.h"
28 #include "radar.h"
29 #include "data.h"
30 #include "marching.h"
31
32 static char *nexrad_base = "http://mesonet.agron.iastate.edu/data/";
33
34 /****************
35  * GObject code *
36  ****************/
37 /* Plugin init */
38 static void aweather_radar_plugin_init(AWeatherPluginInterface *iface);
39 static void _aweather_radar_expose(AWeatherPlugin *_radar);
40 G_DEFINE_TYPE_WITH_CODE(AWeatherRadar, aweather_radar, G_TYPE_OBJECT,
41                 G_IMPLEMENT_INTERFACE(AWEATHER_TYPE_PLUGIN,
42                         aweather_radar_plugin_init));
43 static void aweather_radar_plugin_init(AWeatherPluginInterface *iface)
44 {
45         g_debug("AWeatherRadar: plugin_init");
46         /* Add methods to the interface */
47         iface->expose = _aweather_radar_expose;
48 }
49 /* Class/Object init */
50 static void aweather_radar_init(AWeatherRadar *radar)
51 {
52         g_debug("AWeatherRadar: class_init");
53         /* Set defaults */
54         radar->gui           = NULL;
55         radar->soup          = NULL;
56         radar->cur_triangles = NULL;
57         radar->cur_num_triangles = 0;
58 }
59 static void aweather_radar_dispose(GObject *gobject)
60 {
61         g_debug("AWeatherRadar: dispose");
62         AWeatherRadar *self = AWEATHER_RADAR(gobject);
63         /* Drop references */
64         G_OBJECT_CLASS(aweather_radar_parent_class)->dispose(gobject);
65 }
66 static void aweather_radar_finalize(GObject *gobject)
67 {
68         g_debug("AWeatherRadar: finalize");
69         AWeatherRadar *self = AWEATHER_RADAR(gobject);
70         /* Free data */
71         G_OBJECT_CLASS(aweather_radar_parent_class)->finalize(gobject);
72
73 }
74 static void aweather_radar_class_init(AWeatherRadarClass *klass)
75 {
76         g_debug("AWeatherRadar: class_init");
77         GObjectClass *gobject_class = (GObjectClass*)klass;
78         gobject_class->dispose  = aweather_radar_dispose;
79         gobject_class->finalize = aweather_radar_finalize;
80 }
81
82 /**************************
83  * Data loading functions *
84  **************************/
85 /* Convert a sweep to an 2d array of data points */
86 static void bscan_sweep(AWeatherRadar *self, Sweep *sweep, colormap_t *colormap,
87                 guint8 **data, int *width, int *height)
88 {
89         /* Calculate max number of bins */
90         int max_bins = 0;
91         for (int i = 0; i < sweep->h.nrays; i++)
92                 max_bins = MAX(max_bins, sweep->ray[i]->h.nbins);
93
94         /* Allocate buffer using max number of bins for each ray */
95         guint8 *buf = g_malloc0(sweep->h.nrays * max_bins * 4);
96
97         /* Fill the data */
98         for (int ri = 0; ri < sweep->h.nrays; ri++) {
99                 Ray *ray  = sweep->ray[ri];
100                 for (int bi = 0; bi < ray->h.nbins; bi++) {
101                         /* copy RGBA into buffer */
102                         //guint val   = dz_f(ray->range[bi]);
103                         guint8 val   = (guint8)ray->h.f(ray->range[bi]);
104                         guint  buf_i = (ri*max_bins+bi)*4;
105                         buf[buf_i+0] = colormap->data[val][0];
106                         buf[buf_i+1] = colormap->data[val][1];
107                         buf[buf_i+2] = colormap->data[val][2];
108                         buf[buf_i+3] = colormap->data[val][3]; // TESTING
109                         if (val == BADVAL     || val == RFVAL      || val == APFLAG ||
110                             val == NOTFOUND_H || val == NOTFOUND_V || val == NOECHO) {
111                                 buf[buf_i+3] = 0x00; // transparent
112                         }
113                 }
114         }
115
116         /* set output */
117         *width  = max_bins;
118         *height = sweep->h.nrays;
119         *data   = buf;
120 }
121
122 /* Load a sweep as the active texture */
123 static void load_sweep(AWeatherRadar *self, Sweep *sweep)
124 {
125         GisOpenGL *opengl = aweather_gui_get_opengl(self->gui);
126         gis_opengl_begin(opengl);
127         self->cur_sweep = sweep;
128         int height, width;
129         guint8 *data;
130         bscan_sweep(self, sweep, self->cur_colormap, &data, &width, &height);
131         glDeleteTextures(1, &self->cur_sweep_tex);
132         glGenTextures(1, &self->cur_sweep_tex);
133         glBindTexture(GL_TEXTURE_2D, self->cur_sweep_tex);
134         glPixelStorei(GL_PACK_ALIGNMENT, 1);
135         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
136         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
137         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
138         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0,
139                         GL_RGBA, GL_UNSIGNED_BYTE, data);
140         g_free(data);
141         gis_opengl_redraw(opengl);
142         gis_opengl_end(opengl);
143 }
144
145 static void load_colormap(AWeatherRadar *self, gchar *table)
146 {
147         /* Set colormap so we can draw it on expose */
148         for (int i = 0; colormaps[i].name; i++)
149                 if (g_str_equal(colormaps[i].name, table))
150                         self->cur_colormap = &colormaps[i];
151 }
152
153 /* Add selectors to the config area for the sweeps */
154 static void on_sweep_clicked(GtkRadioButton *button, gpointer _self);
155 static void load_radar_gui(AWeatherRadar *self, Radar *radar)
156 {
157         /* Clear existing items */
158         GtkWidget *child = gtk_bin_get_child(GTK_BIN(self->config_body));
159         if (child)
160                 gtk_widget_destroy(child);
161
162         gdouble elev;
163         guint rows = 1, cols = 1, cur_cols;
164         gchar row_label_str[64], col_label_str[64], button_str[64];
165         GtkWidget *row_label, *col_label, *button = NULL, *elev_box = NULL;
166         GtkWidget *table = gtk_table_new(rows, cols, FALSE);
167
168         for (guint vi = 0; vi < radar->h.nvolumes; vi++) {
169                 Volume *vol = radar->v[vi];
170                 if (vol == NULL) continue;
171                 rows++; cols = 1; elev = 0;
172
173                 /* Row label */
174                 g_snprintf(row_label_str, 64, "<b>%s:</b>", vol->h.type_str);
175                 row_label = gtk_label_new(row_label_str);
176                 gtk_label_set_use_markup(GTK_LABEL(row_label), TRUE);
177                 gtk_misc_set_alignment(GTK_MISC(row_label), 1, 0.5);
178                 gtk_table_attach(GTK_TABLE(table), row_label,
179                                 0,1, rows-1,rows, GTK_FILL,GTK_FILL, 5,0);
180
181                 for (guint si = 0; si < vol->h.nsweeps; si++) {
182                         Sweep *sweep = vol->sweep[si];
183                         if (sweep == NULL || sweep->h.elev == 0) continue;
184                         if (sweep->h.elev != elev) {
185                                 cols++;
186                                 elev = sweep->h.elev;
187
188                                 /* Column label */
189                                 g_object_get(table, "n-columns", &cur_cols, NULL);
190                                 if (cols >  cur_cols) {
191                                         g_snprintf(col_label_str, 64, "<b>%.2f°</b>", elev);
192                                         col_label = gtk_label_new(col_label_str);
193                                         gtk_label_set_use_markup(GTK_LABEL(col_label), TRUE);
194                                         gtk_widget_set_size_request(col_label, 50, -1);
195                                         gtk_table_attach(GTK_TABLE(table), col_label,
196                                                         cols-1,cols, 0,1, GTK_FILL,GTK_FILL, 0,0);
197                                 }
198
199                                 elev_box = gtk_hbox_new(TRUE, 0);
200                                 gtk_table_attach(GTK_TABLE(table), elev_box,
201                                                 cols-1,cols, rows-1,rows, GTK_FILL,GTK_FILL, 0,0);
202                         }
203
204
205                         /* Button */
206                         g_snprintf(button_str, 64, "%3.2f", elev);
207                         button = gtk_radio_button_new_with_label_from_widget(
208                                         GTK_RADIO_BUTTON(button), button_str);
209                         gtk_widget_set_size_request(button, -1, 26);
210                         //button = gtk_radio_button_new_from_widget(GTK_RADIO_BUTTON(button));
211                         //gtk_widget_set_size_request(button, -1, 22);
212                         g_object_set(button, "draw-indicator", FALSE, NULL);
213                         gtk_box_pack_end(GTK_BOX(elev_box), button, TRUE, TRUE, 0);
214
215                         g_object_set_data(G_OBJECT(button), "type",  vol->h.type_str);
216                         g_object_set_data(G_OBJECT(button), "sweep", sweep);
217                         g_signal_connect(button, "clicked", G_CALLBACK(on_sweep_clicked), self);
218                 }
219         }
220         gtk_container_add(GTK_CONTAINER(self->config_body), table);
221         gtk_widget_show_all(table);
222 }
223
224 static void _aweather_radar_grid_set(GRIDCELL *grid, int gi, Ray *ray, int bi)
225 {
226         Range range = ray->range[bi];
227
228         double angle = d2r(ray->h.azimuth);
229         double tilt  = d2r(ray->h.elev);
230
231         double lx    = sin(angle);
232         double ly    = cos(angle);
233         double lz    = sin(tilt);
234
235         double dist   = bi*ray->h.gate_size + ray->h.range_bin1;
236                 
237         grid->p[gi].x = lx*dist;
238         grid->p[gi].y = ly*dist;
239         grid->p[gi].z = lz*dist;
240
241         guint8 val = (guint8)ray->h.f(ray->range[bi]);
242         if (val == BADVAL     || val == RFVAL      || val == APFLAG ||
243             val == NOTFOUND_H || val == NOTFOUND_V || val == NOECHO ||
244             val > 80)
245                 val = 0;
246         grid->val[gi] = (float)val;
247         //g_debug("(%.2f,%.2f,%.2f) - (%.0f,%.0f,%.0f) = %d", 
248         //      angle, tilt, dist,
249         //      grid->p[gi].x,
250         //      grid->p[gi].y,
251         //      grid->p[gi].z,
252         //      val);
253 }
254
255 /* Load a radar from a decompressed file */
256 static void load_radar(AWeatherRadar *self, gchar *radar_file)
257 {
258         char *dir  = g_path_get_dirname(radar_file);
259         char *site = g_path_get_basename(dir);
260         g_free(dir);
261         g_debug("AWeatherRadar: load_radar - Loading new radar");
262         RSL_read_these_sweeps("all", NULL);
263         Radar *radar = self->cur_radar = RSL_wsr88d_to_radar(radar_file, site);
264         if (radar == NULL) {
265                 g_warning("fail to load radar: path=%s, site=%s", radar_file, site);
266                 g_free(site);
267                 return;
268         }
269         g_free(site);
270
271 #ifdef MARCHING
272         /* Load the surface */
273         if (self->cur_triangles) {
274                 g_free(self->cur_triangles);
275                 self->cur_triangles = NULL;
276         }
277         self->cur_num_triangles = 0;
278         int x = 1;
279         for (guint vi = 0; vi < radar->h.nvolumes; vi++) {
280                 if (radar->v[vi] == NULL) continue;
281
282                 for (guint si = 0; si+1 < radar->v[vi]->h.nsweeps; si++) {
283                         Sweep *sweep0 = radar->v[vi]->sweep[si+0];
284                         Sweep *sweep1 = radar->v[vi]->sweep[si+1];
285
286                         //g_debug("_aweather_radar_expose: sweep[%3d-%3d] -- nrays = %d, %d",
287                         //      si, si+1,sweep0->h.nrays, sweep1->h.nrays);
288
289                         /* Skip super->regular resolution switch for now */
290                         if (sweep0 == NULL || sweep0->h.elev == 0 ||
291                             sweep1 == NULL || sweep1->h.elev == 0 ||
292                             sweep0->h.nrays != sweep1->h.nrays)
293                                 continue;
294
295                         /* We repack the arrays so that raysX[0] is always north, etc */
296                         Ray **rays0 = g_malloc0(sizeof(Ray*)*sweep0->h.nrays);
297                         Ray **rays1 = g_malloc0(sizeof(Ray*)*sweep1->h.nrays);
298
299                         for (guint ri = 0; ri < sweep0->h.nrays; ri++)
300                                 rays0[(guint)(sweep0->ray[ri]->h.azimuth * sweep0->h.nrays / 360)] =
301                                         sweep0->ray[ri];
302                         for (guint ri = 0; ri < sweep1->h.nrays; ri++)
303                                 rays1[(guint)(sweep1->ray[ri]->h.azimuth * sweep1->h.nrays / 360)] =
304                                         sweep1->ray[ri];
305
306                         for (guint ri = 0; ri+x < sweep0->h.nrays; ri+=x) {
307                                 //g_debug("_aweather_radar_expose: ray[%3d-%3d] -- nbins = %d, %d, %d, %d",
308                                 //      ri, ri+x,
309                                 //      rays0[ri  ]->h.nbins, 
310                                 //      rays0[ri+1]->h.nbins, 
311                                 //      rays1[ri  ]->h.nbins, 
312                                 //      rays1[ri+1]->h.nbins);
313
314                                 for (guint bi = 0; bi+x < rays1[ri]->h.nbins; bi+=x) {
315                                         GRIDCELL grid = {};
316                                         _aweather_radar_grid_set(&grid, 7, rays0[(ri  )%sweep0->h.nrays], bi+x);
317                                         _aweather_radar_grid_set(&grid, 6, rays0[(ri+x)%sweep0->h.nrays], bi+x);
318                                         _aweather_radar_grid_set(&grid, 5, rays0[(ri+x)%sweep0->h.nrays], bi  );
319                                         _aweather_radar_grid_set(&grid, 4, rays0[(ri  )%sweep0->h.nrays], bi  );
320                                         _aweather_radar_grid_set(&grid, 3, rays1[(ri  )%sweep0->h.nrays], bi+x);
321                                         _aweather_radar_grid_set(&grid, 2, rays1[(ri+x)%sweep0->h.nrays], bi+x);
322                                         _aweather_radar_grid_set(&grid, 1, rays1[(ri+x)%sweep0->h.nrays], bi  );
323                                         _aweather_radar_grid_set(&grid, 0, rays1[(ri  )%sweep0->h.nrays], bi  );
324                                         
325                                         TRIANGLE tris[10];
326                                         int n = march_one_cube(grid, 40, tris);
327
328                                         self->cur_triangles = g_realloc(self->cur_triangles,
329                                                 (self->cur_num_triangles+n)*sizeof(TRIANGLE));
330                                         for (int i = 0; i < n; i++) {
331                                                 //g_debug("triangle: ");
332                                                 //g_debug("\t(%f,%f,%f)", tris[i].p[0].x, tris[i].p[0].y, tris[i].p[0].z);
333                                                 //g_debug("\t(%f,%f,%f)", tris[i].p[1].x, tris[i].p[1].y, tris[i].p[1].z);
334                                                 //g_debug("\t(%f,%f,%f)", tris[i].p[2].x, tris[i].p[2].y, tris[i].p[2].z);
335                                                 self->cur_triangles[self->cur_num_triangles+i] = tris[i];
336                                         }
337                                         self->cur_num_triangles += n;
338                                         //g_debug(" ");
339                                 }
340                         }
341                 }
342                 break; // Exit after first volume (reflectivity)
343         }
344 #endif
345
346         /* Load the first sweep by default */
347         if (radar->h.nvolumes < 1 || radar->v[0]->h.nsweeps < 1) {
348                 g_warning("No sweeps found\n");
349         } else {
350                 /* load first available sweep */
351                 for (int vi = 0; vi < radar->h.nvolumes; vi++) {
352                         if (radar->v[vi]== NULL) continue;
353                         for (int si = 0; si < radar->v[vi]->h.nsweeps; si++) {
354                                 if (radar->v[vi]->sweep[si]== NULL) continue;
355                                 load_colormap(self, radar->v[vi]->h.type_str);
356                                 load_sweep(self, radar->v[vi]->sweep[si]);
357                                 break;
358                         }
359                         break;
360                 }
361         }
362
363         load_radar_gui(self, radar);
364 }
365
366 /* TODO: These update times functions are getting ugly... */
367 static void update_times_gtk(AWeatherRadar *self, GList *times)
368 {
369         gchar *last_time = NULL;
370         GRegex *regex = g_regex_new("^[A-Z]{4}_([0-9]{8}_[0-9]{4})$", 0, 0, NULL); // KLSX_20090622_2113
371         GMatchInfo *info;
372
373         GtkTreeView  *tview  = GTK_TREE_VIEW(aweather_gui_get_widget(self->gui, "time"));
374         GtkListStore *lstore = GTK_LIST_STORE(gtk_tree_view_get_model(tview));
375         gtk_list_store_clear(lstore);
376         GtkTreeIter iter;
377         times = g_list_reverse(times);
378         for (GList *cur = times; cur; cur = cur->next) {
379                 g_message("trying time %s", (gchar*)cur->data);
380                 if (g_regex_match(regex, cur->data, 0, &info)) {
381                         gchar *time = g_match_info_fetch(info, 1);
382                         g_message("adding time %s", (gchar*)cur->data);
383                         gtk_list_store_insert(lstore, &iter, 0);
384                         gtk_list_store_set(lstore, &iter, 0, time, -1);
385                         last_time = time;
386                 }
387         }
388
389         GisView *view = aweather_gui_get_view(self->gui);
390         gis_view_set_time(view, last_time);
391
392         g_regex_unref(regex);
393         g_list_foreach(times, (GFunc)g_free, NULL);
394         g_list_free(times);
395 }
396 static void update_times_online_cb(char *path, gboolean updated, gpointer _self)
397 {
398         GList *times = NULL;
399         gchar *data;
400         gsize length;
401         g_file_get_contents(path, &data, &length, NULL);
402         gchar **lines = g_strsplit(data, "\n", -1);
403         for (int i = 0; lines[i] && lines[i][0]; i++) {
404                 char **parts = g_strsplit(lines[i], " ", 2);
405                 times = g_list_prepend(times, g_strdup(parts[1]));
406                 g_strfreev(parts);
407         }
408         g_strfreev(lines);
409         g_free(data);
410
411         update_times_gtk(_self, times);
412 }
413 static void update_times(AWeatherRadar *self, GisView *view, char *site)
414 {
415         GisWorld *world = aweather_gui_get_world(self->gui);
416         if (gis_world_get_offline(world)) {
417                 GList *times = NULL;
418                 gchar *path = g_build_filename(g_get_user_cache_dir(), PACKAGE, "nexrd2", "raw", site, NULL);
419                 GDir *dir = g_dir_open(path, 0, NULL);
420                 if (dir) {
421                         const gchar *name;
422                         while ((name = g_dir_read_name(dir))) {
423                                 times = g_list_prepend(times, g_strdup(name));
424                         }
425                         g_dir_close(dir);
426                 }
427                 g_free(path);
428                 update_times_gtk(self, times);
429         } else {
430                 gchar *path = g_strdup_printf("nexrd2/raw/%s/dir.list", site);
431                 cache_file(nexrad_base, path, AWEATHER_REFRESH, NULL, update_times_online_cb, self);
432                 /* update_times_gtk from update_times_online_cb */
433         }
434 }
435
436 /*****************
437  * ASync helpers *
438  *****************/
439 typedef struct {
440         AWeatherRadar *self;
441         gchar *radar_file;
442 } decompressed_t;
443
444 static void decompressed_cb(GPid pid, gint status, gpointer _udata)
445 {
446         decompressed_t *udata = _udata;
447         if (status != 0) {
448                 g_warning("wsr88ddec exited with status %d", status);
449                 return;
450         }
451         load_radar(udata->self, udata->radar_file);
452         g_spawn_close_pid(pid);
453         g_free(udata->radar_file);
454         g_free(udata);
455 }
456
457 static void cache_chunk_cb(char *path, goffset cur, goffset total, gpointer _self)
458 {
459         AWeatherRadar *self = AWEATHER_RADAR(_self);
460         double percent = (double)cur/total;
461
462         g_message("AWeatherRadar: cache_chunk_cb - %lld/%lld = %.2f%%",
463                         cur, total, percent*100);
464
465         gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(self->progress_bar), MIN(percent, 1.0));
466
467         gchar *msg = g_strdup_printf("Loading radar... %5.1f%% (%.2f/%.2f MB)",
468                         percent*100, (double)cur/1000000, (double)total/1000000);
469         gtk_label_set_text(GTK_LABEL(self->progress_label), msg);
470         g_free(msg);
471 }
472
473 static void cache_done_cb(char *path, gboolean updated, gpointer _self)
474 {
475         AWeatherRadar *self = AWEATHER_RADAR(_self);
476         char *decompressed = g_strconcat(path, ".raw", NULL);
477         if (!updated) {
478                 load_radar(self, decompressed);
479                 return;
480         }
481
482         decompressed_t *udata = g_malloc(sizeof(decompressed_t));
483         udata->self       = self;
484         udata->radar_file = decompressed;
485         g_debug("AWeatherRadar: cache_done_cb - File updated, decompressing..");
486         char *argv[] = {"wsr88ddec", path, decompressed, NULL};
487         GPid pid;
488         GError *error = NULL;
489         g_spawn_async(
490                 NULL,    // const gchar *working_directory,
491                 argv,    // gchar **argv,
492                 NULL,    // gchar **envp,
493                 G_SPAWN_SEARCH_PATH|
494                 G_SPAWN_DO_NOT_REAP_CHILD, 
495                          // GSpawnFlags flags,
496                 NULL,    // GSpawnChildSetupFunc child_setup,
497                 NULL,    // gpointer user_data,
498                 &pid,    // GPid *child_pid,
499                 &error); // GError **error
500         if (error) {
501                 g_warning("failed to decompress WSR88D data: %s",
502                                 error->message);
503                 g_error_free(error);
504         }
505         g_child_watch_add(pid, decompressed_cb, udata);
506         self->soup = NULL;
507 }
508
509 /*************
510  * Callbacks *
511  *************/
512 static void on_sweep_clicked(GtkRadioButton *button, gpointer _self)
513 {
514         AWeatherRadar *self = AWEATHER_RADAR(_self);
515         load_colormap(self, g_object_get_data(G_OBJECT(button), "type" ));
516         load_sweep   (self, g_object_get_data(G_OBJECT(button), "sweep"));
517 }
518
519 static void on_time_changed(GisView *view, const char *time, gpointer _self)
520 {
521         AWeatherRadar *self = AWEATHER_RADAR(_self);
522         g_debug("AWeatherRadar: on_time_changed - setting time=%s", time);
523         // format: http://mesonet.agron.iastate.edu/data/nexrd2/raw/KABR/KABR_20090510_0323
524         char *site = gis_view_get_site(view);
525         char *path = g_strdup_printf("nexrd2/raw/%s/%s_%s", site, site, time);
526
527         /* Set up progress bar */
528         GtkWidget *child = gtk_bin_get_child(GTK_BIN(self->config_body));
529         if (child) gtk_widget_destroy(child);
530
531         GtkWidget *vbox = gtk_vbox_new(FALSE, 10);
532         gtk_container_set_border_width(GTK_CONTAINER(vbox), 10);
533         self->progress_bar   = gtk_progress_bar_new();
534         self->progress_label = gtk_label_new("Loading radar...");
535         gtk_box_pack_start(GTK_BOX(vbox), self->progress_bar,   FALSE, FALSE, 0);
536         gtk_box_pack_start(GTK_BOX(vbox), self->progress_label, FALSE, FALSE, 0);
537         gtk_container_add(GTK_CONTAINER(self->config_body), vbox);
538         gtk_widget_show_all(self->config_body);
539
540         /* Clear radar */
541         if (self->cur_radar)
542                 RSL_free_radar(self->cur_radar);
543         self->cur_radar = NULL;
544         self->cur_sweep = NULL;
545         gis_opengl_redraw(aweather_gui_get_opengl(self->gui));
546
547         /* Start loading the new radar */
548         if (self->soup) {
549                 soup_session_abort(self->soup);
550                 self->soup = NULL;
551         }
552         if (gis_world_get_offline(aweather_gui_get_world(self->gui))) 
553                 self->soup = cache_file(nexrad_base, path, AWEATHER_ONCE,
554                                 cache_chunk_cb, cache_done_cb, self);
555         else 
556                 self->soup = cache_file(nexrad_base, path, AWEATHER_UPDATE,
557                                 cache_chunk_cb, cache_done_cb, self);
558         g_free(path);
559 }
560
561 static void on_site_changed(GisView *view, char *site, gpointer _self)
562 {
563         AWeatherRadar *self = AWEATHER_RADAR(_self);
564         g_debug("AWeatherRadar: on_site_changed - Loading wsr88d list for %s", site);
565         update_times(self, view, site);
566 }
567
568 static void on_refresh(GisWorld *world, gpointer _self)
569 {
570         AWeatherRadar *self = AWEATHER_RADAR(_self);
571         GisView *view = aweather_gui_get_view(AWEATHER_RADAR(_self)->gui);
572         char *site = gis_view_get_site(view);
573         update_times(self, view, site);
574 }
575
576 /***********
577  * Methods *
578  ***********/
579 AWeatherRadar *aweather_radar_new(AWeatherGui *gui)
580 {
581         g_debug("AWeatherRadar: new");
582         AWeatherRadar *self = g_object_new(AWEATHER_TYPE_RADAR, NULL);
583         self->gui  = gui;
584
585         GtkWidget    *config  = aweather_gui_get_widget(gui, "tabs");
586
587         /* Add configuration tab */
588         self->config_body = gtk_alignment_new(0, 0, 1, 1);
589         gtk_container_set_border_width(GTK_CONTAINER(self->config_body), 5);
590         gtk_container_add(GTK_CONTAINER(self->config_body), gtk_label_new("No radar loaded"));
591         gtk_notebook_prepend_page(GTK_NOTEBOOK(config), self->config_body, gtk_label_new("Radar"));
592
593         /* Set up OpenGL Stuff */
594         GisView  *view  = aweather_gui_get_view(gui);
595         GisWorld *world = aweather_gui_get_world(gui);
596         g_signal_connect(view,  "site-changed", G_CALLBACK(on_site_changed), self);
597         g_signal_connect(view,  "time-changed", G_CALLBACK(on_time_changed), self);
598         g_signal_connect(world, "refresh",      G_CALLBACK(on_refresh),      self);
599
600         on_site_changed(view, gis_view_get_site(view), self);
601
602         return self;
603 }
604
605 static void _aweather_radar_expose(AWeatherPlugin *_self)
606 {
607         AWeatherRadar *self = AWEATHER_RADAR(_self);
608         g_debug("AWeatherRadar: expose");
609         if (self->cur_sweep == NULL)
610                 return;
611         Sweep *sweep = self->cur_sweep;
612
613 #ifdef MARCHING
614         /* Draw the surface */
615         glMatrixMode(GL_MODELVIEW);
616         glPushMatrix();
617         glDisable(GL_TEXTURE_2D);
618         float light_ambient[]  = {0.1f, 0.1f, 0.0f};
619         float light_diffuse[]  = {0.9f, 0.9f, 0.9f};
620         float light_position[] = {-300000.0f, 500000.0f, 400000.0f, 1.0f};
621         glLightfv(GL_LIGHT0, GL_AMBIENT,  light_ambient);
622         glLightfv(GL_LIGHT0, GL_DIFFUSE,  light_diffuse);
623         glLightfv(GL_LIGHT0, GL_POSITION, light_position);
624         glEnable(GL_LIGHT0);
625         glEnable(GL_LIGHTING);
626         glEnable(GL_COLOR_MATERIAL);
627         glColor4f(1,1,1,0.75);
628         g_debug("ntri=%d", self->cur_num_triangles);
629         glBegin(GL_TRIANGLES);
630         for (int i = 0; i < self->cur_num_triangles; i++) {
631                 TRIANGLE t = self->cur_triangles[i];
632                 do_normal(t.p[0].x, t.p[0].y, t.p[0].z,
633                           t.p[1].x, t.p[1].y, t.p[1].z,
634                           t.p[2].x, t.p[2].y, t.p[2].z);
635                 glVertex3f(t.p[0].x, t.p[0].y, t.p[0].z);
636                 glVertex3f(t.p[1].x, t.p[1].y, t.p[1].z);
637                 glVertex3f(t.p[2].x, t.p[2].y, t.p[2].z);
638         }
639         glEnd();
640         glPopMatrix();
641 #endif
642
643         /* Draw the rays */
644         glDisable(GL_LIGHTING);
645         glDisable(GL_COLOR_MATERIAL);
646         glMatrixMode(GL_MODELVIEW);
647         glPushMatrix();
648         glBindTexture(GL_TEXTURE_2D, self->cur_sweep_tex);
649         glEnable(GL_TEXTURE_2D);
650         glDisable(GL_ALPHA_TEST);
651         glColor4f(1,1,1,1);
652         glBegin(GL_QUAD_STRIP);
653         for (int ri = 0; ri <= sweep->h.nrays; ri++) {
654                 Ray  *ray = NULL;
655                 double angle = 0;
656                 if (ri < sweep->h.nrays) {
657                         ray = sweep->ray[ri];
658                         angle = d2r(ray->h.azimuth - ((double)ray->h.beam_width/2.));
659                 } else {
660                         /* Do the right side of the last sweep */
661                         ray = sweep->ray[ri-1];
662                         angle = d2r(ray->h.azimuth + ((double)ray->h.beam_width/2.));
663                 }
664
665                 double lx = sin(angle);
666                 double ly = cos(angle);
667
668                 double near_dist = ray->h.range_bin1;
669                 double far_dist  = ray->h.nbins*ray->h.gate_size + ray->h.range_bin1;
670
671                 /* (find middle of bin) / scale for opengl */
672                 // near left
673                 glTexCoord2f(0.0, (double)ri/sweep->h.nrays-0.01);
674                 glVertex3f(lx*near_dist, ly*near_dist, 2.0);
675
676                 // far  left
677                 // todo: correct range-height function
678                 double height = sin(d2r(ray->h.elev)) * far_dist;
679                 glTexCoord2f(1.0, (double)ri/sweep->h.nrays-0.01);
680                 glVertex3f(lx*far_dist,  ly*far_dist, height);
681         }
682         //g_print("ri=%d, nr=%d, bw=%f\n", _ri, sweep->h.nrays, sweep->h.beam_width);
683         glEnd();
684         glPopMatrix();
685
686         /* Texture debug */
687         //glBegin(GL_QUADS);
688         //glTexCoord2d( 0.,  0.); glVertex3f(-500.,   0., 0.); // bot left
689         //glTexCoord2d( 0.,  1.); glVertex3f(-500., 500., 0.); // top left
690         //glTexCoord2d( 1.,  1.); glVertex3f( 0.,   500., 3.); // top right
691         //glTexCoord2d( 1.,  0.); glVertex3f( 0.,     0., 3.); // bot right
692         //glEnd();
693
694         /* Print the color table */
695         glDisable(GL_TEXTURE_2D);
696         glDisable(GL_DEPTH_TEST);
697         glMatrixMode(GL_MODELVIEW ); glPushMatrix(); glLoadIdentity();
698         glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity();
699         glBegin(GL_QUADS);
700         int i;
701         for (i = 0; i < 256; i++) {
702                 glColor4ub(self->cur_colormap->data[i][0],
703                            self->cur_colormap->data[i][1],
704                            self->cur_colormap->data[i][2],
705                            self->cur_colormap->data[i][3]);
706                 glVertex3f(-1.0, (float)((i  ) - 256/2)/(256/2), 0.0); // bot left
707                 glVertex3f(-1.0, (float)((i+1) - 256/2)/(256/2), 0.0); // top left
708                 glVertex3f(-0.9, (float)((i+1) - 256/2)/(256/2), 0.0); // top right
709                 glVertex3f(-0.9, (float)((i  ) - 256/2)/(256/2), 0.0); // bot right
710         }
711         glEnd();
712         glEnable(GL_DEPTH_TEST);
713         glEnable(GL_ALPHA_TEST);
714         glMatrixMode(GL_PROJECTION); glPopMatrix(); 
715         glMatrixMode(GL_MODELVIEW ); glPopMatrix();
716 }