babylon.tools.ts 32 KB

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