babylon.tools.js 20 KB

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