babylon.glTFFileLoader.js 230 KB

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