babylon.database.ts 24 KB

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