babylon.tools.ts 32 KB

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