babylonjs.loaders.js 279 KB

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