Merge branch 'master' of https://vcs.maemo.org/git/situare
[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 "frienditemshandler.h"
35 #include "gpslocationitem.h"
36 #include "mapcommon.h"
37 #include "mapengine.h"
38 #include "maptile.h"
39
40 MapEngine::MapEngine(QObject *parent)
41     : QObject(parent)
42     , m_autoCenteringEnabled(false)
43     , m_centerTile(QPoint(UNDEFINED, UNDEFINED))
44     , m_lastManualPosition(QPoint(0, 0))
45     , m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
46     , m_zoomedIn(false)
47     , m_zoomLevel(DEFAULT_ZOOM_LEVEL)
48 {
49     qDebug() << __PRETTY_FUNCTION__;
50
51     m_mapScene = new MapScene(this);
52
53     m_mapFetcher = new MapFetcher(new QNetworkAccessManager(this), this);
54     connect(this, SIGNAL(fetchImage(int, int, int)),
55             m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
56     connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
57             this, SLOT(mapImageReceived(int, int, int, QPixmap)));
58
59     m_ownLocation = new OwnLocationItem();
60     m_ownLocation->hide(); // hide until first location info is received
61     m_mapScene->addItem(m_ownLocation);
62
63     m_gpsLocationItem = new GPSLocationItem();
64     m_mapScene->addItem(m_gpsLocationItem);
65
66     m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
67     connect(this, SIGNAL(zoomLevelChanged(int)),
68             m_friendItemsHandler, SLOT(refactorFriendItems(int)));
69
70     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
71             m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
72 }
73
74 void MapEngine::init()
75 {
76     qDebug() << __PRETTY_FUNCTION__;
77
78     emit zoomLevelChanged(m_zoomLevel);
79     setViewLocation(QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE));
80 }
81
82 void MapEngine::setViewLocation(QPointF latLonCoordinate)
83 {
84     qDebug() << __PRETTY_FUNCTION__;
85
86     QPoint sceneCoordinate = convertLatLonToSceneCoordinate(latLonCoordinate);
87
88     m_lastManualPosition = sceneCoordinate;
89
90     setLocation(sceneCoordinate);
91 }
92
93 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
94 {
95     qDebug() << __PRETTY_FUNCTION__;
96
97     QString hashKey = tilePath(zoomLevel, x, y);
98     if (!m_mapScene->isTileInScene(hashKey)) {
99
100         MapTile *mapTile = new MapTile();
101         mapTile->setZoomLevel(zoomLevel, m_zoomLevel);
102         mapTile->setTileNumber(QPoint(x, y));
103         mapTile->setPixmap(image);
104
105         m_mapScene->addTile(mapTile, hashKey);
106
107         m_mapScene->enqueueRemoveStackedTiles(mapTile);
108    }
109 }
110
111 QGraphicsScene* MapEngine::scene()
112 {
113     qDebug() << __PRETTY_FUNCTION__;
114
115     return m_mapScene;
116 }
117
118 int MapEngine::tileMaxValue(int zoomLevel)
119 {
120     qDebug() << __PRETTY_FUNCTION__;
121
122     return (1 << zoomLevel) - 1;
123 }
124
125 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
126 {
127     qDebug() << __PRETTY_FUNCTION__;
128
129     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
130     int gridWidth = (m_viewSize.width() / TILE_SIZE_X + 1) + (GRID_PADDING * 2);
131     int gridHeight = (m_viewSize.height() / TILE_SIZE_Y + 1) + (GRID_PADDING * 2);
132     int topLeftX = tileCoordinate.x() - (gridWidth / 2);
133     int topLeftY = tileCoordinate.y() - (gridHeight / 2);
134
135     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
136
137     return QRect(topLeftX, topLeftY, gridWidth, gridHeight);
138 }
139
140 void MapEngine::setLocation(QPoint sceneCoordinate)
141 {
142     qDebug() << __PRETTY_FUNCTION__;
143
144     if (disableAutoCentering(sceneCoordinate))
145         emit mapScrolledManually();
146
147     m_sceneCoordinate = sceneCoordinate;
148     emit locationChanged(m_sceneCoordinate);
149
150     if (isCenterTileChanged(sceneCoordinate)) {
151         getTiles(sceneCoordinate);
152         m_mapScene->removeOutOfViewTiles();
153     }
154 }
155
156 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
157 {
158     qDebug() << __PRETTY_FUNCTION__;
159
160     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
161     QPoint temp = m_centerTile;
162     m_centerTile = centerTile;
163
164     return (centerTile != temp);
165 }
166
167 void MapEngine::getTiles(QPoint sceneCoordinate)
168 {
169     qDebug() << __PRETTY_FUNCTION__;
170
171     m_viewTilesGrid = calculateTileGrid(sceneCoordinate);
172     updateViewTilesSceneRect();
173
174     int topLeftX = m_viewTilesGrid.topLeft().x();
175     int topLeftY = m_viewTilesGrid.topLeft().y();
176     int bottomRightX = m_viewTilesGrid.bottomRight().x();
177     int bottomRightY = m_viewTilesGrid.bottomRight().y();
178
179     int tileMaxVal = tileMaxValue(m_zoomLevel);
180
181     for (int x = topLeftX; x <= bottomRightX; ++x) {
182         for (int y = topLeftY; y <= bottomRightY; ++y) {
183
184             int tileX = x;
185             int tileY = y;
186
187             if (tileX < 0)
188                 tileX += tileMaxVal;
189             else if (tileX > tileMaxVal)
190                 tileX -= tileMaxVal;
191
192             if (tileY < 0)
193                 tileY += tileMaxVal;
194             else if (tileY > tileMaxVal)
195                 tileY -= tileMaxVal;
196
197             if (!m_mapScene->isTileInScene(tilePath(m_zoomLevel, tileX, tileY)))
198                 emit fetchImage(m_zoomLevel, tileX, tileY);
199         }
200     }
201 }
202
203 void MapEngine::updateViewTilesSceneRect()
204 {
205     qDebug() << __PRETTY_FUNCTION__;
206
207     const QPoint ONE_TILE = QPoint(1, 1);
208     const QPoint ONE_PIXEL = QPoint(1, 1);
209
210     QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
211     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
212     // of the last tile.
213     QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
214                                                             m_viewTilesGrid.bottomRight()
215                                                              + ONE_TILE) - ONE_PIXEL;
216
217     m_mapScene->viewRectUpdated(QRect(topLeft, bottomRight));
218 }
219
220 void MapEngine::viewResized(const QSize &size)
221 {
222     qDebug() << __PRETTY_FUNCTION__;
223
224     m_viewSize = size;
225     getTiles(m_sceneCoordinate);
226     m_mapScene->removeOutOfViewTiles();
227 }
228
229 void MapEngine::viewZoomFinished()
230 {
231     qDebug() << __PRETTY_FUNCTION__;
232
233     if (m_zoomedIn) {
234         m_zoomedIn = false;
235         m_mapScene->removeOutOfViewTiles();
236     }
237
238     if (m_zoomLevel == MAX_MAP_ZOOM_LEVEL)
239         emit maxZoomLevelReached();
240     else if (m_zoomLevel == MIN_VIEW_ZOOM_LEVEL)
241         emit minZoomLevelReached();
242 }
243
244 void MapEngine::zoomIn()
245 {
246     qDebug() << __PRETTY_FUNCTION__;
247
248     if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
249         m_zoomLevel++;
250         m_zoomedIn = true;
251         emit zoomLevelChanged(m_zoomLevel);
252
253         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
254
255         getTiles(m_sceneCoordinate);
256     }
257 }
258
259 void MapEngine::zoomOut()
260 {
261     qDebug() << __PRETTY_FUNCTION__;
262
263     if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {
264         m_zoomLevel--;
265         emit zoomLevelChanged(m_zoomLevel);
266
267         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
268
269         getTiles(m_sceneCoordinate);
270     }
271 }
272
273 QString MapEngine::tilePath(int zoomLevel, int x, int y)
274 {
275     qDebug() << __PRETTY_FUNCTION__;
276
277     QString tilePathString(QString::number(zoomLevel) + "/");
278     tilePathString.append(QString::number(x) + "/");
279     tilePathString.append(QString::number(y));
280
281     return tilePathString;
282 }
283
284 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
285 {
286     qDebug() << __PRETTY_FUNCTION__;
287
288     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
289     int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X * pow));
290     int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y * pow));
291
292     return QPoint(x, y);
293 }
294
295 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
296 {
297     qDebug() << __PRETTY_FUNCTION__;
298
299     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
300     int x = tileNumber.x() * TILE_SIZE_X * pow;
301     int y = tileNumber.y() * TILE_SIZE_Y * pow;
302
303     return QPoint(x, y);
304 }
305
306 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
307 {
308     qDebug() << __PRETTY_FUNCTION__;
309
310     qreal longitude = latLonCoordinate.x();
311     qreal latitude = latLonCoordinate.y();
312
313     if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
314         return QPoint(UNDEFINED, UNDEFINED);
315     if ((latitude > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
316         return QPoint(UNDEFINED, UNDEFINED);
317
318     qreal z = static_cast<qreal>(1 << MAX_MAP_ZOOM_LEVEL);
319
320     qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
321     qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
322                                 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
323
324     return QPointF(x * z * TILE_SIZE_X, y * z * TILE_SIZE_Y).toPoint();
325 }
326
327 void MapEngine::receiveOwnLocation(User *user)
328 {
329     qDebug() << __PRETTY_FUNCTION__;
330
331     QPoint newPosition = convertLatLonToSceneCoordinate(user->coordinates());
332     if (m_ownLocation->pos().toPoint() != newPosition) {
333         m_ownLocation->setPos(newPosition);
334     }
335
336     if (!m_ownLocation->isVisible())
337         m_ownLocation->show();
338 }
339
340 void MapEngine::gpsPositionUpdate(QPointF position, qreal accuracy)
341 {
342     m_gpsLocationItem->updatePosition(convertLatLonToSceneCoordinate(position), accuracy);
343
344     if (m_autoCenteringEnabled)
345         setViewLocation(position);
346 }
347
348 bool MapEngine::disableAutoCentering(QPoint sceneCoordinate)
349 {
350     if (isAutoCenteringEnabled()) {
351         int zoomFactor = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
352
353         QPoint oldPixelValue = QPoint(m_lastManualPosition.x() / zoomFactor,
354                                       m_lastManualPosition.y() / zoomFactor);
355
356         QPoint newPixelValue = QPoint(sceneCoordinate.x() / zoomFactor,
357                                       sceneCoordinate.y() / zoomFactor);
358
359         if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE) ||
360             (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE))
361             return true;
362     }
363
364     return false;
365 }
366
367 bool MapEngine::isAutoCenteringEnabled()
368 {
369     return m_autoCenteringEnabled;
370 }
371
372 void MapEngine::setAutoCentering(bool enabled)
373 {
374     m_autoCenteringEnabled = enabled;
375 }
376
377 void MapEngine::gpsEnabled(bool enabled)
378 {
379     m_gpsLocationItem->setEnabled(enabled);
380 }