]> Pileus Git - grits/blob - src/objects/grits-tile.c
Move OpenGL includes to a common place
[grits] / src / objects / grits-tile.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: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 "gtkgl.h"
37 #include "grits-tile.h"
38
39 gchar *grits_tile_path_table[2][2] = {
40         {"00.", "01."},
41         {"10.", "11."},
42 };
43
44 /**
45  * grits_tile_new:
46  * @parent: the parent for the tile, or NULL
47  * @n:      the northern border of the tile
48  * @s:      the southern border of the tile
49  * @e:      the eastern border of the tile
50  * @w:      the western border of the tile
51  *
52  * Create a tile associated with a particular latitude/longitude box.
53  *
54  * Returns: the new #GritsTile
55  */
56 GritsTile *grits_tile_new(GritsTile *parent,
57         gdouble n, gdouble s, gdouble e, gdouble w)
58 {
59         GritsTile *tile = g_object_new(GRITS_TYPE_TILE, NULL);
60         tile->parent = parent;
61         tile->atime  = time(NULL);
62         grits_bounds_set_bounds(&tile->coords, 0, 1, 1, 0);
63         grits_bounds_set_bounds(&tile->edge, n, s, e, w);
64         return tile;
65 }
66
67 /**
68  * grits_tile_get_path:
69  * @child: the tile to generate a path for
70  *
71  * Generate a string representation of a tiles location in a group of nested
72  * tiles. The string returned consists of groups of two digits separated by a
73  * delimiter. Each group of digits the tiles location with respect to it's
74  * parent tile.
75  *
76  * Returns: the path representing the tiles's location
77  */
78 gchar *grits_tile_get_path(GritsTile *child)
79 {
80         /* This could be easily cached if necessary */
81         int x, y;
82         GList *parts = NULL;
83         for (GritsTile *parent = child->parent; parent; child = parent, parent = child->parent)
84                 grits_tile_foreach_index(child, x, y)
85                         if (parent->children[x][y] == child)
86                                 parts = g_list_prepend(parts, grits_tile_path_table[x][y]);
87         GString *path = g_string_new("");
88         for (GList *cur = parts; cur; cur = cur->next)
89                 g_string_append(path, cur->data);
90         g_list_free(parts);
91         return g_string_free(path, FALSE);
92 }
93
94 static gdouble _grits_tile_get_min_dist(GritsPoint *eye, GritsBounds *bounds)
95 {
96         GritsPoint pos = {};
97         pos.lat = eye->lat > bounds->n ? bounds->n :
98                   eye->lat < bounds->s ? bounds->s : eye->lat;
99         pos.lon = eye->lon > bounds->e ? bounds->e :
100                   eye->lon < bounds->w ? bounds->w : eye->lon;
101         //if (eye->lat == pos.lat && eye->lon == pos.lon)
102         //      return elev; /* Shortcut? */
103         gdouble a[3], b[3];
104         lle2xyz(eye->lat, eye->lon, eye->elev, a+0, a+1, a+2);
105         lle2xyz(pos.lat,  pos.lon,  pos.elev,  b+0, b+1, b+2);
106         return distd(a, b);
107 }
108
109 static gboolean _grits_tile_precise(GritsPoint *eye, GritsBounds *bounds,
110                 gdouble max_res, gint width, gint height)
111 {
112         gdouble min_dist  = _grits_tile_get_min_dist(eye, bounds);
113         gdouble view_res  = MPPX(min_dist);
114
115         gdouble lat_point = bounds->n < 0 ? bounds->n :
116                             bounds->s > 0 ? bounds->s : 0;
117         gdouble lon_dist  = bounds->e - bounds->w;
118         gdouble tile_res  = ll2m(lon_dist, lat_point)/width;
119
120         /* This isn't really right, but it helps with memory since we don't (yet?) test if the tile
121          * would be drawn */
122         gdouble scale = eye->elev / min_dist;
123         view_res /= scale;
124         //view_res /= 1.4; /* make it a little nicer, not sure why this is needed */
125         //g_message("tile=(%7.2f %7.2f %7.2f %7.2f) "
126         //          "eye=(%9.1f %9.1f %9.1f) "
127         //          "elev=%9.1f / dist=%9.1f = %f",
128         //              tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w,
129         //              lat, lon, elev,
130         //              elev, min_dist, scale);
131
132         return tile_res < max_res ||
133                tile_res < view_res;
134 }
135
136 /**
137  * grits_tile_update:
138  * @root:      the root tile to split
139  * @eye:       the point the tile is viewed from, for calculating distances
140  * @res:       a maximum resolution in meters per pixel to split tiles to
141  * @width:     width in pixels of the image associated with the tile
142  * @height:    height in pixels of the image associated with the tile
143  * @load_func: function used to load the image when a new tile is created
144  * @user_data: user data to past to the load function
145  *
146  * Recursively split a tile into children of appropriate detail. The resolution
147  * of the tile in pixels per meter is compared to the resolution which the tile
148  * is being drawn at on the screen. If the screen resolution is insufficient
149  * the tile is recursively subdivided until a sufficient resolution is
150  * achieved.
151  */
152 void grits_tile_update(GritsTile *root, GritsPoint *eye,
153                 gdouble res, gint width, gint height,
154                 GritsTileLoadFunc load_func, gpointer user_data)
155 {
156         root->atime = time(NULL);
157         //g_debug("GritsTile: update - %p->atime = %u",
158         //              root, (guint)root->atime);
159         const gdouble rows = G_N_ELEMENTS(root->children);
160         const gdouble cols = G_N_ELEMENTS(root->children[0]);
161         const gdouble lat_dist = root->edge.n - root->edge.s;
162         const gdouble lon_dist = root->edge.e - root->edge.w;
163         const gdouble lat_step = lat_dist / rows;
164         const gdouble lon_step = lon_dist / cols;
165         int row, col;
166         grits_tile_foreach_index(root, row, col) {
167                 GritsBounds edge;
168                 edge.n = root->edge.n-(lat_step*(row+0));
169                 edge.s = root->edge.n-(lat_step*(row+1));
170                 edge.e = root->edge.w+(lon_step*(col+1));
171                 edge.w = root->edge.w+(lon_step*(col+0));
172
173                 GritsTile **child = &root->children[row][col];
174                 if (!_grits_tile_precise(eye, &edge, res,
175                                 width/cols, height/rows)) {
176                         if (!*child) {
177                                 *child = grits_tile_new(root, edge.n, edge.s,
178                                                 edge.e, edge.w);
179                                 load_func(*child, user_data);
180                         }
181                         grits_tile_update(*child, eye,
182                                         res, width, height,
183                                         load_func, user_data);
184                         GRITS_OBJECT(*child)->hidden = FALSE;
185                 } else if (*child) {
186                         GRITS_OBJECT(*child)->hidden = TRUE;
187                 }
188         }
189 }
190
191 /**
192  * grits_tile_find:
193  * @root: the root tile to search from
194  * @lat:  target latitude
195  * @lon:  target longitude
196  *
197  * Locate the subtile with the highest resolution which contains the given
198  * lat/lon point.
199  * 
200  * Returns: the child tile
201  */
202 GritsTile *grits_tile_find(GritsTile *root, gdouble lat, gdouble lon)
203 {
204         gint    rows = G_N_ELEMENTS(root->children);
205         gint    cols = G_N_ELEMENTS(root->children[0]);
206
207         gdouble lat_step = (root->edge.n - root->edge.s) / rows;
208         gdouble lon_step = (root->edge.e - root->edge.w) / cols;
209
210         gdouble lat_offset = root->edge.n - lat;;
211         gdouble lon_offset = lon - root->edge.w;
212
213         gint    row = lat_offset / lat_step;
214         gint    col = lon_offset / lon_step;
215
216         if (lon == 180) col--;
217         if (lat == -90) row--;
218
219         //if (lon == 180 || lon == -180)
220         //      g_message("lat=%f,lon=%f step=%f,%f off=%f,%f row=%d/%d,col=%d/%d",
221         //              lat,lon, lat_step,lon_step, lat_offset,lon_offset, row,rows,col,cols);
222
223         if (row < 0 || row >= rows || col < 0 || col >= cols)
224                 return NULL;
225         else if (root->children[row][col] && root->children[row][col]->data)
226                 return grits_tile_find(root->children[row][col], lat, lon);
227         else
228                 return root;
229 }
230
231 /**
232  * grits_tile_gc:
233  * @root:      the root tile to start garbage collection at
234  * @atime:     most recent time at which tiles will be kept
235  * @free_func: function used to free the image when a new tile is collected
236  * @user_data: user data to past to the free function
237  *
238  * Garbage collect old tiles. This removes and deallocate tiles that have not
239  * been used since before @atime.
240  *
241  * Returns: a pointer to the original tile, or NULL if it was garbage collected
242  */
243 GritsTile *grits_tile_gc(GritsTile *root, time_t atime,
244                 GritsTileFreeFunc free_func, gpointer user_data)
245 {
246         if (!root)
247                 return NULL;
248         gboolean has_children = FALSE;
249         int x, y;
250         grits_tile_foreach_index(root, x, y) {
251                 root->children[x][y] = grits_tile_gc(
252                                 root->children[x][y], atime,
253                                 free_func, user_data);
254                 if (root->children[x][y])
255                         has_children = TRUE;
256         }
257         //g_debug("GritsTile: gc - %p->atime=%u < atime=%u",
258         //              root, (guint)root->atime, (guint)atime);
259         if (!has_children && root->atime < atime && root->data) {
260                 free_func(root, user_data);
261                 g_object_unref(root);
262                 return NULL;
263         }
264         return root;
265 }
266
267 /* Use GObject for this */
268 /**
269  * grits_tile_free:
270  * @root:      the root tile to free
271  * @free_func: function used to free the image when a new tile is collected
272  * @user_data: user data to past to the free function
273  *
274  * Recursively free a tile and all it's children.
275  */
276 void grits_tile_free(GritsTile *root, GritsTileFreeFunc free_func, gpointer user_data)
277 {
278         if (!root)
279                 return;
280         GritsTile *child;
281         grits_tile_foreach(root, child)
282                 grits_tile_free(child, free_func, user_data);
283         if (free_func)
284                 free_func(root, user_data);
285         g_object_unref(root);
286 }
287
288 /* Draw a single tile */
289 static void grits_tile_draw_one(GritsTile *tile, GritsOpenGL *opengl, GList *triangles)
290 {
291         if (!tile || !tile->data)
292                 return;
293         if (!triangles)
294                 g_warning("GritsOpenGL: _draw_tiles - No triangles to draw: edges=%f,%f,%f,%f",
295                         tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
296         //g_message("drawing %4d triangles for tile edges=%7.2f,%7.2f,%7.2f,%7.2f",
297         //              g_list_length(triangles), tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
298         tile->atime = time(NULL);
299
300         gdouble n = tile->edge.n;
301         gdouble s = tile->edge.s;
302         gdouble e = tile->edge.e;
303         gdouble w = tile->edge.w;
304
305         gdouble londist = e - w;
306         gdouble latdist = n - s;
307
308         gdouble xscale = tile->coords.e - tile->coords.w;
309         gdouble yscale = tile->coords.s - tile->coords.n;
310
311         for (GList *cur = triangles; cur; cur = cur->next) {
312                 RoamTriangle *tri = cur->data;
313
314                 gdouble lat[3] = {tri->p.r->lat, tri->p.m->lat, tri->p.l->lat};
315                 gdouble lon[3] = {tri->p.r->lon, tri->p.m->lon, tri->p.l->lon};
316
317                 if (lon[0] < -90 || lon[1] < -90 || lon[2] < -90) {
318                         if (lon[0] > 90) lon[0] -= 360;
319                         if (lon[1] > 90) lon[1] -= 360;
320                         if (lon[2] > 90) lon[2] -= 360;
321                 }
322
323                 gdouble xy[3][2] = {
324                         {(lon[0]-w)/londist, 1-(lat[0]-s)/latdist},
325                         {(lon[1]-w)/londist, 1-(lat[1]-s)/latdist},
326                         {(lon[2]-w)/londist, 1-(lat[2]-s)/latdist},
327                 };
328
329                 //if ((lat[0] == 90 && (xy[0][0] < 0 || xy[0][0] > 1)) ||
330                 //    (lat[1] == 90 && (xy[1][0] < 0 || xy[1][0] > 1)) ||
331                 //    (lat[2] == 90 && (xy[2][0] < 0 || xy[2][0] > 1)))
332                 //      g_message("w,e=%4.f,%4.f   "
333                 //                "lat,lon,x,y="
334                 //                "%4.1f,%4.0f,%4.2f,%4.2f   "
335                 //                "%4.1f,%4.0f,%4.2f,%4.2f   "
336                 //                "%4.1f,%4.0f,%4.2f,%4.2f   ",
337                 //              w,e,
338                 //              lat[0], lon[0], xy[0][0], xy[0][1],
339                 //              lat[1], lon[1], xy[1][0], xy[1][1],
340                 //              lat[2], lon[2], xy[2][0], xy[2][1]);
341
342                 /* Fix poles */
343                 if (lat[0] == 90 || lat[0] == -90) xy[0][0] = 0.5;
344                 if (lat[1] == 90 || lat[1] == -90) xy[1][0] = 0.5;
345                 if (lat[2] == 90 || lat[2] == -90) xy[2][0] = 0.5;
346
347                 /* Scale to tile coords */
348                 for (int i = 0; i < 3; i++) {
349                         xy[i][0] = tile->coords.w + xy[i][0]*xscale;
350                         xy[i][1] = tile->coords.n + xy[i][1]*yscale;
351                 }
352
353                 glEnable(GL_TEXTURE_2D);
354                 glEnable(GL_POLYGON_OFFSET_FILL);
355                 glBindTexture(GL_TEXTURE_2D, *(guint*)tile->data);
356                 glPolygonOffset(0, -tile->zindex);
357                 glBegin(GL_TRIANGLES);
358                 glNormal3dv(tri->p.r->norm); glTexCoord2dv(xy[0]); glVertex3dv((double*)tri->p.r);
359                 glNormal3dv(tri->p.m->norm); glTexCoord2dv(xy[1]); glVertex3dv((double*)tri->p.m);
360                 glNormal3dv(tri->p.l->norm); glTexCoord2dv(xy[2]); glVertex3dv((double*)tri->p.l);
361                 glEnd();
362         }
363 }
364
365 /* Draw the tile */
366 static void grits_tile_draw_rec(GritsTile *tile, GritsOpenGL *opengl)
367 {
368         /* Only draw children if possible */
369         gboolean has_children = FALSE;
370         GritsTile *child;
371         grits_tile_foreach(tile, child)
372                 if (child && child->data)
373                         has_children = TRUE;
374
375         GList *triangles = NULL;
376         if (has_children && !GRITS_OBJECT(tile)->hidden) {
377                 /* TODO: simplify this */
378                 const gdouble rows = G_N_ELEMENTS(tile->children);
379                 const gdouble cols = G_N_ELEMENTS(tile->children[0]);
380                 const gdouble lat_dist = tile->edge.n - tile->edge.s;
381                 const gdouble lon_dist = tile->edge.e - tile->edge.w;
382                 const gdouble lat_step = lat_dist / rows;
383                 const gdouble lon_step = lon_dist / cols;
384                 int row, col;
385                 grits_tile_foreach_index(tile, row, col) {
386                         GritsTile *child = tile->children[row][col];
387                         if (child && child->data) {
388                                 grits_tile_draw_rec(child, opengl);
389                         } else {
390                                 const gdouble n = tile->edge.n-(lat_step*(row+0));
391                                 const gdouble s = tile->edge.n-(lat_step*(row+1));
392                                 const gdouble e = tile->edge.w+(lon_step*(col+1));
393                                 const gdouble w = tile->edge.w+(lon_step*(col+0));
394                                 GList *these = roam_sphere_get_intersect(opengl->sphere,
395                                                 FALSE, n, s, e, w);
396                                 triangles = g_list_concat(triangles, these);
397                         }
398                 }
399         } else {
400                 triangles = roam_sphere_get_intersect(opengl->sphere, FALSE,
401                                 tile->edge.n, tile->edge.s, tile->edge.e, tile->edge.w);
402         }
403         if (triangles)
404                 grits_tile_draw_one(tile, opengl, triangles);
405         g_list_free(triangles);
406 }
407
408 static void grits_tile_draw(GritsObject *tile, GritsOpenGL *opengl)
409 {
410         glEnable(GL_DEPTH_TEST);
411         glDepthFunc(GL_LESS);
412         grits_tile_draw_rec(GRITS_TILE(tile), opengl);
413 }
414
415
416 /* GObject code */
417 G_DEFINE_TYPE(GritsTile, grits_tile, GRITS_TYPE_OBJECT);
418 static void grits_tile_init(GritsTile *tile)
419 {
420 }
421
422 static void grits_tile_class_init(GritsTileClass *klass)
423 {
424         g_debug("GritsTile: class_init");
425         GritsObjectClass *object_class = GRITS_OBJECT_CLASS(klass);
426         object_class->draw = grits_tile_draw;
427 }