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