babylon.tools.ts 32 KB

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