babylon.database.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. var BABYLON = BABYLON || {};
  2. (function () {
  3. // Handling various flavors of prefixed version of IndexedDB
  4. window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB ||
  5. window.msIndexedDB;
  6. window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction ||
  7. window.msIDBTransaction;
  8. window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
  9. BABYLON.Database = function (urlToScene) {
  10. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  11. this.db = null;
  12. this.enableSceneOffline = false;
  13. this.enableTexturesOffline = false;
  14. this.manifestVersionFound = 0;
  15. this.mustUpdateRessources = false;
  16. this.hasReachedQuota = false;
  17. this.checkManifestFile();
  18. };
  19. BABYLON.Database.isUASupportingBlobStorage = true;
  20. function parseURL(url) {
  21. var a = document.createElement('a');
  22. a.href = url;
  23. var fileName = url.substring(url.lastIndexOf("/") + 1, url.length);
  24. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  25. return absLocation;
  26. };
  27. BABYLON.Database.ReturnFullUrlLocation = function (url) {
  28. if (url.indexOf("http:/") === -1) {
  29. return (parseURL(window.location.href) + url);
  30. }
  31. else {
  32. return url;
  33. }
  34. };
  35. BABYLON.Database.prototype.checkManifestFile = function () {
  36. var that = this;
  37. var manifestURL = this.currentSceneUrl + ".manifest";
  38. var xhr = new XMLHttpRequest();
  39. xhr.open("GET", manifestURL, false);
  40. xhr.addEventListener("load", function () {
  41. if (xhr.status === 200) {
  42. try {
  43. manifestFile = JSON.parse(xhr.response);
  44. that.enableSceneOffline = manifestFile.enableSceneOffline;
  45. that.enableTexturesOffline = manifestFile.enableTexturesOffline;
  46. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  47. that.manifestVersionFound = manifestFile.version;
  48. }
  49. }
  50. catch (ex) {
  51. that.enableSceneOffline = false;
  52. that.enableTexturesOffline = false;
  53. }
  54. }
  55. else {
  56. that.enableSceneOffline = false;
  57. that.enableTexturesOffline = false;
  58. }
  59. }, false);
  60. xhr.addEventListener("error", function (event) {
  61. that.enableSceneOffline = false;
  62. that.enableTexturesOffline = false;
  63. }, false);
  64. xhr.send();
  65. };
  66. BABYLON.Database.prototype.openAsync = function (successCallback, errorCallback) {
  67. var that = this;
  68. if (!window.indexedDB || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  69. // Your browser doesn't support IndexedDB
  70. this.isSupported = false;
  71. if (errorCallback) errorCallback();
  72. }
  73. else {
  74. // If the DB hasn't been opened or created yet
  75. if (!this.db) {
  76. this.hasReachedQuota = false;
  77. this.isSupported = true;
  78. var request = window.indexedDB.open("babylonjs", 1.0);
  79. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  80. request.onerror = function (event) {
  81. that.isSupported = false;
  82. if (errorCallback) errorCallback();
  83. };
  84. // executes when a version change transaction cannot complete due to other active transactions
  85. request.onblocked = function (event) {
  86. console.log("IDB request blocked. Please reload the page.");
  87. if (errorCallback) errorCallback();
  88. };
  89. // DB has been opened successfully
  90. request.onsuccess = function (event) {
  91. that.db = request.result;
  92. successCallback();
  93. };
  94. // Initialization of the DB. Creating Scenes & Textures stores
  95. request.onupgradeneeded = function (event) {
  96. that.db = event.target.result;
  97. var scenesStore = that.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  98. var scenesStore = that.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  99. var texturesStore = that.db.createObjectStore("textures", { keyPath: "textureUrl" });
  100. };
  101. }
  102. // DB has already been created and opened
  103. else {
  104. if (successCallback) successCallback();
  105. }
  106. }
  107. };
  108. BABYLON.Database.prototype.loadImageFromDB = function (url, image) {
  109. var that = this;
  110. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  111. var saveAndLoadImage = function (event) {
  112. if (!that.hasReachedQuota && that.db !== null) {
  113. // the texture is not yet in the DB, let's try to save it
  114. that._saveImageIntoDBAsync(completeURL, image);
  115. }
  116. // If the texture is not in the DB and we've reached the DB quota limit
  117. // let's load it directly from the web
  118. else {
  119. image.src = url;
  120. }
  121. };
  122. if (!this.mustUpdateRessources) {
  123. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  124. }
  125. // First time we're download the images or update requested in the manifest file by a version change
  126. else {
  127. saveAndLoadImage();
  128. }
  129. };
  130. BABYLON.Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  131. if (this.isSupported && this.db !== null) {
  132. var texture;
  133. var transaction = this.db.transaction(["textures"]);
  134. transaction.onabort = function (event) {
  135. image.src = url;
  136. };
  137. transaction.oncomplete = function (event) {
  138. var blobTextureURL;
  139. if (texture) {
  140. var URL = window.URL || window.webkitURL;
  141. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  142. image.src = blobTextureURL;
  143. }
  144. else {
  145. notInDBCallback();
  146. }
  147. };
  148. var getRequest = transaction.objectStore("textures").get(url);
  149. getRequest.onsuccess = function (event) {
  150. texture = event.target.result;
  151. };
  152. getRequest.onerror = function (event) {
  153. console.log("Error loading texture " + url + " from DB.");
  154. image.src = url;
  155. };
  156. }
  157. else {
  158. console.log("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  159. image.src = url;
  160. }
  161. };
  162. BABYLON.Database.prototype._saveImageIntoDBAsync = function (url, image) {
  163. if (this.isSupported) {
  164. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  165. var generateBlobUrl = function () {
  166. var blobTextureURL;
  167. if (blob) {
  168. var URL = window.URL || window.webkitURL;
  169. try {
  170. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  171. }
  172. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  173. catch (ex) {
  174. blobTextureURL = URL.createObjectURL(blob);
  175. }
  176. }
  177. image.src = blobTextureURL;
  178. };
  179. if (BABYLON.Database.isUASupportingBlobStorage) {
  180. var that = this;
  181. // Create XHR
  182. var xhr = new XMLHttpRequest(),
  183. blob;
  184. xhr.open("GET", url, true);
  185. xhr.responseType = "blob";
  186. xhr.addEventListener("load", function () {
  187. if (xhr.status === 200) {
  188. // Blob as response (XHR2)
  189. blob = xhr.response;
  190. var transaction = that.db.transaction(["textures"], "readwrite");
  191. // the transaction could abort because of a QuotaExceededError error
  192. transaction.onabort = function (event) {
  193. try {
  194. if (event.srcElement.error.name === "QuotaExceededError") {
  195. that.hasReachedQuota = true;
  196. }
  197. }
  198. catch (ex) { }
  199. generateBlobUrl();
  200. };
  201. transaction.oncomplete = function (event) {
  202. generateBlobUrl();
  203. };
  204. var newTexture = {};
  205. newTexture.textureUrl = url;
  206. newTexture.data = blob;
  207. try {
  208. // Put the blob into the dabase
  209. var addRequest = transaction.objectStore("textures").put(newTexture);
  210. addRequest.onsuccess = function (event) {
  211. };
  212. addRequest.onerror = function (event) {
  213. generateBlobUrl();
  214. };
  215. }
  216. catch (ex) {
  217. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  218. if (ex.code === 25) {
  219. BABYLON.Database.isUASupportingBlobStorage = false;
  220. }
  221. image.src = url;
  222. }
  223. }
  224. else {
  225. image.src = url;
  226. }
  227. }, false);
  228. xhr.addEventListener("error", function (event) {
  229. console.log("Error in XHR request in BABYLON.Database.");
  230. image.src = url;
  231. }, false);
  232. xhr.send();
  233. }
  234. else {
  235. image.src = url;
  236. }
  237. }
  238. else {
  239. console.log("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  240. image.src = url;
  241. }
  242. };
  243. BABYLON.Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  244. var that = this;
  245. var updateVersion = function (event) {
  246. // the version is not yet in the DB or we need to update it
  247. that._saveVersionIntoDBAsync(url, versionLoaded);
  248. };
  249. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  250. };
  251. BABYLON.Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  252. if (this.isSupported) {
  253. var version;
  254. var that = this;
  255. var transaction = this.db.transaction(["versions"]);
  256. transaction.oncomplete = function (event) {
  257. if (version) {
  258. // If the version in the JSON file is > than the version in DB
  259. if (that.manifestVersionFound > version.data) {
  260. that.mustUpdateRessources = true;
  261. updateInDBCallback();
  262. }
  263. else {
  264. callback(version.data);
  265. }
  266. }
  267. // version was not found in DB
  268. else {
  269. that.mustUpdateRessources = true;
  270. updateInDBCallback();
  271. }
  272. };
  273. transaction.onabort = function (event) {
  274. callback(-1);
  275. };
  276. var getRequest = transaction.objectStore("versions").get(url);
  277. getRequest.onsuccess = function (event) {
  278. version = event.target.result;
  279. };
  280. getRequest.onerror = function (event) {
  281. console.log("Error loading version for scene " + url + " from DB.");
  282. callback(-1);
  283. };
  284. }
  285. else {
  286. console.log("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  287. callback(-1);
  288. }
  289. };
  290. BABYLON.Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  291. if (this.isSupported && !this.hasReachedQuota) {
  292. var that = this;
  293. // Open a transaction to the database
  294. var transaction = this.db.transaction(["versions"], "readwrite");
  295. // the transaction could abort because of a QuotaExceededError error
  296. transaction.onabort = function (event) {
  297. try {
  298. if (event.srcElement.error.name === "QuotaExceededError") {
  299. that.hasReachedQuota = true;
  300. }
  301. }
  302. catch (ex) { }
  303. callback(-1);
  304. };
  305. transaction.oncomplete = function (event) {
  306. callback(that.manifestVersionFound);
  307. };
  308. var newVersion = {};
  309. newVersion.sceneUrl = url;
  310. newVersion.data = this.manifestVersionFound;
  311. try {
  312. // Put the scene into the database
  313. var addRequest = transaction.objectStore("versions").put(newVersion);
  314. addRequest.onsuccess = function (event) {
  315. };
  316. addRequest.onerror = function (event) {
  317. console.log("Error in DB add version request in BABYLON.Database.");
  318. };
  319. }
  320. catch (ex) {
  321. callback(-1);
  322. }
  323. }
  324. else {
  325. callback(-1);
  326. }
  327. };
  328. BABYLON.Database.prototype.loadSceneFromDB = function (url, sceneLoaded, progressCallBack) {
  329. var that = this;
  330. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  331. var saveAndLoadScene = function (event) {
  332. // the scene is not yet in the DB, let's try to save it
  333. that._saveSceneIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  334. };
  335. this._checkVersionFromDB(completeUrl, function (version) {
  336. if (!that.mustUpdateRessources) {
  337. that._loadSceneFromDBAsync(completeUrl, sceneLoaded, saveAndLoadScene);
  338. }
  339. else {
  340. that._saveSceneIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  341. }
  342. });
  343. };
  344. BABYLON.Database.prototype._loadSceneFromDBAsync = function (url, callback, notInDBCallback) {
  345. if (this.isSupported) {
  346. var scene;
  347. var transaction = this.db.transaction(["scenes"]);
  348. transaction.oncomplete = function (event) {
  349. if (scene) {
  350. callback(scene.data);
  351. }
  352. // scene was not found in DB
  353. else {
  354. notInDBCallback();
  355. }
  356. };
  357. transaction.onabort = function (event) {
  358. notInDBCallback();
  359. };
  360. var getRequest = transaction.objectStore("scenes").get(url);
  361. getRequest.onsuccess = function (event) {
  362. scene = event.target.result;
  363. };
  364. getRequest.onerror = function (event) {
  365. console.log("Error loading scene " + url + " from DB.");
  366. notInDBCallback();
  367. };
  368. }
  369. else {
  370. console.log("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  371. callback();
  372. }
  373. };
  374. BABYLON.Database.prototype._saveSceneIntoDBAsync = function (url, callback, progressCallback) {
  375. if (this.isSupported) {
  376. // Create XHR
  377. var xhr = new XMLHttpRequest(), sceneText;
  378. var that = this;
  379. xhr.open("GET", url, true);
  380. xhr.onprogress = progressCallback;
  381. xhr.addEventListener("load", function () {
  382. if (xhr.status === 200) {
  383. // Blob as response (XHR2)
  384. sceneText = xhr.responseText;
  385. if (!that.hasReachedQuota) {
  386. // Open a transaction to the database
  387. var transaction = that.db.transaction(["scenes"], "readwrite");
  388. // the transaction could abort because of a QuotaExceededError error
  389. transaction.onabort = function (event) {
  390. try {
  391. if (event.srcElement.error.name === "QuotaExceededError") {
  392. that.hasReachedQuota = true;
  393. }
  394. }
  395. catch (ex) { }
  396. callback(sceneText);
  397. };
  398. transaction.oncomplete = function (event) {
  399. callback(sceneText);
  400. };
  401. var newScene = {};
  402. newScene.sceneUrl = url;
  403. newScene.data = sceneText;
  404. newScene.version = that.manifestVersionFound;
  405. try {
  406. // Put the scene into the database
  407. var addRequest = transaction.objectStore("scenes").put(newScene);
  408. addRequest.onsuccess = function (event) {
  409. };
  410. addRequest.onerror = function (event) {
  411. console.log("Error in DB add scene request in BABYLON.Database.");
  412. };
  413. }
  414. catch (ex) {
  415. callback(sceneText);
  416. }
  417. }
  418. else {
  419. callback(sceneText);
  420. }
  421. }
  422. else {
  423. callback();
  424. }
  425. }, false);
  426. xhr.addEventListener("error", function (event) {
  427. console.log("error on XHR request.");
  428. callback();
  429. }, false);
  430. xhr.send();
  431. }
  432. else {
  433. console.log("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  434. callback();
  435. }
  436. };
  437. })();