babylon.glTFFileLoader.js 170 KB

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