babylon.tools.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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. public static Format(value: number, decimals: number = 2): string {
  258. return value.toFixed(decimals);
  259. }
  260. public static CheckExtends(v: Vector3, min: Vector3, max: Vector3): void {
  261. if (v.x < min.x)
  262. min.x = v.x;
  263. if (v.y < min.y)
  264. min.y = v.y;
  265. if (v.z < min.z)
  266. min.z = v.z;
  267. if (v.x > max.x)
  268. max.x = v.x;
  269. if (v.y > max.y)
  270. max.y = v.y;
  271. if (v.z > max.z)
  272. max.z = v.z;
  273. }
  274. public static WithinEpsilon(a: number, b: number, epsilon: number = 1.401298E-45): boolean {
  275. var num = a - b;
  276. return -epsilon <= num && num <= epsilon;
  277. }
  278. public static DeepCopy(source, destination, doNotCopyList?: string[], mustCopyList?: string[]): void {
  279. for (var prop in source) {
  280. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  281. continue;
  282. }
  283. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  284. continue;
  285. }
  286. var sourceValue = source[prop];
  287. var typeOfSourceValue = typeof sourceValue;
  288. if (typeOfSourceValue == "function") {
  289. continue;
  290. }
  291. if (typeOfSourceValue == "object") {
  292. if (sourceValue instanceof Array) {
  293. destination[prop] = [];
  294. if (sourceValue.length > 0) {
  295. if (typeof sourceValue[0] == "object") {
  296. for (var index = 0; index < sourceValue.length; index++) {
  297. var clonedValue = cloneValue(sourceValue[index], destination);
  298. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  299. destination[prop].push(clonedValue);
  300. }
  301. }
  302. } else {
  303. destination[prop] = sourceValue.slice(0);
  304. }
  305. }
  306. } else {
  307. destination[prop] = cloneValue(sourceValue, destination);
  308. }
  309. } else {
  310. destination[prop] = sourceValue;
  311. }
  312. }
  313. }
  314. public static IsEmpty(obj): boolean {
  315. for (var i in obj) {
  316. return false;
  317. }
  318. return true;
  319. }
  320. public static RegisterTopRootEvents(events: { name: string; handler: EventListener }[]): void {
  321. for (var index = 0; index < events.length; index++) {
  322. var event = events[index];
  323. window.addEventListener(event.name, event.handler, false);
  324. try {
  325. if (window.parent) {
  326. window.parent.addEventListener(event.name, event.handler, false);
  327. }
  328. } catch (e) {
  329. // Silently fails...
  330. }
  331. }
  332. }
  333. public static UnregisterTopRootEvents(events: { name: string; handler: EventListener }[]): void {
  334. for (var index = 0; index < events.length; index++) {
  335. var event = events[index];
  336. window.removeEventListener(event.name, event.handler);
  337. try {
  338. if (window.parent) {
  339. window.parent.removeEventListener(event.name, event.handler);
  340. }
  341. } catch (e) {
  342. // Silently fails...
  343. }
  344. }
  345. }
  346. public static CreateScreenshot(engine: Engine, camera: Camera, size: any): void {
  347. var width: number;
  348. var height: number;
  349. var scene = camera.getScene();
  350. var previousCamera: BABYLON.Camera = null;
  351. if (scene.activeCamera !== camera) {
  352. previousCamera = scene.activeCamera;
  353. scene.activeCamera = camera;
  354. }
  355. //If a precision value is specified
  356. if (size.precision) {
  357. width = Math.round(engine.getRenderWidth() * size.precision);
  358. height = Math.round(width / engine.getAspectRatio(camera));
  359. size = { width: width, height: height };
  360. }
  361. else if (size.width && size.height) {
  362. width = size.width;
  363. height = size.height;
  364. }
  365. //If passing only width, computing height to keep display canvas ratio.
  366. else if (size.width && !size.height) {
  367. width = size.width;
  368. height = Math.round(width / engine.getAspectRatio(camera));
  369. size = { width: width, height: height };
  370. }
  371. //If passing only height, computing width to keep display canvas ratio.
  372. else if (size.height && !size.width) {
  373. height = size.height;
  374. width = Math.round(height * engine.getAspectRatio(camera));
  375. size = { width: width, height: height };
  376. }
  377. //Assuming here that "size" parameter is a number
  378. else if (!isNaN(size)) {
  379. height = size;
  380. width = size;
  381. }
  382. else {
  383. Tools.Error("Invalid 'size' parameter !");
  384. return;
  385. }
  386. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  387. var texture = new RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  388. texture.renderList = engine.scenes[0].meshes;
  389. texture.onAfterRender = () => {
  390. // Read the contents of the framebuffer
  391. var numberOfChannelsByLine = width * 4;
  392. var halfHeight = height / 2;
  393. //Reading datas from WebGL
  394. var data = engine.readPixels(0, 0, width, height);
  395. //To flip image on Y axis.
  396. for (var i = 0; i < halfHeight; i++) {
  397. for (var j = 0; j < numberOfChannelsByLine; j++) {
  398. var currentCell = j + i * numberOfChannelsByLine;
  399. var targetLine = height - i - 1;
  400. var targetCell = j + targetLine * numberOfChannelsByLine;
  401. var temp = data[currentCell];
  402. data[currentCell] = data[targetCell];
  403. data[targetCell] = temp;
  404. }
  405. }
  406. // Create a 2D canvas to store the result
  407. if (!screenshotCanvas) {
  408. screenshotCanvas = document.createElement('canvas');
  409. }
  410. screenshotCanvas.width = width;
  411. screenshotCanvas.height = height;
  412. var context = screenshotCanvas.getContext('2d');
  413. // Copy the pixels to a 2D canvas
  414. var imageData = context.createImageData(width, height);
  415. imageData.data.set(data);
  416. context.putImageData(imageData, 0, 0);
  417. var base64Image = screenshotCanvas.toDataURL();
  418. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  419. if (("download" in document.createElement("a"))) {
  420. var a = window.document.createElement("a");
  421. a.href = base64Image;
  422. var date = new Date();
  423. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  424. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  425. window.document.body.appendChild(a);
  426. a.addEventListener("click", () => {
  427. a.parentElement.removeChild(a);
  428. });
  429. a.click();
  430. //Or opening a new tab with the image if it is not possible to automatically start download.
  431. } else {
  432. var newWindow = window.open("");
  433. var img = newWindow.document.createElement("img");
  434. img.src = base64Image;
  435. newWindow.document.body.appendChild(img);
  436. }
  437. };
  438. texture.render(true);
  439. texture.dispose();
  440. if (previousCamera) {
  441. scene.activeCamera = previousCamera;
  442. }
  443. }
  444. // XHR response validator for local file scenario
  445. public static ValidateXHRData(xhr: XMLHttpRequest, dataType = 7): boolean {
  446. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  447. try {
  448. if (dataType & 1) {
  449. if (xhr.responseText && xhr.responseText.length > 0) {
  450. return true;
  451. } else if (dataType === 1) {
  452. return false;
  453. }
  454. }
  455. if (dataType & 2) {
  456. // Check header width and height since there is no "TGA" magic number
  457. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  458. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  459. return true;
  460. } else if (dataType === 2) {
  461. return false;
  462. }
  463. }
  464. if (dataType & 4) {
  465. // Check for the "DDS" magic number
  466. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  467. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  468. return true;
  469. } else {
  470. return false;
  471. }
  472. }
  473. } catch (e) {
  474. // Global protection
  475. }
  476. return false;
  477. }
  478. // Logs
  479. private static _NoneLogLevel = 0;
  480. private static _MessageLogLevel = 1;
  481. private static _WarningLogLevel = 2;
  482. private static _ErrorLogLevel = 4;
  483. private static _LogCache = "";
  484. public static OnNewCacheEntry: (entry: string) => void;
  485. static get NoneLogLevel(): number {
  486. return Tools._NoneLogLevel;
  487. }
  488. static get MessageLogLevel(): number {
  489. return Tools._MessageLogLevel;
  490. }
  491. static get WarningLogLevel(): number {
  492. return Tools._WarningLogLevel;
  493. }
  494. static get ErrorLogLevel(): number {
  495. return Tools._ErrorLogLevel;
  496. }
  497. static get AllLogLevel(): number {
  498. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  499. }
  500. private static _AddLogEntry(entry: string) {
  501. Tools._LogCache = entry + Tools._LogCache;
  502. if (Tools.OnNewCacheEntry) {
  503. Tools.OnNewCacheEntry(entry);
  504. }
  505. }
  506. private static _FormatMessage(message: string): string {
  507. var padStr = i => (i < 10) ? "0" + i : "" + i;
  508. var date = new Date();
  509. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  510. }
  511. public static Log: (message: string) => void = Tools._LogEnabled;
  512. private static _LogDisabled(message: string): void {
  513. // nothing to do
  514. }
  515. private static _LogEnabled(message: string): void {
  516. var formattedMessage = Tools._FormatMessage(message);
  517. console.log("BJS - " + formattedMessage);
  518. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  519. Tools._AddLogEntry(entry);
  520. }
  521. public static Warn: (message: string) => void = Tools._WarnEnabled;
  522. private static _WarnDisabled(message: string): void {
  523. // nothing to do
  524. }
  525. private static _WarnEnabled(message: string): void {
  526. var formattedMessage = Tools._FormatMessage(message);
  527. console.warn("BJS - " + formattedMessage);
  528. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  529. Tools._AddLogEntry(entry);
  530. }
  531. public static Error: (message: string) => void = Tools._ErrorEnabled;
  532. private static _ErrorDisabled(message: string): void {
  533. // nothing to do
  534. }
  535. private static _ErrorEnabled(message: string): void {
  536. var formattedMessage = Tools._FormatMessage(message);
  537. console.error("BJS - " + formattedMessage);
  538. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  539. Tools._AddLogEntry(entry);
  540. }
  541. public static get LogCache(): string {
  542. return Tools._LogCache;
  543. }
  544. public static set LogLevels(level: number) {
  545. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  546. Tools.Log = Tools._LogEnabled;
  547. }
  548. else {
  549. Tools.Log = Tools._LogDisabled;
  550. }
  551. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  552. Tools.Warn = Tools._WarnEnabled;
  553. }
  554. else {
  555. Tools.Warn = Tools._WarnDisabled;
  556. }
  557. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  558. Tools.Error = Tools._ErrorEnabled;
  559. }
  560. else {
  561. Tools.Error = Tools._ErrorDisabled;
  562. }
  563. }
  564. // Performances
  565. private static _PerformanceNoneLogLevel = 0;
  566. private static _PerformanceUserMarkLogLevel = 1;
  567. private static _PerformanceConsoleLogLevel = 2;
  568. private static _performance: Performance = window.performance;
  569. static get PerformanceNoneLogLevel(): number {
  570. return Tools._PerformanceNoneLogLevel;
  571. }
  572. static get PerformanceUserMarkLogLevel(): number {
  573. return Tools._PerformanceUserMarkLogLevel;
  574. }
  575. static get PerformanceConsoleLogLevel(): number {
  576. return Tools._PerformanceConsoleLogLevel;
  577. }
  578. public static set PerformanceLogLevel(level: number) {
  579. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  580. Tools.StartPerformanceCounter = Tools._StartUserMark;
  581. Tools.EndPerformanceCounter = Tools._EndUserMark;
  582. return;
  583. }
  584. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  585. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  586. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  587. return;
  588. }
  589. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  590. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  591. }
  592. static _StartPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  593. }
  594. static _EndPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  595. }
  596. static _StartUserMark(counterName: string, condition = true): void {
  597. if (!condition || !Tools._performance.mark) {
  598. return;
  599. }
  600. Tools._performance.mark(counterName + "-Begin");
  601. }
  602. static _EndUserMark(counterName: string, condition = true): void {
  603. if (!condition || !Tools._performance.mark) {
  604. return;
  605. }
  606. Tools._performance.mark(counterName + "-End");
  607. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  608. }
  609. static _StartPerformanceConsole(counterName: string, condition = true): void {
  610. if (!condition) {
  611. return;
  612. }
  613. Tools._StartUserMark(counterName, condition);
  614. if (console.time) {
  615. console.time(counterName);
  616. }
  617. }
  618. static _EndPerformanceConsole(counterName: string, condition = true): void {
  619. if (!condition) {
  620. return;
  621. }
  622. Tools._EndUserMark(counterName, condition);
  623. if (console.time) {
  624. console.timeEnd(counterName);
  625. }
  626. }
  627. public static StartPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._StartPerformanceCounterDisabled;
  628. public static EndPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._EndPerformanceCounterDisabled;
  629. public static get Now(): number {
  630. if (window.performance && window.performance.now) {
  631. return window.performance.now();
  632. }
  633. return new Date().getTime();
  634. }
  635. // Deprecated
  636. public static GetFps(): number {
  637. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  638. return 0;
  639. }
  640. }
  641. /**
  642. * An implementation of a loop for asynchronous functions.
  643. */
  644. export class AsyncLoop {
  645. public index: number;
  646. private _done: boolean;
  647. /**
  648. * Constroctor.
  649. * @param iterations the number of iterations.
  650. * @param _fn the function to run each iteration
  651. * @param _successCallback the callback that will be called upon succesful execution
  652. * @param offset starting offset.
  653. */
  654. constructor(public iterations: number, private _fn: (asyncLoop: AsyncLoop) => void, private _successCallback: () => void, offset: number = 0) {
  655. this.index = offset - 1;
  656. this._done = false;
  657. }
  658. /**
  659. * Execute the next iteration. Must be called after the last iteration was finished.
  660. */
  661. public executeNext(): void {
  662. if (!this._done) {
  663. if (this.index < this.iterations) {
  664. ++this.index;
  665. this._fn(this);
  666. } else {
  667. this.breakLoop();
  668. }
  669. }
  670. }
  671. /**
  672. * Break the loop and run the success callback.
  673. */
  674. public breakLoop(): void {
  675. this._done = true;
  676. this._successCallback();
  677. }
  678. /**
  679. * Helper function
  680. */
  681. public static Run(iterations: number, _fn: (asyncLoop: AsyncLoop) => void, _successCallback: () => void, offset: number = 0): AsyncLoop {
  682. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  683. loop.executeNext();
  684. return loop;
  685. }
  686. /**
  687. * A for-loop that will run a given number of iterations synchronous and the rest async.
  688. * @param iterations total number of iterations
  689. * @param syncedIterations number of synchronous iterations in each async iteration.
  690. * @param fn the function to call each iteration.
  691. * @param callback a success call back that will be called when iterating stops.
  692. * @param breakFunction a break condition (optional)
  693. * @param timeout timeout settings for the setTimeout function. default - 0.
  694. * @constructor
  695. */
  696. public static SyncAsyncForLoop(iterations: number, syncedIterations: number, fn: (iteration: number) => void, callback: () => void, breakFunction?: () => boolean, timeout: number = 0) {
  697. var asyncLoop = new AsyncLoop(Math.ceil(iterations / syncedIterations), (loop: AsyncLoop) => {
  698. if (breakFunction && breakFunction()) loop.breakLoop();
  699. else {
  700. setTimeout(() => {
  701. for (var i = 0; i < syncedIterations; ++i) {
  702. var iteration = (loop.index * syncedIterations) + i;
  703. if (iteration >= iterations) break;
  704. fn(iteration);
  705. if (breakFunction && breakFunction()) {
  706. loop.breakLoop();
  707. break;
  708. }
  709. }
  710. loop.executeNext();
  711. }, timeout);
  712. }
  713. }, callback);
  714. }
  715. }
  716. }