babylonjs.loaders.js 281 KB

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