babylon.tools.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. var BABYLON;
  2. (function (BABYLON) {
  3. // Screenshots
  4. var screenshotCanvas;
  5. var cloneValue = function (source, destinationObject) {
  6. if (!source)
  7. return null;
  8. if (source instanceof BABYLON.Mesh) {
  9. return null;
  10. }
  11. if (source instanceof BABYLON.SubMesh) {
  12. return source.clone(destinationObject);
  13. }
  14. else if (source.clone) {
  15. return source.clone();
  16. }
  17. return null;
  18. };
  19. var Tools = (function () {
  20. function Tools() {
  21. }
  22. Tools.SetImmediate = function (action) {
  23. if (window.setImmediate) {
  24. window.setImmediate(action);
  25. }
  26. else {
  27. setTimeout(action, 1);
  28. }
  29. };
  30. Tools.GetFilename = function (path) {
  31. var index = path.lastIndexOf("/");
  32. if (index < 0)
  33. return path;
  34. return path.substring(index + 1);
  35. };
  36. Tools.GetDOMTextContent = function (element) {
  37. var result = "";
  38. var child = element.firstChild;
  39. while (child) {
  40. if (child.nodeType === 3) {
  41. result += child.textContent;
  42. }
  43. child = child.nextSibling;
  44. }
  45. return result;
  46. };
  47. Tools.ToDegrees = function (angle) {
  48. return angle * 180 / Math.PI;
  49. };
  50. Tools.ToRadians = function (angle) {
  51. return angle * Math.PI / 180;
  52. };
  53. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  54. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  55. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  56. for (var index = indexStart; index < indexStart + indexCount; index++) {
  57. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  58. minimum = BABYLON.Vector3.Minimize(current, minimum);
  59. maximum = BABYLON.Vector3.Maximize(current, maximum);
  60. }
  61. return {
  62. minimum: minimum,
  63. maximum: maximum
  64. };
  65. };
  66. Tools.ExtractMinAndMax = function (positions, start, count) {
  67. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  69. for (var index = start; index < start + count; index++) {
  70. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  71. minimum = BABYLON.Vector3.Minimize(current, minimum);
  72. maximum = BABYLON.Vector3.Maximize(current, maximum);
  73. }
  74. return {
  75. minimum: minimum,
  76. maximum: maximum
  77. };
  78. };
  79. Tools.MakeArray = function (obj, allowsNullUndefined) {
  80. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  81. return undefined;
  82. return Array.isArray(obj) ? obj : [obj];
  83. };
  84. // Misc.
  85. Tools.GetPointerPrefix = function () {
  86. var eventPrefix = "pointer";
  87. // Check if hand.js is referenced or if the browser natively supports pointer events
  88. if (!navigator.pointerEnabled) {
  89. eventPrefix = "mouse";
  90. }
  91. return eventPrefix;
  92. };
  93. Tools.QueueNewFrame = function (func) {
  94. if (window.requestAnimationFrame)
  95. window.requestAnimationFrame(func);
  96. else if (window.msRequestAnimationFrame)
  97. window.msRequestAnimationFrame(func);
  98. else if (window.webkitRequestAnimationFrame)
  99. window.webkitRequestAnimationFrame(func);
  100. else if (window.mozRequestAnimationFrame)
  101. window.mozRequestAnimationFrame(func);
  102. else if (window.oRequestAnimationFrame)
  103. window.oRequestAnimationFrame(func);
  104. else {
  105. window.setTimeout(func, 16);
  106. }
  107. };
  108. Tools.RequestFullscreen = function (element) {
  109. if (element.requestFullscreen)
  110. element.requestFullscreen();
  111. else if (element.msRequestFullscreen)
  112. element.msRequestFullscreen();
  113. else if (element.webkitRequestFullscreen)
  114. element.webkitRequestFullscreen();
  115. else if (element.mozRequestFullScreen)
  116. element.mozRequestFullScreen();
  117. };
  118. Tools.ExitFullscreen = function () {
  119. if (document.exitFullscreen) {
  120. document.exitFullscreen();
  121. }
  122. else if (document.mozCancelFullScreen) {
  123. document.mozCancelFullScreen();
  124. }
  125. else if (document.webkitCancelFullScreen) {
  126. document.webkitCancelFullScreen();
  127. }
  128. else if (document.msCancelFullScreen) {
  129. document.msCancelFullScreen();
  130. }
  131. };
  132. // External files
  133. Tools.CleanUrl = function (url) {
  134. url = url.replace(/#/mg, "%23");
  135. return url;
  136. };
  137. Tools.LoadImage = function (url, onload, onerror, database) {
  138. url = Tools.CleanUrl(url);
  139. var img = new Image();
  140. if (url.substr(0, 5) !== "data:")
  141. img.crossOrigin = 'anonymous';
  142. img.onload = function () {
  143. onload(img);
  144. };
  145. img.onerror = function (err) {
  146. onerror(img, err);
  147. };
  148. var noIndexedDB = function () {
  149. img.src = url;
  150. };
  151. var loadFromIndexedDB = function () {
  152. database.loadImageFromDB(url, img);
  153. };
  154. //ANY database to do!
  155. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  156. database.openAsync(loadFromIndexedDB, noIndexedDB);
  157. }
  158. else {
  159. if (url.indexOf("file:") === -1) {
  160. noIndexedDB();
  161. }
  162. else {
  163. try {
  164. var textureName = url.substring(5);
  165. var blobURL;
  166. try {
  167. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  168. }
  169. catch (ex) {
  170. // Chrome doesn't support oneTimeOnly parameter
  171. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  172. }
  173. img.src = blobURL;
  174. }
  175. catch (e) {
  176. Tools.Log("Error while trying to load texture: " + textureName);
  177. img.src = null;
  178. }
  179. }
  180. }
  181. return img;
  182. };
  183. //ANY
  184. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  185. url = Tools.CleanUrl(url);
  186. var noIndexedDB = function () {
  187. var request = new XMLHttpRequest();
  188. var loadUrl = Tools.BaseUrl + url;
  189. request.open('GET', loadUrl, true);
  190. if (useArrayBuffer) {
  191. request.responseType = "arraybuffer";
  192. }
  193. request.onprogress = progressCallBack;
  194. request.onreadystatechange = function () {
  195. if (request.readyState === 4) {
  196. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  197. callback(!useArrayBuffer ? request.responseText : request.response);
  198. }
  199. else {
  200. if (onError) {
  201. onError();
  202. }
  203. else {
  204. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  205. }
  206. }
  207. }
  208. };
  209. request.send(null);
  210. };
  211. var loadFromIndexedDB = function () {
  212. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  213. };
  214. if (url.indexOf("file:") !== -1) {
  215. var fileName = url.substring(5);
  216. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  217. }
  218. else {
  219. // Caching all files
  220. if (database && database.enableSceneOffline) {
  221. database.openAsync(loadFromIndexedDB, noIndexedDB);
  222. }
  223. else {
  224. noIndexedDB();
  225. }
  226. }
  227. };
  228. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  229. var reader = new FileReader();
  230. reader.onload = function (e) {
  231. //target doesn't have result from ts 1.3
  232. callback(e.target['result']);
  233. };
  234. reader.onprogress = progressCallback;
  235. reader.readAsDataURL(fileToLoad);
  236. };
  237. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  238. var reader = new FileReader();
  239. reader.onerror = function (e) {
  240. Tools.Log("Error while reading file: " + fileToLoad.name);
  241. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  242. };
  243. reader.onload = function (e) {
  244. //target doesn't have result from ts 1.3
  245. callback(e.target['result']);
  246. };
  247. reader.onprogress = progressCallBack;
  248. if (!useArrayBuffer) {
  249. // Asynchronous read
  250. reader.readAsText(fileToLoad);
  251. }
  252. else {
  253. reader.readAsArrayBuffer(fileToLoad);
  254. }
  255. };
  256. // Misc.
  257. Tools.Clamp = function (value, min, max) {
  258. if (min === void 0) { min = 0; }
  259. if (max === void 0) { max = 1; }
  260. return Math.min(max, Math.max(min, value));
  261. };
  262. // Returns -1 when value is a negative number and
  263. // +1 when value is a positive number.
  264. Tools.Sign = function (value) {
  265. value = +value; // convert to a number
  266. if (value === 0 || isNaN(value))
  267. return value;
  268. return value > 0 ? 1 : -1;
  269. };
  270. Tools.Format = function (value, decimals) {
  271. if (decimals === void 0) { decimals = 2; }
  272. return value.toFixed(decimals);
  273. };
  274. Tools.CheckExtends = function (v, min, max) {
  275. if (v.x < min.x)
  276. min.x = v.x;
  277. if (v.y < min.y)
  278. min.y = v.y;
  279. if (v.z < min.z)
  280. min.z = v.z;
  281. if (v.x > max.x)
  282. max.x = v.x;
  283. if (v.y > max.y)
  284. max.y = v.y;
  285. if (v.z > max.z)
  286. max.z = v.z;
  287. };
  288. Tools.WithinEpsilon = function (a, b, epsilon) {
  289. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  290. var num = a - b;
  291. return -epsilon <= num && num <= epsilon;
  292. };
  293. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  294. for (var prop in source) {
  295. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  296. continue;
  297. }
  298. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  299. continue;
  300. }
  301. var sourceValue = source[prop];
  302. var typeOfSourceValue = typeof sourceValue;
  303. if (typeOfSourceValue === "function") {
  304. continue;
  305. }
  306. if (typeOfSourceValue === "object") {
  307. if (sourceValue instanceof Array) {
  308. destination[prop] = [];
  309. if (sourceValue.length > 0) {
  310. if (typeof sourceValue[0] == "object") {
  311. for (var index = 0; index < sourceValue.length; index++) {
  312. var clonedValue = cloneValue(sourceValue[index], destination);
  313. if (destination[prop].indexOf(clonedValue) === -1) {
  314. destination[prop].push(clonedValue);
  315. }
  316. }
  317. }
  318. else {
  319. destination[prop] = sourceValue.slice(0);
  320. }
  321. }
  322. }
  323. else {
  324. destination[prop] = cloneValue(sourceValue, destination);
  325. }
  326. }
  327. else {
  328. destination[prop] = sourceValue;
  329. }
  330. }
  331. };
  332. Tools.IsEmpty = function (obj) {
  333. for (var i in obj) {
  334. return false;
  335. }
  336. return true;
  337. };
  338. Tools.RegisterTopRootEvents = function (events) {
  339. for (var index = 0; index < events.length; index++) {
  340. var event = events[index];
  341. window.addEventListener(event.name, event.handler, false);
  342. try {
  343. if (window.parent) {
  344. window.parent.addEventListener(event.name, event.handler, false);
  345. }
  346. }
  347. catch (e) {
  348. }
  349. }
  350. };
  351. Tools.UnregisterTopRootEvents = function (events) {
  352. for (var index = 0; index < events.length; index++) {
  353. var event = events[index];
  354. window.removeEventListener(event.name, event.handler);
  355. try {
  356. if (window.parent) {
  357. window.parent.removeEventListener(event.name, event.handler);
  358. }
  359. }
  360. catch (e) {
  361. }
  362. }
  363. };
  364. Tools.DumpFramebuffer = function (width, height, engine) {
  365. // Read the contents of the framebuffer
  366. var numberOfChannelsByLine = width * 4;
  367. var halfHeight = height / 2;
  368. //Reading datas from WebGL
  369. var data = engine.readPixels(0, 0, width, height);
  370. for (var i = 0; i < halfHeight; i++) {
  371. for (var j = 0; j < numberOfChannelsByLine; j++) {
  372. var currentCell = j + i * numberOfChannelsByLine;
  373. var targetLine = height - i - 1;
  374. var targetCell = j + targetLine * numberOfChannelsByLine;
  375. var temp = data[currentCell];
  376. data[currentCell] = data[targetCell];
  377. data[targetCell] = temp;
  378. }
  379. }
  380. // Create a 2D canvas to store the result
  381. if (!screenshotCanvas) {
  382. screenshotCanvas = document.createElement('canvas');
  383. }
  384. screenshotCanvas.width = width;
  385. screenshotCanvas.height = height;
  386. var context = screenshotCanvas.getContext('2d');
  387. // Copy the pixels to a 2D canvas
  388. var imageData = context.createImageData(width, height);
  389. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  390. var castData = imageData.data;
  391. castData.set(data);
  392. context.putImageData(imageData, 0, 0);
  393. var base64Image = screenshotCanvas.toDataURL();
  394. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  395. if (("download" in document.createElement("a"))) {
  396. var a = window.document.createElement("a");
  397. a.href = base64Image;
  398. var date = new Date();
  399. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  400. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  401. window.document.body.appendChild(a);
  402. a.addEventListener("click", function () {
  403. a.parentElement.removeChild(a);
  404. });
  405. a.click();
  406. }
  407. else {
  408. var newWindow = window.open("");
  409. var img = newWindow.document.createElement("img");
  410. img.src = base64Image;
  411. newWindow.document.body.appendChild(img);
  412. }
  413. };
  414. Tools.CreateScreenshot = function (engine, camera, size) {
  415. var width;
  416. var height;
  417. var scene = camera.getScene();
  418. var previousCamera = null;
  419. if (scene.activeCamera !== camera) {
  420. previousCamera = scene.activeCamera;
  421. scene.activeCamera = camera;
  422. }
  423. //If a precision value is specified
  424. if (size.precision) {
  425. width = Math.round(engine.getRenderWidth() * size.precision);
  426. height = Math.round(width / engine.getAspectRatio(camera));
  427. size = { width: width, height: height };
  428. }
  429. else if (size.width && size.height) {
  430. width = size.width;
  431. height = size.height;
  432. }
  433. else if (size.width && !size.height) {
  434. width = size.width;
  435. height = Math.round(width / engine.getAspectRatio(camera));
  436. size = { width: width, height: height };
  437. }
  438. else if (size.height && !size.width) {
  439. height = size.height;
  440. width = Math.round(height * engine.getAspectRatio(camera));
  441. size = { width: width, height: height };
  442. }
  443. else if (!isNaN(size)) {
  444. height = size;
  445. width = size;
  446. }
  447. else {
  448. Tools.Error("Invalid 'size' parameter !");
  449. return;
  450. }
  451. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  452. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  453. texture.renderList = scene.meshes;
  454. texture.onAfterRender = function () {
  455. Tools.DumpFramebuffer(width, height, engine);
  456. };
  457. scene.incrementRenderId();
  458. texture.render(true);
  459. texture.dispose();
  460. if (previousCamera) {
  461. scene.activeCamera = previousCamera;
  462. }
  463. };
  464. // XHR response validator for local file scenario
  465. Tools.ValidateXHRData = function (xhr, dataType) {
  466. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  467. if (dataType === void 0) { dataType = 7; }
  468. try {
  469. if (dataType & 1) {
  470. if (xhr.responseText && xhr.responseText.length > 0) {
  471. return true;
  472. }
  473. else if (dataType === 1) {
  474. return false;
  475. }
  476. }
  477. if (dataType & 2) {
  478. // Check header width and height since there is no "TGA" magic number
  479. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  480. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  481. return true;
  482. }
  483. else if (dataType === 2) {
  484. return false;
  485. }
  486. }
  487. if (dataType & 4) {
  488. // Check for the "DDS" magic number
  489. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  490. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  491. return true;
  492. }
  493. else {
  494. return false;
  495. }
  496. }
  497. }
  498. catch (e) {
  499. }
  500. return false;
  501. };
  502. Object.defineProperty(Tools, "NoneLogLevel", {
  503. get: function () {
  504. return Tools._NoneLogLevel;
  505. },
  506. enumerable: true,
  507. configurable: true
  508. });
  509. Object.defineProperty(Tools, "MessageLogLevel", {
  510. get: function () {
  511. return Tools._MessageLogLevel;
  512. },
  513. enumerable: true,
  514. configurable: true
  515. });
  516. Object.defineProperty(Tools, "WarningLogLevel", {
  517. get: function () {
  518. return Tools._WarningLogLevel;
  519. },
  520. enumerable: true,
  521. configurable: true
  522. });
  523. Object.defineProperty(Tools, "ErrorLogLevel", {
  524. get: function () {
  525. return Tools._ErrorLogLevel;
  526. },
  527. enumerable: true,
  528. configurable: true
  529. });
  530. Object.defineProperty(Tools, "AllLogLevel", {
  531. get: function () {
  532. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  533. },
  534. enumerable: true,
  535. configurable: true
  536. });
  537. Tools._AddLogEntry = function (entry) {
  538. Tools._LogCache = entry + Tools._LogCache;
  539. if (Tools.OnNewCacheEntry) {
  540. Tools.OnNewCacheEntry(entry);
  541. }
  542. };
  543. Tools._FormatMessage = function (message) {
  544. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  545. var date = new Date();
  546. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  547. };
  548. Tools._LogDisabled = function (message) {
  549. // nothing to do
  550. };
  551. Tools._LogEnabled = function (message) {
  552. var formattedMessage = Tools._FormatMessage(message);
  553. console.log("BJS - " + formattedMessage);
  554. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  555. Tools._AddLogEntry(entry);
  556. };
  557. Tools._WarnDisabled = function (message) {
  558. // nothing to do
  559. };
  560. Tools._WarnEnabled = function (message) {
  561. var formattedMessage = Tools._FormatMessage(message);
  562. console.warn("BJS - " + formattedMessage);
  563. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  564. Tools._AddLogEntry(entry);
  565. };
  566. Tools._ErrorDisabled = function (message) {
  567. // nothing to do
  568. };
  569. Tools._ErrorEnabled = function (message) {
  570. var formattedMessage = Tools._FormatMessage(message);
  571. console.error("BJS - " + formattedMessage);
  572. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  573. Tools._AddLogEntry(entry);
  574. };
  575. Object.defineProperty(Tools, "LogCache", {
  576. get: function () {
  577. return Tools._LogCache;
  578. },
  579. enumerable: true,
  580. configurable: true
  581. });
  582. Object.defineProperty(Tools, "LogLevels", {
  583. set: function (level) {
  584. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  585. Tools.Log = Tools._LogEnabled;
  586. }
  587. else {
  588. Tools.Log = Tools._LogDisabled;
  589. }
  590. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  591. Tools.Warn = Tools._WarnEnabled;
  592. }
  593. else {
  594. Tools.Warn = Tools._WarnDisabled;
  595. }
  596. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  597. Tools.Error = Tools._ErrorEnabled;
  598. }
  599. else {
  600. Tools.Error = Tools._ErrorDisabled;
  601. }
  602. },
  603. enumerable: true,
  604. configurable: true
  605. });
  606. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  607. get: function () {
  608. return Tools._PerformanceNoneLogLevel;
  609. },
  610. enumerable: true,
  611. configurable: true
  612. });
  613. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  614. get: function () {
  615. return Tools._PerformanceUserMarkLogLevel;
  616. },
  617. enumerable: true,
  618. configurable: true
  619. });
  620. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  621. get: function () {
  622. return Tools._PerformanceConsoleLogLevel;
  623. },
  624. enumerable: true,
  625. configurable: true
  626. });
  627. Object.defineProperty(Tools, "PerformanceLogLevel", {
  628. set: function (level) {
  629. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  630. Tools.StartPerformanceCounter = Tools._StartUserMark;
  631. Tools.EndPerformanceCounter = Tools._EndUserMark;
  632. return;
  633. }
  634. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  635. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  636. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  637. return;
  638. }
  639. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  640. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  641. },
  642. enumerable: true,
  643. configurable: true
  644. });
  645. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  646. };
  647. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  648. };
  649. Tools._StartUserMark = function (counterName, condition) {
  650. if (condition === void 0) { condition = true; }
  651. if (!condition || !Tools._performance.mark) {
  652. return;
  653. }
  654. Tools._performance.mark(counterName + "-Begin");
  655. };
  656. Tools._EndUserMark = function (counterName, condition) {
  657. if (condition === void 0) { condition = true; }
  658. if (!condition || !Tools._performance.mark) {
  659. return;
  660. }
  661. Tools._performance.mark(counterName + "-End");
  662. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  663. };
  664. Tools._StartPerformanceConsole = function (counterName, condition) {
  665. if (condition === void 0) { condition = true; }
  666. if (!condition) {
  667. return;
  668. }
  669. Tools._StartUserMark(counterName, condition);
  670. if (console.time) {
  671. console.time(counterName);
  672. }
  673. };
  674. Tools._EndPerformanceConsole = function (counterName, condition) {
  675. if (condition === void 0) { condition = true; }
  676. if (!condition) {
  677. return;
  678. }
  679. Tools._EndUserMark(counterName, condition);
  680. if (console.time) {
  681. console.timeEnd(counterName);
  682. }
  683. };
  684. Object.defineProperty(Tools, "Now", {
  685. get: function () {
  686. if (window.performance && window.performance.now) {
  687. return window.performance.now();
  688. }
  689. return new Date().getTime();
  690. },
  691. enumerable: true,
  692. configurable: true
  693. });
  694. // Deprecated
  695. Tools.GetFps = function () {
  696. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  697. return 0;
  698. };
  699. Tools.BaseUrl = "";
  700. Tools.GetExponantOfTwo = function (value, max) {
  701. var count = 1;
  702. do {
  703. count *= 2;
  704. } while (count < value);
  705. if (count > max)
  706. count = max;
  707. return count;
  708. };
  709. // Logs
  710. Tools._NoneLogLevel = 0;
  711. Tools._MessageLogLevel = 1;
  712. Tools._WarningLogLevel = 2;
  713. Tools._ErrorLogLevel = 4;
  714. Tools._LogCache = "";
  715. Tools.Log = Tools._LogEnabled;
  716. Tools.Warn = Tools._WarnEnabled;
  717. Tools.Error = Tools._ErrorEnabled;
  718. // Performances
  719. Tools._PerformanceNoneLogLevel = 0;
  720. Tools._PerformanceUserMarkLogLevel = 1;
  721. Tools._PerformanceConsoleLogLevel = 2;
  722. Tools._performance = window.performance;
  723. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  724. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  725. return Tools;
  726. })();
  727. BABYLON.Tools = Tools;
  728. /**
  729. * An implementation of a loop for asynchronous functions.
  730. */
  731. var AsyncLoop = (function () {
  732. /**
  733. * Constroctor.
  734. * @param iterations the number of iterations.
  735. * @param _fn the function to run each iteration
  736. * @param _successCallback the callback that will be called upon succesful execution
  737. * @param offset starting offset.
  738. */
  739. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  740. if (offset === void 0) { offset = 0; }
  741. this.iterations = iterations;
  742. this._fn = _fn;
  743. this._successCallback = _successCallback;
  744. this.index = offset - 1;
  745. this._done = false;
  746. }
  747. /**
  748. * Execute the next iteration. Must be called after the last iteration was finished.
  749. */
  750. AsyncLoop.prototype.executeNext = function () {
  751. if (!this._done) {
  752. if (this.index + 1 < this.iterations) {
  753. ++this.index;
  754. this._fn(this);
  755. }
  756. else {
  757. this.breakLoop();
  758. }
  759. }
  760. };
  761. /**
  762. * Break the loop and run the success callback.
  763. */
  764. AsyncLoop.prototype.breakLoop = function () {
  765. this._done = true;
  766. this._successCallback();
  767. };
  768. /**
  769. * Helper function
  770. */
  771. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  772. if (offset === void 0) { offset = 0; }
  773. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  774. loop.executeNext();
  775. return loop;
  776. };
  777. /**
  778. * A for-loop that will run a given number of iterations synchronous and the rest async.
  779. * @param iterations total number of iterations
  780. * @param syncedIterations number of synchronous iterations in each async iteration.
  781. * @param fn the function to call each iteration.
  782. * @param callback a success call back that will be called when iterating stops.
  783. * @param breakFunction a break condition (optional)
  784. * @param timeout timeout settings for the setTimeout function. default - 0.
  785. * @constructor
  786. */
  787. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  788. if (timeout === void 0) { timeout = 0; }
  789. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  790. if (breakFunction && breakFunction())
  791. loop.breakLoop();
  792. else {
  793. setTimeout(function () {
  794. for (var i = 0; i < syncedIterations; ++i) {
  795. var iteration = (loop.index * syncedIterations) + i;
  796. if (iteration >= iterations)
  797. break;
  798. fn(iteration);
  799. if (breakFunction && breakFunction()) {
  800. loop.breakLoop();
  801. break;
  802. }
  803. }
  804. loop.executeNext();
  805. }, timeout);
  806. }
  807. }, callback);
  808. };
  809. return AsyncLoop;
  810. })();
  811. BABYLON.AsyncLoop = AsyncLoop;
  812. })(BABYLON || (BABYLON = {}));
  813. //# sourceMappingURL=babylon.tools.js.map