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