babylon.glTF2FileLoader.js 191 KB

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