babylon.tools.js 22 KB

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