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