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