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