]> Pileus Git - grits/blob - src/objects/grits-tile.c
61ed0228c56545d31cfdb57e17d0134ac853101f
[grits] / src / objects / grits-tile.c
1 /*
2  * Copyright (C) 2009-2010, 2012 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:grits-tile
20  * @short_description: Latitude/longitude overlays
21  *
22  * Each #GritsTile corresponds to a latitude/longitude box on the surface of
23  * the earth. When drawn, the #GritsTile renders an images associated with it
24  * to the surface of the earth. This is primarily used to draw ground overlays.
25  *
26  * Each GritsTile can be split into subtiles in order to draw higher resolution
27  * overlays. Pointers to subtitles are stored in the parent tile and a parent
28  * pointer is stored in each child.
29  *
30  * Each #GritsTile has a data filed which must be set by the user in order for
31  * the tile to be drawn. When used with GritsOpenGL the data must be an integer
32  * representing the OpenGL texture to use when drawing the tile.
33  */
34
35 #include <config.h>
36 #include <math.h>
37 #include "gtkgl.h"
38 #include "grits-tile.h"
39
40 #ifdef SYS_WIN
41 #define GL_GLEXT_PROTOTYPES
42 #include <GL/glext.h>
43 #endif
44
45 guint  grits_tile_mask = 0;
46
47 gchar *grits_tile_path_table[2][2] = {
48         {"00.", "01."},
49         {"10.", "11."},
50 };
51
52 /**
53  * grits_tile_new:
54  * @parent: the parent for the tile, or NULL
55  * @n:      the northern border of the tile
56  * @s:      the southern border of the tile
57  * @e:      the eastern border of the tile
58  * @w:      the western border of the tile
59  *
60  * Create a tile associated with a particular latitude/longitude box.
61  *
62  * Returns: the new #GritsTile
63  */
64 GritsTile *grits_tile_new(GritsTile *parent,
65         gdouble n, gdouble s, gdouble e, gdouble w)
66 {
67         GritsTile *tile = g_object_new(GRITS_TYPE_TILE, NULL);
68         tile->parent = parent;
69         tile->atime  = time(NULL);
70         grits_bounds_set_bounds(&tile->coords, 0, 1, 1, 0);
71         grits_bounds_set_bounds(&tile->edge, n, s, e, w);
72         if (parent)
73                 tile->proj   = parent->proj;
74         return tile;
75 }
76
77 /**
78  * grits_tile_get_path:
79  * @child: the tile to generate a path for
80  *
81  * Generate a string representation of a tiles location in a group of nested
82  * tiles. The string returned consists of groups of two digits separated by a
83  * delimiter. Each group of digits the tiles location with respect to it's
84  * parent tile.
85  *
86  * Returns: the path representing the tiles's location
87  */
88 gchar *grits_tile_get_path(GritsTile *child)
89 {
90         /* This could be easily cached if necessary */
91         int x, y;
92         GList *parts = NULL;
93         for (GritsTile *parent = child->parent; parent; child = parent, parent = child->parent)
94                 grits_tile_foreach_index(child, x, y)
95                         if (parent->children[x][y] == child)
96                                 parts = g_list_prepend(parts, grits_tile_path_table[x][y]);
97         GString *path = g_string_new("");
98         for (GList *cur = parts; cur; cur = cur->next)
99                 g_string_append(path, cur->data);
100         g_list_free(parts);
101         return g_string_free(path, FALSE);
102 }
103
104 static gdouble _grits_tile_get_min_dist(GritsPoint *eye, GritsBounds *bounds)
105 {
106         GritsPoint pos = {};
107         pos.lat = eye->lat > bounds->n ? bounds->n :
108                   eye->lat < bounds->s ? bounds->s : eye->lat;
109         pos.lon = eye->lon > bounds->e ? bounds->e :
110                   eye->lon < bounds->w ? bounds->w : eye->lon;
111         //if (eye->lat == pos.lat && eye->lon == pos.lon)
112         //      return elev; /* Shortcut? */
113         gdouble a[3], b[3];
114         lle2xyz(eye->lat, eye->lon, eye->elev, a+0, a+1, a+2);
115         lle2xyz(pos.lat,  pos.lon,  pos.elev,  b+0, b+1, b+2);
116         return distd(a, b);
117 }
118
119 static gboolean _grits_tile_precise(GritsPoint *eye, GritsBounds *bounds,
120                 gdouble max_res, gint width, gint height)
121 {
122         gdouble min_dist  = _grits_tile_get_min_dist(eye, bounds);
123         gdouble view_res  = MPPX(min_dist);
124
125         gdouble lat_point = bounds->n < 0 ? bounds->n :
126                             bounds->s > 0 ? bounds->s : 0;
127         gdouble lon_dist  = bounds->e - bounds->w;
128         gdouble tile_res  = ll2m(lon_dist, lat_point)/width;
129
130         /* This isn't really right, but it helps with memory since we don't
131          * (yet?) test if the tile would be drawn */
132         gdouble scale = eye->elev / min_dist;
133         view_res /= scale;
134         view_res *= 1.8;
135         //view_res /= 1.4; /* make it a little nicer, not sure why this is needed */
136         //g_message("tile=(%7.2f %7.2f %7.2f %7.2f) "
137         //          "eye=(%9.1f %9.1f %9.1f) "
138         //          "elev=%9.1f / dist=%9.1f = %f",
139         //              bounds->n, bounds->s, bounds->e, bounds->w,
140         //              eye->lat, eye->lon, eye->elev,
141         //              eye->elev, min_dist, scale);
142
143         return tile_res < max_res ||
144                tile_res < view_res;
145 }
146
147 static void _grits_tile_split_latlon(GritsTile *tile)
148 {
149         //g_debug("GritsTile: split - %p", tile);
150         const gdouble rows = G_N_ELEMENTS(tile->children);
151         const gdouble cols = G_N_ELEMENTS(tile->children[0]);
152         const gdouble lat_dist = tile->edge.n - tile->edge.s;
153         const gdouble lon_dist = tile->edge.e - tile->edge.w;
154         const gdouble lat_step = lat_dist / rows;
155         const gdouble lon_step = lon_dist / cols;
156
157         int row, col;
158         grits_tile_foreach_index(tile, row, col) {
159                 if (!tile->children[row][col])
160                         tile->children[row][col] =
161                                 grits_tile_new(tile, 0, 0, 0, 0);
162                 /* Set edges aferwards so that north and south
163                  * get reset for mercator projections */
164                 GritsTile *child = tile->children[row][col];
165                 child->edge.n = tile->edge.n - lat_step*(row+0);
166                 child->edge.s = tile->edge.n - lat_step*(row+1);
167                 child->edge.e = tile->edge.w + lon_step*(col+1);
168                 child->edge.w = tile->edge.w + lon_step*(col+0);
169         }
170 }
171
172 static void _grits_tile_split_mercator(GritsTile *tile)
173 {
174         GritsTile *child = NULL;
175         GritsBounds tmp = tile->edge;
176
177         /* Project */
178         tile->edge.n = asinh(tan(deg2rad(tile->edge.n)));
179         tile->edge.s = asinh(tan(deg2rad(tile->edge.s)));
180
181         _grits_tile_split_latlon(tile);
182
183         /* Convert back to lat-lon */
184         tile->edge = tmp;
185         grits_tile_foreach(tile, child) {
186                 child->edge.n = rad2deg(atan(sinh(child->edge.n)));
187                 child->edge.s = rad2deg(atan(sinh(child->edge.s)));
188         }
189 }
190
191 /**
192  * grits_tile_update:
193  * @root:      the root tile to split
194  * @eye:       the point the tile is viewed from, for calculating distances
195  * @res:       a maximum resolution in meters per pixel to split tiles to
196  * @width:     width in pixels of the image associated with the tile
197  * @height:    height in pixels of the image associated with the tile
198  * @load_func: function used to load the image when a new tile is created
199  * @user_data: user data to past to the load function
200  *
201  * Recursively split a tile into children of appropriate detail. The resolution
202  * of the tile in pixels per meter is compared to the resolution which the tile
203  * is being drawn at on the screen. If the screen resolution is insufficient
204  * the tile is recursively subdivided until a sufficient resolution is
205  * achieved.
206  */
207 void grits_tile_update(GritsTile *tile, GritsPoint *eye,
208                 gdouble res, gint width, gint height,
209                 GritsTileLoadFunc load_func, gpointer user_data)
210 {
211         GritsTile *child;
212
213         if (tile == NULL)
214                 return;
215
216         //g_debug("GritsTile: update - %p->atime = %u",
217         //              tile, (guint)tile->atime);
218
219         /* Is the parent tile's texture high enough
220          * resolution for this part? */
221         gint xs = G_N_ELEMENTS(tile->children);
222         gint ys = G_N_ELEMENTS(tile->children[0]);
223         if (tile->parent && _grits_tile_precise(eye, &tile->edge,
224                                 res, width/xs, height/ys)) {
225                 GRITS_OBJECT(tile)->hidden = TRUE;
226                 return;
227         }
228
229         /* Load the tile */
230         if (!tile->load && !tile->data)
231                 load_func(tile, user_data);
232         tile->atime = time(NULL);
233         tile->load  = TRUE;
234         GRITS_OBJECT(tile)->hidden = FALSE;
235
236         /* Split tile if needed */
237         grits_tile_foreach(tile, child) {
238                 if (child == NULL) {
239                         switch (tile->proj) {
240                         case GRITS_PROJ_LATLON:   _grits_tile_split_latlon(tile);   break;
241                         case GRITS_PROJ_MERCATOR: _grits_tile_split_mercator(tile); break;
242                         }
243                 }
244         }
245
246         /* Update recursively */
247         grits_tile_foreach(tile, child)
248                 grits_tile_update(child, eye, res, width, height,
249                                 load_func, user_data);
250 }
251
252 /**
253  * grits_tile_find:
254  * @root: the root tile to search from
255  * @lat:  target latitude
256  * @lon:  target longitude
257  *
258  * Locate the subtile with the highest resolution which contains the given
259  * lat/lon point.
260  * 
261  * Returns: the child tile
262  */
263 GritsTile *grits_tile_find(GritsTile *root, gdouble lat, gdouble lon)
264 {
265         gint    rows = G_N_ELEMENTS(root->children);
266         gint    cols = G_N_ELEMENTS(root->children[0]);
267
268         gdouble lat_step = (root->edge.n - root->edge.s) / rows;
269         gdouble lon_step = (root->edge.e - root->edge.w) / cols;
270
271         gdouble lat_offset = root->edge.n - lat;;
272         gdouble lon_offset = lon - root->edge.w;
273
274         gint    row = lat_offset / lat_step;
275         gint    col = lon_offset / lon_step;
276
277         if (lon == 180) col--;
278         if (lat == -90) row--;
279
280         //if (lon == 180 || lon == -180)
281         //      g_message("lat=%f,lon=%f step=%f,%f off=%f,%f row=%d/%d,col=%d/%d",
282         //              lat,lon, lat_step,lon_step, lat_offset,lon_offset, row,rows,col,cols);
283
284         if (row < 0 || row >= rows || col < 0 || col >= cols)
285                 return NULL;
286         else if (root->children[row][col] && root->children[row][col]->data)
287                 return grits_tile_find(root->children[row][col], lat, lon);
288         else
289                 return root;
290 }
291
292 /**
293  * grits_tile_gc:
294  * @root:      the root tile to start garbage collection at
295  * @atime:     most recent time at which tiles will be kept
296  * @free_func: function used to free the image when a new tile is collected
297  * @user_data: user data to past to the free function
298  *
299  * Garbage collect old tiles. This removes and deallocate tiles that have not
300  * been used since before @atime.
301  *
302  * Returns: a pointer to the original tile, or NULL if it was garbage collected
303  */
304 GritsTile *grits_tile_gc(GritsTile *root, time_t atime,
305                 GritsTileFreeFunc free_func, gpointer user_data)
306 {
307         if (!root)
308                 return NULL;
309         gboolean has_children = FALSE;
310         int x, y;
311         grits_tile_foreach_index(root, x, y) {
312                 root->children[x][y] = grits_tile_gc(
313                                 root->children[x][y], atime,
314                                 free_func, user_data);
315                 if (root->children[x][y])
316                         has_children = TRUE;
317         }
318         //g_debug("GritsTile: gc - %p kids=%d time=%d data=%d load=%d",
319         //      root, !!has_children, root->atime < atime, !!root->data, !!root->load);
320         if (root->parent && !has_children && root->atime < atime &&
321                         (root->data || !root->load)) {
322                 //g_debug("GritsTile: gc/free - %p", root);
323                 if (root->data)
324                         free_func(root, user_data);
325                 g_object_unref(root);
326                 return NULL;
327         }
328         return root;
329 }
330
331 /* Use GObject for this */
332 /**
333  * grits_tile_free:
334  * @root:      the root tile to free
335  * @free_func: function used to free the image when a new tile is collected
336  * @user_data: user data to past to the free function
337  *
338  * Recursively free a tile and all it's children.
339  */
340 void grits_tile_free(GritsTile *root, GritsTileFreeFunc free_func, gpointer user_data)
341 {
342         if (!root)
343                 return;
344         GritsTile *child;
345         grits_tile_foreach(root, child)
346                 grits_tile_free(child, free_func, user_data);
347         if (free_func)
348                 free_func(root, user_data);
349         g_object_unref(root);
350 }
351
352 /* Load texture mask so we can draw a texture to just a part of a triangle */
353 static guint _grits_tile_load_mask(void)
354 {
355         guint  tex;
356         guint8 byte = 0xff;
357         glGenTextures(1, &tex);
358         glBindTexture(GL_TEXTURE_2D, tex);
359
360         glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 1, 1, 0,
361                         GL_ALPHA, GL_UNSIGNED_BYTE, &byte);
362
363         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
364         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
365
366         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
367         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
368         return tex;
369 }
370
371 /* Draw a single tile */
372 static void grits_tile_draw_one(GritsTile *tile, GritsOpenGL *opengl, GList *triangles)
373 {
374         if (!tile || !tile->data)
375                 return;
376         if (!triangles)
377                 g_warning("GritsOpenGL: _draw_tiles - No triangles to draw: edges=%f,%f,%f,%f",
378                         tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
379
380         //g_message("drawing %4d triangles for tile edges=%7.2f,%7.2f,%7.2f,%7.2f",
381         //              g_list_length(triangles), tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
382         tile->atime = time(NULL);
383
384         gdouble n = tile->edge.n;
385         gdouble s = tile->edge.s;
386         gdouble e = tile->edge.e;
387         gdouble w = tile->edge.w;
388
389         gdouble londist = e - w;
390         gdouble latdist = n - s;
391
392         gdouble xscale = tile->coords.e - tile->coords.w;
393         gdouble yscale = tile->coords.s - tile->coords.n;
394
395         glPolygonOffset(0, -tile->zindex);
396
397         for (GList *cur = triangles; cur; cur = cur->next) {
398                 RoamTriangle *tri = cur->data;
399
400                 gdouble lat[3] = {tri->p.r->lat, tri->p.m->lat, tri->p.l->lat};
401                 gdouble lon[3] = {tri->p.r->lon, tri->p.m->lon, tri->p.l->lon};
402
403                 if (lon[0] < -90 || lon[1] < -90 || lon[2] < -90) {
404                         if (lon[0] > 90) lon[0] -= 360;
405                         if (lon[1] > 90) lon[1] -= 360;
406                         if (lon[2] > 90) lon[2] -= 360;
407                 }
408
409                 gdouble xy[3][2] = {
410                         {(lon[0]-w)/londist, 1-(lat[0]-s)/latdist},
411                         {(lon[1]-w)/londist, 1-(lat[1]-s)/latdist},
412                         {(lon[2]-w)/londist, 1-(lat[2]-s)/latdist},
413                 };
414
415                 //if ((lat[0] == 90 && (xy[0][0] < 0 || xy[0][0] > 1)) ||
416                 //    (lat[1] == 90 && (xy[1][0] < 0 || xy[1][0] > 1)) ||
417                 //    (lat[2] == 90 && (xy[2][0] < 0 || xy[2][0] > 1)))
418                 //      g_message("w,e=%4.f,%4.f   "
419                 //                "lat,lon,x,y="
420                 //                "%4.1f,%4.0f,%4.2f,%4.2f   "
421                 //                "%4.1f,%4.0f,%4.2f,%4.2f   "
422                 //                "%4.1f,%4.0f,%4.2f,%4.2f   ",
423                 //              w,e,
424                 //              lat[0], lon[0], xy[0][0], xy[0][1],
425                 //              lat[1], lon[1], xy[1][0], xy[1][1],
426                 //              lat[2], lon[2], xy[2][0], xy[2][1]);
427
428                 /* Fix poles */
429                 if (lat[0] == 90 || lat[0] == -90) xy[0][0] = 0.5;
430                 if (lat[1] == 90 || lat[1] == -90) xy[1][0] = 0.5;
431                 if (lat[2] == 90 || lat[2] == -90) xy[2][0] = 0.5;
432
433                 /* Scale to tile coords */
434                 for (int i = 0; i < 3; i++) {
435                         xy[i][0] = tile->coords.w + xy[i][0]*xscale;
436                         xy[i][1] = tile->coords.n + xy[i][1]*yscale;
437                 }
438
439                 /* Draw triangle */
440                 glBindTexture(GL_TEXTURE_2D, *(guint*)tile->data);
441                 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
442                 glBegin(GL_TRIANGLES);
443                 glNormal3dv(tri->p.r->norm); glMultiTexCoord2dv(GL_TEXTURE0, xy[0]); glMultiTexCoord2dv(GL_TEXTURE1, xy[0]); glVertex3dv((double*)tri->p.r);
444                 glNormal3dv(tri->p.m->norm); glMultiTexCoord2dv(GL_TEXTURE0, xy[1]); glMultiTexCoord2dv(GL_TEXTURE1, xy[1]); glVertex3dv((double*)tri->p.m);
445                 glNormal3dv(tri->p.l->norm); glMultiTexCoord2dv(GL_TEXTURE0, xy[2]); glMultiTexCoord2dv(GL_TEXTURE1, xy[2]); glVertex3dv((double*)tri->p.l);
446                 glEnd();
447         }
448 }
449
450 /* Draw the tile */
451 static gboolean grits_tile_draw_rec(GritsTile *tile, GritsOpenGL *opengl)
452 {
453         //g_debug("GritsTile: draw_rec - tile=%p, data=%d, load=%d, hide=%d", tile,
454         //              tile ? !!tile->data : 0,
455         //              tile ? !!tile->load : 0,
456         //              tile ? !!GRITS_OBJECT(tile)->hidden : 0);
457
458         if (!tile || !tile->data || GRITS_OBJECT(tile)->hidden)
459                 return FALSE;
460
461         GritsTile *child = NULL;
462
463         /* Draw child tiles */
464         gboolean draw_parent = FALSE;
465         grits_tile_foreach(tile, child)
466                 if (!grits_tile_draw_rec(child, opengl))
467                         draw_parent = TRUE;
468
469         /* Draw parent tile underneath using depth test */
470         if (draw_parent) {
471                 GList *triangles = roam_sphere_get_intersect(opengl->sphere, FALSE,
472                                 tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
473                 grits_tile_draw_one(tile, opengl, triangles);
474                 g_list_free(triangles);
475         }
476
477         return TRUE;
478 }
479
480 static void grits_tile_draw(GritsObject *tile, GritsOpenGL *opengl)
481 {
482         glEnable(GL_DEPTH_TEST);
483         glDepthFunc(GL_LESS);
484         glEnable(GL_ALPHA_TEST);
485         glAlphaFunc(GL_GREATER, 0.1);
486         glEnable(GL_POLYGON_OFFSET_FILL);
487         glEnable(GL_BLEND);
488
489         /* Setup texture mask */
490         if (!grits_tile_mask)
491                 grits_tile_mask = _grits_tile_load_mask();
492         glActiveTexture(GL_TEXTURE1);
493         glEnable(GL_TEXTURE_2D);
494         glBindTexture(GL_TEXTURE_2D, grits_tile_mask);
495         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
496
497         /* Setup texture */
498         glActiveTexture(GL_TEXTURE0);
499         glEnable(GL_TEXTURE_2D);
500
501         /* Hack to show maps tiles with better color */
502         if (GRITS_TILE(tile)->proj == GRITS_PROJ_MERCATOR) {
503                 float material_emission[] = {0.5, 0.5, 0.5, 1.0};
504                 glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, material_emission);
505         }
506
507         /* Draw all tiles */
508         grits_tile_draw_rec(GRITS_TILE(tile), opengl);
509
510         /* Disable texture mask */
511         glActiveTexture(GL_TEXTURE1);
512         glDisable(GL_TEXTURE_2D);
513         glActiveTexture(GL_TEXTURE0);
514 }
515
516
517 /* GObject code */
518 G_DEFINE_TYPE(GritsTile, grits_tile, GRITS_TYPE_OBJECT);
519 static void grits_tile_init(GritsTile *tile)
520 {
521 }
522
523 static void grits_tile_class_init(GritsTileClass *klass)
524 {
525         g_debug("GritsTile: class_init");
526         GritsObjectClass *object_class = GRITS_OBJECT_CLASS(klass);
527         object_class->draw = grits_tile_draw;
528 }