babylon.database.js 22 KB

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