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