babylonjs.loaders.js 281 KB

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