Try to handle GL context losses
[lantea.git] / js / map.js
index dbc6904715b1e6c12d9a7d0feeef7dda6d04c711..ec9a05c0c0d324fdaf8384552d2bb8fd197e082b 100644 (file)
--- a/js/map.js
+++ b/js/map.js
@@ -72,11 +72,19 @@ function initMap() {
               gGLMapCanvas.getContext("experimental-webgl", {depth: false});
   }
   catch(e) {}
-  // If we don't have a GL context, give up now
   if (!gMap.gl) {
+    // If we don't have a GL context, give up now
     showGLWarningDialog();
     gMap.gl = null;
   }
+  else {
+    // GL context can be lost at any time, handle that.
+    // See http://www.khronos.org/webgl/wiki/HandlingContextLost
+    gGLMapCanvas.addEventListener("webglcontextlost",
+                                  gMap.handleContextLost, false);
+    gGLMapCanvas.addEventListener("webglcontextrestored",
+                                  gMap.handleContextRestored, false);
+  }
   gTrackCanvas = document.getElementById("track");
   gTrackContext = gTrackCanvas.getContext("2d");
   if (!gMap.activeMap)
@@ -203,7 +211,8 @@ var gMap = {
   glResolutionAttr: null,
   glMapTexture: null,
   glTextures: {},
-  glTextureKeys: {},
+  glTxCleanIntervalID: null,
+  glTexturesPerZoomLevel: 0,
 
   activeMap: "osm_mapnik",
   tileSize: 256,
@@ -214,6 +223,11 @@ var gMap = {
     y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
     z: 5           // This could be fractional if supported being between zoom levels.
   },
+  baseDim: { // Map width, height and tile size in level 18 pixels.
+    wid: null,
+    ht: null,
+    tsize: null,
+  },
 
   get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
   get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
@@ -229,7 +243,7 @@ var gMap = {
     '  gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
     '  vTextureCoord = aTextureCoord;\n' +
     '}'; },
-  getFragShaderSource:function() {
+  getFragShaderSource: function() {
     return 'varying highp vec2 vTextureCoord;\n\n' +
     'uniform sampler2D uImage;\n\n' +
     'void main(void) {\n' +
@@ -292,7 +306,7 @@ var gMap = {
       gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
       gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
 
-      gMap.loadImageToTexture(gLoadingTile, 0, "loading::0,0,0");
+      gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
 
       gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
 
@@ -301,10 +315,18 @@ var gMap = {
       gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
       gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
       gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
+
+      // Call texture cleaning every 30 seconds, for now (is 60 better?).
+      gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000);
     }
 
-    var throwEv = new CustomEvent("mapinit-done");
-    gAction.dispatchEvent(throwEv);
+    if (!gAppInitDone) {
+      // We may be called when context was lost and destroyed,
+      // only send event when we are in app startup
+      // (gAppInitDone is set to true right after we return this event).
+      var throwEv = new CustomEvent("mapinit-done");
+      gAction.dispatchEvent(throwEv);
+    }
   },
 
   draw: function() {
@@ -317,25 +339,25 @@ var gMap = {
 
     document.getElementById("zoomLevel").textContent = gMap.pos.z;
     gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
-    var wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor; // Width in level 18 pixels.
-    var ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor; // Height in level 18 pixels.
-    var size = gMap.tileSize * gMap.zoomFactor; // Tile size in level 18 pixels.
+    gMap.baseDim.wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor;
+    gMap.baseDim.ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor;
+    gMap.baseDim.tsize = gMap.tileSize * gMap.zoomFactor;
 
-    var xMin = gMap.pos.x - wid / 2; // Corners of the window in level 18 pixels.
-    var yMin = gMap.pos.y - ht / 2;
-    var xMax = gMap.pos.x + wid / 2;
-    var yMax = gMap.pos.y + ht / 2;
+    var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
+    var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
+    var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
+    var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
 
     if (gMapPrefsLoaded && mainDB)
       gPrefs.set("position", gMap.pos);
 
     // Go through all the tiles in the map, find out if to draw them and do so.
-    for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
-      for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
+    for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
+      for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
         // Only go to loading step if we haven't loaded the texture.
         var coords = {x: x, y: y, z: gMap.pos.z};
         var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
-        if (!gMap.glTextureKeys[tileKey]) {
+        if (!gMap.glTextures[tileKey]) {
           // Initiate loading/drawing of the actual tile.
           gTileService.get(gMap.activeMap, coords,
                            function(aImage, aStyle, aCoords, aTileKey) {
@@ -345,10 +367,8 @@ var gMap = {
               var imgURL = URL.createObjectURL(aImage);
               var imgObj = new Image();
               imgObj.onload = function() {
-                var txNr = 1;
-                while (gMap.glTextures["tx" + txNr]) { txNr++; }
-                gMap.loadImageToTexture(imgObj, txNr, aTileKey);
-                requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
+                gMap.loadImageToTexture(imgObj, aTileKey);
+                window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
                 URL.revokeObjectURL(imgURL);
               }
               imgObj.src = imgURL;
@@ -357,37 +377,30 @@ var gMap = {
         }
       }
     }
-    requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
+    window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
   },
 
   drawGL: function() {
-    var wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor; // Width in level 18 pixels.
-    var ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor; // Height in level 18 pixels.
-    var size = gMap.tileSize * gMap.zoomFactor; // Tile size in level 18 pixels.
-
-    var xMin = gMap.pos.x - wid / 2; // Corners of the window in level 18 pixels.
-    var yMin = gMap.pos.y - ht / 2;
-    var xMax = gMap.pos.x + wid / 2;
-    var yMax = gMap.pos.y + ht / 2;
+    var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
+    var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
+    var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
+    var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
 
-    var txIndexList = [];
     // Go through all the tiles in the map, find out if to draw them and do so.
-    for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
-      for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
-        // Round here is **CRUCIAL** otherwise the images are filtered
-        // and the performance sucks (more than expected).
-        var xoff = Math.round((x * size - xMin) / gMap.zoomFactor);
-        var yoff = Math.round((y * size - yMin) / gMap.zoomFactor);
-        // Draw the tile, first find out the index of the texture to use.
+    for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
+      for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
+        // Rounding the pixel offsets ensures we position the tiles precisely.
+        var xoff = Math.round((x * gMap.baseDim.tsize - xMin) / gMap.zoomFactor);
+        var yoff = Math.round((y * gMap.baseDim.tsize - yMin) / gMap.zoomFactor);
+        // Draw the tile, first find out the actual texture to use.
         var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
         var tileKey = getTileKey(gMap.activeMap, norm);
-        var txIndex = gMap.glTextureKeys[tileKey];
-        if (!txIndex) { txIndex = 0; }
-        txIndexList.push(txIndex);
-        gMap.drawTileGL(xoff, yoff, txIndex);
+        if (!gMap.glTextures[tileKey]) {
+          tileKey = getTileKey("loading", {x: 0, y: 0, z: 0});
+        }
+        gMap.drawTileGL(xoff, yoff, tileKey);
       }
     }
-    console.log("Used Indexes: " + txIndexList.join(","));
   },
 
   resizeAndDraw: function() {
@@ -405,15 +418,17 @@ var gMap = {
         gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
         // Make sure the vertex shader get the right resolution.
         gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
+        // Prepare recalculation of textures to keep for one zoom level.
+        gMap.glTexturesPerZoomLevel = 0;
       }
       gMap.draw();
       showUI();
     }
   },
 
-  drawTileGL: function(aLeft, aRight, aTextureIndex) {
+  drawTileGL: function(aLeft, aRight, aTileKey) {
     gMap.gl.activeTexture(gMap.gl.TEXTURE0);
-    gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures["tx" + aTextureIndex]);
+    gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
     // Set uImage to refer to TEXTURE0
     gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
     var x_start = aLeft;
@@ -434,18 +449,88 @@ var gMap = {
     gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
   },
 
-  loadImageToTexture: function(aImage, aTextureIndex, aTileKey) {
-    // TODO: Get rid of old textures.
-    gMap.glTextureKeys[aTileKey] = aTextureIndex;
+  loadImageToTexture: function(aImage, aTileKey) {
     // Create and bind texture.
-    gMap.glTextures["tx" + aTextureIndex] = gMap.gl.createTexture();
-    gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures["tx" + aTextureIndex]);
+    gMap.glTextures[aTileKey] = gMap.gl.createTexture();
+    gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
     // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
     gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
     gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
     // Upload the image into the texture.
     gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
   },
+
+  cleanTextures: function() {
+    // Get rid of unneeded textures to save memory.
+    // TODO: Be less aggressive, maybe keep neighboring zoom levels (but x/y coords there are zoom-specific).
+    if (!gMap.glTexturesPerZoomLevel) {
+      // Calculate how many textures we need to keep for one zoom level.
+      // ceil(width/size) gives us the minimum, keep one on either side as well.
+      gMap.glTexturesPerZoomLevel =
+        Math.ceil(gMap.gl.drawingBufferWidth / gMap.tileSize + 2) *
+        Math.ceil(gMap.gl.drawingBufferHeight / gMap.tileSize + 2);
+      console.log("Keeping " + gMap.glTexturesPerZoomLevel + " textures per level");
+    }
+    if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) {
+      console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)");
+
+      // Find coordinate ranges for tiles to keep.
+      var tMin = normalizeCoords({x: Math.floor((gMap.pos.x - gMap.baseDim.wid / 2) / gMap.baseDim.tsize) - 1,
+                                  y: Math.floor((gMap.pos.y - gMap.baseDim.ht / 2) / gMap.baseDim.tsize) - 1,
+                                  z: gMap.pos.z});
+      var tMax = normalizeCoords({x: Math.ceil((gMap.pos.x + gMap.baseDim.wid / 2) / gMap.baseDim.tsize) + 1,
+                                  y: Math.ceil((gMap.pos.y + gMap.baseDim.ht / 2) / gMap.baseDim.tsize) + 1,
+                                  z: gMap.pos.z});
+      console.log("In range: " + tMin.x + "," + tMin.y + "," + tMin.z + " - " + tMax.x + "," + tMax.y + "," + tMax.z);
+      for (aTileKey in gMap.glTextures) {
+        var keyMatches = aTileKey.match(/([^:]+)::(\d+),(\d+),(\d+)/);
+        if (keyMatches && keyMatches[1] != "loading") {
+          var txData = {
+            style: keyMatches[1],
+            x: keyMatches[2],
+            y: keyMatches[3],
+            z: keyMatches[4],
+          }
+          var delTx = false;
+          if (txData.style != gMap.activeMap) { delTx = true; console.log("Different map style: " + txData.style); }
+          if (!delTx && (txData.z < tMin.z || txData.z > tMax.z)) { delTx = true; console.log("Out-of-range zoom: " + txData.z); }
+          if (tMin.x < tMax.x) {
+            if (!delTx && (txData.x < tMin.x || txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
+          }
+          else {
+            // We are crossing over the 0 coordinate!
+            if (!delTx && (txData.x < tMin.x && txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
+          }
+          if (tMin.y < tMax.y) {
+            if (!delTx && (txData.y < tMin.y || txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
+          }
+          else {
+            // We are crossing over the 0 coordinate!
+            if (!delTx && (txData.y < tMin.y && txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
+          }
+          if (delTx) {
+            // Delete texture from GL and from the array we are holding.
+            gMap.gl.deleteTexture(gMap.glTextures[aTileKey]);
+            delete gMap.glTextures[aTileKey];
+          }
+        }
+      }
+      console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left)");
+    }
+  },
+
+  handleContextLost: function(event) {
+    event.preventDefault();
+    // GL context is gone, let's reset everything that depends on it.
+    clearInterval(gMap.glTxCleanIntervalID);
+    gMap.glTextures = {};
+  },
+
+  handleContextRestored: function(event) {
+    // When GL context is back, init GL again and draw.
+    gMap.initGL();
+    gMap.draw();
+  },
 }
 
 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.