tools.ts 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. import { Nullable, float } from "../types";
  2. import { Observable } from "./observable";
  3. import { DomManagement } from "./domManagement";
  4. import { Logger } from "./logger";
  5. import { _TypeStore } from "./typeStore";
  6. import { DeepCopier } from "./deepCopier";
  7. import { PrecisionDate } from "./precisionDate";
  8. import { _DevTools } from "./devTools";
  9. import { WebRequest } from "./webRequest";
  10. import { IFileRequest } from "./fileRequest";
  11. import { EngineStore } from "../Engines/engineStore";
  12. import { FileTools, ReadFileError } from "./fileTools";
  13. import { IOfflineProvider } from "../Offline/IOfflineProvider";
  14. import { PromisePolyfill } from "./promise";
  15. import { TimingTools } from "./timingTools";
  16. import { InstantiationTools } from "./instantiationTools";
  17. import { GUID } from "./guid";
  18. import { IScreenshotSize } from "./interfaces/screenshotSize";
  19. declare type Camera = import("../Cameras/camera").Camera;
  20. declare type Engine = import("../Engines/engine").Engine;
  21. interface IColor4Like {
  22. r: float;
  23. g: float;
  24. b: float;
  25. a: float;
  26. }
  27. /**
  28. * Class containing a set of static utilities functions
  29. */
  30. export class Tools {
  31. /**
  32. * Gets or sets the base URL to use to load assets
  33. */
  34. public static get BaseUrl() {
  35. return FileTools.BaseUrl;
  36. }
  37. public static set BaseUrl(value: string) {
  38. FileTools.BaseUrl = value;
  39. }
  40. /**
  41. * Enable/Disable Custom HTTP Request Headers globally.
  42. * default = false
  43. * @see CustomRequestHeaders
  44. */
  45. public static UseCustomRequestHeaders: boolean = false;
  46. /**
  47. * Custom HTTP Request Headers to be sent with XMLHttpRequests
  48. * i.e. when loading files, where the server/service expects an Authorization header
  49. */
  50. public static CustomRequestHeaders = WebRequest.CustomRequestHeaders;
  51. /**
  52. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  53. */
  54. public static get DefaultRetryStrategy() {
  55. return FileTools.DefaultRetryStrategy;
  56. }
  57. public static set DefaultRetryStrategy(strategy: (url: string, request: WebRequest, retryIndex: number) => number) {
  58. FileTools.DefaultRetryStrategy = strategy;
  59. }
  60. /**
  61. * Default behaviour for cors in the application.
  62. * It can be a string if the expected behavior is identical in the entire app.
  63. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  64. */
  65. public static get CorsBehavior(): string | ((url: string | string[]) => string) {
  66. return FileTools.CorsBehavior;
  67. }
  68. public static set CorsBehavior(value: string | ((url: string | string[]) => string)) {
  69. FileTools.CorsBehavior = value;
  70. }
  71. /**
  72. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  73. * @ignorenaming
  74. */
  75. public static get UseFallbackTexture() {
  76. return EngineStore.UseFallbackTexture;
  77. }
  78. public static set UseFallbackTexture(value: boolean) {
  79. EngineStore.UseFallbackTexture = value;
  80. }
  81. /**
  82. * Use this object to register external classes like custom textures or material
  83. * to allow the laoders to instantiate them
  84. */
  85. public static get RegisteredExternalClasses() {
  86. return InstantiationTools.RegisteredExternalClasses;
  87. }
  88. public static set RegisteredExternalClasses(classes: { [key: string]: Object }) {
  89. InstantiationTools.RegisteredExternalClasses = classes;
  90. }
  91. /**
  92. * Texture content used if a texture cannot loaded
  93. * @ignorenaming
  94. */
  95. public static get fallbackTexture() {
  96. return EngineStore.FallbackTexture;
  97. }
  98. public static set fallbackTexture(value: string) {
  99. EngineStore.FallbackTexture = value;
  100. }
  101. /**
  102. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  103. * @param u defines the coordinate on X axis
  104. * @param v defines the coordinate on Y axis
  105. * @param width defines the width of the source data
  106. * @param height defines the height of the source data
  107. * @param pixels defines the source byte array
  108. * @param color defines the output color
  109. */
  110. public static FetchToRef(u: number, v: number, width: number, height: number, pixels: Uint8Array, color: IColor4Like): void {
  111. let wrappedU = (Math.abs(u) * width) % width | 0;
  112. let wrappedV = (Math.abs(v) * height) % height | 0;
  113. let position = (wrappedU + wrappedV * width) * 4;
  114. color.r = pixels[position] / 255;
  115. color.g = pixels[position + 1] / 255;
  116. color.b = pixels[position + 2] / 255;
  117. color.a = pixels[position + 3] / 255;
  118. }
  119. /**
  120. * Interpolates between a and b via alpha
  121. * @param a The lower value (returned when alpha = 0)
  122. * @param b The upper value (returned when alpha = 1)
  123. * @param alpha The interpolation-factor
  124. * @return The mixed value
  125. */
  126. public static Mix(a: number, b: number, alpha: number): number {
  127. return a * (1 - alpha) + b * alpha;
  128. }
  129. /**
  130. * Tries to instantiate a new object from a given class name
  131. * @param className defines the class name to instantiate
  132. * @returns the new object or null if the system was not able to do the instantiation
  133. */
  134. public static Instantiate(className: string): any {
  135. return InstantiationTools.Instantiate(className);
  136. }
  137. /**
  138. * Provides a slice function that will work even on IE
  139. * @param data defines the array to slice
  140. * @param start defines the start of the data (optional)
  141. * @param end defines the end of the data (optional)
  142. * @returns the new sliced array
  143. */
  144. public static Slice<T>(data: T, start?: number, end?: number): T {
  145. if ((data as any).slice) {
  146. return (data as any).slice(start, end);
  147. }
  148. return Array.prototype.slice.call(data, start, end);
  149. }
  150. /**
  151. * Provides a slice function that will work even on IE
  152. * The difference between this and Slice is that this will force-convert to array
  153. * @param data defines the array to slice
  154. * @param start defines the start of the data (optional)
  155. * @param end defines the end of the data (optional)
  156. * @returns the new sliced array
  157. */
  158. public static SliceToArray<T, P>(data: T, start?: number, end?: number): Array<P> {
  159. if (Array.isArray(data)) {
  160. return (data as Array<P>).slice(start, end);
  161. }
  162. return Array.prototype.slice.call(data, start, end);
  163. }
  164. /**
  165. * Polyfill for setImmediate
  166. * @param action defines the action to execute after the current execution block
  167. */
  168. public static SetImmediate(action: () => void) {
  169. TimingTools.SetImmediate(action);
  170. }
  171. /**
  172. * Function indicating if a number is an exponent of 2
  173. * @param value defines the value to test
  174. * @returns true if the value is an exponent of 2
  175. */
  176. public static IsExponentOfTwo(value: number): boolean {
  177. var count = 1;
  178. do {
  179. count *= 2;
  180. } while (count < value);
  181. return count === value;
  182. }
  183. private static _tmpFloatArray = new Float32Array(1);
  184. /**
  185. * Returns the nearest 32-bit single precision float representation of a Number
  186. * @param value A Number. If the parameter is of a different type, it will get converted
  187. * to a number or to NaN if it cannot be converted
  188. * @returns number
  189. */
  190. public static FloatRound(value: number): number {
  191. if (Math.fround) {
  192. return Math.fround(value);
  193. }
  194. return (Tools._tmpFloatArray[0] = value);
  195. }
  196. /**
  197. * Extracts the filename from a path
  198. * @param path defines the path to use
  199. * @returns the filename
  200. */
  201. public static GetFilename(path: string): string {
  202. var index = path.lastIndexOf("/");
  203. if (index < 0) {
  204. return path;
  205. }
  206. return path.substring(index + 1);
  207. }
  208. /**
  209. * Extracts the "folder" part of a path (everything before the filename).
  210. * @param uri The URI to extract the info from
  211. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  212. * @returns The "folder" part of the path
  213. */
  214. public static GetFolderPath(uri: string, returnUnchangedIfNoSlash = false): string {
  215. var index = uri.lastIndexOf("/");
  216. if (index < 0) {
  217. if (returnUnchangedIfNoSlash) {
  218. return uri;
  219. }
  220. return "";
  221. }
  222. return uri.substring(0, index + 1);
  223. }
  224. /**
  225. * Extracts text content from a DOM element hierarchy
  226. * Back Compat only, please use DomManagement.GetDOMTextContent instead.
  227. */
  228. public static GetDOMTextContent = DomManagement.GetDOMTextContent;
  229. /**
  230. * Convert an angle in radians to degrees
  231. * @param angle defines the angle to convert
  232. * @returns the angle in degrees
  233. */
  234. public static ToDegrees(angle: number): number {
  235. return (angle * 180) / Math.PI;
  236. }
  237. /**
  238. * Convert an angle in degrees to radians
  239. * @param angle defines the angle to convert
  240. * @returns the angle in radians
  241. */
  242. public static ToRadians(angle: number): number {
  243. return (angle * Math.PI) / 180;
  244. }
  245. /**
  246. * Returns an array if obj is not an array
  247. * @param obj defines the object to evaluate as an array
  248. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  249. * @returns either obj directly if obj is an array or a new array containing obj
  250. */
  251. public static MakeArray(obj: any, allowsNullUndefined?: boolean): Nullable<Array<any>> {
  252. if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
  253. return null;
  254. }
  255. return Array.isArray(obj) ? obj : [obj];
  256. }
  257. /**
  258. * Gets the pointer prefix to use
  259. * @param engine defines the engine we are finding the prefix for
  260. * @returns "pointer" if touch is enabled. Else returns "mouse"
  261. */
  262. public static GetPointerPrefix(engine: Engine): string {
  263. var eventPrefix = "pointer";
  264. // Check if pointer events are supported
  265. if (DomManagement.IsWindowObjectExist() && !window.PointerEvent && DomManagement.IsNavigatorAvailable() && !navigator.pointerEnabled) {
  266. eventPrefix = "mouse";
  267. }
  268. // Special Fallback MacOS Safari...
  269. if (
  270. engine._badDesktopOS &&
  271. !engine._badOS &&
  272. // And not ipad pros who claim to be macs...
  273. !(document && "ontouchend" in document)
  274. ) {
  275. eventPrefix = "mouse";
  276. }
  277. return eventPrefix;
  278. }
  279. /**
  280. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  281. * @param url define the url we are trying
  282. * @param element define the dom element where to configure the cors policy
  283. */
  284. public static SetCorsBehavior(url: string | string[], element: { crossOrigin: string | null }): void {
  285. FileTools.SetCorsBehavior(url, element);
  286. }
  287. // External files
  288. /**
  289. * Removes unwanted characters from an url
  290. * @param url defines the url to clean
  291. * @returns the cleaned url
  292. */
  293. public static CleanUrl(url: string): string {
  294. url = url.replace(/#/gm, "%23");
  295. return url;
  296. }
  297. /**
  298. * Gets or sets a function used to pre-process url before using them to load assets
  299. */
  300. public static get PreprocessUrl() {
  301. return FileTools.PreprocessUrl;
  302. }
  303. public static set PreprocessUrl(processor: (url: string) => string) {
  304. FileTools.PreprocessUrl = processor;
  305. }
  306. /**
  307. * Loads an image as an HTMLImageElement.
  308. * @param input url string, ArrayBuffer, or Blob to load
  309. * @param onLoad callback called when the image successfully loads
  310. * @param onError callback called when the image fails to load
  311. * @param offlineProvider offline provider for caching
  312. * @param mimeType optional mime type
  313. * @returns the HTMLImageElement of the loaded image
  314. */
  315. public static LoadImage(input: string | ArrayBuffer | Blob, onLoad: (img: HTMLImageElement | ImageBitmap) => void, onError: (message?: string, exception?: any) => void, offlineProvider: Nullable<IOfflineProvider>, mimeType?: string): Nullable<HTMLImageElement> {
  316. return FileTools.LoadImage(input, onLoad, onError, offlineProvider, mimeType);
  317. }
  318. /**
  319. * Loads a file from a url
  320. * @param url url string, ArrayBuffer, or Blob to load
  321. * @param onSuccess callback called when the file successfully loads
  322. * @param onProgress callback called while file is loading (if the server supports this mode)
  323. * @param offlineProvider defines the offline provider for caching
  324. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  325. * @param onError callback called when the file fails to load
  326. * @returns a file request object
  327. */
  328. public static LoadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, offlineProvider?: IOfflineProvider, useArrayBuffer?: boolean, onError?: (request?: WebRequest, exception?: any) => void): IFileRequest {
  329. return FileTools.LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  330. }
  331. /**
  332. * Loads a file from a url
  333. * @param url the file url to load
  334. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  335. * @returns a promise containing an ArrayBuffer corresponding to the loaded file
  336. */
  337. public static LoadFileAsync(url: string, useArrayBuffer: boolean = true): Promise<ArrayBuffer | string> {
  338. return new Promise((resolve, reject) => {
  339. FileTools.LoadFile(
  340. url,
  341. (data) => {
  342. resolve(data);
  343. },
  344. undefined,
  345. undefined,
  346. useArrayBuffer,
  347. (request, exception) => {
  348. reject(exception);
  349. }
  350. );
  351. });
  352. }
  353. /**
  354. * Load a script (identified by an url). When the url returns, the
  355. * content of this file is added into a new script element, attached to the DOM (body element)
  356. * @param scriptUrl defines the url of the script to laod
  357. * @param onSuccess defines the callback called when the script is loaded
  358. * @param onError defines the callback to call if an error occurs
  359. * @param scriptId defines the id of the script element
  360. */
  361. public static LoadScript(scriptUrl: string, onSuccess: () => void, onError?: (message?: string, exception?: any) => void, scriptId?: string) {
  362. if (!DomManagement.IsWindowObjectExist()) {
  363. return;
  364. }
  365. var head = document.getElementsByTagName("head")[0];
  366. var script = document.createElement("script");
  367. script.setAttribute("type", "text/javascript");
  368. script.setAttribute("src", scriptUrl);
  369. if (scriptId) {
  370. script.id = scriptId;
  371. }
  372. script.onload = () => {
  373. if (onSuccess) {
  374. onSuccess();
  375. }
  376. };
  377. script.onerror = (e) => {
  378. if (onError) {
  379. onError(`Unable to load script '${scriptUrl}'`, e);
  380. }
  381. };
  382. head.appendChild(script);
  383. }
  384. /**
  385. * Load an asynchronous script (identified by an url). When the url returns, the
  386. * content of this file is added into a new script element, attached to the DOM (body element)
  387. * @param scriptUrl defines the url of the script to laod
  388. * @param scriptId defines the id of the script element
  389. * @returns a promise request object
  390. */
  391. public static LoadScriptAsync(scriptUrl: string, scriptId?: string): Promise<void> {
  392. return new Promise((resolve, reject) => {
  393. this.LoadScript(
  394. scriptUrl,
  395. () => {
  396. resolve();
  397. },
  398. (message, exception) => {
  399. reject(exception);
  400. }
  401. );
  402. });
  403. }
  404. /**
  405. * Loads a file from a blob
  406. * @param fileToLoad defines the blob to use
  407. * @param callback defines the callback to call when data is loaded
  408. * @param progressCallback defines the callback to call during loading process
  409. * @returns a file request object
  410. */
  411. public static ReadFileAsDataURL(fileToLoad: Blob, callback: (data: any) => void, progressCallback: (ev: ProgressEvent) => any): IFileRequest {
  412. let reader = new FileReader();
  413. let request: IFileRequest = {
  414. onCompleteObservable: new Observable<IFileRequest>(),
  415. abort: () => reader.abort(),
  416. };
  417. reader.onloadend = (e) => {
  418. request.onCompleteObservable.notifyObservers(request);
  419. };
  420. reader.onload = (e) => {
  421. //target doesn't have result from ts 1.3
  422. callback((<any>e.target)["result"]);
  423. };
  424. reader.onprogress = progressCallback;
  425. reader.readAsDataURL(fileToLoad);
  426. return request;
  427. }
  428. /**
  429. * Reads a file from a File object
  430. * @param file defines the file to load
  431. * @param onSuccess defines the callback to call when data is loaded
  432. * @param onProgress defines the callback to call during loading process
  433. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  434. * @param onError defines the callback to call when an error occurs
  435. * @returns a file request object
  436. */
  437. public static ReadFile(file: File, onSuccess: (data: any) => void, onProgress?: (ev: ProgressEvent) => any, useArrayBuffer?: boolean, onError?: (error: ReadFileError) => void): IFileRequest {
  438. return FileTools.ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError);
  439. }
  440. /**
  441. * Creates a data url from a given string content
  442. * @param content defines the content to convert
  443. * @returns the new data url link
  444. */
  445. public static FileAsURL(content: string): string {
  446. var fileBlob = new Blob([content]);
  447. var url = window.URL || window.webkitURL;
  448. var link: string = url.createObjectURL(fileBlob);
  449. return link;
  450. }
  451. /**
  452. * Format the given number to a specific decimal format
  453. * @param value defines the number to format
  454. * @param decimals defines the number of decimals to use
  455. * @returns the formatted string
  456. */
  457. public static Format(value: number, decimals: number = 2): string {
  458. return value.toFixed(decimals);
  459. }
  460. /**
  461. * Tries to copy an object by duplicating every property
  462. * @param source defines the source object
  463. * @param destination defines the target object
  464. * @param doNotCopyList defines a list of properties to avoid
  465. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  466. */
  467. public static DeepCopy(source: any, destination: any, doNotCopyList?: string[], mustCopyList?: string[]): void {
  468. DeepCopier.DeepCopy(source, destination, doNotCopyList, mustCopyList);
  469. }
  470. /**
  471. * Gets a boolean indicating if the given object has no own property
  472. * @param obj defines the object to test
  473. * @returns true if object has no own property
  474. */
  475. public static IsEmpty(obj: any): boolean {
  476. for (var i in obj) {
  477. if (obj.hasOwnProperty(i)) {
  478. return false;
  479. }
  480. }
  481. return true;
  482. }
  483. /**
  484. * Function used to register events at window level
  485. * @param windowElement defines the Window object to use
  486. * @param events defines the events to register
  487. */
  488. public static RegisterTopRootEvents(windowElement: Window, events: { name: string; handler: Nullable<(e: FocusEvent) => any> }[]): void {
  489. for (var index = 0; index < events.length; index++) {
  490. var event = events[index];
  491. windowElement.addEventListener(event.name, <any>event.handler, false);
  492. try {
  493. if (window.parent) {
  494. window.parent.addEventListener(event.name, <any>event.handler, false);
  495. }
  496. } catch (e) {
  497. // Silently fails...
  498. }
  499. }
  500. }
  501. /**
  502. * Function used to unregister events from window level
  503. * @param windowElement defines the Window object to use
  504. * @param events defines the events to unregister
  505. */
  506. public static UnregisterTopRootEvents(windowElement: Window, events: { name: string; handler: Nullable<(e: FocusEvent) => any> }[]): void {
  507. for (var index = 0; index < events.length; index++) {
  508. var event = events[index];
  509. windowElement.removeEventListener(event.name, <any>event.handler);
  510. try {
  511. if (windowElement.parent) {
  512. windowElement.parent.removeEventListener(event.name, <any>event.handler);
  513. }
  514. } catch (e) {
  515. // Silently fails...
  516. }
  517. }
  518. }
  519. /**
  520. * @ignore
  521. */
  522. public static _ScreenshotCanvas: HTMLCanvasElement;
  523. /**
  524. * Dumps the current bound framebuffer
  525. * @param width defines the rendering width
  526. * @param height defines the rendering height
  527. * @param engine defines the hosting engine
  528. * @param successCallback defines the callback triggered once the data are available
  529. * @param mimeType defines the mime type of the result
  530. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  531. * @return a void promise
  532. */
  533. public static async DumpFramebuffer(width: number, height: number, engine: Engine, successCallback?: (data: string) => void, mimeType: string = "image/png", fileName?: string) {
  534. // Read the contents of the framebuffer
  535. let bufferView = await engine.readPixels(0, 0, width, height);
  536. const data = new Uint8Array(bufferView.buffer);
  537. Tools.DumpData(width, height, data, successCallback as (data: string | ArrayBuffer) => void, mimeType, fileName, true);
  538. }
  539. /**
  540. * Dumps an array buffer
  541. * @param width defines the rendering width
  542. * @param height defines the rendering height
  543. * @param data the data array
  544. * @param successCallback defines the callback triggered once the data are available
  545. * @param mimeType defines the mime type of the result
  546. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  547. * @param invertY true to invert the picture in the Y dimension
  548. * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string
  549. */
  550. public static DumpData(width: number, height: number, data: ArrayBufferView, successCallback?: (data: string | ArrayBuffer) => void, mimeType: string = "image/png", fileName?: string, invertY = false, toArrayBuffer = false) {
  551. // Create a 2D canvas to store the result
  552. if (!Tools._ScreenshotCanvas) {
  553. Tools._ScreenshotCanvas = document.createElement("canvas");
  554. }
  555. Tools._ScreenshotCanvas.width = width;
  556. Tools._ScreenshotCanvas.height = height;
  557. var context = Tools._ScreenshotCanvas.getContext("2d");
  558. if (context) {
  559. // Convert if data are float32
  560. if (data instanceof Float32Array) {
  561. const data2 = new Uint8Array(data.length);
  562. let n = data.length;
  563. while (n--) {
  564. let v = data[n];
  565. data2[n] = v < 0 ? 0 : v > 1 ? 1 : Math.round(v * 255);
  566. }
  567. data = data2;
  568. }
  569. // Copy the pixels to a 2D canvas
  570. var imageData = context.createImageData(width, height);
  571. var castData = <any>imageData.data;
  572. castData.set(data);
  573. context.putImageData(imageData, 0, 0);
  574. let canvas = Tools._ScreenshotCanvas;
  575. if (invertY) {
  576. var canvas2 = document.createElement('canvas');
  577. canvas2.width = width;
  578. canvas2.height = height;
  579. var ctx2 = canvas2.getContext('2d');
  580. if (!ctx2) {
  581. return;
  582. }
  583. ctx2.translate(0, height);
  584. ctx2.scale(1, -1);
  585. ctx2.drawImage(Tools._ScreenshotCanvas, 0, 0);
  586. canvas = canvas2;
  587. }
  588. if (toArrayBuffer) {
  589. Tools.ToBlob(canvas, (blob) => {
  590. let fileReader = new FileReader();
  591. fileReader.onload = (event: any) => {
  592. let arrayBuffer = event.target!.result as ArrayBuffer;
  593. if (successCallback) {
  594. successCallback(arrayBuffer);
  595. }
  596. };
  597. fileReader.readAsArrayBuffer(blob!);
  598. });
  599. } else {
  600. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName, canvas);
  601. }
  602. }
  603. }
  604. /**
  605. * Dumps an array buffer
  606. * @param width defines the rendering width
  607. * @param height defines the rendering height
  608. * @param data the data array
  609. * @param successCallback defines the callback triggered once the data are available
  610. * @param mimeType defines the mime type of the result
  611. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  612. * @param invertY true to invert the picture in the Y dimension
  613. * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string
  614. * @return a promise that resolve to the final data
  615. */
  616. public static DumpDataAsync(width: number, height: number, data: ArrayBufferView, mimeType: string = "image/png", fileName?: string, invertY = false, toArrayBuffer = false): Promise<string | ArrayBuffer> {
  617. return new Promise((resolve) => {
  618. Tools.DumpData(width, height, data, (result) => resolve(result), mimeType, fileName, invertY, toArrayBuffer);
  619. });
  620. }
  621. /**
  622. * Converts the canvas data to blob.
  623. * This acts as a polyfill for browsers not supporting the to blob function.
  624. * @param canvas Defines the canvas to extract the data from
  625. * @param successCallback Defines the callback triggered once the data are available
  626. * @param mimeType Defines the mime type of the result
  627. */
  628. static ToBlob(canvas: HTMLCanvasElement, successCallback: (blob: Nullable<Blob>) => void, mimeType: string = "image/png"): void {
  629. // We need HTMLCanvasElement.toBlob for HD screenshots
  630. if (!canvas.toBlob) {
  631. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  632. canvas.toBlob = function (callback, type, quality) {
  633. setTimeout(() => {
  634. var binStr = atob(this.toDataURL(type, quality).split(",")[1]),
  635. len = binStr.length,
  636. arr = new Uint8Array(len);
  637. for (var i = 0; i < len; i++) {
  638. arr[i] = binStr.charCodeAt(i);
  639. }
  640. callback(new Blob([arr]));
  641. });
  642. };
  643. }
  644. canvas.toBlob(function (blob) {
  645. successCallback(blob);
  646. }, mimeType);
  647. }
  648. /**
  649. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  650. * @param successCallback defines the callback triggered once the data are available
  651. * @param mimeType defines the mime type of the result
  652. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  653. * @param canvas canvas to get the data from. If not provided, use the default screenshot canvas
  654. */
  655. static EncodeScreenshotCanvasData(successCallback?: (data: string) => void, mimeType: string = "image/png", fileName?: string, canvas?: HTMLCanvasElement): void {
  656. if (successCallback) {
  657. var base64Image = (canvas ?? Tools._ScreenshotCanvas).toDataURL(mimeType);
  658. successCallback(base64Image);
  659. }
  660. else {
  661. this.ToBlob(canvas ?? Tools._ScreenshotCanvas, function(blob) {
  662. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  663. if (("download" in document.createElement("a"))) {
  664. if (!fileName) {
  665. var date = new Date();
  666. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  667. fileName = "screenshot_" + stringDate + ".png";
  668. }
  669. Tools.Download(blob!, fileName);
  670. }
  671. else {
  672. var url = URL.createObjectURL(blob);
  673. var newWindow = window.open("");
  674. if (!newWindow) { return; }
  675. var img = newWindow.document.createElement("img");
  676. img.onload = function() {
  677. // no longer need to read the blob so it's revoked
  678. URL.revokeObjectURL(url);
  679. };
  680. img.src = url;
  681. newWindow.document.body.appendChild(img);
  682. }
  683. }, mimeType);
  684. }
  685. }
  686. /**
  687. * Downloads a blob in the browser
  688. * @param blob defines the blob to download
  689. * @param fileName defines the name of the downloaded file
  690. */
  691. public static Download(blob: Blob, fileName: string): void {
  692. if (navigator && navigator.msSaveBlob) {
  693. navigator.msSaveBlob(blob, fileName);
  694. return;
  695. }
  696. var url = window.URL.createObjectURL(blob);
  697. var a = document.createElement("a");
  698. document.body.appendChild(a);
  699. a.style.display = "none";
  700. a.href = url;
  701. a.download = fileName;
  702. a.addEventListener("click", () => {
  703. if (a.parentElement) {
  704. a.parentElement.removeChild(a);
  705. }
  706. });
  707. a.click();
  708. window.URL.revokeObjectURL(url);
  709. }
  710. /**
  711. * Will return the right value of the noPreventDefault variable
  712. * Needed to keep backwards compatibility to the old API.
  713. *
  714. * @param args arguments passed to the attachControl function
  715. * @returns the correct value for noPreventDefault
  716. */
  717. public static BackCompatCameraNoPreventDefault(args: IArguments): boolean {
  718. // is it used correctly?
  719. if (typeof args[0] === "boolean") {
  720. return args[0];
  721. } else if (typeof args[1] === "boolean") {
  722. return args[1];
  723. }
  724. return false;
  725. }
  726. /**
  727. * Captures a screenshot of the current rendering
  728. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  729. * @param engine defines the rendering engine
  730. * @param camera defines the source camera
  731. * @param size This parameter can be set to a single number or to an object with the
  732. * following (optional) properties: precision, width, height. If a single number is passed,
  733. * it will be used for both width and height. If an object is passed, the screenshot size
  734. * will be derived from the parameters. The precision property is a multiplier allowing
  735. * rendering at a higher or lower resolution
  736. * @param successCallback defines the callback receives a single parameter which contains the
  737. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  738. * src parameter of an <img> to display it
  739. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  740. * Check your browser for supported MIME types
  741. */
  742. public static CreateScreenshot(engine: Engine, camera: Camera, size: IScreenshotSize | number, successCallback?: (data: string) => void, mimeType: string = "image/png"): void {
  743. throw _DevTools.WarnImport("ScreenshotTools");
  744. }
  745. /**
  746. * Captures a screenshot of the current rendering
  747. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  748. * @param engine defines the rendering engine
  749. * @param camera defines the source camera
  750. * @param size This parameter can be set to a single number or to an object with the
  751. * following (optional) properties: precision, width, height. If a single number is passed,
  752. * it will be used for both width and height. If an object is passed, the screenshot size
  753. * will be derived from the parameters. The precision property is a multiplier allowing
  754. * rendering at a higher or lower resolution
  755. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  756. * Check your browser for supported MIME types
  757. * @returns screenshot as a string of base64-encoded characters. This string can be assigned
  758. * to the src parameter of an <img> to display it
  759. */
  760. public static CreateScreenshotAsync(engine: Engine, camera: Camera, size: IScreenshotSize | number, mimeType: string = "image/png"): Promise<string> {
  761. throw _DevTools.WarnImport("ScreenshotTools");
  762. }
  763. /**
  764. * Generates an image screenshot from the specified camera.
  765. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  766. * @param engine The engine to use for rendering
  767. * @param camera The camera to use for rendering
  768. * @param size This parameter can be set to a single number or to an object with the
  769. * following (optional) properties: precision, width, height. If a single number is passed,
  770. * it will be used for both width and height. If an object is passed, the screenshot size
  771. * will be derived from the parameters. The precision property is a multiplier allowing
  772. * rendering at a higher or lower resolution
  773. * @param successCallback The callback receives a single parameter which contains the
  774. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  775. * src parameter of an <img> to display it
  776. * @param mimeType The MIME type of the screenshot image (default: image/png).
  777. * Check your browser for supported MIME types
  778. * @param samples Texture samples (default: 1)
  779. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  780. * @param fileName A name for for the downloaded file.
  781. */
  782. public static CreateScreenshotUsingRenderTarget(engine: Engine, camera: Camera, size: IScreenshotSize | number, successCallback?: (data: string) => void, mimeType: string = "image/png", samples: number = 1, antialiasing: boolean = false, fileName?: string): void {
  783. throw _DevTools.WarnImport("ScreenshotTools");
  784. }
  785. /**
  786. * Generates an image screenshot from the specified camera.
  787. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  788. * @param engine The engine to use for rendering
  789. * @param camera The camera to use for rendering
  790. * @param size This parameter can be set to a single number or to an object with the
  791. * following (optional) properties: precision, width, height. If a single number is passed,
  792. * it will be used for both width and height. If an object is passed, the screenshot size
  793. * will be derived from the parameters. The precision property is a multiplier allowing
  794. * rendering at a higher or lower resolution
  795. * @param mimeType The MIME type of the screenshot image (default: image/png).
  796. * Check your browser for supported MIME types
  797. * @param samples Texture samples (default: 1)
  798. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  799. * @param fileName A name for for the downloaded file.
  800. * @returns screenshot as a string of base64-encoded characters. This string can be assigned
  801. * to the src parameter of an <img> to display it
  802. */
  803. public static CreateScreenshotUsingRenderTargetAsync(engine: Engine, camera: Camera, size: IScreenshotSize | number, mimeType: string = "image/png", samples: number = 1, antialiasing: boolean = false, fileName?: string): Promise<string> {
  804. throw _DevTools.WarnImport("ScreenshotTools");
  805. }
  806. /**
  807. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  808. * Be aware Math.random() could cause collisions, but:
  809. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  810. * @returns a pseudo random id
  811. */
  812. public static RandomId(): string {
  813. return GUID.RandomId();
  814. }
  815. /**
  816. * Test if the given uri is a base64 string
  817. * @param uri The uri to test
  818. * @return True if the uri is a base64 string or false otherwise
  819. */
  820. public static IsBase64(uri: string): boolean {
  821. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  822. }
  823. /**
  824. * Decode the given base64 uri.
  825. * @param uri The uri to decode
  826. * @return The decoded base64 data.
  827. */
  828. public static DecodeBase64(uri: string): ArrayBuffer {
  829. const decodedString = atob(uri.split(",")[1]);
  830. const bufferLength = decodedString.length;
  831. const bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  832. for (let i = 0; i < bufferLength; i++) {
  833. bufferView[i] = decodedString.charCodeAt(i);
  834. }
  835. return bufferView.buffer;
  836. }
  837. /**
  838. * Gets the absolute url.
  839. * @param url the input url
  840. * @return the absolute url
  841. */
  842. public static GetAbsoluteUrl(url: string): string {
  843. const a = document.createElement("a");
  844. a.href = url;
  845. return a.href;
  846. }
  847. // Logs
  848. /**
  849. * No log
  850. */
  851. public static readonly NoneLogLevel = Logger.NoneLogLevel;
  852. /**
  853. * Only message logs
  854. */
  855. public static readonly MessageLogLevel = Logger.MessageLogLevel;
  856. /**
  857. * Only warning logs
  858. */
  859. public static readonly WarningLogLevel = Logger.WarningLogLevel;
  860. /**
  861. * Only error logs
  862. */
  863. public static readonly ErrorLogLevel = Logger.ErrorLogLevel;
  864. /**
  865. * All logs
  866. */
  867. public static readonly AllLogLevel = Logger.AllLogLevel;
  868. /**
  869. * Gets a value indicating the number of loading errors
  870. * @ignorenaming
  871. */
  872. public static get errorsCount(): number {
  873. return Logger.errorsCount;
  874. }
  875. /**
  876. * Callback called when a new log is added
  877. */
  878. public static OnNewCacheEntry: (entry: string) => void;
  879. /**
  880. * Log a message to the console
  881. * @param message defines the message to log
  882. */
  883. public static Log(message: string): void {
  884. Logger.Log(message);
  885. }
  886. /**
  887. * Write a warning message to the console
  888. * @param message defines the message to log
  889. */
  890. public static Warn(message: string): void {
  891. Logger.Warn(message);
  892. }
  893. /**
  894. * Write an error message to the console
  895. * @param message defines the message to log
  896. */
  897. public static Error(message: string): void {
  898. Logger.Error(message);
  899. }
  900. /**
  901. * Gets current log cache (list of logs)
  902. */
  903. public static get LogCache(): string {
  904. return Logger.LogCache;
  905. }
  906. /**
  907. * Clears the log cache
  908. */
  909. public static ClearLogCache(): void {
  910. Logger.ClearLogCache();
  911. }
  912. /**
  913. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  914. */
  915. public static set LogLevels(level: number) {
  916. Logger.LogLevels = level;
  917. }
  918. /**
  919. * Checks if the window object exists
  920. * Back Compat only, please use DomManagement.IsWindowObjectExist instead.
  921. */
  922. public static IsWindowObjectExist = DomManagement.IsWindowObjectExist;
  923. // Performances
  924. /**
  925. * No performance log
  926. */
  927. public static readonly PerformanceNoneLogLevel = 0;
  928. /**
  929. * Use user marks to log performance
  930. */
  931. public static readonly PerformanceUserMarkLogLevel = 1;
  932. /**
  933. * Log performance to the console
  934. */
  935. public static readonly PerformanceConsoleLogLevel = 2;
  936. private static _performance: Performance;
  937. /**
  938. * Sets the current performance log level
  939. */
  940. public static set PerformanceLogLevel(level: number) {
  941. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  942. Tools.StartPerformanceCounter = Tools._StartUserMark;
  943. Tools.EndPerformanceCounter = Tools._EndUserMark;
  944. return;
  945. }
  946. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  947. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  948. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  949. return;
  950. }
  951. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  952. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  953. }
  954. private static _StartPerformanceCounterDisabled(counterName: string, condition?: boolean): void {}
  955. private static _EndPerformanceCounterDisabled(counterName: string, condition?: boolean): void {}
  956. private static _StartUserMark(counterName: string, condition = true): void {
  957. if (!Tools._performance) {
  958. if (!DomManagement.IsWindowObjectExist()) {
  959. return;
  960. }
  961. Tools._performance = window.performance;
  962. }
  963. if (!condition || !Tools._performance.mark) {
  964. return;
  965. }
  966. Tools._performance.mark(counterName + "-Begin");
  967. }
  968. private static _EndUserMark(counterName: string, condition = true): void {
  969. if (!condition || !Tools._performance.mark) {
  970. return;
  971. }
  972. Tools._performance.mark(counterName + "-End");
  973. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  974. }
  975. private static _StartPerformanceConsole(counterName: string, condition = true): void {
  976. if (!condition) {
  977. return;
  978. }
  979. Tools._StartUserMark(counterName, condition);
  980. if (console.time) {
  981. console.time(counterName);
  982. }
  983. }
  984. private static _EndPerformanceConsole(counterName: string, condition = true): void {
  985. if (!condition) {
  986. return;
  987. }
  988. Tools._EndUserMark(counterName, condition);
  989. console.timeEnd(counterName);
  990. }
  991. /**
  992. * Starts a performance counter
  993. */
  994. public static StartPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._StartPerformanceCounterDisabled;
  995. /**
  996. * Ends a specific performance coutner
  997. */
  998. public static EndPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._EndPerformanceCounterDisabled;
  999. /**
  1000. * Gets either window.performance.now() if supported or Date.now() else
  1001. */
  1002. public static get Now(): number {
  1003. return PrecisionDate.Now;
  1004. }
  1005. /**
  1006. * This method will return the name of the class used to create the instance of the given object.
  1007. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  1008. * @param object the object to get the class name from
  1009. * @param isType defines if the object is actually a type
  1010. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  1011. */
  1012. public static GetClassName(object: any, isType: boolean = false): string {
  1013. let name = null;
  1014. if (!isType && object.getClassName) {
  1015. name = object.getClassName();
  1016. } else {
  1017. if (object instanceof Object) {
  1018. let classObj = isType ? object : Object.getPrototypeOf(object);
  1019. name = classObj.constructor["__bjsclassName__"];
  1020. }
  1021. if (!name) {
  1022. name = typeof object;
  1023. }
  1024. }
  1025. return name;
  1026. }
  1027. /**
  1028. * Gets the first element of an array satisfying a given predicate
  1029. * @param array defines the array to browse
  1030. * @param predicate defines the predicate to use
  1031. * @returns null if not found or the element
  1032. */
  1033. public static First<T>(array: Array<T>, predicate: (item: T) => boolean): Nullable<T> {
  1034. for (let el of array) {
  1035. if (predicate(el)) {
  1036. return el;
  1037. }
  1038. }
  1039. return null;
  1040. }
  1041. /**
  1042. * This method will return the name of the full name of the class, including its owning module (if any).
  1043. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  1044. * @param object the object to get the class name from
  1045. * @param isType defines if the object is actually a type
  1046. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  1047. * @ignorenaming
  1048. */
  1049. public static getFullClassName(object: any, isType: boolean = false): Nullable<string> {
  1050. let className = null;
  1051. let moduleName = null;
  1052. if (!isType && object.getClassName) {
  1053. className = object.getClassName();
  1054. } else {
  1055. if (object instanceof Object) {
  1056. let classObj = isType ? object : Object.getPrototypeOf(object);
  1057. className = classObj.constructor["__bjsclassName__"];
  1058. moduleName = classObj.constructor["__bjsmoduleName__"];
  1059. }
  1060. if (!className) {
  1061. className = typeof object;
  1062. }
  1063. }
  1064. if (!className) {
  1065. return null;
  1066. }
  1067. return (moduleName != null ? moduleName + "." : "") + className;
  1068. }
  1069. /**
  1070. * Returns a promise that resolves after the given amount of time.
  1071. * @param delay Number of milliseconds to delay
  1072. * @returns Promise that resolves after the given amount of time
  1073. */
  1074. public static DelayAsync(delay: number): Promise<void> {
  1075. return new Promise((resolve) => {
  1076. setTimeout(() => {
  1077. resolve();
  1078. }, delay);
  1079. });
  1080. }
  1081. /**
  1082. * Utility function to detect if the current user agent is Safari
  1083. * @returns whether or not the current user agent is safari
  1084. */
  1085. public static IsSafari(): boolean {
  1086. return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  1087. }
  1088. }
  1089. /**
  1090. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  1091. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  1092. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  1093. * @param name The name of the class, case should be preserved
  1094. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  1095. */
  1096. export function className(name: string, module?: string): (target: Object) => void {
  1097. return (target: Object) => {
  1098. (<any>target)["__bjsclassName__"] = name;
  1099. (<any>target)["__bjsmoduleName__"] = module != null ? module : null;
  1100. };
  1101. }
  1102. /**
  1103. * An implementation of a loop for asynchronous functions.
  1104. */
  1105. export class AsyncLoop {
  1106. /**
  1107. * Defines the current index of the loop.
  1108. */
  1109. public index: number;
  1110. private _done: boolean;
  1111. private _fn: (asyncLoop: AsyncLoop) => void;
  1112. private _successCallback: () => void;
  1113. /**
  1114. * Constructor.
  1115. * @param iterations the number of iterations.
  1116. * @param func the function to run each iteration
  1117. * @param successCallback the callback that will be called upon succesful execution
  1118. * @param offset starting offset.
  1119. */
  1120. constructor(
  1121. /**
  1122. * Defines the number of iterations for the loop
  1123. */
  1124. public iterations: number,
  1125. func: (asyncLoop: AsyncLoop) => void,
  1126. successCallback: () => void,
  1127. offset: number = 0
  1128. ) {
  1129. this.index = offset - 1;
  1130. this._done = false;
  1131. this._fn = func;
  1132. this._successCallback = successCallback;
  1133. }
  1134. /**
  1135. * Execute the next iteration. Must be called after the last iteration was finished.
  1136. */
  1137. public executeNext(): void {
  1138. if (!this._done) {
  1139. if (this.index + 1 < this.iterations) {
  1140. ++this.index;
  1141. this._fn(this);
  1142. } else {
  1143. this.breakLoop();
  1144. }
  1145. }
  1146. }
  1147. /**
  1148. * Break the loop and run the success callback.
  1149. */
  1150. public breakLoop(): void {
  1151. this._done = true;
  1152. this._successCallback();
  1153. }
  1154. /**
  1155. * Create and run an async loop.
  1156. * @param iterations the number of iterations.
  1157. * @param fn the function to run each iteration
  1158. * @param successCallback the callback that will be called upon succesful execution
  1159. * @param offset starting offset.
  1160. * @returns the created async loop object
  1161. */
  1162. public static Run(iterations: number, fn: (asyncLoop: AsyncLoop) => void, successCallback: () => void, offset: number = 0): AsyncLoop {
  1163. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  1164. loop.executeNext();
  1165. return loop;
  1166. }
  1167. /**
  1168. * A for-loop that will run a given number of iterations synchronous and the rest async.
  1169. * @param iterations total number of iterations
  1170. * @param syncedIterations number of synchronous iterations in each async iteration.
  1171. * @param fn the function to call each iteration.
  1172. * @param callback a success call back that will be called when iterating stops.
  1173. * @param breakFunction a break condition (optional)
  1174. * @param timeout timeout settings for the setTimeout function. default - 0.
  1175. * @returns the created async loop object
  1176. */
  1177. public static SyncAsyncForLoop(iterations: number, syncedIterations: number, fn: (iteration: number) => void, callback: () => void, breakFunction?: () => boolean, timeout: number = 0): AsyncLoop {
  1178. return AsyncLoop.Run(
  1179. Math.ceil(iterations / syncedIterations),
  1180. (loop: AsyncLoop) => {
  1181. if (breakFunction && breakFunction()) {
  1182. loop.breakLoop();
  1183. } else {
  1184. setTimeout(() => {
  1185. for (var i = 0; i < syncedIterations; ++i) {
  1186. var iteration = loop.index * syncedIterations + i;
  1187. if (iteration >= iterations) {
  1188. break;
  1189. }
  1190. fn(iteration);
  1191. if (breakFunction && breakFunction()) {
  1192. loop.breakLoop();
  1193. break;
  1194. }
  1195. }
  1196. loop.executeNext();
  1197. }, timeout);
  1198. }
  1199. },
  1200. callback
  1201. );
  1202. }
  1203. }
  1204. // Will only be define if Tools is imported freeing up some space when only engine is required
  1205. EngineStore.FallbackTexture =
  1206. "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  1207. // Register promise fallback for IE
  1208. PromisePolyfill.Apply();