]> Pileus Git - grits/blob - src/gis-opengl.c
Call on_configure from on_realize
[grits] / src / gis-opengl.c
1 /*
2  * Copyright (C) 2009-2010 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:gis-opengl
20  * @short_description: OpenGL based virtual globe
21  *
22  * #GisOpenGL is the core rendering engine used by libgis. Theoretically other
23  * renderers could be writte, but they have not been. GisOpenGL uses the ROAM
24  * algorithm for updating surface mesh the planet. The only thing GisOpenGL can
25  * actually render on it's own is a wireframe of a sphere.
26  *
27  * GisOpenGL relies on #GtkGlExt and 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 #include <gtk/gtkgl.h>
36 #include <GL/gl.h>
37 #include <GL/glu.h>
38
39 #include "gis-opengl.h"
40 #include "gis-util.h"
41 #include "roam.h"
42
43 #include "objects/gis-object.h"
44 #include "objects/gis-marker.h"
45 #include "objects/gis-callback.h"
46
47 // #define ROAM_DEBUG
48
49 /* Tessellation, "finding intersecting triangles" */
50 /* http://research.microsoft.com/pubs/70307/tr-2006-81.pdf */
51 /* http://www.opengl.org/wiki/Alpha_Blending */
52
53 /***********
54  * Helpers *
55  ***********/
56 static void _set_visuals(GisOpenGL *opengl)
57 {
58         glMatrixMode(GL_MODELVIEW);
59         glLoadIdentity();
60
61         /* Camera 1 */
62         double lat, lon, elev, rx, ry, rz;
63         gis_viewer_get_location(GIS_VIEWER(opengl), &lat, &lon, &elev);
64         gis_viewer_get_rotation(GIS_VIEWER(opengl), &rx, &ry, &rz);
65         glRotatef(rx, 1, 0, 0);
66         glRotatef(rz, 0, 0, 1);
67
68         /* Lighting */
69 #ifdef ROAM_DEBUG
70         float light_ambient[]  = {0.7f, 0.7f, 0.7f, 1.0f};
71         float light_diffuse[]  = {2.0f, 2.0f, 2.0f, 1.0f};
72 #else
73         float light_ambient[]  = {0.2f, 0.2f, 0.2f, 1.0f};
74         float light_diffuse[]  = {5.0f, 5.0f, 5.0f, 1.0f};
75 #endif
76         float light_position[] = {-13*EARTH_R, 1*EARTH_R, 3*EARTH_R, 1.0f};
77         glLightfv(GL_LIGHT0, GL_AMBIENT,  light_ambient);
78         glLightfv(GL_LIGHT0, GL_DIFFUSE,  light_diffuse);
79         glLightfv(GL_LIGHT0, GL_POSITION, light_position);
80         glEnable(GL_LIGHT0);
81         glEnable(GL_LIGHTING);
82
83         float material_ambient[]  = {0.2, 0.2, 0.2, 1.0};
84         float material_diffuse[]  = {0.8, 0.8, 0.8, 1.0};
85         float material_specular[] = {0.1, 0.1, 0.1, 1.0};
86         float material_emission[] = {0.0, 0.0, 0.0, 1.0};
87         glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT,  material_ambient);
88         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE,  material_diffuse);
89         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material_specular);
90         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, material_emission);
91         glDisable(GL_TEXTURE_2D);
92         glDisable(GL_COLOR_MATERIAL);
93
94         /* Camera 2 */
95         glTranslatef(0, 0, -elev2rad(elev));
96         glRotatef(lat, 1, 0, 0);
97         glRotatef(-lon, 0, 1, 0);
98
99         glDisable(GL_ALPHA_TEST);
100
101         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
102         glEnable(GL_BLEND);
103
104 #ifndef ROAM_DEBUG
105         glCullFace(GL_BACK);
106         glEnable(GL_CULL_FACE);
107 #endif
108
109         glClearDepth(1.0);
110         glDepthFunc(GL_LEQUAL);
111         glEnable(GL_DEPTH_TEST);
112
113         glEnable(GL_LINE_SMOOTH);
114
115         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
116         //glShadeModel(GL_FLAT);
117
118         roam_sphere_update_view(opengl->sphere);
119 }
120
121
122 /********************
123  * Object handleing *
124  ********************/
125 static void _draw_tile(GisOpenGL *opengl, GisTile *tile, GList *triangles)
126 {
127         if (!tile || !tile->data)
128                 return;
129         if (!triangles)
130                 g_warning("GisOpenGL: _draw_tiles - No triangles to draw: edges=%f,%f,%f,%f",
131                         tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
132         //g_message("drawing %4d triangles for tile edges=%7.2f,%7.2f,%7.2f,%7.2f",
133         //              g_list_length(triangles), tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
134         for (GList *cur = triangles; cur; cur = cur->next) {
135                 RoamTriangle *tri = cur->data;
136
137                 gdouble lat[3] = {tri->p.r->lat, tri->p.m->lat, tri->p.l->lat};
138                 gdouble lon[3] = {tri->p.r->lon, tri->p.m->lon, tri->p.l->lon};
139
140                 if (lon[0] < -90 || lon[1] < -90 || lon[2] < -90) {
141                         if (lon[0] > 90) lon[0] -= 360;
142                         if (lon[1] > 90) lon[1] -= 360;
143                         if (lon[2] > 90) lon[2] -= 360;
144                 }
145
146                 gdouble n = tile->edge.n;
147                 gdouble s = tile->edge.s;
148                 gdouble e = tile->edge.e;
149                 gdouble w = tile->edge.w;
150
151                 gdouble londist = e - w;
152                 gdouble latdist = n - s;
153
154                 gdouble xy[3][2] = {
155                         {(lon[0]-w)/londist, 1-(lat[0]-s)/latdist},
156                         {(lon[1]-w)/londist, 1-(lat[1]-s)/latdist},
157                         {(lon[2]-w)/londist, 1-(lat[2]-s)/latdist},
158                 };
159
160                 //if ((lat[0] == 90 && (xy[0][0] < 0 || xy[0][0] > 1)) ||
161                 //    (lat[1] == 90 && (xy[1][0] < 0 || xy[1][0] > 1)) ||
162                 //    (lat[2] == 90 && (xy[2][0] < 0 || xy[2][0] > 1)))
163                 //      g_message("w,e=%4.f,%4.f   "
164                 //                "lat,lon,x,y="
165                 //                "%4.1f,%4.0f,%4.2f,%4.2f   "
166                 //                "%4.1f,%4.0f,%4.2f,%4.2f   "
167                 //                "%4.1f,%4.0f,%4.2f,%4.2f   ",
168                 //              w,e,
169                 //              lat[0], lon[0], xy[0][0], xy[0][1],
170                 //              lat[1], lon[1], xy[1][0], xy[1][1],
171                 //              lat[2], lon[2], xy[2][0], xy[2][1]);
172
173                 /* Fix poles */
174                 if (lat[0] == 90 || lat[0] == -90) xy[0][0] = 0.5;
175                 if (lat[1] == 90 || lat[1] == -90) xy[1][0] = 0.5;
176                 if (lat[2] == 90 || lat[2] == -90) xy[2][0] = 0.5;
177
178                 glEnable(GL_TEXTURE_2D);
179                 glBindTexture(GL_TEXTURE_2D, *(guint*)tile->data);
180                 glBegin(GL_TRIANGLES);
181                 glNormal3dv(tri->p.r->norm); glTexCoord2dv(xy[0]); glVertex3dv((double*)tri->p.r);
182                 glNormal3dv(tri->p.m->norm); glTexCoord2dv(xy[1]); glVertex3dv((double*)tri->p.m);
183                 glNormal3dv(tri->p.l->norm); glTexCoord2dv(xy[2]); glVertex3dv((double*)tri->p.l);
184                 glEnd();
185         }
186         g_list_free(triangles);
187 }
188
189 static void _draw_tiles(GisOpenGL *opengl, GisTile *tile)
190 {
191         /* Only draw children if possible */
192         gboolean has_children = FALSE;
193         GisTile *child;
194         gis_tile_foreach(tile, child)
195                 if (child && child->data)
196                         has_children = TRUE;
197
198         GList *triangles = NULL;
199         if (has_children) {
200                 /* TODO: simplify this */
201                 const gdouble rows = G_N_ELEMENTS(tile->children);
202                 const gdouble cols = G_N_ELEMENTS(tile->children[0]);
203                 const gdouble lat_dist = tile->edge.n - tile->edge.s;
204                 const gdouble lon_dist = tile->edge.e - tile->edge.w;
205                 const gdouble lat_step = lat_dist / rows;
206                 const gdouble lon_step = lon_dist / cols;
207                 int row, col;
208                 gis_tile_foreach_index(tile, row, col) {
209                         GisTile *child = tile->children[row][col];
210                         if (child && child->data) {
211                                 _draw_tiles(opengl, child);
212                         } else {
213                                 const gdouble n = tile->edge.n-(lat_step*(row+0));
214                                 const gdouble s = tile->edge.n-(lat_step*(row+1));
215                                 const gdouble e = tile->edge.w+(lon_step*(col+1));
216                                 const gdouble w = tile->edge.w+(lon_step*(col+0));
217                                 GList *these = roam_sphere_get_intersect(opengl->sphere, FALSE, n, s, e, w);
218                                 triangles = g_list_concat(triangles, these);
219                         }
220                 }
221         } else {
222                 triangles = roam_sphere_get_intersect(opengl->sphere, FALSE,
223                                 tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
224         }
225         if (triangles)
226                 _draw_tile(opengl, tile, triangles);
227 }
228
229 static void _draw_marker(GisOpenGL *opengl, GisMarker *marker)
230 {
231         GisPoint *point = gis_object_center(marker);
232         gdouble px, py, pz;
233         gis_viewer_project(GIS_VIEWER(opengl),
234                         point->lat, point->lon, point->elev,
235                         &px, &py, &pz);
236         if (pz > 1)
237                 return;
238
239         //g_debug("GisOpenGL: draw_marker - %s pz=%f ", marker->label, pz);
240
241         cairo_surface_t *surface = cairo_get_target(marker->cairo);
242         gdouble width  = cairo_image_surface_get_width(surface);
243         gdouble height = cairo_image_surface_get_height(surface);
244
245         glMatrixMode(GL_PROJECTION); glLoadIdentity();
246         glMatrixMode(GL_MODELVIEW);  glLoadIdentity();
247         glOrtho(0, GTK_WIDGET(opengl)->allocation.width,
248                 0, GTK_WIDGET(opengl)->allocation.height, -1, 1);
249         glTranslated(px - marker->xoff,
250                      py - marker->yoff, 0);
251
252         glDisable(GL_LIGHTING);
253         glDisable(GL_COLOR_MATERIAL);
254         glDisable(GL_DEPTH_TEST);
255         glEnable(GL_TEXTURE_2D);
256         glBindTexture(GL_TEXTURE_2D, marker->tex);
257         glBegin(GL_QUADS);
258         glTexCoord2f(1, 1); glVertex3f(width, 0     , 0);
259         glTexCoord2f(1, 0); glVertex3f(width, height, 0);
260         glTexCoord2f(0, 0); glVertex3f(0    , height, 0);
261         glTexCoord2f(0, 1); glVertex3f(0    , 0     , 0);
262         glEnd();
263 }
264
265 static void _draw_callback(GisOpenGL *opengl, GisCallback *callback)
266 {
267         callback->callback(callback, callback->user_data);
268 }
269
270 static void _draw_object(GisOpenGL *opengl, GisObject *object)
271 {
272         //g_debug("GisOpenGL: draw_object");
273         /* Skip out of range objects */
274         if (object->lod > 0) {
275                 gdouble eye[3], obj[3];
276                 gis_viewer_get_location(GIS_VIEWER(opengl), &eye[0], &eye[1], &eye[2]);
277                 lle2xyz(eye[0], eye[1], eye[2], &eye[0], &eye[1], &eye[2]);
278                 lle2xyz(object->center.lat, object->center.lon, object->center.elev,
279                         &obj[0], &obj[1], &obj[2]);
280                 gdouble dist = distd(obj, eye);
281                 if (object->lod < dist)
282                         return;
283         }
284
285         /* Draw */
286         glMatrixMode(GL_PROJECTION); glPushMatrix();
287         glMatrixMode(GL_MODELVIEW);  glPushMatrix();
288         glPushAttrib(GL_ALL_ATTRIB_BITS);
289         if (GIS_IS_MARKER(object)) {
290                 _draw_marker(opengl, GIS_MARKER(object));
291         } else if (GIS_IS_CALLBACK(object)) {
292                 _draw_callback(opengl, GIS_CALLBACK(object));
293         } else if (GIS_IS_TILE(object)) {
294                 glEnable(GL_DEPTH_TEST);
295                 glDepthFunc(GL_LESS);
296                 _draw_tiles(opengl, GIS_TILE(object));
297         }
298         glPopAttrib();
299         glMatrixMode(GL_PROJECTION); glPopMatrix();
300         glMatrixMode(GL_MODELVIEW);  glPopMatrix();
301 }
302
303 static void _load_object(GisOpenGL *opengl, GisObject *object)
304 {
305         g_debug("GisOpenGL: load_object");
306         if (GIS_IS_MARKER(object)) {
307                 GisMarker *marker = GIS_MARKER(object);
308                 cairo_surface_t *surface = cairo_get_target(marker->cairo);
309                 gdouble width  = cairo_image_surface_get_width(surface);
310                 gdouble height = cairo_image_surface_get_height(surface);
311
312                 glEnable(GL_TEXTURE_2D);
313                 glGenTextures(1, &marker->tex);
314                 glBindTexture(GL_TEXTURE_2D, marker->tex);
315
316                 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
317                 glPixelStorei(GL_PACK_ALIGNMENT, 1);
318                 glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
319                                 cairo_image_surface_get_data(surface));
320                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
321                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
322                 g_debug("load_texture: %d", marker->tex);
323         }
324 }
325
326 static void _unload_object(GisOpenGL *opengl, GisObject *object)
327 {
328         g_debug("GisOpenGL: unload_object");
329         if (GIS_IS_MARKER(object)) {
330                 GisMarker *marker = GIS_MARKER(object);
331                 glDeleteTextures(1, &marker->tex);
332         }
333 }
334
335
336 /*************
337  * Callbacks *
338  *************/
339 /* The unsorted/sroted GLists are blank head nodes,
340  * This way us we can remove objects from the level just by fixing up links
341  * I.e. we don't need to do a lookup to remove an object if we have its GList */
342 struct RenderLevel {
343         GList unsorted;
344         GList sorted;
345 };
346
347 static gboolean on_configure(GisOpenGL *opengl, GdkEventConfigure *event, gpointer _)
348 {
349         g_debug("GisOpenGL: on_configure");
350
351         double width  = GTK_WIDGET(opengl)->allocation.width;
352         double height = GTK_WIDGET(opengl)->allocation.height;
353
354         /* Setup OpenGL Window */
355         glViewport(0, 0, width, height);
356         glMatrixMode(GL_PROJECTION);
357         glLoadIdentity();
358         double ang = atan(height/FOV_DIST);
359         gluPerspective(rad2deg(ang)*2, width/height, 1, 10*EARTH_R);
360
361 #ifndef ROAM_DEBUG
362         g_mutex_lock(opengl->sphere_lock);
363         roam_sphere_update_errors(opengl->sphere);
364         g_mutex_unlock(opengl->sphere_lock);
365 #endif
366
367         return FALSE;
368 }
369
370 static void on_realize(GisOpenGL *opengl, gpointer _)
371 {
372         g_debug("GisOpenGL: on_realize");
373
374         GdkGLContext   *glcontext  = gtk_widget_get_gl_context(GTK_WIDGET(opengl));
375         GdkGLDrawable  *gldrawable = gtk_widget_get_gl_drawable(GTK_WIDGET(opengl));
376         if (!gdk_gl_drawable_gl_begin(gldrawable, glcontext))
377                 g_assert_not_reached();
378
379         _set_visuals(opengl);
380         on_configure(opengl, NULL, NULL);
381 }
382
383 static gboolean _draw_level(gpointer key, gpointer value, gpointer user_data)
384 {
385         g_debug("GisOpenGL: _draw_level - level=%-4d", (int)key);
386         GisOpenGL *opengl = user_data;
387         struct RenderLevel *level = value;
388         int nsorted = 0, nunsorted = 0;
389         GList *cur = NULL;
390
391         /* Draw opaque objects without sorting */
392         glDepthMask(TRUE);
393         glClear(GL_DEPTH_BUFFER_BIT);
394         for (cur = level->unsorted.next; cur; cur = cur->next, nunsorted++)
395                 _draw_object(opengl, GIS_OBJECT(cur->data));
396
397         /* Freeze depth buffer and draw transparent objects sorted */
398         /* TODO: sorting */
399         //glDepthMask(FALSE);
400         glAlphaFunc(GL_GREATER, 0.1);
401         for (cur = level->sorted.next; cur; cur = cur->next, nsorted++)
402                 _draw_object(opengl, GIS_OBJECT(cur->data));
403
404         /* TODO: Prune empty levels */
405
406         g_debug("GisOpenGL: _draw_level - drew %d,%d objects",
407                         nunsorted, nsorted);
408         return FALSE;
409 }
410
411 static gboolean on_expose(GisOpenGL *opengl, GdkEventExpose *event, gpointer _)
412 {
413         g_debug("GisOpenGL: on_expose - begin");
414
415         glClear(GL_COLOR_BUFFER_BIT);
416
417         _set_visuals(opengl);
418 #ifdef ROAM_DEBUG
419         glColor4f(0.0, 0.0, 9.0, 0.6);
420         glDisable(GL_TEXTURE_2D);
421         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
422         roam_sphere_draw(opengl->sphere);
423         //roam_sphere_draw_normals(opengl->sphere);
424 #else
425         g_tree_foreach(opengl->objects, _draw_level, opengl);
426         if (opengl->wireframe) {
427                 glClear(GL_DEPTH_BUFFER_BIT);
428                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
429                 roam_sphere_draw(opengl->sphere);
430         }
431 #endif
432
433         GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable(GTK_WIDGET(opengl));
434         gdk_gl_drawable_swap_buffers(gldrawable);
435
436         g_debug("GisOpenGL: on_expose - end\n");
437         return FALSE;
438 }
439
440 static gboolean on_key_press(GisOpenGL *opengl, GdkEventKey *event, gpointer _)
441 {
442         g_debug("GisOpenGL: on_key_press - key=%x, state=%x, plus=%x",
443                         event->keyval, event->state, GDK_plus);
444
445         guint kv = event->keyval;
446         gdk_threads_leave();
447         /* Testing */
448         if (kv == GDK_w) {
449                 opengl->wireframe = !opengl->wireframe;
450                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
451         }
452 #ifdef ROAM_DEBUG
453         else if (kv == GDK_n) roam_sphere_split_one(opengl->sphere);
454         else if (kv == GDK_p) roam_sphere_merge_one(opengl->sphere);
455         else if (kv == GDK_r) roam_sphere_split_merge(opengl->sphere);
456         else if (kv == GDK_u) roam_sphere_update_errors(opengl->sphere);
457         gdk_threads_enter();
458         gtk_widget_queue_draw(GTK_WIDGET(opengl));
459 #else
460         gdk_threads_enter();
461 #endif
462         return FALSE;
463 }
464
465 static gboolean _update_errors_cb(gpointer sphere)
466 {
467         roam_sphere_update_errors(sphere);
468         return FALSE;
469 }
470 static void on_view_changed(GisOpenGL *opengl,
471                 gdouble _1, gdouble _2, gdouble _3)
472 {
473         g_debug("GisOpenGL: on_view_changed");
474         _set_visuals(opengl);
475 #ifndef ROAM_DEBUG
476         opengl->ue_source = g_idle_add_full(G_PRIORITY_HIGH_IDLE+30,
477                         _update_errors_cb, opengl->sphere, NULL);
478         //roam_sphere_update_errors(opengl->sphere);
479 #endif
480 }
481
482 static gboolean on_idle(GisOpenGL *opengl)
483 {
484         //g_debug("GisOpenGL: on_idle");
485         gdk_threads_enter();
486         g_mutex_lock(opengl->sphere_lock);
487         if (roam_sphere_split_merge(opengl->sphere))
488                 gtk_widget_queue_draw(GTK_WIDGET(opengl));
489         g_mutex_unlock(opengl->sphere_lock);
490         gdk_threads_leave();
491         return TRUE;
492 }
493
494
495 /*********************
496  * GisViewer methods *
497  *********************/
498 /**
499  * gis_opengl_new:
500  * @plugins: the plugins store to use
501  * @prefs:   the preferences object to use
502  *
503  * Create a new OpenGL renderer.
504  *
505  * Returns: the new #GisOpenGL
506  */
507 GisViewer *gis_opengl_new(GisPlugins *plugins, GisPrefs *prefs)
508 {
509         g_debug("GisOpenGL: new");
510         GisViewer *opengl = g_object_new(GIS_TYPE_OPENGL, NULL);
511         gis_viewer_setup(opengl, plugins, prefs);
512         return opengl;
513 }
514
515 static void gis_opengl_center_position(GisViewer *_opengl, gdouble lat, gdouble lon, gdouble elev)
516 {
517         GisOpenGL *opengl = GIS_OPENGL(_opengl);
518         glRotatef(lon, 0, 1, 0);
519         glRotatef(-lat, 1, 0, 0);
520         glTranslatef(0, 0, elev2rad(elev));
521 }
522
523 static void gis_opengl_project(GisViewer *_opengl,
524                 gdouble lat, gdouble lon, gdouble elev,
525                 gdouble *px, gdouble *py, gdouble *pz)
526 {
527         GisOpenGL *opengl = GIS_OPENGL(_opengl);
528         gdouble x, y, z;
529         lle2xyz(lat, lon, elev, &x, &y, &z);
530         gluProject(x, y, z,
531                 opengl->sphere->view->model,
532                 opengl->sphere->view->proj,
533                 opengl->sphere->view->view,
534                 px, py, pz);
535 }
536
537 static void gis_opengl_set_height_func(GisViewer *_opengl, GisTile *tile,
538                 RoamHeightFunc height_func, gpointer user_data, gboolean update)
539 {
540         GisOpenGL *opengl = GIS_OPENGL(_opengl);
541         if (!tile)
542                 return;
543         /* TODO: get points? */
544         g_mutex_lock(opengl->sphere_lock);
545         GList *triangles = roam_sphere_get_intersect(opengl->sphere, TRUE,
546                         tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
547         for (GList *cur = triangles; cur; cur = cur->next) {
548                 RoamTriangle *tri = cur->data;
549                 RoamPoint *points[] = {tri->p.l, tri->p.m, tri->p.r, tri->split};
550                 for (int i = 0; i < G_N_ELEMENTS(points); i++) {
551                         if (tile->edge.n >= points[i]->lat && points[i]->lat >= tile->edge.s &&
552                             tile->edge.e >= points[i]->lon && points[i]->lon >= tile->edge.w) {
553                                 points[i]->height_func = height_func;
554                                 points[i]->height_data = user_data;
555                                 roam_point_update_height(points[i]);
556                         }
557                 }
558         }
559         g_list_free(triangles);
560         g_mutex_unlock(opengl->sphere_lock);
561 }
562
563 static void _gis_opengl_clear_height_func_rec(RoamTriangle *root)
564 {
565         if (!root)
566                 return;
567         RoamPoint *points[] = {root->p.l, root->p.m, root->p.r, root->split};
568         for (int i = 0; i < G_N_ELEMENTS(points); i++) {
569                 points[i]->height_func = NULL;
570                 points[i]->height_data = NULL;
571                 roam_point_update_height(points[i]);
572         }
573         _gis_opengl_clear_height_func_rec(root->kids[0]);
574         _gis_opengl_clear_height_func_rec(root->kids[1]);
575 }
576
577 static void gis_opengl_clear_height_func(GisViewer *_opengl)
578 {
579         GisOpenGL *opengl = GIS_OPENGL(_opengl);
580         for (int i = 0; i < G_N_ELEMENTS(opengl->sphere->roots); i++)
581                 _gis_opengl_clear_height_func_rec(opengl->sphere->roots[i]);
582 }
583
584 static gpointer gis_opengl_add(GisViewer *_opengl, GisObject *object,
585                 gint key, gboolean sort)
586 {
587         g_assert(GIS_IS_OPENGL(_opengl));
588         GisOpenGL *opengl = GIS_OPENGL(_opengl);
589         _load_object(opengl, object);
590         struct RenderLevel *level = g_tree_lookup(opengl->objects, (gpointer)key);
591         if (!level) {
592                 level = g_new0(struct RenderLevel, 1);
593                 g_tree_insert(opengl->objects, (gpointer)key, level);
594         }
595         GList *list = sort ? &level->sorted : &level->unsorted;
596         /* Put the link in the list */
597         GList *next = g_new0(GList, 1);
598         next->data = object;
599         next->prev = list;
600         next->next = list->next;
601         list->next = next;
602         return next;
603 }
604
605 static GisObject *gis_opengl_remove(GisViewer *_opengl, gpointer _link)
606 {
607         g_assert(GIS_IS_OPENGL(_opengl));
608         GisOpenGL *opengl = GIS_OPENGL(_opengl);
609         GList *link = _link;
610         GisObject *object = link->data;
611         _unload_object(opengl, object);
612         /* Just unlink and free it, link->prev is assured */
613         link->prev->next = link->next;
614         if (link->next)
615                 link->next->prev = link->prev;
616         g_free(link);
617         g_object_unref(object);
618         return object;
619 }
620
621 /****************
622  * GObject code *
623  ****************/
624 static int _objects_cmp(gconstpointer _a, gconstpointer _b, gpointer _)
625 {
626         gint a = (int)_a, b = (int)_b;
627         return a < b ? -1 :
628                a > b ?  1 : 0;
629 }
630 static void _objects_free(gpointer value)
631 {
632         struct RenderLevel *level = value;
633         if (level->sorted.next)
634                 g_list_free(level->sorted.next);
635         if (level->unsorted.next)
636                 g_list_free(level->unsorted.next);
637         g_free(level);
638 }
639
640 G_DEFINE_TYPE(GisOpenGL, gis_opengl, GIS_TYPE_VIEWER);
641 static void gis_opengl_init(GisOpenGL *opengl)
642 {
643         g_debug("GisOpenGL: init");
644         /* OpenGL setup */
645         GdkGLConfig *glconfig = gdk_gl_config_new_by_mode(
646                         GDK_GL_MODE_RGBA   | GDK_GL_MODE_DEPTH |
647                         GDK_GL_MODE_DOUBLE | GDK_GL_MODE_ALPHA);
648         if (!glconfig)
649                 g_error("Failed to create glconfig");
650         if (!gtk_widget_set_gl_capability(GTK_WIDGET(opengl),
651                                 glconfig, NULL, TRUE, GDK_GL_RGBA_TYPE))
652                 g_error("GL lacks required capabilities");
653         g_object_unref(glconfig);
654
655         opengl->objects = g_tree_new_full(_objects_cmp, NULL, NULL, _objects_free);
656         opengl->sphere = roam_sphere_new(opengl);
657         opengl->sphere_lock = g_mutex_new();
658
659 #ifndef ROAM_DEBUG
660         opengl->sm_source[0] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+30, 33,  (GSourceFunc)on_idle, opengl, NULL);
661         opengl->sm_source[1] = g_timeout_add_full(G_PRIORITY_HIGH_IDLE+10, 500, (GSourceFunc)on_idle, opengl, NULL);
662 #endif
663
664         gtk_widget_add_events(GTK_WIDGET(opengl), GDK_KEY_PRESS_MASK);
665         g_signal_connect(opengl, "realize",          G_CALLBACK(on_realize),      NULL);
666         g_signal_connect(opengl, "configure-event",  G_CALLBACK(on_configure),    NULL);
667         g_signal_connect(opengl, "expose-event",     G_CALLBACK(on_expose),       NULL);
668
669         g_signal_connect(opengl, "key-press-event",  G_CALLBACK(on_key_press),    NULL);
670
671         g_signal_connect(opengl, "location-changed", G_CALLBACK(on_view_changed), NULL);
672         g_signal_connect(opengl, "rotation-changed", G_CALLBACK(on_view_changed), NULL);
673 }
674 static void gis_opengl_dispose(GObject *_opengl)
675 {
676         g_debug("GisOpenGL: dispose");
677         GisOpenGL *opengl = GIS_OPENGL(_opengl);
678         if (opengl->sm_source[0]) {
679                 g_source_remove(opengl->sm_source[0]);
680                 opengl->sm_source[0] = 0;
681         }
682         if (opengl->sm_source[1]) {
683                 g_source_remove(opengl->sm_source[1]);
684                 opengl->sm_source[1] = 0;
685         }
686         if (opengl->ue_source) {
687                 g_source_remove(opengl->ue_source);
688                 opengl->ue_source = 0;
689         }
690         G_OBJECT_CLASS(gis_opengl_parent_class)->dispose(_opengl);
691 }
692 static void gis_opengl_finalize(GObject *_opengl)
693 {
694         g_debug("GisOpenGL: finalize");
695         GisOpenGL *opengl = GIS_OPENGL(_opengl);
696         roam_sphere_free(opengl->sphere);
697         g_tree_destroy(opengl->objects);
698         g_mutex_free(opengl->sphere_lock);
699         G_OBJECT_CLASS(gis_opengl_parent_class)->finalize(_opengl);
700 }
701 static void gis_opengl_class_init(GisOpenGLClass *klass)
702 {
703         g_debug("GisOpenGL: class_init");
704         GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
705         gobject_class->finalize = gis_opengl_finalize;
706         gobject_class->dispose = gis_opengl_dispose;
707
708         GisViewerClass *viewer_class = GIS_VIEWER_CLASS(klass);
709         viewer_class->center_position   = gis_opengl_center_position;
710         viewer_class->project           = gis_opengl_project;
711         viewer_class->clear_height_func = gis_opengl_clear_height_func;
712         viewer_class->set_height_func   = gis_opengl_set_height_func;
713         viewer_class->add               = gis_opengl_add;
714         viewer_class->remove            = gis_opengl_remove;
715 }