babylon.glTF2FileLoader.js 188 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. /**
  5. * Mode that determines the coordinate system to use.
  6. */
  7. var GLTFLoaderCoordinateSystemMode;
  8. (function (GLTFLoaderCoordinateSystemMode) {
  9. /**
  10. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  11. */
  12. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  13. /**
  14. * Sets the useRightHandedSystem flag on the scene.
  15. */
  16. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  17. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  18. /**
  19. * Mode that determines what animations will start.
  20. */
  21. var GLTFLoaderAnimationStartMode;
  22. (function (GLTFLoaderAnimationStartMode) {
  23. /**
  24. * No animation will start.
  25. */
  26. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  27. /**
  28. * The first animation will start.
  29. */
  30. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  31. /**
  32. * All animations will start.
  33. */
  34. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  35. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  36. /**
  37. * Loader state.
  38. */
  39. var GLTFLoaderState;
  40. (function (GLTFLoaderState) {
  41. /**
  42. * The asset is loading.
  43. */
  44. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  45. /**
  46. * The asset is ready for rendering.
  47. */
  48. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  49. /**
  50. * The asset is completely loaded.
  51. */
  52. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  53. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  54. /**
  55. * File loader for loading glTF files into a scene.
  56. */
  57. var GLTFFileLoader = /** @class */ (function () {
  58. function GLTFFileLoader() {
  59. // #region Common options
  60. /**
  61. * Raised when the asset has been parsed
  62. */
  63. this.onParsedObservable = new BABYLON.Observable();
  64. // #endregion
  65. // #region V2 options
  66. /**
  67. * The coordinate system mode. Defaults to AUTO.
  68. */
  69. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  70. /**
  71. * The animation start mode. Defaults to FIRST.
  72. */
  73. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  74. /**
  75. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  76. */
  77. this.compileMaterials = false;
  78. /**
  79. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  80. */
  81. this.useClipPlane = false;
  82. /**
  83. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  84. */
  85. this.compileShadowGenerators = false;
  86. /**
  87. * Defines if the Alpha blended materials are only applied as coverage.
  88. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  89. * If true, no extra effects are applied to transparent pixels.
  90. */
  91. this.transparencyAsCoverage = false;
  92. /** @hidden */
  93. this._normalizeAnimationGroupsToBeginAtZero = true;
  94. /**
  95. * Function called before loading a url referenced by the asset.
  96. */
  97. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  98. /**
  99. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  100. */
  101. this.onMeshLoadedObservable = new BABYLON.Observable();
  102. /**
  103. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  104. */
  105. this.onTextureLoadedObservable = new BABYLON.Observable();
  106. /**
  107. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  108. */
  109. this.onMaterialLoadedObservable = new BABYLON.Observable();
  110. /**
  111. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  112. */
  113. this.onCameraLoadedObservable = new BABYLON.Observable();
  114. /**
  115. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  116. * For assets with LODs, raised when all of the LODs are complete.
  117. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  118. */
  119. this.onCompleteObservable = new BABYLON.Observable();
  120. /**
  121. * Observable raised when an error occurs.
  122. */
  123. this.onErrorObservable = new BABYLON.Observable();
  124. /**
  125. * Observable raised after the loader is disposed.
  126. */
  127. this.onDisposeObservable = new BABYLON.Observable();
  128. /**
  129. * Observable raised after a loader extension is created.
  130. * Set additional options for a loader extension in this event.
  131. */
  132. this.onExtensionLoadedObservable = new BABYLON.Observable();
  133. // #endregion
  134. this._loader = null;
  135. /**
  136. * Name of the loader ("gltf")
  137. */
  138. this.name = "gltf";
  139. /**
  140. * Supported file extensions of the loader (.gltf, .glb)
  141. */
  142. this.extensions = {
  143. ".gltf": { isBinary: false },
  144. ".glb": { isBinary: true }
  145. };
  146. this._logIndentLevel = 0;
  147. this._loggingEnabled = false;
  148. /** @hidden */
  149. this._log = this._logDisabled;
  150. this._capturePerformanceCounters = false;
  151. /** @hidden */
  152. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  153. /** @hidden */
  154. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  155. }
  156. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  157. /**
  158. * Raised when the asset has been parsed
  159. */
  160. set: function (callback) {
  161. if (this._onParsedObserver) {
  162. this.onParsedObservable.remove(this._onParsedObserver);
  163. }
  164. this._onParsedObserver = this.onParsedObservable.add(callback);
  165. },
  166. enumerable: true,
  167. configurable: true
  168. });
  169. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  170. /**
  171. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  172. */
  173. set: function (callback) {
  174. if (this._onMeshLoadedObserver) {
  175. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  176. }
  177. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  178. },
  179. enumerable: true,
  180. configurable: true
  181. });
  182. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  183. /**
  184. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  185. */
  186. set: function (callback) {
  187. if (this._onTextureLoadedObserver) {
  188. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  189. }
  190. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  191. },
  192. enumerable: true,
  193. configurable: true
  194. });
  195. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  196. /**
  197. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  198. */
  199. set: function (callback) {
  200. if (this._onMaterialLoadedObserver) {
  201. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  202. }
  203. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  204. },
  205. enumerable: true,
  206. configurable: true
  207. });
  208. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  209. /**
  210. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  211. */
  212. set: function (callback) {
  213. if (this._onCameraLoadedObserver) {
  214. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  215. }
  216. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  217. },
  218. enumerable: true,
  219. configurable: true
  220. });
  221. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  222. /**
  223. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  224. * For assets with LODs, raised when all of the LODs are complete.
  225. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  226. */
  227. set: function (callback) {
  228. if (this._onCompleteObserver) {
  229. this.onCompleteObservable.remove(this._onCompleteObserver);
  230. }
  231. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  232. },
  233. enumerable: true,
  234. configurable: true
  235. });
  236. Object.defineProperty(GLTFFileLoader.prototype, "onError", {
  237. /**
  238. * Callback raised when an error occurs.
  239. */
  240. set: function (callback) {
  241. if (this._onErrorObserver) {
  242. this.onErrorObservable.remove(this._onErrorObserver);
  243. }
  244. this._onErrorObserver = this.onErrorObservable.add(callback);
  245. },
  246. enumerable: true,
  247. configurable: true
  248. });
  249. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  250. /**
  251. * Callback raised after the loader is disposed.
  252. */
  253. set: function (callback) {
  254. if (this._onDisposeObserver) {
  255. this.onDisposeObservable.remove(this._onDisposeObserver);
  256. }
  257. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  258. },
  259. enumerable: true,
  260. configurable: true
  261. });
  262. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  263. /**
  264. * Callback raised after a loader extension is created.
  265. */
  266. set: function (callback) {
  267. if (this._onExtensionLoadedObserver) {
  268. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  269. }
  270. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  271. },
  272. enumerable: true,
  273. configurable: true
  274. });
  275. /**
  276. * Returns a promise that resolves when the asset is completely loaded.
  277. * @returns a promise that resolves when the asset is completely loaded.
  278. */
  279. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  280. var _this = this;
  281. return new Promise(function (resolve, reject) {
  282. _this.onCompleteObservable.addOnce(function () {
  283. resolve();
  284. });
  285. _this.onErrorObservable.addOnce(function (reason) {
  286. reject(reason);
  287. });
  288. });
  289. };
  290. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  291. /**
  292. * The loader state or null if the loader is not active.
  293. */
  294. get: function () {
  295. return this._loader ? this._loader.state : null;
  296. },
  297. enumerable: true,
  298. configurable: true
  299. });
  300. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  301. /**
  302. * Defines if the loader logging is enabled.
  303. */
  304. get: function () {
  305. return this._loggingEnabled;
  306. },
  307. set: function (value) {
  308. if (this._loggingEnabled === value) {
  309. return;
  310. }
  311. this._loggingEnabled = value;
  312. if (this._loggingEnabled) {
  313. this._log = this._logEnabled;
  314. }
  315. else {
  316. this._log = this._logDisabled;
  317. }
  318. },
  319. enumerable: true,
  320. configurable: true
  321. });
  322. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  323. /**
  324. * Defines if the loader should capture performance counters.
  325. */
  326. get: function () {
  327. return this._capturePerformanceCounters;
  328. },
  329. set: function (value) {
  330. if (this._capturePerformanceCounters === value) {
  331. return;
  332. }
  333. this._capturePerformanceCounters = value;
  334. if (this._capturePerformanceCounters) {
  335. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  336. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  337. }
  338. else {
  339. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  340. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  341. }
  342. },
  343. enumerable: true,
  344. configurable: true
  345. });
  346. /**
  347. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  348. */
  349. GLTFFileLoader.prototype.dispose = function () {
  350. if (this._loader) {
  351. this._loader.dispose();
  352. this._loader = null;
  353. }
  354. this._clear();
  355. this.onDisposeObservable.notifyObservers(undefined);
  356. this.onDisposeObservable.clear();
  357. };
  358. /** @hidden */
  359. GLTFFileLoader.prototype._clear = function () {
  360. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  361. this.onMeshLoadedObservable.clear();
  362. this.onTextureLoadedObservable.clear();
  363. this.onMaterialLoadedObservable.clear();
  364. this.onCameraLoadedObservable.clear();
  365. this.onCompleteObservable.clear();
  366. this.onExtensionLoadedObservable.clear();
  367. };
  368. /**
  369. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  370. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  371. * @param scene the scene the meshes should be added to
  372. * @param data the glTF data to load
  373. * @param rootUrl root url to load from
  374. * @param onProgress event that fires when loading progress has occured
  375. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  376. */
  377. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  378. var _this = this;
  379. return Promise.resolve().then(function () {
  380. var loaderData = _this._parse(data);
  381. _this._loader = _this._getLoader(loaderData);
  382. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  383. });
  384. };
  385. /**
  386. * Imports all objects from the loaded glTF data and adds them to the scene
  387. * @param scene the scene the objects should be added to
  388. * @param data the glTF data to load
  389. * @param rootUrl root url to load from
  390. * @param onProgress event that fires when loading progress has occured
  391. * @returns a promise which completes when objects have been loaded to the scene
  392. */
  393. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  394. var _this = this;
  395. return Promise.resolve().then(function () {
  396. var loaderData = _this._parse(data);
  397. _this._loader = _this._getLoader(loaderData);
  398. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  399. });
  400. };
  401. /**
  402. * Load into an asset container.
  403. * @param scene The scene to load into
  404. * @param data The data to import
  405. * @param rootUrl The root url for scene and resources
  406. * @param onProgress The callback when the load progresses
  407. * @returns The loaded asset container
  408. */
  409. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  410. var _this = this;
  411. return Promise.resolve().then(function () {
  412. var loaderData = _this._parse(data);
  413. _this._loader = _this._getLoader(loaderData);
  414. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  415. var container = new BABYLON.AssetContainer(scene);
  416. Array.prototype.push.apply(container.meshes, result.meshes);
  417. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  418. Array.prototype.push.apply(container.skeletons, result.skeletons);
  419. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  420. container.removeAllFromScene();
  421. return container;
  422. });
  423. });
  424. };
  425. /**
  426. * If the data string can be loaded directly.
  427. * @param data string contianing the file data
  428. * @returns if the data can be loaded directly
  429. */
  430. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  431. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  432. };
  433. /**
  434. * Instantiates a glTF file loader plugin.
  435. * @returns the created plugin
  436. */
  437. GLTFFileLoader.prototype.createPlugin = function () {
  438. return new GLTFFileLoader();
  439. };
  440. GLTFFileLoader.prototype._parse = function (data) {
  441. this._startPerformanceCounter("Parse");
  442. var parsedData;
  443. if (data instanceof ArrayBuffer) {
  444. this._log("Parsing binary");
  445. parsedData = this._parseBinary(data);
  446. }
  447. else {
  448. this._log("Parsing JSON");
  449. this._log("JSON length: " + data.length);
  450. parsedData = {
  451. json: JSON.parse(data),
  452. bin: null
  453. };
  454. }
  455. this.onParsedObservable.notifyObservers(parsedData);
  456. this.onParsedObservable.clear();
  457. this._endPerformanceCounter("Parse");
  458. return parsedData;
  459. };
  460. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  461. var asset = loaderData.json.asset || {};
  462. this._log("Asset version: " + asset.version);
  463. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  464. asset.generator && this._log("Asset generator: " + asset.generator);
  465. var version = GLTFFileLoader._parseVersion(asset.version);
  466. if (!version) {
  467. throw new Error("Invalid version: " + asset.version);
  468. }
  469. if (asset.minVersion !== undefined) {
  470. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  471. if (!minVersion) {
  472. throw new Error("Invalid minimum version: " + asset.minVersion);
  473. }
  474. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  475. throw new Error("Incompatible minimum version: " + asset.minVersion);
  476. }
  477. }
  478. var createLoaders = {
  479. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  480. 2: GLTFFileLoader._CreateGLTFLoaderV2
  481. };
  482. var createLoader = createLoaders[version.major];
  483. if (!createLoader) {
  484. throw new Error("Unsupported version: " + asset.version);
  485. }
  486. return createLoader(this);
  487. };
  488. GLTFFileLoader.prototype._parseBinary = function (data) {
  489. var Binary = {
  490. Magic: 0x46546C67
  491. };
  492. this._log("Binary length: " + data.byteLength);
  493. var binaryReader = new BinaryReader(data);
  494. var magic = binaryReader.readUint32();
  495. if (magic !== Binary.Magic) {
  496. throw new Error("Unexpected magic: " + magic);
  497. }
  498. var version = binaryReader.readUint32();
  499. if (this.loggingEnabled) {
  500. this._log("Binary version: " + version);
  501. }
  502. switch (version) {
  503. case 1: return this._parseV1(binaryReader);
  504. case 2: return this._parseV2(binaryReader);
  505. }
  506. throw new Error("Unsupported version: " + version);
  507. };
  508. GLTFFileLoader.prototype._parseV1 = function (binaryReader) {
  509. var ContentFormat = {
  510. JSON: 0
  511. };
  512. var length = binaryReader.readUint32();
  513. if (length != binaryReader.getLength()) {
  514. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  515. }
  516. var contentLength = binaryReader.readUint32();
  517. var contentFormat = binaryReader.readUint32();
  518. var content;
  519. switch (contentFormat) {
  520. case ContentFormat.JSON: {
  521. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  522. break;
  523. }
  524. default: {
  525. throw new Error("Unexpected content format: " + contentFormat);
  526. }
  527. }
  528. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  529. var body = binaryReader.readUint8Array(bytesRemaining);
  530. return {
  531. json: content,
  532. bin: body
  533. };
  534. };
  535. GLTFFileLoader.prototype._parseV2 = function (binaryReader) {
  536. var ChunkFormat = {
  537. JSON: 0x4E4F534A,
  538. BIN: 0x004E4942
  539. };
  540. var length = binaryReader.readUint32();
  541. if (length !== binaryReader.getLength()) {
  542. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  543. }
  544. // JSON chunk
  545. var chunkLength = binaryReader.readUint32();
  546. var chunkFormat = binaryReader.readUint32();
  547. if (chunkFormat !== ChunkFormat.JSON) {
  548. throw new Error("First chunk format is not JSON");
  549. }
  550. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  551. // Look for BIN chunk
  552. var bin = null;
  553. while (binaryReader.getPosition() < binaryReader.getLength()) {
  554. var chunkLength_1 = binaryReader.readUint32();
  555. var chunkFormat_1 = binaryReader.readUint32();
  556. switch (chunkFormat_1) {
  557. case ChunkFormat.JSON: {
  558. throw new Error("Unexpected JSON chunk");
  559. }
  560. case ChunkFormat.BIN: {
  561. bin = binaryReader.readUint8Array(chunkLength_1);
  562. break;
  563. }
  564. default: {
  565. // ignore unrecognized chunkFormat
  566. binaryReader.skipBytes(chunkLength_1);
  567. break;
  568. }
  569. }
  570. }
  571. return {
  572. json: json,
  573. bin: bin
  574. };
  575. };
  576. GLTFFileLoader._parseVersion = function (version) {
  577. if (version === "1.0" || version === "1.0.1") {
  578. return {
  579. major: 1,
  580. minor: 0
  581. };
  582. }
  583. var match = (version + "").match(/^(\d+)\.(\d+)/);
  584. if (!match) {
  585. return null;
  586. }
  587. return {
  588. major: parseInt(match[1]),
  589. minor: parseInt(match[2])
  590. };
  591. };
  592. GLTFFileLoader._compareVersion = function (a, b) {
  593. if (a.major > b.major)
  594. return 1;
  595. if (a.major < b.major)
  596. return -1;
  597. if (a.minor > b.minor)
  598. return 1;
  599. if (a.minor < b.minor)
  600. return -1;
  601. return 0;
  602. };
  603. GLTFFileLoader._decodeBufferToText = function (buffer) {
  604. var result = "";
  605. var length = buffer.byteLength;
  606. for (var i = 0; i < length; i++) {
  607. result += String.fromCharCode(buffer[i]);
  608. }
  609. return result;
  610. };
  611. /** @hidden */
  612. GLTFFileLoader.prototype._logOpen = function (message) {
  613. this._log(message);
  614. this._logIndentLevel++;
  615. };
  616. /** @hidden */
  617. GLTFFileLoader.prototype._logClose = function () {
  618. --this._logIndentLevel;
  619. };
  620. GLTFFileLoader.prototype._logEnabled = function (message) {
  621. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  622. BABYLON.Tools.Log("" + spaces + message);
  623. };
  624. GLTFFileLoader.prototype._logDisabled = function (message) {
  625. };
  626. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  627. BABYLON.Tools.StartPerformanceCounter(counterName);
  628. };
  629. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  630. };
  631. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  632. BABYLON.Tools.EndPerformanceCounter(counterName);
  633. };
  634. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  635. };
  636. // #endregion
  637. // #region V1 options
  638. /**
  639. * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.
  640. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  641. * Defaults to true.
  642. * @hidden
  643. */
  644. GLTFFileLoader.IncrementalLoading = true;
  645. /**
  646. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  647. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  648. * @hidden
  649. */
  650. GLTFFileLoader.HomogeneousCoordinates = false;
  651. GLTFFileLoader._logSpaces = " ";
  652. return GLTFFileLoader;
  653. }());
  654. BABYLON.GLTFFileLoader = GLTFFileLoader;
  655. var BinaryReader = /** @class */ (function () {
  656. function BinaryReader(arrayBuffer) {
  657. this._arrayBuffer = arrayBuffer;
  658. this._dataView = new DataView(arrayBuffer);
  659. this._byteOffset = 0;
  660. }
  661. BinaryReader.prototype.getPosition = function () {
  662. return this._byteOffset;
  663. };
  664. BinaryReader.prototype.getLength = function () {
  665. return this._arrayBuffer.byteLength;
  666. };
  667. BinaryReader.prototype.readUint32 = function () {
  668. var value = this._dataView.getUint32(this._byteOffset, true);
  669. this._byteOffset += 4;
  670. return value;
  671. };
  672. BinaryReader.prototype.readUint8Array = function (length) {
  673. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  674. this._byteOffset += length;
  675. return value;
  676. };
  677. BinaryReader.prototype.skipBytes = function (length) {
  678. this._byteOffset += length;
  679. };
  680. return BinaryReader;
  681. }());
  682. if (BABYLON.SceneLoader) {
  683. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  684. }
  685. })(BABYLON || (BABYLON = {}));
  686. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  687. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  688. /// <reference path="../../../../dist/preview release/glTF2Interface/babylon.glTF2Interface.d.ts"/>
  689. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  690. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  691. /**
  692. * Defines the module used to import/export glTF 2.0 assets
  693. */
  694. var BABYLON;
  695. (function (BABYLON) {
  696. var GLTF2;
  697. (function (GLTF2) {
  698. /** @hidden */
  699. var _ArrayItem = /** @class */ (function () {
  700. function _ArrayItem() {
  701. }
  702. _ArrayItem.Assign = function (values) {
  703. if (values) {
  704. for (var index = 0; index < values.length; index++) {
  705. values[index]._index = index;
  706. }
  707. }
  708. };
  709. return _ArrayItem;
  710. }());
  711. GLTF2._ArrayItem = _ArrayItem;
  712. /** @hidden */
  713. var GLTFLoader = /** @class */ (function () {
  714. function GLTFLoader(parent) {
  715. this._completePromises = new Array();
  716. this._disposed = false;
  717. this._state = null;
  718. this._extensions = {};
  719. this._defaultSampler = {};
  720. this._defaultBabylonMaterials = {};
  721. this._requests = new Array();
  722. this._parent = parent;
  723. }
  724. GLTFLoader._Register = function (name, factory) {
  725. if (GLTFLoader._ExtensionFactories[name]) {
  726. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  727. return;
  728. }
  729. GLTFLoader._ExtensionFactories[name] = factory;
  730. // Keep the order of registration so that extensions registered first are called first.
  731. GLTFLoader._ExtensionNames.push(name);
  732. };
  733. Object.defineProperty(GLTFLoader.prototype, "state", {
  734. get: function () {
  735. return this._state;
  736. },
  737. enumerable: true,
  738. configurable: true
  739. });
  740. GLTFLoader.prototype.dispose = function () {
  741. if (this._disposed) {
  742. return;
  743. }
  744. this._disposed = true;
  745. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  746. var request = _a[_i];
  747. request.abort();
  748. }
  749. this._requests.length = 0;
  750. delete this._gltf;
  751. delete this._babylonScene;
  752. this._completePromises.length = 0;
  753. for (var name_1 in this._extensions) {
  754. this._extensions[name_1].dispose();
  755. }
  756. this._extensions = {};
  757. delete this._rootBabylonMesh;
  758. delete this._progressCallback;
  759. this._parent._clear();
  760. };
  761. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  762. var _this = this;
  763. return Promise.resolve().then(function () {
  764. _this._babylonScene = scene;
  765. _this._rootUrl = rootUrl;
  766. _this._progressCallback = onProgress;
  767. _this._loadData(data);
  768. var nodes = null;
  769. if (meshesNames) {
  770. var nodeMap_1 = {};
  771. if (_this._gltf.nodes) {
  772. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  773. var node = _a[_i];
  774. if (node.name) {
  775. nodeMap_1[node.name] = node._index;
  776. }
  777. }
  778. }
  779. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  780. nodes = names.map(function (name) {
  781. var node = nodeMap_1[name];
  782. if (node === undefined) {
  783. throw new Error("Failed to find node '" + name + "'");
  784. }
  785. return node;
  786. });
  787. }
  788. return _this._loadAsync(nodes).then(function () {
  789. return {
  790. meshes: _this._getMeshes(),
  791. particleSystems: [],
  792. skeletons: _this._getSkeletons(),
  793. animationGroups: _this._getAnimationGroups()
  794. };
  795. });
  796. });
  797. };
  798. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  799. var _this = this;
  800. return Promise.resolve().then(function () {
  801. _this._babylonScene = scene;
  802. _this._rootUrl = rootUrl;
  803. _this._progressCallback = onProgress;
  804. _this._loadData(data);
  805. return _this._loadAsync(null);
  806. });
  807. };
  808. GLTFLoader.prototype._loadAsync = function (nodes) {
  809. var _this = this;
  810. return Promise.resolve().then(function () {
  811. _this._loadExtensions();
  812. _this._checkExtensions();
  813. var loadingToReadyCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.READY];
  814. var loadingToCompleteCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.COMPLETE];
  815. _this._parent._startPerformanceCounter(loadingToReadyCounterName);
  816. _this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  817. _this._setState(BABYLON.GLTFLoaderState.LOADING);
  818. GLTF2.GLTFLoaderExtension._OnLoading(_this);
  819. var promises = new Array();
  820. if (nodes) {
  821. promises.push(_this._loadSceneAsync("#/nodes", { nodes: nodes, _index: -1 }));
  822. }
  823. else {
  824. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  825. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  826. }
  827. if (_this._parent.compileMaterials) {
  828. promises.push(_this._compileMaterialsAsync());
  829. }
  830. if (_this._parent.compileShadowGenerators) {
  831. promises.push(_this._compileShadowGeneratorsAsync());
  832. }
  833. var resultPromise = Promise.all(promises).then(function () {
  834. _this._setState(BABYLON.GLTFLoaderState.READY);
  835. GLTF2.GLTFLoaderExtension._OnReady(_this);
  836. _this._startAnimations();
  837. });
  838. resultPromise.then(function () {
  839. _this._parent._endPerformanceCounter(loadingToReadyCounterName);
  840. BABYLON.Tools.SetImmediate(function () {
  841. if (!_this._disposed) {
  842. Promise.all(_this._completePromises).then(function () {
  843. _this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  844. _this._setState(BABYLON.GLTFLoaderState.COMPLETE);
  845. _this._parent.onCompleteObservable.notifyObservers(undefined);
  846. _this._parent.onCompleteObservable.clear();
  847. _this.dispose();
  848. }, function (error) {
  849. _this._parent.onErrorObservable.notifyObservers(error);
  850. _this._parent.onErrorObservable.clear();
  851. _this.dispose();
  852. });
  853. }
  854. });
  855. });
  856. return resultPromise;
  857. }, function (error) {
  858. if (!_this._disposed) {
  859. _this._parent.onErrorObservable.notifyObservers(error);
  860. _this._parent.onErrorObservable.clear();
  861. _this.dispose();
  862. throw error;
  863. }
  864. });
  865. };
  866. GLTFLoader.prototype._loadData = function (data) {
  867. this._gltf = data.json;
  868. this._setupData();
  869. if (data.bin) {
  870. var buffers = this._gltf.buffers;
  871. if (buffers && buffers[0] && !buffers[0].uri) {
  872. var binaryBuffer = buffers[0];
  873. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  874. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  875. }
  876. binaryBuffer._data = Promise.resolve(data.bin);
  877. }
  878. else {
  879. BABYLON.Tools.Warn("Unexpected BIN chunk");
  880. }
  881. }
  882. };
  883. GLTFLoader.prototype._setupData = function () {
  884. _ArrayItem.Assign(this._gltf.accessors);
  885. _ArrayItem.Assign(this._gltf.animations);
  886. _ArrayItem.Assign(this._gltf.buffers);
  887. _ArrayItem.Assign(this._gltf.bufferViews);
  888. _ArrayItem.Assign(this._gltf.cameras);
  889. _ArrayItem.Assign(this._gltf.images);
  890. _ArrayItem.Assign(this._gltf.materials);
  891. _ArrayItem.Assign(this._gltf.meshes);
  892. _ArrayItem.Assign(this._gltf.nodes);
  893. _ArrayItem.Assign(this._gltf.samplers);
  894. _ArrayItem.Assign(this._gltf.scenes);
  895. _ArrayItem.Assign(this._gltf.skins);
  896. _ArrayItem.Assign(this._gltf.textures);
  897. if (this._gltf.nodes) {
  898. var nodeParents = {};
  899. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  900. var node = _a[_i];
  901. if (node.children) {
  902. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  903. var index = _c[_b];
  904. nodeParents[index] = node._index;
  905. }
  906. }
  907. }
  908. var rootNode = this._createRootNode();
  909. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  910. var node = _e[_d];
  911. var parentIndex = nodeParents[node._index];
  912. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  913. }
  914. }
  915. };
  916. GLTFLoader.prototype._loadExtensions = function () {
  917. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  918. var name_2 = _a[_i];
  919. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  920. this._extensions[name_2] = extension;
  921. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  922. }
  923. this._parent.onExtensionLoadedObservable.clear();
  924. };
  925. GLTFLoader.prototype._checkExtensions = function () {
  926. if (this._gltf.extensionsRequired) {
  927. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  928. var name_3 = _a[_i];
  929. var extension = this._extensions[name_3];
  930. if (!extension || !extension.enabled) {
  931. throw new Error("Require extension " + name_3 + " is not available");
  932. }
  933. }
  934. }
  935. };
  936. GLTFLoader.prototype._setState = function (state) {
  937. this._state = state;
  938. this._parent._log(BABYLON.GLTFLoaderState[this._state]);
  939. };
  940. GLTFLoader.prototype._createRootNode = function () {
  941. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  942. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  943. switch (this._parent.coordinateSystemMode) {
  944. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  945. if (!this._babylonScene.useRightHandedSystem) {
  946. rootNode.rotation = [0, 1, 0, 0];
  947. rootNode.scale = [1, 1, -1];
  948. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  949. }
  950. break;
  951. }
  952. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  953. this._babylonScene.useRightHandedSystem = true;
  954. break;
  955. }
  956. default: {
  957. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  958. }
  959. }
  960. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  961. return rootNode;
  962. };
  963. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  964. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  965. if (extensionPromise) {
  966. return extensionPromise;
  967. }
  968. var promises = new Array();
  969. this._parent._logOpen(context + " " + (scene.name || ""));
  970. if (scene.nodes) {
  971. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  972. var index = _a[_i];
  973. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  974. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  975. }
  976. }
  977. promises.push(this._loadAnimationsAsync());
  978. this._parent._logClose();
  979. return Promise.all(promises).then(function () { });
  980. };
  981. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  982. if (node._primitiveBabylonMeshes) {
  983. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  984. var babylonMesh = _a[_i];
  985. callback(babylonMesh);
  986. }
  987. }
  988. else {
  989. callback(node._babylonMesh);
  990. }
  991. };
  992. GLTFLoader.prototype._getMeshes = function () {
  993. var meshes = new Array();
  994. // Root mesh is always first.
  995. meshes.push(this._rootBabylonMesh);
  996. var nodes = this._gltf.nodes;
  997. if (nodes) {
  998. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  999. var node = nodes_1[_i];
  1000. if (node._babylonMesh) {
  1001. meshes.push(node._babylonMesh);
  1002. }
  1003. if (node._primitiveBabylonMeshes) {
  1004. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  1005. var babylonMesh = _b[_a];
  1006. meshes.push(babylonMesh);
  1007. }
  1008. }
  1009. }
  1010. }
  1011. return meshes;
  1012. };
  1013. GLTFLoader.prototype._getSkeletons = function () {
  1014. var skeletons = new Array();
  1015. var skins = this._gltf.skins;
  1016. if (skins) {
  1017. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  1018. var skin = skins_1[_i];
  1019. if (skin._babylonSkeleton) {
  1020. skeletons.push(skin._babylonSkeleton);
  1021. }
  1022. }
  1023. }
  1024. return skeletons;
  1025. };
  1026. GLTFLoader.prototype._getAnimationGroups = function () {
  1027. var animationGroups = new Array();
  1028. var animations = this._gltf.animations;
  1029. if (animations) {
  1030. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  1031. var animation = animations_1[_i];
  1032. if (animation._babylonAnimationGroup) {
  1033. animationGroups.push(animation._babylonAnimationGroup);
  1034. }
  1035. }
  1036. }
  1037. return animationGroups;
  1038. };
  1039. GLTFLoader.prototype._startAnimations = function () {
  1040. switch (this._parent.animationStartMode) {
  1041. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  1042. // do nothing
  1043. break;
  1044. }
  1045. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  1046. var babylonAnimationGroups = this._getAnimationGroups();
  1047. if (babylonAnimationGroups.length !== 0) {
  1048. babylonAnimationGroups[0].start(true);
  1049. }
  1050. break;
  1051. }
  1052. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  1053. var babylonAnimationGroups = this._getAnimationGroups();
  1054. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  1055. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  1056. babylonAnimationGroup.start(true);
  1057. }
  1058. break;
  1059. }
  1060. default: {
  1061. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  1062. return;
  1063. }
  1064. }
  1065. };
  1066. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  1067. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  1068. if (extensionPromise) {
  1069. return extensionPromise;
  1070. }
  1071. if (node._babylonMesh) {
  1072. throw new Error(context + ": Invalid recursive node hierarchy");
  1073. }
  1074. var promises = new Array();
  1075. this._parent._logOpen(context + " " + (node.name || ""));
  1076. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);
  1077. node._babylonMesh = babylonMesh;
  1078. babylonMesh.setEnabled(false);
  1079. GLTFLoader._LoadTransform(node, babylonMesh);
  1080. if (node.mesh != undefined) {
  1081. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  1082. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  1083. }
  1084. if (node.camera != undefined) {
  1085. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  1086. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  1087. }
  1088. if (node.children) {
  1089. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  1090. var index = _a[_i];
  1091. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  1092. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  1093. }
  1094. }
  1095. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  1096. this._parent._logClose();
  1097. return Promise.all(promises).then(function () {
  1098. babylonMesh.setEnabled(true);
  1099. });
  1100. };
  1101. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  1102. var _this = this;
  1103. var promises = new Array();
  1104. this._parent._logOpen(context + " " + (mesh.name || ""));
  1105. var primitives = mesh.primitives;
  1106. if (!primitives || primitives.length === 0) {
  1107. throw new Error(context + ": Primitives are missing");
  1108. }
  1109. _ArrayItem.Assign(primitives);
  1110. if (primitives.length === 1) {
  1111. var primitive = primitives[0];
  1112. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  1113. }
  1114. else {
  1115. node._primitiveBabylonMeshes = [];
  1116. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  1117. var primitive = primitives_1[_i];
  1118. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  1119. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  1120. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  1121. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  1122. }
  1123. }
  1124. if (node.skin != undefined) {
  1125. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  1126. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  1127. }
  1128. this._parent._logClose();
  1129. return Promise.all(promises).then(function () {
  1130. _this._forEachPrimitive(node, function (babylonMesh) {
  1131. babylonMesh._refreshBoundingInfo(true);
  1132. });
  1133. });
  1134. };
  1135. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  1136. var _this = this;
  1137. var promises = new Array();
  1138. this._parent._logOpen("" + context);
  1139. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  1140. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  1141. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  1142. babylonGeometry.applyToMesh(babylonMesh);
  1143. });
  1144. }));
  1145. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  1146. if (primitive.material == undefined) {
  1147. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  1148. }
  1149. else {
  1150. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  1151. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  1152. babylonMesh.material = babylonMaterial;
  1153. }));
  1154. }
  1155. this._parent._logClose();
  1156. return Promise.all(promises).then(function () { });
  1157. };
  1158. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  1159. var _this = this;
  1160. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  1161. if (extensionPromise) {
  1162. return extensionPromise;
  1163. }
  1164. var attributes = primitive.attributes;
  1165. if (!attributes) {
  1166. throw new Error(context + ": Attributes are missing");
  1167. }
  1168. var promises = new Array();
  1169. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  1170. if (primitive.indices == undefined) {
  1171. babylonMesh.isUnIndexed = true;
  1172. }
  1173. else {
  1174. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  1175. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  1176. babylonGeometry.setIndices(data);
  1177. }));
  1178. }
  1179. var loadAttribute = function (attribute, kind, callback) {
  1180. if (attributes[attribute] == undefined) {
  1181. return;
  1182. }
  1183. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  1184. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  1185. babylonMesh._delayInfo.push(kind);
  1186. }
  1187. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  1188. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  1189. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  1190. }));
  1191. if (callback) {
  1192. callback(accessor);
  1193. }
  1194. };
  1195. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  1196. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  1197. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  1198. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  1199. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  1200. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  1201. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  1202. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  1203. if (accessor.type === "VEC4" /* VEC4 */) {
  1204. babylonMesh.hasVertexAlpha = true;
  1205. }
  1206. });
  1207. return Promise.all(promises).then(function () {
  1208. return babylonGeometry;
  1209. });
  1210. };
  1211. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  1212. if (!primitive.targets) {
  1213. return;
  1214. }
  1215. if (node._numMorphTargets == undefined) {
  1216. node._numMorphTargets = primitive.targets.length;
  1217. }
  1218. else if (primitive.targets.length !== node._numMorphTargets) {
  1219. throw new Error(context + ": Primitives do not have the same number of targets");
  1220. }
  1221. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  1222. for (var index = 0; index < primitive.targets.length; index++) {
  1223. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  1224. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  1225. // TODO: tell the target whether it has positions, normals, tangents
  1226. }
  1227. };
  1228. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  1229. if (!primitive.targets) {
  1230. return Promise.resolve();
  1231. }
  1232. var promises = new Array();
  1233. var morphTargetManager = babylonMesh.morphTargetManager;
  1234. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  1235. var babylonMorphTarget = morphTargetManager.getTarget(index);
  1236. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  1237. }
  1238. return Promise.all(promises).then(function () { });
  1239. };
  1240. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  1241. var _this = this;
  1242. var promises = new Array();
  1243. var loadAttribute = function (attribute, kind, setData) {
  1244. if (attributes[attribute] == undefined) {
  1245. return;
  1246. }
  1247. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  1248. if (!babylonVertexBuffer) {
  1249. return;
  1250. }
  1251. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  1252. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  1253. setData(babylonVertexBuffer, data);
  1254. }));
  1255. };
  1256. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  1257. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1258. data[index] += value;
  1259. });
  1260. babylonMorphTarget.setPositions(data);
  1261. });
  1262. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  1263. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1264. data[index] += value;
  1265. });
  1266. babylonMorphTarget.setNormals(data);
  1267. });
  1268. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  1269. var dataIndex = 0;
  1270. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  1271. // Tangent data for morph targets is stored as xyz delta.
  1272. // The vertexData.tangent is stored as xyzw.
  1273. // So we need to skip every fourth vertexData.tangent.
  1274. if (((index + 1) % 4) !== 0) {
  1275. data[dataIndex++] += value;
  1276. }
  1277. });
  1278. babylonMorphTarget.setTangents(data);
  1279. });
  1280. return Promise.all(promises).then(function () { });
  1281. };
  1282. GLTFLoader._LoadTransform = function (node, babylonNode) {
  1283. var position = BABYLON.Vector3.Zero();
  1284. var rotation = BABYLON.Quaternion.Identity();
  1285. var scaling = BABYLON.Vector3.One();
  1286. if (node.matrix) {
  1287. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  1288. matrix.decompose(scaling, rotation, position);
  1289. }
  1290. else {
  1291. if (node.translation)
  1292. position = BABYLON.Vector3.FromArray(node.translation);
  1293. if (node.rotation)
  1294. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  1295. if (node.scale)
  1296. scaling = BABYLON.Vector3.FromArray(node.scale);
  1297. }
  1298. babylonNode.position = position;
  1299. babylonNode.rotationQuaternion = rotation;
  1300. babylonNode.scaling = scaling;
  1301. };
  1302. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  1303. var _this = this;
  1304. var assignSkeleton = function (skeleton) {
  1305. _this._forEachPrimitive(node, function (babylonMesh) {
  1306. babylonMesh.skeleton = skeleton;
  1307. });
  1308. // Ignore the TRS of skinned nodes.
  1309. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1310. node._babylonMesh.parent = _this._rootBabylonMesh;
  1311. node._babylonMesh.position = BABYLON.Vector3.Zero();
  1312. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  1313. node._babylonMesh.scaling = BABYLON.Vector3.One();
  1314. };
  1315. if (skin._loaded) {
  1316. return skin._loaded.then(function () {
  1317. assignSkeleton(skin._babylonSkeleton);
  1318. });
  1319. }
  1320. var skeletonId = "skeleton" + skin._index;
  1321. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  1322. skin._babylonSkeleton = babylonSkeleton;
  1323. this._loadBones(context, skin);
  1324. assignSkeleton(babylonSkeleton);
  1325. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  1326. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  1327. }));
  1328. };
  1329. GLTFLoader.prototype._loadBones = function (context, skin) {
  1330. var babylonBones = {};
  1331. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  1332. var index = _a[_i];
  1333. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  1334. this._loadBone(node, skin, babylonBones);
  1335. }
  1336. };
  1337. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  1338. var babylonBone = babylonBones[node._index];
  1339. if (babylonBone) {
  1340. return babylonBone;
  1341. }
  1342. var babylonParentBone = null;
  1343. if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {
  1344. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  1345. }
  1346. var boneIndex = skin.joints.indexOf(node._index);
  1347. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  1348. babylonBones[node._index] = babylonBone;
  1349. node._babylonBones = node._babylonBones || [];
  1350. node._babylonBones.push(babylonBone);
  1351. return babylonBone;
  1352. };
  1353. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  1354. if (skin.inverseBindMatrices == undefined) {
  1355. return Promise.resolve(null);
  1356. }
  1357. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  1358. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  1359. };
  1360. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  1361. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  1362. var babylonBone = _a[_i];
  1363. var baseMatrix = BABYLON.Matrix.Identity();
  1364. var boneIndex = babylonBone._index;
  1365. if (inverseBindMatricesData && boneIndex !== -1) {
  1366. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  1367. baseMatrix.invertToRef(baseMatrix);
  1368. }
  1369. var babylonParentBone = babylonBone.getParent();
  1370. if (babylonParentBone) {
  1371. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  1372. }
  1373. babylonBone.updateMatrix(baseMatrix, false, false);
  1374. babylonBone._updateDifferenceMatrix(undefined, false);
  1375. }
  1376. };
  1377. GLTFLoader.prototype._getNodeMatrix = function (node) {
  1378. return node.matrix ?
  1379. BABYLON.Matrix.FromArray(node.matrix) :
  1380. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  1381. };
  1382. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  1383. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  1384. babylonCamera.parent = babylonMesh;
  1385. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  1386. switch (camera.type) {
  1387. case "perspective" /* PERSPECTIVE */: {
  1388. var perspective = camera.perspective;
  1389. if (!perspective) {
  1390. throw new Error(context + ": Camera perspective properties are missing");
  1391. }
  1392. babylonCamera.fov = perspective.yfov;
  1393. babylonCamera.minZ = perspective.znear;
  1394. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  1395. break;
  1396. }
  1397. case "orthographic" /* ORTHOGRAPHIC */: {
  1398. if (!camera.orthographic) {
  1399. throw new Error(context + ": Camera orthographic properties are missing");
  1400. }
  1401. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1402. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  1403. babylonCamera.orthoRight = camera.orthographic.xmag;
  1404. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  1405. babylonCamera.orthoTop = camera.orthographic.ymag;
  1406. babylonCamera.minZ = camera.orthographic.znear;
  1407. babylonCamera.maxZ = camera.orthographic.zfar;
  1408. break;
  1409. }
  1410. default: {
  1411. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  1412. }
  1413. }
  1414. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  1415. };
  1416. GLTFLoader.prototype._loadAnimationsAsync = function () {
  1417. var animations = this._gltf.animations;
  1418. if (!animations) {
  1419. return Promise.resolve();
  1420. }
  1421. var promises = new Array();
  1422. for (var index = 0; index < animations.length; index++) {
  1423. var animation = animations[index];
  1424. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  1425. }
  1426. return Promise.all(promises).then(function () { });
  1427. };
  1428. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  1429. var _this = this;
  1430. var promise = GLTF2.GLTFLoaderExtension._LoadAnimationAsync(this, context, animation);
  1431. if (promise) {
  1432. return promise;
  1433. }
  1434. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  1435. animation._babylonAnimationGroup = babylonAnimationGroup;
  1436. var promises = new Array();
  1437. _ArrayItem.Assign(animation.channels);
  1438. _ArrayItem.Assign(animation.samplers);
  1439. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  1440. var channel = _a[_i];
  1441. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  1442. }
  1443. return Promise.all(promises).then(function () {
  1444. babylonAnimationGroup.normalize(_this._parent._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  1445. });
  1446. };
  1447. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  1448. var _this = this;
  1449. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  1450. // Ignore animations that have no animation targets.
  1451. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  1452. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  1453. return Promise.resolve();
  1454. }
  1455. // Ignore animations targeting TRS of skinned nodes.
  1456. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1457. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  1458. return Promise.resolve();
  1459. }
  1460. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  1461. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  1462. var targetPath;
  1463. var animationType;
  1464. switch (channel.target.path) {
  1465. case "translation" /* TRANSLATION */: {
  1466. targetPath = "position";
  1467. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1468. break;
  1469. }
  1470. case "rotation" /* ROTATION */: {
  1471. targetPath = "rotationQuaternion";
  1472. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1473. break;
  1474. }
  1475. case "scale" /* SCALE */: {
  1476. targetPath = "scaling";
  1477. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1478. break;
  1479. }
  1480. case "weights" /* WEIGHTS */: {
  1481. targetPath = "influence";
  1482. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  1483. break;
  1484. }
  1485. default: {
  1486. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  1487. }
  1488. }
  1489. var outputBufferOffset = 0;
  1490. var getNextOutputValue;
  1491. switch (targetPath) {
  1492. case "position": {
  1493. getNextOutputValue = function () {
  1494. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  1495. outputBufferOffset += 3;
  1496. return value;
  1497. };
  1498. break;
  1499. }
  1500. case "rotationQuaternion": {
  1501. getNextOutputValue = function () {
  1502. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  1503. outputBufferOffset += 4;
  1504. return value;
  1505. };
  1506. break;
  1507. }
  1508. case "scaling": {
  1509. getNextOutputValue = function () {
  1510. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  1511. outputBufferOffset += 3;
  1512. return value;
  1513. };
  1514. break;
  1515. }
  1516. case "influence": {
  1517. getNextOutputValue = function () {
  1518. var value = new Array(targetNode._numMorphTargets);
  1519. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  1520. value[i] = data.output[outputBufferOffset++];
  1521. }
  1522. return value;
  1523. };
  1524. break;
  1525. }
  1526. }
  1527. var getNextKey;
  1528. switch (data.interpolation) {
  1529. case "STEP" /* STEP */: {
  1530. getNextKey = function (frameIndex) { return ({
  1531. frame: data.input[frameIndex],
  1532. value: getNextOutputValue(),
  1533. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  1534. }); };
  1535. break;
  1536. }
  1537. case "LINEAR" /* LINEAR */: {
  1538. getNextKey = function (frameIndex) { return ({
  1539. frame: data.input[frameIndex],
  1540. value: getNextOutputValue()
  1541. }); };
  1542. break;
  1543. }
  1544. case "CUBICSPLINE" /* CUBICSPLINE */: {
  1545. getNextKey = function (frameIndex) { return ({
  1546. frame: data.input[frameIndex],
  1547. inTangent: getNextOutputValue(),
  1548. value: getNextOutputValue(),
  1549. outTangent: getNextOutputValue()
  1550. }); };
  1551. break;
  1552. }
  1553. }
  1554. var keys = new Array(data.input.length);
  1555. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  1556. keys[frameIndex] = getNextKey(frameIndex);
  1557. }
  1558. if (targetPath === "influence") {
  1559. var _loop_1 = function (targetIndex) {
  1560. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  1561. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1562. babylonAnimation.setKeys(keys.map(function (key) { return ({
  1563. frame: key.frame,
  1564. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1565. value: key.value[targetIndex],
  1566. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1567. }); }));
  1568. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  1569. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  1570. var babylonAnimationClone = babylonAnimation.clone();
  1571. morphTarget.animations.push(babylonAnimationClone);
  1572. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  1573. });
  1574. };
  1575. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  1576. _loop_1(targetIndex);
  1577. }
  1578. }
  1579. else {
  1580. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  1581. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1582. babylonAnimation.setKeys(keys);
  1583. if (targetNode._babylonBones) {
  1584. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  1585. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  1586. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  1587. babylonAnimationTarget.animations.push(babylonAnimation);
  1588. }
  1589. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  1590. }
  1591. else {
  1592. targetNode._babylonMesh.animations.push(babylonAnimation);
  1593. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  1594. }
  1595. }
  1596. });
  1597. };
  1598. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  1599. if (sampler._data) {
  1600. return sampler._data;
  1601. }
  1602. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  1603. switch (interpolation) {
  1604. case "STEP" /* STEP */:
  1605. case "LINEAR" /* LINEAR */:
  1606. case "CUBICSPLINE" /* CUBICSPLINE */: {
  1607. break;
  1608. }
  1609. default: {
  1610. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  1611. }
  1612. }
  1613. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  1614. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  1615. sampler._data = Promise.all([
  1616. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  1617. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  1618. ]).then(function (_a) {
  1619. var inputData = _a[0], outputData = _a[1];
  1620. return {
  1621. input: inputData,
  1622. interpolation: interpolation,
  1623. output: outputData,
  1624. };
  1625. });
  1626. return sampler._data;
  1627. };
  1628. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  1629. if (buffer._data) {
  1630. return buffer._data;
  1631. }
  1632. if (!buffer.uri) {
  1633. throw new Error(context + ": Uri is missing");
  1634. }
  1635. buffer._data = this._loadUriAsync(context, buffer.uri);
  1636. return buffer._data;
  1637. };
  1638. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  1639. if (bufferView._data) {
  1640. return bufferView._data;
  1641. }
  1642. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  1643. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  1644. try {
  1645. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1646. }
  1647. catch (e) {
  1648. throw new Error(context + ": " + e.message);
  1649. }
  1650. });
  1651. return bufferView._data;
  1652. };
  1653. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  1654. if (accessor.type !== "SCALAR" /* SCALAR */) {
  1655. throw new Error(context + ": Invalid type " + accessor.type);
  1656. }
  1657. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  1658. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  1659. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  1660. throw new Error(context + ": Invalid component type " + accessor.componentType);
  1661. }
  1662. if (accessor._data) {
  1663. return accessor._data;
  1664. }
  1665. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  1666. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  1667. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  1668. });
  1669. return accessor._data;
  1670. };
  1671. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  1672. // TODO: support normalized and stride
  1673. var _this = this;
  1674. if (accessor.componentType !== 5126 /* FLOAT */) {
  1675. throw new Error("Invalid component type " + accessor.componentType);
  1676. }
  1677. if (accessor._data) {
  1678. return accessor._data;
  1679. }
  1680. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  1681. var length = numComponents * accessor.count;
  1682. if (accessor.bufferView == undefined) {
  1683. accessor._data = Promise.resolve(new Float32Array(length));
  1684. }
  1685. else {
  1686. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  1687. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  1688. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  1689. });
  1690. }
  1691. if (accessor.sparse) {
  1692. var sparse_1 = accessor.sparse;
  1693. accessor._data = accessor._data.then(function (data) {
  1694. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  1695. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  1696. return Promise.all([
  1697. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  1698. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  1699. ]).then(function (_a) {
  1700. var indicesData = _a[0], valuesData = _a[1];
  1701. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  1702. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  1703. var valuesIndex = 0;
  1704. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  1705. var dataIndex = indices[indicesIndex] * numComponents;
  1706. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1707. data[dataIndex++] = values[valuesIndex++];
  1708. }
  1709. }
  1710. return data;
  1711. });
  1712. });
  1713. }
  1714. return accessor._data;
  1715. };
  1716. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  1717. var _this = this;
  1718. if (bufferView._babylonBuffer) {
  1719. return bufferView._babylonBuffer;
  1720. }
  1721. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  1722. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  1723. });
  1724. return bufferView._babylonBuffer;
  1725. };
  1726. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  1727. var _this = this;
  1728. if (accessor._babylonVertexBuffer) {
  1729. return accessor._babylonVertexBuffer;
  1730. }
  1731. if (accessor.sparse) {
  1732. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  1733. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  1734. });
  1735. }
  1736. else {
  1737. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  1738. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  1739. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  1740. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  1741. });
  1742. }
  1743. return accessor._babylonVertexBuffer;
  1744. };
  1745. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  1746. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  1747. if (!babylonMaterial) {
  1748. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  1749. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  1750. babylonMaterial.metallic = 1;
  1751. babylonMaterial.roughness = 1;
  1752. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1753. }
  1754. return babylonMaterial;
  1755. };
  1756. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  1757. var promises = new Array();
  1758. // Ensure metallic workflow
  1759. babylonMaterial.metallic = 1;
  1760. babylonMaterial.roughness = 1;
  1761. var properties = material.pbrMetallicRoughness;
  1762. if (properties) {
  1763. if (properties.baseColorFactor) {
  1764. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  1765. babylonMaterial.alpha = properties.baseColorFactor[3];
  1766. }
  1767. else {
  1768. babylonMaterial.albedoColor = BABYLON.Color3.White();
  1769. }
  1770. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  1771. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  1772. if (properties.baseColorTexture) {
  1773. promises.push(this._loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  1774. babylonMaterial.albedoTexture = texture;
  1775. }));
  1776. }
  1777. if (properties.metallicRoughnessTexture) {
  1778. promises.push(this._loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  1779. babylonMaterial.metallicTexture = texture;
  1780. }));
  1781. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1782. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1783. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1784. }
  1785. }
  1786. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  1787. return Promise.all(promises).then(function () { });
  1788. };
  1789. GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  1790. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);
  1791. if (extensionPromise) {
  1792. return extensionPromise;
  1793. }
  1794. material._babylonData = material._babylonData || {};
  1795. var babylonData = material._babylonData[babylonDrawMode];
  1796. if (!babylonData) {
  1797. this._parent._logOpen(context + " " + (material.name || ""));
  1798. var name_4 = material.name || "material" + material._index;
  1799. var babylonMaterial = this._createMaterial(name_4, babylonDrawMode);
  1800. babylonData = {
  1801. material: babylonMaterial,
  1802. meshes: [],
  1803. loaded: this._loadMaterialPropertiesAsync(context, material, babylonMaterial)
  1804. };
  1805. material._babylonData[babylonDrawMode] = babylonData;
  1806. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1807. this._parent._logClose();
  1808. }
  1809. babylonData.meshes.push(babylonMesh);
  1810. babylonMesh.onDisposeObservable.addOnce(function () {
  1811. var index = babylonData.meshes.indexOf(babylonMesh);
  1812. if (index !== -1) {
  1813. babylonData.meshes.splice(index, 1);
  1814. }
  1815. });
  1816. assign(babylonData.material);
  1817. return babylonData.loaded;
  1818. };
  1819. GLTFLoader.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  1820. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadMaterialPropertiesAsync(this, context, material, babylonMaterial);
  1821. if (extensionPromise) {
  1822. return extensionPromise;
  1823. }
  1824. var promises = new Array();
  1825. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  1826. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  1827. return Promise.all(promises).then(function () { });
  1828. };
  1829. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  1830. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  1831. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  1832. babylonMaterial.fillMode = drawMode;
  1833. babylonMaterial.enableSpecularAntiAliasing = true;
  1834. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  1835. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  1836. return babylonMaterial;
  1837. };
  1838. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  1839. var promises = new Array();
  1840. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1841. if (material.doubleSided) {
  1842. babylonMaterial.backFaceCulling = false;
  1843. babylonMaterial.twoSidedLighting = true;
  1844. }
  1845. if (material.normalTexture) {
  1846. promises.push(this._loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  1847. babylonMaterial.bumpTexture = texture;
  1848. }));
  1849. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1850. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1851. if (material.normalTexture.scale != undefined) {
  1852. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1853. }
  1854. }
  1855. if (material.occlusionTexture) {
  1856. promises.push(this._loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  1857. babylonMaterial.ambientTexture = texture;
  1858. }));
  1859. babylonMaterial.useAmbientInGrayScale = true;
  1860. if (material.occlusionTexture.strength != undefined) {
  1861. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1862. }
  1863. }
  1864. if (material.emissiveTexture) {
  1865. promises.push(this._loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  1866. babylonMaterial.emissiveTexture = texture;
  1867. }));
  1868. }
  1869. return Promise.all(promises).then(function () { });
  1870. };
  1871. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  1872. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  1873. switch (alphaMode) {
  1874. case "OPAQUE" /* OPAQUE */: {
  1875. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  1876. break;
  1877. }
  1878. case "MASK" /* MASK */: {
  1879. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  1880. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  1881. if (babylonMaterial.albedoTexture) {
  1882. babylonMaterial.albedoTexture.hasAlpha = true;
  1883. }
  1884. break;
  1885. }
  1886. case "BLEND" /* BLEND */: {
  1887. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  1888. if (babylonMaterial.albedoTexture) {
  1889. babylonMaterial.albedoTexture.hasAlpha = true;
  1890. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1891. }
  1892. break;
  1893. }
  1894. default: {
  1895. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  1896. }
  1897. }
  1898. };
  1899. GLTFLoader.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) {
  1900. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadTextureInfoAsync(this, context, textureInfo, assign);
  1901. if (extensionPromise) {
  1902. return extensionPromise;
  1903. }
  1904. this._parent._logOpen("" + context);
  1905. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  1906. var promise = this._loadTextureAsync("#/textures/" + textureInfo.index, texture, function (babylonTexture) {
  1907. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  1908. assign(babylonTexture);
  1909. });
  1910. this._parent._logClose();
  1911. return promise;
  1912. };
  1913. GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) {
  1914. var _this = this;
  1915. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, texture, assign);
  1916. if (extensionPromise) {
  1917. return extensionPromise;
  1918. }
  1919. var promises = new Array();
  1920. this._parent._logOpen(context + " " + (texture.name || ""));
  1921. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  1922. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  1923. var deferred = new BABYLON.Deferred();
  1924. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  1925. if (!_this._disposed) {
  1926. deferred.resolve();
  1927. }
  1928. }, function (message, exception) {
  1929. if (!_this._disposed) {
  1930. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  1931. }
  1932. });
  1933. promises.push(deferred.promise);
  1934. babylonTexture.name = texture.name || "texture" + texture._index;
  1935. babylonTexture.wrapU = samplerData.wrapU;
  1936. babylonTexture.wrapV = samplerData.wrapV;
  1937. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  1938. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (data) {
  1939. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  1940. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  1941. }));
  1942. assign(babylonTexture);
  1943. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  1944. this._parent._logClose();
  1945. return Promise.all(promises).then(function () { });
  1946. };
  1947. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  1948. if (!sampler._data) {
  1949. sampler._data = {
  1950. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  1951. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  1952. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  1953. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  1954. };
  1955. }
  1956. ;
  1957. return sampler._data;
  1958. };
  1959. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  1960. if (!image._data) {
  1961. this._parent._logOpen(context + " " + (image.name || ""));
  1962. if (image.uri) {
  1963. image._data = this._loadUriAsync(context, image.uri);
  1964. }
  1965. else {
  1966. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  1967. image._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  1968. }
  1969. this._parent._logClose();
  1970. }
  1971. return image._data;
  1972. };
  1973. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  1974. var _this = this;
  1975. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  1976. if (extensionPromise) {
  1977. return extensionPromise;
  1978. }
  1979. if (!GLTFLoader._ValidateUri(uri)) {
  1980. throw new Error(context + ": Uri '" + uri + "' is invalid");
  1981. }
  1982. if (BABYLON.Tools.IsBase64(uri)) {
  1983. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  1984. this._parent._log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  1985. return Promise.resolve(data);
  1986. }
  1987. this._parent._log("Loading " + uri);
  1988. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  1989. return new Promise(function (resolve, reject) {
  1990. if (!_this._disposed) {
  1991. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  1992. if (!_this._disposed) {
  1993. var data = new Uint8Array(fileData);
  1994. _this._parent._log("Loaded " + uri + " (" + data.length + " bytes)");
  1995. resolve(data);
  1996. }
  1997. }, function (event) {
  1998. if (!_this._disposed) {
  1999. if (request_1) {
  2000. request_1._lengthComputable = event.lengthComputable;
  2001. request_1._loaded = event.loaded;
  2002. request_1._total = event.total;
  2003. }
  2004. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  2005. try {
  2006. _this._onProgress();
  2007. }
  2008. catch (e) {
  2009. reject(e);
  2010. }
  2011. }
  2012. }
  2013. }, _this._babylonScene.database, true, function (request, exception) {
  2014. if (!_this._disposed) {
  2015. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  2016. }
  2017. });
  2018. _this._requests.push(request_1);
  2019. }
  2020. });
  2021. });
  2022. };
  2023. GLTFLoader.prototype._onProgress = function () {
  2024. if (!this._progressCallback) {
  2025. return;
  2026. }
  2027. var lengthComputable = true;
  2028. var loaded = 0;
  2029. var total = 0;
  2030. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  2031. var request = _a[_i];
  2032. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  2033. return;
  2034. }
  2035. lengthComputable = lengthComputable && request._lengthComputable;
  2036. loaded += request._loaded;
  2037. total += request._total;
  2038. }
  2039. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  2040. };
  2041. GLTFLoader._GetProperty = function (context, array, index) {
  2042. if (!array || index == undefined || !array[index]) {
  2043. throw new Error(context + ": Failed to find index (" + index + ")");
  2044. }
  2045. return array[index];
  2046. };
  2047. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  2048. // Set defaults if undefined
  2049. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  2050. switch (mode) {
  2051. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2052. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2053. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2054. default:
  2055. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  2056. return BABYLON.Texture.WRAP_ADDRESSMODE;
  2057. }
  2058. };
  2059. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  2060. // Set defaults if undefined
  2061. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  2062. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  2063. if (magFilter === 9729 /* LINEAR */) {
  2064. switch (minFilter) {
  2065. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  2066. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  2067. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  2068. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  2069. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  2070. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  2071. default:
  2072. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  2073. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  2074. }
  2075. }
  2076. else {
  2077. if (magFilter !== 9728 /* NEAREST */) {
  2078. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  2079. }
  2080. switch (minFilter) {
  2081. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  2082. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  2083. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  2084. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  2085. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  2086. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  2087. default:
  2088. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  2089. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  2090. }
  2091. }
  2092. };
  2093. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  2094. var buffer = bufferView.buffer;
  2095. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  2096. try {
  2097. switch (componentType) {
  2098. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  2099. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  2100. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  2101. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  2102. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  2103. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  2104. default: throw new Error("Invalid component type " + componentType);
  2105. }
  2106. }
  2107. catch (e) {
  2108. throw new Error(context + ": " + e);
  2109. }
  2110. };
  2111. GLTFLoader._GetNumComponents = function (context, type) {
  2112. switch (type) {
  2113. case "SCALAR": return 1;
  2114. case "VEC2": return 2;
  2115. case "VEC3": return 3;
  2116. case "VEC4": return 4;
  2117. case "MAT2": return 4;
  2118. case "MAT3": return 9;
  2119. case "MAT4": return 16;
  2120. }
  2121. throw new Error(context + ": Invalid type (" + type + ")");
  2122. };
  2123. GLTFLoader._ValidateUri = function (uri) {
  2124. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  2125. };
  2126. GLTFLoader._GetDrawMode = function (context, mode) {
  2127. if (mode == undefined) {
  2128. mode = 4 /* TRIANGLES */;
  2129. }
  2130. switch (mode) {
  2131. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  2132. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  2133. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  2134. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  2135. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  2136. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  2137. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  2138. }
  2139. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  2140. };
  2141. GLTFLoader.prototype._compileMaterialsAsync = function () {
  2142. var _this = this;
  2143. this._parent._startPerformanceCounter("Compile materials");
  2144. var promises = new Array();
  2145. if (this._gltf.materials) {
  2146. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  2147. var material = _a[_i];
  2148. if (material._babylonData) {
  2149. for (var babylonDrawMode in material._babylonData) {
  2150. var babylonData = material._babylonData[babylonDrawMode];
  2151. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  2152. var babylonMesh = _c[_b];
  2153. // Ensure nonUniformScaling is set if necessary.
  2154. babylonMesh.computeWorldMatrix(true);
  2155. var babylonMaterial = babylonData.material;
  2156. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  2157. if (this._parent.useClipPlane) {
  2158. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  2159. }
  2160. }
  2161. }
  2162. }
  2163. }
  2164. }
  2165. return Promise.all(promises).then(function () {
  2166. _this._parent._endPerformanceCounter("Compile materials");
  2167. });
  2168. };
  2169. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  2170. var _this = this;
  2171. this._parent._startPerformanceCounter("Compile shadow generators");
  2172. var promises = new Array();
  2173. var lights = this._babylonScene.lights;
  2174. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  2175. var light = lights_1[_i];
  2176. var generator = light.getShadowGenerator();
  2177. if (generator) {
  2178. promises.push(generator.forceCompilationAsync());
  2179. }
  2180. }
  2181. return Promise.all(promises).then(function () {
  2182. _this._parent._endPerformanceCounter("Compile shadow generators");
  2183. });
  2184. };
  2185. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  2186. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  2187. var name_5 = _a[_i];
  2188. var extension = this._extensions[name_5];
  2189. if (extension.enabled) {
  2190. var promise = actionAsync(extension);
  2191. if (promise) {
  2192. return promise;
  2193. }
  2194. }
  2195. }
  2196. return null;
  2197. };
  2198. GLTFLoader.prototype._forEachExtensions = function (action) {
  2199. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  2200. var name_6 = _a[_i];
  2201. var extension = this._extensions[name_6];
  2202. if (extension.enabled) {
  2203. action(extension);
  2204. }
  2205. }
  2206. };
  2207. GLTFLoader._ExtensionNames = new Array();
  2208. GLTFLoader._ExtensionFactories = {};
  2209. return GLTFLoader;
  2210. }());
  2211. GLTF2.GLTFLoader = GLTFLoader;
  2212. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  2213. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2214. })(BABYLON || (BABYLON = {}));
  2215. //# sourceMappingURL=babylon.glTFLoader.js.map
  2216. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2217. var BABYLON;
  2218. (function (BABYLON) {
  2219. var GLTF2;
  2220. (function (GLTF2) {
  2221. /**
  2222. * Abstract class that can be implemented to extend existing glTF loader behavior.
  2223. */
  2224. var GLTFLoaderExtension = /** @class */ (function () {
  2225. /**
  2226. * Creates new GLTFLoaderExtension
  2227. * @param loader defines the GLTFLoader to use
  2228. */
  2229. function GLTFLoaderExtension(loader) {
  2230. /**
  2231. * Gets or sets a boolean indicating if the extension is enabled
  2232. */
  2233. this.enabled = true;
  2234. this._loader = loader;
  2235. }
  2236. /**
  2237. * Release all resources
  2238. */
  2239. GLTFLoaderExtension.prototype.dispose = function () {
  2240. delete this._loader;
  2241. };
  2242. // #region Overridable Methods
  2243. /**
  2244. * Override this method to do work after the state changes to LOADING.
  2245. */
  2246. GLTFLoaderExtension.prototype._onLoading = function () { };
  2247. /**
  2248. * Override this method to do work after the state changes to READY.
  2249. */
  2250. GLTFLoaderExtension.prototype._onReady = function () { };
  2251. /**
  2252. * Override this method to modify the default behavior for loading scenes.
  2253. * @hidden
  2254. */
  2255. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  2256. /**
  2257. * Override this method to modify the default behavior for loading nodes.
  2258. * @hidden
  2259. */
  2260. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  2261. /**
  2262. * Override this method to modify the default behavior for loading mesh primitive vertex data.
  2263. * @hidden
  2264. */
  2265. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  2266. /**
  2267. * Override this method to modify the default behavior for loading materials.
  2268. * @hidden
  2269. */
  2270. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };
  2271. /**
  2272. * Override this method to modify the default behavior for loading material properties.
  2273. * @hidden
  2274. */
  2275. GLTFLoaderExtension.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { return null; };
  2276. /**
  2277. * Override this method to modify the default behavior for loading texture infos.
  2278. * @hidden
  2279. */
  2280. GLTFLoaderExtension.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) { return null; };
  2281. /**
  2282. * Override this method to modify the default behavior for loading textures.
  2283. * @hidden
  2284. */
  2285. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, texture, assign) { return null; };
  2286. /**
  2287. * Override this method to modify the default behavior for loading uris.
  2288. * @hidden
  2289. */
  2290. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  2291. /** Override this method to modify the default behavior for loading animations. */
  2292. GLTFLoaderExtension.prototype._loadAnimationAsync = function (context, animation) { return null; };
  2293. // #endregion
  2294. /**
  2295. * Helper method called by a loader extension to load an glTF extension.
  2296. * @hidden
  2297. */
  2298. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  2299. if (!property.extensions) {
  2300. return null;
  2301. }
  2302. var extensions = property.extensions;
  2303. var extension = extensions[this.name];
  2304. if (!extension) {
  2305. return null;
  2306. }
  2307. // Clear out the extension before executing the action to avoid infinite recursion.
  2308. delete extensions[this.name];
  2309. try {
  2310. return actionAsync(context + "/extensions/" + this.name, extension);
  2311. }
  2312. finally {
  2313. // Restore the extension after executing the action.
  2314. extensions[this.name] = extension;
  2315. }
  2316. };
  2317. /**
  2318. * Helper method called by the loader to allow extensions to override loading scenes.
  2319. * @hidden
  2320. */
  2321. GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {
  2322. if (!property.extras) {
  2323. return null;
  2324. }
  2325. var extras = property.extras;
  2326. var value = extras[this.name];
  2327. if (value === undefined) {
  2328. return null;
  2329. }
  2330. // Clear out the extras value before executing the action to avoid infinite recursion.
  2331. delete extras[this.name];
  2332. try {
  2333. return actionAsync(context + "/extras/" + this.name, value);
  2334. }
  2335. finally {
  2336. // Restore the extras value after executing the action.
  2337. extras[this.name] = value;
  2338. }
  2339. };
  2340. /**
  2341. * Helper method called by the loader after the state changes to LOADING.
  2342. * @hidden
  2343. */
  2344. GLTFLoaderExtension._OnLoading = function (loader) {
  2345. loader._forEachExtensions(function (extension) { return extension._onLoading(); });
  2346. };
  2347. /**
  2348. * Helper method called by the loader after the state changes to READY.
  2349. * @hidden
  2350. */
  2351. GLTFLoaderExtension._OnReady = function (loader) {
  2352. loader._forEachExtensions(function (extension) { return extension._onReady(); });
  2353. };
  2354. /**
  2355. * Helper method called by the loader to allow extensions to override loading scenes.
  2356. * @hidden
  2357. */
  2358. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  2359. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  2360. };
  2361. /**
  2362. * Helper method called by the loader to allow extensions to override loading nodes.
  2363. * @hidden
  2364. */
  2365. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  2366. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  2367. };
  2368. /**
  2369. * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.
  2370. * @hidden
  2371. */
  2372. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  2373. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  2374. };
  2375. /**
  2376. * Helper method called by the loader to allow extensions to override loading materials.
  2377. * @hidden
  2378. */
  2379. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  2380. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });
  2381. };
  2382. /**
  2383. * Helper method called by the loader to allow extensions to override loading material properties.
  2384. * @hidden
  2385. */
  2386. GLTFLoaderExtension._LoadMaterialPropertiesAsync = function (loader, context, material, babylonMaterial) {
  2387. return loader._applyExtensions(function (extension) { return extension._loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  2388. };
  2389. /**
  2390. * Helper method called by the loader to allow extensions to override loading texture infos.
  2391. * @hidden
  2392. */
  2393. GLTFLoaderExtension._LoadTextureInfoAsync = function (loader, context, textureInfo, assign) {
  2394. return loader._applyExtensions(function (extension) { return extension._loadTextureInfoAsync(context, textureInfo, assign); });
  2395. };
  2396. /**
  2397. * Helper method called by the loader to allow extensions to override loading textures.
  2398. * @hidden
  2399. */
  2400. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, texture, assign) {
  2401. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, texture, assign); });
  2402. };
  2403. /**
  2404. * Helper method called by the loader to allow extensions to override loading uris.
  2405. * @hidden
  2406. */
  2407. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  2408. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  2409. };
  2410. /**
  2411. * Helper method called by the loader to allow extensions to override loading animations.
  2412. * @hidden
  2413. */
  2414. GLTFLoaderExtension._LoadAnimationAsync = function (loader, context, animation) {
  2415. return loader._applyExtensions(function (extension) { return extension._loadAnimationAsync(context, animation); });
  2416. };
  2417. return GLTFLoaderExtension;
  2418. }());
  2419. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  2420. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2421. })(BABYLON || (BABYLON = {}));
  2422. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2423. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2424. var __extends = (this && this.__extends) || (function () {
  2425. var extendStatics = Object.setPrototypeOf ||
  2426. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2427. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2428. return function (d, b) {
  2429. extendStatics(d, b);
  2430. function __() { this.constructor = d; }
  2431. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2432. };
  2433. })();
  2434. var BABYLON;
  2435. (function (BABYLON) {
  2436. var GLTF2;
  2437. (function (GLTF2) {
  2438. var Extensions;
  2439. (function (Extensions) {
  2440. var NAME = "MSFT_audio_emitter";
  2441. /**
  2442. * [Specification](https://github.com/najadojo/glTF/tree/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter)
  2443. */
  2444. var MSFT_audio_emitter = /** @class */ (function (_super) {
  2445. __extends(MSFT_audio_emitter, _super);
  2446. function MSFT_audio_emitter() {
  2447. var _this = _super !== null && _super.apply(this, arguments) || this;
  2448. _this.name = NAME;
  2449. return _this;
  2450. }
  2451. MSFT_audio_emitter.prototype._loadClipAsync = function (context, clip) {
  2452. if (clip._objectURL) {
  2453. return clip._objectURL;
  2454. }
  2455. var promise;
  2456. if (clip.uri) {
  2457. promise = this._loader._loadUriAsync(context, clip.uri);
  2458. }
  2459. else {
  2460. var bufferView = GLTF2.GLTFLoader._GetProperty(context + "/bufferView", this._loader._gltf.bufferViews, clip.bufferView);
  2461. promise = this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  2462. }
  2463. clip._objectURL = promise.then(function (data) {
  2464. return URL.createObjectURL(new Blob([data], { type: clip.mimeType }));
  2465. });
  2466. return clip._objectURL;
  2467. };
  2468. MSFT_audio_emitter.prototype._loadEmitterAsync = function (context, emitter) {
  2469. var _this = this;
  2470. emitter._babylonSounds = emitter._babylonSounds || [];
  2471. if (!emitter._babylonData) {
  2472. var clipPromises = new Array();
  2473. var name_1 = emitter.name || "emitter" + emitter._index;
  2474. var options_1 = {
  2475. loop: false,
  2476. autoplay: false,
  2477. volume: emitter.volume == undefined ? 1 : emitter.volume,
  2478. };
  2479. GLTF2._ArrayItem.Assign(this._clips);
  2480. var _loop_1 = function (i) {
  2481. var clipContext = "#/extensions/" + NAME + "/clips";
  2482. var clip = GLTF2.GLTFLoader._GetProperty(clipContext, this_1._clips, emitter.clips[i].clip);
  2483. clipPromises.push(this_1._loadClipAsync(clipContext + "/" + emitter.clips[i].clip, clip).then(function (objectURL) {
  2484. var sound = emitter._babylonSounds[i] = new BABYLON.Sound(name_1, objectURL, _this._loader._babylonScene, null, options_1);
  2485. sound.refDistance = emitter.refDistance || 1;
  2486. sound.maxDistance = emitter.maxDistance || 256;
  2487. sound.rolloffFactor = emitter.rolloffFactor || 1;
  2488. sound.distanceModel = emitter.distanceModel || 'exponential';
  2489. sound._positionInEmitterSpace = true;
  2490. }));
  2491. };
  2492. var this_1 = this;
  2493. for (var i = 0; i < emitter.clips.length; i++) {
  2494. _loop_1(i);
  2495. }
  2496. var promise = Promise.all(clipPromises).then(function () {
  2497. var weights = emitter.clips.map(function (clip) { return clip.weight || 1; });
  2498. var weightedSound = new BABYLON.WeightedSound(emitter.loop || false, emitter._babylonSounds, weights);
  2499. if (emitter.innerAngle)
  2500. weightedSound.directionalConeInnerAngle = 2 * BABYLON.Tools.ToDegrees(emitter.innerAngle);
  2501. if (emitter.outerAngle)
  2502. weightedSound.directionalConeOuterAngle = 2 * BABYLON.Tools.ToDegrees(emitter.outerAngle);
  2503. if (emitter.volume)
  2504. weightedSound.volume = emitter.volume;
  2505. emitter._babylonData.sound = weightedSound;
  2506. });
  2507. emitter._babylonData = {
  2508. loaded: promise
  2509. };
  2510. }
  2511. return emitter._babylonData.loaded;
  2512. };
  2513. MSFT_audio_emitter.prototype._loadSceneAsync = function (context, scene) {
  2514. var _this = this;
  2515. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  2516. return _this._loader._loadSceneAsync(context, scene).then(function () {
  2517. var promises = new Array();
  2518. GLTF2._ArrayItem.Assign(_this._emitters);
  2519. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  2520. var emitterIndex = _a[_i];
  2521. var emitter = GLTF2.GLTFLoader._GetProperty(extensionContext + "/emitters", _this._emitters, emitterIndex);
  2522. if (emitter.refDistance != undefined || emitter.maxDistance != undefined || emitter.rolloffFactor != undefined ||
  2523. emitter.distanceModel != undefined || emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  2524. throw new Error(extensionContext + ": Direction or Distance properties are not allowed on emitters attached to a scene");
  2525. }
  2526. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter._index, emitter));
  2527. }
  2528. return Promise.all(promises).then(function () { });
  2529. });
  2530. });
  2531. };
  2532. MSFT_audio_emitter.prototype._loadNodeAsync = function (context, node) {
  2533. var _this = this;
  2534. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  2535. return _this._loader._loadNodeAsync(extensionContext, node).then(function () {
  2536. var promises = new Array();
  2537. GLTF2._ArrayItem.Assign(_this._emitters);
  2538. var _loop_2 = function (emitterIndex) {
  2539. var emitter = GLTF2.GLTFLoader._GetProperty(extensionContext + "/emitters", _this._emitters, emitterIndex);
  2540. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter._index, emitter).then(function () {
  2541. if (node._babylonMesh) {
  2542. for (var _i = 0, _a = emitter._babylonSounds; _i < _a.length; _i++) {
  2543. var sound = _a[_i];
  2544. sound.attachToMesh(node._babylonMesh);
  2545. if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  2546. sound.setLocalDirectionToMesh(new BABYLON.Vector3(0, 0, 1));
  2547. sound.setDirectionalCone(2 * BABYLON.Tools.ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle), 2 * BABYLON.Tools.ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle), 0);
  2548. }
  2549. }
  2550. }
  2551. }));
  2552. };
  2553. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  2554. var emitterIndex = _a[_i];
  2555. _loop_2(emitterIndex);
  2556. }
  2557. return Promise.all(promises).then(function () { });
  2558. });
  2559. });
  2560. };
  2561. MSFT_audio_emitter.prototype._loadAnimationAsync = function (context, animation) {
  2562. var _this = this;
  2563. return this._loadExtensionAsync(context, animation, function (extensionContext, extension) {
  2564. return _this._loader._loadAnimationAsync(extensionContext, animation).then(function () {
  2565. var promises = new Array();
  2566. var babylonAnimationGroup = animation._babylonAnimationGroup;
  2567. GLTF2._ArrayItem.Assign(extension.events);
  2568. for (var _i = 0, _a = extension.events; _i < _a.length; _i++) {
  2569. var event_1 = _a[_i];
  2570. promises.push(_this._loadAnimationEventAsync(extensionContext + "/events/" + event_1._index, context, animation, event_1, babylonAnimationGroup));
  2571. }
  2572. return Promise.all(promises).then(function () { });
  2573. });
  2574. });
  2575. };
  2576. MSFT_audio_emitter.prototype._getEventAction = function (context, sound, action, time, startOffset) {
  2577. if (action == "play" /* play */) {
  2578. return function (currentFrame) {
  2579. var frameOffset = (startOffset || 0) + (currentFrame - time);
  2580. sound.play(frameOffset);
  2581. };
  2582. }
  2583. else if (action == "stop" /* stop */) {
  2584. return function (currentFrame) {
  2585. sound.stop();
  2586. };
  2587. }
  2588. else if (action == "pause" /* pause */) {
  2589. return function (currentFrame) {
  2590. sound.pause();
  2591. };
  2592. }
  2593. else {
  2594. throw new Error(context + ": Unsupported action " + action);
  2595. }
  2596. };
  2597. MSFT_audio_emitter.prototype._loadAnimationEventAsync = function (context, animationContext, animation, event, babylonAnimationGroup) {
  2598. var _this = this;
  2599. if (babylonAnimationGroup.targetedAnimations.length == 0) {
  2600. return Promise.resolve();
  2601. }
  2602. var babylonAnimation = babylonAnimationGroup.targetedAnimations[0];
  2603. var emitterIndex = event.emitter;
  2604. var emitter = GLTF2.GLTFLoader._GetProperty("#/extensions/" + NAME + "/emitters", this._emitters, emitterIndex);
  2605. return this._loadEmitterAsync(context, emitter).then(function () {
  2606. var sound = emitter._babylonData.sound;
  2607. if (sound) {
  2608. var babylonAnimationEvent = new BABYLON.AnimationEvent(event.time, _this._getEventAction(context, sound, event.action, event.time, event.startOffset));
  2609. babylonAnimation.animation.addEvent(babylonAnimationEvent);
  2610. // Make sure all started audio stops when this animation is terminated.
  2611. babylonAnimationGroup.onAnimationGroupEndObservable.add(function () {
  2612. sound.stop();
  2613. });
  2614. babylonAnimationGroup.onAnimationGroupPauseObservable.add(function () {
  2615. sound.pause();
  2616. });
  2617. }
  2618. });
  2619. };
  2620. Object.defineProperty(MSFT_audio_emitter.prototype, "_extension", {
  2621. get: function () {
  2622. var extensions = this._loader._gltf.extensions;
  2623. if (!extensions || !extensions[this.name]) {
  2624. throw new Error("#/extensions: '" + this.name + "' not found");
  2625. }
  2626. return extensions[this.name];
  2627. },
  2628. enumerable: true,
  2629. configurable: true
  2630. });
  2631. Object.defineProperty(MSFT_audio_emitter.prototype, "_clips", {
  2632. get: function () {
  2633. return this._extension.clips;
  2634. },
  2635. enumerable: true,
  2636. configurable: true
  2637. });
  2638. Object.defineProperty(MSFT_audio_emitter.prototype, "_emitters", {
  2639. get: function () {
  2640. return this._extension.emitters;
  2641. },
  2642. enumerable: true,
  2643. configurable: true
  2644. });
  2645. return MSFT_audio_emitter;
  2646. }(GLTF2.GLTFLoaderExtension));
  2647. Extensions.MSFT_audio_emitter = MSFT_audio_emitter;
  2648. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_audio_emitter(loader); });
  2649. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2650. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2651. })(BABYLON || (BABYLON = {}));
  2652. //# sourceMappingURL=MSFT_audio_emitter.js.map
  2653. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2654. var __extends = (this && this.__extends) || (function () {
  2655. var extendStatics = Object.setPrototypeOf ||
  2656. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2657. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2658. return function (d, b) {
  2659. extendStatics(d, b);
  2660. function __() { this.constructor = d; }
  2661. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2662. };
  2663. })();
  2664. var BABYLON;
  2665. (function (BABYLON) {
  2666. var GLTF2;
  2667. (function (GLTF2) {
  2668. var Extensions;
  2669. (function (Extensions) {
  2670. var NAME = "MSFT_lod";
  2671. /**
  2672. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  2673. */
  2674. var MSFT_lod = /** @class */ (function (_super) {
  2675. __extends(MSFT_lod, _super);
  2676. function MSFT_lod() {
  2677. var _this = _super !== null && _super.apply(this, arguments) || this;
  2678. _this.name = NAME;
  2679. /**
  2680. * Maximum number of LODs to load, starting from the lowest LOD.
  2681. */
  2682. _this.maxLODsToLoad = Number.MAX_VALUE;
  2683. /**
  2684. * Observable raised when all node LODs of one level are loaded.
  2685. * The event data is the index of the loaded LOD starting from zero.
  2686. * Dispose the loader to cancel the loading of the next level of LODs.
  2687. */
  2688. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  2689. /**
  2690. * Observable raised when all material LODs of one level are loaded.
  2691. * The event data is the index of the loaded LOD starting from zero.
  2692. * Dispose the loader to cancel the loading of the next level of LODs.
  2693. */
  2694. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  2695. _this._nodeIndexLOD = null;
  2696. _this._nodeSignalLODs = new Array();
  2697. _this._nodePromiseLODs = new Array();
  2698. _this._materialIndexLOD = null;
  2699. _this._materialSignalLODs = new Array();
  2700. _this._materialPromiseLODs = new Array();
  2701. return _this;
  2702. }
  2703. MSFT_lod.prototype.dispose = function () {
  2704. _super.prototype.dispose.call(this);
  2705. this._nodeIndexLOD = null;
  2706. this._nodeSignalLODs.length = 0;
  2707. this._nodePromiseLODs.length = 0;
  2708. this._materialIndexLOD = null;
  2709. this._materialSignalLODs.length = 0;
  2710. this._materialPromiseLODs.length = 0;
  2711. this.onMaterialLODsLoadedObservable.clear();
  2712. this.onNodeLODsLoadedObservable.clear();
  2713. };
  2714. MSFT_lod.prototype._onReady = function () {
  2715. var _this = this;
  2716. var _loop_1 = function (indexLOD) {
  2717. var promise = Promise.all(this_1._nodePromiseLODs[indexLOD]).then(function () {
  2718. if (indexLOD !== 0) {
  2719. _this._loader._parent._endPerformanceCounter("Node LOD " + indexLOD);
  2720. }
  2721. _this._loader._parent._log("Loaded node LOD " + indexLOD);
  2722. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  2723. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  2724. _this._loader._parent._startPerformanceCounter("Node LOD " + (indexLOD + 1));
  2725. if (_this._nodeSignalLODs[indexLOD]) {
  2726. _this._nodeSignalLODs[indexLOD].resolve();
  2727. }
  2728. }
  2729. });
  2730. this_1._loader._completePromises.push(promise);
  2731. };
  2732. var this_1 = this;
  2733. for (var indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {
  2734. _loop_1(indexLOD);
  2735. }
  2736. var _loop_2 = function (indexLOD) {
  2737. var promise = Promise.all(this_2._materialPromiseLODs[indexLOD]).then(function () {
  2738. if (indexLOD !== 0) {
  2739. _this._loader._parent._endPerformanceCounter("Material LOD " + indexLOD);
  2740. }
  2741. _this._loader._parent._log("Loaded material LOD " + indexLOD);
  2742. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  2743. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  2744. _this._loader._parent._startPerformanceCounter("Material LOD " + (indexLOD + 1));
  2745. if (_this._materialSignalLODs[indexLOD]) {
  2746. _this._materialSignalLODs[indexLOD].resolve();
  2747. }
  2748. }
  2749. });
  2750. this_2._loader._completePromises.push(promise);
  2751. };
  2752. var this_2 = this;
  2753. for (var indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {
  2754. _loop_2(indexLOD);
  2755. }
  2756. };
  2757. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  2758. var _this = this;
  2759. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  2760. var firstPromise;
  2761. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  2762. _this._loader._parent._logOpen("" + extensionContext);
  2763. var _loop_3 = function (indexLOD) {
  2764. var nodeLOD = nodeLODs[indexLOD];
  2765. if (indexLOD !== 0) {
  2766. _this._nodeIndexLOD = indexLOD;
  2767. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  2768. }
  2769. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  2770. if (indexLOD !== 0) {
  2771. var previousNodeLOD = nodeLODs[indexLOD - 1];
  2772. if (previousNodeLOD._babylonMesh) {
  2773. previousNodeLOD._babylonMesh.dispose();
  2774. delete previousNodeLOD._babylonMesh;
  2775. _this._disposeUnusedMaterials();
  2776. }
  2777. }
  2778. });
  2779. if (indexLOD === 0) {
  2780. firstPromise = promise;
  2781. }
  2782. else {
  2783. _this._nodeIndexLOD = null;
  2784. }
  2785. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  2786. _this._nodePromiseLODs[indexLOD].push(promise);
  2787. };
  2788. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  2789. _loop_3(indexLOD);
  2790. }
  2791. _this._loader._parent._logClose();
  2792. return firstPromise;
  2793. });
  2794. };
  2795. MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  2796. var _this = this;
  2797. // Don't load material LODs if already loading a node LOD.
  2798. if (this._nodeIndexLOD) {
  2799. return null;
  2800. }
  2801. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  2802. var firstPromise;
  2803. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  2804. _this._loader._parent._logOpen("" + extensionContext);
  2805. var _loop_4 = function (indexLOD) {
  2806. var materialLOD = materialLODs[indexLOD];
  2807. if (indexLOD !== 0) {
  2808. _this._materialIndexLOD = indexLOD;
  2809. }
  2810. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  2811. if (indexLOD !== 0) {
  2812. var babylonDataLOD = materialLOD._babylonData;
  2813. assign(babylonDataLOD[babylonDrawMode].material);
  2814. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  2815. if (previousBabylonDataLOD[babylonDrawMode]) {
  2816. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  2817. delete previousBabylonDataLOD[babylonDrawMode];
  2818. }
  2819. }
  2820. });
  2821. if (indexLOD === 0) {
  2822. firstPromise = promise;
  2823. }
  2824. else {
  2825. _this._materialIndexLOD = null;
  2826. }
  2827. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  2828. _this._materialPromiseLODs[indexLOD].push(promise);
  2829. };
  2830. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  2831. _loop_4(indexLOD);
  2832. }
  2833. _this._loader._parent._logClose();
  2834. return firstPromise;
  2835. });
  2836. };
  2837. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  2838. var _this = this;
  2839. // Defer the loading of uris if loading a material or node LOD.
  2840. if (this._materialIndexLOD !== null) {
  2841. this._loader._parent._log("deferred");
  2842. var previousIndexLOD = this._materialIndexLOD - 1;
  2843. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  2844. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  2845. return _this._loader._loadUriAsync(context, uri);
  2846. });
  2847. }
  2848. else if (this._nodeIndexLOD !== null) {
  2849. this._loader._parent._log("deferred");
  2850. var previousIndexLOD = this._nodeIndexLOD - 1;
  2851. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  2852. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  2853. return _this._loader._loadUriAsync(context, uri);
  2854. });
  2855. }
  2856. return null;
  2857. };
  2858. /**
  2859. * Gets an array of LOD properties from lowest to highest.
  2860. */
  2861. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  2862. if (this.maxLODsToLoad <= 0) {
  2863. throw new Error("maxLODsToLoad must be greater than zero");
  2864. }
  2865. var properties = new Array();
  2866. for (var i = ids.length - 1; i >= 0; i--) {
  2867. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  2868. if (properties.length === this.maxLODsToLoad) {
  2869. return properties;
  2870. }
  2871. }
  2872. properties.push(property);
  2873. return properties;
  2874. };
  2875. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  2876. var materials = this._loader._gltf.materials;
  2877. if (materials) {
  2878. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  2879. var material = materials_1[_i];
  2880. if (material._babylonData) {
  2881. for (var drawMode in material._babylonData) {
  2882. var babylonData = material._babylonData[drawMode];
  2883. if (babylonData.meshes.length === 0) {
  2884. babylonData.material.dispose(false, true);
  2885. delete material._babylonData[drawMode];
  2886. }
  2887. }
  2888. }
  2889. }
  2890. }
  2891. };
  2892. return MSFT_lod;
  2893. }(GLTF2.GLTFLoaderExtension));
  2894. Extensions.MSFT_lod = MSFT_lod;
  2895. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  2896. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2897. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2898. })(BABYLON || (BABYLON = {}));
  2899. //# sourceMappingURL=MSFT_lod.js.map
  2900. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2901. var __extends = (this && this.__extends) || (function () {
  2902. var extendStatics = Object.setPrototypeOf ||
  2903. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2904. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2905. return function (d, b) {
  2906. extendStatics(d, b);
  2907. function __() { this.constructor = d; }
  2908. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2909. };
  2910. })();
  2911. var BABYLON;
  2912. (function (BABYLON) {
  2913. var GLTF2;
  2914. (function (GLTF2) {
  2915. var Extensions;
  2916. (function (Extensions) {
  2917. var NAME = "MSFT_minecraftMesh";
  2918. /** @hidden */
  2919. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  2920. __extends(MSFT_minecraftMesh, _super);
  2921. function MSFT_minecraftMesh() {
  2922. var _this = _super !== null && _super.apply(this, arguments) || this;
  2923. _this.name = NAME;
  2924. return _this;
  2925. }
  2926. MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  2927. var _this = this;
  2928. return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {
  2929. if (value) {
  2930. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  2931. if (babylonMaterial.needAlphaBlending()) {
  2932. babylonMaterial.forceDepthWrite = true;
  2933. babylonMaterial.separateCullingPass = true;
  2934. }
  2935. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  2936. babylonMaterial.twoSidedLighting = true;
  2937. assign(babylonMaterial);
  2938. });
  2939. }
  2940. return null;
  2941. });
  2942. };
  2943. return MSFT_minecraftMesh;
  2944. }(GLTF2.GLTFLoaderExtension));
  2945. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  2946. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  2947. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2948. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2949. })(BABYLON || (BABYLON = {}));
  2950. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  2951. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2952. var __extends = (this && this.__extends) || (function () {
  2953. var extendStatics = Object.setPrototypeOf ||
  2954. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2955. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2956. return function (d, b) {
  2957. extendStatics(d, b);
  2958. function __() { this.constructor = d; }
  2959. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2960. };
  2961. })();
  2962. var BABYLON;
  2963. (function (BABYLON) {
  2964. var GLTF2;
  2965. (function (GLTF2) {
  2966. var Extensions;
  2967. (function (Extensions) {
  2968. var NAME = "MSFT_sRGBFactors";
  2969. /** @hidden */
  2970. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  2971. __extends(MSFT_sRGBFactors, _super);
  2972. function MSFT_sRGBFactors() {
  2973. var _this = _super !== null && _super.apply(this, arguments) || this;
  2974. _this.name = NAME;
  2975. return _this;
  2976. }
  2977. MSFT_sRGBFactors.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2978. var _this = this;
  2979. return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {
  2980. if (value) {
  2981. var promise = _this._loader._loadMaterialPropertiesAsync(context, material, babylonMaterial);
  2982. _this._convertColorsToLinear(babylonMaterial);
  2983. return promise;
  2984. }
  2985. return null;
  2986. });
  2987. };
  2988. MSFT_sRGBFactors.prototype._convertColorsToLinear = function (babylonMaterial) {
  2989. if (!babylonMaterial.albedoTexture) {
  2990. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  2991. }
  2992. if (!babylonMaterial.reflectivityTexture) {
  2993. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  2994. }
  2995. };
  2996. return MSFT_sRGBFactors;
  2997. }(GLTF2.GLTFLoaderExtension));
  2998. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  2999. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  3000. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3001. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3002. })(BABYLON || (BABYLON = {}));
  3003. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  3004. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3005. var __extends = (this && this.__extends) || (function () {
  3006. var extendStatics = Object.setPrototypeOf ||
  3007. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3008. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3009. return function (d, b) {
  3010. extendStatics(d, b);
  3011. function __() { this.constructor = d; }
  3012. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3013. };
  3014. })();
  3015. var BABYLON;
  3016. (function (BABYLON) {
  3017. var GLTF2;
  3018. (function (GLTF2) {
  3019. var Extensions;
  3020. (function (Extensions) {
  3021. var NAME = "KHR_draco_mesh_compression";
  3022. /**
  3023. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  3024. */
  3025. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  3026. __extends(KHR_draco_mesh_compression, _super);
  3027. function KHR_draco_mesh_compression(loader) {
  3028. var _this = _super.call(this, loader) || this;
  3029. _this.name = NAME;
  3030. _this._dracoCompression = null;
  3031. // Disable extension if decoder is not available.
  3032. if (!BABYLON.DracoCompression.DecoderAvailable) {
  3033. _this.enabled = false;
  3034. }
  3035. return _this;
  3036. }
  3037. KHR_draco_mesh_compression.prototype.dispose = function () {
  3038. if (this._dracoCompression) {
  3039. this._dracoCompression.dispose();
  3040. }
  3041. _super.prototype.dispose.call(this);
  3042. };
  3043. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  3044. var _this = this;
  3045. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  3046. if (primitive.mode != undefined) {
  3047. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  3048. primitive.mode !== 4 /* TRIANGLES */) {
  3049. throw new Error(context + ": Unsupported mode " + primitive.mode);
  3050. }
  3051. // TODO: handle triangle strips
  3052. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  3053. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  3054. }
  3055. }
  3056. var attributes = {};
  3057. var loadAttribute = function (name, kind) {
  3058. var uniqueId = extension.attributes[name];
  3059. if (uniqueId == undefined) {
  3060. return;
  3061. }
  3062. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3063. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3064. babylonMesh._delayInfo.push(kind);
  3065. }
  3066. attributes[kind] = uniqueId;
  3067. };
  3068. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  3069. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  3070. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  3071. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  3072. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  3073. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  3074. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  3075. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  3076. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  3077. if (!bufferView._dracoBabylonGeometry) {
  3078. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  3079. if (!_this._dracoCompression) {
  3080. _this._dracoCompression = new BABYLON.DracoCompression();
  3081. }
  3082. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  3083. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  3084. babylonVertexData.applyToGeometry(babylonGeometry);
  3085. return babylonGeometry;
  3086. }).catch(function (error) {
  3087. throw new Error(context + ": " + error.message);
  3088. });
  3089. });
  3090. }
  3091. return bufferView._dracoBabylonGeometry;
  3092. });
  3093. };
  3094. return KHR_draco_mesh_compression;
  3095. }(GLTF2.GLTFLoaderExtension));
  3096. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  3097. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  3098. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3099. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3100. })(BABYLON || (BABYLON = {}));
  3101. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  3102. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3103. var __extends = (this && this.__extends) || (function () {
  3104. var extendStatics = Object.setPrototypeOf ||
  3105. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3106. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3107. return function (d, b) {
  3108. extendStatics(d, b);
  3109. function __() { this.constructor = d; }
  3110. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3111. };
  3112. })();
  3113. var BABYLON;
  3114. (function (BABYLON) {
  3115. var GLTF2;
  3116. (function (GLTF2) {
  3117. var Extensions;
  3118. (function (Extensions) {
  3119. var NAME = "KHR_materials_pbrSpecularGlossiness";
  3120. /**
  3121. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  3122. */
  3123. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  3124. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  3125. function KHR_materials_pbrSpecularGlossiness() {
  3126. var _this = _super !== null && _super.apply(this, arguments) || this;
  3127. _this.name = NAME;
  3128. return _this;
  3129. }
  3130. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  3131. var _this = this;
  3132. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  3133. var promises = new Array();
  3134. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  3135. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  3136. return Promise.all(promises).then(function () { });
  3137. });
  3138. };
  3139. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  3140. var promises = new Array();
  3141. if (properties.diffuseFactor) {
  3142. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  3143. babylonMaterial.alpha = properties.diffuseFactor[3];
  3144. }
  3145. else {
  3146. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3147. }
  3148. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  3149. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  3150. if (properties.diffuseTexture) {
  3151. promises.push(this._loader._loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  3152. babylonMaterial.albedoTexture = texture;
  3153. }));
  3154. }
  3155. if (properties.specularGlossinessTexture) {
  3156. promises.push(this._loader._loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  3157. babylonMaterial.reflectivityTexture = texture;
  3158. }));
  3159. babylonMaterial.reflectivityTexture.hasAlpha = true;
  3160. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  3161. }
  3162. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  3163. return Promise.all(promises).then(function () { });
  3164. };
  3165. return KHR_materials_pbrSpecularGlossiness;
  3166. }(GLTF2.GLTFLoaderExtension));
  3167. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  3168. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  3169. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3170. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3171. })(BABYLON || (BABYLON = {}));
  3172. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  3173. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3174. var __extends = (this && this.__extends) || (function () {
  3175. var extendStatics = Object.setPrototypeOf ||
  3176. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3177. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3178. return function (d, b) {
  3179. extendStatics(d, b);
  3180. function __() { this.constructor = d; }
  3181. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3182. };
  3183. })();
  3184. var BABYLON;
  3185. (function (BABYLON) {
  3186. var GLTF2;
  3187. (function (GLTF2) {
  3188. var Extensions;
  3189. (function (Extensions) {
  3190. var NAME = "KHR_materials_unlit";
  3191. /**
  3192. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  3193. */
  3194. var KHR_materials_unlit = /** @class */ (function (_super) {
  3195. __extends(KHR_materials_unlit, _super);
  3196. function KHR_materials_unlit() {
  3197. var _this = _super !== null && _super.apply(this, arguments) || this;
  3198. _this.name = NAME;
  3199. return _this;
  3200. }
  3201. KHR_materials_unlit.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  3202. var _this = this;
  3203. return this._loadExtensionAsync(context, material, function () {
  3204. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  3205. });
  3206. };
  3207. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  3208. var promises = new Array();
  3209. babylonMaterial.unlit = true;
  3210. // Ensure metallic workflow
  3211. babylonMaterial.metallic = 1;
  3212. babylonMaterial.roughness = 1;
  3213. var properties = material.pbrMetallicRoughness;
  3214. if (properties) {
  3215. if (properties.baseColorFactor) {
  3216. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  3217. babylonMaterial.alpha = properties.baseColorFactor[3];
  3218. }
  3219. else {
  3220. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3221. }
  3222. if (properties.baseColorTexture) {
  3223. promises.push(this._loader._loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  3224. babylonMaterial.albedoTexture = texture;
  3225. }));
  3226. }
  3227. }
  3228. if (material.doubleSided) {
  3229. babylonMaterial.backFaceCulling = false;
  3230. babylonMaterial.twoSidedLighting = true;
  3231. }
  3232. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  3233. return Promise.all(promises).then(function () { });
  3234. };
  3235. return KHR_materials_unlit;
  3236. }(GLTF2.GLTFLoaderExtension));
  3237. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  3238. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  3239. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3240. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3241. })(BABYLON || (BABYLON = {}));
  3242. //# sourceMappingURL=KHR_materials_unlit.js.map
  3243. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3244. var __extends = (this && this.__extends) || (function () {
  3245. var extendStatics = Object.setPrototypeOf ||
  3246. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3247. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3248. return function (d, b) {
  3249. extendStatics(d, b);
  3250. function __() { this.constructor = d; }
  3251. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3252. };
  3253. })();
  3254. var BABYLON;
  3255. (function (BABYLON) {
  3256. var GLTF2;
  3257. (function (GLTF2) {
  3258. var Extensions;
  3259. (function (Extensions) {
  3260. var NAME = "KHR_lights";
  3261. var LightType;
  3262. (function (LightType) {
  3263. LightType["AMBIENT"] = "ambient";
  3264. LightType["DIRECTIONAL"] = "directional";
  3265. LightType["POINT"] = "point";
  3266. LightType["SPOT"] = "spot";
  3267. })(LightType || (LightType = {}));
  3268. /**
  3269. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  3270. */
  3271. var KHR_lights = /** @class */ (function (_super) {
  3272. __extends(KHR_lights, _super);
  3273. function KHR_lights() {
  3274. var _this = _super !== null && _super.apply(this, arguments) || this;
  3275. _this.name = NAME;
  3276. return _this;
  3277. }
  3278. KHR_lights.prototype._onLoading = function () {
  3279. var extensions = this._loader._gltf.extensions;
  3280. if (extensions && extensions[this.name]) {
  3281. var extension = extensions[this.name];
  3282. this._lights = extension.lights;
  3283. }
  3284. };
  3285. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  3286. var _this = this;
  3287. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  3288. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  3289. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  3290. if (light.type !== LightType.AMBIENT) {
  3291. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  3292. }
  3293. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  3294. return promise;
  3295. });
  3296. };
  3297. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  3298. var _this = this;
  3299. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  3300. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  3301. var babylonLight;
  3302. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  3303. var name = node._babylonMesh.name;
  3304. switch (light.type) {
  3305. case LightType.AMBIENT: {
  3306. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  3307. }
  3308. case LightType.DIRECTIONAL: {
  3309. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  3310. break;
  3311. }
  3312. case LightType.POINT: {
  3313. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  3314. break;
  3315. }
  3316. case LightType.SPOT: {
  3317. // TODO: support inner and outer cone angles
  3318. //const innerConeAngle = spotLight.innerConeAngle || 0;
  3319. var outerConeAngle = light.spot && light.spot.outerConeAngle || Math.PI / 4;
  3320. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  3321. break;
  3322. }
  3323. default: {
  3324. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  3325. }
  3326. }
  3327. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  3328. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  3329. babylonLight.parent = node._babylonMesh;
  3330. return promise;
  3331. });
  3332. };
  3333. return KHR_lights;
  3334. }(GLTF2.GLTFLoaderExtension));
  3335. Extensions.KHR_lights = KHR_lights;
  3336. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  3337. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3338. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3339. })(BABYLON || (BABYLON = {}));
  3340. //# sourceMappingURL=KHR_lights.js.map
  3341. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3342. var __extends = (this && this.__extends) || (function () {
  3343. var extendStatics = Object.setPrototypeOf ||
  3344. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3345. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3346. return function (d, b) {
  3347. extendStatics(d, b);
  3348. function __() { this.constructor = d; }
  3349. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3350. };
  3351. })();
  3352. var BABYLON;
  3353. (function (BABYLON) {
  3354. var GLTF2;
  3355. (function (GLTF2) {
  3356. var Extensions;
  3357. (function (Extensions) {
  3358. var NAME = "KHR_texture_transform";
  3359. /**
  3360. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  3361. */
  3362. var KHR_texture_transform = /** @class */ (function (_super) {
  3363. __extends(KHR_texture_transform, _super);
  3364. function KHR_texture_transform() {
  3365. var _this = _super !== null && _super.apply(this, arguments) || this;
  3366. _this.name = NAME;
  3367. return _this;
  3368. }
  3369. KHR_texture_transform.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) {
  3370. var _this = this;
  3371. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  3372. return _this._loader._loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {
  3373. if (extension.offset) {
  3374. babylonTexture.uOffset = extension.offset[0];
  3375. babylonTexture.vOffset = extension.offset[1];
  3376. }
  3377. // Always rotate around the origin.
  3378. babylonTexture.uRotationCenter = 0;
  3379. babylonTexture.vRotationCenter = 0;
  3380. if (extension.rotation) {
  3381. babylonTexture.wAng = -extension.rotation;
  3382. }
  3383. if (extension.scale) {
  3384. babylonTexture.uScale = extension.scale[0];
  3385. babylonTexture.vScale = extension.scale[1];
  3386. }
  3387. if (extension.texCoord != undefined) {
  3388. babylonTexture.coordinatesIndex = extension.texCoord;
  3389. }
  3390. assign(babylonTexture);
  3391. });
  3392. });
  3393. };
  3394. return KHR_texture_transform;
  3395. }(GLTF2.GLTFLoaderExtension));
  3396. Extensions.KHR_texture_transform = KHR_texture_transform;
  3397. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  3398. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3399. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3400. })(BABYLON || (BABYLON = {}));
  3401. //# sourceMappingURL=KHR_texture_transform.js.map
  3402. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3403. var __extends = (this && this.__extends) || (function () {
  3404. var extendStatics = Object.setPrototypeOf ||
  3405. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3406. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3407. return function (d, b) {
  3408. extendStatics(d, b);
  3409. function __() { this.constructor = d; }
  3410. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3411. };
  3412. })();
  3413. var BABYLON;
  3414. (function (BABYLON) {
  3415. var GLTF2;
  3416. (function (GLTF2) {
  3417. var Extensions;
  3418. (function (Extensions) {
  3419. var NAME = "EXT_lights_imageBased";
  3420. /**
  3421. * [Specification](TODO) (Experimental)
  3422. */
  3423. var EXT_lights_imageBased = /** @class */ (function (_super) {
  3424. __extends(EXT_lights_imageBased, _super);
  3425. function EXT_lights_imageBased() {
  3426. var _this = _super !== null && _super.apply(this, arguments) || this;
  3427. _this.name = NAME;
  3428. return _this;
  3429. }
  3430. EXT_lights_imageBased.prototype._onLoading = function () {
  3431. var extensions = this._loader._gltf.extensions;
  3432. if (extensions && extensions[this.name]) {
  3433. var extension = extensions[this.name];
  3434. this._lights = extension.lights;
  3435. }
  3436. };
  3437. EXT_lights_imageBased.prototype._loadSceneAsync = function (context, scene) {
  3438. var _this = this;
  3439. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  3440. var promises = new Array();
  3441. promises.push(_this._loader._loadSceneAsync(context, scene));
  3442. _this._loader._parent._logOpen("" + extensionContext);
  3443. var light = GLTF2.GLTFLoader._GetProperty(extensionContext + "/light", _this._lights, extension.light);
  3444. promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) {
  3445. _this._loader._babylonScene.environmentTexture = texture;
  3446. }));
  3447. _this._loader._parent._logClose();
  3448. return Promise.all(promises).then(function () { });
  3449. });
  3450. };
  3451. EXT_lights_imageBased.prototype._loadLightAsync = function (context, light) {
  3452. var _this = this;
  3453. if (!light._loaded) {
  3454. var promises = new Array();
  3455. this._loader._parent._logOpen("" + context);
  3456. var imageData_1 = new Array(light.specularImages.length);
  3457. var _loop_1 = function (mipmap) {
  3458. var faces = light.specularImages[mipmap];
  3459. imageData_1[mipmap] = new Array(faces.length);
  3460. var _loop_2 = function (face) {
  3461. var specularImageContext = context + "/specularImages/" + mipmap + "/" + face;
  3462. this_1._loader._parent._logOpen("" + specularImageContext);
  3463. var index = faces[face];
  3464. var image = GLTF2.GLTFLoader._GetProperty(specularImageContext, this_1._loader._gltf.images, index);
  3465. promises.push(this_1._loader._loadImageAsync("#/images/" + index, image).then(function (data) {
  3466. imageData_1[mipmap][face] = data;
  3467. }));
  3468. this_1._loader._parent._logClose();
  3469. };
  3470. for (var face = 0; face < faces.length; face++) {
  3471. _loop_2(face);
  3472. }
  3473. };
  3474. var this_1 = this;
  3475. for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {
  3476. _loop_1(mipmap);
  3477. }
  3478. this._loader._parent._logClose();
  3479. light._loaded = Promise.all(promises).then(function () {
  3480. var babylonTexture = new BABYLON.RawCubeTexture(_this._loader._babylonScene, null, light.specularImageSize);
  3481. light._babylonTexture = babylonTexture;
  3482. if (light.intensity != undefined) {
  3483. babylonTexture.level = light.intensity;
  3484. }
  3485. if (light.rotation) {
  3486. var rotation = BABYLON.Quaternion.FromArray(light.rotation);
  3487. // Invert the rotation so that positive rotation is counter-clockwise.
  3488. if (!_this._loader._babylonScene.useRightHandedSystem) {
  3489. rotation = BABYLON.Quaternion.Inverse(rotation);
  3490. }
  3491. BABYLON.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());
  3492. }
  3493. var sphericalHarmonics = BABYLON.SphericalHarmonics.FromArray(light.irradianceCoefficients);
  3494. sphericalHarmonics.scale(light.intensity);
  3495. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  3496. var sphericalPolynomial = BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  3497. // Compute the lod generation scale to fit exactly to the number of levels available.
  3498. var lodGenerationScale = (imageData_1.length - 1) / BABYLON.Scalar.Log2(light.specularImageSize);
  3499. return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);
  3500. });
  3501. }
  3502. return light._loaded.then(function () {
  3503. return light._babylonTexture;
  3504. });
  3505. };
  3506. return EXT_lights_imageBased;
  3507. }(GLTF2.GLTFLoaderExtension));
  3508. Extensions.EXT_lights_imageBased = EXT_lights_imageBased;
  3509. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new EXT_lights_imageBased(loader); });
  3510. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3511. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3512. })(BABYLON || (BABYLON = {}));
  3513. //# sourceMappingURL=EXT_lights_imageBased.js.map