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