babylon.database.js 23 KB

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