babylon.tools.ts 29 KB

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