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