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