Implemented smooth centering feature
[situare] / src / map / mapengine.cpp
1 /*
2    Situare - A location system for Facebook
3    Copyright (C) 2010  Ixonos Plc. Authors:
4
5        Sami Rämö - sami.ramo@ixonos.com
6        Jussi Laitinen - jussi.laitinen@ixonos.com
7        Pekka Nissinen - pekka.nissinen@ixonos.com
8        Ville Tiensuu - ville.tiensuu@ixonos.com
9
10    Situare is free software; you can redistribute it and/or
11    modify it under the terms of the GNU General Public License
12    version 2 as published by the Free Software Foundation.
13
14    Situare is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with Situare; if not, write to the Free Software
21    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
22    USA.
23 */
24
25 #include <QtAlgorithms>
26 #include <QDebug>
27 #include <QString>
28 #include <QStringList>
29 #include <QUrl>
30 #include <QHash>
31 #include <QHashIterator>
32 #include <QRect>
33
34 #include "common.h"
35 #include "frienditemshandler.h"
36 #include "gpslocationitem.h"
37 #include "mapcommon.h"
38 #include "mapfetcher.h"
39 #include "mapscene.h"
40 #include "mapscroller.h"
41 #include "maptile.h"
42 #include "network/networkaccessmanager.h"
43 #include "ownlocationitem.h"
44 #include "user/user.h"
45
46 #include "mapengine.h"
47
48 const int SMOOTH_CENTERING_TIME_MS = 1000;
49
50 MapEngine::MapEngine(QObject *parent)
51     : QObject(parent),
52       m_autoCenteringEnabled(false),
53       m_zoomedIn(false),
54       m_zoomLevel(DEFAULT_ZOOM_LEVEL),
55       m_centerTile(QPoint(UNDEFINED, UNDEFINED)),
56       m_lastManualPosition(QPoint(0, 0)),
57       m_tilesGridSize(QSize(0, 0)),
58       m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
59 {
60     qDebug() << __PRETTY_FUNCTION__;
61
62     m_mapScene = new MapScene(this);
63
64     m_mapFetcher = new MapFetcher(NetworkAccessManager::instance(), this);
65     connect(this, SIGNAL(fetchImage(int, int, int)),
66             m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
67     connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
68             this, SLOT(mapImageReceived(int, int, int, QPixmap)));
69     connect(m_mapFetcher, SIGNAL(error(int)),
70             this, SIGNAL(error(int)));
71
72     m_ownLocation = new OwnLocationItem();
73     m_ownLocation->hide(); // hide until first location info is received
74     m_mapScene->addItem(m_ownLocation);
75
76     m_gpsLocationItem = new GPSLocationItem();
77     m_mapScene->addItem(m_gpsLocationItem);
78
79     m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
80     connect(this, SIGNAL(zoomLevelChanged(int)),
81             m_friendItemsHandler, SLOT(refactorFriendItems(int)));
82
83     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
84             m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
85
86     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
87             this, SLOT(friendsPositionsUpdated()));
88
89     connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
90             this, SIGNAL(locationItemClicked(QList<QString>)));
91
92     m_scroller = &MapScroller::getInstance();
93
94     connect(m_scroller, SIGNAL(coordinateUpdated(QPoint)),
95             this, SLOT(setCenterPosition(QPoint)));
96 }
97
98 MapEngine::~MapEngine()
99 {
100     qDebug() << __PRETTY_FUNCTION__;
101
102     QSettings settings(DIRECTORY_NAME, FILE_NAME);
103     settings.setValue(MAP_LAST_POSITION,
104                       convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate));
105     settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
106 }
107
108 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
109 {
110     qDebug() << __PRETTY_FUNCTION__;
111
112     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
113
114     QPoint topLeft;
115     topLeft.setX(tileCoordinate.x() - (m_tilesGridSize.width() / 2));
116     topLeft.setY(tileCoordinate.y() - (m_tilesGridSize.height() / 2));
117
118     return QRect(topLeft, m_tilesGridSize);
119 }
120
121 QPointF MapEngine::centerGeoCoordinate()
122 {
123     qDebug() << __PRETTY_FUNCTION__;
124
125     return convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate);
126 }
127
128 void MapEngine::centerToCoordinates(QPointF latLonCoordinate)
129 {
130     qDebug() << __PRETTY_FUNCTION__;
131
132     QPoint scenePosition = convertLatLonToSceneCoordinate(latLonCoordinate);
133
134     m_lastManualPosition = scenePosition;
135
136     scrollToPosition(scenePosition);
137 }
138
139 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
140 {
141     qDebug() << __PRETTY_FUNCTION__;
142
143     qreal longitude = latLonCoordinate.x();
144     qreal latitude = latLonCoordinate.y();
145
146     if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
147         return QPoint(UNDEFINED, UNDEFINED);
148     if ((latitude > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
149         return QPoint(UNDEFINED, UNDEFINED);
150
151     qreal z = static_cast<qreal>(MapEngine::tilesPerSide(MAX_MAP_ZOOM_LEVEL));
152
153     qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
154     qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
155                                 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
156
157     return QPointF(x * z * TILE_SIZE_X, y * z * TILE_SIZE_Y).toPoint();
158 }
159
160 QPointF MapEngine::convertSceneCoordinateToLatLon(int zoomLevel, QPoint sceneCoordinate)
161 {
162     qDebug() << __PRETTY_FUNCTION__;
163
164     double tileFactor = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
165     double xFactor = (sceneCoordinate.x() / (TILE_SIZE_X*tileFactor));
166     double yFactor = (sceneCoordinate.y() / (TILE_SIZE_Y*tileFactor));
167
168     tileFactor = 1 << zoomLevel;
169     double longitude = xFactor / tileFactor * 360.0 - 180;
170
171     double n = M_PI - 2.0 * M_PI * yFactor / tileFactor;
172     double latitude = 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
173
174     return QPointF(longitude, latitude);
175 }
176
177 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
178 {
179     qDebug() << __PRETTY_FUNCTION__;
180
181     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
182     int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X * pow));
183     int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y * pow));
184
185     return QPoint(x, y);
186 }
187
188 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
189 {
190     qDebug() << __PRETTY_FUNCTION__;
191
192     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
193     int x = tileNumber.x() * TILE_SIZE_X * pow;
194     int y = tileNumber.y() * TILE_SIZE_Y * pow;
195
196     return QPoint(x, y);
197 }
198
199 bool MapEngine::disableAutoCentering(QPoint sceneCoordinate)
200 {
201     if (isAutoCenteringEnabled()) {
202         int zoomFactor = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
203
204         QPoint oldPixelValue = QPoint(m_lastManualPosition.x() / zoomFactor,
205                                       m_lastManualPosition.y() / zoomFactor);
206
207         QPoint newPixelValue = QPoint(sceneCoordinate.x() / zoomFactor,
208                                       sceneCoordinate.y() / zoomFactor);
209
210         if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE) ||
211             (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE))
212             return true;
213     }
214
215     return false;
216 }
217
218 void MapEngine::friendsPositionsUpdated()
219 {
220     qDebug() << __PRETTY_FUNCTION__;
221
222     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
223 }
224
225 void MapEngine::getTiles(QPoint sceneCoordinate)
226 {
227     qDebug() << __PRETTY_FUNCTION__;
228
229     m_viewTilesGrid = calculateTileGrid(sceneCoordinate);
230     updateViewTilesSceneRect();
231     m_mapScene->setTilesGrid(m_viewTilesGrid);
232
233     int topLeftX = m_viewTilesGrid.topLeft().x();
234     int topLeftY = m_viewTilesGrid.topLeft().y();
235     int bottomRightX = m_viewTilesGrid.bottomRight().x();
236     int bottomRightY = m_viewTilesGrid.bottomRight().y();
237
238     int tileMaxVal = tileMaxIndex(m_zoomLevel);
239
240     for (int x = topLeftX; x <= bottomRightX; ++x) {
241         for (int y = topLeftY; y <= bottomRightY; ++y) {
242
243             // map doesn't span in vertical direction, so y index must be inside the limits
244             if (y >= MAP_TILE_MIN_INDEX && y <= tileMaxVal) {
245                 if (!m_mapScene->tileInScene(tilePath(m_zoomLevel, x, y)))
246                     emit fetchImage(m_zoomLevel, normalize(x, MAP_TILE_MIN_INDEX, tileMaxVal), y);
247             }
248         }
249     }
250 }
251
252 void MapEngine::gpsPositionUpdate(QPointF position, qreal accuracy)
253 {
254     qDebug() << __PRETTY_FUNCTION__;
255
256     m_gpsLocationItem->updatePosition(convertLatLonToSceneCoordinate(position), accuracy);
257     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
258
259     if (m_autoCenteringEnabled)
260         centerToCoordinates(position);
261 }
262
263 qreal MapEngine::greatCircleDistance(QPointF firstLocation, QPointF secondLocation)
264 {
265     qDebug() << __PRETTY_FUNCTION__;
266
267     const qreal TORAD = (M_PI/180);
268
269     qreal dLat = (secondLocation.y() - firstLocation.y())*TORAD;
270     qreal dLon = (secondLocation.x() - firstLocation.x())*TORAD;
271     qreal a = pow(sin(dLat/2),2) + cos(firstLocation.y()*TORAD) * cos(secondLocation.y()*TORAD)
272               * pow(sin(dLon/2),2);
273     qreal c = 2 * atan2(sqrt(a), sqrt(1-a));
274
275     return (EARTH_RADIUS * c);
276 }
277
278 void MapEngine::init()
279 {
280     qDebug() << __PRETTY_FUNCTION__;
281
282     QPointF startLocation;
283     QSettings settings(DIRECTORY_NAME, FILE_NAME);
284
285     if (settings.value(MAP_LAST_POSITION, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString()
286         == ERROR_VALUE_NOT_FOUND_ON_SETTINGS || settings.value(MAP_LAST_ZOOMLEVEL,
287         ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString() == ERROR_VALUE_NOT_FOUND_ON_SETTINGS) {
288
289         startLocation = QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE);
290         m_zoomLevel = qBound(MIN_VIEW_ZOOM_LEVEL, DEFAULT_START_ZOOM_LEVEL, MAX_MAP_ZOOM_LEVEL);
291     } else {
292         m_zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toInt();
293         startLocation = settings.value(MAP_LAST_POSITION,
294                                        ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toPointF();
295     }
296
297     emit zoomLevelChanged(m_zoomLevel);
298     centerToCoordinates(QPointF(startLocation.x(), startLocation.y()));
299 }
300
301 bool MapEngine::isAutoCenteringEnabled()
302 {
303     return m_autoCenteringEnabled;
304 }
305
306 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
307 {
308     qDebug() << __PRETTY_FUNCTION__;
309
310     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
311     QPoint temp = m_centerTile;
312     m_centerTile = centerTile;
313
314     return (centerTile != temp);
315 }
316
317 qreal MapEngine::sceneResolution()
318 {
319     qDebug() << __PRETTY_FUNCTION__;
320
321     const int SHIFT = 200;
322     const int KM_TO_M = 1000;
323     qreal scale = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
324     QPointF centerCoordinate = centerGeoCoordinate();
325     QPoint shiftedSceneCoordinate = QPoint(m_sceneCoordinate.x() + SHIFT*scale
326                                            , m_sceneCoordinate.y());
327     QPointF shiftedCoordinate = convertSceneCoordinateToLatLon(m_zoomLevel, shiftedSceneCoordinate);
328     qreal dist = greatCircleDistance(centerCoordinate, shiftedCoordinate) * KM_TO_M;
329     return (dist / SHIFT);
330 }
331
332 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
333 {
334     qDebug() << __PRETTY_FUNCTION__;
335
336     // add normal tile inside the world
337     QPoint tileNumber(x, y);
338     m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
339
340     // note: add 1 so odd width is rounded up and even is rounded down
341     int tilesGridWidthHalf = (m_viewTilesGrid.width() + 1) / 2;
342
343     // duplicate to east side? (don't need to duplicate over padding)
344     if (tileNumber.x() < (tilesGridWidthHalf - GRID_PADDING)) {
345         QPoint adjustedTileNumber(tileNumber.x() + tileMaxIndex(zoomLevel) + 1, tileNumber.y());
346         m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
347     }
348
349     // duplicate to west side? (don't need to duplicate over padding)
350     if (tileNumber.x() > (tileMaxIndex(zoomLevel) - tilesGridWidthHalf + GRID_PADDING)) {
351         QPoint adjustedTileNumber(tileNumber.x() - tileMaxIndex(zoomLevel) - 1, tileNumber.y());
352         m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
353     }
354 }
355
356 int MapEngine::normalize(int value, int min, int max)
357 {
358     qDebug() << __PRETTY_FUNCTION__;
359     Q_ASSERT_X(max >= min, "parameters", "max can't be smaller than min");
360
361     while (value < min)
362         value += max - min + 1;
363
364     while (value > max)
365         value -= max - min + 1;
366
367     return value;
368 }
369
370 void MapEngine::receiveOwnLocation(User *user)
371 {
372     qDebug() << __PRETTY_FUNCTION__;
373
374     if(user) {
375         QPoint newPosition = convertLatLonToSceneCoordinate(user->coordinates());
376         if (m_ownLocation->pos().toPoint() != newPosition) {
377             m_ownLocation->setPos(newPosition);
378         }
379
380         if (!m_ownLocation->isVisible())
381             m_ownLocation->show();
382     } else {
383         m_ownLocation->hide();
384     }
385
386     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
387 }
388
389 QGraphicsScene* MapEngine::scene()
390 {
391     qDebug() << __PRETTY_FUNCTION__;
392
393     return m_mapScene;
394 }
395
396 void MapEngine::scrollToPosition(QPoint scenePosition)
397 {
398     m_scroller->stop();
399     m_scroller->setEasingCurve(QEasingCurve::InOutQuart);
400     m_scroller->setDuration(SMOOTH_CENTERING_TIME_MS);
401     m_scroller->setStartValue(m_sceneCoordinate);
402     m_scroller->setEndValue(scenePosition);
403     m_scroller->start();
404 }
405
406 void MapEngine::setAutoCentering(bool enabled)
407 {
408     m_autoCenteringEnabled = enabled;
409 }
410
411 void MapEngine::setGPSEnabled(bool enabled)
412 {
413     m_gpsLocationItem->setEnabled(enabled);
414 }
415
416 void MapEngine::setCenterPosition(QPoint scenePosition)
417 {
418     qDebug() << __PRETTY_FUNCTION__;
419
420     // jump to opposite side of the world if world horizontal limit is exceeded
421     scenePosition.setX(normalize(scenePosition.x(), MAP_MIN_PIXEL_X, MAP_MAX_PIXEL_X));
422
423     // don't allow vertical scene coordinates go out of the map
424     scenePosition.setY(qBound(MAP_MIN_PIXEL_Y, scenePosition.y(), MAP_MAX_PIXEL_Y));
425
426     if (disableAutoCentering(scenePosition))
427         emit mapScrolledManually();
428
429     m_sceneCoordinate = scenePosition;
430     emit locationChanged(m_sceneCoordinate);
431
432     if (isCenterTileChanged(scenePosition)) {
433         getTiles(scenePosition);
434         m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
435     }
436
437     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
438     emit newMapResolution(sceneResolution());
439 }
440
441 void MapEngine::setZoomLevel(int newZoomLevel)
442 {
443     qDebug() << __PRETTY_FUNCTION__;
444
445     m_zoomLevel = newZoomLevel;
446     zoomed();
447 }
448
449 void MapEngine::setTilesGridSize(const QSize &viewSize)
450 {
451     qDebug() << __PRETTY_FUNCTION__;
452
453     // there must be scrolling reserve of at least half tile added to tile amount
454     // calculated from view size
455     const qreal SCROLLING_RESERVE = 0.5;
456
457     // converting scene tile to tile number does cause grid centering inaccuracy of one tile
458     const int CENTER_TILE_INACCURACY = 1;
459
460     int gridWidth = ceil(qreal(viewSize.width()) / TILE_SIZE_X + SCROLLING_RESERVE)
461                     + CENTER_TILE_INACCURACY + (GRID_PADDING * 2);
462     int gridHeight = ceil(qreal(viewSize.height()) / TILE_SIZE_Y + SCROLLING_RESERVE)
463                      + CENTER_TILE_INACCURACY + (GRID_PADDING * 2);
464
465     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
466
467     m_tilesGridSize.setHeight(gridHeight);
468     m_tilesGridSize.setWidth(gridWidth);
469 }
470
471 int MapEngine::tileMaxIndex(int zoomLevel)
472 {
473     qDebug() << __PRETTY_FUNCTION__;
474
475     // subtract one because first tile index is zero
476     return tilesPerSide(zoomLevel) - 1;
477 }
478
479 QString MapEngine::tilePath(int zoomLevel, int x, int y)
480 {
481     qDebug() << __PRETTY_FUNCTION__;
482
483     QString tilePathString(QString::number(zoomLevel) + "/");
484     tilePathString.append(QString::number(x) + "/");
485     tilePathString.append(QString::number(y));
486
487     return tilePathString;
488 }
489
490 int MapEngine::tilesPerSide(int zoomLevel)
491 {
492     return (1 << zoomLevel);
493 }
494
495 void MapEngine::updateViewTilesSceneRect()
496 {
497     qDebug() << __PRETTY_FUNCTION__;
498
499     const QPoint ONE_TILE = QPoint(1, 1);
500     const QPoint ONE_PIXEL = QPoint(1, 1);
501
502     QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
503     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
504     // of the last tile.
505     QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
506                                                             m_viewTilesGrid.bottomRight()
507                                                              + ONE_TILE) - ONE_PIXEL;
508
509     m_mapScene->tilesSceneRectUpdated(QRect(topLeft, bottomRight));
510 }
511
512 void MapEngine::viewResized(const QSize &size)
513 {
514     qDebug() << __PRETTY_FUNCTION__;
515
516     m_viewSize = size;
517     setTilesGridSize(m_viewSize);
518
519     emit locationChanged(m_sceneCoordinate);
520     getTiles(m_sceneCoordinate);
521     m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
522     m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
523 }
524
525 void MapEngine::viewZoomFinished()
526 {
527     qDebug() << __PRETTY_FUNCTION__;
528
529     if (m_zoomedIn) {
530         m_zoomedIn = false;
531         m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
532     }
533
534     if (m_zoomLevel == MAX_MAP_ZOOM_LEVEL)
535         emit maxZoomLevelReached();
536     else if (m_zoomLevel == MIN_VIEW_ZOOM_LEVEL)
537         emit minZoomLevelReached();
538 }
539
540 void MapEngine::zoomed()
541 {
542     emit zoomLevelChanged(m_zoomLevel);
543     m_mapScene->setTilesDrawingLevels(m_zoomLevel);
544     m_mapScene->setZoomLevel(m_zoomLevel);
545     getTiles(m_sceneCoordinate);
546     m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
547     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
548     emit newMapResolution(sceneResolution());
549 }
550
551 void MapEngine::zoomIn()
552 {
553     qDebug() << __PRETTY_FUNCTION__;
554
555     if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
556         m_zoomLevel++;
557         m_zoomedIn = true;
558         zoomed();
559     }
560 }
561
562 void MapEngine::zoomOut()
563 {
564     qDebug() << __PRETTY_FUNCTION__;
565
566     if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {
567         m_zoomLevel--;
568         zoomed();
569     }
570 }