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 = Vector3.Minimize(current, minimum);
  64. maximum = 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 = Vector3.Minimize(current, minimum);
  77. maximum = 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 && 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(FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  173. }
  174. catch (ex) {
  175. // Chrome doesn't support oneTimeOnly parameter
  176. blobURL = URL.createObjectURL(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 || 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. Tools.ReadFile(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: 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. scene.incrementRenderId();
  447. texture.render(true);
  448. texture.dispose();
  449. if (previousCamera) {
  450. scene.activeCamera = previousCamera;
  451. }
  452. }
  453. // XHR response validator for local file scenario
  454. public static ValidateXHRData(xhr: XMLHttpRequest, dataType = 7): boolean {
  455. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  456. try {
  457. if (dataType & 1) {
  458. if (xhr.responseText && xhr.responseText.length > 0) {
  459. return true;
  460. } else if (dataType === 1) {
  461. return false;
  462. }
  463. }
  464. if (dataType & 2) {
  465. // Check header width and height since there is no "TGA" magic number
  466. var tgaHeader = Internals.TGATools.GetTGAHeader(xhr.response);
  467. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  468. return true;
  469. } else if (dataType === 2) {
  470. return false;
  471. }
  472. }
  473. if (dataType & 4) {
  474. // Check for the "DDS" magic number
  475. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  476. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  477. return true;
  478. } else {
  479. return false;
  480. }
  481. }
  482. } catch (e) {
  483. // Global protection
  484. }
  485. return false;
  486. }
  487. // Logs
  488. private static _NoneLogLevel = 0;
  489. private static _MessageLogLevel = 1;
  490. private static _WarningLogLevel = 2;
  491. private static _ErrorLogLevel = 4;
  492. private static _LogCache = "";
  493. public static OnNewCacheEntry: (entry: string) => void;
  494. static get NoneLogLevel(): number {
  495. return Tools._NoneLogLevel;
  496. }
  497. static get MessageLogLevel(): number {
  498. return Tools._MessageLogLevel;
  499. }
  500. static get WarningLogLevel(): number {
  501. return Tools._WarningLogLevel;
  502. }
  503. static get ErrorLogLevel(): number {
  504. return Tools._ErrorLogLevel;
  505. }
  506. static get AllLogLevel(): number {
  507. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  508. }
  509. private static _AddLogEntry(entry: string) {
  510. Tools._LogCache = entry + Tools._LogCache;
  511. if (Tools.OnNewCacheEntry) {
  512. Tools.OnNewCacheEntry(entry);
  513. }
  514. }
  515. private static _FormatMessage(message: string): string {
  516. var padStr = i => (i < 10) ? "0" + i : "" + i;
  517. var date = new Date();
  518. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  519. }
  520. public static Log: (message: string) => void = Tools._LogEnabled;
  521. private static _LogDisabled(message: string): void {
  522. // nothing to do
  523. }
  524. private static _LogEnabled(message: string): void {
  525. var formattedMessage = Tools._FormatMessage(message);
  526. console.log("BJS - " + formattedMessage);
  527. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  528. Tools._AddLogEntry(entry);
  529. }
  530. public static Warn: (message: string) => void = Tools._WarnEnabled;
  531. private static _WarnDisabled(message: string): void {
  532. // nothing to do
  533. }
  534. private static _WarnEnabled(message: string): void {
  535. var formattedMessage = Tools._FormatMessage(message);
  536. console.warn("BJS - " + formattedMessage);
  537. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  538. Tools._AddLogEntry(entry);
  539. }
  540. public static Error: (message: string) => void = Tools._ErrorEnabled;
  541. private static _ErrorDisabled(message: string): void {
  542. // nothing to do
  543. }
  544. private static _ErrorEnabled(message: string): void {
  545. var formattedMessage = Tools._FormatMessage(message);
  546. console.error("BJS - " + formattedMessage);
  547. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  548. Tools._AddLogEntry(entry);
  549. }
  550. public static get LogCache(): string {
  551. return Tools._LogCache;
  552. }
  553. public static set LogLevels(level: number) {
  554. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  555. Tools.Log = Tools._LogEnabled;
  556. }
  557. else {
  558. Tools.Log = Tools._LogDisabled;
  559. }
  560. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  561. Tools.Warn = Tools._WarnEnabled;
  562. }
  563. else {
  564. Tools.Warn = Tools._WarnDisabled;
  565. }
  566. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  567. Tools.Error = Tools._ErrorEnabled;
  568. }
  569. else {
  570. Tools.Error = Tools._ErrorDisabled;
  571. }
  572. }
  573. // Performances
  574. private static _PerformanceNoneLogLevel = 0;
  575. private static _PerformanceUserMarkLogLevel = 1;
  576. private static _PerformanceConsoleLogLevel = 2;
  577. private static _performance: Performance = window.performance;
  578. static get PerformanceNoneLogLevel(): number {
  579. return Tools._PerformanceNoneLogLevel;
  580. }
  581. static get PerformanceUserMarkLogLevel(): number {
  582. return Tools._PerformanceUserMarkLogLevel;
  583. }
  584. static get PerformanceConsoleLogLevel(): number {
  585. return Tools._PerformanceConsoleLogLevel;
  586. }
  587. public static set PerformanceLogLevel(level: number) {
  588. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  589. Tools.StartPerformanceCounter = Tools._StartUserMark;
  590. Tools.EndPerformanceCounter = Tools._EndUserMark;
  591. return;
  592. }
  593. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  594. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  595. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  596. return;
  597. }
  598. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  599. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  600. }
  601. static _StartPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  602. }
  603. static _EndPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  604. }
  605. static _StartUserMark(counterName: string, condition = true): void {
  606. if (!condition || !Tools._performance.mark) {
  607. return;
  608. }
  609. Tools._performance.mark(counterName + "-Begin");
  610. }
  611. static _EndUserMark(counterName: string, condition = true): void {
  612. if (!condition || !Tools._performance.mark) {
  613. return;
  614. }
  615. Tools._performance.mark(counterName + "-End");
  616. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  617. }
  618. static _StartPerformanceConsole(counterName: string, condition = true): void {
  619. if (!condition) {
  620. return;
  621. }
  622. Tools._StartUserMark(counterName, condition);
  623. if (console.time) {
  624. console.time(counterName);
  625. }
  626. }
  627. static _EndPerformanceConsole(counterName: string, condition = true): void {
  628. if (!condition) {
  629. return;
  630. }
  631. Tools._EndUserMark(counterName, condition);
  632. if (console.time) {
  633. console.timeEnd(counterName);
  634. }
  635. }
  636. public static StartPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._StartPerformanceCounterDisabled;
  637. public static EndPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._EndPerformanceCounterDisabled;
  638. public static get Now(): number {
  639. if (window.performance && window.performance.now) {
  640. return window.performance.now();
  641. }
  642. return new Date().getTime();
  643. }
  644. // Deprecated
  645. public static GetFps(): number {
  646. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  647. return 0;
  648. }
  649. }
  650. /**
  651. * An implementation of a loop for asynchronous functions.
  652. */
  653. export class AsyncLoop {
  654. public index: number;
  655. private _done: boolean;
  656. /**
  657. * Constroctor.
  658. * @param iterations the number of iterations.
  659. * @param _fn the function to run each iteration
  660. * @param _successCallback the callback that will be called upon succesful execution
  661. * @param offset starting offset.
  662. */
  663. constructor(public iterations: number, private _fn: (asyncLoop: AsyncLoop) => void, private _successCallback: () => void, offset: number = 0) {
  664. this.index = offset - 1;
  665. this._done = false;
  666. }
  667. /**
  668. * Execute the next iteration. Must be called after the last iteration was finished.
  669. */
  670. public executeNext(): void {
  671. if (!this._done) {
  672. if (this.index + 1 < this.iterations) {
  673. ++this.index;
  674. this._fn(this);
  675. } else {
  676. this.breakLoop();
  677. }
  678. }
  679. }
  680. /**
  681. * Break the loop and run the success callback.
  682. */
  683. public breakLoop(): void {
  684. this._done = true;
  685. this._successCallback();
  686. }
  687. /**
  688. * Helper function
  689. */
  690. public static Run(iterations: number, _fn: (asyncLoop: AsyncLoop) => void, _successCallback: () => void, offset: number = 0): AsyncLoop {
  691. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  692. loop.executeNext();
  693. return loop;
  694. }
  695. /**
  696. * A for-loop that will run a given number of iterations synchronous and the rest async.
  697. * @param iterations total number of iterations
  698. * @param syncedIterations number of synchronous iterations in each async iteration.
  699. * @param fn the function to call each iteration.
  700. * @param callback a success call back that will be called when iterating stops.
  701. * @param breakFunction a break condition (optional)
  702. * @param timeout timeout settings for the setTimeout function. default - 0.
  703. * @constructor
  704. */
  705. public static SyncAsyncForLoop(iterations: number, syncedIterations: number, fn: (iteration: number) => void, callback: () => void, breakFunction?: () => boolean, timeout: number = 0) {
  706. AsyncLoop.Run(Math.ceil(iterations / syncedIterations),(loop: AsyncLoop) => {
  707. if (breakFunction && breakFunction()) loop.breakLoop();
  708. else {
  709. setTimeout(() => {
  710. for (var i = 0; i < syncedIterations; ++i) {
  711. var iteration = (loop.index * syncedIterations) + i;
  712. if (iteration >= iterations) break;
  713. fn(iteration);
  714. if (breakFunction && breakFunction()) {
  715. loop.breakLoop();
  716. break;
  717. }
  718. }
  719. loop.executeNext();
  720. }, timeout);
  721. }
  722. }, callback);
  723. }
  724. }
  725. }