babylon.database.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  97. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  98. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  99. } catch (ex) {
  100. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  101. handleError();
  102. }
  103. };
  104. } else {
  105. if (successCallback)
  106. successCallback();
  107. }
  108. }
  109. };
  110. Database.prototype.loadImageFromDB = function (url, image) {
  111. var _this = this;
  112. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  113. var saveAndLoadImage = function () {
  114. if (!_this.hasReachedQuota && _this.db !== null) {
  115. // the texture is not yet in the DB, let's try to save it
  116. _this._saveImageIntoDBAsync(completeURL, image);
  117. } else {
  118. image.src = url;
  119. }
  120. };
  121. if (!this.mustUpdateRessources) {
  122. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  123. } else {
  124. saveAndLoadImage();
  125. }
  126. };
  127. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  128. if (this.isSupported && this.db !== null) {
  129. var texture;
  130. var transaction = this.db.transaction(["textures"]);
  131. transaction.onabort = function (event) {
  132. image.src = url;
  133. };
  134. transaction.oncomplete = function (event) {
  135. var blobTextureURL;
  136. if (texture) {
  137. var URL = window.URL || window.webkitURL;
  138. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  139. image.onerror = function () {
  140. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  141. image.src = url;
  142. };
  143. image.src = blobTextureURL;
  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. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  154. image.src = url;
  155. };
  156. } else {
  157. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  158. image.src = url;
  159. }
  160. };
  161. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  162. var _this = this;
  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. } catch (ex) {
  172. blobTextureURL = URL.createObjectURL(blob);
  173. }
  174. }
  175. image.src = blobTextureURL;
  176. };
  177. if (BABYLON.Database.isUASupportingBlobStorage) {
  178. var xhr = new XMLHttpRequest(), blob;
  179. xhr.open("GET", url, true);
  180. xhr.responseType = "blob";
  181. xhr.addEventListener("load", function () {
  182. if (xhr.status === 200) {
  183. // Blob as response (XHR2)
  184. blob = xhr.response;
  185. var transaction = _this.db.transaction(["textures"], "readwrite");
  186. // the transaction could abort because of a QuotaExceededError error
  187. transaction.onabort = function (event) {
  188. try {
  189. if (event.srcElement.error.name === "QuotaExceededError") {
  190. this.hasReachedQuota = true;
  191. }
  192. } catch (ex) {
  193. }
  194. generateBlobUrl();
  195. };
  196. transaction.oncomplete = function (event) {
  197. generateBlobUrl();
  198. };
  199. var newTexture = { textureUrl: url, data: blob };
  200. try {
  201. // Put the blob into the dabase
  202. var addRequest = transaction.objectStore("textures").put(newTexture);
  203. addRequest.onsuccess = function (event) {
  204. };
  205. addRequest.onerror = function (event) {
  206. generateBlobUrl();
  207. };
  208. } catch (ex) {
  209. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  210. if (ex.code === 25) {
  211. BABYLON.Database.isUASupportingBlobStorage = false;
  212. }
  213. image.src = url;
  214. }
  215. } else {
  216. image.src = url;
  217. }
  218. }, false);
  219. xhr.addEventListener("error", function (event) {
  220. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  221. image.src = url;
  222. }, false);
  223. xhr.send();
  224. } else {
  225. image.src = url;
  226. }
  227. } else {
  228. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  229. image.src = url;
  230. }
  231. };
  232. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  233. var _this = this;
  234. var updateVersion = function (event) {
  235. // the version is not yet in the DB or we need to update it
  236. _this._saveVersionIntoDBAsync(url, versionLoaded);
  237. };
  238. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  239. };
  240. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  241. var _this = this;
  242. if (this.isSupported) {
  243. var version;
  244. try {
  245. var transaction = this.db.transaction(["versions"]);
  246. transaction.oncomplete = function (event) {
  247. if (version) {
  248. // If the version in the JSON file is > than the version in DB
  249. if (_this.manifestVersionFound > version.data) {
  250. _this.mustUpdateRessources = true;
  251. updateInDBCallback();
  252. } else {
  253. callback(version.data);
  254. }
  255. } else {
  256. _this.mustUpdateRessources = true;
  257. updateInDBCallback();
  258. }
  259. };
  260. transaction.onabort = function (event) {
  261. callback(-1);
  262. };
  263. var getRequest = transaction.objectStore("versions").get(url);
  264. getRequest.onsuccess = function (event) {
  265. version = (event.target).result;
  266. };
  267. getRequest.onerror = function (event) {
  268. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  269. callback(-1);
  270. };
  271. } catch (ex) {
  272. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  273. callback(-1);
  274. }
  275. } else {
  276. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  277. callback(-1);
  278. }
  279. };
  280. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  281. var _this = this;
  282. if (this.isSupported && !this.hasReachedQuota) {
  283. try {
  284. // Open a transaction to the database
  285. var transaction = this.db.transaction(["versions"], "readwrite");
  286. // the transaction could abort because of a QuotaExceededError error
  287. transaction.onabort = function (event) {
  288. try {
  289. if (event.srcElement.error.name === "QuotaExceededError") {
  290. _this.hasReachedQuota = true;
  291. }
  292. } catch (ex) {
  293. }
  294. callback(-1);
  295. };
  296. transaction.oncomplete = function (event) {
  297. callback(_this.manifestVersionFound);
  298. };
  299. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  300. // Put the scene into the database
  301. var addRequest = transaction.objectStore("versions").put(newVersion);
  302. addRequest.onsuccess = function (event) {
  303. };
  304. addRequest.onerror = function (event) {
  305. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  306. };
  307. } catch (ex) {
  308. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  309. callback(-1);
  310. }
  311. } else {
  312. callback(-1);
  313. }
  314. };
  315. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  316. var _this = this;
  317. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  318. var saveAndLoadFile = function (event) {
  319. // the scene is not yet in the DB, let's try to save it
  320. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  321. };
  322. this._checkVersionFromDB(completeUrl, function (version) {
  323. if (version !== -1) {
  324. if (!_this.mustUpdateRessources) {
  325. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  326. } else {
  327. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  328. }
  329. } else {
  330. errorCallback();
  331. }
  332. });
  333. };
  334. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  335. if (this.isSupported) {
  336. var targetStore;
  337. if (url.indexOf(".babylon") !== -1) {
  338. targetStore = "scenes";
  339. } else {
  340. targetStore = "textures";
  341. }
  342. var file;
  343. var transaction = this.db.transaction([targetStore]);
  344. transaction.oncomplete = function (event) {
  345. if (file) {
  346. callback(file.data);
  347. } else {
  348. notInDBCallback();
  349. }
  350. };
  351. transaction.onabort = function (event) {
  352. notInDBCallback();
  353. };
  354. var getRequest = transaction.objectStore(targetStore).get(url);
  355. getRequest.onsuccess = function (event) {
  356. file = (event.target).result;
  357. };
  358. getRequest.onerror = function (event) {
  359. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  360. notInDBCallback();
  361. };
  362. } else {
  363. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  364. callback();
  365. }
  366. };
  367. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  368. var _this = this;
  369. if (this.isSupported) {
  370. var targetStore;
  371. if (url.indexOf(".babylon") !== -1) {
  372. targetStore = "scenes";
  373. } else {
  374. targetStore = "textures";
  375. }
  376. // Create XHR
  377. var xhr = new XMLHttpRequest(), fileData;
  378. xhr.open("GET", url, true);
  379. if (useArrayBuffer) {
  380. xhr.responseType = "arraybuffer";
  381. }
  382. xhr.onprogress = progressCallback;
  383. xhr.addEventListener("load", function () {
  384. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  385. // Blob as response (XHR2)
  386. //fileData = xhr.responseText;
  387. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  388. if (!_this.hasReachedQuota) {
  389. // Open a transaction to the database
  390. var transaction = _this.db.transaction([targetStore], "readwrite");
  391. // the transaction could abort because of a QuotaExceededError error
  392. transaction.onabort = function (event) {
  393. try {
  394. if (event.srcElement.error.name === "QuotaExceededError") {
  395. this.hasReachedQuota = true;
  396. }
  397. } catch (ex) {
  398. }
  399. callback(fileData);
  400. };
  401. transaction.oncomplete = function (event) {
  402. callback(fileData);
  403. };
  404. var newFile;
  405. if (targetStore === "scenes") {
  406. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  407. } else {
  408. newFile = { textureUrl: url, data: fileData };
  409. }
  410. try {
  411. // Put the scene into the database
  412. var addRequest = transaction.objectStore(targetStore).put(newFile);
  413. addRequest.onsuccess = function (event) {
  414. };
  415. addRequest.onerror = function (event) {
  416. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  417. };
  418. } catch (ex) {
  419. callback(fileData);
  420. }
  421. } else {
  422. callback(fileData);
  423. }
  424. } else {
  425. callback();
  426. }
  427. }, false);
  428. xhr.addEventListener("error", function (event) {
  429. BABYLON.Tools.Error("error on XHR request.");
  430. callback();
  431. }, false);
  432. xhr.send();
  433. } else {
  434. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  435. callback();
  436. }
  437. };
  438. Database.isUASupportingBlobStorage = true;
  439. Database.parseURL = function (url) {
  440. var a = document.createElement('a');
  441. a.href = url;
  442. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  443. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  444. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  445. return absLocation;
  446. };
  447. Database.ReturnFullUrlLocation = function (url) {
  448. if (url.indexOf("http:/") === -1) {
  449. return (BABYLON.Database.parseURL(window.location.href) + url);
  450. } else {
  451. return url;
  452. }
  453. };
  454. return Database;
  455. })();
  456. BABYLON.Database = Database;
  457. })(BABYLON || (BABYLON = {}));
  458. //# sourceMappingURL=babylon.database.js.map