babylon.tools.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. var BABYLON;
  2. (function (BABYLON) {
  3. // Screenshots
  4. var screenshotCanvas;
  5. // FPS
  6. var fpsRange = 60;
  7. var previousFramesDuration = [];
  8. var fps = 60;
  9. var deltaTime = 0;
  10. var cloneValue = function (source, destinationObject) {
  11. if (!source)
  12. return null;
  13. if (source instanceof BABYLON.Mesh) {
  14. return null;
  15. }
  16. if (source instanceof BABYLON.SubMesh) {
  17. return source.clone(destinationObject);
  18. } else if (source.clone) {
  19. return source.clone();
  20. }
  21. return null;
  22. };
  23. var Tools = (function () {
  24. function Tools() {
  25. }
  26. Tools.GetFilename = function (path) {
  27. var index = path.lastIndexOf("/");
  28. if (index < 0)
  29. return path;
  30. return path.substring(index + 1);
  31. };
  32. Tools.GetDOMTextContent = function (element) {
  33. var result = "";
  34. var child = element.firstChild;
  35. while (child) {
  36. if (child.nodeType == 3) {
  37. result += child.textContent;
  38. }
  39. child = child.nextSibling;
  40. }
  41. return result;
  42. };
  43. Tools.ToDegrees = function (angle) {
  44. return angle * 180 / Math.PI;
  45. };
  46. Tools.ToRadians = function (angle) {
  47. return angle * Math.PI / 180;
  48. };
  49. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  50. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  51. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  52. for (var index = indexStart; index < indexStart + indexCount; index++) {
  53. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  54. minimum = BABYLON.Vector3.Minimize(current, minimum);
  55. maximum = BABYLON.Vector3.Maximize(current, maximum);
  56. }
  57. return {
  58. minimum: minimum,
  59. maximum: maximum
  60. };
  61. };
  62. Tools.ExtractMinAndMax = function (positions, start, count) {
  63. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  65. for (var index = start; index < start + count; index++) {
  66. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  67. minimum = BABYLON.Vector3.Minimize(current, minimum);
  68. maximum = BABYLON.Vector3.Maximize(current, maximum);
  69. }
  70. return {
  71. minimum: minimum,
  72. maximum: maximum
  73. };
  74. };
  75. Tools.MakeArray = function (obj, allowsNullUndefined) {
  76. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  77. return undefined;
  78. return Array.isArray(obj) ? obj : [obj];
  79. };
  80. // Misc.
  81. Tools.GetPointerPrefix = function () {
  82. var eventPrefix = "pointer";
  83. // Check if hand.js is referenced or if the browser natively supports pointer events
  84. if (!navigator.pointerEnabled) {
  85. eventPrefix = "mouse";
  86. }
  87. return eventPrefix;
  88. };
  89. Tools.QueueNewFrame = function (func) {
  90. if (window.requestAnimationFrame)
  91. window.requestAnimationFrame(func);
  92. else if (window.msRequestAnimationFrame)
  93. window.msRequestAnimationFrame(func);
  94. else if (window.webkitRequestAnimationFrame)
  95. window.webkitRequestAnimationFrame(func);
  96. else if (window.mozRequestAnimationFrame)
  97. window.mozRequestAnimationFrame(func);
  98. else if (window.oRequestAnimationFrame)
  99. window.oRequestAnimationFrame(func);
  100. else {
  101. window.setTimeout(func, 16);
  102. }
  103. };
  104. Tools.RequestFullscreen = function (element) {
  105. if (element.requestFullscreen)
  106. element.requestFullscreen();
  107. else if (element.msRequestFullscreen)
  108. element.msRequestFullscreen();
  109. else if (element.webkitRequestFullscreen)
  110. element.webkitRequestFullscreen();
  111. else if (element.mozRequestFullScreen)
  112. element.mozRequestFullScreen();
  113. };
  114. Tools.ExitFullscreen = function () {
  115. if (document.exitFullscreen) {
  116. document.exitFullscreen();
  117. } else if (document.mozCancelFullScreen) {
  118. document.mozCancelFullScreen();
  119. } else if (document.webkitCancelFullScreen) {
  120. document.webkitCancelFullScreen();
  121. } else if (document.msCancelFullScreen) {
  122. document.msCancelFullScreen();
  123. }
  124. };
  125. // External files
  126. Tools.CleanUrl = function (url) {
  127. url = url.replace(/#/mg, "%23");
  128. return url;
  129. };
  130. Tools.LoadImage = function (url, onload, onerror, database) {
  131. url = Tools.CleanUrl(url);
  132. var img = new Image();
  133. img.crossOrigin = 'anonymous';
  134. img.onload = function () {
  135. onload(img);
  136. };
  137. img.onerror = function (err) {
  138. onerror(img, err);
  139. };
  140. var noIndexedDB = function () {
  141. img.src = url;
  142. };
  143. var loadFromIndexedDB = function () {
  144. database.loadImageFromDB(url, img);
  145. };
  146. //ANY database to do!
  147. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  148. database.openAsync(loadFromIndexedDB, noIndexedDB);
  149. } else {
  150. if (url.indexOf("file:") === -1) {
  151. noIndexedDB();
  152. } else {
  153. try {
  154. var textureName = url.substring(5);
  155. var blobURL;
  156. try {
  157. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  158. } catch (ex) {
  159. // Chrome doesn't support oneTimeOnly parameter
  160. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  161. }
  162. img.src = blobURL;
  163. } catch (e) {
  164. Tools.Log("Error while trying to load texture: " + textureName);
  165. img.src = null;
  166. }
  167. }
  168. }
  169. return img;
  170. };
  171. //ANY
  172. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  173. url = Tools.CleanUrl(url);
  174. var noIndexedDB = function () {
  175. var request = new XMLHttpRequest();
  176. var loadUrl = Tools.BaseUrl + url;
  177. request.open('GET', loadUrl, true);
  178. if (useArrayBuffer) {
  179. request.responseType = "arraybuffer";
  180. }
  181. request.onprogress = progressCallBack;
  182. request.onreadystatechange = function () {
  183. if (request.readyState == 4) {
  184. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  185. callback(!useArrayBuffer ? request.responseText : request.response);
  186. } else {
  187. if (onError) {
  188. onError();
  189. } else {
  190. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  191. }
  192. }
  193. }
  194. };
  195. request.send(null);
  196. };
  197. var loadFromIndexedDB = function () {
  198. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  199. };
  200. if (url.indexOf("file:") !== -1) {
  201. var fileName = url.substring(5);
  202. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  203. } else {
  204. // Caching all files
  205. if (database && database.enableSceneOffline) {
  206. database.openAsync(loadFromIndexedDB, noIndexedDB);
  207. } else {
  208. noIndexedDB();
  209. }
  210. }
  211. };
  212. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  213. var reader = new FileReader();
  214. reader.onload = function (e) {
  215. callback(e.target.result);
  216. };
  217. reader.onprogress = progressCallback;
  218. reader.readAsDataURL(fileToLoad);
  219. };
  220. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  221. var reader = new FileReader();
  222. reader.onload = function (e) {
  223. callback(e.target.result);
  224. };
  225. reader.onprogress = progressCallBack;
  226. if (!useArrayBuffer) {
  227. // Asynchronous read
  228. reader.readAsText(fileToLoad);
  229. } else {
  230. reader.readAsArrayBuffer(fileToLoad);
  231. }
  232. };
  233. // Misc.
  234. Tools.CheckExtends = function (v, min, max) {
  235. if (v.x < min.x)
  236. min.x = v.x;
  237. if (v.y < min.y)
  238. min.y = v.y;
  239. if (v.z < min.z)
  240. min.z = v.z;
  241. if (v.x > max.x)
  242. max.x = v.x;
  243. if (v.y > max.y)
  244. max.y = v.y;
  245. if (v.z > max.z)
  246. max.z = v.z;
  247. };
  248. Tools.WithinEpsilon = function (a, b) {
  249. var num = a - b;
  250. return -1.401298E-45 <= num && num <= 1.401298E-45;
  251. };
  252. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  253. for (var prop in source) {
  254. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  255. continue;
  256. }
  257. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  258. continue;
  259. }
  260. var sourceValue = source[prop];
  261. var typeOfSourceValue = typeof sourceValue;
  262. if (typeOfSourceValue == "function") {
  263. continue;
  264. }
  265. if (typeOfSourceValue == "object") {
  266. if (sourceValue instanceof Array) {
  267. destination[prop] = [];
  268. if (sourceValue.length > 0) {
  269. if (typeof sourceValue[0] == "object") {
  270. for (var index = 0; index < sourceValue.length; index++) {
  271. var clonedValue = cloneValue(sourceValue[index], destination);
  272. if (destination[prop].indexOf(clonedValue) === -1) {
  273. destination[prop].push(clonedValue);
  274. }
  275. }
  276. } else {
  277. destination[prop] = sourceValue.slice(0);
  278. }
  279. }
  280. } else {
  281. destination[prop] = cloneValue(sourceValue, destination);
  282. }
  283. } else {
  284. destination[prop] = sourceValue;
  285. }
  286. }
  287. };
  288. Tools.IsEmpty = function (obj) {
  289. for (var i in obj) {
  290. return false;
  291. }
  292. return true;
  293. };
  294. Tools.RegisterTopRootEvents = function (events) {
  295. for (var index = 0; index < events.length; index++) {
  296. var event = events[index];
  297. window.addEventListener(event.name, event.handler, false);
  298. try {
  299. if (window.parent) {
  300. window.parent.addEventListener(event.name, event.handler, false);
  301. }
  302. } catch (e) {
  303. // Silently fails...
  304. }
  305. }
  306. };
  307. Tools.UnregisterTopRootEvents = function (events) {
  308. for (var index = 0; index < events.length; index++) {
  309. var event = events[index];
  310. window.removeEventListener(event.name, event.handler);
  311. try {
  312. if (window.parent) {
  313. window.parent.removeEventListener(event.name, event.handler);
  314. }
  315. } catch (e) {
  316. // Silently fails...
  317. }
  318. }
  319. };
  320. Tools.GetFps = function () {
  321. return fps;
  322. };
  323. Tools.GetDeltaTime = function () {
  324. return deltaTime;
  325. };
  326. Tools._MeasureFps = function () {
  327. previousFramesDuration.push((new Date).getTime());
  328. var length = previousFramesDuration.length;
  329. if (length >= 2) {
  330. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  331. }
  332. if (length >= fpsRange) {
  333. if (length > fpsRange) {
  334. previousFramesDuration.splice(0, 1);
  335. length = previousFramesDuration.length;
  336. }
  337. var sum = 0;
  338. for (var id = 0; id < length - 1; id++) {
  339. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  340. }
  341. fps = 1000.0 / (sum / (length - 1));
  342. }
  343. };
  344. Tools.CreateScreenshot = function (engine, camera, size) {
  345. var width;
  346. var height;
  347. var scene = camera.getScene();
  348. var previousCamera = null;
  349. if (scene.activeCamera !== camera) {
  350. previousCamera = scene.activeCamera;
  351. scene.activeCamera = camera;
  352. }
  353. //If a precision value is specified
  354. if (size.precision) {
  355. width = Math.round(engine.getRenderWidth() * size.precision);
  356. height = Math.round(width / engine.getAspectRatio(camera));
  357. size = { width: width, height: height };
  358. } else if (size.width && size.height) {
  359. width = size.width;
  360. height = size.height;
  361. } else if (size.width && !size.height) {
  362. width = size.width;
  363. height = Math.round(width / engine.getAspectRatio(camera));
  364. size = { width: width, height: height };
  365. } else if (size.height && !size.width) {
  366. height = size.height;
  367. width = Math.round(height * engine.getAspectRatio(camera));
  368. size = { width: width, height: height };
  369. } else if (!isNaN(size)) {
  370. height = size;
  371. width = size;
  372. } else {
  373. Tools.Error("Invalid 'size' parameter !");
  374. return;
  375. }
  376. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  377. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  378. texture.renderList = engine.scenes[0].meshes;
  379. texture.onAfterRender = function () {
  380. // Read the contents of the framebuffer
  381. var numberOfChannelsByLine = width * 4;
  382. var halfHeight = height / 2;
  383. //Reading datas from WebGL
  384. var data = engine.readPixels(0, 0, width, height);
  385. for (var i = 0; i < halfHeight; i++) {
  386. for (var j = 0; j < numberOfChannelsByLine; j++) {
  387. var currentCell = j + i * numberOfChannelsByLine;
  388. var targetLine = height - i - 1;
  389. var targetCell = j + targetLine * numberOfChannelsByLine;
  390. var temp = data[currentCell];
  391. data[currentCell] = data[targetCell];
  392. data[targetCell] = temp;
  393. }
  394. }
  395. // Create a 2D canvas to store the result
  396. if (!screenshotCanvas) {
  397. screenshotCanvas = document.createElement('canvas');
  398. }
  399. screenshotCanvas.width = width;
  400. screenshotCanvas.height = height;
  401. var context = screenshotCanvas.getContext('2d');
  402. // Copy the pixels to a 2D canvas
  403. var imageData = context.createImageData(width, height);
  404. imageData.data.set(data);
  405. context.putImageData(imageData, 0, 0);
  406. var base64Image = screenshotCanvas.toDataURL();
  407. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  408. if (("download" in document.createElement("a"))) {
  409. var a = window.document.createElement("a");
  410. a.href = base64Image;
  411. var date = new Date();
  412. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  413. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  414. window.document.body.appendChild(a);
  415. a.addEventListener("click", function () {
  416. a.parentElement.removeChild(a);
  417. });
  418. a.click();
  419. //Or opening a new tab with the image if it is not possible to automatically start download.
  420. } else {
  421. var newWindow = window.open("");
  422. var img = newWindow.document.createElement("img");
  423. img.src = base64Image;
  424. newWindow.document.body.appendChild(img);
  425. }
  426. };
  427. texture.render(true);
  428. texture.dispose();
  429. if (previousCamera) {
  430. scene.activeCamera = previousCamera;
  431. }
  432. };
  433. // XHR response validator for local file scenario
  434. Tools.ValidateXHRData = function (xhr, dataType) {
  435. if (typeof dataType === "undefined") { dataType = 7; }
  436. try {
  437. if (dataType & 1) {
  438. if (xhr.responseText && xhr.responseText.length > 0) {
  439. return true;
  440. } else if (dataType === 1) {
  441. return false;
  442. }
  443. }
  444. if (dataType & 2) {
  445. // Check header width and height since there is no "TGA" magic number
  446. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  447. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  448. return true;
  449. } else if (dataType === 2) {
  450. return false;
  451. }
  452. }
  453. if (dataType & 4) {
  454. // Check for the "DDS" magic number
  455. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  456. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  457. return true;
  458. } else {
  459. return false;
  460. }
  461. }
  462. } catch (e) {
  463. // Global protection
  464. }
  465. return false;
  466. };
  467. Object.defineProperty(Tools, "NoneLogLevel", {
  468. get: function () {
  469. return Tools._NoneLogLevel;
  470. },
  471. enumerable: true,
  472. configurable: true
  473. });
  474. Object.defineProperty(Tools, "MessageLogLevel", {
  475. get: function () {
  476. return Tools._MessageLogLevel;
  477. },
  478. enumerable: true,
  479. configurable: true
  480. });
  481. Object.defineProperty(Tools, "WarningLogLevel", {
  482. get: function () {
  483. return Tools._WarningLogLevel;
  484. },
  485. enumerable: true,
  486. configurable: true
  487. });
  488. Object.defineProperty(Tools, "ErrorLogLevel", {
  489. get: function () {
  490. return Tools._ErrorLogLevel;
  491. },
  492. enumerable: true,
  493. configurable: true
  494. });
  495. Object.defineProperty(Tools, "AllLogLevel", {
  496. get: function () {
  497. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  498. },
  499. enumerable: true,
  500. configurable: true
  501. });
  502. Tools._FormatMessage = function (message) {
  503. var padStr = function (i) {
  504. return (i < 10) ? "0" + i : "" + i;
  505. };
  506. var date = new Date();
  507. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  508. };
  509. Tools._LogDisabled = function (message) {
  510. // nothing to do
  511. };
  512. Tools._LogEnabled = function (message) {
  513. console.log(Tools._FormatMessage(message));
  514. };
  515. Tools._WarnDisabled = function (message) {
  516. // nothing to do
  517. };
  518. Tools._WarnEnabled = function (message) {
  519. console.warn(Tools._FormatMessage(message));
  520. };
  521. Tools._ErrorDisabled = function (message) {
  522. // nothing to do
  523. };
  524. Tools._ErrorEnabled = function (message) {
  525. console.error(Tools._FormatMessage(message));
  526. };
  527. Object.defineProperty(Tools, "LogLevels", {
  528. set: function (level) {
  529. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  530. Tools.Log = Tools._LogEnabled;
  531. } else {
  532. Tools.Log = Tools._LogDisabled;
  533. }
  534. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  535. Tools.Warn = Tools._WarnEnabled;
  536. } else {
  537. Tools.Warn = Tools._WarnDisabled;
  538. }
  539. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  540. Tools.Error = Tools._ErrorEnabled;
  541. } else {
  542. Tools.Error = Tools._ErrorDisabled;
  543. }
  544. },
  545. enumerable: true,
  546. configurable: true
  547. });
  548. Tools.BaseUrl = "";
  549. Tools._NoneLogLevel = 0;
  550. Tools._MessageLogLevel = 1;
  551. Tools._WarningLogLevel = 2;
  552. Tools._ErrorLogLevel = 4;
  553. Tools.Log = Tools._LogEnabled;
  554. Tools.Warn = Tools._WarnEnabled;
  555. Tools.Error = Tools._ErrorEnabled;
  556. return Tools;
  557. })();
  558. BABYLON.Tools = Tools;
  559. })(BABYLON || (BABYLON = {}));
  560. //# sourceMappingURL=babylon.tools.js.map