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