babylon.glTF2FileLoader.js 171 KB

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