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