babylonjs.loaders.js 257 KB

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