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