babylon.tools.ts 31 KB

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