]> Pileus Git - grits/blob - src/roam.c
aa488fcc560a7d033b5c321d52a0f12e1afa6fa6
[grits] / src / roam.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:roam
20  * @short_description: Realtime Optimally-Adapting Meshes
21  *
22  * A spherical version of the Realtime Optimally-Adapting Meshes (ROAM)
23  * algorithm is use for drawing the surface of the planet. ROAM provide a
24  * continuous level-of-detail mesh of the planet which is used by #GisOpenGL
25  * when drawing surface textures for GisTiles.
26  *
27  * This implementation of the ROAM algorithm is based on an octahedron as the
28  * base model.
29  */
30
31 #include <glib.h>
32 #include <math.h>
33 #include <string.h>
34 #include <GL/gl.h>
35 #include <GL/glu.h>
36
37 #include "gpqueue.h"
38 #include "gis-util.h"
39 #include "roam.h"
40
41 /*
42  * TODO:
43  *   - Optimize for memory consumption
44  *   - Profile for computation speed
45  *   - Target polygon count/detail
46  */
47
48 /* For GPQueue comparators */
49 static gint tri_cmp(RoamTriangle *a, RoamTriangle *b, gpointer data)
50 {
51         if      (a->error < b->error) return  1;
52         else if (a->error > b->error) return -1;
53         else                          return  0;
54 }
55 static gint dia_cmp(RoamDiamond *a, RoamDiamond *b, gpointer data)
56 {
57         if      (a->error < b->error) return -1;
58         else if (a->error > b->error) return  1;
59         else                          return  0;
60 }
61
62
63 /*************
64  * RoamPoint *
65  *************/
66 /**
67  * roam_point_new:
68  * @lat:  the latitude for the point
69  * @lon:  the longitude for the point
70  * @elev: the elevation for the point
71  *
72  * Create a new point at the given locaiton
73  *
74  * Returns: the new point
75  */
76 RoamPoint *roam_point_new(gdouble lat, gdouble lon, gdouble elev)
77 {
78         RoamPoint *point = g_new0(RoamPoint, 1);
79         point->lat  = lat;
80         point->lon  = lon;
81         point->elev = elev;
82         /* For get_intersect */
83         lle2xyz(lat, lon, elev, &point->x, &point->y, &point->z);
84         return point;
85 }
86
87 /**
88  * roam_point_add_triangle:
89  * @point:    the point
90  * @triangle: the to add
91  *
92  * Associating a triangle with a point and update it's vertex normal.
93  */
94 void roam_point_add_triangle(RoamPoint *point, RoamTriangle *triangle)
95 {
96         for (int i = 0; i < 3; i++) {
97                 point->norm[i] *= point->tris;
98                 point->norm[i] += triangle->norm[i];
99         }
100         point->tris++;
101         for (int i = 0; i < 3; i++)
102                 point->norm[i] /= point->tris;
103 }
104
105 /**
106  * roam_point_remove_triangle:
107  * @point:    the point
108  * @triangle: the to add
109  *
110  * Un-associating a triangle with a point and update it's vertex normal.
111  */
112 void roam_point_remove_triangle(RoamPoint *point, RoamTriangle *triangle)
113 {
114         for (int i = 0; i < 3; i++) {
115                 point->norm[i] *= point->tris;
116                 point->norm[i] -= triangle->norm[i];
117         }
118         point->tris--;
119         if (point->tris)
120                 for (int i = 0; i < 3; i++)
121                         point->norm[i] /= point->tris;
122 }
123
124 /**
125  * roam_point_update_height:
126  * @point: the point
127  *
128  * Update the height (elevation) of a point based on the current height function
129  */
130 void roam_point_update_height(RoamPoint *point)
131 {
132         if (point->height_func) {
133                 gdouble elev = point->height_func(
134                                 point->lat, point->lon, point->height_data);
135                 lle2xyz(point->lat, point->lon, elev,
136                                 &point->x, &point->y, &point->z);
137         }
138 }
139
140 /**
141  * roam_point_update_projection:
142  * @point: the point
143  * @view:  the view to use when projecting the point
144  *
145  * Updated the screen-space projection of a point.
146  */
147 void roam_point_update_projection(RoamPoint *point, RoamView *view)
148 {
149         static int count   = 0;
150         static int version = 0;
151         if (version != view->version) {
152                 g_debug("RoamPoint: Projected %d points", count);
153                 count   = 0;
154                 version = view->version;
155         }
156
157         if (point->pversion != view->version) {
158                 /* Cache projection */
159                 gluProject(point->x, point->y, point->z,
160                         view->model, view->proj, view->view,
161                         &point->px, &point->py, &point->pz);
162                 point->pversion = view->version;
163                 count++;
164         }
165 }
166
167 /****************
168  * RoamTriangle *
169  ****************/
170 /**
171  * roam_triangle_new:
172  * @l: the left point
173  * @m: the middle point
174  * @r: the right point
175  *
176  * Create a new triangle consisting of three points. 
177  *
178  * Returns: the new triangle
179  */
180 RoamTriangle *roam_triangle_new(RoamPoint *l, RoamPoint *m, RoamPoint *r,
181                 RoamDiamond *parent)
182 {
183         RoamTriangle *triangle = g_new0(RoamTriangle, 1);
184
185         triangle->error  = 0;
186         triangle->p.l    = l;
187         triangle->p.m    = m;
188         triangle->p.r    = r;
189         triangle->parent = parent;
190         triangle->split  = roam_point_new(
191                 (l->lat + r->lat)/2,
192                 (ABS(l->lat) == 90 ? r->lon :
193                  ABS(r->lat) == 90 ? l->lon :
194                  lon_avg(l->lon, r->lon)),
195                 (l->elev + r->elev)/2);
196         /* TODO: Move this back to sphere, or actually use the nesting */
197         triangle->split->height_func = m->height_func;
198         triangle->split->height_data = m->height_data;
199         roam_point_update_height(triangle->split);
200         //if ((float)triangle->split->lat > 44 && (float)triangle->split->lat < 46)
201         //      g_debug("RoamTriangle: new - (l,m,r,split).lats = %7.2f %7.2f %7.2f %7.2f",
202         //                      l->lat, m->lat, r->lat, triangle->split->lat);
203         //if ((float)l->lat == (float)r->lat &&
204         //    (float)triangle->split->lat != (float)l->lat)
205         //      g_warning("RoamTriangle: new - split.lat=%f != (l=r).lat=%f",
206         //              triangle->split->lat, l->lat);
207
208         /* Update normal */
209         double pa[3];
210         double pb[3];
211         pa[0] = triangle->p.l->x - triangle->p.m->x;
212         pa[1] = triangle->p.l->y - triangle->p.m->y;
213         pa[2] = triangle->p.l->z - triangle->p.m->z;
214
215         pb[0] = triangle->p.r->x - triangle->p.m->x;
216         pb[1] = triangle->p.r->y - triangle->p.m->y;
217         pb[2] = triangle->p.r->z - triangle->p.m->z;
218
219         triangle->norm[0] = pa[1] * pb[2] - pa[2] * pb[1];
220         triangle->norm[1] = pa[2] * pb[0] - pa[0] * pb[2];
221         triangle->norm[2] = pa[0] * pb[1] - pa[1] * pb[0];
222
223         double total = sqrt(triangle->norm[0] * triangle->norm[0] +
224                             triangle->norm[1] * triangle->norm[1] +
225                             triangle->norm[2] * triangle->norm[2]);
226
227         triangle->norm[0] /= total;
228         triangle->norm[1] /= total;
229         triangle->norm[2] /= total;
230
231         /* Store bounding box, for get_intersect */
232         RoamPoint *p[] = {l,m,r};
233         triangle->edge.n =  -90; triangle->edge.s =  90;
234         triangle->edge.e = -180; triangle->edge.w = 180;
235         gboolean maxed = FALSE;
236         for (int i = 0; i < G_N_ELEMENTS(p); i++) {
237                 triangle->edge.n = MAX(triangle->edge.n, p[i]->lat);
238                 triangle->edge.s = MIN(triangle->edge.s, p[i]->lat);
239                 if (p[i]->lat == 90 || p[i]->lat == -90)
240                         continue;
241                 if (p[i]->lon == 180) {
242                         maxed = TRUE;
243                         continue;
244                 }
245                 triangle->edge.e = MAX(triangle->edge.e, p[i]->lon);
246                 triangle->edge.w = MIN(triangle->edge.w, p[i]->lon);
247         }
248         if (maxed) {
249                 if (triangle->edge.e < 0)
250                         triangle->edge.w = -180;
251                 else
252                         triangle->edge.e =  180;
253         }
254
255         //g_message("roam_triangle_new: %p", triangle);
256         return triangle;
257 }
258
259 /**
260  * roam_triangle_free:
261  * @triangle: the triangle
262  *
263  * Free data associated with a triangle
264  */
265 void roam_triangle_free(RoamTriangle *triangle)
266 {
267         g_free(triangle->split);
268         g_free(triangle);
269 }
270
271 /**
272  * roam_triangle_add:
273  * @triangle: the triangle
274  * @left:     the left neighbor
275  * @base:     the base neighbor
276  * @right:    the right neighbor
277  * @sphere:   the sphere to add the triangle to
278  *
279  * Add a triangle into the sphere's mesh using the given neighbors.
280  */
281 void roam_triangle_add(RoamTriangle *triangle,
282                 RoamTriangle *left, RoamTriangle *base, RoamTriangle *right,
283                 RoamSphere *sphere)
284 {
285         triangle->t.l = left;
286         triangle->t.b = base;
287         triangle->t.r = right;
288
289         roam_point_add_triangle(triangle->p.l, triangle);
290         roam_point_add_triangle(triangle->p.m, triangle);
291         roam_point_add_triangle(triangle->p.r, triangle);
292
293         if (sphere->view)
294                 roam_triangle_update_errors(triangle, sphere);
295
296         triangle->handle = g_pqueue_push(sphere->triangles, triangle);
297 }
298
299 /**
300  * roam_triangle_remove:
301  * @triangle: the triangle
302  * @sphere:   the sphere to remove the triangle from
303  *
304  * Remove a triangle from a sphere's mesh.
305  */
306 void roam_triangle_remove(RoamTriangle *triangle, RoamSphere *sphere)
307 {
308         /* Update vertex normals */
309         roam_point_remove_triangle(triangle->p.l, triangle);
310         roam_point_remove_triangle(triangle->p.m, triangle);
311         roam_point_remove_triangle(triangle->p.r, triangle);
312
313         g_pqueue_remove(sphere->triangles, triangle->handle);
314 }
315
316 /* (neight->t.? == old) = new */
317 static void roam_triangle_sync_neighbors(RoamTriangle *neigh, RoamTriangle *old, RoamTriangle *new)
318 {
319         if      (neigh->t.l == old) neigh->t.l = new;
320         else if (neigh->t.b == old) neigh->t.b = new;
321         else if (neigh->t.r == old) neigh->t.r = new;
322 }
323
324 static gboolean roam_triangle_visible(RoamTriangle *triangle, RoamSphere *sphere)
325 {
326         RoamPoint *l = triangle->p.l;
327         RoamPoint *m = triangle->p.m;
328         RoamPoint *r = triangle->p.r;
329         gdouble min_x = MIN(MIN(l->px, m->px), r->px);
330         gdouble max_x = MAX(MAX(l->px, m->px), r->px);
331         gdouble min_y = MIN(MIN(l->py, m->py), r->py);
332         gdouble max_y = MAX(MAX(l->py, m->py), r->py);
333         gint *view = sphere->view->view;
334         return !(max_x < view[0] || min_x > view[2] ||
335                  max_y < view[1] || min_y > view[3]) &&
336                  l->pz > 0 && m->pz > 0 && r->pz > 0 &&
337                  l->pz < 1 && m->pz < 1 && r->pz < 1;
338 }
339
340 static gboolean roam_triangle_backface(RoamTriangle *triangle, RoamSphere *sphere)
341 {
342         RoamPoint *l = triangle->p.l;
343         RoamPoint *m = triangle->p.m;
344         RoamPoint *r = triangle->p.r;
345         roam_point_update_projection(l, sphere->view);
346         roam_point_update_projection(m, sphere->view);
347         roam_point_update_projection(r, sphere->view);
348         double size = -( l->px * (m->py - r->py) +
349                          m->px * (r->py - l->py) +
350                          r->px * (l->py - m->py) ) / 2.0;
351         return size < 0;
352 }
353
354 /**
355  * roam_triangle_update_errors:
356  * @triangle: the triangle
357  * @sphere:   the sphere to use when updating errors
358  *
359  * Update the error value associated with a triangle. Called when the view
360  * changes.
361  */
362 void roam_triangle_update_errors(RoamTriangle *triangle, RoamSphere *sphere)
363 {
364 #if 0
365         /* Update points */
366         roam_point_update_projection(triangle->p.l, sphere->view);
367         roam_point_update_projection(triangle->p.m, sphere->view);
368         roam_point_update_projection(triangle->p.r, sphere->view);
369
370         if (!roam_triangle_visible(triangle, sphere)) {
371                 triangle->error = -1;
372         } else {
373                 roam_point_update_projection(triangle->split, sphere->view);
374                 RoamPoint *l     = triangle->p.l;
375                 RoamPoint *m     = triangle->p.m;
376                 RoamPoint *r     = triangle->p.r;
377                 RoamPoint *split = triangle->split;
378
379                 /*               l-r midpoint        projected l-r midpoint */
380                 gdouble pxdist = (l->px + r->px)/2 - split->px;
381                 gdouble pydist = (l->py + r->py)/2 - split->py;
382
383                 triangle->error = sqrt(pxdist*pxdist + pydist*pydist);
384
385                 /* Multiply by size of triangle */
386                 double size = -( l->px * (m->py - r->py) +
387                                  m->px * (r->py - l->py) +
388                                  r->px * (l->py - m->py) ) / 2.0;
389
390                 /* Size < 0 == backface */
391                 triangle->error *= size;
392
393                 /* Give some preference to "edge" faces */
394                 if (roam_triangle_backface(triangle->t.l, sphere) ||
395                     roam_triangle_backface(triangle->t.b, sphere) ||
396                     roam_triangle_backface(triangle->t.r, sphere))
397                         triangle->error *= 500;
398         }
399 #endif
400
401         /* For pure distance based errors */
402         (void)roam_triangle_visible;
403         (void)roam_triangle_backface;
404         RoamPoint *l = triangle->p.l;
405         RoamPoint *m = triangle->p.m;
406         RoamPoint *r = triangle->p.r;
407         double base = distd((gdouble*)l, (gdouble*)r);
408         double dist = distd((gdouble*)m, (gdouble*)sphere->view->pos);
409         triangle->error = base/dist;
410 }
411
412 /**
413  * roam_triangle_split:
414  * @triangle: the triangle
415  * @sphere:   the sphere
416  *
417  * Split a triangle into two child triangles and update the sphere.
418  * triangle
419  */
420 void roam_triangle_split(RoamTriangle *triangle, RoamSphere *sphere)
421 {
422         //g_message("roam_triangle_split: %p, e=%f\n", triangle, triangle->error);
423
424         sphere->polys += 2;
425
426         if (triangle != triangle->t.b->t.b)
427                 roam_triangle_split(triangle->t.b, sphere);
428         if (triangle != triangle->t.b->t.b)
429                 g_assert_not_reached();
430
431         RoamTriangle *s = triangle;      // Self
432         RoamTriangle *b = triangle->t.b; // Base
433
434         RoamDiamond *dia = roam_diamond_new(s, b);
435
436         /* Add new triangles */
437         RoamPoint *mid = triangle->split;
438         RoamTriangle *sl = s->kids[0] = roam_triangle_new(s->p.m, mid, s->p.l, dia); // Self Left
439         RoamTriangle *sr = s->kids[1] = roam_triangle_new(s->p.r, mid, s->p.m, dia); // Self Right
440         RoamTriangle *bl = b->kids[0] = roam_triangle_new(b->p.m, mid, b->p.l, dia); // Base Left
441         RoamTriangle *br = b->kids[1] = roam_triangle_new(b->p.r, mid, b->p.m, dia); // Base Right
442
443         /*                triangle,l,  base,      r,  sphere */
444         roam_triangle_add(sl, sr, s->t.l, br, sphere);
445         roam_triangle_add(sr, bl, s->t.r, sl, sphere);
446         roam_triangle_add(bl, br, b->t.l, sr, sphere);
447         roam_triangle_add(br, sl, b->t.r, bl, sphere);
448
449         roam_triangle_sync_neighbors(s->t.l, s, sl);
450         roam_triangle_sync_neighbors(s->t.r, s, sr);
451         roam_triangle_sync_neighbors(b->t.l, b, bl);
452         roam_triangle_sync_neighbors(b->t.r, b, br);
453
454         /* Remove old triangles */
455         roam_triangle_remove(s, sphere);
456         roam_triangle_remove(b, sphere);
457
458         /* Add/Remove diamonds */
459         roam_diamond_update_errors(dia, sphere);
460         roam_diamond_add(dia, sphere);
461         roam_diamond_remove(s->parent, sphere);
462         roam_diamond_remove(b->parent, sphere);
463 }
464
465 /**
466  * roam_triangle_draw:
467  * @triangle: the triangle
468  *
469  * Draw the triangle. Use for debugging.
470  */
471 void roam_triangle_draw(RoamTriangle *triangle)
472 {
473         glBegin(GL_TRIANGLES);
474         glNormal3dv(triangle->p.r->norm); glVertex3dv((double*)triangle->p.r);
475         glNormal3dv(triangle->p.m->norm); glVertex3dv((double*)triangle->p.m);
476         glNormal3dv(triangle->p.l->norm); glVertex3dv((double*)triangle->p.l);
477         glEnd();
478         return;
479 }
480
481 /**
482  * roam_triangle_draw_normal:
483  * @triangle: the triangle
484  *
485  * Draw a normal vector for the triangle. Used while debugging.
486  */
487 void roam_triangle_draw_normal(RoamTriangle *triangle)
488 {
489         double center[] = {
490                 (triangle->p.l->x + triangle->p.m->x + triangle->p.r->x)/3.0,
491                 (triangle->p.l->y + triangle->p.m->y + triangle->p.r->y)/3.0,
492                 (triangle->p.l->z + triangle->p.m->z + triangle->p.r->z)/3.0,
493         };
494         double end[] = {
495                 center[0]+triangle->norm[0]*2000000,
496                 center[1]+triangle->norm[1]*2000000,
497                 center[2]+triangle->norm[2]*2000000,
498         };
499         glBegin(GL_LINES);
500         glVertex3dv(center);
501         glVertex3dv(end);
502         glEnd();
503 }
504
505 /***************
506  * RoamDiamond *
507  ***************/
508 /**
509  * roam_diamond_new:
510  * @parent0: a parent triangle
511  * @parent1: a parent triangle
512  * @kid0:    a child triangle
513  * @kid1:    a child triangle
514  * @kid2:    a child triangle
515  * @kid3:    a child triangle
516  *
517  * Create a diamond to store information about two split triangles.
518  *
519  * Returns: the new diamond
520  */
521 RoamDiamond *roam_diamond_new(RoamTriangle *parent0, RoamTriangle *parent1)
522 {
523         RoamDiamond *diamond = g_new0(RoamDiamond, 1);
524         diamond->parents[0] = parent0;
525         diamond->parents[1] = parent1;
526         return diamond;
527 }
528
529 /**
530  * roam_diamond_add:
531  * @diamond: the diamond
532  * @sphere:  the sphere to add the diamond to
533  *
534  * Add a diamond into the sphere's pool of diamonds. It will be check for
535  * possible merges.
536  */
537 void roam_diamond_add(RoamDiamond *diamond, RoamSphere *sphere)
538 {
539         diamond->active = TRUE;
540         diamond->error  = MAX(diamond->parents[0]->error, diamond->parents[1]->error);
541         diamond->handle = g_pqueue_push(sphere->diamonds, diamond);
542 }
543
544 /**
545  * roam_diamond_remove:
546  * @diamond: the diamond
547  * @sphere:  the sphere to remove the diamond from
548  *
549  * Remove a diamond from the sphere's pool of diamonds.
550  */
551 void roam_diamond_remove(RoamDiamond *diamond, RoamSphere *sphere)
552 {
553         if (diamond && diamond->active) {
554                 diamond->active = FALSE;
555                 g_pqueue_remove(sphere->diamonds, diamond->handle);
556         }
557 }
558
559 /**
560  * roam_diamond_merge:
561  * @diamond: the diamond
562  * @sphere:  the sphere
563  *
564  * "Merge" a diamond back into two parent triangles. The original two triangles
565  * are added back into the sphere and the four child triangles as well as the
566  * diamond are removed.
567  */
568 void roam_diamond_merge(RoamDiamond *diamond, RoamSphere *sphere)
569 {
570         //g_message("roam_diamond_merge: %p, e=%f\n", diamond, diamond->error);
571
572         /* TODO: pick the best split */
573         sphere->polys -= 2;
574
575         /* Use nicer temp names */
576         RoamTriangle *s = diamond->parents[0]; // Self
577         RoamTriangle *b = diamond->parents[1]; // Base
578
579         RoamTriangle *sl = s->kids[0];
580         RoamTriangle *sr = s->kids[1];
581         RoamTriangle *bl = b->kids[0];
582         RoamTriangle *br = b->kids[1];
583
584         s->kids[0] = s->kids[1] = NULL;
585         b->kids[0] = b->kids[1] = NULL;
586
587         /* Add original triangles */
588         roam_triangle_sync_neighbors(s->t.l, sl, s);
589         roam_triangle_sync_neighbors(s->t.r, sr, s);
590         roam_triangle_sync_neighbors(b->t.l, bl, b);
591         roam_triangle_sync_neighbors(b->t.r, br, b);
592
593         roam_triangle_add(s, sl->t.b, b, sr->t.b, sphere);
594         roam_triangle_add(b, bl->t.b, s, br->t.b, sphere);
595
596         roam_triangle_sync_neighbors(sl->t.b, sl, s);
597         roam_triangle_sync_neighbors(sr->t.b, sr, s);
598         roam_triangle_sync_neighbors(bl->t.b, bl, b);
599         roam_triangle_sync_neighbors(br->t.b, br, b);
600
601         /* Remove child triangles */
602         roam_triangle_remove(sl, sphere);
603         roam_triangle_remove(sr, sphere);
604         roam_triangle_remove(bl, sphere);
605         roam_triangle_remove(br, sphere);
606
607         /* Add/Remove triangles */
608         if (s->t.l->t.l == s->t.r->t.r &&
609             s->t.l->t.l != s && s->parent) {
610                 roam_diamond_update_errors(s->parent, sphere);
611                 roam_diamond_add(s->parent, sphere);
612         }
613
614         if (b->t.l->t.l == b->t.r->t.r &&
615             b->t.l->t.l != b && b->parent) {
616                 roam_diamond_update_errors(b->parent, sphere);
617                 roam_diamond_add(b->parent, sphere);
618         }
619
620         /* Remove and free diamond and child triangles */
621         roam_diamond_remove(diamond, sphere);
622         g_assert(sl->p.m == sr->p.m &&
623                  sr->p.m == bl->p.m &&
624                  bl->p.m == br->p.m);
625         g_assert(sl->p.m->tris == 0);
626         roam_triangle_free(sl);
627         roam_triangle_free(sr);
628         roam_triangle_free(bl);
629         roam_triangle_free(br);
630         g_free(diamond);
631 }
632
633 /**
634  * roam_diamond_update_errors:
635  * @diamond: the diamond
636  * @sphere:  the sphere to use when updating errors
637  *
638  * Update the error value associated with a diamond. Called when the view
639  * changes.
640  */
641 void roam_diamond_update_errors(RoamDiamond *diamond, RoamSphere *sphere)
642 {
643         roam_triangle_update_errors(diamond->parents[0], sphere);
644         roam_triangle_update_errors(diamond->parents[1], sphere);
645         diamond->error = MAX(diamond->parents[0]->error, diamond->parents[1]->error);
646 }
647
648 /**************
649  * RoamSphere *
650  **************/
651 /**
652  * roam_sphere_new:
653  *
654  * Create a new sphere
655  *
656  * Returns: the sphere
657  */
658 RoamSphere *roam_sphere_new()
659 {
660         RoamSphere *sphere = g_new0(RoamSphere, 1);
661         sphere->polys       = 8;
662         sphere->triangles   = g_pqueue_new((GCompareDataFunc)tri_cmp, NULL);
663         sphere->diamonds    = g_pqueue_new((GCompareDataFunc)dia_cmp, NULL);
664
665         RoamPoint *vertexes[] = {
666                 roam_point_new( 90,   0,  0), // 0 (North)
667                 roam_point_new(-90,   0,  0), // 1 (South)
668                 roam_point_new(  0,   0,  0), // 2 (Europe/Africa)
669                 roam_point_new(  0,  90,  0), // 3 (Asia,East)
670                 roam_point_new(  0, 180,  0), // 4 (Pacific)
671                 roam_point_new(  0, -90,  0), // 5 (Americas,West)
672         };
673         int _triangles[][2][3] = {
674                 /*lv mv rv   ln, bn, rn */
675                 {{2,0,3}, {3, 4, 1}}, // 0
676                 {{3,0,4}, {0, 5, 2}}, // 1
677                 {{4,0,5}, {1, 6, 3}}, // 2
678                 {{5,0,2}, {2, 7, 0}}, // 3
679                 {{3,1,2}, {5, 0, 7}}, // 4
680                 {{4,1,3}, {6, 1, 4}}, // 5
681                 {{5,1,4}, {7, 2, 5}}, // 6
682                 {{2,1,5}, {4, 3, 6}}, // 7
683         };
684
685         for (int i = 0; i < 6; i++)
686                 roam_point_update_height(vertexes[i]);
687         for (int i = 0; i < 8; i++)
688                 sphere->roots[i] = roam_triangle_new(
689                         vertexes[_triangles[i][0][0]],
690                         vertexes[_triangles[i][0][1]],
691                         vertexes[_triangles[i][0][2]],
692                         NULL);
693         for (int i = 0; i < 8; i++)
694                 roam_triangle_add(sphere->roots[i],
695                         sphere->roots[_triangles[i][1][0]],
696                         sphere->roots[_triangles[i][1][1]],
697                         sphere->roots[_triangles[i][1][2]],
698                         sphere);
699         for (int i = 0; i < 8; i++)
700                 g_debug("RoamSphere: new - %p edge=%f,%f,%f,%f", sphere->roots[i],
701                                 sphere->roots[i]->edge.n,
702                                 sphere->roots[i]->edge.s,
703                                 sphere->roots[i]->edge.e,
704                                 sphere->roots[i]->edge.w);
705
706         return sphere;
707 }
708
709 /**
710  * roam_sphere_update_view
711  * @sphere: the sphere
712  *
713  * Recreate the sphere's view matrices based on the current OpenGL state.
714  */
715 void roam_sphere_update_view(RoamSphere *sphere)
716 {
717         if (!sphere->view)
718                 sphere->view = g_new0(RoamView, 1);
719         glGetDoublev (GL_MODELVIEW_MATRIX,  sphere->view->model);
720         glGetDoublev (GL_PROJECTION_MATRIX, sphere->view->proj);
721         glGetIntegerv(GL_VIEWPORT,          sphere->view->view);
722         sphere->view->version++;
723 }
724
725 /**
726  * roam_sphere_update_errors
727  * @sphere: the sphere
728  *
729  * Update triangle and diamond errors in the sphere.
730  */
731 void roam_sphere_update_errors(RoamSphere *sphere)
732 {
733         g_debug("RoamSphere: update_errors - polys=%d", sphere->polys);
734         GPtrArray *tris = g_pqueue_get_array(sphere->triangles);
735         GPtrArray *dias = g_pqueue_get_array(sphere->diamonds);
736
737         roam_sphere_update_view(sphere);
738
739         for (int i = 0; i < tris->len; i++) {
740                 RoamTriangle *triangle = tris->pdata[i];
741                 roam_triangle_update_errors(triangle, sphere);
742                 g_pqueue_priority_changed(sphere->triangles, triangle->handle);
743         }
744
745         for (int i = 0; i < dias->len; i++) {
746                 RoamDiamond *diamond = dias->pdata[i];
747                 roam_diamond_update_errors(diamond, sphere);
748                 g_pqueue_priority_changed(sphere->diamonds, diamond->handle);
749         }
750
751         g_ptr_array_free(tris, TRUE);
752         g_ptr_array_free(dias, TRUE);
753 }
754
755 /**
756  * roam_sphere_split_one
757  * @sphere: the sphere
758  *
759  * Split the triangle with the greatest error.
760  */
761 void roam_sphere_split_one(RoamSphere *sphere)
762 {
763         RoamTriangle *to_split = g_pqueue_peek(sphere->triangles);
764         if (!to_split) return;
765         roam_triangle_split(to_split, sphere);
766 }
767
768 /**
769  * roam_sphere_merge_one
770  * @sphere: the sphere
771  *
772  * Merge the diamond with the lowest error.
773  */
774 void roam_sphere_merge_one(RoamSphere *sphere)
775 {
776         RoamDiamond *to_merge = g_pqueue_peek(sphere->diamonds);
777         if (!to_merge) return;
778         roam_diamond_merge(to_merge, sphere);
779 }
780
781 /**
782  * roam_sphere_split_merge
783  * @sphere: the sphere
784  *
785  * Perform a predetermined number split-merge iterations.
786  *
787  * Returns: the number splits and merges done
788  */
789 gint roam_sphere_split_merge(RoamSphere *sphere)
790 {
791         gint iters = 0, max_iters = 500;
792         gint target = 10000;
793         //gint target = 4000;
794         //gint target = 2000;
795         //gint target = 500;
796
797         if (!sphere->view)
798                 return 0;
799
800         if (target - sphere->polys > 100) {
801                 //g_debug("RoamSphere: split_merge - Splitting %d - %d > 100", target, sphere->polys);
802                 while (sphere->polys < target && iters++ < max_iters)
803                         roam_sphere_split_one(sphere);
804         }
805
806         if (sphere->polys - target > 100) {
807                 //g_debug("RoamSphere: split_merge - Merging %d - %d > 100", sphere->polys, target);
808                 while (sphere->polys > target && iters++ < max_iters)
809                         roam_sphere_merge_one(sphere);
810         }
811
812         while (((RoamTriangle*)g_pqueue_peek(sphere->triangles))->error >
813                ((RoamDiamond *)g_pqueue_peek(sphere->diamonds ))->error &&
814                iters++ < max_iters) {
815                 //g_debug("RoamSphere: split_merge - Fixing 1 %f > %f && %d < %d",
816                 //              ((RoamTriangle*)g_pqueue_peek(sphere->triangles))->error,
817                 //              ((RoamDiamond *)g_pqueue_peek(sphere->diamonds ))->error,
818                 //              iters-1, max_iters);
819                 roam_sphere_merge_one(sphere);
820                 roam_sphere_split_one(sphere);
821         }
822
823         return iters;
824 }
825
826 /**
827  * roam_sphere_draw:
828  * @sphere: the sphere
829  *
830  * Draw the sphere. Use for debugging.
831  */
832 void roam_sphere_draw(RoamSphere *sphere)
833 {
834         g_debug("RoamSphere: draw");
835         g_pqueue_foreach(sphere->triangles, (GFunc)roam_triangle_draw, NULL);
836 }
837
838 /**
839  * roam_sphere_draw_normals
840  * @sphere: the sphere
841  *
842  * Draw all the surface normal vectors for the sphere. Used while debugging.
843  */
844 void roam_sphere_draw_normals(RoamSphere *sphere)
845 {
846         g_debug("RoamSphere: draw_normal");
847         g_pqueue_foreach(sphere->triangles, (GFunc)roam_triangle_draw_normal, NULL);
848 }
849
850 static GList *_roam_sphere_get_leaves(RoamTriangle *triangle, GList *list, gboolean all)
851 {
852         if (triangle->kids[0] && triangle->kids[1]) {
853                 if (all) list = g_list_prepend(list, triangle);
854                 list = _roam_sphere_get_leaves(triangle->kids[0], list, all);
855                 list = _roam_sphere_get_leaves(triangle->kids[1], list, all);
856                 return list;
857         } else {
858                 return g_list_prepend(list, triangle);
859         }
860 }
861
862 static GList *_roam_sphere_get_intersect_rec(RoamTriangle *triangle, GList *list,
863                 gboolean all, gdouble n, gdouble s, gdouble e, gdouble w)
864 {
865         gdouble tn = triangle->edge.n;
866         gdouble ts = triangle->edge.s;
867         gdouble te = triangle->edge.e;
868         gdouble tw = triangle->edge.w;
869
870         gboolean debug = FALSE  &&
871                 n==90 && s==45 && e==-90 && w==-180 &&
872                 ts > 44 && ts < 46;
873
874         if (debug)
875                 g_message("t=%p: %f < %f || %f > %f || %f < %f || %f > %f",
876                             triangle, tn,   s,   ts,   n,   te,   w,   tw,   e);
877         if (tn <= s || ts >= n || te <= w || tw >= e) {
878                 /* No intersect */
879                 if (debug) g_message("no intersect");
880                 return list;
881         } else if (tn <= n && ts >= s && te <= e && tw >= w) {
882                 /* Triangle is completely contained */
883                 if (debug) g_message("contained");
884                 if (all) list = g_list_prepend(list, triangle);
885                 return _roam_sphere_get_leaves(triangle, list, all);
886         } else if (triangle->kids[0] && triangle->kids[1]) {
887                 /* Paritial intersect with children */
888                 if (debug) g_message("edge w/ child");
889                 if (all) list = g_list_prepend(list, triangle);
890                 list = _roam_sphere_get_intersect_rec(triangle->kids[0], list, all, n, s, e, w);
891                 list = _roam_sphere_get_intersect_rec(triangle->kids[1], list, all, n, s, e, w);
892                 return list;
893         } else {
894                 /* This triangle is an edge case */
895                 if (debug) g_message("edge");
896                 return g_list_prepend(list, triangle);
897         }
898 }
899
900 /**
901  * roam_sphere_get_intersect
902  * @sphere: the sphere
903  * @all: TRUE if non-leaf triangle should be returned as well
904  * @n: the northern edge 
905  * @s: the southern edge 
906  * @e: the eastern edge 
907  * @w: the western edge 
908  *
909  * Lookup triangles withing the sphere that intersect a given lat-lon box.
910  *
911  * Returns: the list of intersecting triangles.
912  */
913 /* Warning: This grabs pointers to triangles which can be changed by other
914  * calls, e.g. split_merge. If you use this, you need to do some locking to
915  * prevent the returned list from becomming stale. */
916 GList *roam_sphere_get_intersect(RoamSphere *sphere, gboolean all,
917                 gdouble n, gdouble s, gdouble e, gdouble w)
918 {
919         /* I think this is correct..
920          * i_cost = cost for triangle-rectagnle intersect test
921          * time = n_tiles * 2*tris_per_tile * i_cost
922          * time = 30      * 2*333           * i_cost = 20000 * i_cost */
923         GList *list = NULL;
924         for (int i = 0; i < G_N_ELEMENTS(sphere->roots); i++)
925                 list = _roam_sphere_get_intersect_rec(sphere->roots[i],
926                                 list, all, n, s, e, w);
927         return list;
928 }
929
930 static void roam_sphere_free_tri(RoamTriangle *triangle)
931 {
932         if (--triangle->p.l->tris == 0) g_free(triangle->p.l);
933         if (--triangle->p.m->tris == 0) g_free(triangle->p.m);
934         if (--triangle->p.r->tris == 0) g_free(triangle->p.r);
935         roam_triangle_free(triangle);
936 }
937
938 /**
939  * roam_sphere_free
940  * @sphere: the sphere
941  *
942  * Free data associated with a sphere
943  */
944 void roam_sphere_free(RoamSphere *sphere)
945 {
946         g_debug("RoamSphere: free");
947         /* Slow method, but it should work */
948         while (sphere->polys > 8)
949                 roam_sphere_merge_one(sphere);
950         /* TODO: free points */
951         g_pqueue_foreach(sphere->triangles, (GFunc)roam_sphere_free_tri, NULL);
952         g_pqueue_free(sphere->triangles);
953         g_pqueue_free(sphere->diamonds);
954         g_free(sphere->view);
955         g_free(sphere);
956 }