babylon.tools.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. // Caching only scenes files
  198. if (database && url.indexOf(".babylon") !== -1 && (database.enableSceneOffline)) {
  199. database.openAsync(loadFromIndexedDB, noIndexedDB);
  200. } else {
  201. noIndexedDB();
  202. }
  203. };
  204. Tools.ReadFile = function (fileToLoad, callback, progressCallBack) {
  205. var reader = new FileReader();
  206. reader.onload = function (e) {
  207. callback(e.target.result);
  208. };
  209. reader.onprogress = progressCallBack;
  210. // Asynchronous read
  211. reader.readAsText(fileToLoad);
  212. };
  213. // Misc.
  214. Tools.CheckExtends = function (v, min, max) {
  215. if (v.x < min.x)
  216. min.x = v.x;
  217. if (v.y < min.y)
  218. min.y = v.y;
  219. if (v.z < min.z)
  220. min.z = v.z;
  221. if (v.x > max.x)
  222. max.x = v.x;
  223. if (v.y > max.y)
  224. max.y = v.y;
  225. if (v.z > max.z)
  226. max.z = v.z;
  227. };
  228. Tools.WithinEpsilon = function (a, b) {
  229. var num = a - b;
  230. return -1.401298E-45 <= num && num <= 1.401298E-45;
  231. };
  232. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  233. for (var prop in source) {
  234. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  235. continue;
  236. }
  237. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  238. continue;
  239. }
  240. var sourceValue = source[prop];
  241. var typeOfSourceValue = typeof sourceValue;
  242. if (typeOfSourceValue == "function") {
  243. continue;
  244. }
  245. if (typeOfSourceValue == "object") {
  246. if (sourceValue instanceof Array) {
  247. destination[prop] = [];
  248. if (sourceValue.length > 0) {
  249. if (typeof sourceValue[0] == "object") {
  250. for (var index = 0; index < sourceValue.length; index++) {
  251. var clonedValue = cloneValue(sourceValue[index], destination);
  252. if (destination[prop].indexOf(clonedValue) === -1) {
  253. destination[prop].push(clonedValue);
  254. }
  255. }
  256. } else {
  257. destination[prop] = sourceValue.slice(0);
  258. }
  259. }
  260. } else {
  261. destination[prop] = cloneValue(sourceValue, destination);
  262. }
  263. } else {
  264. destination[prop] = sourceValue;
  265. }
  266. }
  267. };
  268. Tools.IsEmpty = function (obj) {
  269. for (var i in obj) {
  270. return false;
  271. }
  272. return true;
  273. };
  274. Tools.RegisterTopRootEvents = function (events) {
  275. for (var index = 0; index < events.length; index++) {
  276. var event = events[index];
  277. window.addEventListener(event.name, event.handler, false);
  278. try {
  279. if (window.parent) {
  280. window.parent.addEventListener(event.name, event.handler, false);
  281. }
  282. } catch (e) {
  283. // Silently fails...
  284. }
  285. }
  286. };
  287. Tools.UnregisterTopRootEvents = function (events) {
  288. for (var index = 0; index < events.length; index++) {
  289. var event = events[index];
  290. window.removeEventListener(event.name, event.handler);
  291. try {
  292. if (window.parent) {
  293. window.parent.removeEventListener(event.name, event.handler);
  294. }
  295. } catch (e) {
  296. // Silently fails...
  297. }
  298. }
  299. };
  300. Tools.GetFps = function () {
  301. return fps;
  302. };
  303. Tools.GetDeltaTime = function () {
  304. return deltaTime;
  305. };
  306. Tools._MeasureFps = function () {
  307. previousFramesDuration.push((new Date).getTime());
  308. var length = previousFramesDuration.length;
  309. if (length >= 2) {
  310. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  311. }
  312. if (length >= fpsRange) {
  313. if (length > fpsRange) {
  314. previousFramesDuration.splice(0, 1);
  315. length = previousFramesDuration.length;
  316. }
  317. var sum = 0;
  318. for (var id = 0; id < length - 1; id++) {
  319. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  320. }
  321. fps = 1000.0 / (sum / (length - 1));
  322. }
  323. };
  324. Tools.CreateScreenshot = function (engine, camera, size) {
  325. var width;
  326. var height;
  327. var scene = camera.getScene();
  328. var previousCamera = null;
  329. if (scene.activeCamera !== camera) {
  330. previousCamera = scene.activeCamera;
  331. scene.activeCamera = camera;
  332. }
  333. //If a precision value is specified
  334. if (size.precision) {
  335. width = Math.round(engine.getRenderWidth() * size.precision);
  336. height = Math.round(width / engine.getAspectRatio(camera));
  337. size = { width: width, height: height };
  338. } else if (size.width && size.height) {
  339. width = size.width;
  340. height = size.height;
  341. } else if (size.width && !size.height) {
  342. width = size.width;
  343. height = Math.round(width / engine.getAspectRatio(camera));
  344. size = { width: width, height: height };
  345. } else if (size.height && !size.width) {
  346. height = size.height;
  347. width = Math.round(height * engine.getAspectRatio(camera));
  348. size = { width: width, height: height };
  349. } else if (!isNaN(size)) {
  350. height = size;
  351. width = size;
  352. } else {
  353. Tools.Error("Invalid 'size' parameter !");
  354. return;
  355. }
  356. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  357. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0]);
  358. texture.renderList = engine.scenes[0].meshes;
  359. texture.onAfterRender = function () {
  360. // Read the contents of the framebuffer
  361. var numberOfChannelsByLine = width * 4;
  362. var halfHeight = height / 2;
  363. //Reading datas from WebGL
  364. var data = engine.readPixels(0, 0, width, height);
  365. for (var i = 0; i < halfHeight; i++) {
  366. for (var j = 0; j < numberOfChannelsByLine; j++) {
  367. var currentCell = j + i * numberOfChannelsByLine;
  368. var targetLine = height - i - 1;
  369. var targetCell = j + targetLine * numberOfChannelsByLine;
  370. var temp = data[currentCell];
  371. data[currentCell] = data[targetCell];
  372. data[targetCell] = temp;
  373. }
  374. }
  375. // Create a 2D canvas to store the result
  376. if (!screenshotCanvas) {
  377. screenshotCanvas = document.createElement('canvas');
  378. }
  379. screenshotCanvas.width = width;
  380. screenshotCanvas.height = height;
  381. var context = screenshotCanvas.getContext('2d');
  382. // Copy the pixels to a 2D canvas
  383. var imageData = context.createImageData(width, height);
  384. imageData.data.set(data);
  385. context.putImageData(imageData, 0, 0);
  386. var base64Image = screenshotCanvas.toDataURL();
  387. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  388. if (("download" in document.createElement("a"))) {
  389. var a = window.document.createElement("a");
  390. a.href = base64Image;
  391. var date = new Date();
  392. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  393. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  394. window.document.body.appendChild(a);
  395. a.addEventListener("click", function () {
  396. a.parentElement.removeChild(a);
  397. });
  398. a.click();
  399. //Or opening a new tab with the image if it is not possible to automatically start download.
  400. } else {
  401. var newWindow = window.open("");
  402. var img = newWindow.document.createElement("img");
  403. img.src = base64Image;
  404. newWindow.document.body.appendChild(img);
  405. }
  406. };
  407. texture.render(true);
  408. texture.dispose();
  409. if (previousCamera) {
  410. scene.activeCamera = previousCamera;
  411. }
  412. };
  413. Object.defineProperty(Tools, "NoneLogLevel", {
  414. get: function () {
  415. return Tools._NoneLogLevel;
  416. },
  417. enumerable: true,
  418. configurable: true
  419. });
  420. Object.defineProperty(Tools, "MessageLogLevel", {
  421. get: function () {
  422. return Tools._MessageLogLevel;
  423. },
  424. enumerable: true,
  425. configurable: true
  426. });
  427. Object.defineProperty(Tools, "WarningLogLevel", {
  428. get: function () {
  429. return Tools._WarningLogLevel;
  430. },
  431. enumerable: true,
  432. configurable: true
  433. });
  434. Object.defineProperty(Tools, "ErrorLogLevel", {
  435. get: function () {
  436. return Tools._ErrorLogLevel;
  437. },
  438. enumerable: true,
  439. configurable: true
  440. });
  441. Object.defineProperty(Tools, "AllLogLevel", {
  442. get: function () {
  443. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  444. ;
  445. },
  446. enumerable: true,
  447. configurable: true
  448. });
  449. Tools._FormatMessage = function (message) {
  450. var padStr = function (i) {
  451. return (i < 10) ? "0" + i : "" + i;
  452. };
  453. var date = new Date();
  454. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  455. };
  456. Tools._LogDisabled = function (message) {
  457. // nothing to do
  458. };
  459. Tools._LogEnabled = function (message) {
  460. console.log(Tools._FormatMessage(message));
  461. };
  462. Tools._WarnDisabled = function (message) {
  463. // nothing to do
  464. };
  465. Tools._WarnEnabled = function (message) {
  466. console.warn(Tools._FormatMessage(message));
  467. };
  468. Tools._ErrorDisabled = function (message) {
  469. // nothing to do
  470. };
  471. Tools._ErrorEnabled = function (message) {
  472. console.error(Tools._FormatMessage(message));
  473. };
  474. Object.defineProperty(Tools, "LogLevels", {
  475. set: function (level) {
  476. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  477. Tools.Log = Tools._LogEnabled;
  478. } else {
  479. Tools.Log = Tools._LogDisabled;
  480. }
  481. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  482. Tools.Warn = Tools._WarnEnabled;
  483. } else {
  484. Tools.Warn = Tools._WarnDisabled;
  485. }
  486. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  487. Tools.Error = Tools._ErrorEnabled;
  488. } else {
  489. Tools.Error = Tools._ErrorDisabled;
  490. }
  491. },
  492. enumerable: true,
  493. configurable: true
  494. });
  495. Tools.BaseUrl = "";
  496. Tools._NoneLogLevel = 0;
  497. Tools._MessageLogLevel = 1;
  498. Tools._WarningLogLevel = 2;
  499. Tools._ErrorLogLevel = 4;
  500. Tools.Log = Tools._LogEnabled;
  501. Tools.Warn = Tools._WarnEnabled;
  502. Tools.Error = Tools._ErrorEnabled;
  503. return Tools;
  504. })();
  505. BABYLON.Tools = Tools;
  506. })(BABYLON || (BABYLON = {}));
  507. //# sourceMappingURL=babylon.tools.js.map