babylon.glTFFileLoader.js 198 KB

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