remove separate tile indexes array and use a direct tilekey->texture array instead
[lantea.git] / js / map.js
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3  * You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 var gGLMapCanvas, gTrackCanvas, gTrackContext, gGeolocation;
6 var gDebug = false;
7
8 var gMinTrackAccuracy = 1000; // meters
9 var gTrackWidth = 2; // pixels
10 var gTrackColor = "#FF0000";
11 var gCurLocSize = 6; // pixels
12 var gCurLocColor = "#A00000";
13
14 var gMapStyles = {
15   // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy
16   // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
17   osm_mapnik:
18     {name: "OpenStreetMap (Mapnik)",
19      url: "http://tile.openstreetmap.org/{z}/{x}/{y}.png",
20      copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
21   osm_cyclemap:
22     {name: "Cycle Map (OSM)",
23      url: "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
24      copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
25   osm_transmap:
26     {name: "Transport Map (OSM)",
27      url: "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
28      copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
29   mapquest_open:
30     {name: "MapQuest OSM",
31      url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png",
32      copyright: 'Map data &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> and contributors (<a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>), tiles Courtesy of <a href="http://www.mapquest.com/">MapQuest</a>.'},
33   mapquest_aerial:
34     {name: "MapQuest Open Aerial",
35      url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
36      copyright: 'Tiles Courtesy of <a href="http://www.mapquest.com/">MapQuest</a>, portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency.'},
37   opengeoserver_arial:
38     {name: "OpenGeoServer Aerial",
39      url: "http://services.opengeoserver.org/tiles/1.0.0/globe.aerial_EPSG3857/{z}/{x}/{y}.png?origin=nw",
40      copyright: 'Tiles by <a href="http://www.opengeoserver.org/">OpenGeoServer.org</a>, <a href="https://creativecommons.org/licenses/by/3.0/at/">CC-BY 3.0 AT</a>.'},
41   google_map:
42     {name: "Google Maps",
43      url: " http://mt1.google.com/vt/x={x}&y={y}&z={z}",
44      copyright: 'Map data and imagery &copy; <a href="http://maps.google.com/">Google</a>'},
45 };
46
47 var gLastMouseX = 0;
48 var gLastMouseY = 0;
49
50 var gLoadingTile;
51
52 var gMapPrefsLoaded = false;
53
54 var gDragging = false;
55 var gDragTouchID, gPinchStartWidth;
56
57 var gGeoWatchID;
58 var gTrack = [];
59 var gLastTrackPoint, gLastDrawnPoint;
60 var gCenterPosition = true;
61
62 var gCurPosMapCache;
63
64 function initMap() {
65   gGeolocation = navigator.geolocation;
66   // Set up canvas context.
67   gGLMapCanvas = document.getElementById("map");
68   try {
69     // Try to grab the standard context. If it fails, fallback to experimental.
70     // We also try to tell it we do not need a depth buffer.
71     gMap.gl = gGLMapCanvas.getContext("webgl", {depth: false}) ||
72               gGLMapCanvas.getContext("experimental-webgl", {depth: false});
73   }
74   catch(e) {}
75   // If we don't have a GL context, give up now
76   if (!gMap.gl) {
77     showGLWarningDialog();
78     gMap.gl = null;
79   }
80   gTrackCanvas = document.getElementById("track");
81   gTrackContext = gTrackCanvas.getContext("2d");
82   if (!gMap.activeMap)
83     gMap.activeMap = "osm_mapnik";
84
85   //gDebug = true;
86   if (gDebug) {
87     gGeolocation = geofake;
88     var hiddenList = document.getElementsByClassName("debugHide");
89     // last to first - list of elements with that class is changing!
90     for (var i = hiddenList.length - 1; i >= 0; i--) {
91       hiddenList[i].classList.remove("debugHide");
92     }
93   }
94
95   gAction.addEventListener("prefload-done", gMap.initGL, false);
96
97   console.log("map vars set, loading prefs...");
98   loadPrefs();
99 }
100
101 function loadPrefs(aEvent) {
102   if (aEvent && aEvent.type == "prefs-step") {
103     console.log("wait: " + gWaitCounter);
104     if (gWaitCounter == 0) {
105       gAction.removeEventListener(aEvent.type, loadPrefs, false);
106       gMapPrefsLoaded = true;
107       console.log("prefs loaded.");
108
109       gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
110       gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
111       gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
112       gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
113
114       gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
115       gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
116       gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
117       gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
118       gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
119
120       gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
121
122       document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
123
124       document.getElementById("copyright").innerHTML =
125           gMapStyles[gMap.activeMap].copyright;
126
127       gLoadingTile = new Image();
128       gLoadingTile.src = "style/loading.png";
129       gLoadingTile.onload = function() {
130         var throwEv = new CustomEvent("prefload-done");
131         gAction.dispatchEvent(throwEv);
132       };
133     }
134   }
135   else {
136     if (aEvent)
137       gAction.removeEventListener(aEvent.type, loadPrefs, false);
138     gAction.addEventListener("prefs-step", loadPrefs, false);
139     gWaitCounter++;
140     gPrefs.get("position", function(aValue) {
141       if (aValue && aValue.x && aValue.y && aValue.z) {
142         gMap.pos = aValue;
143       }
144       gWaitCounter--;
145       var throwEv = new CustomEvent("prefs-step");
146       gAction.dispatchEvent(throwEv);
147     });
148     gWaitCounter++;
149     gPrefs.get("center_map", function(aValue) {
150       if (aValue === undefined)
151         document.getElementById("centerCheckbox").checked = true;
152       else
153         document.getElementById("centerCheckbox").checked = aValue;
154       setCentering(document.getElementById("centerCheckbox"));
155       gWaitCounter--;
156       var throwEv = new CustomEvent("prefs-step");
157       gAction.dispatchEvent(throwEv);
158     });
159     gWaitCounter++;
160     gPrefs.get("tracking_enabled", function(aValue) {
161       if (aValue === undefined)
162         document.getElementById("trackCheckbox").checked = true;
163       else
164         document.getElementById("trackCheckbox").checked = aValue;
165       gWaitCounter--;
166       var throwEv = new CustomEvent("prefs-step");
167       gAction.dispatchEvent(throwEv);
168     });
169     gWaitCounter++;
170     var trackLoadStarted = false;
171     var redrawBase = 100;
172     gTrackStore.getListStepped(function(aTPoint) {
173       if (aTPoint) {
174         // Add in front and return new length.
175         var tracklen = gTrack.unshift(aTPoint);
176         // Redraw track periodically, larger distance the longer it gets.
177         // Initial paint will do initial track drawing.
178         if (tracklen % redrawBase == 0) {
179           drawTrack();
180           redrawBase = tracklen;
181         }
182       }
183       else {
184         // Last point received.
185         drawTrack();
186       }
187       if (!trackLoadStarted) {
188         // We have the most recent point, if present, rest will load async.
189         trackLoadStarted = true;
190         gWaitCounter--;
191         var throwEv = new CustomEvent("prefs-step");
192         gAction.dispatchEvent(throwEv);
193       }
194     });
195   }
196 }
197
198 var gMap = {
199   gl: null,
200   glShaderProgram: null,
201   glVertexPositionAttr: null,
202   glTextureCoordAttr: null,
203   glResolutionAttr: null,
204   glMapTexture: null,
205   glTextures: {},
206
207   activeMap: "osm_mapnik",
208   tileSize: 256,
209   maxZoom: 18, // The minimum is 0.
210   zoomFactor: null,
211   pos: {
212     x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
213     y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
214     z: 5           // This could be fractional if supported being between zoom levels.
215   },
216
217   get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
218   get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
219
220   getVertShaderSource: function() {
221     return 'attribute vec2 aVertexPosition;\n' +
222     'attribute vec2 aTextureCoord;\n\n' +
223     'uniform vec2 uResolution;\n\n' +
224     'varying highp vec2 vTextureCoord;\n\n' +
225     'void main(void) {\n' +
226     // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
227     '  vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
228     '  gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
229     '  vTextureCoord = aTextureCoord;\n' +
230     '}'; },
231   getFragShaderSource:function() {
232     return 'varying highp vec2 vTextureCoord;\n\n' +
233     'uniform sampler2D uImage;\n\n' +
234     'void main(void) {\n' +
235     '  gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
236     '}'; },
237
238   initGL: function() {
239     // When called from the event listener, the "this" reference doesn't work, so use the object name.
240     if (gMap.gl) {
241       gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
242       gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5);                          // Set clear color to black, fully opaque.
243       gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT);  // Clear the color.
244
245       // Create and initialize the shaders.
246       var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
247       var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
248       gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
249       // Compile the shader program.
250       gMap.gl.compileShader(vertShader);
251       // See if it compiled successfully.
252       if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
253         console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
254         return null;
255       }
256       gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
257       // Compile the shader program.
258       gMap.gl.compileShader(fragShader);
259       // See if it compiled successfully.
260       if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
261         console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
262         return null;
263       }
264
265       gMap.glShaderProgram = gMap.gl.createProgram();
266       gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
267       gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
268       gMap.gl.linkProgram(gMap.glShaderProgram);
269       // If creating the shader program failed, alert
270       if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
271         alert("Unable to initialize the shader program.");
272       }
273       gMap.gl.useProgram(gMap.glShaderProgram);
274       // Get locations of the attributes.
275       gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
276       gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
277       gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
278
279       var tileVerticesBuffer = gMap.gl.createBuffer();
280       gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
281       // The vertices are the coordinates of the corner points of the square.
282       var vertices = [
283         0.0,  0.0,
284         1.0,  0.0,
285         0.0,  1.0,
286         0.0,  1.0,
287         1.0,  0.0,
288         1.0,  1.0,
289       ];
290       gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
291       gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
292       gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
293
294       gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
295
296       gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
297
298       // Create a buffer for the position of the rectangle corners.
299       var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
300       gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
301       gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
302       gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
303     }
304
305     var throwEv = new CustomEvent("mapinit-done");
306     gAction.dispatchEvent(throwEv);
307   },
308
309   draw: function() {
310     gMap.assembleGL();
311     drawTrack();
312   },
313
314   assembleGL: function() {
315     if (!gMap.gl) { return; }
316
317     document.getElementById("zoomLevel").textContent = gMap.pos.z;
318     gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
319     var wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor; // Width in level 18 pixels.
320     var ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor; // Height in level 18 pixels.
321     var size = gMap.tileSize * gMap.zoomFactor; // Tile size in level 18 pixels.
322
323     var xMin = gMap.pos.x - wid / 2; // Corners of the window in level 18 pixels.
324     var yMin = gMap.pos.y - ht / 2;
325     var xMax = gMap.pos.x + wid / 2;
326     var yMax = gMap.pos.y + ht / 2;
327
328     if (gMapPrefsLoaded && mainDB)
329       gPrefs.set("position", gMap.pos);
330
331     // Go through all the tiles in the map, find out if to draw them and do so.
332     for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
333       for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
334         // Only go to loading step if we haven't loaded the texture.
335         var coords = {x: x, y: y, z: gMap.pos.z};
336         var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
337         if (!gMap.glTextures[tileKey]) {
338           // Initiate loading/drawing of the actual tile.
339           gTileService.get(gMap.activeMap, coords,
340                            function(aImage, aStyle, aCoords, aTileKey) {
341             // Only actually load if this still applies for the current view.
342             if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
343               var URL = window.URL;
344               var imgURL = URL.createObjectURL(aImage);
345               var imgObj = new Image();
346               imgObj.onload = function() {
347                 gMap.loadImageToTexture(imgObj, aTileKey);
348                 requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
349                 URL.revokeObjectURL(imgURL);
350               }
351               imgObj.src = imgURL;
352             }
353           });
354         }
355       }
356     }
357     requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
358   },
359
360   drawGL: function() {
361     var wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor; // Width in level 18 pixels.
362     var ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor; // Height in level 18 pixels.
363     var size = gMap.tileSize * gMap.zoomFactor; // Tile size in level 18 pixels.
364
365     var xMin = gMap.pos.x - wid / 2; // Corners of the window in level 18 pixels.
366     var yMin = gMap.pos.y - ht / 2;
367     var xMax = gMap.pos.x + wid / 2;
368     var yMax = gMap.pos.y + ht / 2;
369
370     // Go through all the tiles in the map, find out if to draw them and do so.
371     for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
372       for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
373         // Round here is **CRUCIAL** otherwise the images are filtered
374         // and the performance sucks (more than expected).
375         var xoff = Math.round((x * size - xMin) / gMap.zoomFactor);
376         var yoff = Math.round((y * size - yMin) / gMap.zoomFactor);
377         // Draw the tile, first find out the actual texture to use.
378         var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
379         var tileKey = getTileKey(gMap.activeMap, norm);
380         if (!gMap.glTextures[tileKey]) {
381           tileKey = getTileKey("loading", {x: 0, y: 0, z: 0});
382         }
383         gMap.drawTileGL(xoff, yoff, tileKey);
384       }
385     }
386   },
387
388   resizeAndDraw: function() {
389     var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
390     var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
391     if (gGLMapCanvas && gTrackCanvas) {
392       gGLMapCanvas.width = viewportWidth;
393       gGLMapCanvas.height = viewportHeight;
394       gTrackCanvas.width = viewportWidth;
395       gTrackCanvas.height = viewportHeight;
396       if (gMap.gl) {
397         // Size viewport to canvas size.
398         gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
399         // Clear the color.
400         gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
401         // Make sure the vertex shader get the right resolution.
402         gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
403       }
404       gMap.draw();
405       showUI();
406     }
407   },
408
409   drawTileGL: function(aLeft, aRight, aTileKey) {
410     gMap.gl.activeTexture(gMap.gl.TEXTURE0);
411     gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
412     // Set uImage to refer to TEXTURE0
413     gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
414     var x_start = aLeft;
415     var i_width = gMap.tileSize;
416     var y_start = aRight;
417     var i_height = gMap.tileSize;
418     var textureCoordinates = [
419       x_start, y_start,
420       x_start + i_width, y_start,
421       x_start, y_start + i_height,
422       x_start, y_start + i_height,
423       x_start + i_width, y_start,
424       x_start + i_width, y_start + i_height,
425     ];
426     gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
427
428     // There are 6 indices in textureCoordinates.
429     gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
430   },
431
432   loadImageToTexture: function(aImage, aTileKey) {
433     // TODO: Get rid of old textures.
434     // Create and bind texture.
435     gMap.glTextures[aTileKey] = gMap.gl.createTexture();
436     gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
437     // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
438     gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
439     gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
440     // Upload the image into the texture.
441     gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
442   },
443 }
444
445 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
446 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
447
448 function zoomIn() {
449   if (gMap.pos.z < gMap.maxZoom) {
450     gMap.pos.z++;
451     gMap.draw();
452   }
453 }
454
455 function zoomOut() {
456   if (gMap.pos.z > 0) {
457     gMap.pos.z--;
458     gMap.draw();
459   }
460 }
461
462 function zoomTo(aTargetLevel) {
463   aTargetLevel = parseInt(aTargetLevel);
464   if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
465     gMap.pos.z = aTargetLevel;
466     gMap.draw();
467   }
468 }
469
470 function gps2xy(aLatitude, aLongitude) {
471   var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
472   var convLat = aLatitude * Math.PI / 180;
473   var rawY = (1 - Math.log(Math.tan(convLat) +
474                            1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
475   var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
476   return {x: Math.round(rawX),
477           y: Math.round(rawY)};
478 }
479
480 function xy2gps(aX, aY) {
481   var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
482   var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
483   return {latitude: 180 / Math.PI *
484                     Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
485           longitude: aX / maxZoomFactor * 360 - 180};
486 }
487
488 function setMapStyle() {
489   var mapSel = document.getElementById("mapSelector");
490   if (mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) {
491     gMap.activeMap = mapSel.value;
492     document.getElementById("copyright").innerHTML =
493         gMapStyles[gMap.activeMap].copyright;
494     showUI();
495     gMap.draw();
496   }
497 }
498
499 // A sane mod function that works for negative numbers.
500 // Returns a % b.
501 function mod(a, b) {
502   return ((a % b) + b) % b;
503 }
504
505 function normalizeCoords(aCoords) {
506   var zoomFactor = Math.pow(2, aCoords.z);
507   return {x: mod(aCoords.x, zoomFactor),
508           y: mod(aCoords.y, zoomFactor),
509           z: aCoords.z};
510 }
511
512 function getTileKey(aStyle, aNormalizedCoords) {
513   return aStyle + "::" +
514          aNormalizedCoords.x + "," +
515          aNormalizedCoords.y + "," +
516          aNormalizedCoords.z;
517 }
518
519 // Returns true if the tile is outside the current view.
520 function isOutsideWindow(t) {
521   var pos = decodeIndex(t);
522
523   var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
524   var wid = gMap.width * zoomFactor;
525   var ht = gMap.height * zoomFactor;
526
527   pos.x *= zoomFactor;
528   pos.y *= zoomFactor;
529
530   var sz = gMap.tileSize * zoomFactor;
531   if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
532       pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
533     return true;
534   return false;
535 }
536
537 function encodeIndex(x, y, z) {
538   var norm = normalizeCoords({x: x, y: y, z: z});
539   return norm.x + "," + norm.y + "," + norm.z;
540 }
541
542 function decodeIndex(encodedIdx) {
543   var ind = encodedIdx.split(",", 3);
544   return {x: ind[0], y: ind[1], z: ind[2]};
545 }
546
547 function drawTrack() {
548   gLastDrawnPoint = null;
549   gCurPosMapCache = undefined;
550   gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
551   if (gTrack.length) {
552     for (var i = 0; i < gTrack.length; i++) {
553       drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
554                      (i + 1 >= gTrack.length));
555     }
556   }
557 }
558
559 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
560   var trackpoint = gps2xy(aLatitude, aLongitude);
561   // lastPoint is for optimizing (not actually executing the draw until the last)
562   trackpoint.optimized = (lastPoint === false);
563   var mappos = {x: Math.round((trackpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
564                 y: Math.round((trackpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
565
566   if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
567     gTrackContext.strokeStyle = gTrackColor;
568     gTrackContext.fillStyle = gTrackContext.strokeStyle;
569     gTrackContext.lineWidth = gTrackWidth;
570     gTrackContext.lineCap = "round";
571     gTrackContext.lineJoin = "round";
572   }
573   if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
574     // This breaks optimiziation, so make sure to close path and reset optimization.
575     if (gLastDrawnPoint && gLastDrawnPoint.optimized)
576       gTrackContext.stroke();
577     gTrackContext.beginPath();
578     trackpoint.optimized = false;
579     gTrackContext.arc(mappos.x, mappos.y,
580                       gTrackContext.lineWidth, 0, Math.PI * 2, false);
581     gTrackContext.fill();
582   }
583   else {
584     if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
585       gTrackContext.beginPath();
586       gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
587                            Math.round((gLastDrawnPoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2));
588     }
589     gTrackContext.lineTo(mappos.x, mappos.y);
590     if (!trackpoint.optimized)
591       gTrackContext.stroke();
592   }
593   gLastDrawnPoint = trackpoint;
594 }
595
596 function drawCurrentLocation(trackPoint) {
597   var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
598   var circleRadius = Math.round(gCurLocSize / 2);
599   var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
600                 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
601
602   undrawCurrentLocation();
603
604   // Cache overdrawn area.
605   gCurPosMapCache =
606       {point: locpoint,
607        radius: circleRadius,
608        data: gTrackContext.getImageData(mappos.x - circleRadius,
609                                         mappos.y - circleRadius,
610                                         circleRadius * 2, circleRadius * 2)};
611
612   gTrackContext.strokeStyle = gCurLocColor;
613   gTrackContext.fillStyle = gTrackContext.strokeStyle;
614   gTrackContext.beginPath();
615   gTrackContext.arc(mappos.x, mappos.y,
616                     circleRadius, 0, Math.PI * 2, false);
617   gTrackContext.fill();
618 }
619
620 function undrawCurrentLocation() {
621   if (gCurPosMapCache) {
622     var oldpoint = gCurPosMapCache.point;
623     var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
624                  y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
625     gTrackContext.putImageData(gCurPosMapCache.data,
626                                oldmp.x - gCurPosMapCache.radius,
627                                oldmp.y - gCurPosMapCache.radius);
628     gCurPosMapCache = undefined;
629   }
630 }
631
632 var mapEvHandler = {
633   handleEvent: function(aEvent) {
634     var touchEvent = aEvent.type.indexOf('touch') != -1;
635
636     if (touchEvent) {
637       aEvent.stopPropagation();
638     }
639
640     // Bail out if the event is happening on an input.
641     if (aEvent.target.tagName.toLowerCase() == "input")
642       return;
643
644     // Bail out on unwanted map moves, but not zoom or keyboard events.
645     if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
646       // Bail out if this is neither a touch nor left-click.
647       if (!touchEvent && aEvent.button != 0)
648         return;
649
650       // Bail out if the started touch can't be found.
651       if (touchEvent && gDragging &&
652           !aEvent.changedTouches.identifiedTouch(gDragTouchID))
653         return;
654     }
655
656     var coordObj = touchEvent ?
657                    aEvent.changedTouches.identifiedTouch(gDragTouchID) :
658                    aEvent;
659
660     switch (aEvent.type) {
661       case "mousedown":
662       case "touchstart":
663         if (touchEvent) {
664           if (aEvent.targetTouches.length == 2) {
665             gPinchStartWidth = Math.sqrt(
666                 Math.pow(aEvent.targetTouches.item(1).clientX -
667                          aEvent.targetTouches.item(0).clientX, 2) +
668                 Math.pow(aEvent.targetTouches.item(1).clientY -
669                          aEvent.targetTouches.item(0).clientY, 2)
670             );
671           }
672           gDragTouchID = aEvent.changedTouches.item(0).identifier;
673           coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
674         }
675         var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
676         var y = coordObj.clientY - gGLMapCanvas.offsetTop;
677
678         if (touchEvent || aEvent.button === 0) {
679           gDragging = true;
680         }
681         gLastMouseX = x;
682         gLastMouseY = y;
683         showUI();
684         break;
685       case "mousemove":
686       case "touchmove":
687         if (touchEvent && aEvent.targetTouches.length == 2) {
688           curPinchStartWidth = Math.sqrt(
689               Math.pow(aEvent.targetTouches.item(1).clientX -
690                        aEvent.targetTouches.item(0).clientX, 2) +
691               Math.pow(aEvent.targetTouches.item(1).clientY -
692                        aEvent.targetTouches.item(0).clientY, 2)
693           );
694           if (!gPinchStartWidth)
695             gPinchStartWidth = curPinchStartWidth;
696
697           if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
698               gPinchStartWidth / curPinchStartWidth < 0.6) {
699             var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
700             if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
701               // Calculate new center of the map - preserve middle of pinch.
702               // This means that pixel distance between old center and middle
703               // must equal pixel distance of new center and middle.
704               var x = (aEvent.targetTouches.item(1).clientX +
705                        aEvent.targetTouches.item(0).clientX) / 2 -
706                       gGLMapCanvas.offsetLeft;
707               var y = (aEvent.targetTouches.item(1).clientY +
708                        aEvent.targetTouches.item(0).clientY) / 2 -
709                       gGLMapCanvas.offsetTop;
710
711               // Zoom factor after this action.
712               var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
713               gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
714               gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
715
716               if (gPinchStartWidth < curPinchStartWidth)
717                 zoomIn();
718               else
719                 zoomOut();
720
721               // Reset pinch start width and start another pinch gesture.
722               gPinchStartWidth = null;
723             }
724           }
725           // If we are in a pinch, do not drag.
726           break;
727         }
728         var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
729         var y = coordObj.clientY - gGLMapCanvas.offsetTop;
730         if (gDragging === true) {
731           var dX = x - gLastMouseX;
732           var dY = y - gLastMouseY;
733           gMap.pos.x -= dX * gMap.zoomFactor;
734           gMap.pos.y -= dY * gMap.zoomFactor;
735           gMap.draw();
736           showUI();
737         }
738         gLastMouseX = x;
739         gLastMouseY = y;
740         break;
741       case "mouseup":
742       case "touchend":
743         gPinchStartWidth = null;
744         gDragging = false;
745         showUI();
746         break;
747       case "mouseout":
748       case "touchcancel":
749       case "touchleave":
750         //gDragging = false;
751         break;
752       case "wheel":
753         // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
754         // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
755
756         // Only accept (non-null) deltaY values
757         if (!aEvent.deltaY)
758           break;
759
760         // Debug output: "coordinates" of the point the mouse was over.
761         /*
762         var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
763                        y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
764         var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
765         var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
766         console.log(ptCoord.x + "/" + ptCoord.y + " - " +
767                     gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
768                     pt2Coord.x + "/" + pt2Coord.y);
769         */
770
771         var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
772         if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
773           // Calculate new center of the map - same point stays under the mouse.
774           // This means that the pixel distance between the old center and point
775           // must equal the pixel distance of the new center and that point.
776           var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
777           var y = coordObj.clientY - gGLMapCanvas.offsetTop;
778
779           // Zoom factor after this action.
780           var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
781           gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
782           gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
783
784           if (aEvent.deltaY < 0)
785             zoomIn();
786           else
787             zoomOut();
788         }
789         break;
790       case "keydown":
791         // Allow keyboard control to move and zoom the map.
792         // Should use aEvent.key instead of aEvent.which but needs bug 680830.
793         // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
794         var dX = 0;
795         var dY = 0;
796         switch (aEvent.which) {
797           case 39: // right
798             dX = -gMap.tileSize / 2;
799           break;
800           case 37: // left
801             dX = gMap.tileSize / 2;
802           break;
803           case 38: // up
804             dY = gMap.tileSize / 2;
805           break;
806           case 40: // down
807             dY = -gMap.tileSize / 2;
808           break;
809           case 87: // w
810           case 107: // + (numpad)
811           case 171: // + (normal key)
812             zoomIn();
813           break;
814           case 83: // s
815           case 109: // - (numpad)
816           case 173: // - (normal key)
817             zoomOut();
818           break;
819           case 48: // 0
820           case 49: // 1
821           case 50: // 2
822           case 51: // 3
823           case 52: // 4
824           case 53: // 5
825           case 54: // 6
826           case 55: // 7
827           case 56: // 8
828             zoomTo(aEvent.which - 38);
829           break;
830           case 57: // 9
831             zoomTo(9);
832           break;
833           case 96: // 0 (numpad)
834           case 97: // 1 (numpad)
835           case 98: // 2 (numpad)
836           case 99: // 3 (numpad)
837           case 100: // 4 (numpad)
838           case 101: // 5 (numpad)
839           case 102: // 6 (numpad)
840           case 103: // 7 (numpad)
841           case 104: // 8 (numpad)
842             zoomTo(aEvent.which - 86);
843           break;
844           case 105: // 9 (numpad)
845             zoomTo(9);
846           break;
847           default: // not supported
848             console.log("key not supported: " + aEvent.which);
849           break;
850         }
851
852         // Move if needed.
853         if (dX || dY) {
854           gMap.pos.x -= dX * gMap.zoomFactor;
855           gMap.pos.y -= dY * gMap.zoomFactor;
856           gMap.draw();
857         }
858         break;
859     }
860   }
861 };
862
863 var geofake = {
864   tracking: false,
865   lastPos: {x: undefined, y: undefined},
866   watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
867     this.tracking = true;
868     var watchCall = function() {
869       // calc new position in lat/lon degrees
870       // 90° on Earth surface are ~10,000 km at the equator,
871       // so try moving at most 10m at a time
872       if (geofake.lastPos.x)
873         geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
874       else
875         geofake.lastPos.x = 48.208174
876       if (geofake.lastPos.y)
877         geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
878       else
879         geofake.lastPos.y = 16.373819
880       aSuccessCallback({timestamp: Date.now(),
881                         coords: {latitude: geofake.lastPos.x,
882                                  longitude: geofake.lastPos.y,
883                                  accuracy: 20}});
884       if (geofake.tracking)
885         setTimeout(watchCall, 1000);
886     };
887     setTimeout(watchCall, 1000);
888     return "foo";
889   },
890   clearWatch: function(aID) {
891     this.tracking = false;
892   }
893 }
894
895 function setCentering(aCheckbox) {
896   if (gMapPrefsLoaded && mainDB)
897     gPrefs.set("center_map", aCheckbox.checked);
898   gCenterPosition = aCheckbox.checked;
899 }
900
901 function setTracking(aCheckbox) {
902   if (gMapPrefsLoaded && mainDB)
903     gPrefs.set("tracking_enabled", aCheckbox.checked);
904   if (aCheckbox.checked)
905     startTracking();
906   else
907     endTracking();
908 }
909
910 function startTracking() {
911   if (gGeolocation) {
912     gActionLabel.textContent = "Establishing Position";
913     gAction.style.display = "block";
914     gGeoWatchID = gGeolocation.watchPosition(
915       function(position) {
916         if (gActionLabel.textContent) {
917           gActionLabel.textContent = "";
918           gAction.style.display = "none";
919         }
920         // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
921         var tPoint = {time: position.timestamp,
922                       coords: {latitude: position.coords.latitude,
923                                longitude: position.coords.longitude,
924                                altitude: position.coords.altitude,
925                                accuracy: position.coords.accuracy,
926                                altitudeAccuracy: position.coords.altitudeAccuracy,
927                                heading: position.coords.heading,
928                                speed: position.coords.speed},
929                       beginSegment: !gLastTrackPoint};
930         // Only add point to track is accuracy is good enough.
931         if (tPoint.coords.accuracy < gMinTrackAccuracy) {
932           gLastTrackPoint = tPoint;
933           gTrack.push(tPoint);
934           try { gTrackStore.push(tPoint); } catch(e) {}
935           var redrawn = false;
936           if (gCenterPosition) {
937             var posCoord = gps2xy(position.coords.latitude,
938                                   position.coords.longitude);
939             if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
940                 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
941               gMap.pos.x = posCoord.x;
942               gMap.pos.y = posCoord.y;
943               gMap.draw(); // This draws the current point as well.
944               redrawn = true;
945             }
946           }
947           if (!redrawn)
948             undrawCurrentLocation();
949             drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
950         }
951         drawCurrentLocation(tPoint);
952       },
953       function(error) {
954         // Ignore erros for the moment, but this is good for debugging.
955         // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
956         if (gDebug)
957           console.log(error.message);
958       },
959       {enableHighAccuracy: true}
960     );
961   }
962 }
963
964 function endTracking() {
965   if (gActionLabel.textContent) {
966     gActionLabel.textContent = "";
967     gAction.style.display = "none";
968   }
969   if (gGeoWatchID) {
970     gGeolocation.clearWatch(gGeoWatchID);
971   }
972 }
973
974 function clearTrack() {
975   gTrack = [];
976   gTrackStore.clear();
977   drawTrack();
978 }
979
980 var gTileService = {
981   objStore: "tilecache",
982
983   ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
984
985   get: function(aStyle, aCoords, aCallback) {
986     var norm = normalizeCoords(aCoords);
987     var dbkey = getTileKey(aStyle, norm);
988     this.getDBCache(dbkey, function(aResult, aEvent) {
989       if (aResult) {
990         // We did get a cached object.
991         aCallback(aResult.image, aStyle, aCoords, dbkey);
992         // Look at the timestamp and return if it's not too old.
993         if (aResult.timestamp + gTileService.ageLimit > Date.now())
994           return;
995         // Reload cached tile otherwise.
996         var oldDate = new Date(aResult.timestamp);
997         console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
998       }
999       // Retrieve image from the web and store it in the cache.
1000       var XHR = new XMLHttpRequest();
1001       XHR.open("GET",
1002                 gMapStyles[aStyle].url
1003                   .replace("{x}", norm.x)
1004                   .replace("{y}", norm.y)
1005                   .replace("{z}", norm.z)
1006                   .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
1007                   .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
1008                 true);
1009       XHR.responseType = "blob";
1010       XHR.addEventListener("load", function () {
1011         if (XHR.status === 200) {
1012           var blob = XHR.response;
1013           aCallback(blob, aStyle, aCoords, dbkey);
1014           gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1015         }
1016       }, false);
1017       XHR.send();
1018     });
1019   },
1020
1021   getDBCache: function(aKey, aCallback) {
1022     if (!mainDB)
1023       return;
1024     var transaction = mainDB.transaction([this.objStore]);
1025     var request = transaction.objectStore(this.objStore).get(aKey);
1026     request.onsuccess = function(event) {
1027       aCallback(request.result, event);
1028     };
1029     request.onerror = function(event) {
1030       // Errors can be handled here.
1031       aCallback(undefined, event);
1032     };
1033   },
1034
1035   setDBCache: function(aKey, aValue, aCallback) {
1036     if (!mainDB)
1037       return;
1038     var success = false;
1039     var transaction = mainDB.transaction([this.objStore], "readwrite");
1040     var objStore = transaction.objectStore(this.objStore);
1041     var request = objStore.put(aValue, aKey);
1042     request.onsuccess = function(event) {
1043       success = true;
1044       if (aCallback)
1045         aCallback(success, event);
1046     };
1047     request.onerror = function(event) {
1048       // Errors can be handled here.
1049       if (aCallback)
1050         aCallback(success, event);
1051     };
1052   },
1053
1054   unsetDBCache: function(aKey, aCallback) {
1055     if (!mainDB)
1056       return;
1057     var success = false;
1058     var transaction = mainDB.transaction([this.objStore], "readwrite");
1059     var request = transaction.objectStore(this.objStore).delete(aKey);
1060     request.onsuccess = function(event) {
1061       success = true;
1062       if (aCallback)
1063         aCallback(success, event);
1064     };
1065     request.onerror = function(event) {
1066       // Errors can be handled here.
1067       if (aCallback)
1068         aCallback(success, event);
1069     }
1070   },
1071
1072   clearDB: function(aCallback) {
1073     if (!mainDB)
1074       return;
1075     var success = false;
1076     var transaction = mainDB.transaction([this.objStore], "readwrite");
1077     var request = transaction.objectStore(this.objStore).clear();
1078     request.onsuccess = function(event) {
1079       success = true;
1080       if (aCallback)
1081         aCallback(success, event);
1082     };
1083     request.onerror = function(event) {
1084       // Errors can be handled here.
1085       if (aCallback)
1086         aCallback(success, event);
1087     }
1088   }
1089 };