]> Pileus Git - grits/blob - src/roam.c
Miscellaneous updates, mostly aesthetic
[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 #include <glib.h>
19 #include <math.h>
20 #include <string.h>
21 #include <GL/gl.h>
22 #include <GL/glu.h>
23
24 #include "gpqueue.h"
25 #include "gis-util.h"
26 #include "roam.h"
27
28 /**
29  * TODO:
30  *   - Optimize for memory consumption
31  *   - Profile for computation speed
32  *   - Target polygon count/detail
33  */
34
35 /* For GPQueue comparators */
36 static gint tri_cmp(RoamTriangle *a, RoamTriangle *b, gpointer data)
37 {
38         if      (a->error < b->error) return  1;
39         else if (a->error > b->error) return -1;
40         else                          return  0;
41 }
42 static gint dia_cmp(RoamDiamond *a, RoamDiamond *b, gpointer data)
43 {
44         if      (a->error < b->error) return -1;
45         else if (a->error > b->error) return  1;
46         else                          return  0;
47 }
48
49
50 /*************
51  * RoamPoint *
52  *************/
53 RoamPoint *roam_point_new(gdouble lat, gdouble lon, gdouble elev)
54 {
55         RoamPoint *point = g_new0(RoamPoint, 1);
56         point->lat  = lat;
57         point->lon  = lon;
58         point->elev = elev;
59         /* For get_intersect */
60         lle2xyz(lat, lon, elev, &point->x, &point->y, &point->z);
61         return point;
62 }
63
64 static RoamPoint *roam_point_dup(RoamPoint *point)
65 {
66         RoamPoint *new = g_memdup(point, sizeof(RoamPoint));
67         new->tris = 0;
68         return new;
69 }
70 void roam_point_add_triangle(RoamPoint *point, RoamTriangle *triangle)
71 {
72         for (int i = 0; i < 3; i++) {
73                 point->norm[i] *= point->tris;
74                 point->norm[i] += triangle->norm[i];
75         }
76         point->tris++;
77         for (int i = 0; i < 3; i++)
78                 point->norm[i] /= point->tris;
79 }
80 void roam_point_remove_triangle(RoamPoint *point, RoamTriangle *triangle)
81 {
82         for (int i = 0; i < 3; i++) {
83                 point->norm[i] *= point->tris;
84                 point->norm[i] -= triangle->norm[i];
85         }
86         point->tris--;
87         if (point->tris)
88                 for (int i = 0; i < 3; i++)
89                         point->norm[i] /= point->tris;
90 }
91 void roam_point_update_height(RoamPoint *point)
92 {
93         if (point->height_func) {
94                 gdouble elev = point->height_func(
95                                 point->lat, point->lon, point->height_data);
96                 lle2xyz(point->lat, point->lon, elev,
97                                 &point->x, &point->y, &point->z);
98         }
99 }
100
101 void roam_point_update_projection(RoamPoint *point, RoamView *view)
102 {
103         static int count   = 0;
104         static int version = 0;
105         if (version != view->version) {
106                 g_debug("RoamPoint: Projected %d points", count);
107                 count   = 0;
108                 version = view->version;
109         }
110
111         if (point->pversion != view->version) {
112                 /* Cache projection */
113                 gluProject(point->x, point->y, point->z,
114                         view->model, view->proj, view->view,
115                         &point->px, &point->py, &point->pz);
116                 point->pversion = view->version;
117                 count++;
118         }
119 }
120
121 /****************
122  * RoamTriangle *
123  ****************/
124 RoamTriangle *roam_triangle_new(RoamPoint *l, RoamPoint *m, RoamPoint *r)
125 {
126         RoamTriangle *triangle = g_new0(RoamTriangle, 1);
127
128         triangle->error = 0;
129         triangle->p.l = l;
130         triangle->p.m = m;
131         triangle->p.r = r;
132         triangle->split = roam_point_new(
133                 (l->lat + r->lat)/2,
134                 (ABS(l->lat) == 90 ? r->lon :
135                  ABS(r->lat) == 90 ? l->lon :
136                  lon_avg(l->lon, r->lon)),
137                 (l->elev + r->elev)/2);
138         /* TODO: Move this back to sphere, or actually use the nesting */
139         triangle->split->height_func = m->height_func;
140         triangle->split->height_data = m->height_data;
141         roam_point_update_height(triangle->split);
142         //if ((float)triangle->split->lat > 44 && (float)triangle->split->lat < 46)
143         //      g_debug("RoamTriangle: new - (l,m,r,split).lats = %7.2f %7.2f %7.2f %7.2f",
144         //                      l->lat, m->lat, r->lat, triangle->split->lat);
145         //if ((float)l->lat == (float)r->lat &&
146         //    (float)triangle->split->lat != (float)l->lat)
147         //      g_warning("RoamTriangle: new - split.lat=%f != (l=r).lat=%f",
148         //              triangle->split->lat, l->lat);
149
150         /* Update normal */
151         double pa[3];
152         double pb[3];
153         pa[0] = triangle->p.l->x - triangle->p.m->x;
154         pa[1] = triangle->p.l->y - triangle->p.m->y;
155         pa[2] = triangle->p.l->z - triangle->p.m->z;
156
157         pb[0] = triangle->p.r->x - triangle->p.m->x;
158         pb[1] = triangle->p.r->y - triangle->p.m->y;
159         pb[2] = triangle->p.r->z - triangle->p.m->z;
160
161         triangle->norm[0] = pa[1] * pb[2] - pa[2] * pb[1];
162         triangle->norm[1] = pa[2] * pb[0] - pa[0] * pb[2];
163         triangle->norm[2] = pa[0] * pb[1] - pa[1] * pb[0];
164
165         double total = sqrt(triangle->norm[0] * triangle->norm[0] +
166                             triangle->norm[1] * triangle->norm[1] +
167                             triangle->norm[2] * triangle->norm[2]);
168
169         triangle->norm[0] /= total;
170         triangle->norm[1] /= total;
171         triangle->norm[2] /= total;
172
173         /* Store bounding box, for get_intersect */
174         RoamPoint *p[] = {l,m,r};
175         triangle->edge.n =  -90; triangle->edge.s =  90;
176         triangle->edge.e = -180; triangle->edge.w = 180;
177         gboolean maxed = FALSE;
178         for (int i = 0; i < G_N_ELEMENTS(p); i++) {
179                 triangle->edge.n = MAX(triangle->edge.n, p[i]->lat);
180                 triangle->edge.s = MIN(triangle->edge.s, p[i]->lat);
181                 if (p[i]->lat == 90 || p[i]->lat == -90)
182                         continue;
183                 if (p[i]->lon == 180) {
184                         maxed = TRUE;
185                         continue;
186                 }
187                 triangle->edge.e = MAX(triangle->edge.e, p[i]->lon);
188                 triangle->edge.w = MIN(triangle->edge.w, p[i]->lon);
189         }
190         if (maxed) {
191                 if (triangle->edge.e < 0)
192                         triangle->edge.w = -180;
193                 else
194                         triangle->edge.e =  180;
195         }
196
197         //g_message("roam_triangle_new: %p", triangle);
198         return triangle;
199 }
200
201 void roam_triangle_free(RoamTriangle *triangle)
202 {
203         g_free(triangle->split);
204         g_free(triangle);
205 }
206
207 void roam_triangle_add(RoamTriangle *triangle,
208                 RoamTriangle *left, RoamTriangle *base, RoamTriangle *right,
209                 RoamSphere *sphere)
210 {
211         triangle->t.l = left;
212         triangle->t.b = base;
213         triangle->t.r = right;
214
215         roam_point_add_triangle(triangle->p.l, triangle);
216         roam_point_add_triangle(triangle->p.m, triangle);
217         roam_point_add_triangle(triangle->p.r, triangle);
218
219         if (sphere->view)
220                 roam_triangle_update_errors(triangle, sphere);
221
222         triangle->handle = g_pqueue_push(sphere->triangles, triangle);
223 }
224
225 void roam_triangle_remove(RoamTriangle *triangle, RoamSphere *sphere)
226 {
227         /* Update vertex normals */
228         roam_point_remove_triangle(triangle->p.l, triangle);
229         roam_point_remove_triangle(triangle->p.m, triangle);
230         roam_point_remove_triangle(triangle->p.r, triangle);
231
232         g_pqueue_remove(sphere->triangles, triangle->handle);
233 }
234
235 static void roam_triangle_sync_neighbors(RoamTriangle *new, RoamTriangle *old, RoamTriangle *neigh)
236 {
237         if      (neigh->t.l == old) neigh->t.l = new;
238         else if (neigh->t.b == old) neigh->t.b = new;
239         else if (neigh->t.r == old) neigh->t.r = new;
240         else g_assert_not_reached();
241 }
242
243 static gboolean roam_point_visible(RoamPoint *triangle, RoamSphere *sphere)
244 {
245         gint *view = sphere->view->view;
246         return triangle->px > view[0] && triangle->px < view[2] &&
247                triangle->py > view[1] && triangle->py < view[3] &&
248                triangle->pz > 0       && triangle->pz < 1;
249 }
250 static gboolean roam_triangle_visible(RoamTriangle *triangle, RoamSphere *sphere)
251 {
252         /* Do this with a bounding box */
253         return roam_point_visible(triangle->p.l, sphere) ||
254                roam_point_visible(triangle->p.m, sphere) ||
255                roam_point_visible(triangle->p.r, sphere);
256 }
257
258 void roam_triangle_update_errors(RoamTriangle *triangle, RoamSphere *sphere)
259 {
260         /* Update points */
261         roam_point_update_projection(triangle->p.l, sphere->view);
262         roam_point_update_projection(triangle->p.m, sphere->view);
263         roam_point_update_projection(triangle->p.r, sphere->view);
264
265         /* Not exactly correct, could be out on both sides (middle in) */
266         if (!roam_triangle_visible(triangle, sphere)) {
267                 triangle->error = -1;
268         } else {
269                 roam_point_update_projection(triangle->split, sphere->view);
270                 RoamPoint *l = triangle->p.l;
271                 RoamPoint *m = triangle->p.m;
272                 RoamPoint *r = triangle->p.r;
273                 RoamPoint *split = triangle->split;
274
275                 /*               l-r midpoint        projected l-r midpoint */
276                 gdouble pxdist = (l->px + r->px)/2 - split->px;
277                 gdouble pydist = (l->py + r->py)/2 - split->py;
278
279                 triangle->error = sqrt(pxdist*pxdist + pydist*pydist);
280
281                 /* Multiply by size of triangle */
282                 double size = -( l->px * (m->py - r->py) +
283                                  m->px * (r->py - l->py) +
284                                  r->px * (l->py - m->py) ) / 2.0;
285
286                 /* Size < 0 == backface */
287                 //if (size < 0)
288                 //      triangle->error *= -1;
289                 triangle->error *= size;
290         }
291 }
292
293 void roam_triangle_split(RoamTriangle *triangle, RoamSphere *sphere)
294 {
295         //g_message("roam_triangle_split: %p, e=%f\n", triangle, triangle->error);
296
297         sphere->polys += 2;
298
299         if (triangle != triangle->t.b->t.b)
300                 roam_triangle_split(triangle->t.b, sphere);
301         if (triangle != triangle->t.b->t.b)
302                 g_assert_not_reached();
303
304         RoamTriangle *base = triangle->t.b;
305
306         /* Add new triangles */
307         RoamPoint *mid = triangle->split;
308         RoamTriangle *sl = triangle->kids[0] = roam_triangle_new(triangle->p.m, mid, triangle->p.l); // triangle Left
309         RoamTriangle *sr = triangle->kids[1] = roam_triangle_new(triangle->p.r, mid, triangle->p.m); // triangle Right
310         RoamTriangle *bl = base->kids[0] = roam_triangle_new(base->p.m, mid, base->p.l); // Base Left
311         RoamTriangle *br = base->kids[1] = roam_triangle_new(base->p.r, mid, base->p.m); // Base Right
312
313         /*                triangle,l,  base,      r,  sphere */
314         roam_triangle_add(sl, sr, triangle->t.l, br, sphere);
315         roam_triangle_add(sr, bl, triangle->t.r, sl, sphere);
316         roam_triangle_add(bl, br, base->t.l, sr, sphere);
317         roam_triangle_add(br, sl, base->t.r, bl, sphere);
318
319         roam_triangle_sync_neighbors(sl, triangle, triangle->t.l);
320         roam_triangle_sync_neighbors(sr, triangle, triangle->t.r);
321         roam_triangle_sync_neighbors(bl, base, base->t.l);
322         roam_triangle_sync_neighbors(br, base, base->t.r);
323
324         /* Remove old triangles */
325         roam_triangle_remove(triangle, sphere);
326         roam_triangle_remove(base, sphere);
327
328         /* Add/Remove diamonds */
329         RoamDiamond *diamond = roam_diamond_new(triangle, base, sl, sr, bl, br);
330         roam_diamond_update_errors(diamond, sphere);
331         roam_diamond_add(diamond, sphere);
332         roam_diamond_remove(triangle->parent, sphere);
333         roam_diamond_remove(base->parent, sphere);
334 }
335
336 void roam_triangle_draw(RoamTriangle *triangle)
337 {
338         glBegin(GL_TRIANGLES);
339         glNormal3dv(triangle->p.r->norm); glVertex3dv((double*)triangle->p.r);
340         glNormal3dv(triangle->p.m->norm); glVertex3dv((double*)triangle->p.m);
341         glNormal3dv(triangle->p.l->norm); glVertex3dv((double*)triangle->p.l);
342         glEnd();
343         return;
344 }
345
346 void roam_triangle_draw_normal(RoamTriangle *triangle)
347 {
348         double center[] = {
349                 (triangle->p.l->x + triangle->p.m->x + triangle->p.r->x)/3.0,
350                 (triangle->p.l->y + triangle->p.m->y + triangle->p.r->y)/3.0,
351                 (triangle->p.l->z + triangle->p.m->z + triangle->p.r->z)/3.0,
352         };
353         double end[] = {
354                 center[0]+triangle->norm[0]*2000000,
355                 center[1]+triangle->norm[1]*2000000,
356                 center[2]+triangle->norm[2]*2000000,
357         };
358         glBegin(GL_LINES);
359         glVertex3dv(center);
360         glVertex3dv(end);
361         glEnd();
362 }
363
364 /***************
365  * RoamDiamond *
366  ***************/
367 RoamDiamond *roam_diamond_new(
368                 RoamTriangle *parent0, RoamTriangle *parent1,
369                 RoamTriangle *kid0, RoamTriangle *kid1,
370                 RoamTriangle *kid2, RoamTriangle *kid3)
371 {
372         RoamDiamond *diamond = g_new0(RoamDiamond, 1);
373
374         diamond->kids[0] = kid0;
375         diamond->kids[1] = kid1;
376         diamond->kids[2] = kid2;
377         diamond->kids[3] = kid3;
378
379         kid0->parent = diamond;
380         kid1->parent = diamond;
381         kid2->parent = diamond;
382         kid3->parent = diamond;
383
384         diamond->parents[0] = parent0;
385         diamond->parents[1] = parent1;
386
387         return diamond;
388 }
389 void roam_diamond_add(RoamDiamond *diamond, RoamSphere *sphere)
390 {
391         diamond->active = TRUE;
392         diamond->error  = MAX(diamond->parents[0]->error, diamond->parents[1]->error);
393         diamond->handle = g_pqueue_push(sphere->diamonds, diamond);
394 }
395 void roam_diamond_remove(RoamDiamond *diamond, RoamSphere *sphere)
396 {
397         if (diamond && diamond->active) {
398                 diamond->active = FALSE;
399                 g_pqueue_remove(sphere->diamonds, diamond->handle);
400         }
401 }
402 void roam_diamond_merge(RoamDiamond *diamond, RoamSphere *sphere)
403 {
404         //g_message("roam_diamond_merge: %p, e=%f\n", diamond, diamond->error);
405
406         sphere->polys -= 2;
407
408         /* TODO: pick the best split */
409         RoamTriangle **kids = diamond->kids;
410
411         /* Create triangles */
412         RoamTriangle *triangle  = diamond->parents[0];
413         RoamTriangle *base = diamond->parents[1];
414
415         roam_triangle_add(triangle,  kids[0]->t.b, base, kids[1]->t.b, sphere);
416         roam_triangle_add(base, kids[2]->t.b, triangle,  kids[3]->t.b, sphere);
417
418         roam_triangle_sync_neighbors(triangle,  kids[0], kids[0]->t.b);
419         roam_triangle_sync_neighbors(triangle,  kids[1], kids[1]->t.b);
420         roam_triangle_sync_neighbors(base, kids[2], kids[2]->t.b);
421         roam_triangle_sync_neighbors(base, kids[3], kids[3]->t.b);
422
423         /* Remove triangles */
424         roam_triangle_remove(kids[0], sphere);
425         roam_triangle_remove(kids[1], sphere);
426         roam_triangle_remove(kids[2], sphere);
427         roam_triangle_remove(kids[3], sphere);
428
429         /* Clear kids */
430         triangle->kids[0]  = triangle->kids[1]  = NULL;
431         base->kids[0] = base->kids[1] = NULL;
432
433         /* Add/Remove triangles */
434         if (triangle->t.l->t.l == triangle->t.r->t.r &&
435             triangle->t.l->t.l != triangle && triangle->parent) {
436                 roam_diamond_update_errors(triangle->parent, sphere);
437                 roam_diamond_add(triangle->parent, sphere);
438         }
439
440         if (base->t.l->t.l == base->t.r->t.r &&
441             base->t.l->t.l != base && base->parent) {
442                 roam_diamond_update_errors(base->parent, sphere);
443                 roam_diamond_add(base->parent, sphere);
444         }
445
446         /* Remove and free diamond and child triangles */
447         roam_diamond_remove(diamond, sphere);
448         g_assert(diamond->kids[0]->p.m == diamond->kids[1]->p.m &&
449                  diamond->kids[1]->p.m == diamond->kids[2]->p.m &&
450                  diamond->kids[2]->p.m == diamond->kids[3]->p.m);
451         g_assert(diamond->kids[0]->p.m->tris == 0);
452         roam_triangle_free(diamond->kids[0]);
453         roam_triangle_free(diamond->kids[1]);
454         roam_triangle_free(diamond->kids[2]);
455         roam_triangle_free(diamond->kids[3]);
456         g_free(diamond);
457 }
458 void roam_diamond_update_errors(RoamDiamond *diamond, RoamSphere *sphere)
459 {
460         roam_triangle_update_errors(diamond->parents[0], sphere);
461         roam_triangle_update_errors(diamond->parents[1], sphere);
462         diamond->error = MAX(diamond->parents[0]->error, diamond->parents[1]->error);
463 }
464
465 /**************
466  * RoamSphere *
467  **************/
468 RoamSphere *roam_sphere_new()
469 {
470         RoamSphere *sphere = g_new0(RoamSphere, 1);
471         sphere->polys       = 8;
472         sphere->triangles   = g_pqueue_new((GCompareDataFunc)tri_cmp, NULL);
473         sphere->diamonds    = g_pqueue_new((GCompareDataFunc)dia_cmp, NULL);
474
475         RoamPoint *vertexes[] = {
476                 roam_point_new( 90,   0,  0), // 0 (North)
477                 roam_point_new(-90,   0,  0), // 1 (South)
478                 roam_point_new(  0,   0,  0), // 2 (Europe/Africa)
479                 roam_point_new(  0,  90,  0), // 3 (Asia,East)
480                 roam_point_new(  0, 180,  0), // 4 (Pacific)
481                 roam_point_new(  0, -90,  0), // 5 (Americas,West)
482         };
483         int _triangles[][2][3] = {
484                 /*lv mv rv   ln, bn, rn */
485                 {{2,0,3}, {3, 4, 1}}, // 0
486                 {{3,0,4}, {0, 5, 2}}, // 1
487                 {{4,0,5}, {1, 6, 3}}, // 2
488                 {{5,0,2}, {2, 7, 0}}, // 3
489                 {{3,1,2}, {5, 0, 7}}, // 4
490                 {{4,1,3}, {6, 1, 4}}, // 5
491                 {{5,1,4}, {7, 2, 5}}, // 6
492                 {{2,1,5}, {4, 3, 6}}, // 7
493         };
494
495         for (int i = 0; i < 6; i++)
496                 roam_point_update_height(vertexes[i]);
497         for (int i = 0; i < 8; i++)
498                 sphere->roots[i] = roam_triangle_new(
499                         vertexes[_triangles[i][0][0]],
500                         vertexes[_triangles[i][0][1]],
501                         vertexes[_triangles[i][0][2]]);
502         for (int i = 0; i < 8; i++)
503                 roam_triangle_add(sphere->roots[i],
504                         sphere->roots[_triangles[i][1][0]],
505                         sphere->roots[_triangles[i][1][1]],
506                         sphere->roots[_triangles[i][1][2]],
507                         sphere);
508         for (int i = 0; i < 8; i++)
509                 g_debug("RoamSphere: new - %p edge=%f,%f,%f,%f", sphere->roots[i],
510                                 sphere->roots[i]->edge.n,
511                                 sphere->roots[i]->edge.s,
512                                 sphere->roots[i]->edge.e,
513                                 sphere->roots[i]->edge.w);
514
515         return sphere;
516 }
517 void roam_sphere_update_view(RoamSphere *sphere)
518 {
519         if (!sphere->view)
520                 sphere->view = g_new0(RoamView, 1);
521         glGetDoublev (GL_MODELVIEW_MATRIX,  sphere->view->model);
522         glGetDoublev (GL_PROJECTION_MATRIX, sphere->view->proj);
523         glGetIntegerv(GL_VIEWPORT,          sphere->view->view);
524         sphere->view->version++;
525 }
526 void roam_sphere_update_errors(RoamSphere *sphere)
527 {
528         g_debug("RoamSphere: update_errors - polys=%d", sphere->polys);
529         GPtrArray *tris = g_pqueue_get_array(sphere->triangles);
530         GPtrArray *dias = g_pqueue_get_array(sphere->diamonds);
531
532         roam_sphere_update_view(sphere);
533
534         for (int i = 0; i < tris->len; i++) {
535                 RoamTriangle *triangle = tris->pdata[i];
536                 roam_triangle_update_errors(triangle, sphere);
537                 g_pqueue_priority_changed(sphere->triangles, triangle->handle);
538         }
539
540         for (int i = 0; i < dias->len; i++) {
541                 RoamDiamond *diamond = dias->pdata[i];
542                 roam_diamond_update_errors(diamond, sphere);
543                 g_pqueue_priority_changed(sphere->diamonds, diamond->handle);
544         }
545
546         g_ptr_array_free(tris, TRUE);
547         g_ptr_array_free(dias, TRUE);
548 }
549
550 void roam_sphere_split_one(RoamSphere *sphere)
551 {
552         RoamTriangle *to_split = g_pqueue_peek(sphere->triangles);
553         if (!to_split) return;
554         roam_triangle_split(to_split, sphere);
555 }
556 void roam_sphere_merge_one(RoamSphere *sphere)
557 {
558         RoamDiamond *to_merge = g_pqueue_peek(sphere->diamonds);
559         if (!to_merge) return;
560         roam_diamond_merge(to_merge, sphere);
561 }
562 gint roam_sphere_split_merge(RoamSphere *sphere)
563 {
564         gint iters = 0, max_iters = 500;
565         //gint target = 4000;
566         gint target = 2000;
567         //gint target = 500;
568
569         if (!sphere->view)
570                 return 0;
571
572         if (target - sphere->polys > 100) {
573                 //g_debug("RoamSphere: split_merge - Splitting %d - %d > 100", target, sphere->polys);
574                 while (sphere->polys < target && iters++ < max_iters)
575                         roam_sphere_split_one(sphere);
576         }
577
578         if (sphere->polys - target > 100) {
579                 //g_debug("RoamSphere: split_merge - Merging %d - %d > 100", sphere->polys, target);
580                 while (sphere->polys > target && iters++ < max_iters)
581                         roam_sphere_merge_one(sphere);
582         }
583
584         while (((RoamTriangle*)g_pqueue_peek(sphere->triangles))->error >
585                ((RoamDiamond *)g_pqueue_peek(sphere->diamonds ))->error &&
586                iters++ < max_iters) {
587                 //g_debug("RoamSphere: split_merge - Fixing 1 %f > %f && %d < %d",
588                 //              ((RoamTriangle*)g_pqueue_peek(sphere->triangles))->error,
589                 //              ((RoamDiamond *)g_pqueue_peek(sphere->diamonds ))->error,
590                 //              iters-1, max_iters);
591                 roam_sphere_merge_one(sphere);
592                 roam_sphere_split_one(sphere);
593         }
594
595         return iters;
596 }
597 void roam_sphere_draw(RoamSphere *sphere)
598 {
599         g_debug("RoamSphere: draw");
600         g_pqueue_foreach(sphere->triangles, (GFunc)roam_triangle_draw, NULL);
601 }
602 void roam_sphere_draw_normals(RoamSphere *sphere)
603 {
604         g_debug("RoamSphere: draw_normal");
605         g_pqueue_foreach(sphere->triangles, (GFunc)roam_triangle_draw_normal, NULL);
606 }
607 static GList *_roam_sphere_get_leaves(RoamTriangle *triangle, GList *list, gboolean all)
608 {
609         if (triangle->kids[0] && triangle->kids[1]) {
610                 if (all) list = g_list_prepend(list, triangle);
611                 list = _roam_sphere_get_leaves(triangle->kids[0], list, all);
612                 list = _roam_sphere_get_leaves(triangle->kids[1], list, all);
613                 return list;
614         } else {
615                 return g_list_prepend(list, triangle);
616         }
617 }
618 static GList *_roam_sphere_get_intersect_rec(RoamTriangle *triangle, GList *list,
619                 gboolean all, gdouble n, gdouble s, gdouble e, gdouble w)
620 {
621         gdouble tn = triangle->edge.n;
622         gdouble ts = triangle->edge.s;
623         gdouble te = triangle->edge.e;
624         gdouble tw = triangle->edge.w;
625
626         gboolean debug = FALSE  &&
627                 n==90 && s==45 && e==-90 && w==-180 &&
628                 ts > 44 && ts < 46;
629
630         if (debug)
631                 g_message("t=%p: %f < %f || %f > %f || %f < %f || %f > %f",
632                             triangle, tn,   s,   ts,   n,   te,   w,   tw,   e);
633         if (tn < s || ts > n || te < w || tw > e) {
634                 /* No intersect */
635                 if (debug) g_message("no intersect");
636                 return list;
637         } else if (tn <= n && ts >= s && te <= e && tw >= w) {
638                 /* Triangle is completely contained */
639                 if (debug) g_message("contained");
640                 if (all) list = g_list_prepend(list, triangle);
641                 return _roam_sphere_get_leaves(triangle, list, all);
642         } else if (triangle->kids[0] && triangle->kids[1]) {
643                 /* Paritial intersect with children */
644                 if (debug) g_message("edge w/ child");
645                 if (all) list = g_list_prepend(list, triangle);
646                 list = _roam_sphere_get_intersect_rec(triangle->kids[0], list, all, n, s, e, w);
647                 list = _roam_sphere_get_intersect_rec(triangle->kids[1], list, all, n, s, e, w);
648                 return list;
649         } else {
650                 /* This triangle is an edge case */
651                 if (debug) g_message("edge");
652                 return g_list_prepend(list, triangle);
653         }
654 }
655 /* Warning: This grabs pointers to triangles which can be changed by other
656  * calls, e.g. split_merge. If you use this, you need to do some locking to
657  * prevent the returned list from becomming stale. */
658 GList *roam_sphere_get_intersect(RoamSphere *sphere, gboolean all,
659                 gdouble n, gdouble s, gdouble e, gdouble w)
660 {
661         /* I think this is correct..
662          * i_cost = cost for triangle-rectagnle intersect test
663          * time = n_tiles * 2*tris_per_tile * i_cost
664          * time = 30      * 2*333           * i_cost = 20000 * i_cost */
665         GList *list = NULL;
666         for (int i = 0; i < G_N_ELEMENTS(sphere->roots); i++)
667                 list = _roam_sphere_get_intersect_rec(sphere->roots[i],
668                                 list, all, n, s, e, w);
669         return list;
670 }
671
672 static void roam_sphere_free_tri(RoamTriangle *triangle)
673 {
674         if (--triangle->p.l->tris == 0) g_free(triangle->p.l);
675         if (--triangle->p.m->tris == 0) g_free(triangle->p.m);
676         if (--triangle->p.r->tris == 0) g_free(triangle->p.r);
677         roam_triangle_free(triangle);
678 }
679 void roam_sphere_free(RoamSphere *sphere)
680 {
681         g_debug("RoamSphere: free");
682         /* Slow method, but it should work */
683         while (sphere->polys > 8)
684                 roam_sphere_merge_one(sphere);
685         /* TODO: free points */
686         g_pqueue_foreach(sphere->triangles, (GFunc)roam_sphere_free_tri, NULL);
687         g_pqueue_free(sphere->triangles);
688         g_pqueue_free(sphere->diamonds);
689         g_free(sphere->view);
690         g_free(sphere);
691 }