]> Pileus Git - grits/blob - src/grits-opengl.c
Add support for picking on orthographic projections
[grits] / src / grits-opengl.c
1 /*
2  * Copyright (C) 2009-2011 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 /**
19  * SECTION:grits-opengl
20  * @short_description: OpenGL based virtual globe
21  *
22  * #GritsOpenGL is the core rendering engine used by grits. Theoretically other
23  * renderers could be writte, but they have not been. GritsOpenGL uses the ROAM
24  * algorithm for updating surface mesh the planet. The only thing GritsOpenGL
25  * can actually render on it's own is a wireframe of a sphere.
26  *
27  * GritsOpenGL requires (at least) OpenGL 2.0.
28  */
29
30 #include <config.h>
31 #include <math.h>
32 #include <string.h>
33 #include <gdk/gdkkeysyms.h>
34 #include <gtk/gtk.h>
35
36 #include "grits-opengl.h"
37 #include "grits-util.h"
38 #include "gtkgl.h"
39 #include "roam.h"
40
41 // #define ROAM_DEBUG
42
43 /* Tessellation, "finding intersecting triangles" */
44 /* http://research.microsoft.com/pubs/70307/tr-2006-81.pdf */
45 /* http://www.opengl.org/wiki/Alpha_Blending */
46
47 /* The unsorted/sroted GLists are blank head nodes,
48  * This way us we can remove objects from the level just by fixing up links
49  * I.e. we don't need to do a lookup to remove an object if we have its GList */
50 struct RenderLevel {
51         GList unsorted;
52         GList sorted;
53 };
54
55 /***********
56  * Helpers *
57  ***********/
58 static void _set_visuals(GritsOpenGL *opengl)
59 {
60         double lat, lon, elev, rx, ry, rz;
61         grits_viewer_get_location(GRITS_VIEWER(opengl), &lat, &lon, &elev);
62         grits_viewer_get_rotation(GRITS_VIEWER(opengl), &rx, &ry, &rz);
63
64         /* Set projection and clipping planes */
65         glMatrixMode(GL_PROJECTION);
66         glLoadIdentity();
67
68         double width  = GTK_WIDGET(opengl)->allocation.width;
69         double height = GTK_WIDGET(opengl)->allocation.height;
70         double ang    = atan((height/2)/FOV_DIST)*2;
71         double atmos  = 100000;
72         double near   = MAX(elev*0.75 - atmos, 50); // View 100km of atmosphere
73         double far    = elev + 2*EARTH_R + atmos;   // on both sides of the earth
74
75         grits_viewer_get_location(GRITS_VIEWER(opengl), &lat, &lon, &elev);
76         glViewport(0, 0, width, height);
77         gluPerspective(rad2deg(ang), width/height, near, far);
78
79         /* Setup camera and lighting */
80         glMatrixMode(GL_MODELVIEW);
81         glLoadIdentity();
82
83         /* Camera 1 */
84         glRotatef(rx, 1, 0, 0);
85         glRotatef(rz, 0, 0, 1);
86
87         /* Lighting */
88 #ifdef ROAM_DEBUG
89         float light_ambient[]  = {0.7f, 0.7f, 0.7f, 1.0f};
90         float light_diffuse[]  = {2.0f, 2.0f, 2.0f, 1.0f};
91 #else
92         float light_ambient[]  = {0.2f, 0.2f, 0.2f, 1.0f};
93         float light_diffuse[]  = {0.8f, 0.8f, 0.8f, 1.0f};
94 #endif
95         float light_position[] = {-13*EARTH_R, 1*EARTH_R, 3*EARTH_R, 1.0f};
96         glLightfv(GL_LIGHT0, GL_AMBIENT,  light_ambient);
97         glLightfv(GL_LIGHT0, GL_DIFFUSE,  light_diffuse);
98         glLightfv(GL_LIGHT0, GL_POSITION, light_position);
99         glEnable(GL_LIGHT0);
100         glEnable(GL_LIGHTING);
101
102         float material_ambient[]  = {1.0, 1.0, 1.0, 1.0};
103         float material_diffuse[]  = {1.0, 1.0, 1.0, 1.0};
104         float material_specular[] = {0.0, 0.0, 0.0, 1.0};
105         float material_emission[] = {0.0, 0.0, 0.0, 1.0};
106         glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT,  material_ambient);
107         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE,  material_diffuse);
108         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material_specular);
109         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, material_emission);
110         glDisable(GL_TEXTURE_2D);
111         glDisable(GL_COLOR_MATERIAL);
112
113         /* Camera 2 */
114         glTranslatef(0, 0, -elev2rad(elev));
115         glRotatef(lat, 1, 0, 0);
116         glRotatef(-lon, 0, 1, 0);
117
118         glDisable(GL_ALPHA_TEST);
119
120         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
121         glEnable(GL_BLEND);
122
123 #ifndef ROAM_DEBUG
124         glCullFace(GL_BACK);
125         glEnable(GL_CULL_FACE);
126
127         glClearDepth(1.0);
128         glDepthFunc(GL_LEQUAL);
129         glEnable(GL_DEPTH_TEST);
130 #endif
131
132         glEnable(GL_LINE_SMOOTH);
133
134         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
135         //glShadeModel(GL_FLAT);
136
137         g_mutex_lock(opengl->sphere_lock);
138         roam_sphere_update_view(opengl->sphere);
139         g_mutex_unlock(opengl->sphere_lock);
140 }
141
142 typedef void (*GritsLevelFunc)(GritsObject *obj, gpointer user_data, gint level, gboolean sorted);
143
144 static gboolean _foreach_object_cb(gpointer key, gpointer value, gpointer pointers)
145 {
146         struct RenderLevel *level = value;
147         GritsLevelFunc user_func = ((gpointer*)pointers)[0];
148         gpointer       user_data = ((gpointer*)pointers)[1];
149         for (GList *cur = level->unsorted.next; cur; cur = cur->next)
150                 user_func(cur->data, user_data, (gint)key, FALSE);
151         for (GList *cur = level->sorted.next;   cur; cur = cur->next)
152                 user_func(cur->data, user_data, (gint)key, TRUE);
153         return FALSE;
154 }
155
156 static void _foreach_object(GritsOpenGL *opengl, GritsLevelFunc func, gpointer user_data)
157 {
158         gpointer pointers[2] = {func, user_data};
159         g_tree_foreach(opengl->objects, _foreach_object_cb, pointers);
160 }
161
162 static void _add_object_world(GritsObject *object, GPtrArray *array, gint level, gboolean sorted)
163 {
164         if (level < GRITS_LEVEL_HUD)
165                 g_ptr_array_add(array, object);
166 }
167
168 static void _add_object_ortho(GritsObject *object, GPtrArray *array, gint level, gboolean sorted)
169 {
170         if (level >= GRITS_LEVEL_HUD)
171                 g_ptr_array_add(array, object);
172 }
173
174 static GPtrArray *_objects_to_array(GritsOpenGL *opengl, gboolean ortho)
175 {
176         GPtrArray *array = g_ptr_array_new();
177         GritsLevelFunc func = (GritsLevelFunc)(ortho ? _add_object_ortho : _add_object_world);
178         _foreach_object(opengl, func, array);
179         return array;
180 }
181
182 /*************
183  * Callbacks *
184  *************/
185 static gboolean on_configure(GritsOpenGL *opengl, GdkEventConfigure *event, gpointer _)
186 {
187         g_debug("GritsOpenGL: on_configure");
188
189         _set_visuals(opengl);
190 #ifndef ROAM_DEBUG
191         g_mutex_lock(opengl->sphere_lock);
192         roam_sphere_update_errors(opengl->sphere);
193         g_mutex_unlock(opengl->sphere_lock);
194 #endif
195
196         return FALSE;
197 }
198
199 static gint run_picking(GritsOpenGL *opengl, GPtrArray *objects)
200 {
201         /* Setup picking buffers */
202         guint buffer[100][4] = {};
203         glSelectBuffer(G_N_ELEMENTS(buffer), (guint*)buffer);
204         if (!opengl->pickmode)
205                 glRenderMode(GL_SELECT);
206         glInitNames();
207
208         /* Render/pick objects */
209         for (guint i = 0; i < objects->len; i++) {
210                 glPushName(i);
211                 GritsObject *object = objects->pdata[i];
212                 object->state.picked = FALSE;
213                 grits_object_pick(object, opengl);
214                 glPopName();
215         }
216
217         int hits = glRenderMode(GL_RENDER);
218
219         /* Process hits */
220         for (int i = 0; i < hits; i++) {
221                 //g_debug("\tHit: %d",     i);
222                 //g_debug("\t\tcount: %d", buffer[i][0]);
223                 //g_debug("\t\tz1:    %f", (float)buffer[i][1]/0x7fffffff);
224                 //g_debug("\t\tz2:    %f", (float)buffer[i][2]/0x7fffffff);
225                 //g_debug("\t\tname:  %p", (gpointer)buffer[i][3]);
226                 guint        index  = buffer[i][3];
227                 GritsObject *object = objects->pdata[index];
228                 object->state.picked = TRUE;
229         }
230
231         /* Notify objects of pointer movements */
232         for (guint i = 0; i < objects->len; i++) {
233                 GritsObject *object = objects->pdata[i];
234                 grits_object_set_pointer(object, object->state.picked);
235         }
236
237         return hits;
238 }
239
240 static gboolean on_motion_notify(GritsOpenGL *opengl, GdkEventMotion *event, gpointer _)
241 {
242         gdouble height = GTK_WIDGET(opengl)->allocation.height;
243         gdouble gl_x   = event->x;
244         gdouble gl_y   = height - event->y;
245         gdouble delta  = opengl->pickmode ? 200 : 2;
246
247         if (opengl->pickmode) {
248                 gtk_gl_begin(GTK_WIDGET(opengl));
249                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
250         }
251
252         /* Save matricies */
253         gdouble projection[16];
254         gint    viewport[4]; // x=0,y=0,w,h
255         glGetDoublev(GL_PROJECTION_MATRIX, projection);
256         glGetIntegerv(GL_VIEWPORT, viewport);
257         glMatrixMode(GL_MODELVIEW);  glPushMatrix();
258         glMatrixMode(GL_PROJECTION); glPushMatrix();
259
260         g_mutex_lock(opengl->objects_lock);
261
262         GPtrArray *ortho = _objects_to_array(opengl, TRUE);
263         GPtrArray *world = _objects_to_array(opengl, FALSE);
264
265         /* Run perspective picking */
266         glMatrixMode(GL_PROJECTION); glLoadIdentity();
267         gluPickMatrix(gl_x, gl_y, delta, delta, viewport);
268         glMultMatrixd(projection);
269         gint world_hits = run_picking(opengl, world);
270
271         /* Run ortho picking */
272         glMatrixMode(GL_PROJECTION); glLoadIdentity();
273         gluPickMatrix(gl_x, gl_y, delta, delta, viewport);
274         glMatrixMode(GL_MODELVIEW);  glLoadIdentity();
275         glOrtho(0, viewport[2], viewport[3], 0, 1000, -1000);
276         gint ortho_hits = run_picking(opengl, ortho);
277
278         g_debug("GritsOpenGL: on_motion_notify - hits=%d/%d,%d/%d ev=%.0lf,%.0lf",
279                         world_hits, world->len, ortho_hits, ortho->len, gl_x, gl_y);
280
281         g_ptr_array_free(world, TRUE);
282         g_ptr_array_free(ortho, TRUE);
283
284         g_mutex_unlock(opengl->objects_lock);
285
286
287         /* Test unproject */
288         //gdouble lat, lon, elev;
289         //grits_viewer_unproject(GRITS_VIEWER(opengl),
290         //              gl_x, gl_y, -1, &lat, &lon, &elev);
291
292         /* Cleanup */
293         glMatrixMode(GL_PROJECTION); glPopMatrix();
294         glMatrixMode(GL_MODELVIEW);  glPopMatrix();
295
296         if (opengl->pickmode)
297                 gtk_gl_end(GTK_WIDGET(opengl));
298
299         return FALSE;
300 }
301
302 static gboolean _draw_level(gpointer key, gpointer value, gpointer user_data)
303 {
304         GritsOpenGL *opengl = user_data;
305         glong lnum = (glong)key;
306         struct RenderLevel *level = value;
307
308         g_debug("GritsOpenGL: _draw_level - level=%-4ld", lnum);
309         int nsorted = 0, nunsorted = 0;
310         GList *cur = NULL;
311
312         /* Configure individual levels */
313         if (lnum < GRITS_LEVEL_WORLD) {
314                 /* Disable depth for background levels */
315                 glDepthMask(FALSE);
316                 glDisable(GL_ALPHA_TEST);
317         } else if (lnum < GRITS_LEVEL_OVERLAY) {
318                 /* Enable depth and alpha for world levels */
319                 glEnable(GL_ALPHA_TEST);
320                 glAlphaFunc(GL_GREATER, 0.1);
321                 glDepthMask(TRUE);
322         } else {
323                 /* Disable depth for Overlay/HUD levels */
324                 // This causes rendering glitches not sure why..
325                 //glDepthMask(FALSE);
326         }
327
328         /* Start ortho */
329         if (lnum >= GRITS_LEVEL_HUD) {
330                 glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity();
331                 glMatrixMode(GL_MODELVIEW);  glPushMatrix(); glLoadIdentity();
332                 gint win_width  = GTK_WIDGET(opengl)->allocation.width;
333                 gint win_height = GTK_WIDGET(opengl)->allocation.height;
334                 glOrtho(0, win_width, win_height, 0, 1000, -1000);
335         }
336
337         /* Draw unsorted objects without depth testing,
338          * these are polygons, etc, rather than physical objects */
339         glDisable(GL_DEPTH_TEST);
340         for (cur = level->unsorted.next; cur; cur = cur->next, nunsorted++)
341                 grits_object_draw(GRITS_OBJECT(cur->data), opengl);
342
343         /* Draw sorted objects using depth testing
344          * These are things that are actually part of the world */
345         glEnable(GL_DEPTH_TEST);
346         for (cur = level->sorted.next; cur; cur = cur->next, nsorted++)
347                 grits_object_draw(GRITS_OBJECT(cur->data), opengl);
348
349         /* End ortho */
350         if (lnum >= GRITS_LEVEL_HUD) {
351                 glMatrixMode(GL_PROJECTION); glPopMatrix();
352                 glMatrixMode(GL_MODELVIEW);  glPopMatrix();
353         }
354
355         /* TODO: Prune empty levels */
356
357         g_debug("GritsOpenGL: _draw_level - drew %d,%d objects",
358                         nunsorted, nsorted);
359         return FALSE;
360 }
361
362 static gboolean on_expose(GritsOpenGL *opengl, GdkEventExpose *event, gpointer _)
363 {
364         g_debug("GritsOpenGL: on_expose - begin");
365
366         if (opengl->pickmode)
367                 return on_motion_notify(opengl, (GdkEventMotion*)event, NULL);
368
369         gtk_gl_begin(GTK_WIDGET(opengl));
370
371         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
372
373         _set_visuals(opengl);
374 #ifdef ROAM_DEBUG
375         glColor4f(1.0, 1.0, 1.0, 1.0);
376         glLineWidth(2);
377         glDisable(GL_TEXTURE_2D);
378         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
379         roam_sphere_draw(opengl->sphere);
380         (void)_draw_level;
381         //roam_sphere_draw_normals(opengl->sphere);
382 #else
383         g_mutex_lock(opengl->objects_lock);
384         if (opengl->wireframe)
385                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
386         g_tree_foreach(opengl->objects, _draw_level, opengl);
387         g_mutex_unlock(opengl->objects_lock);
388 #endif
389
390         gtk_gl_end(GTK_WIDGET(opengl));
391
392         g_debug("GritsOpenGL: on_expose - end\n");
393         return FALSE;
394 }
395
396 static gboolean on_key_press(GritsOpenGL *opengl, GdkEventKey *event, gpointer _)
397 {
398         g_debug("GritsOpenGL: on_key_press - key=%x, state=%x, plus=%x",
399                         event->keyval, event->state, GDK_plus);
400
401         guint kv = event->keyval;
402         /* Testing */
403         if (kv == GDK_w) {
404                 opengl->wireframe = !opengl->wireframe;
405                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
406         }
407         if (kv == GDK_p) {
408                 opengl->pickmode = !opengl->pickmode;
409                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
410         }
411 #ifdef ROAM_DEBUG
412         else if (kv == GDK_n) roam_sphere_split_one(opengl->sphere);
413         else if (kv == GDK_p) roam_sphere_merge_one(opengl->sphere);
414         else if (kv == GDK_r) roam_sphere_split_merge(opengl->sphere);
415         else if (kv == GDK_u) roam_sphere_update_errors(opengl->sphere);
416         gtk_widget_queue_draw(GTK_WIDGET(opengl));
417 #endif
418         return FALSE;
419 }
420
421 static gboolean on_chained_event(GritsOpenGL *opengl, GdkEvent *event, gpointer _)
422 {
423         _foreach_object(opengl, (GritsLevelFunc)grits_object_event, event);
424         return FALSE;
425 }
426
427 static gboolean _update_errors_cb(gpointer _opengl)
428 {
429         GritsOpenGL *opengl = _opengl;
430         g_mutex_lock(opengl->sphere_lock);
431         roam_sphere_update_errors(opengl->sphere);
432         g_mutex_unlock(opengl->sphere_lock);
433         opengl->ue_source = 0;
434         return FALSE;
435 }
436 static void on_view_changed(GritsOpenGL *opengl,
437                 gdouble _1, gdouble _2, gdouble _3)
438 {
439         g_debug("GritsOpenGL: on_view_changed");
440         _set_visuals(opengl);
441 #ifndef ROAM_DEBUG
442         if (!opengl->ue_source)
443                 opengl->ue_source = g_idle_add_full(G_PRIORITY_HIGH_IDLE+30,
444                                 _update_errors_cb, opengl, NULL);
445         //roam_sphere_update_errors(opengl->sphere);
446 #else
447         (void)_update_errors_cb;
448 #endif
449 }
450
451 static gboolean on_idle(GritsOpenGL *opengl)
452 {
453         //g_debug("GritsOpenGL: on_idle");
454         g_mutex_lock(opengl->sphere_lock);
455         if (roam_sphere_split_merge(opengl->sphere))
456                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
457         g_mutex_unlock(opengl->sphere_lock);
458         return TRUE;
459 }
460
461 static void on_realize(GritsOpenGL *opengl, gpointer _)
462 {
463         g_debug("GritsOpenGL: on_realize");
464         gtk_gl_begin(GTK_WIDGET(opengl));
465
466         /* Connect signals and idle functions now that opengl is fully initialized */
467         gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
468         g_signal_connect(opengl, "configure-event",  G_CALLBACK(on_configure),    NULL);
469         g_signal_connect(opengl, "expose-event",     G_CALLBACK(on_expose),       NULL);
470
471         g_signal_connect(opengl, "key-press-event",  G_CALLBACK(on_key_press),    NULL);
472
473         g_signal_connect(opengl, "location-changed", G_CALLBACK(on_view_changed), NULL);
474         g_signal_connect(opengl, "rotation-changed", G_CALLBACK(on_view_changed), NULL);
475
476         g_signal_connect(opengl, "motion-notify-event", G_CALLBACK(on_motion_notify), NULL);
477         g_signal_connect_after(opengl, "key-press-event",      G_CALLBACK(on_chained_event), NULL);
478         g_signal_connect_after(opengl, "key-release-event",    G_CALLBACK(on_chained_event), NULL);
479         g_signal_connect_after(opengl, "button-press-event",   G_CALLBACK(on_chained_event), NULL);
480         g_signal_connect_after(opengl, "button-release-event", G_CALLBACK(on_chained_event), NULL);
481         g_signal_connect_after(opengl, "motion-notify-event",  G_CALLBACK(on_chained_event), NULL);
482
483 #ifndef ROAM_DEBUG
484         opengl->sm_source[0] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+30, 33,  (GSourceFunc)on_idle, opengl, NULL);
485         opengl->sm_source[1] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+10, 500, (GSourceFunc)on_idle, opengl, NULL);
486 #else
487         (void)on_idle;
488         (void)_update_errors_cb;
489 #endif
490
491         /* Re-queue resize incase configure was triggered before realize */
492         gtk_widget_queue_resize(GTK_WIDGET(opengl));
493 }
494
495 /*********************
496  * GritsViewer methods *
497  *********************/
498 /**
499  * grits_opengl_new:
500  * @plugins: the plugins store to use
501  * @prefs:   the preferences object to use
502  *
503  * Create a new OpenGL renderer.
504  *
505  * Returns: the new #GritsOpenGL
506  */
507 GritsViewer *grits_opengl_new(GritsPlugins *plugins, GritsPrefs *prefs)
508 {
509         g_debug("GritsOpenGL: new");
510         GritsViewer *opengl = g_object_new(GRITS_TYPE_OPENGL, NULL);
511         grits_viewer_setup(opengl, plugins, prefs);
512         return opengl;
513 }
514
515 static void grits_opengl_center_position(GritsViewer *_opengl, gdouble lat, gdouble lon, gdouble elev)
516 {
517         glRotatef(lon, 0, 1, 0);
518         glRotatef(-lat, 1, 0, 0);
519         glTranslatef(0, 0, elev2rad(elev));
520 }
521
522 static void grits_opengl_project(GritsViewer *_opengl,
523                 gdouble lat, gdouble lon, gdouble elev,
524                 gdouble *px, gdouble *py, gdouble *pz)
525 {
526         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
527         gdouble x, y, z;
528         lle2xyz(lat, lon, elev, &x, &y, &z);
529         gluProject(x, y, z,
530                 opengl->sphere->view->model,
531                 opengl->sphere->view->proj,
532                 opengl->sphere->view->view,
533                 px, py, pz);
534 }
535
536 static void grits_opengl_unproject(GritsViewer *_opengl,
537                 gdouble px, gdouble py, gdouble pz,
538                 gdouble *lat, gdouble *lon, gdouble *elev)
539 {
540         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
541         if (!opengl->sphere->view)
542                 return;
543         gdouble x, y, z;
544         if (pz < 0) {
545                 gfloat tmp = 0;
546                 glReadPixels(px, py, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &tmp);
547                 pz = tmp;
548         }
549         gluUnProject(px, py, pz,
550                 opengl->sphere->view->model,
551                 opengl->sphere->view->proj,
552                 opengl->sphere->view->view,
553                 &x, &y, &z);
554         xyz2lle(x, y, z, lat, lon, elev);
555         //g_message("GritsOpenGL: unproject - "
556         //              "%4.0lf,%4.0lf,(%5.3lf) -> "
557         //              "%8.0lf,%8.0lf,%8.0lf -> "
558         //              "%6.2lf,%7.2lf,%4.0lf",
559         //      px, py, pz, x, y, z, *lat, *lon, *elev);
560 }
561
562 static void grits_opengl_set_height_func(GritsViewer *_opengl, GritsBounds *bounds,
563                 RoamHeightFunc height_func, gpointer user_data, gboolean update)
564 {
565         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
566         /* TODO: get points? */
567         g_mutex_lock(opengl->sphere_lock);
568         GList *triangles = roam_sphere_get_intersect(opengl->sphere, TRUE,
569                         bounds->n, bounds->s, bounds->e, bounds->w);
570         for (GList *cur = triangles; cur; cur = cur->next) {
571                 RoamTriangle *tri = cur->data;
572                 RoamPoint *points[] = {tri->p.l, tri->p.m, tri->p.r, tri->split};
573                 for (int i = 0; i < G_N_ELEMENTS(points); i++) {
574                         if (bounds->n >= points[i]->lat && points[i]->lat >= bounds->s &&
575                             bounds->e >= points[i]->lon && points[i]->lon >= bounds->w) {
576                                 points[i]->height_func = height_func;
577                                 points[i]->height_data = user_data;
578                                 roam_point_update_height(points[i]);
579                         }
580                 }
581         }
582         g_list_free(triangles);
583         g_mutex_unlock(opengl->sphere_lock);
584 }
585
586 static void _grits_opengl_clear_height_func_rec(RoamTriangle *root)
587 {
588         if (!root)
589                 return;
590         RoamPoint *points[] = {root->p.l, root->p.m, root->p.r, root->split};
591         for (int i = 0; i < G_N_ELEMENTS(points); i++) {
592                 points[i]->height_func = NULL;
593                 points[i]->height_data = NULL;
594                 roam_point_update_height(points[i]);
595         }
596         _grits_opengl_clear_height_func_rec(root->kids[0]);
597         _grits_opengl_clear_height_func_rec(root->kids[1]);
598 }
599
600 static void grits_opengl_clear_height_func(GritsViewer *_opengl)
601 {
602         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
603         for (int i = 0; i < G_N_ELEMENTS(opengl->sphere->roots); i++)
604                 _grits_opengl_clear_height_func_rec(opengl->sphere->roots[i]);
605 }
606
607 static gpointer grits_opengl_add(GritsViewer *_opengl, GritsObject *object,
608                 gint key, gboolean sort)
609 {
610         g_assert(GRITS_IS_OPENGL(_opengl));
611         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
612         g_mutex_lock(opengl->objects_lock);
613         struct RenderLevel *level = g_tree_lookup(opengl->objects, (gpointer)(gintptr)key);
614         if (!level) {
615                 level = g_new0(struct RenderLevel, 1);
616                 g_tree_insert(opengl->objects, (gpointer)(gintptr)key, level);
617         }
618         GList *list = sort ? &level->sorted : &level->unsorted;
619         /* Put the link in the list */
620         GList *link = g_new0(GList, 1);
621         link->data = object;
622         link->prev = list;
623         link->next = list->next;
624         if (list->next)
625                 list->next->prev = link;
626         list->next = link;
627         g_mutex_unlock(opengl->objects_lock);
628         return link;
629 }
630
631 static GritsObject *grits_opengl_remove(GritsViewer *_opengl, GritsObject *object)
632 {
633         g_assert(GRITS_IS_OPENGL(_opengl));
634         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
635         GList *link = object->ref;
636         g_mutex_lock(opengl->objects_lock);
637         /* Just unlink and free it, link->prev is assured */
638         link->prev->next = link->next;
639         if (link->next)
640                 link->next->prev = link->prev;
641         g_mutex_unlock(opengl->objects_lock);
642         object->ref    = NULL;
643         object->viewer = NULL;
644         g_free(link);
645         g_object_unref(object);
646         return object;
647 }
648
649 /****************
650  * GObject code *
651  ****************/
652 static int _objects_cmp(gconstpointer _a, gconstpointer _b, gpointer _)
653 {
654         gintptr a = (gintptr)_a, b = (gintptr)_b;
655         return a < b ? -1 :
656                a > b ?  1 : 0;
657 }
658 static void _objects_free(gpointer value)
659 {
660         struct RenderLevel *level = value;
661         if (level->sorted.next)
662                 g_list_free(level->sorted.next);
663         if (level->unsorted.next)
664                 g_list_free(level->unsorted.next);
665         g_free(level);
666 }
667
668 G_DEFINE_TYPE(GritsOpenGL, grits_opengl, GRITS_TYPE_VIEWER);
669 static void grits_opengl_init(GritsOpenGL *opengl)
670 {
671         g_debug("GritsOpenGL: init");
672         opengl->objects      = g_tree_new_full(_objects_cmp, NULL, NULL, _objects_free);
673         opengl->objects_lock = g_mutex_new();
674         opengl->sphere       = roam_sphere_new(opengl);
675         opengl->sphere_lock  = g_mutex_new();
676         gtk_gl_enable(GTK_WIDGET(opengl));
677         gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
678         g_signal_connect(opengl, "map", G_CALLBACK(on_realize), NULL);
679 }
680 static void grits_opengl_dispose(GObject *_opengl)
681 {
682         g_debug("GritsOpenGL: dispose");
683         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
684         if (opengl->sm_source[0]) {
685                 g_source_remove(opengl->sm_source[0]);
686                 opengl->sm_source[0] = 0;
687         }
688         if (opengl->sm_source[1]) {
689                 g_source_remove(opengl->sm_source[1]);
690                 opengl->sm_source[1] = 0;
691         }
692         if (opengl->ue_source) {
693                 g_source_remove(opengl->ue_source);
694                 opengl->ue_source = 0;
695         }
696         G_OBJECT_CLASS(grits_opengl_parent_class)->dispose(_opengl);
697 }
698 static void grits_opengl_finalize(GObject *_opengl)
699 {
700         g_debug("GritsOpenGL: finalize");
701         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
702         roam_sphere_free(opengl->sphere);
703         g_tree_destroy(opengl->objects);
704         g_mutex_free(opengl->objects_lock);
705         g_mutex_free(opengl->sphere_lock);
706         G_OBJECT_CLASS(grits_opengl_parent_class)->finalize(_opengl);
707 }
708 static void grits_opengl_class_init(GritsOpenGLClass *klass)
709 {
710         g_debug("GritsOpenGL: class_init");
711         GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
712         gobject_class->finalize = grits_opengl_finalize;
713         gobject_class->dispose = grits_opengl_dispose;
714
715         GritsViewerClass *viewer_class = GRITS_VIEWER_CLASS(klass);
716         viewer_class->center_position   = grits_opengl_center_position;
717         viewer_class->project           = grits_opengl_project;
718         viewer_class->unproject         = grits_opengl_unproject;
719         viewer_class->clear_height_func = grits_opengl_clear_height_func;
720         viewer_class->set_height_func   = grits_opengl_set_height_func;
721         viewer_class->add               = grits_opengl_add;
722         viewer_class->remove            = grits_opengl_remove;
723 }