tools.ts 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019
  1. import { FloatArray, IndicesArray, Nullable } from "../types";
  2. import { Color4, Color3, Vector2, Vector3 } from "../Maths/math";
  3. import { Scalar } from "../Maths/math.scalar";
  4. import { IOfflineProvider } from "../Offline/IOfflineProvider";
  5. import { Observable } from "./observable";
  6. import { FilesInputStore } from "./filesInputStore";
  7. import { Constants } from "../Engines/constants";
  8. import { DomManagement } from "./domManagement";
  9. import { Logger } from "./logger";
  10. import { _TypeStore } from "./typeStore";
  11. import { DeepCopier } from "./deepCopier";
  12. import { PrecisionDate } from './precisionDate';
  13. import { _DevTools } from './devTools';
  14. declare type Camera = import("../Cameras/camera").Camera;
  15. declare type Engine = import("../Engines/engine").Engine;
  16. declare type Animation = import("../Animations/animation").Animation;
  17. /**
  18. * Interface for any object that can request an animation frame
  19. */
  20. export interface ICustomAnimationFrameRequester {
  21. /**
  22. * This function will be called when the render loop is ready. If this is not populated, the engine's renderloop function will be called
  23. */
  24. renderFunction?: Function;
  25. /**
  26. * Called to request the next frame to render to
  27. * @see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
  28. */
  29. requestAnimationFrame: Function;
  30. /**
  31. * You can pass this value to cancelAnimationFrame() to cancel the refresh callback request
  32. * @see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame#Return_value
  33. */
  34. requestID?: number;
  35. }
  36. /**
  37. * Interface containing an array of animations
  38. */
  39. export interface IAnimatable {
  40. /**
  41. * Array of animations
  42. */
  43. animations: Array<Animation>;
  44. }
  45. /** Interface used by value gradients (color, factor, ...) */
  46. export interface IValueGradient {
  47. /**
  48. * Gets or sets the gradient value (between 0 and 1)
  49. */
  50. gradient: number;
  51. }
  52. /** Class used to store color4 gradient */
  53. export class ColorGradient implements IValueGradient {
  54. /**
  55. * Gets or sets the gradient value (between 0 and 1)
  56. */
  57. public gradient: number;
  58. /**
  59. * Gets or sets first associated color
  60. */
  61. public color1: Color4;
  62. /**
  63. * Gets or sets second associated color
  64. */
  65. public color2?: Color4;
  66. /**
  67. * Will get a color picked randomly between color1 and color2.
  68. * If color2 is undefined then color1 will be used
  69. * @param result defines the target Color4 to store the result in
  70. */
  71. public getColorToRef(result: Color4) {
  72. if (!this.color2) {
  73. result.copyFrom(this.color1);
  74. return;
  75. }
  76. Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  77. }
  78. }
  79. /** Class used to store color 3 gradient */
  80. export class Color3Gradient implements IValueGradient {
  81. /**
  82. * Gets or sets the gradient value (between 0 and 1)
  83. */
  84. public gradient: number;
  85. /**
  86. * Gets or sets the associated color
  87. */
  88. public color: Color3;
  89. }
  90. /** Class used to store factor gradient */
  91. export class FactorGradient implements IValueGradient {
  92. /**
  93. * Gets or sets the gradient value (between 0 and 1)
  94. */
  95. public gradient: number;
  96. /**
  97. * Gets or sets first associated factor
  98. */
  99. public factor1: number;
  100. /**
  101. * Gets or sets second associated factor
  102. */
  103. public factor2?: number;
  104. /**
  105. * Will get a number picked randomly between factor1 and factor2.
  106. * If factor2 is undefined then factor1 will be used
  107. * @returns the picked number
  108. */
  109. public getFactor(): number {
  110. if (this.factor2 === undefined) {
  111. return this.factor1;
  112. }
  113. return Scalar.Lerp(this.factor1, this.factor2, Math.random());
  114. }
  115. }
  116. /**
  117. * @ignore
  118. * Application error to support additional information when loading a file
  119. */
  120. export class LoadFileError extends Error {
  121. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  122. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  123. // Polyfill for Object.setPrototypeOf if necessary.
  124. private static _setPrototypeOf: (o: any, proto: object | null) => any =
  125. (Object as any).setPrototypeOf || ((o, proto) => { o.__proto__ = proto; return o; });
  126. /**
  127. * Creates a new LoadFileError
  128. * @param message defines the message of the error
  129. * @param request defines the optional XHR request
  130. */
  131. constructor(
  132. message: string,
  133. /** defines the optional XHR request */
  134. public request?: XMLHttpRequest
  135. ) {
  136. super(message);
  137. this.name = "LoadFileError";
  138. LoadFileError._setPrototypeOf(this, LoadFileError.prototype);
  139. }
  140. }
  141. /**
  142. * Class used to define a retry strategy when error happens while loading assets
  143. */
  144. export class RetryStrategy {
  145. /**
  146. * Function used to defines an exponential back off strategy
  147. * @param maxRetries defines the maximum number of retries (3 by default)
  148. * @param baseInterval defines the interval between retries
  149. * @returns the strategy function to use
  150. */
  151. public static ExponentialBackoff(maxRetries = 3, baseInterval = 500) {
  152. return (url: string, request: XMLHttpRequest, retryIndex: number): number => {
  153. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  154. return -1;
  155. }
  156. return Math.pow(2, retryIndex) * baseInterval;
  157. };
  158. }
  159. }
  160. /**
  161. * File request interface
  162. */
  163. export interface IFileRequest {
  164. /**
  165. * Raised when the request is complete (success or error).
  166. */
  167. onCompleteObservable: Observable<IFileRequest>;
  168. /**
  169. * Aborts the request for a file.
  170. */
  171. abort: () => void;
  172. }
  173. /**
  174. * Class containing a set of static utilities functions
  175. */
  176. export class Tools {
  177. /**
  178. * Gets or sets the base URL to use to load assets
  179. */
  180. public static BaseUrl = "";
  181. /**
  182. * Enable/Disable Custom HTTP Request Headers globally.
  183. * default = false
  184. * @see CustomRequestHeaders
  185. */
  186. public static UseCustomRequestHeaders: boolean = false;
  187. /**
  188. * Custom HTTP Request Headers to be sent with XMLHttpRequests
  189. * i.e. when loading files, where the server/service expects an Authorization header.
  190. * @see InjectCustomRequestHeaders injects them to an XMLHttpRequest
  191. */
  192. public static CustomRequestHeaders: { [key: string]: string } = {};
  193. /**
  194. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  195. */
  196. public static DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  197. /**
  198. * Default behaviour for cors in the application.
  199. * It can be a string if the expected behavior is identical in the entire app.
  200. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  201. */
  202. public static CorsBehavior: string | ((url: string | string[]) => string) = "anonymous";
  203. /**
  204. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  205. * @ignorenaming
  206. */
  207. public static UseFallbackTexture = true;
  208. /**
  209. * Use this object to register external classes like custom textures or material
  210. * to allow the laoders to instantiate them
  211. */
  212. public static RegisteredExternalClasses: { [key: string]: Object } = {};
  213. /**
  214. * Texture content used if a texture cannot loaded
  215. * @ignorenaming
  216. */
  217. public static fallbackTexture = "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";
  218. /**
  219. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  220. * @param u defines the coordinate on X axis
  221. * @param v defines the coordinate on Y axis
  222. * @param width defines the width of the source data
  223. * @param height defines the height of the source data
  224. * @param pixels defines the source byte array
  225. * @param color defines the output color
  226. */
  227. public static FetchToRef(u: number, v: number, width: number, height: number, pixels: Uint8Array, color: Color4): void {
  228. let wrappedU = ((Math.abs(u) * width) % width) | 0;
  229. let wrappedV = ((Math.abs(v) * height) % height) | 0;
  230. let position = (wrappedU + wrappedV * width) * 4;
  231. color.r = pixels[position] / 255;
  232. color.g = pixels[position + 1] / 255;
  233. color.b = pixels[position + 2] / 255;
  234. color.a = pixels[position + 3] / 255;
  235. }
  236. /**
  237. * Interpolates between a and b via alpha
  238. * @param a The lower value (returned when alpha = 0)
  239. * @param b The upper value (returned when alpha = 1)
  240. * @param alpha The interpolation-factor
  241. * @return The mixed value
  242. */
  243. public static Mix(a: number, b: number, alpha: number): number {
  244. return a * (1 - alpha) + b * alpha;
  245. }
  246. /**
  247. * Tries to instantiate a new object from a given class name
  248. * @param className defines the class name to instantiate
  249. * @returns the new object or null if the system was not able to do the instantiation
  250. */
  251. public static Instantiate(className: string): any {
  252. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  253. return Tools.RegisteredExternalClasses[className];
  254. }
  255. const internalClass = _TypeStore.GetClass(className);
  256. if (internalClass) {
  257. return internalClass;
  258. }
  259. Logger.Warn(className + " not found, you may have missed an import.");
  260. var arr = className.split(".");
  261. var fn: any = (window || this);
  262. for (var i = 0, len = arr.length; i < len; i++) {
  263. fn = fn[arr[i]];
  264. }
  265. if (typeof fn !== "function") {
  266. return null;
  267. }
  268. return fn;
  269. }
  270. /**
  271. * Provides a slice function that will work even on IE
  272. * @param data defines the array to slice
  273. * @param start defines the start of the data (optional)
  274. * @param end defines the end of the data (optional)
  275. * @returns the new sliced array
  276. */
  277. public static Slice<T>(data: T, start?: number, end?: number): T {
  278. if ((data as any).slice) {
  279. return (data as any).slice(start, end);
  280. }
  281. return Array.prototype.slice.call(data, start, end);
  282. }
  283. /**
  284. * Polyfill for setImmediate
  285. * @param action defines the action to execute after the current execution block
  286. */
  287. public static SetImmediate(action: () => void) {
  288. if (DomManagement.IsWindowObjectExist() && window.setImmediate) {
  289. window.setImmediate(action);
  290. } else {
  291. setTimeout(action, 1);
  292. }
  293. }
  294. /**
  295. * Function indicating if a number is an exponent of 2
  296. * @param value defines the value to test
  297. * @returns true if the value is an exponent of 2
  298. */
  299. public static IsExponentOfTwo(value: number): boolean {
  300. var count = 1;
  301. do {
  302. count *= 2;
  303. } while (count < value);
  304. return count === value;
  305. }
  306. private static _tmpFloatArray = new Float32Array(1);
  307. /**
  308. * Returns the nearest 32-bit single precision float representation of a Number
  309. * @param value A Number. If the parameter is of a different type, it will get converted
  310. * to a number or to NaN if it cannot be converted
  311. * @returns number
  312. */
  313. public static FloatRound(value: number): number {
  314. if (Math.fround) {
  315. return Math.fround(value);
  316. }
  317. return (Tools._tmpFloatArray[0] = value);
  318. }
  319. /**
  320. * Find the next highest power of two.
  321. * @param x Number to start search from.
  322. * @return Next highest power of two.
  323. */
  324. public static CeilingPOT(x: number): number {
  325. x--;
  326. x |= x >> 1;
  327. x |= x >> 2;
  328. x |= x >> 4;
  329. x |= x >> 8;
  330. x |= x >> 16;
  331. x++;
  332. return x;
  333. }
  334. /**
  335. * Find the next lowest power of two.
  336. * @param x Number to start search from.
  337. * @return Next lowest power of two.
  338. */
  339. public static FloorPOT(x: number): number {
  340. x = x | (x >> 1);
  341. x = x | (x >> 2);
  342. x = x | (x >> 4);
  343. x = x | (x >> 8);
  344. x = x | (x >> 16);
  345. return x - (x >> 1);
  346. }
  347. /**
  348. * Find the nearest power of two.
  349. * @param x Number to start search from.
  350. * @return Next nearest power of two.
  351. */
  352. public static NearestPOT(x: number): number {
  353. var c = Tools.CeilingPOT(x);
  354. var f = Tools.FloorPOT(x);
  355. return (c - x) > (x - f) ? f : c;
  356. }
  357. /**
  358. * Get the closest exponent of two
  359. * @param value defines the value to approximate
  360. * @param max defines the maximum value to return
  361. * @param mode defines how to define the closest value
  362. * @returns closest exponent of two of the given value
  363. */
  364. public static GetExponentOfTwo(value: number, max: number, mode = Constants.SCALEMODE_NEAREST): number {
  365. let pot;
  366. switch (mode) {
  367. case Constants.SCALEMODE_FLOOR:
  368. pot = Tools.FloorPOT(value);
  369. break;
  370. case Constants.SCALEMODE_NEAREST:
  371. pot = Tools.NearestPOT(value);
  372. break;
  373. case Constants.SCALEMODE_CEILING:
  374. default:
  375. pot = Tools.CeilingPOT(value);
  376. break;
  377. }
  378. return Math.min(pot, max);
  379. }
  380. /**
  381. * Extracts the filename from a path
  382. * @param path defines the path to use
  383. * @returns the filename
  384. */
  385. public static GetFilename(path: string): string {
  386. var index = path.lastIndexOf("/");
  387. if (index < 0) {
  388. return path;
  389. }
  390. return path.substring(index + 1);
  391. }
  392. /**
  393. * Extracts the "folder" part of a path (everything before the filename).
  394. * @param uri The URI to extract the info from
  395. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  396. * @returns The "folder" part of the path
  397. */
  398. public static GetFolderPath(uri: string, returnUnchangedIfNoSlash = false): string {
  399. var index = uri.lastIndexOf("/");
  400. if (index < 0) {
  401. if (returnUnchangedIfNoSlash) {
  402. return uri;
  403. }
  404. return "";
  405. }
  406. return uri.substring(0, index + 1);
  407. }
  408. /**
  409. * Extracts text content from a DOM element hierarchy
  410. * Back Compat only, please use DomManagement.GetDOMTextContent instead.
  411. */
  412. public static GetDOMTextContent = DomManagement.GetDOMTextContent;
  413. /**
  414. * Convert an angle in radians to degrees
  415. * @param angle defines the angle to convert
  416. * @returns the angle in degrees
  417. */
  418. public static ToDegrees(angle: number): number {
  419. return angle * 180 / Math.PI;
  420. }
  421. /**
  422. * Convert an angle in degrees to radians
  423. * @param angle defines the angle to convert
  424. * @returns the angle in radians
  425. */
  426. public static ToRadians(angle: number): number {
  427. return angle * Math.PI / 180;
  428. }
  429. /**
  430. * Encode a buffer to a base64 string
  431. * @param buffer defines the buffer to encode
  432. * @returns the encoded string
  433. */
  434. public static EncodeArrayBufferTobase64(buffer: ArrayBuffer): string {
  435. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  436. var output = "";
  437. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  438. var i = 0;
  439. var bytes = new Uint8Array(buffer);
  440. while (i < bytes.length) {
  441. chr1 = bytes[i++];
  442. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  443. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  444. enc1 = chr1 >> 2;
  445. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  446. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  447. enc4 = chr3 & 63;
  448. if (isNaN(chr2)) {
  449. enc3 = enc4 = 64;
  450. } else if (isNaN(chr3)) {
  451. enc4 = 64;
  452. }
  453. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  454. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  455. }
  456. return "data:image/png;base64," + output;
  457. }
  458. /**
  459. * Extracts minimum and maximum values from a list of indexed positions
  460. * @param positions defines the positions to use
  461. * @param indices defines the indices to the positions
  462. * @param indexStart defines the start index
  463. * @param indexCount defines the end index
  464. * @param bias defines bias value to add to the result
  465. * @return minimum and maximum values
  466. */
  467. public static ExtractMinAndMaxIndexed(positions: FloatArray, indices: IndicesArray, indexStart: number, indexCount: number, bias: Nullable<Vector2> = null): { minimum: Vector3; maximum: Vector3 } {
  468. var minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  469. var maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  470. for (var index = indexStart; index < indexStart + indexCount; index++) {
  471. const offset = indices[index] * 3;
  472. const x = positions[offset];
  473. const y = positions[offset + 1];
  474. const z = positions[offset + 2];
  475. minimum.minimizeInPlaceFromFloats(x, y, z);
  476. maximum.maximizeInPlaceFromFloats(x, y, z);
  477. }
  478. if (bias) {
  479. minimum.x -= minimum.x * bias.x + bias.y;
  480. minimum.y -= minimum.y * bias.x + bias.y;
  481. minimum.z -= minimum.z * bias.x + bias.y;
  482. maximum.x += maximum.x * bias.x + bias.y;
  483. maximum.y += maximum.y * bias.x + bias.y;
  484. maximum.z += maximum.z * bias.x + bias.y;
  485. }
  486. return {
  487. minimum: minimum,
  488. maximum: maximum
  489. };
  490. }
  491. /**
  492. * Extracts minimum and maximum values from a list of positions
  493. * @param positions defines the positions to use
  494. * @param start defines the start index in the positions array
  495. * @param count defines the number of positions to handle
  496. * @param bias defines bias value to add to the result
  497. * @param stride defines the stride size to use (distance between two positions in the positions array)
  498. * @return minimum and maximum values
  499. */
  500. public static ExtractMinAndMax(positions: FloatArray, start: number, count: number, bias: Nullable<Vector2> = null, stride?: number): { minimum: Vector3; maximum: Vector3 } {
  501. var minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  502. var maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  503. if (!stride) {
  504. stride = 3;
  505. }
  506. for (var index = start, offset = start * stride; index < start + count; index++ , offset += stride) {
  507. const x = positions[offset];
  508. const y = positions[offset + 1];
  509. const z = positions[offset + 2];
  510. minimum.minimizeInPlaceFromFloats(x, y, z);
  511. maximum.maximizeInPlaceFromFloats(x, y, z);
  512. }
  513. if (bias) {
  514. minimum.x -= minimum.x * bias.x + bias.y;
  515. minimum.y -= minimum.y * bias.x + bias.y;
  516. minimum.z -= minimum.z * bias.x + bias.y;
  517. maximum.x += maximum.x * bias.x + bias.y;
  518. maximum.y += maximum.y * bias.x + bias.y;
  519. maximum.z += maximum.z * bias.x + bias.y;
  520. }
  521. return {
  522. minimum: minimum,
  523. maximum: maximum
  524. };
  525. }
  526. /**
  527. * Returns an array if obj is not an array
  528. * @param obj defines the object to evaluate as an array
  529. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  530. * @returns either obj directly if obj is an array or a new array containing obj
  531. */
  532. public static MakeArray(obj: any, allowsNullUndefined?: boolean): Nullable<Array<any>> {
  533. if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
  534. return null;
  535. }
  536. return Array.isArray(obj) ? obj : [obj];
  537. }
  538. /**
  539. * Gets the pointer prefix to use
  540. * @returns "pointer" if touch is enabled. Else returns "mouse"
  541. */
  542. public static GetPointerPrefix(): string {
  543. var eventPrefix = "pointer";
  544. // Check if pointer events are supported
  545. if (DomManagement.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  546. eventPrefix = "mouse";
  547. }
  548. return eventPrefix;
  549. }
  550. /**
  551. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  552. * @param func - the function to be called
  553. * @param requester - the object that will request the next frame. Falls back to window.
  554. * @returns frame number
  555. */
  556. public static QueueNewFrame(func: () => void, requester?: any): number {
  557. if (!DomManagement.IsWindowObjectExist()) {
  558. return setTimeout(func, 16);
  559. }
  560. if (!requester) {
  561. requester = window;
  562. }
  563. if (requester.requestAnimationFrame) {
  564. return requester.requestAnimationFrame(func);
  565. }
  566. else if (requester.msRequestAnimationFrame) {
  567. return requester.msRequestAnimationFrame(func);
  568. }
  569. else if (requester.webkitRequestAnimationFrame) {
  570. return requester.webkitRequestAnimationFrame(func);
  571. }
  572. else if (requester.mozRequestAnimationFrame) {
  573. return requester.mozRequestAnimationFrame(func);
  574. }
  575. else if (requester.oRequestAnimationFrame) {
  576. return requester.oRequestAnimationFrame(func);
  577. }
  578. else {
  579. return window.setTimeout(func, 16);
  580. }
  581. }
  582. /**
  583. * Ask the browser to promote the current element to fullscreen rendering mode
  584. * @param element defines the DOM element to promote
  585. */
  586. public static RequestFullscreen(element: HTMLElement): void {
  587. var requestFunction = element.requestFullscreen || (<any>element).msRequestFullscreen || (<any>element).webkitRequestFullscreen || (<any>element).mozRequestFullScreen;
  588. if (!requestFunction) { return; }
  589. requestFunction.call(element);
  590. }
  591. /**
  592. * Asks the browser to exit fullscreen mode
  593. */
  594. public static ExitFullscreen(): void {
  595. if (document.exitFullscreen) {
  596. document.exitFullscreen();
  597. }
  598. else if (document.mozCancelFullScreen) {
  599. document.mozCancelFullScreen();
  600. }
  601. else if (document.webkitCancelFullScreen) {
  602. document.webkitCancelFullScreen();
  603. }
  604. else if (document.msCancelFullScreen) {
  605. document.msCancelFullScreen();
  606. }
  607. }
  608. /**
  609. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  610. * @param url define the url we are trying
  611. * @param element define the dom element where to configure the cors policy
  612. */
  613. public static SetCorsBehavior(url: string | string[], element: { crossOrigin: string | null }): void {
  614. if (url && url.indexOf("data:") === 0) {
  615. return;
  616. }
  617. if (Tools.CorsBehavior) {
  618. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  619. element.crossOrigin = <string>Tools.CorsBehavior;
  620. }
  621. else {
  622. var result = Tools.CorsBehavior(url);
  623. if (result) {
  624. element.crossOrigin = result;
  625. }
  626. }
  627. }
  628. }
  629. // External files
  630. /**
  631. * Removes unwanted characters from an url
  632. * @param url defines the url to clean
  633. * @returns the cleaned url
  634. */
  635. public static CleanUrl(url: string): string {
  636. url = url.replace(/#/mg, "%23");
  637. return url;
  638. }
  639. /**
  640. * Gets or sets a function used to pre-process url before using them to load assets
  641. */
  642. public static PreprocessUrl = (url: string) => {
  643. return url;
  644. }
  645. /**
  646. * Loads an image as an HTMLImageElement.
  647. * @param input url string, ArrayBuffer, or Blob to load
  648. * @param onLoad callback called when the image successfully loads
  649. * @param onError callback called when the image fails to load
  650. * @param offlineProvider offline provider for caching
  651. * @returns the HTMLImageElement of the loaded image
  652. */
  653. public static LoadImage(input: string | ArrayBuffer | Blob, onLoad: (img: HTMLImageElement) => void, onError: (message?: string, exception?: any) => void, offlineProvider: Nullable<IOfflineProvider>): HTMLImageElement {
  654. let url: string;
  655. let usingObjectURL = false;
  656. if (input instanceof ArrayBuffer) {
  657. url = URL.createObjectURL(new Blob([input]));
  658. usingObjectURL = true;
  659. }
  660. else if (input instanceof Blob) {
  661. url = URL.createObjectURL(input);
  662. usingObjectURL = true;
  663. }
  664. else {
  665. url = Tools.CleanUrl(input);
  666. url = Tools.PreprocessUrl(input);
  667. }
  668. var img = new Image();
  669. Tools.SetCorsBehavior(url, img);
  670. const loadHandler = () => {
  671. if (usingObjectURL && img.src) {
  672. URL.revokeObjectURL(img.src);
  673. }
  674. img.removeEventListener("load", loadHandler);
  675. img.removeEventListener("error", errorHandler);
  676. onLoad(img);
  677. };
  678. const errorHandler = (err: any) => {
  679. if (usingObjectURL && img.src) {
  680. URL.revokeObjectURL(img.src);
  681. }
  682. img.removeEventListener("load", loadHandler);
  683. img.removeEventListener("error", errorHandler);
  684. Logger.Error("Error while trying to load image: " + input);
  685. if (onError) {
  686. onError("Error while trying to load image: " + input, err);
  687. }
  688. };
  689. img.addEventListener("load", loadHandler);
  690. img.addEventListener("error", errorHandler);
  691. var noOfflineSupport = () => {
  692. img.src = url;
  693. };
  694. var loadFromOfflineSupport = () => {
  695. if (offlineProvider) {
  696. offlineProvider.loadImage(url, img);
  697. }
  698. };
  699. if (url.substr(0, 5) !== "data:" && offlineProvider && offlineProvider.enableTexturesOffline) {
  700. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);
  701. }
  702. else {
  703. if (url.indexOf("file:") !== -1) {
  704. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  705. if (FilesInputStore.FilesToLoad[textureName]) {
  706. try {
  707. var blobURL;
  708. try {
  709. blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]);
  710. }
  711. catch (ex) {
  712. // Chrome doesn't support oneTimeOnly parameter
  713. blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]);
  714. }
  715. img.src = blobURL;
  716. usingObjectURL = true;
  717. }
  718. catch (e) {
  719. img.src = "";
  720. }
  721. return img;
  722. }
  723. }
  724. noOfflineSupport();
  725. }
  726. return img;
  727. }
  728. /**
  729. * Loads a file
  730. * @param url url string, ArrayBuffer, or Blob to load
  731. * @param onSuccess callback called when the file successfully loads
  732. * @param onProgress callback called while file is loading (if the server supports this mode)
  733. * @param offlineProvider defines the offline provider for caching
  734. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  735. * @param onError callback called when the file fails to load
  736. * @returns a file request object
  737. */
  738. public static LoadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, offlineProvider?: IOfflineProvider, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  739. url = Tools.CleanUrl(url);
  740. url = Tools.PreprocessUrl(url);
  741. // If file and file input are set
  742. if (url.indexOf("file:") !== -1) {
  743. const fileName = decodeURIComponent(url.substring(5).toLowerCase());
  744. if (FilesInputStore.FilesToLoad[fileName]) {
  745. return Tools.ReadFile(FilesInputStore.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  746. }
  747. }
  748. const loadUrl = Tools.BaseUrl + url;
  749. let aborted = false;
  750. const fileRequest: IFileRequest = {
  751. onCompleteObservable: new Observable<IFileRequest>(),
  752. abort: () => aborted = true,
  753. };
  754. const requestFile = () => {
  755. let request = new XMLHttpRequest();
  756. let retryHandle: Nullable<number> = null;
  757. fileRequest.abort = () => {
  758. aborted = true;
  759. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  760. request.abort();
  761. }
  762. if (retryHandle !== null) {
  763. clearTimeout(retryHandle);
  764. retryHandle = null;
  765. }
  766. };
  767. const retryLoop = (retryIndex: number) => {
  768. request.open('GET', loadUrl, true);
  769. if (useArrayBuffer) {
  770. request.responseType = "arraybuffer";
  771. }
  772. if (onProgress) {
  773. request.addEventListener("progress", onProgress);
  774. }
  775. const onLoadEnd = () => {
  776. request.removeEventListener("loadend", onLoadEnd);
  777. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  778. fileRequest.onCompleteObservable.clear();
  779. };
  780. request.addEventListener("loadend", onLoadEnd);
  781. const onReadyStateChange = () => {
  782. if (aborted) {
  783. return;
  784. }
  785. // In case of undefined state in some browsers.
  786. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  787. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  788. request.removeEventListener("readystatechange", onReadyStateChange);
  789. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!DomManagement.IsWindowObjectExist() || Tools.IsFileURL()))) {
  790. onSuccess(!useArrayBuffer ? request.responseText : <ArrayBuffer>request.response, request.responseURL);
  791. return;
  792. }
  793. let retryStrategy = Tools.DefaultRetryStrategy;
  794. if (retryStrategy) {
  795. let waitTime = retryStrategy(loadUrl, request, retryIndex);
  796. if (waitTime !== -1) {
  797. // Prevent the request from completing for retry.
  798. request.removeEventListener("loadend", onLoadEnd);
  799. request = new XMLHttpRequest();
  800. retryHandle = setTimeout(() => retryLoop(retryIndex + 1), waitTime);
  801. return;
  802. }
  803. }
  804. let e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  805. if (onError) {
  806. onError(request, e);
  807. } else {
  808. throw e;
  809. }
  810. }
  811. };
  812. request.addEventListener("readystatechange", onReadyStateChange);
  813. if (Tools.UseCustomRequestHeaders) {
  814. Tools.InjectCustomRequestHeaders(request);
  815. }
  816. request.send();
  817. };
  818. retryLoop(0);
  819. };
  820. // Caching all files
  821. if (offlineProvider && offlineProvider.enableSceneOffline) {
  822. const noOfflineSupport = (request?: any) => {
  823. if (request && request.status > 400) {
  824. if (onError) {
  825. onError(request);
  826. }
  827. } else {
  828. if (!aborted) {
  829. requestFile();
  830. }
  831. }
  832. };
  833. const loadFromOfflineSupport = () => {
  834. // TODO: database needs to support aborting and should return a IFileRequest
  835. if (aborted) {
  836. return;
  837. }
  838. if (offlineProvider) {
  839. offlineProvider.loadFile(url, (data) => {
  840. if (!aborted) {
  841. onSuccess(data);
  842. }
  843. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  844. }, onProgress ? (event) => {
  845. if (!aborted) {
  846. onProgress(event);
  847. }
  848. } : undefined, noOfflineSupport, useArrayBuffer);
  849. }
  850. };
  851. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);
  852. }
  853. else {
  854. requestFile();
  855. }
  856. return fileRequest;
  857. }
  858. /**
  859. * Load a script (identified by an url). When the url returns, the
  860. * content of this file is added into a new script element, attached to the DOM (body element)
  861. * @param scriptUrl defines the url of the script to laod
  862. * @param onSuccess defines the callback called when the script is loaded
  863. * @param onError defines the callback to call if an error occurs
  864. */
  865. public static LoadScript(scriptUrl: string, onSuccess: () => void, onError?: (message?: string, exception?: any) => void) {
  866. if (!DomManagement.IsWindowObjectExist()) {
  867. return;
  868. }
  869. var head = document.getElementsByTagName('head')[0];
  870. var script = document.createElement('script');
  871. script.type = 'text/javascript';
  872. script.src = scriptUrl;
  873. script.onload = () => {
  874. if (onSuccess) {
  875. onSuccess();
  876. }
  877. };
  878. script.onerror = (e) => {
  879. if (onError) {
  880. onError(`Unable to load script '${scriptUrl}'`, e);
  881. }
  882. };
  883. head.appendChild(script);
  884. }
  885. /**
  886. * Loads a file from a blob
  887. * @param fileToLoad defines the blob to use
  888. * @param callback defines the callback to call when data is loaded
  889. * @param progressCallback defines the callback to call during loading process
  890. * @returns a file request object
  891. */
  892. public static ReadFileAsDataURL(fileToLoad: Blob, callback: (data: any) => void, progressCallback: (ev: ProgressEvent) => any): IFileRequest {
  893. let reader = new FileReader();
  894. let request: IFileRequest = {
  895. onCompleteObservable: new Observable<IFileRequest>(),
  896. abort: () => reader.abort(),
  897. };
  898. reader.onloadend = (e) => {
  899. request.onCompleteObservable.notifyObservers(request);
  900. };
  901. reader.onload = (e) => {
  902. //target doesn't have result from ts 1.3
  903. callback((<any>e.target)['result']);
  904. };
  905. reader.onprogress = progressCallback;
  906. reader.readAsDataURL(fileToLoad);
  907. return request;
  908. }
  909. /**
  910. * Loads a file
  911. * @param fileToLoad defines the file to load
  912. * @param callback defines the callback to call when data is loaded
  913. * @param progressCallBack defines the callback to call during loading process
  914. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  915. * @returns a file request object
  916. */
  917. public static ReadFile(fileToLoad: File, callback: (data: any) => void, progressCallBack?: (ev: ProgressEvent) => any, useArrayBuffer?: boolean): IFileRequest {
  918. let reader = new FileReader();
  919. let request: IFileRequest = {
  920. onCompleteObservable: new Observable<IFileRequest>(),
  921. abort: () => reader.abort(),
  922. };
  923. reader.onloadend = (e) => request.onCompleteObservable.notifyObservers(request);
  924. reader.onerror = (e) => {
  925. Logger.Log("Error while reading file: " + fileToLoad.name);
  926. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  927. };
  928. reader.onload = (e) => {
  929. //target doesn't have result from ts 1.3
  930. callback((<any>e.target)['result']);
  931. };
  932. if (progressCallBack) {
  933. reader.onprogress = progressCallBack;
  934. }
  935. if (!useArrayBuffer) {
  936. // Asynchronous read
  937. reader.readAsText(fileToLoad);
  938. }
  939. else {
  940. reader.readAsArrayBuffer(fileToLoad);
  941. }
  942. return request;
  943. }
  944. /**
  945. * Creates a data url from a given string content
  946. * @param content defines the content to convert
  947. * @returns the new data url link
  948. */
  949. public static FileAsURL(content: string): string {
  950. var fileBlob = new Blob([content]);
  951. var url = window.URL || window.webkitURL;
  952. var link: string = url.createObjectURL(fileBlob);
  953. return link;
  954. }
  955. /**
  956. * Format the given number to a specific decimal format
  957. * @param value defines the number to format
  958. * @param decimals defines the number of decimals to use
  959. * @returns the formatted string
  960. */
  961. public static Format(value: number, decimals: number = 2): string {
  962. return value.toFixed(decimals);
  963. }
  964. /**
  965. * Checks if a given vector is inside a specific range
  966. * @param v defines the vector to test
  967. * @param min defines the minimum range
  968. * @param max defines the maximum range
  969. */
  970. public static CheckExtends(v: Vector3, min: Vector3, max: Vector3): void {
  971. min.minimizeInPlace(v);
  972. max.maximizeInPlace(v);
  973. }
  974. /**
  975. * Tries to copy an object by duplicating every property
  976. * @param source defines the source object
  977. * @param destination defines the target object
  978. * @param doNotCopyList defines a list of properties to avoid
  979. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  980. */
  981. public static DeepCopy(source: any, destination: any, doNotCopyList?: string[], mustCopyList?: string[]): void {
  982. DeepCopier.DeepCopy(source, destination, doNotCopyList, mustCopyList);
  983. }
  984. /**
  985. * Gets a boolean indicating if the given object has no own property
  986. * @param obj defines the object to test
  987. * @returns true if object has no own property
  988. */
  989. public static IsEmpty(obj: any): boolean {
  990. for (var i in obj) {
  991. if (obj.hasOwnProperty(i)) {
  992. return false;
  993. }
  994. }
  995. return true;
  996. }
  997. /**
  998. * Function used to register events at window level
  999. * @param events defines the events to register
  1000. */
  1001. public static RegisterTopRootEvents(events: { name: string; handler: Nullable<(e: FocusEvent) => any> }[]): void {
  1002. for (var index = 0; index < events.length; index++) {
  1003. var event = events[index];
  1004. window.addEventListener(event.name, <any>event.handler, false);
  1005. try {
  1006. if (window.parent) {
  1007. window.parent.addEventListener(event.name, <any>event.handler, false);
  1008. }
  1009. } catch (e) {
  1010. // Silently fails...
  1011. }
  1012. }
  1013. }
  1014. /**
  1015. * Function used to unregister events from window level
  1016. * @param events defines the events to unregister
  1017. */
  1018. public static UnregisterTopRootEvents(events: { name: string; handler: Nullable<(e: FocusEvent) => any> }[]): void {
  1019. for (var index = 0; index < events.length; index++) {
  1020. var event = events[index];
  1021. window.removeEventListener(event.name, <any>event.handler);
  1022. try {
  1023. if (window.parent) {
  1024. window.parent.removeEventListener(event.name, <any>event.handler);
  1025. }
  1026. } catch (e) {
  1027. // Silently fails...
  1028. }
  1029. }
  1030. }
  1031. public static _ScreenshotCanvas: HTMLCanvasElement;
  1032. /**
  1033. * Dumps the current bound framebuffer
  1034. * @param width defines the rendering width
  1035. * @param height defines the rendering height
  1036. * @param engine defines the hosting engine
  1037. * @param successCallback defines the callback triggered once the data are available
  1038. * @param mimeType defines the mime type of the result
  1039. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  1040. */
  1041. public static DumpFramebuffer(width: number, height: number, engine: Engine, successCallback?: (data: string) => void, mimeType: string = "image/png", fileName?: string): void {
  1042. // Read the contents of the framebuffer
  1043. var numberOfChannelsByLine = width * 4;
  1044. var halfHeight = height / 2;
  1045. //Reading datas from WebGL
  1046. var data = engine.readPixels(0, 0, width, height);
  1047. //To flip image on Y axis.
  1048. for (var i = 0; i < halfHeight; i++) {
  1049. for (var j = 0; j < numberOfChannelsByLine; j++) {
  1050. var currentCell = j + i * numberOfChannelsByLine;
  1051. var targetLine = height - i - 1;
  1052. var targetCell = j + targetLine * numberOfChannelsByLine;
  1053. var temp = data[currentCell];
  1054. data[currentCell] = data[targetCell];
  1055. data[targetCell] = temp;
  1056. }
  1057. }
  1058. // Create a 2D canvas to store the result
  1059. if (!Tools._ScreenshotCanvas) {
  1060. Tools._ScreenshotCanvas = document.createElement('canvas');
  1061. }
  1062. Tools._ScreenshotCanvas.width = width;
  1063. Tools._ScreenshotCanvas.height = height;
  1064. var context = Tools._ScreenshotCanvas.getContext('2d');
  1065. if (context) {
  1066. // Copy the pixels to a 2D canvas
  1067. var imageData = context.createImageData(width, height);
  1068. var castData = <any>(imageData.data);
  1069. castData.set(data);
  1070. context.putImageData(imageData, 0, 0);
  1071. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  1072. }
  1073. }
  1074. /**
  1075. * Converts the canvas data to blob.
  1076. * This acts as a polyfill for browsers not supporting the to blob function.
  1077. * @param canvas Defines the canvas to extract the data from
  1078. * @param successCallback Defines the callback triggered once the data are available
  1079. * @param mimeType Defines the mime type of the result
  1080. */
  1081. static ToBlob(canvas: HTMLCanvasElement, successCallback: (blob: Nullable<Blob>) => void, mimeType: string = "image/png"): void {
  1082. // We need HTMLCanvasElement.toBlob for HD screenshots
  1083. if (!canvas.toBlob) {
  1084. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  1085. canvas.toBlob = function(callback, type, quality) {
  1086. setTimeout(() => {
  1087. var binStr = atob(this.toDataURL(type, quality).split(',')[1]),
  1088. len = binStr.length,
  1089. arr = new Uint8Array(len);
  1090. for (var i = 0; i < len; i++) {
  1091. arr[i] = binStr.charCodeAt(i);
  1092. }
  1093. callback(new Blob([arr]));
  1094. });
  1095. };
  1096. }
  1097. canvas.toBlob(function(blob) {
  1098. successCallback(blob);
  1099. }, mimeType);
  1100. }
  1101. /**
  1102. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  1103. * @param successCallback defines the callback triggered once the data are available
  1104. * @param mimeType defines the mime type of the result
  1105. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  1106. */
  1107. static EncodeScreenshotCanvasData(successCallback?: (data: string) => void, mimeType: string = "image/png", fileName?: string): void {
  1108. if (successCallback) {
  1109. var base64Image = Tools._ScreenshotCanvas.toDataURL(mimeType);
  1110. successCallback(base64Image);
  1111. }
  1112. else {
  1113. this.ToBlob(Tools._ScreenshotCanvas, function(blob) {
  1114. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  1115. if (("download" in document.createElement("a"))) {
  1116. if (!fileName) {
  1117. var date = new Date();
  1118. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  1119. fileName = "screenshot_" + stringDate + ".png";
  1120. }
  1121. Tools.Download(blob!, fileName);
  1122. }
  1123. else {
  1124. var url = URL.createObjectURL(blob);
  1125. var newWindow = window.open("");
  1126. if (!newWindow) { return; }
  1127. var img = newWindow.document.createElement("img");
  1128. img.onload = function() {
  1129. // no longer need to read the blob so it's revoked
  1130. URL.revokeObjectURL(url);
  1131. };
  1132. img.src = url;
  1133. newWindow.document.body.appendChild(img);
  1134. }
  1135. }, mimeType);
  1136. }
  1137. }
  1138. /**
  1139. * Downloads a blob in the browser
  1140. * @param blob defines the blob to download
  1141. * @param fileName defines the name of the downloaded file
  1142. */
  1143. public static Download(blob: Blob, fileName: string): void {
  1144. if (navigator && navigator.msSaveBlob) {
  1145. navigator.msSaveBlob(blob, fileName);
  1146. return;
  1147. }
  1148. var url = window.URL.createObjectURL(blob);
  1149. var a = document.createElement("a");
  1150. document.body.appendChild(a);
  1151. a.style.display = "none";
  1152. a.href = url;
  1153. a.download = fileName;
  1154. a.addEventListener("click", () => {
  1155. if (a.parentElement) {
  1156. a.parentElement.removeChild(a);
  1157. }
  1158. });
  1159. a.click();
  1160. window.URL.revokeObjectURL(url);
  1161. }
  1162. /**
  1163. * Captures a screenshot of the current rendering
  1164. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  1165. * @param engine defines the rendering engine
  1166. * @param camera defines the source camera
  1167. * @param size This parameter can be set to a single number or to an object with the
  1168. * following (optional) properties: precision, width, height. If a single number is passed,
  1169. * it will be used for both width and height. If an object is passed, the screenshot size
  1170. * will be derived from the parameters. The precision property is a multiplier allowing
  1171. * rendering at a higher or lower resolution
  1172. * @param successCallback defines the callback receives a single parameter which contains the
  1173. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  1174. * src parameter of an <img> to display it
  1175. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  1176. * Check your browser for supported MIME types
  1177. */
  1178. public static CreateScreenshot(engine: Engine, camera: Camera, size: any, successCallback?: (data: string) => void, mimeType: string = "image/png"): void {
  1179. throw _DevTools.WarnImport("ScreenshotTools");
  1180. }
  1181. /**
  1182. * Generates an image screenshot from the specified camera.
  1183. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  1184. * @param engine The engine to use for rendering
  1185. * @param camera The camera to use for rendering
  1186. * @param size This parameter can be set to a single number or to an object with the
  1187. * following (optional) properties: precision, width, height. If a single number is passed,
  1188. * it will be used for both width and height. If an object is passed, the screenshot size
  1189. * will be derived from the parameters. The precision property is a multiplier allowing
  1190. * rendering at a higher or lower resolution
  1191. * @param successCallback The callback receives a single parameter which contains the
  1192. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  1193. * src parameter of an <img> to display it
  1194. * @param mimeType The MIME type of the screenshot image (default: image/png).
  1195. * Check your browser for supported MIME types
  1196. * @param samples Texture samples (default: 1)
  1197. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  1198. * @param fileName A name for for the downloaded file.
  1199. */
  1200. public static CreateScreenshotUsingRenderTarget(engine: Engine, camera: Camera, size: any, successCallback?: (data: string) => void, mimeType: string = "image/png", samples: number = 1, antialiasing: boolean = false, fileName?: string): void {
  1201. throw _DevTools.WarnImport("ScreenshotTools");
  1202. }
  1203. /**
  1204. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  1205. * Be aware Math.random() could cause collisions, but:
  1206. * "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"
  1207. * @returns a pseudo random id
  1208. */
  1209. public static RandomId(): string {
  1210. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
  1211. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  1212. return v.toString(16);
  1213. });
  1214. }
  1215. /**
  1216. * Test if the given uri is a base64 string
  1217. * @param uri The uri to test
  1218. * @return True if the uri is a base64 string or false otherwise
  1219. */
  1220. public static IsBase64(uri: string): boolean {
  1221. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1222. }
  1223. /**
  1224. * Decode the given base64 uri.
  1225. * @param uri The uri to decode
  1226. * @return The decoded base64 data.
  1227. */
  1228. public static DecodeBase64(uri: string): ArrayBuffer {
  1229. const decodedString = atob(uri.split(",")[1]);
  1230. const bufferLength = decodedString.length;
  1231. const bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1232. for (let i = 0; i < bufferLength; i++) {
  1233. bufferView[i] = decodedString.charCodeAt(i);
  1234. }
  1235. return bufferView.buffer;
  1236. }
  1237. // Logs
  1238. /**
  1239. * No log
  1240. */
  1241. public static readonly NoneLogLevel = Logger.NoneLogLevel;
  1242. /**
  1243. * Only message logs
  1244. */
  1245. public static readonly MessageLogLevel = Logger.MessageLogLevel;
  1246. /**
  1247. * Only warning logs
  1248. */
  1249. public static readonly WarningLogLevel = Logger.WarningLogLevel;
  1250. /**
  1251. * Only error logs
  1252. */
  1253. public static readonly ErrorLogLevel = Logger.ErrorLogLevel;
  1254. /**
  1255. * All logs
  1256. */
  1257. public static readonly AllLogLevel = Logger.AllLogLevel;
  1258. /**
  1259. * Gets a value indicating the number of loading errors
  1260. * @ignorenaming
  1261. */
  1262. public static get errorsCount(): number {
  1263. return Logger.errorsCount;
  1264. }
  1265. /**
  1266. * Callback called when a new log is added
  1267. */
  1268. public static OnNewCacheEntry: (entry: string) => void;
  1269. /**
  1270. * Log a message to the console
  1271. * @param message defines the message to log
  1272. */
  1273. public static Log(message: string): void {
  1274. Logger.Log(message);
  1275. }
  1276. /**
  1277. * Write a warning message to the console
  1278. * @param message defines the message to log
  1279. */
  1280. public static Warn(message: string): void {
  1281. Logger.Warn(message);
  1282. }
  1283. /**
  1284. * Write an error message to the console
  1285. * @param message defines the message to log
  1286. */
  1287. public static Error(message: string): void {
  1288. Logger.Error(message);
  1289. }
  1290. /**
  1291. * Gets current log cache (list of logs)
  1292. */
  1293. public static get LogCache(): string {
  1294. return Logger.LogCache;
  1295. }
  1296. /**
  1297. * Clears the log cache
  1298. */
  1299. public static ClearLogCache(): void {
  1300. Logger.ClearLogCache();
  1301. }
  1302. /**
  1303. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  1304. */
  1305. public static set LogLevels(level: number) {
  1306. Logger.LogLevels = level;
  1307. }
  1308. /**
  1309. * Checks if the loaded document was accessed via `file:`-Protocol.
  1310. * @returns boolean
  1311. */
  1312. public static IsFileURL(): boolean {
  1313. return location.protocol === "file:";
  1314. }
  1315. /**
  1316. * Checks if the window object exists
  1317. * Back Compat only, please use DomManagement.IsWindowObjectExist instead.
  1318. */
  1319. public static IsWindowObjectExist = DomManagement.IsWindowObjectExist;
  1320. // Performances
  1321. /**
  1322. * No performance log
  1323. */
  1324. public static readonly PerformanceNoneLogLevel = 0;
  1325. /**
  1326. * Use user marks to log performance
  1327. */
  1328. public static readonly PerformanceUserMarkLogLevel = 1;
  1329. /**
  1330. * Log performance to the console
  1331. */
  1332. public static readonly PerformanceConsoleLogLevel = 2;
  1333. private static _performance: Performance;
  1334. /**
  1335. * Sets the current performance log level
  1336. */
  1337. public static set PerformanceLogLevel(level: number) {
  1338. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  1339. Tools.StartPerformanceCounter = Tools._StartUserMark;
  1340. Tools.EndPerformanceCounter = Tools._EndUserMark;
  1341. return;
  1342. }
  1343. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  1344. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  1345. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  1346. return;
  1347. }
  1348. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  1349. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  1350. }
  1351. private static _StartPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  1352. }
  1353. private static _EndPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  1354. }
  1355. private static _StartUserMark(counterName: string, condition = true): void {
  1356. if (!Tools._performance) {
  1357. if (!DomManagement.IsWindowObjectExist()) {
  1358. return;
  1359. }
  1360. Tools._performance = window.performance;
  1361. }
  1362. if (!condition || !Tools._performance.mark) {
  1363. return;
  1364. }
  1365. Tools._performance.mark(counterName + "-Begin");
  1366. }
  1367. private static _EndUserMark(counterName: string, condition = true): void {
  1368. if (!condition || !Tools._performance.mark) {
  1369. return;
  1370. }
  1371. Tools._performance.mark(counterName + "-End");
  1372. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  1373. }
  1374. private static _StartPerformanceConsole(counterName: string, condition = true): void {
  1375. if (!condition) {
  1376. return;
  1377. }
  1378. Tools._StartUserMark(counterName, condition);
  1379. if (console.time) {
  1380. console.time(counterName);
  1381. }
  1382. }
  1383. private static _EndPerformanceConsole(counterName: string, condition = true): void {
  1384. if (!condition) {
  1385. return;
  1386. }
  1387. Tools._EndUserMark(counterName, condition);
  1388. if (console.time) {
  1389. console.timeEnd(counterName);
  1390. }
  1391. }
  1392. /**
  1393. * Injects the @see CustomRequestHeaders into the given request
  1394. * @param request the request that should be used for injection
  1395. */
  1396. public static InjectCustomRequestHeaders(request: XMLHttpRequest): void {
  1397. for (let key in Tools.CustomRequestHeaders) {
  1398. const val = Tools.CustomRequestHeaders[key];
  1399. if (val) {
  1400. request.setRequestHeader(key, val);
  1401. }
  1402. }
  1403. }
  1404. /**
  1405. * Starts a performance counter
  1406. */
  1407. public static StartPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._StartPerformanceCounterDisabled;
  1408. /**
  1409. * Ends a specific performance coutner
  1410. */
  1411. public static EndPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._EndPerformanceCounterDisabled;
  1412. /**
  1413. * Gets either window.performance.now() if supported or Date.now() else
  1414. */
  1415. public static get Now(): number {
  1416. return PrecisionDate.Now;
  1417. }
  1418. /**
  1419. * This method will return the name of the class used to create the instance of the given object.
  1420. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  1421. * @param object the object to get the class name from
  1422. * @param isType defines if the object is actually a type
  1423. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  1424. */
  1425. public static GetClassName(object: any, isType: boolean = false): string {
  1426. let name = null;
  1427. if (!isType && object.getClassName) {
  1428. name = object.getClassName();
  1429. } else {
  1430. if (object instanceof Object) {
  1431. let classObj = isType ? object : Object.getPrototypeOf(object);
  1432. name = classObj.constructor["__bjsclassName__"];
  1433. }
  1434. if (!name) {
  1435. name = typeof object;
  1436. }
  1437. }
  1438. return name;
  1439. }
  1440. /**
  1441. * Gets the first element of an array satisfying a given predicate
  1442. * @param array defines the array to browse
  1443. * @param predicate defines the predicate to use
  1444. * @returns null if not found or the element
  1445. */
  1446. public static First<T>(array: Array<T>, predicate: (item: T) => boolean): Nullable<T> {
  1447. for (let el of array) {
  1448. if (predicate(el)) {
  1449. return el;
  1450. }
  1451. }
  1452. return null;
  1453. }
  1454. /**
  1455. * This method will return the name of the full name of the class, including its owning module (if any).
  1456. * 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).
  1457. * @param object the object to get the class name from
  1458. * @param isType defines if the object is actually a type
  1459. * @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.
  1460. * @ignorenaming
  1461. */
  1462. public static getFullClassName(object: any, isType: boolean = false): Nullable<string> {
  1463. let className = null;
  1464. let moduleName = null;
  1465. if (!isType && object.getClassName) {
  1466. className = object.getClassName();
  1467. } else {
  1468. if (object instanceof Object) {
  1469. let classObj = isType ? object : Object.getPrototypeOf(object);
  1470. className = classObj.constructor["__bjsclassName__"];
  1471. moduleName = classObj.constructor["__bjsmoduleName__"];
  1472. }
  1473. if (!className) {
  1474. className = typeof object;
  1475. }
  1476. }
  1477. if (!className) {
  1478. return null;
  1479. }
  1480. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  1481. }
  1482. /**
  1483. * Returns a promise that resolves after the given amount of time.
  1484. * @param delay Number of milliseconds to delay
  1485. * @returns Promise that resolves after the given amount of time
  1486. */
  1487. public static DelayAsync(delay: number): Promise<void> {
  1488. return new Promise((resolve) => {
  1489. setTimeout(() => {
  1490. resolve();
  1491. }, delay);
  1492. });
  1493. }
  1494. /**
  1495. * Gets the current gradient from an array of IValueGradient
  1496. * @param ratio defines the current ratio to get
  1497. * @param gradients defines the array of IValueGradient
  1498. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  1499. */
  1500. public static GetCurrentGradient(ratio: number, gradients: IValueGradient[], updateFunc: (current: IValueGradient, next: IValueGradient, scale: number) => void) {
  1501. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  1502. let currentGradient = gradients[gradientIndex];
  1503. let nextGradient = gradients[gradientIndex + 1];
  1504. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  1505. let scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  1506. updateFunc(currentGradient, nextGradient, scale);
  1507. return;
  1508. }
  1509. }
  1510. // Use last index if over
  1511. const lastIndex = gradients.length - 1;
  1512. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  1513. }
  1514. }
  1515. /**
  1516. * This class is used to track a performance counter which is number based.
  1517. * The user has access to many properties which give statistics of different nature.
  1518. *
  1519. * The implementer can track two kinds of Performance Counter: time and count.
  1520. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  1521. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  1522. */
  1523. export class PerfCounter {
  1524. /**
  1525. * Gets or sets a global boolean to turn on and off all the counters
  1526. */
  1527. public static Enabled = true;
  1528. /**
  1529. * Returns the smallest value ever
  1530. */
  1531. public get min(): number {
  1532. return this._min;
  1533. }
  1534. /**
  1535. * Returns the biggest value ever
  1536. */
  1537. public get max(): number {
  1538. return this._max;
  1539. }
  1540. /**
  1541. * Returns the average value since the performance counter is running
  1542. */
  1543. public get average(): number {
  1544. return this._average;
  1545. }
  1546. /**
  1547. * Returns the average value of the last second the counter was monitored
  1548. */
  1549. public get lastSecAverage(): number {
  1550. return this._lastSecAverage;
  1551. }
  1552. /**
  1553. * Returns the current value
  1554. */
  1555. public get current(): number {
  1556. return this._current;
  1557. }
  1558. /**
  1559. * Gets the accumulated total
  1560. */
  1561. public get total(): number {
  1562. return this._totalAccumulated;
  1563. }
  1564. /**
  1565. * Gets the total value count
  1566. */
  1567. public get count(): number {
  1568. return this._totalValueCount;
  1569. }
  1570. /**
  1571. * Creates a new counter
  1572. */
  1573. constructor() {
  1574. this._startMonitoringTime = 0;
  1575. this._min = 0;
  1576. this._max = 0;
  1577. this._average = 0;
  1578. this._lastSecAverage = 0;
  1579. this._current = 0;
  1580. this._totalValueCount = 0;
  1581. this._totalAccumulated = 0;
  1582. this._lastSecAccumulated = 0;
  1583. this._lastSecTime = 0;
  1584. this._lastSecValueCount = 0;
  1585. }
  1586. /**
  1587. * Call this method to start monitoring a new frame.
  1588. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  1589. */
  1590. public fetchNewFrame() {
  1591. this._totalValueCount++;
  1592. this._current = 0;
  1593. this._lastSecValueCount++;
  1594. }
  1595. /**
  1596. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  1597. * @param newCount the count value to add to the monitored count
  1598. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  1599. */
  1600. public addCount(newCount: number, fetchResult: boolean) {
  1601. if (!PerfCounter.Enabled) {
  1602. return;
  1603. }
  1604. this._current += newCount;
  1605. if (fetchResult) {
  1606. this._fetchResult();
  1607. }
  1608. }
  1609. /**
  1610. * Start monitoring this performance counter
  1611. */
  1612. public beginMonitoring() {
  1613. if (!PerfCounter.Enabled) {
  1614. return;
  1615. }
  1616. this._startMonitoringTime = PrecisionDate.Now;
  1617. }
  1618. /**
  1619. * Compute the time lapsed since the previous beginMonitoring() call.
  1620. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  1621. */
  1622. public endMonitoring(newFrame: boolean = true) {
  1623. if (!PerfCounter.Enabled) {
  1624. return;
  1625. }
  1626. if (newFrame) {
  1627. this.fetchNewFrame();
  1628. }
  1629. let currentTime = PrecisionDate.Now;
  1630. this._current = currentTime - this._startMonitoringTime;
  1631. if (newFrame) {
  1632. this._fetchResult();
  1633. }
  1634. }
  1635. private _fetchResult() {
  1636. this._totalAccumulated += this._current;
  1637. this._lastSecAccumulated += this._current;
  1638. // Min/Max update
  1639. this._min = Math.min(this._min, this._current);
  1640. this._max = Math.max(this._max, this._current);
  1641. this._average = this._totalAccumulated / this._totalValueCount;
  1642. // Reset last sec?
  1643. let now = PrecisionDate.Now;
  1644. if ((now - this._lastSecTime) > 1000) {
  1645. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  1646. this._lastSecTime = now;
  1647. this._lastSecAccumulated = 0;
  1648. this._lastSecValueCount = 0;
  1649. }
  1650. }
  1651. private _startMonitoringTime: number;
  1652. private _min: number;
  1653. private _max: number;
  1654. private _average: number;
  1655. private _current: number;
  1656. private _totalValueCount: number;
  1657. private _totalAccumulated: number;
  1658. private _lastSecAverage: number;
  1659. private _lastSecAccumulated: number;
  1660. private _lastSecTime: number;
  1661. private _lastSecValueCount: number;
  1662. }
  1663. /**
  1664. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  1665. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  1666. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  1667. * @param name The name of the class, case should be preserved
  1668. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  1669. */
  1670. export function className(name: string, module?: string): (target: Object) => void {
  1671. return (target: Object) => {
  1672. (<any>target)["__bjsclassName__"] = name;
  1673. (<any>target)["__bjsmoduleName__"] = (module != null) ? module : null;
  1674. };
  1675. }
  1676. /**
  1677. * An implementation of a loop for asynchronous functions.
  1678. */
  1679. export class AsyncLoop {
  1680. /**
  1681. * Defines the current index of the loop.
  1682. */
  1683. public index: number;
  1684. private _done: boolean;
  1685. private _fn: (asyncLoop: AsyncLoop) => void;
  1686. private _successCallback: () => void;
  1687. /**
  1688. * Constructor.
  1689. * @param iterations the number of iterations.
  1690. * @param func the function to run each iteration
  1691. * @param successCallback the callback that will be called upon succesful execution
  1692. * @param offset starting offset.
  1693. */
  1694. constructor(
  1695. /**
  1696. * Defines the number of iterations for the loop
  1697. */
  1698. public iterations: number,
  1699. func: (asyncLoop: AsyncLoop) => void,
  1700. successCallback: () => void,
  1701. offset: number = 0) {
  1702. this.index = offset - 1;
  1703. this._done = false;
  1704. this._fn = func;
  1705. this._successCallback = successCallback;
  1706. }
  1707. /**
  1708. * Execute the next iteration. Must be called after the last iteration was finished.
  1709. */
  1710. public executeNext(): void {
  1711. if (!this._done) {
  1712. if (this.index + 1 < this.iterations) {
  1713. ++this.index;
  1714. this._fn(this);
  1715. } else {
  1716. this.breakLoop();
  1717. }
  1718. }
  1719. }
  1720. /**
  1721. * Break the loop and run the success callback.
  1722. */
  1723. public breakLoop(): void {
  1724. this._done = true;
  1725. this._successCallback();
  1726. }
  1727. /**
  1728. * Create and run an async loop.
  1729. * @param iterations the number of iterations.
  1730. * @param fn the function to run each iteration
  1731. * @param successCallback the callback that will be called upon succesful execution
  1732. * @param offset starting offset.
  1733. * @returns the created async loop object
  1734. */
  1735. public static Run(iterations: number, fn: (asyncLoop: AsyncLoop) => void, successCallback: () => void, offset: number = 0): AsyncLoop {
  1736. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  1737. loop.executeNext();
  1738. return loop;
  1739. }
  1740. /**
  1741. * A for-loop that will run a given number of iterations synchronous and the rest async.
  1742. * @param iterations total number of iterations
  1743. * @param syncedIterations number of synchronous iterations in each async iteration.
  1744. * @param fn the function to call each iteration.
  1745. * @param callback a success call back that will be called when iterating stops.
  1746. * @param breakFunction a break condition (optional)
  1747. * @param timeout timeout settings for the setTimeout function. default - 0.
  1748. * @returns the created async loop object
  1749. */
  1750. public static SyncAsyncForLoop(iterations: number, syncedIterations: number, fn: (iteration: number) => void, callback: () => void, breakFunction?: () => boolean, timeout: number = 0): AsyncLoop {
  1751. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), (loop: AsyncLoop) => {
  1752. if (breakFunction && breakFunction()) { loop.breakLoop(); }
  1753. else {
  1754. setTimeout(() => {
  1755. for (var i = 0; i < syncedIterations; ++i) {
  1756. var iteration = (loop.index * syncedIterations) + i;
  1757. if (iteration >= iterations) { break; }
  1758. fn(iteration);
  1759. if (breakFunction && breakFunction()) {
  1760. loop.breakLoop();
  1761. break;
  1762. }
  1763. }
  1764. loop.executeNext();
  1765. }, timeout);
  1766. }
  1767. }, callback);
  1768. }
  1769. }