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