babylon.glTFFileLoader.js 236 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFLoaderCoordinateSystemMode;
  5. (function (GLTFLoaderCoordinateSystemMode) {
  6. /**
  7. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  8. */
  9. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  10. /**
  11. * Sets the useRightHandedSystem flag on the scene.
  12. */
  13. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  14. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  15. var GLTFLoaderAnimationStartMode;
  16. (function (GLTFLoaderAnimationStartMode) {
  17. /**
  18. * No animation will start.
  19. */
  20. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  21. /**
  22. * The first animation will start.
  23. */
  24. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  25. /**
  26. * All animations will start.
  27. */
  28. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  29. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  30. var GLTFLoaderState;
  31. (function (GLTFLoaderState) {
  32. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  33. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  34. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  35. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  36. var GLTFFileLoader = /** @class */ (function () {
  37. function GLTFFileLoader() {
  38. // #region Common options
  39. /**
  40. * Raised when the asset has been parsed.
  41. * The data.json property stores the glTF JSON.
  42. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  43. */
  44. this.onParsedObservable = new BABYLON.Observable();
  45. // #endregion
  46. // #region V2 options
  47. /**
  48. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  49. */
  50. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  51. /**
  52. * The animation start mode (NONE, FIRST, ALL).
  53. */
  54. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  55. /**
  56. * Set to true to compile materials before raising the success callback.
  57. */
  58. this.compileMaterials = false;
  59. /**
  60. * Set to true to also compile materials with clip planes.
  61. */
  62. this.useClipPlane = false;
  63. /**
  64. * Set to true to compile shadow generators before raising the success callback.
  65. */
  66. this.compileShadowGenerators = false;
  67. /**
  68. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  69. */
  70. this.onMeshLoadedObservable = new BABYLON.Observable();
  71. /**
  72. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  73. */
  74. this.onTextureLoadedObservable = new BABYLON.Observable();
  75. /**
  76. * Raised when the loader creates a material after parsing the glTF properties of the material.
  77. */
  78. this.onMaterialLoadedObservable = new BABYLON.Observable();
  79. /**
  80. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  81. */
  82. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  83. /**
  84. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  85. * For assets with LODs, raised when all of the LODs are complete.
  86. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  87. */
  88. this.onCompleteObservable = new BABYLON.Observable();
  89. /**
  90. * Raised when the loader is disposed.
  91. */
  92. this.onDisposeObservable = new BABYLON.Observable();
  93. /**
  94. * Raised after a loader extension is created.
  95. * Set additional options for a loader extension in this event.
  96. */
  97. this.onExtensionLoadedObservable = new BABYLON.Observable();
  98. // #endregion
  99. this._loader = null;
  100. this.name = "gltf";
  101. this.extensions = {
  102. ".gltf": { isBinary: false },
  103. ".glb": { isBinary: true }
  104. };
  105. }
  106. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  107. set: function (callback) {
  108. if (this._onParsedObserver) {
  109. this.onParsedObservable.remove(this._onParsedObserver);
  110. }
  111. this._onParsedObserver = this.onParsedObservable.add(callback);
  112. },
  113. enumerable: true,
  114. configurable: true
  115. });
  116. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  117. set: function (callback) {
  118. if (this._onMeshLoadedObserver) {
  119. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  120. }
  121. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  122. },
  123. enumerable: true,
  124. configurable: true
  125. });
  126. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  127. set: function (callback) {
  128. if (this._onTextureLoadedObserver) {
  129. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  130. }
  131. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  132. },
  133. enumerable: true,
  134. configurable: true
  135. });
  136. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  137. set: function (callback) {
  138. if (this._onMaterialLoadedObserver) {
  139. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  140. }
  141. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  142. },
  143. enumerable: true,
  144. configurable: true
  145. });
  146. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  147. set: function (callback) {
  148. if (this._onAnimationGroupLoadedObserver) {
  149. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  150. }
  151. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  152. },
  153. enumerable: true,
  154. configurable: true
  155. });
  156. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  157. set: function (callback) {
  158. if (this._onCompleteObserver) {
  159. this.onCompleteObservable.remove(this._onCompleteObserver);
  160. }
  161. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  162. },
  163. enumerable: true,
  164. configurable: true
  165. });
  166. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  167. set: function (callback) {
  168. if (this._onDisposeObserver) {
  169. this.onDisposeObservable.remove(this._onDisposeObserver);
  170. }
  171. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  172. },
  173. enumerable: true,
  174. configurable: true
  175. });
  176. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  177. set: function (callback) {
  178. if (this._onExtensionLoadedObserver) {
  179. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  180. }
  181. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  182. },
  183. enumerable: true,
  184. configurable: true
  185. });
  186. /**
  187. * Gets a promise that resolves when the asset is completely loaded.
  188. * @returns A promise that resolves when the asset is completely loaded.
  189. */
  190. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  191. var _this = this;
  192. return new Promise(function (resolve) {
  193. _this.onCompleteObservable.add(function () {
  194. resolve();
  195. }, undefined, undefined, undefined, true);
  196. });
  197. };
  198. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  199. /**
  200. * The loader state or null if not active.
  201. */
  202. get: function () {
  203. return this._loader ? this._loader.state : null;
  204. },
  205. enumerable: true,
  206. configurable: true
  207. });
  208. /**
  209. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  210. */
  211. GLTFFileLoader.prototype.dispose = function () {
  212. if (this._loader) {
  213. this._loader.dispose();
  214. this._loader = null;
  215. }
  216. this.onMeshLoadedObservable.clear();
  217. this.onTextureLoadedObservable.clear();
  218. this.onMaterialLoadedObservable.clear();
  219. this.onDisposeObservable.notifyObservers(this);
  220. this.onDisposeObservable.clear();
  221. };
  222. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  223. var _this = this;
  224. return Promise.resolve().then(function () {
  225. var loaderData = _this._parse(data);
  226. _this._loader = _this._getLoader(loaderData);
  227. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  228. });
  229. };
  230. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  231. var _this = this;
  232. return Promise.resolve().then(function () {
  233. var loaderData = _this._parse(data);
  234. _this._loader = _this._getLoader(loaderData);
  235. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  236. });
  237. };
  238. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  239. var _this = this;
  240. return Promise.resolve().then(function () {
  241. var loaderData = _this._parse(data);
  242. _this._loader = _this._getLoader(loaderData);
  243. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  244. var container = new BABYLON.AssetContainer(scene);
  245. Array.prototype.push.apply(container.meshes, result.meshes);
  246. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  247. Array.prototype.push.apply(container.skeletons, result.skeletons);
  248. container.removeAllFromScene();
  249. return container;
  250. });
  251. });
  252. };
  253. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  254. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  255. };
  256. GLTFFileLoader.prototype.createPlugin = function () {
  257. return new GLTFFileLoader();
  258. };
  259. GLTFFileLoader.prototype._parse = function (data) {
  260. var parsedData;
  261. if (data instanceof ArrayBuffer) {
  262. parsedData = GLTFFileLoader._parseBinary(data);
  263. }
  264. else {
  265. parsedData = {
  266. json: JSON.parse(data),
  267. bin: null
  268. };
  269. }
  270. this.onParsedObservable.notifyObservers(parsedData);
  271. this.onParsedObservable.clear();
  272. return parsedData;
  273. };
  274. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  275. var _this = this;
  276. var loaderVersion = { major: 2, minor: 0 };
  277. var asset = loaderData.json.asset || {};
  278. var version = GLTFFileLoader._parseVersion(asset.version);
  279. if (!version) {
  280. throw new Error("Invalid version: " + asset.version);
  281. }
  282. if (asset.minVersion !== undefined) {
  283. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  284. if (!minVersion) {
  285. throw new Error("Invalid minimum version: " + asset.minVersion);
  286. }
  287. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  288. throw new Error("Incompatible minimum version: " + asset.minVersion);
  289. }
  290. }
  291. var createLoaders = {
  292. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  293. 2: GLTFFileLoader.CreateGLTFLoaderV2
  294. };
  295. var createLoader = createLoaders[version.major];
  296. if (!createLoader) {
  297. throw new Error("Unsupported version: " + asset.version);
  298. }
  299. var loader = createLoader();
  300. loader.coordinateSystemMode = this.coordinateSystemMode;
  301. loader.animationStartMode = this.animationStartMode;
  302. loader.compileMaterials = this.compileMaterials;
  303. loader.useClipPlane = this.useClipPlane;
  304. loader.compileShadowGenerators = this.compileShadowGenerators;
  305. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  306. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  307. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  308. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  309. loader.onCompleteObservable.add(function () {
  310. _this.onMeshLoadedObservable.clear();
  311. _this.onTextureLoadedObservable.clear();
  312. _this.onMaterialLoadedObservable.clear();
  313. _this.onCompleteObservable.notifyObservers(_this);
  314. _this.onCompleteObservable.clear();
  315. });
  316. return loader;
  317. };
  318. GLTFFileLoader._parseBinary = function (data) {
  319. var Binary = {
  320. Magic: 0x46546C67
  321. };
  322. var binaryReader = new BinaryReader(data);
  323. var magic = binaryReader.readUint32();
  324. if (magic !== Binary.Magic) {
  325. throw new Error("Unexpected magic: " + magic);
  326. }
  327. var version = binaryReader.readUint32();
  328. switch (version) {
  329. case 1: return GLTFFileLoader._parseV1(binaryReader);
  330. case 2: return GLTFFileLoader._parseV2(binaryReader);
  331. }
  332. throw new Error("Unsupported version: " + version);
  333. };
  334. GLTFFileLoader._parseV1 = function (binaryReader) {
  335. var ContentFormat = {
  336. JSON: 0
  337. };
  338. var length = binaryReader.readUint32();
  339. if (length != binaryReader.getLength()) {
  340. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  341. }
  342. var contentLength = binaryReader.readUint32();
  343. var contentFormat = binaryReader.readUint32();
  344. var content;
  345. switch (contentFormat) {
  346. case ContentFormat.JSON: {
  347. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  348. break;
  349. }
  350. default: {
  351. throw new Error("Unexpected content format: " + contentFormat);
  352. }
  353. }
  354. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  355. var body = binaryReader.readUint8Array(bytesRemaining);
  356. return {
  357. json: content,
  358. bin: body
  359. };
  360. };
  361. GLTFFileLoader._parseV2 = function (binaryReader) {
  362. var ChunkFormat = {
  363. JSON: 0x4E4F534A,
  364. BIN: 0x004E4942
  365. };
  366. var length = binaryReader.readUint32();
  367. if (length !== binaryReader.getLength()) {
  368. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  369. }
  370. // JSON chunk
  371. var chunkLength = binaryReader.readUint32();
  372. var chunkFormat = binaryReader.readUint32();
  373. if (chunkFormat !== ChunkFormat.JSON) {
  374. throw new Error("First chunk format is not JSON");
  375. }
  376. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  377. // Look for BIN chunk
  378. var bin = null;
  379. while (binaryReader.getPosition() < binaryReader.getLength()) {
  380. var chunkLength_1 = binaryReader.readUint32();
  381. var chunkFormat_1 = binaryReader.readUint32();
  382. switch (chunkFormat_1) {
  383. case ChunkFormat.JSON: {
  384. throw new Error("Unexpected JSON chunk");
  385. }
  386. case ChunkFormat.BIN: {
  387. bin = binaryReader.readUint8Array(chunkLength_1);
  388. break;
  389. }
  390. default: {
  391. // ignore unrecognized chunkFormat
  392. binaryReader.skipBytes(chunkLength_1);
  393. break;
  394. }
  395. }
  396. }
  397. return {
  398. json: json,
  399. bin: bin
  400. };
  401. };
  402. GLTFFileLoader._parseVersion = function (version) {
  403. if (version === "1.0" || version === "1.0.1") {
  404. return {
  405. major: 1,
  406. minor: 0
  407. };
  408. }
  409. var match = (version + "").match(/^(\d+)\.(\d+)/);
  410. if (!match) {
  411. return null;
  412. }
  413. return {
  414. major: parseInt(match[1]),
  415. minor: parseInt(match[2])
  416. };
  417. };
  418. GLTFFileLoader._compareVersion = function (a, b) {
  419. if (a.major > b.major)
  420. return 1;
  421. if (a.major < b.major)
  422. return -1;
  423. if (a.minor > b.minor)
  424. return 1;
  425. if (a.minor < b.minor)
  426. return -1;
  427. return 0;
  428. };
  429. GLTFFileLoader._decodeBufferToText = function (buffer) {
  430. var result = "";
  431. var length = buffer.byteLength;
  432. for (var i = 0; i < length; i++) {
  433. result += String.fromCharCode(buffer[i]);
  434. }
  435. return result;
  436. };
  437. // #endregion
  438. // #region V1 options
  439. GLTFFileLoader.IncrementalLoading = true;
  440. GLTFFileLoader.HomogeneousCoordinates = false;
  441. return GLTFFileLoader;
  442. }());
  443. BABYLON.GLTFFileLoader = GLTFFileLoader;
  444. var BinaryReader = /** @class */ (function () {
  445. function BinaryReader(arrayBuffer) {
  446. this._arrayBuffer = arrayBuffer;
  447. this._dataView = new DataView(arrayBuffer);
  448. this._byteOffset = 0;
  449. }
  450. BinaryReader.prototype.getPosition = function () {
  451. return this._byteOffset;
  452. };
  453. BinaryReader.prototype.getLength = function () {
  454. return this._arrayBuffer.byteLength;
  455. };
  456. BinaryReader.prototype.readUint32 = function () {
  457. var value = this._dataView.getUint32(this._byteOffset, true);
  458. this._byteOffset += 4;
  459. return value;
  460. };
  461. BinaryReader.prototype.readUint8Array = function (length) {
  462. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  463. this._byteOffset += length;
  464. return value;
  465. };
  466. BinaryReader.prototype.skipBytes = function (length) {
  467. this._byteOffset += length;
  468. };
  469. return BinaryReader;
  470. }());
  471. if (BABYLON.SceneLoader) {
  472. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  473. }
  474. })(BABYLON || (BABYLON = {}));
  475. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  476. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  477. var BABYLON;
  478. (function (BABYLON) {
  479. var GLTF1;
  480. (function (GLTF1) {
  481. /**
  482. * Enums
  483. */
  484. var EComponentType;
  485. (function (EComponentType) {
  486. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  487. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  488. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  489. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  490. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  491. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  492. var EShaderType;
  493. (function (EShaderType) {
  494. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  495. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  496. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  497. var EParameterType;
  498. (function (EParameterType) {
  499. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  500. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  501. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  502. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  503. EParameterType[EParameterType["INT"] = 5124] = "INT";
  504. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  505. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  506. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  507. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  508. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  509. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  510. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  511. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  512. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  513. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  514. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  515. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  516. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  517. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  518. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  519. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  520. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  521. var ETextureWrapMode;
  522. (function (ETextureWrapMode) {
  523. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  524. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  525. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  526. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  527. var ETextureFilterType;
  528. (function (ETextureFilterType) {
  529. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  530. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  531. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  532. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  533. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  534. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  535. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  536. var ETextureFormat;
  537. (function (ETextureFormat) {
  538. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  539. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  540. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  541. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  542. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  543. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  544. var ECullingType;
  545. (function (ECullingType) {
  546. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  547. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  548. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  549. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  550. var EBlendingFunction;
  551. (function (EBlendingFunction) {
  552. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  553. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  554. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  555. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  556. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  557. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  558. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  559. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  560. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  561. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  562. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  563. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  564. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  565. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  566. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  567. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  568. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  569. })(BABYLON || (BABYLON = {}));
  570. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  571. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  572. var BABYLON;
  573. (function (BABYLON) {
  574. var GLTF1;
  575. (function (GLTF1) {
  576. /**
  577. * Tokenizer. Used for shaders compatibility
  578. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  579. */
  580. var ETokenType;
  581. (function (ETokenType) {
  582. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  583. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  584. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  585. })(ETokenType || (ETokenType = {}));
  586. var Tokenizer = /** @class */ (function () {
  587. function Tokenizer(toParse) {
  588. this._pos = 0;
  589. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  590. this._toParse = toParse;
  591. this._maxPos = toParse.length;
  592. }
  593. Tokenizer.prototype.getNextToken = function () {
  594. if (this.isEnd())
  595. return ETokenType.END_OF_INPUT;
  596. this.currentString = this.read();
  597. this.currentToken = ETokenType.UNKNOWN;
  598. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  599. this.currentToken = ETokenType.IDENTIFIER;
  600. this.currentIdentifier = this.currentString;
  601. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  602. this.currentIdentifier += this.currentString;
  603. this.forward();
  604. }
  605. }
  606. return this.currentToken;
  607. };
  608. Tokenizer.prototype.peek = function () {
  609. return this._toParse[this._pos];
  610. };
  611. Tokenizer.prototype.read = function () {
  612. return this._toParse[this._pos++];
  613. };
  614. Tokenizer.prototype.forward = function () {
  615. this._pos++;
  616. };
  617. Tokenizer.prototype.isEnd = function () {
  618. return this._pos >= this._maxPos;
  619. };
  620. return Tokenizer;
  621. }());
  622. /**
  623. * Values
  624. */
  625. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  626. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  627. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  628. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  629. /**
  630. * Parse
  631. */
  632. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  633. for (var buf in parsedBuffers) {
  634. var parsedBuffer = parsedBuffers[buf];
  635. gltfRuntime.buffers[buf] = parsedBuffer;
  636. gltfRuntime.buffersCount++;
  637. }
  638. };
  639. var parseShaders = function (parsedShaders, gltfRuntime) {
  640. for (var sha in parsedShaders) {
  641. var parsedShader = parsedShaders[sha];
  642. gltfRuntime.shaders[sha] = parsedShader;
  643. gltfRuntime.shaderscount++;
  644. }
  645. };
  646. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  647. for (var object in parsedObjects) {
  648. var parsedObject = parsedObjects[object];
  649. gltfRuntime[runtimeProperty][object] = parsedObject;
  650. }
  651. };
  652. /**
  653. * Utils
  654. */
  655. var normalizeUVs = function (buffer) {
  656. if (!buffer) {
  657. return;
  658. }
  659. for (var i = 0; i < buffer.length / 2; i++) {
  660. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  661. }
  662. };
  663. var getAttribute = function (attributeParameter) {
  664. if (attributeParameter.semantic === "NORMAL") {
  665. return "normal";
  666. }
  667. else if (attributeParameter.semantic === "POSITION") {
  668. return "position";
  669. }
  670. else if (attributeParameter.semantic === "JOINT") {
  671. return "matricesIndices";
  672. }
  673. else if (attributeParameter.semantic === "WEIGHT") {
  674. return "matricesWeights";
  675. }
  676. else if (attributeParameter.semantic === "COLOR") {
  677. return "color";
  678. }
  679. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  680. var channel = Number(attributeParameter.semantic.split("_")[1]);
  681. return "uv" + (channel === 0 ? "" : channel + 1);
  682. }
  683. return null;
  684. };
  685. /**
  686. * Loads and creates animations
  687. */
  688. var loadAnimations = function (gltfRuntime) {
  689. for (var anim in gltfRuntime.animations) {
  690. var animation = gltfRuntime.animations[anim];
  691. if (!animation.channels || !animation.samplers) {
  692. continue;
  693. }
  694. var lastAnimation = null;
  695. for (var i = 0; i < animation.channels.length; i++) {
  696. // Get parameters and load buffers
  697. var channel = animation.channels[i];
  698. var sampler = animation.samplers[channel.sampler];
  699. if (!sampler) {
  700. continue;
  701. }
  702. var inputData = null;
  703. var outputData = null;
  704. if (animation.parameters) {
  705. inputData = animation.parameters[sampler.input];
  706. outputData = animation.parameters[sampler.output];
  707. }
  708. else {
  709. inputData = sampler.input;
  710. outputData = sampler.output;
  711. }
  712. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  713. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  714. var targetID = channel.target.id;
  715. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  716. if (targetNode === null) {
  717. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  718. }
  719. if (targetNode === null) {
  720. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  721. continue;
  722. }
  723. var isBone = targetNode instanceof BABYLON.Bone;
  724. // Get target path (position, rotation or scaling)
  725. var targetPath = channel.target.path;
  726. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  727. if (targetPathIndex !== -1) {
  728. targetPath = babylonAnimationPaths[targetPathIndex];
  729. }
  730. // Determine animation type
  731. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  732. if (!isBone) {
  733. if (targetPath === "rotationQuaternion") {
  734. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  735. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  736. }
  737. else {
  738. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  739. }
  740. }
  741. // Create animation and key frames
  742. var babylonAnimation = null;
  743. var keys = [];
  744. var arrayOffset = 0;
  745. var modifyKey = false;
  746. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  747. babylonAnimation = lastAnimation;
  748. modifyKey = true;
  749. }
  750. if (!modifyKey) {
  751. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  752. }
  753. // For each frame
  754. for (var j = 0; j < bufferInput.length; j++) {
  755. var value = null;
  756. if (targetPath === "rotationQuaternion") {
  757. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  758. arrayOffset += 4;
  759. }
  760. else {
  761. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  762. arrayOffset += 3;
  763. }
  764. if (isBone) {
  765. var bone = targetNode;
  766. var translation = BABYLON.Vector3.Zero();
  767. var rotationQuaternion = new BABYLON.Quaternion();
  768. var scaling = BABYLON.Vector3.Zero();
  769. // Warning on decompose
  770. var mat = bone.getBaseMatrix();
  771. if (modifyKey && lastAnimation) {
  772. mat = lastAnimation.getKeys()[j].value;
  773. }
  774. mat.decompose(scaling, rotationQuaternion, translation);
  775. if (targetPath === "position") {
  776. translation = value;
  777. }
  778. else if (targetPath === "rotationQuaternion") {
  779. rotationQuaternion = value;
  780. }
  781. else {
  782. scaling = value;
  783. }
  784. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  785. }
  786. if (!modifyKey) {
  787. keys.push({
  788. frame: bufferInput[j],
  789. value: value
  790. });
  791. }
  792. else if (lastAnimation) {
  793. lastAnimation.getKeys()[j].value = value;
  794. }
  795. }
  796. // Finish
  797. if (!modifyKey && babylonAnimation) {
  798. babylonAnimation.setKeys(keys);
  799. targetNode.animations.push(babylonAnimation);
  800. }
  801. lastAnimation = babylonAnimation;
  802. gltfRuntime.scene.stopAnimation(targetNode);
  803. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  804. }
  805. }
  806. };
  807. /**
  808. * Returns the bones transformation matrix
  809. */
  810. var configureBoneTransformation = function (node) {
  811. var mat = null;
  812. if (node.translation || node.rotation || node.scale) {
  813. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  814. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  815. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  816. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  817. }
  818. else {
  819. mat = BABYLON.Matrix.FromArray(node.matrix);
  820. }
  821. return mat;
  822. };
  823. /**
  824. * Returns the parent bone
  825. */
  826. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  827. // Try to find
  828. for (var i = 0; i < newSkeleton.bones.length; i++) {
  829. if (newSkeleton.bones[i].name === jointName) {
  830. return newSkeleton.bones[i];
  831. }
  832. }
  833. // Not found, search in gltf nodes
  834. var nodes = gltfRuntime.nodes;
  835. for (var nde in nodes) {
  836. var node = nodes[nde];
  837. if (!node.jointName) {
  838. continue;
  839. }
  840. var children = node.children;
  841. for (var i = 0; i < children.length; i++) {
  842. var child = gltfRuntime.nodes[children[i]];
  843. if (!child.jointName) {
  844. continue;
  845. }
  846. if (child.jointName === jointName) {
  847. var mat = configureBoneTransformation(node);
  848. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  849. bone.id = nde;
  850. return bone;
  851. }
  852. }
  853. }
  854. return null;
  855. };
  856. /**
  857. * Returns the appropriate root node
  858. */
  859. var getNodeToRoot = function (nodesToRoot, id) {
  860. for (var i = 0; i < nodesToRoot.length; i++) {
  861. var nodeToRoot = nodesToRoot[i];
  862. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  863. var child = nodeToRoot.node.children[j];
  864. if (child === id) {
  865. return nodeToRoot.bone;
  866. }
  867. }
  868. }
  869. return null;
  870. };
  871. /**
  872. * Returns the node with the joint name
  873. */
  874. var getJointNode = function (gltfRuntime, jointName) {
  875. var nodes = gltfRuntime.nodes;
  876. var node = nodes[jointName];
  877. if (node) {
  878. return {
  879. node: node,
  880. id: jointName
  881. };
  882. }
  883. for (var nde in nodes) {
  884. node = nodes[nde];
  885. if (node.jointName === jointName) {
  886. return {
  887. node: node,
  888. id: nde
  889. };
  890. }
  891. }
  892. return null;
  893. };
  894. /**
  895. * Checks if a nodes is in joints
  896. */
  897. var nodeIsInJoints = function (skins, id) {
  898. for (var i = 0; i < skins.jointNames.length; i++) {
  899. if (skins.jointNames[i] === id) {
  900. return true;
  901. }
  902. }
  903. return false;
  904. };
  905. /**
  906. * Fills the nodes to root for bones and builds hierarchy
  907. */
  908. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  909. // Creates nodes for root
  910. for (var nde in gltfRuntime.nodes) {
  911. var node = gltfRuntime.nodes[nde];
  912. var id = nde;
  913. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  914. continue;
  915. }
  916. // Create node to root bone
  917. var mat = configureBoneTransformation(node);
  918. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  919. bone.id = id;
  920. nodesToRoot.push({ bone: bone, node: node, id: id });
  921. }
  922. // Parenting
  923. for (var i = 0; i < nodesToRoot.length; i++) {
  924. var nodeToRoot = nodesToRoot[i];
  925. var children = nodeToRoot.node.children;
  926. for (var j = 0; j < children.length; j++) {
  927. var child = null;
  928. for (var k = 0; k < nodesToRoot.length; k++) {
  929. if (nodesToRoot[k].id === children[j]) {
  930. child = nodesToRoot[k];
  931. break;
  932. }
  933. }
  934. if (child) {
  935. child.bone._parent = nodeToRoot.bone;
  936. nodeToRoot.bone.children.push(child.bone);
  937. }
  938. }
  939. }
  940. };
  941. /**
  942. * Imports a skeleton
  943. */
  944. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  945. if (!newSkeleton) {
  946. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  947. }
  948. if (!skins.babylonSkeleton) {
  949. return newSkeleton;
  950. }
  951. // Find the root bones
  952. var nodesToRoot = [];
  953. var nodesToRootToAdd = [];
  954. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  955. newSkeleton.bones = [];
  956. // Joints
  957. for (var i = 0; i < skins.jointNames.length; i++) {
  958. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  959. if (!jointNode) {
  960. continue;
  961. }
  962. var node = jointNode.node;
  963. if (!node) {
  964. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  965. continue;
  966. }
  967. var id = jointNode.id;
  968. // Optimize, if the bone already exists...
  969. var existingBone = gltfRuntime.scene.getBoneByID(id);
  970. if (existingBone) {
  971. newSkeleton.bones.push(existingBone);
  972. continue;
  973. }
  974. // Search for parent bone
  975. var foundBone = false;
  976. var parentBone = null;
  977. for (var j = 0; j < i; j++) {
  978. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  979. if (!jointNode_1) {
  980. continue;
  981. }
  982. var joint = jointNode_1.node;
  983. if (!joint) {
  984. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  985. continue;
  986. }
  987. var children = joint.children;
  988. if (!children) {
  989. continue;
  990. }
  991. foundBone = false;
  992. for (var k = 0; k < children.length; k++) {
  993. if (children[k] === id) {
  994. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  995. foundBone = true;
  996. break;
  997. }
  998. }
  999. if (foundBone) {
  1000. break;
  1001. }
  1002. }
  1003. // Create bone
  1004. var mat = configureBoneTransformation(node);
  1005. if (!parentBone && nodesToRoot.length > 0) {
  1006. parentBone = getNodeToRoot(nodesToRoot, id);
  1007. if (parentBone) {
  1008. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  1009. nodesToRootToAdd.push(parentBone);
  1010. }
  1011. }
  1012. }
  1013. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  1014. bone.id = id;
  1015. }
  1016. // Polish
  1017. var bones = newSkeleton.bones;
  1018. newSkeleton.bones = [];
  1019. for (var i = 0; i < skins.jointNames.length; i++) {
  1020. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1021. if (!jointNode) {
  1022. continue;
  1023. }
  1024. for (var j = 0; j < bones.length; j++) {
  1025. if (bones[j].id === jointNode.id) {
  1026. newSkeleton.bones.push(bones[j]);
  1027. break;
  1028. }
  1029. }
  1030. }
  1031. newSkeleton.prepare();
  1032. // Finish
  1033. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1034. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1035. }
  1036. return newSkeleton;
  1037. };
  1038. /**
  1039. * Imports a mesh and its geometries
  1040. */
  1041. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1042. if (!newMesh) {
  1043. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1044. newMesh.id = id;
  1045. }
  1046. if (!node.babylonNode) {
  1047. return newMesh;
  1048. }
  1049. var subMaterials = [];
  1050. var vertexData = null;
  1051. var verticesStarts = new Array();
  1052. var verticesCounts = new Array();
  1053. var indexStarts = new Array();
  1054. var indexCounts = new Array();
  1055. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1056. var meshID = meshes[meshIndex];
  1057. var mesh = gltfRuntime.meshes[meshID];
  1058. if (!mesh) {
  1059. continue;
  1060. }
  1061. // Positions, normals and UVs
  1062. for (var i = 0; i < mesh.primitives.length; i++) {
  1063. // Temporary vertex data
  1064. var tempVertexData = new BABYLON.VertexData();
  1065. var primitive = mesh.primitives[i];
  1066. if (primitive.mode !== 4) {
  1067. // continue;
  1068. }
  1069. var attributes = primitive.attributes;
  1070. var accessor = null;
  1071. var buffer = null;
  1072. // Set positions, normal and uvs
  1073. for (var semantic in attributes) {
  1074. // Link accessor and buffer view
  1075. accessor = gltfRuntime.accessors[attributes[semantic]];
  1076. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1077. if (semantic === "NORMAL") {
  1078. tempVertexData.normals = new Float32Array(buffer.length);
  1079. tempVertexData.normals.set(buffer);
  1080. }
  1081. else if (semantic === "POSITION") {
  1082. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  1083. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  1084. for (var j = 0; j < buffer.length; j += 4) {
  1085. tempVertexData.positions[j] = buffer[j];
  1086. tempVertexData.positions[j + 1] = buffer[j + 1];
  1087. tempVertexData.positions[j + 2] = buffer[j + 2];
  1088. }
  1089. }
  1090. else {
  1091. tempVertexData.positions = new Float32Array(buffer.length);
  1092. tempVertexData.positions.set(buffer);
  1093. }
  1094. verticesCounts.push(tempVertexData.positions.length);
  1095. }
  1096. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  1097. var channel = Number(semantic.split("_")[1]);
  1098. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  1099. var uvs = new Float32Array(buffer.length);
  1100. uvs.set(buffer);
  1101. normalizeUVs(uvs);
  1102. tempVertexData.set(uvs, uvKind);
  1103. }
  1104. else if (semantic === "JOINT") {
  1105. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  1106. tempVertexData.matricesIndices.set(buffer);
  1107. }
  1108. else if (semantic === "WEIGHT") {
  1109. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  1110. tempVertexData.matricesWeights.set(buffer);
  1111. }
  1112. else if (semantic === "COLOR") {
  1113. tempVertexData.colors = new Float32Array(buffer.length);
  1114. tempVertexData.colors.set(buffer);
  1115. }
  1116. }
  1117. // Indices
  1118. accessor = gltfRuntime.accessors[primitive.indices];
  1119. if (accessor) {
  1120. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1121. tempVertexData.indices = new Int32Array(buffer.length);
  1122. tempVertexData.indices.set(buffer);
  1123. indexCounts.push(tempVertexData.indices.length);
  1124. }
  1125. else {
  1126. // Set indices on the fly
  1127. var indices = [];
  1128. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  1129. indices.push(j);
  1130. }
  1131. tempVertexData.indices = new Int32Array(indices);
  1132. indexCounts.push(tempVertexData.indices.length);
  1133. }
  1134. if (!vertexData) {
  1135. vertexData = tempVertexData;
  1136. }
  1137. else {
  1138. vertexData.merge(tempVertexData);
  1139. }
  1140. // Sub material
  1141. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  1142. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  1143. // Update vertices start and index start
  1144. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  1145. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  1146. }
  1147. }
  1148. var material;
  1149. if (subMaterials.length > 1) {
  1150. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  1151. material.subMaterials = subMaterials;
  1152. }
  1153. else {
  1154. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  1155. }
  1156. if (subMaterials.length === 1) {
  1157. material = subMaterials[0];
  1158. }
  1159. if (!newMesh.material) {
  1160. newMesh.material = material;
  1161. }
  1162. // Apply geometry
  1163. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  1164. newMesh.computeWorldMatrix(true);
  1165. // Apply submeshes
  1166. newMesh.subMeshes = [];
  1167. var index = 0;
  1168. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1169. var meshID = meshes[meshIndex];
  1170. var mesh = gltfRuntime.meshes[meshID];
  1171. if (!mesh) {
  1172. continue;
  1173. }
  1174. for (var i = 0; i < mesh.primitives.length; i++) {
  1175. if (mesh.primitives[i].mode !== 4) {
  1176. //continue;
  1177. }
  1178. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  1179. index++;
  1180. }
  1181. }
  1182. // Finish
  1183. return newMesh;
  1184. };
  1185. /**
  1186. * Configure node transformation from position, rotation and scaling
  1187. */
  1188. var configureNode = function (newNode, position, rotation, scaling) {
  1189. if (newNode.position) {
  1190. newNode.position = position;
  1191. }
  1192. if (newNode.rotationQuaternion || newNode.rotation) {
  1193. newNode.rotationQuaternion = rotation;
  1194. }
  1195. if (newNode.scaling) {
  1196. newNode.scaling = scaling;
  1197. }
  1198. };
  1199. /**
  1200. * Configures node from transformation matrix
  1201. */
  1202. var configureNodeFromMatrix = function (newNode, node, parent) {
  1203. if (node.matrix) {
  1204. var position = new BABYLON.Vector3(0, 0, 0);
  1205. var rotation = new BABYLON.Quaternion();
  1206. var scaling = new BABYLON.Vector3(0, 0, 0);
  1207. var mat = BABYLON.Matrix.FromArray(node.matrix);
  1208. mat.decompose(scaling, rotation, position);
  1209. configureNode(newNode, position, rotation, scaling);
  1210. }
  1211. else if (node.translation && node.rotation && node.scale) {
  1212. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  1213. }
  1214. newNode.computeWorldMatrix(true);
  1215. };
  1216. /**
  1217. * Imports a node
  1218. */
  1219. var importNode = function (gltfRuntime, node, id, parent) {
  1220. var lastNode = null;
  1221. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  1222. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  1223. return null;
  1224. }
  1225. }
  1226. // Meshes
  1227. if (node.skin) {
  1228. if (node.meshes) {
  1229. var skin = gltfRuntime.skins[node.skin];
  1230. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1231. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1232. if (newMesh.skeleton === null) {
  1233. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1234. if (!skin.babylonSkeleton) {
  1235. skin.babylonSkeleton = newMesh.skeleton;
  1236. }
  1237. }
  1238. lastNode = newMesh;
  1239. }
  1240. }
  1241. else if (node.meshes) {
  1242. /**
  1243. * Improve meshes property
  1244. */
  1245. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1246. lastNode = newMesh;
  1247. }
  1248. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1249. var light = gltfRuntime.lights[node.light];
  1250. if (light) {
  1251. if (light.type === "ambient") {
  1252. var ambienLight = light[light.type];
  1253. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1254. hemiLight.name = node.name || "";
  1255. if (ambienLight.color) {
  1256. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1257. }
  1258. lastNode = hemiLight;
  1259. }
  1260. else if (light.type === "directional") {
  1261. var directionalLight = light[light.type];
  1262. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1263. dirLight.name = node.name || "";
  1264. if (directionalLight.color) {
  1265. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1266. }
  1267. lastNode = dirLight;
  1268. }
  1269. else if (light.type === "point") {
  1270. var pointLight = light[light.type];
  1271. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1272. ptLight.name = node.name || "";
  1273. if (pointLight.color) {
  1274. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1275. }
  1276. lastNode = ptLight;
  1277. }
  1278. else if (light.type === "spot") {
  1279. var spotLight = light[light.type];
  1280. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1281. spLight.name = node.name || "";
  1282. if (spotLight.color) {
  1283. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1284. }
  1285. if (spotLight.fallOfAngle) {
  1286. spLight.angle = spotLight.fallOfAngle;
  1287. }
  1288. if (spotLight.fallOffExponent) {
  1289. spLight.exponent = spotLight.fallOffExponent;
  1290. }
  1291. lastNode = spLight;
  1292. }
  1293. }
  1294. }
  1295. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1296. var camera = gltfRuntime.cameras[node.camera];
  1297. if (camera) {
  1298. if (camera.type === "orthographic") {
  1299. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1300. orthoCamera.name = node.name || "";
  1301. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1302. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1303. lastNode = orthoCamera;
  1304. }
  1305. else if (camera.type === "perspective") {
  1306. var perspectiveCamera = camera[camera.type];
  1307. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1308. persCamera.name = node.name || "";
  1309. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1310. if (!perspectiveCamera.aspectRatio) {
  1311. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1312. }
  1313. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1314. persCamera.maxZ = perspectiveCamera.zfar;
  1315. persCamera.minZ = perspectiveCamera.znear;
  1316. }
  1317. lastNode = persCamera;
  1318. }
  1319. }
  1320. }
  1321. // Empty node
  1322. if (!node.jointName) {
  1323. if (node.babylonNode) {
  1324. return node.babylonNode;
  1325. }
  1326. else if (lastNode === null) {
  1327. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1328. node.babylonNode = dummy;
  1329. lastNode = dummy;
  1330. }
  1331. }
  1332. if (lastNode !== null) {
  1333. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1334. configureNodeFromMatrix(lastNode, node, parent);
  1335. }
  1336. else {
  1337. var translation = node.translation || [0, 0, 0];
  1338. var rotation = node.rotation || [0, 0, 0, 1];
  1339. var scale = node.scale || [1, 1, 1];
  1340. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1341. }
  1342. lastNode.updateCache(true);
  1343. node.babylonNode = lastNode;
  1344. }
  1345. return lastNode;
  1346. };
  1347. /**
  1348. * Traverses nodes and creates them
  1349. */
  1350. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1351. if (meshIncluded === void 0) { meshIncluded = false; }
  1352. var node = gltfRuntime.nodes[id];
  1353. var newNode = null;
  1354. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1355. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1356. meshIncluded = true;
  1357. }
  1358. else {
  1359. meshIncluded = false;
  1360. }
  1361. }
  1362. else {
  1363. meshIncluded = true;
  1364. }
  1365. if (!node.jointName && meshIncluded) {
  1366. newNode = importNode(gltfRuntime, node, id, parent);
  1367. if (newNode !== null) {
  1368. newNode.id = id;
  1369. newNode.parent = parent;
  1370. }
  1371. }
  1372. if (node.children) {
  1373. for (var i = 0; i < node.children.length; i++) {
  1374. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1375. }
  1376. }
  1377. };
  1378. /**
  1379. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1380. */
  1381. var postLoad = function (gltfRuntime) {
  1382. // Nodes
  1383. var currentScene = gltfRuntime.currentScene;
  1384. if (currentScene) {
  1385. for (var i = 0; i < currentScene.nodes.length; i++) {
  1386. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1387. }
  1388. }
  1389. else {
  1390. for (var thing in gltfRuntime.scenes) {
  1391. currentScene = gltfRuntime.scenes[thing];
  1392. for (var i = 0; i < currentScene.nodes.length; i++) {
  1393. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1394. }
  1395. }
  1396. }
  1397. // Set animations
  1398. loadAnimations(gltfRuntime);
  1399. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1400. var skeleton = gltfRuntime.scene.skeletons[i];
  1401. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1402. }
  1403. };
  1404. /**
  1405. * onBind shaderrs callback to set uniforms and matrices
  1406. */
  1407. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1408. var materialValues = material.values || technique.parameters;
  1409. for (var unif in unTreatedUniforms) {
  1410. var uniform = unTreatedUniforms[unif];
  1411. var type = uniform.type;
  1412. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1413. if (uniform.semantic && !uniform.source && !uniform.node) {
  1414. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1415. }
  1416. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1417. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1418. if (source === null) {
  1419. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1420. }
  1421. if (source === null) {
  1422. continue;
  1423. }
  1424. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1425. }
  1426. }
  1427. else {
  1428. var value = materialValues[technique.uniforms[unif]];
  1429. if (!value) {
  1430. continue;
  1431. }
  1432. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1433. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1434. if (texture === null || texture === undefined) {
  1435. continue;
  1436. }
  1437. shaderMaterial.getEffect().setTexture(unif, texture);
  1438. }
  1439. else {
  1440. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1441. }
  1442. }
  1443. }
  1444. onSuccess(shaderMaterial);
  1445. };
  1446. /**
  1447. * Prepare uniforms to send the only one time
  1448. * Loads the appropriate textures
  1449. */
  1450. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1451. var materialValues = material.values || technique.parameters;
  1452. var techniqueUniforms = technique.uniforms;
  1453. /**
  1454. * Prepare values here (not matrices)
  1455. */
  1456. for (var unif in unTreatedUniforms) {
  1457. var uniform = unTreatedUniforms[unif];
  1458. var type = uniform.type;
  1459. var value = materialValues[techniqueUniforms[unif]];
  1460. if (value === undefined) {
  1461. // In case the value is the same for all materials
  1462. value = uniform.value;
  1463. }
  1464. if (!value) {
  1465. continue;
  1466. }
  1467. var onLoadTexture = function (uniformName) {
  1468. return function (texture) {
  1469. if (uniform.value && uniformName) {
  1470. // Static uniform
  1471. shaderMaterial.setTexture(uniformName, texture);
  1472. delete unTreatedUniforms[uniformName];
  1473. }
  1474. };
  1475. };
  1476. // Texture (sampler2D)
  1477. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1478. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1479. }
  1480. else {
  1481. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1482. // Static uniform
  1483. delete unTreatedUniforms[unif];
  1484. }
  1485. }
  1486. }
  1487. };
  1488. /**
  1489. * Shader compilation failed
  1490. */
  1491. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1492. return function (effect, error) {
  1493. shaderMaterial.dispose(true);
  1494. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1495. };
  1496. };
  1497. /**
  1498. * Shader compilation success
  1499. */
  1500. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1501. return function (_) {
  1502. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1503. shaderMaterial.onBind = function (mesh) {
  1504. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1505. };
  1506. };
  1507. };
  1508. /**
  1509. * Returns the appropriate uniform if already handled by babylon
  1510. */
  1511. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1512. for (var unif in technique.uniforms) {
  1513. var uniform = technique.uniforms[unif];
  1514. var uniformParameter = technique.parameters[uniform];
  1515. if (tokenizer.currentIdentifier === unif) {
  1516. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1517. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1518. if (transformIndex !== -1) {
  1519. delete unTreatedUniforms[unif];
  1520. return babylonTransforms[transformIndex];
  1521. }
  1522. }
  1523. }
  1524. }
  1525. return tokenizer.currentIdentifier;
  1526. };
  1527. /**
  1528. * All shaders loaded. Create materials one by one
  1529. */
  1530. var importMaterials = function (gltfRuntime) {
  1531. // Create materials
  1532. for (var mat in gltfRuntime.materials) {
  1533. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1534. }
  1535. };
  1536. /**
  1537. * Implementation of the base glTF spec
  1538. */
  1539. var GLTFLoaderBase = /** @class */ (function () {
  1540. function GLTFLoaderBase() {
  1541. }
  1542. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1543. var gltfRuntime = {
  1544. extensions: {},
  1545. accessors: {},
  1546. buffers: {},
  1547. bufferViews: {},
  1548. meshes: {},
  1549. lights: {},
  1550. cameras: {},
  1551. nodes: {},
  1552. images: {},
  1553. textures: {},
  1554. shaders: {},
  1555. programs: {},
  1556. samplers: {},
  1557. techniques: {},
  1558. materials: {},
  1559. animations: {},
  1560. skins: {},
  1561. extensionsUsed: [],
  1562. scenes: {},
  1563. buffersCount: 0,
  1564. shaderscount: 0,
  1565. scene: scene,
  1566. rootUrl: rootUrl,
  1567. loadedBufferCount: 0,
  1568. loadedBufferViews: {},
  1569. loadedShaderCount: 0,
  1570. importOnlyMeshes: false,
  1571. dummyNodes: []
  1572. };
  1573. // Parse
  1574. if (parsedData.extensions) {
  1575. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1576. }
  1577. if (parsedData.extensionsUsed) {
  1578. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1579. }
  1580. if (parsedData.buffers) {
  1581. parseBuffers(parsedData.buffers, gltfRuntime);
  1582. }
  1583. if (parsedData.bufferViews) {
  1584. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1585. }
  1586. if (parsedData.accessors) {
  1587. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1588. }
  1589. if (parsedData.meshes) {
  1590. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1591. }
  1592. if (parsedData.lights) {
  1593. parseObject(parsedData.lights, "lights", gltfRuntime);
  1594. }
  1595. if (parsedData.cameras) {
  1596. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1597. }
  1598. if (parsedData.nodes) {
  1599. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1600. }
  1601. if (parsedData.images) {
  1602. parseObject(parsedData.images, "images", gltfRuntime);
  1603. }
  1604. if (parsedData.textures) {
  1605. parseObject(parsedData.textures, "textures", gltfRuntime);
  1606. }
  1607. if (parsedData.shaders) {
  1608. parseShaders(parsedData.shaders, gltfRuntime);
  1609. }
  1610. if (parsedData.programs) {
  1611. parseObject(parsedData.programs, "programs", gltfRuntime);
  1612. }
  1613. if (parsedData.samplers) {
  1614. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1615. }
  1616. if (parsedData.techniques) {
  1617. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1618. }
  1619. if (parsedData.materials) {
  1620. parseObject(parsedData.materials, "materials", gltfRuntime);
  1621. }
  1622. if (parsedData.animations) {
  1623. parseObject(parsedData.animations, "animations", gltfRuntime);
  1624. }
  1625. if (parsedData.skins) {
  1626. parseObject(parsedData.skins, "skins", gltfRuntime);
  1627. }
  1628. if (parsedData.scenes) {
  1629. gltfRuntime.scenes = parsedData.scenes;
  1630. }
  1631. if (parsedData.scene && parsedData.scenes) {
  1632. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1633. }
  1634. return gltfRuntime;
  1635. };
  1636. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1637. var buffer = gltfRuntime.buffers[id];
  1638. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  1639. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  1640. }
  1641. else {
  1642. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1643. if (request) {
  1644. onError(request.status + " " + request.statusText);
  1645. }
  1646. });
  1647. }
  1648. };
  1649. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1650. var texture = gltfRuntime.textures[id];
  1651. if (!texture || !texture.source) {
  1652. onError("");
  1653. return;
  1654. }
  1655. if (texture.babylonTexture) {
  1656. onSuccess(null);
  1657. return;
  1658. }
  1659. var source = gltfRuntime.images[texture.source];
  1660. if (BABYLON.Tools.IsBase64(source.uri)) {
  1661. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  1662. }
  1663. else {
  1664. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1665. if (request) {
  1666. onError(request.status + " " + request.statusText);
  1667. }
  1668. });
  1669. }
  1670. };
  1671. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1672. var texture = gltfRuntime.textures[id];
  1673. if (texture.babylonTexture) {
  1674. onSuccess(texture.babylonTexture);
  1675. return;
  1676. }
  1677. var sampler = gltfRuntime.samplers[texture.sampler];
  1678. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1679. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1680. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1681. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1682. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1683. var blob = new Blob([buffer]);
  1684. var blobURL = URL.createObjectURL(blob);
  1685. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1686. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1687. if (sampler.wrapS !== undefined) {
  1688. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1689. }
  1690. if (sampler.wrapT !== undefined) {
  1691. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1692. }
  1693. newTexture.name = id;
  1694. texture.babylonTexture = newTexture;
  1695. onSuccess(newTexture);
  1696. };
  1697. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1698. var shader = gltfRuntime.shaders[id];
  1699. if (BABYLON.Tools.IsBase64(shader.uri)) {
  1700. var shaderString = atob(shader.uri.split(",")[1]);
  1701. onSuccess(shaderString);
  1702. }
  1703. else {
  1704. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1705. if (request) {
  1706. onError(request.status + " " + request.statusText);
  1707. }
  1708. });
  1709. }
  1710. };
  1711. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1712. var material = gltfRuntime.materials[id];
  1713. if (!material.technique) {
  1714. if (onError) {
  1715. onError("No technique found.");
  1716. }
  1717. return;
  1718. }
  1719. var technique = gltfRuntime.techniques[material.technique];
  1720. if (!technique) {
  1721. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1722. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1723. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1724. onSuccess(defaultMaterial);
  1725. return;
  1726. }
  1727. var program = gltfRuntime.programs[technique.program];
  1728. var states = technique.states;
  1729. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1730. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1731. var newVertexShader = "";
  1732. var newPixelShader = "";
  1733. var vertexTokenizer = new Tokenizer(vertexShader);
  1734. var pixelTokenizer = new Tokenizer(pixelShader);
  1735. var unTreatedUniforms = {};
  1736. var uniforms = [];
  1737. var attributes = [];
  1738. var samplers = [];
  1739. // Fill uniform, sampler2D and attributes
  1740. for (var unif in technique.uniforms) {
  1741. var uniform = technique.uniforms[unif];
  1742. var uniformParameter = technique.parameters[uniform];
  1743. unTreatedUniforms[unif] = uniformParameter;
  1744. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1745. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1746. if (transformIndex !== -1) {
  1747. uniforms.push(babylonTransforms[transformIndex]);
  1748. delete unTreatedUniforms[unif];
  1749. }
  1750. else {
  1751. uniforms.push(unif);
  1752. }
  1753. }
  1754. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1755. samplers.push(unif);
  1756. }
  1757. else {
  1758. uniforms.push(unif);
  1759. }
  1760. }
  1761. for (var attr in technique.attributes) {
  1762. var attribute = technique.attributes[attr];
  1763. var attributeParameter = technique.parameters[attribute];
  1764. if (attributeParameter.semantic) {
  1765. attributes.push(getAttribute(attributeParameter));
  1766. }
  1767. }
  1768. // Configure vertex shader
  1769. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1770. var tokenType = vertexTokenizer.currentToken;
  1771. if (tokenType !== ETokenType.IDENTIFIER) {
  1772. newVertexShader += vertexTokenizer.currentString;
  1773. continue;
  1774. }
  1775. var foundAttribute = false;
  1776. for (var attr in technique.attributes) {
  1777. var attribute = technique.attributes[attr];
  1778. var attributeParameter = technique.parameters[attribute];
  1779. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1780. newVertexShader += getAttribute(attributeParameter);
  1781. foundAttribute = true;
  1782. break;
  1783. }
  1784. }
  1785. if (foundAttribute) {
  1786. continue;
  1787. }
  1788. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1789. }
  1790. // Configure pixel shader
  1791. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1792. var tokenType = pixelTokenizer.currentToken;
  1793. if (tokenType !== ETokenType.IDENTIFIER) {
  1794. newPixelShader += pixelTokenizer.currentString;
  1795. continue;
  1796. }
  1797. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1798. }
  1799. // Create shader material
  1800. var shaderPath = {
  1801. vertex: program.vertexShader + id,
  1802. fragment: program.fragmentShader + id
  1803. };
  1804. var options = {
  1805. attributes: attributes,
  1806. uniforms: uniforms,
  1807. samplers: samplers,
  1808. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1809. };
  1810. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1811. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1812. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1813. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1814. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1815. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1816. if (states && states.functions) {
  1817. var functions = states.functions;
  1818. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1819. shaderMaterial.backFaceCulling = false;
  1820. }
  1821. var blendFunc = functions.blendFuncSeparate;
  1822. if (blendFunc) {
  1823. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1824. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1825. }
  1826. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1827. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1828. }
  1829. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1830. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1831. }
  1832. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1833. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1834. }
  1835. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1836. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1837. }
  1838. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1839. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1840. }
  1841. }
  1842. }
  1843. };
  1844. return GLTFLoaderBase;
  1845. }());
  1846. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1847. /**
  1848. * glTF V1 Loader
  1849. */
  1850. var GLTFLoader = /** @class */ (function () {
  1851. function GLTFLoader() {
  1852. // #region Stubs for IGLTFLoader interface
  1853. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  1854. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  1855. this.compileMaterials = false;
  1856. this.useClipPlane = false;
  1857. this.compileShadowGenerators = false;
  1858. this.onDisposeObservable = new BABYLON.Observable();
  1859. this.onMeshLoadedObservable = new BABYLON.Observable();
  1860. this.onTextureLoadedObservable = new BABYLON.Observable();
  1861. this.onMaterialLoadedObservable = new BABYLON.Observable();
  1862. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  1863. this.onCompleteObservable = new BABYLON.Observable();
  1864. this.onExtensionLoadedObservable = new BABYLON.Observable();
  1865. this.state = null;
  1866. }
  1867. GLTFLoader.RegisterExtension = function (extension) {
  1868. if (GLTFLoader.Extensions[extension.name]) {
  1869. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1870. return;
  1871. }
  1872. GLTFLoader.Extensions[extension.name] = extension;
  1873. };
  1874. GLTFLoader.prototype.dispose = function () { };
  1875. // #endregion
  1876. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1877. var _this = this;
  1878. scene.useRightHandedSystem = true;
  1879. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1880. gltfRuntime.importOnlyMeshes = true;
  1881. if (meshesNames === "") {
  1882. gltfRuntime.importMeshesNames = [];
  1883. }
  1884. else if (typeof meshesNames === "string") {
  1885. gltfRuntime.importMeshesNames = [meshesNames];
  1886. }
  1887. else if (meshesNames && !(meshesNames instanceof Array)) {
  1888. gltfRuntime.importMeshesNames = [meshesNames];
  1889. }
  1890. else {
  1891. gltfRuntime.importMeshesNames = [];
  1892. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1893. }
  1894. // Create nodes
  1895. _this._createNodes(gltfRuntime);
  1896. var meshes = new Array();
  1897. var skeletons = new Array();
  1898. // Fill arrays of meshes and skeletons
  1899. for (var nde in gltfRuntime.nodes) {
  1900. var node = gltfRuntime.nodes[nde];
  1901. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1902. meshes.push(node.babylonNode);
  1903. }
  1904. }
  1905. for (var skl in gltfRuntime.skins) {
  1906. var skin = gltfRuntime.skins[skl];
  1907. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1908. skeletons.push(skin.babylonSkeleton);
  1909. }
  1910. }
  1911. // Load buffers, shaders, materials, etc.
  1912. _this._loadBuffersAsync(gltfRuntime, function () {
  1913. _this._loadShadersAsync(gltfRuntime, function () {
  1914. importMaterials(gltfRuntime);
  1915. postLoad(gltfRuntime);
  1916. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1917. onSuccess(meshes, [], skeletons);
  1918. }
  1919. });
  1920. }, onProgress);
  1921. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1922. onSuccess(meshes, [], skeletons);
  1923. }
  1924. }, onError);
  1925. return true;
  1926. };
  1927. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1928. var _this = this;
  1929. return new Promise(function (resolve, reject) {
  1930. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  1931. resolve({
  1932. meshes: meshes,
  1933. particleSystems: particleSystems,
  1934. skeletons: skeletons
  1935. });
  1936. }, onProgress, function (message) {
  1937. reject(new Error(message));
  1938. });
  1939. });
  1940. };
  1941. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1942. var _this = this;
  1943. scene.useRightHandedSystem = true;
  1944. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1945. // Load runtime extensios
  1946. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1947. // Create nodes
  1948. _this._createNodes(gltfRuntime);
  1949. // Load buffers, shaders, materials, etc.
  1950. _this._loadBuffersAsync(gltfRuntime, function () {
  1951. _this._loadShadersAsync(gltfRuntime, function () {
  1952. importMaterials(gltfRuntime);
  1953. postLoad(gltfRuntime);
  1954. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1955. onSuccess();
  1956. }
  1957. });
  1958. });
  1959. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1960. onSuccess();
  1961. }
  1962. }, onError);
  1963. }, onError);
  1964. };
  1965. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1966. var _this = this;
  1967. return new Promise(function (resolve, reject) {
  1968. _this._loadAsync(scene, data, rootUrl, function () {
  1969. resolve();
  1970. }, onProgress, function (message) {
  1971. reject(new Error(message));
  1972. });
  1973. });
  1974. };
  1975. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1976. var hasShaders = false;
  1977. var processShader = function (sha, shader) {
  1978. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1979. gltfRuntime.loadedShaderCount++;
  1980. if (shaderString) {
  1981. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1982. }
  1983. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1984. onload();
  1985. }
  1986. }, function () {
  1987. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1988. });
  1989. };
  1990. for (var sha in gltfRuntime.shaders) {
  1991. hasShaders = true;
  1992. var shader = gltfRuntime.shaders[sha];
  1993. if (shader) {
  1994. processShader.bind(this, sha, shader)();
  1995. }
  1996. else {
  1997. BABYLON.Tools.Error("No shader named: " + sha);
  1998. }
  1999. }
  2000. if (!hasShaders) {
  2001. onload();
  2002. }
  2003. };
  2004. ;
  2005. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  2006. var hasBuffers = false;
  2007. var processBuffer = function (buf, buffer) {
  2008. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  2009. gltfRuntime.loadedBufferCount++;
  2010. if (bufferView) {
  2011. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  2012. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  2013. }
  2014. gltfRuntime.loadedBufferViews[buf] = bufferView;
  2015. }
  2016. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  2017. onLoad();
  2018. }
  2019. }, function () {
  2020. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  2021. });
  2022. };
  2023. for (var buf in gltfRuntime.buffers) {
  2024. hasBuffers = true;
  2025. var buffer = gltfRuntime.buffers[buf];
  2026. if (buffer) {
  2027. processBuffer.bind(this, buf, buffer)();
  2028. }
  2029. else {
  2030. BABYLON.Tools.Error("No buffer named: " + buf);
  2031. }
  2032. }
  2033. if (!hasBuffers) {
  2034. onLoad();
  2035. }
  2036. };
  2037. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2038. var currentScene = gltfRuntime.currentScene;
  2039. if (currentScene) {
  2040. // Only one scene even if multiple scenes are defined
  2041. for (var i = 0; i < currentScene.nodes.length; i++) {
  2042. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2043. }
  2044. }
  2045. else {
  2046. // Load all scenes
  2047. for (var thing in gltfRuntime.scenes) {
  2048. currentScene = gltfRuntime.scenes[thing];
  2049. for (var i = 0; i < currentScene.nodes.length; i++) {
  2050. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2051. }
  2052. }
  2053. }
  2054. };
  2055. GLTFLoader.Extensions = {};
  2056. return GLTFLoader;
  2057. }());
  2058. GLTF1.GLTFLoader = GLTFLoader;
  2059. ;
  2060. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2061. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2062. })(BABYLON || (BABYLON = {}));
  2063. //# sourceMappingURL=babylon.glTFLoader.js.map
  2064. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2065. var BABYLON;
  2066. (function (BABYLON) {
  2067. var GLTF1;
  2068. (function (GLTF1) {
  2069. /**
  2070. * Utils functions for GLTF
  2071. */
  2072. var GLTFUtils = /** @class */ (function () {
  2073. function GLTFUtils() {
  2074. }
  2075. /**
  2076. * Sets the given "parameter" matrix
  2077. * @param scene: the {BABYLON.Scene} object
  2078. * @param source: the source node where to pick the matrix
  2079. * @param parameter: the GLTF technique parameter
  2080. * @param uniformName: the name of the shader's uniform
  2081. * @param shaderMaterial: the shader material
  2082. */
  2083. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2084. var mat = null;
  2085. if (parameter.semantic === "MODEL") {
  2086. mat = source.getWorldMatrix();
  2087. }
  2088. else if (parameter.semantic === "PROJECTION") {
  2089. mat = scene.getProjectionMatrix();
  2090. }
  2091. else if (parameter.semantic === "VIEW") {
  2092. mat = scene.getViewMatrix();
  2093. }
  2094. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2095. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2096. }
  2097. else if (parameter.semantic === "MODELVIEW") {
  2098. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2099. }
  2100. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2101. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2102. }
  2103. else if (parameter.semantic === "MODELINVERSE") {
  2104. mat = source.getWorldMatrix().invert();
  2105. }
  2106. else if (parameter.semantic === "VIEWINVERSE") {
  2107. mat = scene.getViewMatrix().invert();
  2108. }
  2109. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2110. mat = scene.getProjectionMatrix().invert();
  2111. }
  2112. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2113. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2114. }
  2115. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2116. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2117. }
  2118. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2119. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2120. }
  2121. else {
  2122. debugger;
  2123. }
  2124. if (mat) {
  2125. switch (parameter.type) {
  2126. case GLTF1.EParameterType.FLOAT_MAT2:
  2127. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2128. break;
  2129. case GLTF1.EParameterType.FLOAT_MAT3:
  2130. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2131. break;
  2132. case GLTF1.EParameterType.FLOAT_MAT4:
  2133. shaderMaterial.setMatrix(uniformName, mat);
  2134. break;
  2135. default: break;
  2136. }
  2137. }
  2138. };
  2139. /**
  2140. * Sets the given "parameter" matrix
  2141. * @param shaderMaterial: the shader material
  2142. * @param uniform: the name of the shader's uniform
  2143. * @param value: the value of the uniform
  2144. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2145. */
  2146. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2147. switch (type) {
  2148. case GLTF1.EParameterType.FLOAT:
  2149. shaderMaterial.setFloat(uniform, value);
  2150. return true;
  2151. case GLTF1.EParameterType.FLOAT_VEC2:
  2152. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2153. return true;
  2154. case GLTF1.EParameterType.FLOAT_VEC3:
  2155. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2156. return true;
  2157. case GLTF1.EParameterType.FLOAT_VEC4:
  2158. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2159. return true;
  2160. default: return false;
  2161. }
  2162. };
  2163. /**
  2164. * Returns the wrap mode of the texture
  2165. * @param mode: the mode value
  2166. */
  2167. GLTFUtils.GetWrapMode = function (mode) {
  2168. switch (mode) {
  2169. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2170. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2171. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2172. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2173. }
  2174. };
  2175. /**
  2176. * Returns the byte stride giving an accessor
  2177. * @param accessor: the GLTF accessor objet
  2178. */
  2179. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2180. // Needs this function since "byteStride" isn't requiered in glTF format
  2181. var type = accessor.type;
  2182. switch (type) {
  2183. case "VEC2": return 2;
  2184. case "VEC3": return 3;
  2185. case "VEC4": return 4;
  2186. case "MAT2": return 4;
  2187. case "MAT3": return 9;
  2188. case "MAT4": return 16;
  2189. default: return 1;
  2190. }
  2191. };
  2192. /**
  2193. * Returns the texture filter mode giving a mode value
  2194. * @param mode: the filter mode value
  2195. */
  2196. GLTFUtils.GetTextureFilterMode = function (mode) {
  2197. switch (mode) {
  2198. case GLTF1.ETextureFilterType.LINEAR:
  2199. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2200. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2201. case GLTF1.ETextureFilterType.NEAREST:
  2202. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2203. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2204. }
  2205. };
  2206. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2207. var byteOffset = bufferView.byteOffset + byteOffset;
  2208. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2209. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2210. throw new Error("Buffer access is out of range");
  2211. }
  2212. var buffer = loadedBufferView.buffer;
  2213. byteOffset += loadedBufferView.byteOffset;
  2214. switch (componentType) {
  2215. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2216. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2217. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2218. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2219. default: return new Float32Array(buffer, byteOffset, byteLength);
  2220. }
  2221. };
  2222. /**
  2223. * Returns a buffer from its accessor
  2224. * @param gltfRuntime: the GLTF runtime
  2225. * @param accessor: the GLTF accessor
  2226. */
  2227. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2228. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2229. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2230. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2231. };
  2232. /**
  2233. * Decodes a buffer view into a string
  2234. * @param view: the buffer view
  2235. */
  2236. GLTFUtils.DecodeBufferToText = function (view) {
  2237. var result = "";
  2238. var length = view.byteLength;
  2239. for (var i = 0; i < length; ++i) {
  2240. result += String.fromCharCode(view[i]);
  2241. }
  2242. return result;
  2243. };
  2244. /**
  2245. * Returns the default material of gltf. Related to
  2246. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2247. * @param scene: the Babylon.js scene
  2248. */
  2249. GLTFUtils.GetDefaultMaterial = function (scene) {
  2250. if (!GLTFUtils._DefaultMaterial) {
  2251. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2252. "precision highp float;",
  2253. "",
  2254. "uniform mat4 worldView;",
  2255. "uniform mat4 projection;",
  2256. "",
  2257. "attribute vec3 position;",
  2258. "",
  2259. "void main(void)",
  2260. "{",
  2261. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2262. "}"
  2263. ].join("\n");
  2264. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2265. "precision highp float;",
  2266. "",
  2267. "uniform vec4 u_emission;",
  2268. "",
  2269. "void main(void)",
  2270. "{",
  2271. " gl_FragColor = u_emission;",
  2272. "}"
  2273. ].join("\n");
  2274. var shaderPath = {
  2275. vertex: "GLTFDefaultMaterial",
  2276. fragment: "GLTFDefaultMaterial"
  2277. };
  2278. var options = {
  2279. attributes: ["position"],
  2280. uniforms: ["worldView", "projection", "u_emission"],
  2281. samplers: new Array(),
  2282. needAlphaBlending: false
  2283. };
  2284. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2285. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2286. }
  2287. return GLTFUtils._DefaultMaterial;
  2288. };
  2289. // The GLTF default material
  2290. GLTFUtils._DefaultMaterial = null;
  2291. return GLTFUtils;
  2292. }());
  2293. GLTF1.GLTFUtils = GLTFUtils;
  2294. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2295. })(BABYLON || (BABYLON = {}));
  2296. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2297. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2298. var BABYLON;
  2299. (function (BABYLON) {
  2300. var GLTF1;
  2301. (function (GLTF1) {
  2302. var GLTFLoaderExtension = /** @class */ (function () {
  2303. function GLTFLoaderExtension(name) {
  2304. this._name = name;
  2305. }
  2306. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2307. get: function () {
  2308. return this._name;
  2309. },
  2310. enumerable: true,
  2311. configurable: true
  2312. });
  2313. /**
  2314. * Defines an override for loading the runtime
  2315. * Return true to stop further extensions from loading the runtime
  2316. */
  2317. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2318. return false;
  2319. };
  2320. /**
  2321. * Defines an onverride for creating gltf runtime
  2322. * Return true to stop further extensions from creating the runtime
  2323. */
  2324. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2325. return false;
  2326. };
  2327. /**
  2328. * Defines an override for loading buffers
  2329. * Return true to stop further extensions from loading this buffer
  2330. */
  2331. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2332. return false;
  2333. };
  2334. /**
  2335. * Defines an override for loading texture buffers
  2336. * Return true to stop further extensions from loading this texture data
  2337. */
  2338. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2339. return false;
  2340. };
  2341. /**
  2342. * Defines an override for creating textures
  2343. * Return true to stop further extensions from loading this texture
  2344. */
  2345. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2346. return false;
  2347. };
  2348. /**
  2349. * Defines an override for loading shader strings
  2350. * Return true to stop further extensions from loading this shader data
  2351. */
  2352. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2353. return false;
  2354. };
  2355. /**
  2356. * Defines an override for loading materials
  2357. * Return true to stop further extensions from loading this material
  2358. */
  2359. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2360. return false;
  2361. };
  2362. // ---------
  2363. // Utilities
  2364. // ---------
  2365. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2366. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2367. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2368. }, function () {
  2369. setTimeout(function () {
  2370. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2371. });
  2372. });
  2373. };
  2374. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2375. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2376. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2377. }, function () {
  2378. setTimeout(function () {
  2379. onSuccess();
  2380. });
  2381. });
  2382. };
  2383. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2384. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2385. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2386. }, function () {
  2387. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2388. });
  2389. };
  2390. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2391. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  2392. };
  2393. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2394. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2395. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2396. }, function () {
  2397. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2398. });
  2399. };
  2400. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2401. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2402. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2403. }, function () {
  2404. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2405. });
  2406. };
  2407. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2408. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2409. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2410. }, function () {
  2411. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2412. });
  2413. };
  2414. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2415. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2416. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2417. }, function () {
  2418. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2419. });
  2420. };
  2421. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2422. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2423. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2424. if (func(loaderExtension)) {
  2425. return;
  2426. }
  2427. }
  2428. defaultFunc();
  2429. };
  2430. return GLTFLoaderExtension;
  2431. }());
  2432. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2433. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2434. })(BABYLON || (BABYLON = {}));
  2435. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2436. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2437. var __extends = (this && this.__extends) || (function () {
  2438. var extendStatics = Object.setPrototypeOf ||
  2439. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2440. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2441. return function (d, b) {
  2442. extendStatics(d, b);
  2443. function __() { this.constructor = d; }
  2444. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2445. };
  2446. })();
  2447. var BABYLON;
  2448. (function (BABYLON) {
  2449. var GLTF1;
  2450. (function (GLTF1) {
  2451. var BinaryExtensionBufferName = "binary_glTF";
  2452. ;
  2453. ;
  2454. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2455. __extends(GLTFBinaryExtension, _super);
  2456. function GLTFBinaryExtension() {
  2457. return _super.call(this, "KHR_binary_glTF") || this;
  2458. }
  2459. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2460. var extensionsUsed = data.json.extensionsUsed;
  2461. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2462. return false;
  2463. }
  2464. this._bin = data.bin;
  2465. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2466. return true;
  2467. };
  2468. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2469. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2470. return false;
  2471. }
  2472. if (id !== BinaryExtensionBufferName) {
  2473. return false;
  2474. }
  2475. onSuccess(this._bin);
  2476. return true;
  2477. };
  2478. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2479. var texture = gltfRuntime.textures[id];
  2480. var source = gltfRuntime.images[texture.source];
  2481. if (!source.extensions || !(this.name in source.extensions)) {
  2482. return false;
  2483. }
  2484. var sourceExt = source.extensions[this.name];
  2485. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2486. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2487. onSuccess(buffer);
  2488. return true;
  2489. };
  2490. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2491. var shader = gltfRuntime.shaders[id];
  2492. if (!shader.extensions || !(this.name in shader.extensions)) {
  2493. return false;
  2494. }
  2495. var binaryExtensionShader = shader.extensions[this.name];
  2496. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2497. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2498. setTimeout(function () {
  2499. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2500. onSuccess(shaderString);
  2501. });
  2502. return true;
  2503. };
  2504. return GLTFBinaryExtension;
  2505. }(GLTF1.GLTFLoaderExtension));
  2506. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2507. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2508. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2509. })(BABYLON || (BABYLON = {}));
  2510. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2511. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2512. var __extends = (this && this.__extends) || (function () {
  2513. var extendStatics = Object.setPrototypeOf ||
  2514. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2515. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2516. return function (d, b) {
  2517. extendStatics(d, b);
  2518. function __() { this.constructor = d; }
  2519. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2520. };
  2521. })();
  2522. var BABYLON;
  2523. (function (BABYLON) {
  2524. var GLTF1;
  2525. (function (GLTF1) {
  2526. ;
  2527. ;
  2528. ;
  2529. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2530. __extends(GLTFMaterialsCommonExtension, _super);
  2531. function GLTFMaterialsCommonExtension() {
  2532. return _super.call(this, "KHR_materials_common") || this;
  2533. }
  2534. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2535. if (!gltfRuntime.extensions)
  2536. return false;
  2537. var extension = gltfRuntime.extensions[this.name];
  2538. if (!extension)
  2539. return false;
  2540. // Create lights
  2541. var lights = extension.lights;
  2542. if (lights) {
  2543. for (var thing in lights) {
  2544. var light = lights[thing];
  2545. switch (light.type) {
  2546. case "ambient":
  2547. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2548. var ambient = light.ambient;
  2549. if (ambient) {
  2550. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2551. }
  2552. break;
  2553. case "point":
  2554. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2555. var point = light.point;
  2556. if (point) {
  2557. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2558. }
  2559. break;
  2560. case "directional":
  2561. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2562. var directional = light.directional;
  2563. if (directional) {
  2564. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2565. }
  2566. break;
  2567. case "spot":
  2568. var spot = light.spot;
  2569. if (spot) {
  2570. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2571. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2572. }
  2573. break;
  2574. default:
  2575. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2576. break;
  2577. }
  2578. }
  2579. }
  2580. return false;
  2581. };
  2582. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2583. var material = gltfRuntime.materials[id];
  2584. if (!material || !material.extensions)
  2585. return false;
  2586. var extension = material.extensions[this.name];
  2587. if (!extension)
  2588. return false;
  2589. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2590. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2591. if (extension.technique === "CONSTANT") {
  2592. standardMaterial.disableLighting = true;
  2593. }
  2594. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2595. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2596. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2597. // Ambient
  2598. if (typeof extension.values.ambient === "string") {
  2599. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2600. }
  2601. else {
  2602. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2603. }
  2604. // Diffuse
  2605. if (typeof extension.values.diffuse === "string") {
  2606. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2607. }
  2608. else {
  2609. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2610. }
  2611. // Emission
  2612. if (typeof extension.values.emission === "string") {
  2613. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2614. }
  2615. else {
  2616. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2617. }
  2618. // Specular
  2619. if (typeof extension.values.specular === "string") {
  2620. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2621. }
  2622. else {
  2623. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2624. }
  2625. return true;
  2626. };
  2627. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2628. // Create buffer from texture url
  2629. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2630. // Create texture from buffer
  2631. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2632. }, onError);
  2633. };
  2634. return GLTFMaterialsCommonExtension;
  2635. }(GLTF1.GLTFLoaderExtension));
  2636. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2637. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2638. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2639. })(BABYLON || (BABYLON = {}));
  2640. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  2641. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2642. var BABYLON;
  2643. (function (BABYLON) {
  2644. var GLTF2;
  2645. (function (GLTF2) {
  2646. var ArrayItem = /** @class */ (function () {
  2647. function ArrayItem() {
  2648. }
  2649. ArrayItem.Assign = function (values) {
  2650. if (values) {
  2651. for (var index = 0; index < values.length; index++) {
  2652. values[index]._index = index;
  2653. }
  2654. }
  2655. };
  2656. return ArrayItem;
  2657. }());
  2658. GLTF2.ArrayItem = ArrayItem;
  2659. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2660. })(BABYLON || (BABYLON = {}));
  2661. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  2662. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2663. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  2664. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  2665. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2666. var BABYLON;
  2667. (function (BABYLON) {
  2668. var GLTF2;
  2669. (function (GLTF2) {
  2670. var GLTFLoader = /** @class */ (function () {
  2671. function GLTFLoader() {
  2672. this._completePromises = new Array();
  2673. this._disposed = false;
  2674. this._state = null;
  2675. this._extensions = {};
  2676. this._defaultSampler = {};
  2677. this._defaultBabylonMaterials = {};
  2678. this._requests = new Array();
  2679. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  2680. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  2681. this.compileMaterials = false;
  2682. this.useClipPlane = false;
  2683. this.compileShadowGenerators = false;
  2684. this.onDisposeObservable = new BABYLON.Observable();
  2685. this.onMeshLoadedObservable = new BABYLON.Observable();
  2686. this.onTextureLoadedObservable = new BABYLON.Observable();
  2687. this.onMaterialLoadedObservable = new BABYLON.Observable();
  2688. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  2689. this.onExtensionLoadedObservable = new BABYLON.Observable();
  2690. this.onCompleteObservable = new BABYLON.Observable();
  2691. }
  2692. GLTFLoader._Register = function (name, factory) {
  2693. if (GLTFLoader._Factories[name]) {
  2694. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  2695. return;
  2696. }
  2697. GLTFLoader._Factories[name] = factory;
  2698. // Keep the order of registration so that extensions registered first are called first.
  2699. GLTFLoader._Names.push(name);
  2700. };
  2701. Object.defineProperty(GLTFLoader.prototype, "state", {
  2702. get: function () {
  2703. return this._state;
  2704. },
  2705. enumerable: true,
  2706. configurable: true
  2707. });
  2708. GLTFLoader.prototype.dispose = function () {
  2709. if (this._disposed) {
  2710. return;
  2711. }
  2712. this._disposed = true;
  2713. this.onDisposeObservable.notifyObservers(this);
  2714. this.onDisposeObservable.clear();
  2715. this._clear();
  2716. };
  2717. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  2718. var _this = this;
  2719. return Promise.resolve().then(function () {
  2720. var nodes = null;
  2721. if (meshesNames) {
  2722. var nodeMap_1 = {};
  2723. if (_this._gltf.nodes) {
  2724. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  2725. var node = _a[_i];
  2726. if (node.name) {
  2727. nodeMap_1[node.name] = node;
  2728. }
  2729. }
  2730. }
  2731. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  2732. nodes = names.map(function (name) {
  2733. var node = nodeMap_1[name];
  2734. if (!node) {
  2735. throw new Error("Failed to find node '" + name + "'");
  2736. }
  2737. return node;
  2738. });
  2739. }
  2740. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  2741. return {
  2742. meshes: _this._getMeshes(),
  2743. particleSystems: [],
  2744. skeletons: _this._getSkeletons(),
  2745. };
  2746. });
  2747. });
  2748. };
  2749. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  2750. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  2751. };
  2752. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  2753. var _this = this;
  2754. return Promise.resolve().then(function () {
  2755. _this._loadExtensions();
  2756. _this._babylonScene = scene;
  2757. _this._rootUrl = rootUrl;
  2758. _this._progressCallback = onProgress;
  2759. _this._state = BABYLON.GLTFLoaderState.Loading;
  2760. _this._loadData(data);
  2761. _this._checkExtensions();
  2762. var promises = new Array();
  2763. if (nodes) {
  2764. promises.push(_this._loadNodesAsync(nodes));
  2765. }
  2766. else {
  2767. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  2768. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  2769. }
  2770. if (_this.compileMaterials) {
  2771. promises.push(_this._compileMaterialsAsync());
  2772. }
  2773. if (_this.compileShadowGenerators) {
  2774. promises.push(_this._compileShadowGeneratorsAsync());
  2775. }
  2776. var resultPromise = Promise.all(promises).then(function () {
  2777. _this._state = BABYLON.GLTFLoaderState.Ready;
  2778. _this._startAnimations();
  2779. });
  2780. resultPromise.then(function () {
  2781. _this._rootBabylonMesh.setEnabled(true);
  2782. BABYLON.Tools.SetImmediate(function () {
  2783. if (!_this._disposed) {
  2784. Promise.all(_this._completePromises).then(function () {
  2785. _this._state = BABYLON.GLTFLoaderState.Complete;
  2786. _this.onCompleteObservable.notifyObservers(_this);
  2787. _this.onCompleteObservable.clear();
  2788. _this._clear();
  2789. }).catch(function (error) {
  2790. BABYLON.Tools.Error("glTF Loader: " + error.message);
  2791. _this._clear();
  2792. });
  2793. }
  2794. });
  2795. });
  2796. return resultPromise;
  2797. }).catch(function (error) {
  2798. BABYLON.Tools.Error("glTF Loader: " + error.message);
  2799. _this._clear();
  2800. throw error;
  2801. });
  2802. };
  2803. GLTFLoader.prototype._loadExtensions = function () {
  2804. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  2805. var name_1 = _a[_i];
  2806. var extension = GLTFLoader._Factories[name_1](this);
  2807. this._extensions[name_1] = extension;
  2808. this.onExtensionLoadedObservable.notifyObservers(extension);
  2809. }
  2810. this.onExtensionLoadedObservable.clear();
  2811. };
  2812. GLTFLoader.prototype._loadData = function (data) {
  2813. this._gltf = data.json;
  2814. this._setupData();
  2815. if (data.bin) {
  2816. var buffers = this._gltf.buffers;
  2817. if (buffers && buffers[0] && !buffers[0].uri) {
  2818. var binaryBuffer = buffers[0];
  2819. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  2820. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  2821. }
  2822. binaryBuffer._data = Promise.resolve(data.bin);
  2823. }
  2824. else {
  2825. BABYLON.Tools.Warn("Unexpected BIN chunk");
  2826. }
  2827. }
  2828. };
  2829. GLTFLoader.prototype._setupData = function () {
  2830. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  2831. GLTF2.ArrayItem.Assign(this._gltf.animations);
  2832. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  2833. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  2834. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  2835. GLTF2.ArrayItem.Assign(this._gltf.images);
  2836. GLTF2.ArrayItem.Assign(this._gltf.materials);
  2837. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  2838. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  2839. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  2840. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  2841. GLTF2.ArrayItem.Assign(this._gltf.skins);
  2842. GLTF2.ArrayItem.Assign(this._gltf.textures);
  2843. if (this._gltf.nodes) {
  2844. var nodeParents = {};
  2845. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  2846. var node = _a[_i];
  2847. if (node.children) {
  2848. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  2849. var index = _c[_b];
  2850. nodeParents[index] = node._index;
  2851. }
  2852. }
  2853. }
  2854. var rootNode = this._createRootNode();
  2855. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  2856. var node = _e[_d];
  2857. var parentIndex = nodeParents[node._index];
  2858. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  2859. }
  2860. }
  2861. };
  2862. GLTFLoader.prototype._checkExtensions = function () {
  2863. if (this._gltf.extensionsRequired) {
  2864. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  2865. var name_2 = _a[_i];
  2866. var extension = this._extensions[name_2];
  2867. if (!extension || !extension.enabled) {
  2868. throw new Error("Require extension " + name_2 + " is not available");
  2869. }
  2870. }
  2871. }
  2872. };
  2873. GLTFLoader.prototype._createRootNode = function () {
  2874. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  2875. this._rootBabylonMesh.setEnabled(false);
  2876. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  2877. switch (this.coordinateSystemMode) {
  2878. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  2879. if (!this._babylonScene.useRightHandedSystem) {
  2880. rootNode.rotation = [0, 1, 0, 0];
  2881. rootNode.scale = [1, 1, -1];
  2882. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  2883. }
  2884. break;
  2885. }
  2886. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  2887. this._babylonScene.useRightHandedSystem = true;
  2888. break;
  2889. }
  2890. default: {
  2891. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  2892. }
  2893. }
  2894. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  2895. return rootNode;
  2896. };
  2897. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  2898. var promises = new Array();
  2899. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  2900. var node = nodes_1[_i];
  2901. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  2902. }
  2903. promises.push(this._loadAnimationsAsync());
  2904. return Promise.all(promises).then(function () { });
  2905. };
  2906. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  2907. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  2908. if (promise) {
  2909. return promise;
  2910. }
  2911. var promises = new Array();
  2912. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  2913. var index = _a[_i];
  2914. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  2915. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  2916. }
  2917. promises.push(this._loadAnimationsAsync());
  2918. return Promise.all(promises).then(function () { });
  2919. };
  2920. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  2921. if (node._primitiveBabylonMeshes) {
  2922. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  2923. var babylonMesh = _a[_i];
  2924. callback(babylonMesh);
  2925. }
  2926. }
  2927. else {
  2928. callback(node._babylonMesh);
  2929. }
  2930. };
  2931. GLTFLoader.prototype._getMeshes = function () {
  2932. var meshes = new Array();
  2933. // Root mesh is always first.
  2934. meshes.push(this._rootBabylonMesh);
  2935. var nodes = this._gltf.nodes;
  2936. if (nodes) {
  2937. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  2938. var node = nodes_2[_i];
  2939. if (node._babylonMesh) {
  2940. meshes.push(node._babylonMesh);
  2941. }
  2942. if (node._primitiveBabylonMeshes) {
  2943. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  2944. var babylonMesh = _b[_a];
  2945. meshes.push(babylonMesh);
  2946. }
  2947. }
  2948. }
  2949. }
  2950. return meshes;
  2951. };
  2952. GLTFLoader.prototype._getSkeletons = function () {
  2953. var skeletons = new Array();
  2954. var skins = this._gltf.skins;
  2955. if (skins) {
  2956. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  2957. var skin = skins_1[_i];
  2958. if (skin._babylonSkeleton) {
  2959. skeletons.push(skin._babylonSkeleton);
  2960. }
  2961. }
  2962. }
  2963. return skeletons;
  2964. };
  2965. GLTFLoader.prototype._startAnimations = function () {
  2966. var animations = this._gltf.animations;
  2967. if (!animations) {
  2968. return;
  2969. }
  2970. switch (this.animationStartMode) {
  2971. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  2972. // do nothing
  2973. break;
  2974. }
  2975. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  2976. var animation = animations[0];
  2977. animation._babylonAnimationGroup.start(true);
  2978. break;
  2979. }
  2980. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  2981. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  2982. var animation = animations_1[_i];
  2983. animation._babylonAnimationGroup.start(true);
  2984. }
  2985. break;
  2986. }
  2987. default: {
  2988. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  2989. return;
  2990. }
  2991. }
  2992. };
  2993. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  2994. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  2995. if (promise) {
  2996. return promise;
  2997. }
  2998. if (node._babylonMesh) {
  2999. throw new Error(context + ": Invalid recursive node hierarchy");
  3000. }
  3001. var promises = new Array();
  3002. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  3003. node._babylonMesh = babylonMesh;
  3004. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  3005. node._babylonAnimationTargets.push(babylonMesh);
  3006. GLTFLoader._LoadTransform(node, babylonMesh);
  3007. if (node.mesh != undefined) {
  3008. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  3009. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  3010. }
  3011. if (node.children) {
  3012. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  3013. var index = _a[_i];
  3014. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  3015. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  3016. }
  3017. }
  3018. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  3019. return Promise.all(promises).then(function () { });
  3020. };
  3021. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  3022. // TODO: instancing
  3023. var _this = this;
  3024. var promises = new Array();
  3025. var primitives = mesh.primitives;
  3026. if (!primitives || primitives.length === 0) {
  3027. throw new Error(context + ": Primitives are missing");
  3028. }
  3029. GLTF2.ArrayItem.Assign(primitives);
  3030. if (primitives.length === 1) {
  3031. var primitive = primitives[0];
  3032. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  3033. }
  3034. else {
  3035. node._primitiveBabylonMeshes = [];
  3036. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  3037. var primitive = primitives_1[_i];
  3038. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  3039. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  3040. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  3041. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  3042. }
  3043. }
  3044. if (node.skin != undefined) {
  3045. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  3046. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  3047. }
  3048. return Promise.all(promises).then(function () {
  3049. _this._forEachPrimitive(node, function (babylonMesh) {
  3050. babylonMesh._refreshBoundingInfo(true);
  3051. });
  3052. });
  3053. };
  3054. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  3055. var _this = this;
  3056. var promises = new Array();
  3057. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  3058. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  3059. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  3060. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  3061. }));
  3062. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  3063. if (primitive.material == undefined) {
  3064. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  3065. }
  3066. else {
  3067. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  3068. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  3069. babylonMesh.material = babylonMaterial;
  3070. }));
  3071. }
  3072. return Promise.all(promises).then(function () { });
  3073. };
  3074. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  3075. var _this = this;
  3076. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  3077. if (promise) {
  3078. return promise;
  3079. }
  3080. var attributes = primitive.attributes;
  3081. if (!attributes) {
  3082. throw new Error(context + ": Attributes are missing");
  3083. }
  3084. var promises = new Array();
  3085. var babylonVertexData = new BABYLON.VertexData();
  3086. if (primitive.indices == undefined) {
  3087. var positionAccessorIndex = attributes["POSITION"];
  3088. if (positionAccessorIndex != undefined) {
  3089. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  3090. babylonVertexData.indices = new Uint32Array(accessor.count);
  3091. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  3092. babylonVertexData.indices[i] = i;
  3093. }
  3094. }
  3095. }
  3096. else {
  3097. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  3098. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  3099. babylonVertexData.indices = data;
  3100. }));
  3101. }
  3102. var loadAttribute = function (attribute, kind) {
  3103. if (attributes[attribute] == undefined) {
  3104. return;
  3105. }
  3106. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3107. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3108. babylonMesh._delayInfo.push(kind);
  3109. }
  3110. if (attribute === "COLOR_0") {
  3111. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  3112. babylonMesh.hasVertexAlpha = true;
  3113. }
  3114. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3115. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3116. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  3117. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  3118. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  3119. }
  3120. babylonVertexData.set(attributeData, kind);
  3121. }));
  3122. };
  3123. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  3124. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  3125. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  3126. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  3127. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  3128. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  3129. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  3130. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  3131. return Promise.all(promises).then(function () {
  3132. return babylonVertexData;
  3133. });
  3134. };
  3135. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  3136. if (!primitive.targets) {
  3137. return;
  3138. }
  3139. if (node._numMorphTargets == undefined) {
  3140. node._numMorphTargets = primitive.targets.length;
  3141. }
  3142. else if (primitive.targets.length !== node._numMorphTargets) {
  3143. throw new Error(context + ": Primitives do not have the same number of targets");
  3144. }
  3145. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  3146. for (var index = 0; index < primitive.targets.length; index++) {
  3147. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  3148. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  3149. // TODO: tell the target whether it has positions, normals, tangents
  3150. }
  3151. };
  3152. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  3153. if (!primitive.targets) {
  3154. return Promise.resolve();
  3155. }
  3156. var promises = new Array();
  3157. var morphTargetManager = babylonMesh.morphTargetManager;
  3158. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  3159. var babylonMorphTarget = morphTargetManager.getTarget(index);
  3160. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  3161. }
  3162. return Promise.all(promises).then(function () { });
  3163. };
  3164. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  3165. var _this = this;
  3166. var promises = new Array();
  3167. var loadAttribute = function (attribute, setData) {
  3168. if (attributes[attribute] == undefined) {
  3169. return;
  3170. }
  3171. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3172. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3173. setData(data);
  3174. }));
  3175. };
  3176. loadAttribute("POSITION", function (data) {
  3177. if (babylonVertexData.positions) {
  3178. for (var i = 0; i < data.length; i++) {
  3179. data[i] += babylonVertexData.positions[i];
  3180. }
  3181. babylonMorphTarget.setPositions(data);
  3182. }
  3183. });
  3184. loadAttribute("NORMAL", function (data) {
  3185. if (babylonVertexData.normals) {
  3186. for (var i = 0; i < data.length; i++) {
  3187. data[i] += babylonVertexData.normals[i];
  3188. }
  3189. babylonMorphTarget.setNormals(data);
  3190. }
  3191. });
  3192. loadAttribute("TANGENT", function (data) {
  3193. if (babylonVertexData.tangents) {
  3194. // Tangent data for morph targets is stored as xyz delta.
  3195. // The vertexData.tangent is stored as xyzw.
  3196. // So we need to skip every fourth vertexData.tangent.
  3197. for (var i = 0, j = 0; i < data.length; i++) {
  3198. data[i] += babylonVertexData.tangents[j++];
  3199. if ((i + 1) % 3 == 0) {
  3200. j++;
  3201. }
  3202. }
  3203. babylonMorphTarget.setTangents(data);
  3204. }
  3205. });
  3206. return Promise.all(promises).then(function () { });
  3207. };
  3208. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  3209. if (accessor.componentType == 5126 /* FLOAT */) {
  3210. return data;
  3211. }
  3212. var factor = 1;
  3213. if (accessor.normalized) {
  3214. switch (accessor.componentType) {
  3215. case 5121 /* UNSIGNED_BYTE */: {
  3216. factor = 1 / 255;
  3217. break;
  3218. }
  3219. case 5123 /* UNSIGNED_SHORT */: {
  3220. factor = 1 / 65535;
  3221. break;
  3222. }
  3223. default: {
  3224. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  3225. }
  3226. }
  3227. }
  3228. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  3229. for (var i = 0; i < result.length; i++) {
  3230. result[i] = data[i] * factor;
  3231. }
  3232. return result;
  3233. };
  3234. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  3235. var result = new Float32Array(data.length / 3 * 4);
  3236. var offset = 0;
  3237. for (var i = 0; i < result.length; i++) {
  3238. if ((i + 1) % 4 === 0) {
  3239. result[i] = 1;
  3240. }
  3241. else {
  3242. result[i] = data[offset++];
  3243. }
  3244. }
  3245. return result;
  3246. };
  3247. GLTFLoader._LoadTransform = function (node, babylonNode) {
  3248. var position = BABYLON.Vector3.Zero();
  3249. var rotation = BABYLON.Quaternion.Identity();
  3250. var scaling = BABYLON.Vector3.One();
  3251. if (node.matrix) {
  3252. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  3253. matrix.decompose(scaling, rotation, position);
  3254. }
  3255. else {
  3256. if (node.translation)
  3257. position = BABYLON.Vector3.FromArray(node.translation);
  3258. if (node.rotation)
  3259. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  3260. if (node.scale)
  3261. scaling = BABYLON.Vector3.FromArray(node.scale);
  3262. }
  3263. babylonNode.position = position;
  3264. babylonNode.rotationQuaternion = rotation;
  3265. babylonNode.scaling = scaling;
  3266. };
  3267. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  3268. var _this = this;
  3269. var assignSkeleton = function () {
  3270. _this._forEachPrimitive(node, function (babylonMesh) {
  3271. babylonMesh.skeleton = skin._babylonSkeleton;
  3272. });
  3273. node._babylonMesh.parent = _this._rootBabylonMesh;
  3274. node._babylonMesh.position = BABYLON.Vector3.Zero();
  3275. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  3276. node._babylonMesh.scaling = BABYLON.Vector3.One();
  3277. };
  3278. if (skin._loaded) {
  3279. return skin._loaded.then(function () {
  3280. assignSkeleton();
  3281. });
  3282. }
  3283. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  3284. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  3285. var skeletonId = "skeleton" + skin._index;
  3286. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  3287. skin._babylonSkeleton = babylonSkeleton;
  3288. _this._loadBones(context, skin, inverseBindMatricesData);
  3289. assignSkeleton();
  3290. }));
  3291. };
  3292. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  3293. if (skin.inverseBindMatrices == undefined) {
  3294. return Promise.resolve(null);
  3295. }
  3296. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  3297. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3298. return data;
  3299. });
  3300. };
  3301. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  3302. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  3303. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  3304. node._babylonAnimationTargets.push(babylonBone);
  3305. return babylonBone;
  3306. };
  3307. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  3308. var babylonBones = {};
  3309. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  3310. var index = _a[_i];
  3311. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  3312. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  3313. }
  3314. };
  3315. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  3316. var babylonBone = babylonBones[node._index];
  3317. if (babylonBone) {
  3318. return babylonBone;
  3319. }
  3320. var boneIndex = skin.joints.indexOf(node._index);
  3321. var baseMatrix = BABYLON.Matrix.Identity();
  3322. if (inverseBindMatricesData && boneIndex !== -1) {
  3323. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  3324. baseMatrix.invertToRef(baseMatrix);
  3325. }
  3326. var babylonParentBone = null;
  3327. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  3328. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  3329. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  3330. }
  3331. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  3332. babylonBones[node._index] = babylonBone;
  3333. return babylonBone;
  3334. };
  3335. GLTFLoader.prototype._getNodeMatrix = function (node) {
  3336. return node.matrix ?
  3337. BABYLON.Matrix.FromArray(node.matrix) :
  3338. 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());
  3339. };
  3340. GLTFLoader.prototype._loadAnimationsAsync = function () {
  3341. var animations = this._gltf.animations;
  3342. if (!animations) {
  3343. return Promise.resolve();
  3344. }
  3345. var promises = new Array();
  3346. for (var index = 0; index < animations.length; index++) {
  3347. var animation = animations[index];
  3348. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  3349. }
  3350. return Promise.all(promises).then(function () { });
  3351. };
  3352. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  3353. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  3354. animation._babylonAnimationGroup = babylonAnimationGroup;
  3355. var promises = new Array();
  3356. GLTF2.ArrayItem.Assign(animation.channels);
  3357. GLTF2.ArrayItem.Assign(animation.samplers);
  3358. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  3359. var channel = _a[_i];
  3360. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  3361. }
  3362. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  3363. return Promise.all(promises).then(function () {
  3364. babylonAnimationGroup.normalize();
  3365. });
  3366. };
  3367. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  3368. var _this = this;
  3369. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  3370. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  3371. return Promise.resolve();
  3372. }
  3373. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  3374. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  3375. var targetPath;
  3376. var animationType;
  3377. switch (channel.target.path) {
  3378. case "translation" /* TRANSLATION */: {
  3379. targetPath = "position";
  3380. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3381. break;
  3382. }
  3383. case "rotation" /* ROTATION */: {
  3384. targetPath = "rotationQuaternion";
  3385. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  3386. break;
  3387. }
  3388. case "scale" /* SCALE */: {
  3389. targetPath = "scaling";
  3390. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3391. break;
  3392. }
  3393. case "weights" /* WEIGHTS */: {
  3394. targetPath = "influence";
  3395. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  3396. break;
  3397. }
  3398. default: {
  3399. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  3400. }
  3401. }
  3402. var outputBufferOffset = 0;
  3403. var getNextOutputValue;
  3404. switch (targetPath) {
  3405. case "position": {
  3406. getNextOutputValue = function () {
  3407. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3408. outputBufferOffset += 3;
  3409. return value;
  3410. };
  3411. break;
  3412. }
  3413. case "rotationQuaternion": {
  3414. getNextOutputValue = function () {
  3415. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  3416. outputBufferOffset += 4;
  3417. return value;
  3418. };
  3419. break;
  3420. }
  3421. case "scaling": {
  3422. getNextOutputValue = function () {
  3423. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3424. outputBufferOffset += 3;
  3425. return value;
  3426. };
  3427. break;
  3428. }
  3429. case "influence": {
  3430. getNextOutputValue = function () {
  3431. var value = new Array(targetNode._numMorphTargets);
  3432. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  3433. value[i] = data.output[outputBufferOffset++];
  3434. }
  3435. return value;
  3436. };
  3437. break;
  3438. }
  3439. }
  3440. var getNextKey;
  3441. switch (data.interpolation) {
  3442. case "STEP" /* STEP */: {
  3443. getNextKey = function (frameIndex) { return ({
  3444. frame: data.input[frameIndex],
  3445. value: getNextOutputValue(),
  3446. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  3447. }); };
  3448. break;
  3449. }
  3450. case "LINEAR" /* LINEAR */: {
  3451. getNextKey = function (frameIndex) { return ({
  3452. frame: data.input[frameIndex],
  3453. value: getNextOutputValue()
  3454. }); };
  3455. break;
  3456. }
  3457. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3458. getNextKey = function (frameIndex) { return ({
  3459. frame: data.input[frameIndex],
  3460. inTangent: getNextOutputValue(),
  3461. value: getNextOutputValue(),
  3462. outTangent: getNextOutputValue()
  3463. }); };
  3464. break;
  3465. }
  3466. }
  3467. var keys = new Array(data.input.length);
  3468. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  3469. keys[frameIndex] = getNextKey(frameIndex);
  3470. }
  3471. if (targetPath === "influence") {
  3472. var _loop_1 = function (targetIndex) {
  3473. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3474. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3475. babylonAnimation.setKeys(keys.map(function (key) { return ({
  3476. frame: key.frame,
  3477. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  3478. value: key.value[targetIndex],
  3479. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  3480. }); }));
  3481. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  3482. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  3483. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  3484. });
  3485. };
  3486. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  3487. _loop_1(targetIndex);
  3488. }
  3489. }
  3490. else {
  3491. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3492. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3493. babylonAnimation.setKeys(keys);
  3494. if (targetNode._babylonAnimationTargets) {
  3495. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  3496. var target = _a[_i];
  3497. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  3498. }
  3499. }
  3500. }
  3501. });
  3502. };
  3503. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  3504. if (sampler._data) {
  3505. return sampler._data;
  3506. }
  3507. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  3508. switch (interpolation) {
  3509. case "STEP" /* STEP */:
  3510. case "LINEAR" /* LINEAR */:
  3511. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3512. break;
  3513. }
  3514. default: {
  3515. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  3516. }
  3517. }
  3518. var inputData;
  3519. var outputData;
  3520. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  3521. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  3522. sampler._data = Promise.all([
  3523. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  3524. inputData = data;
  3525. }),
  3526. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  3527. outputData = data;
  3528. })
  3529. ]).then(function () {
  3530. return {
  3531. input: inputData,
  3532. interpolation: interpolation,
  3533. output: outputData,
  3534. };
  3535. });
  3536. return sampler._data;
  3537. };
  3538. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  3539. if (buffer._data) {
  3540. return buffer._data;
  3541. }
  3542. if (!buffer.uri) {
  3543. throw new Error(context + ": Uri is missing");
  3544. }
  3545. buffer._data = this._loadUriAsync(context, buffer.uri);
  3546. return buffer._data;
  3547. };
  3548. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  3549. if (bufferView._data) {
  3550. return bufferView._data;
  3551. }
  3552. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  3553. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  3554. try {
  3555. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  3556. }
  3557. catch (e) {
  3558. throw new Error(context + ": " + e.message);
  3559. }
  3560. });
  3561. return bufferView._data;
  3562. };
  3563. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  3564. var _this = this;
  3565. if (accessor.sparse) {
  3566. throw new Error(context + ": Sparse accessors are not currently supported");
  3567. }
  3568. if (accessor._data) {
  3569. return accessor._data;
  3570. }
  3571. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  3572. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  3573. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  3574. var byteOffset = accessor.byteOffset || 0;
  3575. var byteStride = bufferView.byteStride;
  3576. if (byteStride === 0) {
  3577. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  3578. }
  3579. try {
  3580. switch (accessor.componentType) {
  3581. case 5120 /* BYTE */: {
  3582. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3583. }
  3584. case 5121 /* UNSIGNED_BYTE */: {
  3585. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3586. }
  3587. case 5122 /* SHORT */: {
  3588. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3589. }
  3590. case 5123 /* UNSIGNED_SHORT */: {
  3591. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3592. }
  3593. case 5125 /* UNSIGNED_INT */: {
  3594. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3595. }
  3596. case 5126 /* FLOAT */: {
  3597. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3598. }
  3599. default: {
  3600. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  3601. }
  3602. }
  3603. }
  3604. catch (e) {
  3605. throw new Error(context + ": " + e.messsage);
  3606. }
  3607. });
  3608. return accessor._data;
  3609. };
  3610. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  3611. byteOffset += data.byteOffset;
  3612. var targetLength = count * numComponents;
  3613. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  3614. return new typedArray(data.buffer, byteOffset, targetLength);
  3615. }
  3616. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  3617. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  3618. var targetBuffer = new typedArray(targetLength);
  3619. var sourceIndex = 0;
  3620. var targetIndex = 0;
  3621. while (targetIndex < targetLength) {
  3622. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  3623. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  3624. targetIndex++;
  3625. }
  3626. sourceIndex += elementStride;
  3627. }
  3628. return targetBuffer;
  3629. };
  3630. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  3631. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  3632. if (!babylonMaterial) {
  3633. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  3634. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  3635. babylonMaterial.metallic = 1;
  3636. babylonMaterial.roughness = 1;
  3637. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3638. }
  3639. return babylonMaterial;
  3640. };
  3641. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  3642. var promises = new Array();
  3643. // Ensure metallic workflow
  3644. babylonMaterial.metallic = 1;
  3645. babylonMaterial.roughness = 1;
  3646. var properties = material.pbrMetallicRoughness;
  3647. if (properties) {
  3648. if (properties.baseColorFactor) {
  3649. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  3650. babylonMaterial.alpha = properties.baseColorFactor[3];
  3651. }
  3652. else {
  3653. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3654. }
  3655. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  3656. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  3657. if (properties.baseColorTexture) {
  3658. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  3659. babylonMaterial.albedoTexture = texture;
  3660. }));
  3661. }
  3662. if (properties.metallicRoughnessTexture) {
  3663. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  3664. babylonMaterial.metallicTexture = texture;
  3665. }));
  3666. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  3667. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  3668. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  3669. }
  3670. }
  3671. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  3672. return Promise.all(promises).then(function () { });
  3673. };
  3674. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  3675. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  3676. if (promise) {
  3677. return promise;
  3678. }
  3679. material._babylonData = material._babylonData || {};
  3680. var babylonData = material._babylonData[babylonDrawMode];
  3681. if (!babylonData) {
  3682. var promises = new Array();
  3683. var name_3 = material.name || "materialSG_" + material._index;
  3684. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  3685. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  3686. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  3687. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3688. babylonData = {
  3689. material: babylonMaterial,
  3690. meshes: [],
  3691. loaded: Promise.all(promises).then(function () { })
  3692. };
  3693. material._babylonData[babylonDrawMode] = babylonData;
  3694. }
  3695. babylonData.meshes.push(babylonMesh);
  3696. assign(babylonData.material);
  3697. return babylonData.loaded;
  3698. };
  3699. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  3700. var babylonMaterial = new type(name, this._babylonScene);
  3701. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  3702. babylonMaterial.fillMode = drawMode;
  3703. return babylonMaterial;
  3704. };
  3705. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  3706. var promises = new Array();
  3707. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  3708. if (material.doubleSided) {
  3709. babylonMaterial.backFaceCulling = false;
  3710. babylonMaterial.twoSidedLighting = true;
  3711. }
  3712. if (material.normalTexture) {
  3713. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  3714. babylonMaterial.bumpTexture = texture;
  3715. }));
  3716. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  3717. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  3718. if (material.normalTexture.scale != undefined) {
  3719. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  3720. }
  3721. }
  3722. if (material.occlusionTexture) {
  3723. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  3724. babylonMaterial.ambientTexture = texture;
  3725. }));
  3726. babylonMaterial.useAmbientInGrayScale = true;
  3727. if (material.occlusionTexture.strength != undefined) {
  3728. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  3729. }
  3730. }
  3731. if (material.emissiveTexture) {
  3732. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  3733. babylonMaterial.emissiveTexture = texture;
  3734. }));
  3735. }
  3736. return Promise.all(promises).then(function () { });
  3737. };
  3738. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  3739. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  3740. switch (alphaMode) {
  3741. case "OPAQUE" /* OPAQUE */: {
  3742. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  3743. break;
  3744. }
  3745. case "MASK" /* MASK */: {
  3746. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  3747. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  3748. if (babylonMaterial.alpha) {
  3749. if (babylonMaterial.alpha === 0) {
  3750. babylonMaterial.alphaCutOff = 1;
  3751. }
  3752. else {
  3753. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  3754. }
  3755. babylonMaterial.alpha = 1;
  3756. }
  3757. if (babylonMaterial.albedoTexture) {
  3758. babylonMaterial.albedoTexture.hasAlpha = true;
  3759. }
  3760. break;
  3761. }
  3762. case "BLEND" /* BLEND */: {
  3763. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  3764. if (babylonMaterial.albedoTexture) {
  3765. babylonMaterial.albedoTexture.hasAlpha = true;
  3766. babylonMaterial.useAlphaFromAlbedoTexture = true;
  3767. }
  3768. break;
  3769. }
  3770. default: {
  3771. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  3772. }
  3773. }
  3774. };
  3775. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  3776. var _this = this;
  3777. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  3778. context = "#/textures/" + textureInfo.index;
  3779. var promises = new Array();
  3780. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  3781. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  3782. var deferred = new BABYLON.Deferred();
  3783. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  3784. if (!_this._disposed) {
  3785. deferred.resolve();
  3786. }
  3787. }, function (message, exception) {
  3788. if (!_this._disposed) {
  3789. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  3790. }
  3791. });
  3792. promises.push(deferred.promise);
  3793. babylonTexture.name = texture.name || "texture" + texture._index;
  3794. babylonTexture.wrapU = samplerData.wrapU;
  3795. babylonTexture.wrapV = samplerData.wrapV;
  3796. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  3797. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  3798. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  3799. babylonTexture.updateURL(objectURL);
  3800. }));
  3801. assign(babylonTexture);
  3802. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  3803. return Promise.all(promises).then(function () { });
  3804. };
  3805. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  3806. if (!sampler._data) {
  3807. sampler._data = {
  3808. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  3809. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  3810. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  3811. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  3812. };
  3813. }
  3814. ;
  3815. return sampler._data;
  3816. };
  3817. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  3818. if (image._objectURL) {
  3819. return image._objectURL;
  3820. }
  3821. var promise;
  3822. if (image.uri) {
  3823. promise = this._loadUriAsync(context, image.uri);
  3824. }
  3825. else {
  3826. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  3827. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  3828. }
  3829. image._objectURL = promise.then(function (data) {
  3830. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  3831. });
  3832. return image._objectURL;
  3833. };
  3834. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  3835. var _this = this;
  3836. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  3837. if (promise) {
  3838. return promise;
  3839. }
  3840. if (!GLTFLoader._ValidateUri(uri)) {
  3841. throw new Error(context + ": Uri '" + uri + "' is invalid");
  3842. }
  3843. if (BABYLON.Tools.IsBase64(uri)) {
  3844. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  3845. }
  3846. return new Promise(function (resolve, reject) {
  3847. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  3848. if (!_this._disposed) {
  3849. resolve(new Uint8Array(data));
  3850. }
  3851. }, function (event) {
  3852. if (!_this._disposed) {
  3853. try {
  3854. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  3855. request._lengthComputable = event.lengthComputable;
  3856. request._loaded = event.loaded;
  3857. request._total = event.total;
  3858. _this._onProgress();
  3859. }
  3860. }
  3861. catch (e) {
  3862. reject(e);
  3863. }
  3864. }
  3865. }, _this._babylonScene.database, true, function (request, exception) {
  3866. if (!_this._disposed) {
  3867. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  3868. }
  3869. });
  3870. _this._requests.push(request);
  3871. });
  3872. };
  3873. GLTFLoader.prototype._onProgress = function () {
  3874. if (!this._progressCallback) {
  3875. return;
  3876. }
  3877. var lengthComputable = true;
  3878. var loaded = 0;
  3879. var total = 0;
  3880. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  3881. var request = _a[_i];
  3882. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  3883. return;
  3884. }
  3885. lengthComputable = lengthComputable && request._lengthComputable;
  3886. loaded += request._loaded;
  3887. total += request._total;
  3888. }
  3889. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  3890. };
  3891. GLTFLoader._GetProperty = function (context, array, index) {
  3892. if (!array || index == undefined || !array[index]) {
  3893. throw new Error(context + ": Failed to find index (" + index + ")");
  3894. }
  3895. return array[index];
  3896. };
  3897. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  3898. // Set defaults if undefined
  3899. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  3900. switch (mode) {
  3901. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  3902. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  3903. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3904. default:
  3905. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  3906. return BABYLON.Texture.WRAP_ADDRESSMODE;
  3907. }
  3908. };
  3909. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  3910. // Set defaults if undefined
  3911. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  3912. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  3913. if (magFilter === 9729 /* LINEAR */) {
  3914. switch (minFilter) {
  3915. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  3916. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  3917. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  3918. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  3919. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  3920. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  3921. default:
  3922. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  3923. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  3924. }
  3925. }
  3926. else {
  3927. if (magFilter !== 9728 /* NEAREST */) {
  3928. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  3929. }
  3930. switch (minFilter) {
  3931. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  3932. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  3933. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  3934. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  3935. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  3936. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  3937. default:
  3938. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  3939. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  3940. }
  3941. }
  3942. };
  3943. GLTFLoader._GetNumComponents = function (context, type) {
  3944. switch (type) {
  3945. case "SCALAR": return 1;
  3946. case "VEC2": return 2;
  3947. case "VEC3": return 3;
  3948. case "VEC4": return 4;
  3949. case "MAT2": return 4;
  3950. case "MAT3": return 9;
  3951. case "MAT4": return 16;
  3952. }
  3953. throw new Error(context + ": Invalid type (" + type + ")");
  3954. };
  3955. GLTFLoader._ValidateUri = function (uri) {
  3956. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  3957. };
  3958. GLTFLoader._GetDrawMode = function (context, mode) {
  3959. mode = mode || 4 /* TRIANGLES */;
  3960. switch (mode) {
  3961. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  3962. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  3963. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  3964. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  3965. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  3966. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  3967. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  3968. }
  3969. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  3970. };
  3971. GLTFLoader.prototype._compileMaterialsAsync = function () {
  3972. var promises = new Array();
  3973. if (this._gltf.materials) {
  3974. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  3975. var material = _a[_i];
  3976. if (material._babylonData) {
  3977. for (var babylonDrawMode in material._babylonData) {
  3978. var babylonData = material._babylonData[babylonDrawMode];
  3979. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  3980. var babylonMesh = _c[_b];
  3981. // Ensure nonUniformScaling is set if necessary.
  3982. babylonMesh.computeWorldMatrix(true);
  3983. var babylonMaterial = babylonData.material;
  3984. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  3985. if (this.useClipPlane) {
  3986. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  3987. }
  3988. }
  3989. }
  3990. }
  3991. }
  3992. }
  3993. return Promise.all(promises).then(function () { });
  3994. };
  3995. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  3996. var promises = new Array();
  3997. var lights = this._babylonScene.lights;
  3998. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  3999. var light = lights_1[_i];
  4000. var generator = light.getShadowGenerator();
  4001. if (generator) {
  4002. promises.push(generator.forceCompilationAsync());
  4003. }
  4004. }
  4005. return Promise.all(promises).then(function () { });
  4006. };
  4007. GLTFLoader.prototype._clear = function () {
  4008. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  4009. var request = _a[_i];
  4010. request.abort();
  4011. }
  4012. this._requests.length = 0;
  4013. if (this._gltf && this._gltf.images) {
  4014. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  4015. var image = _c[_b];
  4016. if (image._objectURL) {
  4017. image._objectURL.then(function (value) {
  4018. URL.revokeObjectURL(value);
  4019. });
  4020. image._objectURL = undefined;
  4021. }
  4022. }
  4023. }
  4024. delete this._gltf;
  4025. delete this._babylonScene;
  4026. this._completePromises.length = 0;
  4027. for (var name_4 in this._extensions) {
  4028. this._extensions[name_4].dispose();
  4029. }
  4030. this._extensions = {};
  4031. delete this._rootBabylonMesh;
  4032. delete this._progressCallback;
  4033. this.onMeshLoadedObservable.clear();
  4034. this.onTextureLoadedObservable.clear();
  4035. this.onMaterialLoadedObservable.clear();
  4036. };
  4037. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  4038. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  4039. var name_5 = _a[_i];
  4040. var extension = this._extensions[name_5];
  4041. if (extension.enabled) {
  4042. var promise = actionAsync(extension);
  4043. if (promise) {
  4044. return promise;
  4045. }
  4046. }
  4047. }
  4048. return null;
  4049. };
  4050. GLTFLoader._Names = new Array();
  4051. GLTFLoader._Factories = {};
  4052. return GLTFLoader;
  4053. }());
  4054. GLTF2.GLTFLoader = GLTFLoader;
  4055. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  4056. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4057. })(BABYLON || (BABYLON = {}));
  4058. //# sourceMappingURL=babylon.glTFLoader.js.map
  4059. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  4060. var BABYLON;
  4061. (function (BABYLON) {
  4062. var GLTF2;
  4063. (function (GLTF2) {
  4064. var GLTFLoaderExtension = /** @class */ (function () {
  4065. function GLTFLoaderExtension(loader) {
  4066. this.enabled = true;
  4067. this._loader = loader;
  4068. }
  4069. GLTFLoaderExtension.prototype.dispose = function () {
  4070. delete this._loader;
  4071. };
  4072. // #region Overridable Methods
  4073. /** Override this method to modify the default behavior for loading scenes. */
  4074. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  4075. /** Override this method to modify the default behavior for loading nodes. */
  4076. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  4077. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  4078. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  4079. /** Override this method to modify the default behavior for loading materials. */
  4080. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  4081. /** Override this method to modify the default behavior for loading uris. */
  4082. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  4083. // #endregion
  4084. /** Helper method called by a loader extension to load an glTF extension. */
  4085. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  4086. if (!property.extensions) {
  4087. return null;
  4088. }
  4089. var extensions = property.extensions;
  4090. var extension = extensions[this.name];
  4091. if (!extension) {
  4092. return null;
  4093. }
  4094. // Clear out the extension before executing the action to avoid recursing into the same property.
  4095. delete extensions[this.name];
  4096. try {
  4097. return actionAsync(context + "/extensions/" + this.name, extension);
  4098. }
  4099. finally {
  4100. // Restore the extension after executing the action.
  4101. extensions[this.name] = extension;
  4102. }
  4103. };
  4104. /** Helper method called by the loader to allow extensions to override loading scenes. */
  4105. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  4106. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  4107. };
  4108. /** Helper method called by the loader to allow extensions to override loading nodes. */
  4109. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  4110. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  4111. };
  4112. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  4113. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  4114. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  4115. };
  4116. /** Helper method called by the loader to allow extensions to override loading materials. */
  4117. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  4118. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  4119. };
  4120. /** Helper method called by the loader to allow extensions to override loading uris. */
  4121. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  4122. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  4123. };
  4124. return GLTFLoaderExtension;
  4125. }());
  4126. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  4127. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4128. })(BABYLON || (BABYLON = {}));
  4129. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  4130. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4131. var __extends = (this && this.__extends) || (function () {
  4132. var extendStatics = Object.setPrototypeOf ||
  4133. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4134. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4135. return function (d, b) {
  4136. extendStatics(d, b);
  4137. function __() { this.constructor = d; }
  4138. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4139. };
  4140. })();
  4141. var BABYLON;
  4142. (function (BABYLON) {
  4143. var GLTF2;
  4144. (function (GLTF2) {
  4145. var Extensions;
  4146. (function (Extensions) {
  4147. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  4148. var NAME = "MSFT_lod";
  4149. var MSFT_lod = /** @class */ (function (_super) {
  4150. __extends(MSFT_lod, _super);
  4151. function MSFT_lod() {
  4152. var _this = _super !== null && _super.apply(this, arguments) || this;
  4153. _this.name = NAME;
  4154. /**
  4155. * Maximum number of LODs to load, starting from the lowest LOD.
  4156. */
  4157. _this.maxLODsToLoad = Number.MAX_VALUE;
  4158. _this._loadingNodeLOD = null;
  4159. _this._loadNodeSignals = {};
  4160. _this._loadingMaterialLOD = null;
  4161. _this._loadMaterialSignals = {};
  4162. return _this;
  4163. }
  4164. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  4165. var _this = this;
  4166. return this._loadExtensionAsync(context, node, function (context, extension) {
  4167. var firstPromise;
  4168. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  4169. var _loop_1 = function (indexLOD) {
  4170. var nodeLOD = nodeLODs[indexLOD];
  4171. if (indexLOD !== 0) {
  4172. _this._loadingNodeLOD = nodeLOD;
  4173. if (!_this._loadNodeSignals[nodeLOD._index]) {
  4174. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  4175. }
  4176. }
  4177. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  4178. if (indexLOD !== 0) {
  4179. var previousNodeLOD = nodeLODs[indexLOD - 1];
  4180. if (previousNodeLOD._babylonMesh) {
  4181. previousNodeLOD._babylonMesh.dispose();
  4182. delete previousNodeLOD._babylonMesh;
  4183. }
  4184. }
  4185. if (indexLOD !== nodeLODs.length - 1) {
  4186. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  4187. if (_this._loadNodeSignals[nodeIndex]) {
  4188. _this._loadNodeSignals[nodeIndex].resolve();
  4189. delete _this._loadNodeSignals[nodeIndex];
  4190. }
  4191. }
  4192. });
  4193. if (indexLOD === 0) {
  4194. firstPromise = promise;
  4195. }
  4196. else {
  4197. _this._loader._completePromises.push(promise);
  4198. _this._loadingNodeLOD = null;
  4199. }
  4200. };
  4201. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  4202. _loop_1(indexLOD);
  4203. }
  4204. return firstPromise;
  4205. });
  4206. };
  4207. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4208. var _this = this;
  4209. // Don't load material LODs if already loading a node LOD.
  4210. if (this._loadingNodeLOD) {
  4211. return null;
  4212. }
  4213. return this._loadExtensionAsync(context, material, function (context, extension) {
  4214. var firstPromise;
  4215. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  4216. var _loop_2 = function (indexLOD) {
  4217. var materialLOD = materialLODs[indexLOD];
  4218. if (indexLOD !== 0) {
  4219. _this._loadingMaterialLOD = materialLOD;
  4220. if (!_this._loadMaterialSignals[materialLOD._index]) {
  4221. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  4222. }
  4223. }
  4224. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  4225. if (indexLOD !== 0) {
  4226. var babylonDataLOD = materialLOD._babylonData;
  4227. assign(babylonDataLOD[babylonDrawMode].material);
  4228. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  4229. if (previousBabylonDataLOD[babylonDrawMode]) {
  4230. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  4231. delete previousBabylonDataLOD[babylonDrawMode];
  4232. }
  4233. }
  4234. if (indexLOD !== materialLODs.length - 1) {
  4235. var materialIndex = materialLODs[indexLOD + 1]._index;
  4236. if (_this._loadMaterialSignals[materialIndex]) {
  4237. _this._loadMaterialSignals[materialIndex].resolve();
  4238. delete _this._loadMaterialSignals[materialIndex];
  4239. }
  4240. }
  4241. });
  4242. if (indexLOD === 0) {
  4243. firstPromise = promise;
  4244. }
  4245. else {
  4246. _this._loader._completePromises.push(promise);
  4247. _this._loadingMaterialLOD = null;
  4248. }
  4249. };
  4250. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  4251. _loop_2(indexLOD);
  4252. }
  4253. return firstPromise;
  4254. });
  4255. };
  4256. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  4257. var _this = this;
  4258. // Defer the loading of uris if loading a material or node LOD.
  4259. if (this._loadingMaterialLOD) {
  4260. var index = this._loadingMaterialLOD._index;
  4261. return this._loadMaterialSignals[index].promise.then(function () {
  4262. return _this._loader._loadUriAsync(context, uri);
  4263. });
  4264. }
  4265. else if (this._loadingNodeLOD) {
  4266. var index = this._loadingNodeLOD._index;
  4267. return this._loadNodeSignals[index].promise.then(function () {
  4268. return _this._loader._loadUriAsync(context, uri);
  4269. });
  4270. }
  4271. return null;
  4272. };
  4273. /**
  4274. * Gets an array of LOD properties from lowest to highest.
  4275. */
  4276. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  4277. if (this.maxLODsToLoad <= 0) {
  4278. throw new Error("maxLODsToLoad must be greater than zero");
  4279. }
  4280. var properties = new Array();
  4281. for (var i = ids.length - 1; i >= 0; i--) {
  4282. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  4283. if (properties.length === this.maxLODsToLoad) {
  4284. return properties;
  4285. }
  4286. }
  4287. properties.push(property);
  4288. return properties;
  4289. };
  4290. return MSFT_lod;
  4291. }(GLTF2.GLTFLoaderExtension));
  4292. Extensions.MSFT_lod = MSFT_lod;
  4293. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  4294. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4295. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4296. })(BABYLON || (BABYLON = {}));
  4297. //# sourceMappingURL=MSFT_lod.js.map
  4298. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4299. var __extends = (this && this.__extends) || (function () {
  4300. var extendStatics = Object.setPrototypeOf ||
  4301. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4302. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4303. return function (d, b) {
  4304. extendStatics(d, b);
  4305. function __() { this.constructor = d; }
  4306. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4307. };
  4308. })();
  4309. var BABYLON;
  4310. (function (BABYLON) {
  4311. var GLTF2;
  4312. (function (GLTF2) {
  4313. var Extensions;
  4314. (function (Extensions) {
  4315. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  4316. var NAME = "KHR_draco_mesh_compression";
  4317. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  4318. __extends(KHR_draco_mesh_compression, _super);
  4319. function KHR_draco_mesh_compression(loader) {
  4320. var _this = _super.call(this, loader) || this;
  4321. _this.name = NAME;
  4322. _this._dracoCompression = null;
  4323. // Disable extension if decoder is not available.
  4324. if (!BABYLON.DracoCompression.DecoderUrl) {
  4325. _this.enabled = false;
  4326. }
  4327. return _this;
  4328. }
  4329. KHR_draco_mesh_compression.prototype.dispose = function () {
  4330. if (this._dracoCompression) {
  4331. this._dracoCompression.dispose();
  4332. }
  4333. _super.prototype.dispose.call(this);
  4334. };
  4335. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  4336. var _this = this;
  4337. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  4338. if (primitive.mode != undefined) {
  4339. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  4340. primitive.mode !== 4 /* TRIANGLES */) {
  4341. throw new Error(context + ": Unsupported mode " + primitive.mode);
  4342. }
  4343. // TODO: handle triangle strips
  4344. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  4345. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  4346. }
  4347. }
  4348. var attributes = {};
  4349. var loadAttribute = function (name, kind) {
  4350. var uniqueId = extension.attributes[name];
  4351. if (uniqueId == undefined) {
  4352. return;
  4353. }
  4354. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  4355. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  4356. babylonMesh._delayInfo.push(kind);
  4357. }
  4358. attributes[kind] = uniqueId;
  4359. };
  4360. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  4361. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  4362. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  4363. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  4364. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  4365. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  4366. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  4367. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  4368. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  4369. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  4370. try {
  4371. if (!_this._dracoCompression) {
  4372. _this._dracoCompression = new BABYLON.DracoCompression();
  4373. }
  4374. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  4375. }
  4376. catch (e) {
  4377. throw new Error(context + ": " + e.message);
  4378. }
  4379. });
  4380. });
  4381. };
  4382. return KHR_draco_mesh_compression;
  4383. }(GLTF2.GLTFLoaderExtension));
  4384. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  4385. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  4386. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4387. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4388. })(BABYLON || (BABYLON = {}));
  4389. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  4390. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4391. var __extends = (this && this.__extends) || (function () {
  4392. var extendStatics = Object.setPrototypeOf ||
  4393. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4394. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4395. return function (d, b) {
  4396. extendStatics(d, b);
  4397. function __() { this.constructor = d; }
  4398. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4399. };
  4400. })();
  4401. var BABYLON;
  4402. (function (BABYLON) {
  4403. var GLTF2;
  4404. (function (GLTF2) {
  4405. var Extensions;
  4406. (function (Extensions) {
  4407. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  4408. var NAME = "KHR_materials_pbrSpecularGlossiness";
  4409. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  4410. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  4411. function KHR_materials_pbrSpecularGlossiness() {
  4412. var _this = _super !== null && _super.apply(this, arguments) || this;
  4413. _this.name = NAME;
  4414. return _this;
  4415. }
  4416. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4417. var _this = this;
  4418. return this._loadExtensionAsync(context, material, function (context, extension) {
  4419. material._babylonData = material._babylonData || {};
  4420. var babylonData = material._babylonData[babylonDrawMode];
  4421. if (!babylonData) {
  4422. var promises = new Array();
  4423. var name_1 = material.name || "materialSG_" + material._index;
  4424. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  4425. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  4426. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension, babylonMaterial));
  4427. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4428. babylonData = {
  4429. material: babylonMaterial,
  4430. meshes: [],
  4431. loaded: Promise.all(promises).then(function () { })
  4432. };
  4433. material._babylonData[babylonDrawMode] = babylonData;
  4434. }
  4435. babylonData.meshes.push(babylonMesh);
  4436. assign(babylonData.material);
  4437. return babylonData.loaded;
  4438. });
  4439. };
  4440. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  4441. var promises = new Array();
  4442. if (properties.diffuseFactor) {
  4443. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  4444. babylonMaterial.alpha = properties.diffuseFactor[3];
  4445. }
  4446. else {
  4447. babylonMaterial.albedoColor = BABYLON.Color3.White();
  4448. }
  4449. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  4450. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  4451. if (properties.diffuseTexture) {
  4452. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  4453. babylonMaterial.albedoTexture = texture;
  4454. }));
  4455. }
  4456. if (properties.specularGlossinessTexture) {
  4457. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  4458. babylonMaterial.reflectivityTexture = texture;
  4459. }));
  4460. babylonMaterial.reflectivityTexture.hasAlpha = true;
  4461. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  4462. }
  4463. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  4464. return Promise.all(promises).then(function () { });
  4465. };
  4466. return KHR_materials_pbrSpecularGlossiness;
  4467. }(GLTF2.GLTFLoaderExtension));
  4468. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  4469. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  4470. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4471. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4472. })(BABYLON || (BABYLON = {}));
  4473. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  4474. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4475. var __extends = (this && this.__extends) || (function () {
  4476. var extendStatics = Object.setPrototypeOf ||
  4477. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4478. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4479. return function (d, b) {
  4480. extendStatics(d, b);
  4481. function __() { this.constructor = d; }
  4482. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4483. };
  4484. })();
  4485. var BABYLON;
  4486. (function (BABYLON) {
  4487. var GLTF2;
  4488. (function (GLTF2) {
  4489. var Extensions;
  4490. (function (Extensions) {
  4491. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  4492. var NAME = "KHR_lights";
  4493. var LightType;
  4494. (function (LightType) {
  4495. LightType["AMBIENT"] = "ambient";
  4496. LightType["DIRECTIONAL"] = "directional";
  4497. LightType["POINT"] = "point";
  4498. LightType["SPOT"] = "spot";
  4499. })(LightType || (LightType = {}));
  4500. var KHR_lights = /** @class */ (function (_super) {
  4501. __extends(KHR_lights, _super);
  4502. function KHR_lights() {
  4503. var _this = _super !== null && _super.apply(this, arguments) || this;
  4504. _this.name = NAME;
  4505. return _this;
  4506. }
  4507. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  4508. var _this = this;
  4509. return this._loadExtensionAsync(context, scene, function (context, extension) {
  4510. var promise = _this._loader._loadSceneAsync(context, scene);
  4511. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  4512. if (light.type !== LightType.AMBIENT) {
  4513. throw new Error(context + ": Only ambient lights are allowed on a scene");
  4514. }
  4515. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  4516. return promise;
  4517. });
  4518. };
  4519. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  4520. var _this = this;
  4521. return this._loadExtensionAsync(context, node, function (context, extension) {
  4522. var promise = _this._loader._loadNodeAsync(context, node);
  4523. var babylonLight;
  4524. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  4525. var name = node._babylonMesh.name;
  4526. switch (light.type) {
  4527. case LightType.AMBIENT: {
  4528. throw new Error(context + ": Ambient lights are not allowed on a node");
  4529. }
  4530. case LightType.DIRECTIONAL: {
  4531. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  4532. break;
  4533. }
  4534. case LightType.POINT: {
  4535. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  4536. break;
  4537. }
  4538. case LightType.SPOT: {
  4539. var spotLight = light;
  4540. // TODO: support inner and outer cone angles
  4541. //const innerConeAngle = spotLight.innerConeAngle || 0;
  4542. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  4543. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  4544. break;
  4545. }
  4546. default: {
  4547. throw new Error(context + ": Invalid light type (" + light.type + ")");
  4548. }
  4549. }
  4550. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  4551. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  4552. babylonLight.parent = node._babylonMesh;
  4553. return promise;
  4554. });
  4555. };
  4556. Object.defineProperty(KHR_lights.prototype, "_lights", {
  4557. get: function () {
  4558. var extensions = this._loader._gltf.extensions;
  4559. if (!extensions || !extensions[this.name]) {
  4560. throw new Error("#/extensions: '" + this.name + "' not found");
  4561. }
  4562. var extension = extensions[this.name];
  4563. return extension.lights;
  4564. },
  4565. enumerable: true,
  4566. configurable: true
  4567. });
  4568. return KHR_lights;
  4569. }(GLTF2.GLTFLoaderExtension));
  4570. Extensions.KHR_lights = KHR_lights;
  4571. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  4572. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4573. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4574. })(BABYLON || (BABYLON = {}));
  4575. //# sourceMappingURL=KHR_lights.js.map