babylon.glTFFileLoader.js 205 KB

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