babylon.tools.ts 32 KB

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