babylon.tools.ts 94 KB

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