]> Pileus Git - grits/blob - src/grits-opengl.c
Change GdkEventExpose to gpointer
[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 #define OVERLAY_SLICE 0.01
44
45 /* Tessellation, "finding intersecting triangles" */
46 /* http://research.microsoft.com/pubs/70307/tr-2006-81.pdf */
47 /* http://www.opengl.org/wiki/Alpha_Blending */
48
49 /* The unsorted/sroted GLists are blank head nodes,
50  * This way us we can remove objects from the level just by fixing up links
51  * I.e. we don't need to do a lookup to remove an object if we have its GList */
52 struct RenderLevel {
53         gint  num;
54         GList unsorted;
55         GList sorted;
56 };
57
58 /***********
59  * Helpers *
60  ***********/
61 static void _set_projection(GritsOpenGL *opengl)
62 {
63         double lat, lon, elev, rx, ry, rz;
64         grits_viewer_get_location(GRITS_VIEWER(opengl), &lat, &lon, &elev);
65         grits_viewer_get_rotation(GRITS_VIEWER(opengl), &rx, &ry, &rz);
66
67         /* Set projection and clipping planes */
68         glMatrixMode(GL_PROJECTION);
69         glLoadIdentity();
70
71         double width  = GTK_WIDGET(opengl)->allocation.width;
72         double height = GTK_WIDGET(opengl)->allocation.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         gdouble height = GTK_WIDGET(opengl)->allocation.height;
223         gdouble gl_x   = event->x;
224         gdouble gl_y   = height - event->y;
225         gdouble delta  = opengl->pickmode ? 200 : 2;
226
227         if (opengl->pickmode) {
228                 gtk_gl_begin(GTK_WIDGET(opengl));
229                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
230         }
231
232         /* Save matricies */
233         gdouble projection[16];
234         gint    viewport[4]; // x=0,y=0,w,h
235         glGetDoublev(GL_PROJECTION_MATRIX, projection);
236         glGetIntegerv(GL_VIEWPORT, viewport);
237         glMatrixMode(GL_MODELVIEW);  glPushMatrix();
238         glMatrixMode(GL_PROJECTION); glPushMatrix();
239
240         g_mutex_lock(&opengl->objects_lock);
241
242         GritsObject *top = NULL;
243         GPtrArray *ortho = _objects_to_array(opengl, TRUE);
244         GPtrArray *world = _objects_to_array(opengl, FALSE);
245
246         /* Run perspective picking */
247         glMatrixMode(GL_PROJECTION); glLoadIdentity();
248         gluPickMatrix(gl_x, gl_y, delta, delta, viewport);
249         glMultMatrixd(projection);
250         gint world_hits = run_picking(opengl, (GdkEvent*)event, world, &top);
251
252         /* Run ortho picking */
253         glMatrixMode(GL_PROJECTION); glLoadIdentity();
254         gluPickMatrix(gl_x, gl_y, delta, delta, viewport);
255         glMatrixMode(GL_MODELVIEW);  glLoadIdentity();
256         glOrtho(0, viewport[2], viewport[3], 0, 1000, -1000);
257         gint ortho_hits = run_picking(opengl, (GdkEvent*)event, ortho, &top);
258
259         /* Update cursor */
260         static GdkCursor *cursor = NULL;
261         static GdkWindow *window = NULL;
262         if (!window || !cursor) {
263                 cursor = gdk_cursor_new(GDK_FLEUR);
264                 window = gtk_widget_get_window(GTK_WIDGET(opengl));
265         }
266         GdkCursor *topcursor = top && top->cursor ? top->cursor : cursor;
267         gdk_window_set_cursor(window, topcursor);
268
269         g_debug("GritsOpenGL: run_mouse_move - hits=%d/%d,%d/%d ev=%.0lf,%.0lf",
270                         world_hits, world->len, ortho_hits, ortho->len, gl_x, gl_y);
271
272         g_ptr_array_free(world, TRUE);
273         g_ptr_array_free(ortho, TRUE);
274
275         g_mutex_unlock(&opengl->objects_lock);
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 gboolean on_motion_notify(GritsOpenGL *opengl, GdkEventMotion *event, gpointer _)
293 {
294         opengl->mouse_queue = *event;
295         grits_viewer_queue_draw(GRITS_VIEWER(opengl));
296         return FALSE;
297 }
298
299 static void _draw_level(gpointer _level, gpointer _opengl)
300 {
301         GritsOpenGL *opengl = _opengl;
302         struct RenderLevel *level = _level;
303
304         g_debug("GritsOpenGL: _draw_level - level=%-4d", level->num);
305         int nsorted = 0, nunsorted = 0;
306         GList *cur = NULL;
307
308         /* Configure individual levels */
309         if (level->num < GRITS_LEVEL_WORLD) {
310                 /* Disable depth for background levels */
311                 glDepthMask(FALSE);
312                 glDisable(GL_ALPHA_TEST);
313         } else if (level->num < GRITS_LEVEL_OVERLAY) {
314                 /* Enable depth and alpha for world levels */
315                 glEnable(GL_ALPHA_TEST);
316                 glAlphaFunc(GL_GREATER, 0.1);
317                 glDepthRange(OVERLAY_SLICE, 1);
318         } else {
319                 /* Draw overlay in front of world */
320                 glDepthRange(0, OVERLAY_SLICE);
321         }
322
323         /* Start ortho */
324         if (level->num >= GRITS_LEVEL_HUD) {
325                 glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity();
326                 glMatrixMode(GL_MODELVIEW);  glPushMatrix(); glLoadIdentity();
327                 gint win_width  = GTK_WIDGET(opengl)->allocation.width;
328                 gint win_height = GTK_WIDGET(opengl)->allocation.height;
329                 glOrtho(0, win_width, win_height, 0, 1000, -1000);
330         }
331
332         /* Draw unsorted objects without depth testing,
333          * these are polygons, etc, rather than physical objects */
334         glDisable(GL_DEPTH_TEST);
335         for (cur = level->unsorted.next; cur; cur = cur->next, nunsorted++)
336                 grits_object_draw(GRITS_OBJECT(cur->data), opengl);
337
338         /* Draw sorted objects using depth testing
339          * These are things that are actually part of the world */
340         glEnable(GL_DEPTH_TEST);
341         for (cur = level->sorted.next; cur; cur = cur->next, nsorted++)
342                 grits_object_draw(GRITS_OBJECT(cur->data), opengl);
343
344         /* End ortho */
345         if (level->num >= GRITS_LEVEL_HUD) {
346                 glMatrixMode(GL_PROJECTION); glPopMatrix();
347                 glMatrixMode(GL_MODELVIEW);  glPopMatrix();
348         }
349
350         /* Leave depth buffer write enabled */
351         glDepthMask(TRUE);
352
353         /* TODO: Prune empty levels */
354
355         g_debug("GritsOpenGL: _draw_level - drew %d,%d objects",
356                         nunsorted, nsorted);
357 }
358
359 static gboolean on_expose(GritsOpenGL *opengl, gpointer data, gpointer _)
360 {
361         g_debug("GritsOpenGL: on_expose - begin");
362
363         if (opengl->pickmode)
364                 return run_mouse_move(opengl, &(GdkEventMotion){});
365
366         if (opengl->mouse_queue.type != GDK_NOTHING) {
367                 run_mouse_move(opengl, &opengl->mouse_queue);
368                 opengl->mouse_queue.type = GDK_NOTHING;
369         }
370
371         gtk_gl_begin(GTK_WIDGET(opengl));
372
373         _set_settings(opengl);
374         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
375
376 #ifndef ROAM_DEBUG
377         g_mutex_lock(&opengl->sphere_lock);
378         roam_sphere_update_errors(opengl->sphere);
379         roam_sphere_split_merge(opengl->sphere);
380         g_mutex_unlock(&opengl->sphere_lock);
381 #endif
382
383 #ifdef ROAM_DEBUG
384         roam_sphere_draw(opengl->sphere);
385         roam_sphere_draw_normals(opengl->sphere);
386         (void)_draw_level;
387 #else
388         g_mutex_lock(&opengl->objects_lock);
389         g_queue_foreach(opengl->objects, _draw_level, opengl);
390         g_mutex_unlock(&opengl->objects_lock);
391 #endif
392
393         gtk_gl_end(GTK_WIDGET(opengl));
394
395         g_debug("GritsOpenGL: on_expose - end\n");
396         return FALSE;
397 }
398
399 static gboolean on_key_press(GritsOpenGL *opengl, GdkEventKey *event, gpointer _)
400 {
401         g_debug("GritsOpenGL: on_key_press - key=%x, state=%x, plus=%x",
402                         event->keyval, event->state, GDK_KEY_plus);
403
404         guint kv = event->keyval;
405         /* Testing */
406         if (kv == GDK_KEY_w) {
407                 opengl->wireframe = !opengl->wireframe;
408                 grits_viewer_queue_draw(GRITS_VIEWER(opengl));
409         }
410         if (kv == GDK_KEY_p) {
411                 opengl->pickmode = !opengl->pickmode;
412                 grits_viewer_queue_draw(GRITS_VIEWER(opengl));
413         }
414 #ifdef ROAM_DEBUG
415         else if (kv == GDK_KEY_n) roam_sphere_split_one(opengl->sphere);
416         else if (kv == GDK_KEY_p) roam_sphere_merge_one(opengl->sphere);
417         else if (kv == GDK_KEY_r) roam_sphere_split_merge(opengl->sphere);
418         else if (kv == GDK_KEY_u) roam_sphere_update_errors(opengl->sphere);
419         grits_viewer_queue_draw(GRITS_VIEWER(opengl));
420 #endif
421         return FALSE;
422 }
423
424 static gboolean on_chained_event(GritsOpenGL *opengl, GdkEvent *event, gpointer _)
425 {
426         for (GList *i = opengl->objects->tail; i; i = i->prev) {
427                 struct RenderLevel *level = i->data;
428                 for (GList *j = level->unsorted.next; j; j = j->next)
429                         if (grits_object_event(j->data, event))
430                                 return TRUE;
431                 for (GList *j = level->sorted.next;   j; j = j->next)
432                         if (grits_object_event(j->data, event))
433                                 return TRUE;
434         }
435         return FALSE;
436 }
437
438 static void on_realize(GritsOpenGL *opengl, gpointer _)
439 {
440         g_debug("GritsOpenGL: on_realize");
441         gtk_gl_begin(GTK_WIDGET(opengl));
442
443         /* Connect signals and idle functions now that opengl is fully initialized */
444         gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
445         g_signal_connect(opengl, "configure-event",  G_CALLBACK(_set_projection), NULL);
446         g_signal_connect(opengl, "expose-event",     G_CALLBACK(on_expose),       NULL);
447
448         g_signal_connect(opengl, "key-press-event",  G_CALLBACK(on_key_press),    NULL);
449
450         g_signal_connect(opengl, "location-changed", G_CALLBACK(_set_projection), NULL);
451         g_signal_connect(opengl, "rotation-changed", G_CALLBACK(_set_projection), NULL);
452
453         g_signal_connect(opengl, "motion-notify-event", G_CALLBACK(on_motion_notify), NULL);
454         g_signal_connect_after(opengl, "key-press-event",      G_CALLBACK(on_chained_event), NULL);
455         g_signal_connect_after(opengl, "key-release-event",    G_CALLBACK(on_chained_event), NULL);
456         g_signal_connect_after(opengl, "button-press-event",   G_CALLBACK(on_chained_event), NULL);
457         g_signal_connect_after(opengl, "button-release-event", G_CALLBACK(on_chained_event), NULL);
458         g_signal_connect_after(opengl, "motion-notify-event",  G_CALLBACK(on_chained_event), NULL);
459
460         /* Re-queue resize incase configure was triggered before realize */
461         gtk_widget_queue_resize(GTK_WIDGET(opengl));
462 }
463
464 /*********************
465  * GritsViewer methods *
466  *********************/
467 /**
468  * grits_opengl_new:
469  * @plugins: the plugins store to use
470  * @prefs:   the preferences object to use
471  *
472  * Create a new OpenGL renderer.
473  *
474  * Returns: the new #GritsOpenGL
475  */
476 GritsViewer *grits_opengl_new(GritsPlugins *plugins, GritsPrefs *prefs)
477 {
478         g_debug("GritsOpenGL: new");
479         GritsViewer *opengl = g_object_new(GRITS_TYPE_OPENGL, NULL);
480         grits_viewer_setup(opengl, plugins, prefs);
481         return opengl;
482 }
483
484 static void grits_opengl_center_position(GritsViewer *_opengl, gdouble lat, gdouble lon, gdouble elev)
485 {
486         glRotatef(lon, 0, 1, 0);
487         glRotatef(-lat, 1, 0, 0);
488         glTranslatef(0, 0, elev2rad(elev));
489 }
490
491 static void grits_opengl_project(GritsViewer *_opengl,
492                 gdouble lat, gdouble lon, gdouble elev,
493                 gdouble *px, gdouble *py, gdouble *pz)
494 {
495         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
496         gdouble x, y, z;
497         lle2xyz(lat, lon, elev, &x, &y, &z);
498         gluProject(x, y, z,
499                 opengl->sphere->view->model,
500                 opengl->sphere->view->proj,
501                 opengl->sphere->view->view,
502                 px, py, pz);
503 }
504
505 static void grits_opengl_unproject(GritsViewer *_opengl,
506                 gdouble px, gdouble py, gdouble pz,
507                 gdouble *lat, gdouble *lon, gdouble *elev)
508 {
509         GritsOpenGL *opengl = GRITS_OPENGL(_opengl);
510         if (!opengl->sphere->view)
511                 return;
512         gdouble x, y, z;
513         if (pz < 0) {
514                 gfloat tmp = 0;
515                 glReadPixels(px, py, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &tmp);
516                 pz = tmp;
517         }
518         pz = (pz-OVERLAY_SLICE) * (1.0/(1-OVERLAY_SLICE));
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 }