babylon.glTFFileLoader.js 209 KB

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