]> Pileus Git - grits/blob - src/grits-opengl.c
Remove deprecated thread functions
[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         } else {
311                 /* Disable depth for Overlay/HUD levels */
312                 glDepthMask(FALSE);
313         }
314
315         /* Start ortho */
316         if (level->num >= GRITS_LEVEL_HUD) {
317                 glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity();
318                 glMatrixMode(GL_MODELVIEW);  glPushMatrix(); glLoadIdentity();
319                 gint win_width  = GTK_WIDGET(opengl)->allocation.width;
320                 gint win_height = GTK_WIDGET(opengl)->allocation.height;
321                 glOrtho(0, win_width, win_height, 0, 1000, -1000);
322         }
323
324         /* Draw unsorted objects without depth testing,
325          * these are polygons, etc, rather than physical objects */
326         glDisable(GL_DEPTH_TEST);
327         for (cur = level->unsorted.next; cur; cur = cur->next, nunsorted++)
328                 grits_object_draw(GRITS_OBJECT(cur->data), opengl);
329
330         /* Draw sorted objects using depth testing
331          * These are things that are actually part of the world */
332         glEnable(GL_DEPTH_TEST);
333         for (cur = level->sorted.next; cur; cur = cur->next, nsorted++)
334                 grits_object_draw(GRITS_OBJECT(cur->data), opengl);
335
336         /* End ortho */
337         if (level->num >= GRITS_LEVEL_HUD) {
338                 glMatrixMode(GL_PROJECTION); glPopMatrix();
339                 glMatrixMode(GL_MODELVIEW);  glPopMatrix();
340         }
341
342         /* Leave depth buffer write enabled */
343         glDepthMask(TRUE);
344
345         /* TODO: Prune empty levels */
346
347         g_debug("GritsOpenGL: _draw_level - drew %d,%d objects",
348                         nunsorted, nsorted);
349 }
350
351 static gboolean on_expose(GritsOpenGL *opengl, GdkEventExpose *event, gpointer _)
352 {
353         g_debug("GritsOpenGL: on_expose - begin");
354
355         if (opengl->pickmode)
356                 return on_motion_notify(opengl, (GdkEventMotion*)event, NULL);
357
358         gtk_gl_begin(GTK_WIDGET(opengl));
359
360         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
361
362         _set_visuals(opengl);
363 #ifdef ROAM_DEBUG
364         glColor4f(1.0, 1.0, 1.0, 1.0);
365         glLineWidth(2);
366         glDisable(GL_TEXTURE_2D);
367         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
368         roam_sphere_draw(opengl->sphere);
369         (void)_draw_level;
370         //roam_sphere_draw_normals(opengl->sphere);
371 #else
372         g_mutex_lock(&opengl->objects_lock);
373         if (opengl->wireframe)
374                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
375         g_queue_foreach(opengl->objects, _draw_level, opengl);
376         g_mutex_unlock(&opengl->objects_lock);
377 #endif
378
379         gtk_gl_end(GTK_WIDGET(opengl));
380
381         g_debug("GritsOpenGL: on_expose - end\n");
382         return FALSE;
383 }
384
385 static gboolean on_key_press(GritsOpenGL *opengl, GdkEventKey *event, gpointer _)
386 {
387         g_debug("GritsOpenGL: on_key_press - key=%x, state=%x, plus=%x",
388                         event->keyval, event->state, GDK_plus);
389
390         guint kv = event->keyval;
391         /* Testing */
392         if (kv == GDK_w) {
393                 opengl->wireframe = !opengl->wireframe;
394                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
395         }
396         if (kv == GDK_p) {
397                 opengl->pickmode = !opengl->pickmode;
398                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
399         }
400 #ifdef ROAM_DEBUG
401         else if (kv == GDK_n) roam_sphere_split_one(opengl->sphere);
402         else if (kv == GDK_p) roam_sphere_merge_one(opengl->sphere);
403         else if (kv == GDK_r) roam_sphere_split_merge(opengl->sphere);
404         else if (kv == GDK_u) roam_sphere_update_errors(opengl->sphere);
405         gtk_widget_queue_draw(GTK_WIDGET(opengl));
406 #endif
407         return FALSE;
408 }
409
410 static gboolean on_chained_event(GritsOpenGL *opengl, GdkEvent *event, gpointer _)
411 {
412         for (GList *i = opengl->objects->tail; i; i = i->prev) {
413                 struct RenderLevel *level = i->data;
414                 for (GList *j = level->unsorted.next; j; j = j->next)
415                         if (grits_object_event(j->data, event))
416                                 return TRUE;
417                 for (GList *j = level->sorted.next;   j; j = j->next)
418                         if (grits_object_event(j->data, event))
419                                 return TRUE;
420         }
421         return FALSE;
422 }
423
424 static gboolean _update_errors_cb(gpointer _opengl)
425 {
426         GritsOpenGL *opengl = _opengl;
427         g_mutex_lock(&opengl->sphere_lock);
428         roam_sphere_update_errors(opengl->sphere);
429         g_mutex_unlock(&opengl->sphere_lock);
430         opengl->ue_source = 0;
431         return FALSE;
432 }
433 static void on_view_changed(GritsOpenGL *opengl,
434                 gdouble _1, gdouble _2, gdouble _3)
435 {
436         g_debug("GritsOpenGL: on_view_changed");
437         _set_visuals(opengl);
438 #ifndef ROAM_DEBUG
439         if (!opengl->ue_source)
440                 opengl->ue_source = g_idle_add_full(G_PRIORITY_HIGH_IDLE+30,
441                                 _update_errors_cb, opengl, NULL);
442         //roam_sphere_update_errors(opengl->sphere);
443 #else
444         (void)_update_errors_cb;
445 #endif
446 }
447
448 static gboolean on_idle(GritsOpenGL *opengl)
449 {
450         //g_debug("GritsOpenGL: on_idle");
451         g_mutex_lock(&opengl->sphere_lock);
452         if (roam_sphere_split_merge(opengl->sphere))
453                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
454         g_mutex_unlock(&opengl->sphere_lock);
455         return TRUE;
456 }
457
458 static void on_realize(GritsOpenGL *opengl, gpointer _)
459 {
460         g_debug("GritsOpenGL: on_realize");
461         gtk_gl_begin(GTK_WIDGET(opengl));
462
463         /* Connect signals and idle functions now that opengl is fully initialized */
464         gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
465         g_signal_connect(opengl, "configure-event",  G_CALLBACK(on_configure),    NULL);
466         g_signal_connect(opengl, "expose-event",     G_CALLBACK(on_expose),       NULL);
467
468         g_signal_connect(opengl, "key-press-event",  G_CALLBACK(on_key_press),    NULL);
469
470         g_signal_connect(opengl, "location-changed", G_CALLBACK(on_view_changed), NULL);
471         g_signal_connect(opengl, "rotation-changed", G_CALLBACK(on_view_changed), NULL);
472
473         g_signal_connect(opengl, "motion-notify-event", G_CALLBACK(on_motion_notify), NULL);
474         g_signal_connect_after(opengl, "key-press-event",      G_CALLBACK(on_chained_event), NULL);
475         g_signal_connect_after(opengl, "key-release-event",    G_CALLBACK(on_chained_event), NULL);
476         g_signal_connect_after(opengl, "button-press-event",   G_CALLBACK(on_chained_event), NULL);
477         g_signal_connect_after(opengl, "button-release-event", G_CALLBACK(on_chained_event), NULL);
478         g_signal_connect_after(opengl, "motion-notify-event",  G_CALLBACK(on_chained_event), NULL);
479
480 #ifndef ROAM_DEBUG
481         opengl->sm_source[0] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+30, 33,  (GSourceFunc)on_idle, opengl, NULL);
482         opengl->sm_source[1] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+10, 500, (GSourceFunc)on_idle, opengl, NULL);
483 #else
484         (void)on_idle;
485         (void)_update_errors_cb;
486 #endif
487
488         /* Re-queue resize incase configure was triggered before realize */
489         gtk_widget_queue_resize(GTK_WIDGET(opengl));
490 }
491
492 /*********************
493  * GritsViewer methods *
494  *********************/
495 /**
496  * grits_opengl_new:
497  * @plugins: the plugins store to use
498  * @prefs:   the preferences object to use
499  *
500  * Create a new OpenGL renderer.
501  *
502  * Returns: the new #GritsOpenGL
503  */
504 GritsViewer *grits_opengl_new(GritsPlugins *plugins, GritsPrefs *prefs)
505 {
506         g_debug("GritsOpenGL: new");
507         GritsViewer *opengl = g_object_new(GRITS_TYPE_OPENGL, NULL);
508         grits_viewer_setup(opengl, plugins, prefs);
509         return opengl;
510 }
511
512 static void grits_opengl_center_position(GritsViewer *_opengl, gdouble lat, gdouble lon, gdouble elev)
513 {
514         glRotatef(lon, 0, 1, 0);
515         glRotatef(-lat, 1, 0, 0);
516         glTranslatef(0, 0, elev2rad(elev));
517 }
518
519 static void grits_opengl_project(GritsViewer *_opengl,
520                 gdouble lat, gdouble lon, gdouble elev,
521                 gdouble *px, gdouble *py, gdouble *pz)
522 {
523         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
524         gdouble x, y, z;
525         lle2xyz(lat, lon, elev, &x, &y, &z);
526         gluProject(x, y, z,
527                 opengl->sphere->view->model,
528                 opengl->sphere->view->proj,
529                 opengl->sphere->view->view,
530                 px, py, pz);
531 }
532
533 static void grits_opengl_unproject(GritsViewer *_opengl,
534                 gdouble px, gdouble py, gdouble pz,
535                 gdouble *lat, gdouble *lon, gdouble *elev)
536 {
537         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
538         if (!opengl->sphere->view)
539                 return;
540         gdouble x, y, z;
541         if (pz < 0) {
542                 gfloat tmp = 0;
543                 glReadPixels(px, py, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &tmp);
544                 pz = tmp;
545         }
546         gluUnProject(px, py, pz,
547                 opengl->sphere->view->model,
548                 opengl->sphere->view->proj,
549                 opengl->sphere->view->view,
550                 &x, &y, &z);
551         xyz2lle(x, y, z, lat, lon, elev);
552         //g_message("GritsOpenGL: unproject - "
553         //              "%4.0lf,%4.0lf,(%5.3lf) -> "
554         //              "%8.0lf,%8.0lf,%8.0lf -> "
555         //              "%6.2lf,%7.2lf,%4.0lf",
556         //      px, py, pz, x, y, z, *lat, *lon, *elev);
557 }
558
559 static void grits_opengl_set_height_func(GritsViewer *_opengl, GritsBounds *bounds,
560                 RoamHeightFunc height_func, gpointer user_data, gboolean update)
561 {
562         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
563         /* TODO: get points? */
564         g_mutex_lock(&opengl->sphere_lock);
565         GList *triangles = roam_sphere_get_intersect(opengl->sphere, TRUE,
566                         bounds->n, bounds->s, bounds->e, bounds->w);
567         for (GList *cur = triangles; cur; cur = cur->next) {
568                 RoamTriangle *tri = cur->data;
569                 RoamPoint *points[] = {tri->p.l, tri->p.m, tri->p.r, tri->split};
570                 for (int i = 0; i < G_N_ELEMENTS(points); i++) {
571                         if (bounds->n >= points[i]->lat && points[i]->lat >= bounds->s &&
572                             bounds->e >= points[i]->lon && points[i]->lon >= bounds->w) {
573                                 points[i]->height_func = height_func;
574                                 points[i]->height_data = user_data;
575                                 roam_point_update_height(points[i]);
576                         }
577                 }
578         }
579         g_list_free(triangles);
580         g_mutex_unlock(&opengl->sphere_lock);
581 }
582
583 static void _grits_opengl_clear_height_func_rec(RoamTriangle *root)
584 {
585         if (!root)
586                 return;
587         RoamPoint *points[] = {root->p.l, root->p.m, root->p.r, root->split};
588         for (int i = 0; i < G_N_ELEMENTS(points); i++) {
589                 points[i]->height_func = NULL;
590                 points[i]->height_data = NULL;
591                 roam_point_update_height(points[i]);
592         }
593         _grits_opengl_clear_height_func_rec(root->kids[0]);
594         _grits_opengl_clear_height_func_rec(root->kids[1]);
595 }
596
597 static void grits_opengl_clear_height_func(GritsViewer *_opengl)
598 {
599         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
600         for (int i = 0; i < G_N_ELEMENTS(opengl->sphere->roots); i++)
601                 _grits_opengl_clear_height_func_rec(opengl->sphere->roots[i]);
602 }
603
604 static gint _objects_find(gconstpointer a, gconstpointer b)
605 {
606         const struct RenderLevel *level = a;
607         const gint *key = b;
608         return level->num == *key ? 0 : 1;
609 }
610
611 static gint _objects_sort(gconstpointer _a, gconstpointer _b, gpointer _)
612 {
613         const struct RenderLevel *a = _a;
614         const struct RenderLevel *b = _b;
615         return a->num < b->num ? -1 :
616                a->num > b->num ?  1 : 0;
617 }
618
619 static void _objects_free(gpointer value, gpointer _)
620 {
621         struct RenderLevel *level = value;
622         if (level->sorted.next)
623                 g_list_free(level->sorted.next);
624         if (level->unsorted.next)
625                 g_list_free(level->unsorted.next);
626         g_free(level);
627 }
628
629 static gpointer grits_opengl_add(GritsViewer *_opengl, GritsObject *object,
630                 gint num, gboolean sort)
631 {
632         g_assert(GRITS_IS_OPENGL(_opengl));
633         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
634         g_mutex_lock(&opengl->objects_lock);
635         struct RenderLevel *level = NULL;
636         GList *tmp = g_queue_find_custom(opengl->objects, &num, _objects_find);
637         if (tmp) {
638                 level = tmp->data;
639         } else {
640                 level = g_new0(struct RenderLevel, 1);
641                 level->num = num;
642                 g_queue_insert_sorted(opengl->objects, level, _objects_sort, NULL);
643         }
644         GList *list = sort ? &level->sorted : &level->unsorted;
645         /* Put the link in the list */
646         GList *link = g_new0(GList, 1);
647         link->data = object;
648         link->prev = list;
649         link->next = list->next;
650         if (list->next)
651                 list->next->prev = link;
652         list->next = link;
653         g_mutex_unlock(&opengl->objects_lock);
654         return link;
655 }
656
657 static GritsObject *grits_opengl_remove(GritsViewer *_opengl, GritsObject *object)
658 {
659         g_assert(GRITS_IS_OPENGL(_opengl));
660         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
661         GList *link = object->ref;
662         g_mutex_lock(&opengl->objects_lock);
663         /* Just unlink and free it, link->prev is assured */
664         link->prev->next = link->next;
665         if (link->next)
666                 link->next->prev = link->prev;
667         g_mutex_unlock(&opengl->objects_lock);
668         object->ref    = NULL;
669         object->viewer = NULL;
670         g_free(link);
671         g_object_unref(object);
672         return object;
673 }
674
675 /****************
676  * GObject code *
677  ****************/
678 G_DEFINE_TYPE(GritsOpenGL, grits_opengl, GRITS_TYPE_VIEWER);
679 static void grits_opengl_init(GritsOpenGL *opengl)
680 {
681         g_debug("GritsOpenGL: init");
682         opengl->objects = g_queue_new();
683         opengl->sphere  = roam_sphere_new(opengl);
684         g_mutex_init(&opengl->objects_lock);
685         g_mutex_init(&opengl->sphere_lock);
686         gtk_gl_enable(GTK_WIDGET(opengl));
687         gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
688         g_signal_connect(opengl, "map", G_CALLBACK(on_realize), NULL);
689 }
690 static void grits_opengl_dispose(GObject *_opengl)
691 {
692         g_debug("GritsOpenGL: dispose");
693         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
694         if (opengl->sm_source[0]) {
695                 g_source_remove(opengl->sm_source[0]);
696                 opengl->sm_source[0] = 0;
697         }
698         if (opengl->sm_source[1]) {
699                 g_source_remove(opengl->sm_source[1]);
700                 opengl->sm_source[1] = 0;
701         }
702         if (opengl->ue_source) {
703                 g_source_remove(opengl->ue_source);
704                 opengl->ue_source = 0;
705         }
706         G_OBJECT_CLASS(grits_opengl_parent_class)->dispose(_opengl);
707 }
708 static void grits_opengl_finalize(GObject *_opengl)
709 {
710         g_debug("GritsOpenGL: finalize");
711         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
712         roam_sphere_free(opengl->sphere);
713         g_queue_foreach(opengl->objects, _objects_free, NULL);
714         g_queue_free(opengl->objects);
715         g_mutex_clear(&opengl->objects_lock);
716         g_mutex_clear(&opengl->sphere_lock);
717         G_OBJECT_CLASS(grits_opengl_parent_class)->finalize(_opengl);
718 }
719 static void grits_opengl_class_init(GritsOpenGLClass *klass)
720 {
721         g_debug("GritsOpenGL: class_init");
722         GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
723         gobject_class->finalize = grits_opengl_finalize;
724         gobject_class->dispose = grits_opengl_dispose;
725
726         GritsViewerClass *viewer_class = GRITS_VIEWER_CLASS(klass);
727         viewer_class->center_position   = grits_opengl_center_position;
728         viewer_class->project           = grits_opengl_project;
729         viewer_class->unproject         = grits_opengl_unproject;
730         viewer_class->clear_height_func = grits_opengl_clear_height_func;
731         viewer_class->set_height_func   = grits_opengl_set_height_func;
732         viewer_class->add               = grits_opengl_add;
733         viewer_class->remove            = grits_opengl_remove;
734 }