babylon.tools.js 20 KB

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