Added flag for map scroll direction
[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 "maptile.h"
41 #include "ownlocationitem.h"
42
43 #include "mapengine.h"
44 #include "network/networkaccessmanager.h"
45
46 MapEngine::MapEngine(QObject *parent)
47     : QObject(parent),
48       m_autoCenteringEnabled(false),
49       m_zoomedIn(false),
50       m_zoomLevel(DEFAULT_ZOOM_LEVEL),
51       m_centerTile(QPoint(UNDEFINED, UNDEFINED)),
52       m_lastManualPosition(QPoint(0, 0)),
53       m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
54 {
55     qDebug() << __PRETTY_FUNCTION__;
56
57     m_mapScene = new MapScene(this);
58
59     m_mapFetcher = new MapFetcher(NetworkAccessManager::instance(), this);
60     connect(this, SIGNAL(fetchImage(int, int, int)),
61             m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
62     connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
63             this, SLOT(mapImageReceived(int, int, int, QPixmap)));
64
65     m_ownLocation = new OwnLocationItem();
66     m_ownLocation->hide(); // hide until first location info is received
67     m_mapScene->addItem(m_ownLocation);
68
69     m_gpsLocationItem = new GPSLocationItem();
70     m_mapScene->addItem(m_gpsLocationItem);
71
72     m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
73     connect(this, SIGNAL(zoomLevelChanged(int)),
74             m_friendItemsHandler, SLOT(refactorFriendItems(int)));
75
76     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
77             m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
78
79     connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
80             this, SIGNAL(locationItemClicked(QList<QString>)));
81 }
82
83 MapEngine::~MapEngine()
84 {
85     qDebug() << __PRETTY_FUNCTION__;
86
87     QSettings settings(DIRECTORY_NAME, FILE_NAME);
88     settings.setValue(MAP_LAST_POSITION,
89                       convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate));
90     settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
91 }
92
93 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
94 {
95     qDebug() << __PRETTY_FUNCTION__;
96
97     int horizontalPadding = GRID_PADDING;
98     if (m_zoomLevel <= 2)
99             horizontalPadding = 0;
100
101     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
102     int gridWidth = (m_viewSize.width() / TILE_SIZE_X + 1) + (horizontalPadding * 2);
103     int gridHeight = (m_viewSize.height() / TILE_SIZE_Y + 1) + (GRID_PADDING * 2);
104     int topLeftX = tileCoordinate.x() - (gridWidth / 2);
105     int topLeftY = tileCoordinate.y() - (gridHeight / 2);
106
107     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
108
109 //    qWarning() << __PRETTY_FUNCTION__ << topLeftX << topLeftY << "->"
110 //                                      << topLeftX + gridWidth << topLeftY + gridHeight;
111
112     return QRect(topLeftX, topLeftY, gridWidth, gridHeight);
113 }
114
115 QPointF MapEngine::centerGeoCoordinate()
116 {
117     qDebug() << __PRETTY_FUNCTION__;
118
119     return convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate);
120 }
121
122 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
123 {
124     qDebug() << __PRETTY_FUNCTION__;
125
126     qreal longitude = latLonCoordinate.x();
127     qreal latitude = latLonCoordinate.y();
128
129     if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
130         return QPoint(UNDEFINED, UNDEFINED);
131     if ((latitude > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
132         return QPoint(UNDEFINED, UNDEFINED);
133
134     qreal z = static_cast<qreal>(1 << MAX_MAP_ZOOM_LEVEL);
135
136     qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
137     qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
138                                 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
139
140     return QPointF(x * z * TILE_SIZE_X, y * z * TILE_SIZE_Y).toPoint();
141 }
142
143 QPointF MapEngine::convertSceneCoordinateToLatLon(int zoomLevel, QPoint sceneCoordinate)
144 {
145     qDebug() << __PRETTY_FUNCTION__;
146
147     double tileFactor = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
148     double xFactor = (sceneCoordinate.x() / (TILE_SIZE_X*tileFactor));
149     double yFactor = (sceneCoordinate.y() / (TILE_SIZE_Y*tileFactor));
150
151     tileFactor = 1 << zoomLevel;
152     double longitude = xFactor / tileFactor * 360.0 - 180;
153
154     double n = M_PI - 2.0 * M_PI * yFactor / tileFactor;
155     double latitude = 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
156
157     return QPointF(longitude, latitude);
158 }
159
160 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
161 {
162     qDebug() << __PRETTY_FUNCTION__;
163
164     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
165     int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X * pow));
166     int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y * pow));
167
168     return QPoint(x, y);
169 }
170
171 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
172 {
173     qDebug() << __PRETTY_FUNCTION__;
174
175     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
176     int x = tileNumber.x() * TILE_SIZE_X * pow;
177     int y = tileNumber.y() * TILE_SIZE_Y * pow;
178
179     return QPoint(x, y);
180 }
181
182 bool MapEngine::disableAutoCentering(QPoint sceneCoordinate)
183 {
184     if (isAutoCenteringEnabled()) {
185         int zoomFactor = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
186
187         QPoint oldPixelValue = QPoint(m_lastManualPosition.x() / zoomFactor,
188                                       m_lastManualPosition.y() / zoomFactor);
189
190         QPoint newPixelValue = QPoint(sceneCoordinate.x() / zoomFactor,
191                                       sceneCoordinate.y() / zoomFactor);
192
193         if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE) ||
194             (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE))
195             return true;
196     }
197
198     return false;
199 }
200
201 void MapEngine::getTiles(QPoint sceneCoordinate)
202 {
203     qDebug() << __PRETTY_FUNCTION__;
204
205     m_viewTilesGrid = calculateTileGrid(sceneCoordinate);
206     QRect tilesSceneRect = updateViewTilesSceneRect();
207
208     int topLeftX = m_viewTilesGrid.topLeft().x();
209     int topLeftY = m_viewTilesGrid.topLeft().y();
210     int bottomRightX = m_viewTilesGrid.bottomRight().x();
211     int bottomRightY = m_viewTilesGrid.bottomRight().y();
212
213     int tileMaxVal = tileMaxValue(m_zoomLevel);
214
215 //    qWarning() << __PRETTY_FUNCTION__ << "topleft:" << topLeftX << topLeftY
216 //                                      << "bottomright:" << bottomRightX << bottomRightY;
217
218     for (int x = topLeftX; x <= bottomRightX; ++x) {
219         for (int y = topLeftY; y <= bottomRightY; ++y) {
220
221             int tileX = x;
222             int tileY = y;
223
224             int requestedX = x;
225
226             // span in horizontal direction if world limits has been reached
227             if (tileX < 0) {
228                 tileX += tileMaxVal + 1;
229 //                qWarning() << __PRETTY_FUNCTION__ << "x value:" << requestedX << "->" << tileX;
230             }
231             else if (tileX > tileMaxVal) {
232                 tileX -= tileMaxVal + 1;
233 //                qWarning() << __PRETTY_FUNCTION__ << "x value:" << requestedX << "->" << tileX;
234             }
235
236             // map doesn't span in vertical direction
237             if (tileY < 0 || tileY > tileMaxVal)
238                 continue;
239
240             MapTile *tile;
241             if (!(tile = m_mapScene->tileInScene(tilePath(m_zoomLevel, tileX, tileY)))) {
242                 emit fetchImage(m_zoomLevel, tileX, tileY);
243             }
244             else {
245                 // tile was already in the scene, maybe it should be moved?
246 //                qWarning() << __PRETTY_FUNCTION__ << "tile was already in the scene";
247 //                m_mapScene->spanItem(tile, tilesSceneRect);
248             }
249         }
250     }
251
252 //    m_friendItemsHandler->spanFriendItems(tilesSceneRect);
253
254     m_mapScene->spanItems(m_scrollDirection);
255 }
256
257 void MapEngine::gpsPositionUpdate(QPointF position, qreal accuracy)
258 {
259     qDebug() << __PRETTY_FUNCTION__;
260
261     m_gpsLocationItem->updatePosition(convertLatLonToSceneCoordinate(position), accuracy);
262
263     if (m_autoCenteringEnabled)
264         setViewLocation(position);
265 }
266
267 void MapEngine::init()
268 {
269     qDebug() << __PRETTY_FUNCTION__;
270
271     QPointF startLocation;
272     QSettings settings(DIRECTORY_NAME, FILE_NAME);
273
274     if (settings.value(MAP_LAST_POSITION, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString()
275         == ERROR_VALUE_NOT_FOUND_ON_SETTINGS || settings.value(MAP_LAST_ZOOMLEVEL,
276         ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString() == ERROR_VALUE_NOT_FOUND_ON_SETTINGS) {
277
278         startLocation = QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE);
279         m_zoomLevel = DEFAULT_START_ZOOM_LEVEL;
280     } else {
281         m_zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toInt();
282         startLocation = settings.value(MAP_LAST_POSITION,
283                                        ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toPointF();
284     }
285
286     emit zoomLevelChanged(m_zoomLevel);
287     setViewLocation(QPointF(startLocation.x(), startLocation.y()));
288 }
289
290 bool MapEngine::isAutoCenteringEnabled()
291 {
292     return m_autoCenteringEnabled;
293 }
294
295 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
296 {
297     qDebug() << __PRETTY_FUNCTION__;
298
299     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
300     QPoint temp = m_centerTile;
301     m_centerTile = centerTile;
302
303     return (centerTile != temp);
304 }
305
306 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
307 {
308     qDebug() << __PRETTY_FUNCTION__ << "x:" << x << "y:" << y;
309
310     QString hashKey = tilePath(zoomLevel, x, y);
311     if (!m_mapScene->tileInScene(hashKey)) {
312
313         MapTile *mapTile = new MapTile();
314         mapTile->setZoomLevel(zoomLevel, m_zoomLevel);
315         mapTile->setTileNumber(QPoint(x, y));
316         mapTile->setPixmap(image);
317
318         m_mapScene->addTile(mapTile, hashKey);
319
320         m_mapScene->enqueueRemoveStackedTiles(mapTile);
321     }
322     else {
323         qCritical() << __PRETTY_FUNCTION__ << "WARNING: Received tile which already is in the scene";
324     }
325 }
326
327 void MapEngine::receiveOwnLocation(User *user)
328 {
329     qDebug() << __PRETTY_FUNCTION__;
330
331     if(user) {
332         QPoint newPosition = convertLatLonToSceneCoordinate(user->coordinates());
333         if (m_ownLocation->pos().toPoint() != newPosition) {
334             m_ownLocation->setPos(newPosition);
335         }
336
337         if (!m_ownLocation->isVisible())
338             m_ownLocation->show();
339     }
340     else {
341         m_ownLocation->hide();
342     }
343 }
344
345 QGraphicsScene* MapEngine::scene()
346 {
347     qDebug() << __PRETTY_FUNCTION__;
348
349     return m_mapScene;
350 }
351
352 void MapEngine::setAutoCentering(bool enabled)
353 {
354     m_autoCenteringEnabled = enabled;
355 }
356
357 void MapEngine::setGPSEnabled(bool enabled)
358 {
359     m_gpsLocationItem->setEnabled(enabled);
360 }
361
362 void MapEngine::setLocation(QPoint sceneCoordinate)
363 {
364     qWarning() << __PRETTY_FUNCTION__ << "X:" << sceneCoordinate.x();
365
366     if (sceneCoordinate.x() < 0) {
367 //        qWarning() << __PRETTY_FUNCTION__ << "World west limit reached";
368         sceneCoordinate.setX(sceneCoordinate.x() + WORLD_PIXELS_X);
369     }
370     else if (sceneCoordinate.x() > WORLD_PIXELS_X - 1) {
371 //        qWarning() << __PRETTY_FUNCTION__ << "World east limit reached";
372         sceneCoordinate.setX(sceneCoordinate.x() - WORLD_PIXELS_X);
373     }
374
375     if (sceneCoordinate.x() > m_sceneCoordinate.x())
376         m_scrollDirection = SCROLL_EAST;
377     else
378         m_scrollDirection = SCROLL_WEST;
379
380     if (disableAutoCentering(sceneCoordinate))
381         emit mapScrolledManually();
382
383     m_sceneCoordinate = sceneCoordinate;
384     emit locationChanged(m_sceneCoordinate);
385
386     if (isCenterTileChanged(sceneCoordinate)) {
387         getTiles(sceneCoordinate);
388         m_mapScene->removeOutOfViewTiles();
389     }
390 }
391
392 void MapEngine::setZoomLevel(int newZoomLevel)
393 {
394     qDebug() << __PRETTY_FUNCTION__;
395
396     m_zoomLevel = newZoomLevel;
397     emit zoomLevelChanged(m_zoomLevel);
398 }
399
400 void MapEngine::setViewLocation(QPointF latLonCoordinate)
401 {
402     qDebug() << __PRETTY_FUNCTION__;
403
404     QPoint sceneCoordinate = convertLatLonToSceneCoordinate(latLonCoordinate);
405
406     m_lastManualPosition = sceneCoordinate;
407
408     setLocation(sceneCoordinate);
409 }
410
411 int MapEngine::tileMaxValue(int zoomLevel)
412 {
413     qDebug() << __PRETTY_FUNCTION__;
414
415     return (1 << zoomLevel) - 1;
416 }
417
418 QString MapEngine::tilePath(int zoomLevel, int x, int y)
419 {
420     qDebug() << __PRETTY_FUNCTION__;
421
422     QString tilePathString(QString::number(zoomLevel) + "/");
423     tilePathString.append(QString::number(x) + "/");
424     tilePathString.append(QString::number(y));
425
426     return tilePathString;
427 }
428
429 QRect MapEngine::updateViewTilesSceneRect()
430 {
431     qDebug() << __PRETTY_FUNCTION__;
432
433     const QPoint ONE_TILE = QPoint(1, 1);
434     const QPoint ONE_PIXEL = QPoint(1, 1);
435
436     QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
437     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
438     // of the last tile.
439     QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
440                                                             m_viewTilesGrid.bottomRight()
441                                                              + ONE_TILE) - ONE_PIXEL;
442     QRect rect(topLeft, bottomRight);
443     m_mapScene->viewRectUpdated(rect);
444
445     return rect;
446 }
447
448 void MapEngine::viewResized(const QSize &size)
449 {
450     qDebug() << __PRETTY_FUNCTION__;
451
452     m_viewSize = size;
453     emit locationChanged(m_sceneCoordinate);
454     getTiles(m_sceneCoordinate);
455     m_mapScene->removeOutOfViewTiles();
456 }
457
458 void MapEngine::viewZoomFinished()
459 {
460     qDebug() << __PRETTY_FUNCTION__;
461
462     if (m_zoomedIn) {
463         m_zoomedIn = false;
464         m_mapScene->removeOutOfViewTiles();
465     }
466
467     if (m_zoomLevel == MAX_MAP_ZOOM_LEVEL)
468         emit maxZoomLevelReached();
469     else if (m_zoomLevel == MIN_VIEW_ZOOM_LEVEL)
470         emit minZoomLevelReached();
471 }
472
473 void MapEngine::zoomIn()
474 {
475     qDebug() << __PRETTY_FUNCTION__;
476
477     if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
478         m_zoomLevel++;
479         m_zoomedIn = true;
480         emit zoomLevelChanged(m_zoomLevel);
481
482         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
483
484         getTiles(m_sceneCoordinate);
485     }
486 }
487
488 void MapEngine::zoomOut()
489 {
490     qDebug() << __PRETTY_FUNCTION__;
491
492     if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {
493         m_zoomLevel--;
494         emit zoomLevelChanged(m_zoomLevel);
495
496         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
497
498         getTiles(m_sceneCoordinate);
499     }
500 }