babylon.glTF1FileLoader.js 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFLoaderCoordinateSystemMode;
  5. (function (GLTFLoaderCoordinateSystemMode) {
  6. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  7. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  8. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  9. // The glTF right-handed data is not transformed in any form and is loaded directly.
  10. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  11. // Sets the useRightHandedSystem flag on the scene.
  12. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  13. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  14. var GLTFFileLoader = /** @class */ (function () {
  15. function GLTFFileLoader() {
  16. // V2 options
  17. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  18. this.compileMaterials = false;
  19. this.compileShadowGenerators = false;
  20. this.useClipPlane = false;
  21. this.name = "gltf";
  22. this.extensions = {
  23. ".gltf": { isBinary: false },
  24. ".glb": { isBinary: true }
  25. };
  26. }
  27. GLTFFileLoader.prototype.dispose = function () {
  28. if (this._loader) {
  29. this._loader.dispose();
  30. }
  31. };
  32. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  33. try {
  34. var loaderData = GLTFFileLoader._parse(data);
  35. if (this.onParsed) {
  36. this.onParsed(loaderData);
  37. }
  38. this._loader = this._getLoader(loaderData);
  39. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  40. }
  41. catch (e) {
  42. onError(e.message);
  43. }
  44. };
  45. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  46. try {
  47. var loaderData = GLTFFileLoader._parse(data);
  48. if (this.onParsed) {
  49. this.onParsed(loaderData);
  50. }
  51. this._loader = this._getLoader(loaderData);
  52. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  53. }
  54. catch (e) {
  55. onError(e.message);
  56. }
  57. };
  58. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  59. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  60. };
  61. GLTFFileLoader.prototype.createPlugin = function () {
  62. return new GLTFFileLoader();
  63. };
  64. GLTFFileLoader._parse = function (data) {
  65. if (data instanceof ArrayBuffer) {
  66. return GLTFFileLoader._parseBinary(data);
  67. }
  68. return {
  69. json: JSON.parse(data),
  70. bin: null
  71. };
  72. };
  73. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  74. var loaderVersion = { major: 2, minor: 0 };
  75. var asset = loaderData.json.asset || {};
  76. var version = GLTFFileLoader._parseVersion(asset.version);
  77. if (!version) {
  78. throw new Error("Invalid version: " + asset.version);
  79. }
  80. if (asset.minVersion !== undefined) {
  81. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  82. if (!minVersion) {
  83. throw new Error("Invalid minimum version: " + asset.minVersion);
  84. }
  85. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  86. throw new Error("Incompatible minimum version: " + asset.minVersion);
  87. }
  88. }
  89. var createLoaders = {
  90. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  91. 2: GLTFFileLoader.CreateGLTFLoaderV2
  92. };
  93. var createLoader = createLoaders[version.major];
  94. if (!createLoader) {
  95. throw new Error("Unsupported version: " + asset.version);
  96. }
  97. return createLoader(this);
  98. };
  99. GLTFFileLoader._parseBinary = function (data) {
  100. var Binary = {
  101. Magic: 0x46546C67
  102. };
  103. var binaryReader = new BinaryReader(data);
  104. var magic = binaryReader.readUint32();
  105. if (magic !== Binary.Magic) {
  106. throw new Error("Unexpected magic: " + magic);
  107. }
  108. var version = binaryReader.readUint32();
  109. switch (version) {
  110. case 1: return GLTFFileLoader._parseV1(binaryReader);
  111. case 2: return GLTFFileLoader._parseV2(binaryReader);
  112. }
  113. throw new Error("Unsupported version: " + version);
  114. };
  115. GLTFFileLoader._parseV1 = function (binaryReader) {
  116. var ContentFormat = {
  117. JSON: 0
  118. };
  119. var length = binaryReader.readUint32();
  120. if (length != binaryReader.getLength()) {
  121. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  122. }
  123. var contentLength = binaryReader.readUint32();
  124. var contentFormat = binaryReader.readUint32();
  125. var content;
  126. switch (contentFormat) {
  127. case ContentFormat.JSON: {
  128. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  129. break;
  130. }
  131. default: {
  132. throw new Error("Unexpected content format: " + contentFormat);
  133. }
  134. }
  135. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  136. var body = binaryReader.readUint8Array(bytesRemaining);
  137. return {
  138. json: content,
  139. bin: body
  140. };
  141. };
  142. GLTFFileLoader._parseV2 = function (binaryReader) {
  143. var ChunkFormat = {
  144. JSON: 0x4E4F534A,
  145. BIN: 0x004E4942
  146. };
  147. var length = binaryReader.readUint32();
  148. if (length !== binaryReader.getLength()) {
  149. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  150. }
  151. // JSON chunk
  152. var chunkLength = binaryReader.readUint32();
  153. var chunkFormat = binaryReader.readUint32();
  154. if (chunkFormat !== ChunkFormat.JSON) {
  155. throw new Error("First chunk format is not JSON");
  156. }
  157. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  158. // Look for BIN chunk
  159. var bin = null;
  160. while (binaryReader.getPosition() < binaryReader.getLength()) {
  161. var chunkLength_1 = binaryReader.readUint32();
  162. var chunkFormat_1 = binaryReader.readUint32();
  163. switch (chunkFormat_1) {
  164. case ChunkFormat.JSON: {
  165. throw new Error("Unexpected JSON chunk");
  166. }
  167. case ChunkFormat.BIN: {
  168. bin = binaryReader.readUint8Array(chunkLength_1);
  169. break;
  170. }
  171. default: {
  172. // ignore unrecognized chunkFormat
  173. binaryReader.skipBytes(chunkLength_1);
  174. break;
  175. }
  176. }
  177. }
  178. return {
  179. json: json,
  180. bin: bin
  181. };
  182. };
  183. GLTFFileLoader._parseVersion = function (version) {
  184. if (version === "1.0" || version === "1.0.1") {
  185. return {
  186. major: 1,
  187. minor: 0
  188. };
  189. }
  190. var match = (version + "").match(/^(\d+)\.(\d+)/);
  191. if (!match) {
  192. return null;
  193. }
  194. return {
  195. major: parseInt(match[1]),
  196. minor: parseInt(match[2])
  197. };
  198. };
  199. GLTFFileLoader._compareVersion = function (a, b) {
  200. if (a.major > b.major)
  201. return 1;
  202. if (a.major < b.major)
  203. return -1;
  204. if (a.minor > b.minor)
  205. return 1;
  206. if (a.minor < b.minor)
  207. return -1;
  208. return 0;
  209. };
  210. GLTFFileLoader._decodeBufferToText = function (buffer) {
  211. var result = "";
  212. var length = buffer.byteLength;
  213. for (var i = 0; i < length; i++) {
  214. result += String.fromCharCode(buffer[i]);
  215. }
  216. return result;
  217. };
  218. // V1 options
  219. GLTFFileLoader.HomogeneousCoordinates = false;
  220. GLTFFileLoader.IncrementalLoading = true;
  221. return GLTFFileLoader;
  222. }());
  223. BABYLON.GLTFFileLoader = GLTFFileLoader;
  224. var BinaryReader = /** @class */ (function () {
  225. function BinaryReader(arrayBuffer) {
  226. this._arrayBuffer = arrayBuffer;
  227. this._dataView = new DataView(arrayBuffer);
  228. this._byteOffset = 0;
  229. }
  230. BinaryReader.prototype.getPosition = function () {
  231. return this._byteOffset;
  232. };
  233. BinaryReader.prototype.getLength = function () {
  234. return this._arrayBuffer.byteLength;
  235. };
  236. BinaryReader.prototype.readUint32 = function () {
  237. var value = this._dataView.getUint32(this._byteOffset, true);
  238. this._byteOffset += 4;
  239. return value;
  240. };
  241. BinaryReader.prototype.readUint8Array = function (length) {
  242. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  243. this._byteOffset += length;
  244. return value;
  245. };
  246. BinaryReader.prototype.skipBytes = function (length) {
  247. this._byteOffset += length;
  248. };
  249. return BinaryReader;
  250. }());
  251. if (BABYLON.SceneLoader) {
  252. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  253. }
  254. })(BABYLON || (BABYLON = {}));
  255. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  256. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  257. var BABYLON;
  258. (function (BABYLON) {
  259. var GLTF1;
  260. (function (GLTF1) {
  261. /**
  262. * Enums
  263. */
  264. var EComponentType;
  265. (function (EComponentType) {
  266. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  267. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  268. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  269. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  270. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  271. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  272. var EShaderType;
  273. (function (EShaderType) {
  274. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  275. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  276. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  277. var EParameterType;
  278. (function (EParameterType) {
  279. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  280. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  281. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  282. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  283. EParameterType[EParameterType["INT"] = 5124] = "INT";
  284. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  285. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  286. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  287. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  288. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  289. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  290. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  291. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  292. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  293. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  294. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  295. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  296. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  297. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  298. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  299. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  300. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  301. var ETextureWrapMode;
  302. (function (ETextureWrapMode) {
  303. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  304. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  305. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  306. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  307. var ETextureFilterType;
  308. (function (ETextureFilterType) {
  309. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  310. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  311. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  312. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  313. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  314. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  315. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  316. var ETextureFormat;
  317. (function (ETextureFormat) {
  318. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  319. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  320. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  321. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  322. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  323. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  324. var ECullingType;
  325. (function (ECullingType) {
  326. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  327. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  328. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  329. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  330. var EBlendingFunction;
  331. (function (EBlendingFunction) {
  332. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  333. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  334. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  335. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  336. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  337. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  338. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  339. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  340. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  341. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  342. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  343. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  344. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  345. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  346. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  347. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  348. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  349. })(BABYLON || (BABYLON = {}));
  350. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  351. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  352. var BABYLON;
  353. (function (BABYLON) {
  354. var GLTF1;
  355. (function (GLTF1) {
  356. /**
  357. * Tokenizer. Used for shaders compatibility
  358. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  359. */
  360. var ETokenType;
  361. (function (ETokenType) {
  362. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  363. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  364. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  365. })(ETokenType || (ETokenType = {}));
  366. var Tokenizer = /** @class */ (function () {
  367. function Tokenizer(toParse) {
  368. this._pos = 0;
  369. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  370. this._toParse = toParse;
  371. this._maxPos = toParse.length;
  372. }
  373. Tokenizer.prototype.getNextToken = function () {
  374. if (this.isEnd())
  375. return ETokenType.END_OF_INPUT;
  376. this.currentString = this.read();
  377. this.currentToken = ETokenType.UNKNOWN;
  378. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  379. this.currentToken = ETokenType.IDENTIFIER;
  380. this.currentIdentifier = this.currentString;
  381. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  382. this.currentIdentifier += this.currentString;
  383. this.forward();
  384. }
  385. }
  386. return this.currentToken;
  387. };
  388. Tokenizer.prototype.peek = function () {
  389. return this._toParse[this._pos];
  390. };
  391. Tokenizer.prototype.read = function () {
  392. return this._toParse[this._pos++];
  393. };
  394. Tokenizer.prototype.forward = function () {
  395. this._pos++;
  396. };
  397. Tokenizer.prototype.isEnd = function () {
  398. return this._pos >= this._maxPos;
  399. };
  400. return Tokenizer;
  401. }());
  402. /**
  403. * Values
  404. */
  405. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  406. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  407. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  408. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  409. /**
  410. * Parse
  411. */
  412. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  413. for (var buf in parsedBuffers) {
  414. var parsedBuffer = parsedBuffers[buf];
  415. gltfRuntime.buffers[buf] = parsedBuffer;
  416. gltfRuntime.buffersCount++;
  417. }
  418. };
  419. var parseShaders = function (parsedShaders, gltfRuntime) {
  420. for (var sha in parsedShaders) {
  421. var parsedShader = parsedShaders[sha];
  422. gltfRuntime.shaders[sha] = parsedShader;
  423. gltfRuntime.shaderscount++;
  424. }
  425. };
  426. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  427. for (var object in parsedObjects) {
  428. var parsedObject = parsedObjects[object];
  429. gltfRuntime[runtimeProperty][object] = parsedObject;
  430. }
  431. };
  432. /**
  433. * Utils
  434. */
  435. var normalizeUVs = function (buffer) {
  436. if (!buffer) {
  437. return;
  438. }
  439. for (var i = 0; i < buffer.length / 2; i++) {
  440. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  441. }
  442. };
  443. var getAttribute = function (attributeParameter) {
  444. if (attributeParameter.semantic === "NORMAL") {
  445. return "normal";
  446. }
  447. else if (attributeParameter.semantic === "POSITION") {
  448. return "position";
  449. }
  450. else if (attributeParameter.semantic === "JOINT") {
  451. return "matricesIndices";
  452. }
  453. else if (attributeParameter.semantic === "WEIGHT") {
  454. return "matricesWeights";
  455. }
  456. else if (attributeParameter.semantic === "COLOR") {
  457. return "color";
  458. }
  459. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  460. var channel = Number(attributeParameter.semantic.split("_")[1]);
  461. return "uv" + (channel === 0 ? "" : channel + 1);
  462. }
  463. return null;
  464. };
  465. /**
  466. * Loads and creates animations
  467. */
  468. var loadAnimations = function (gltfRuntime) {
  469. for (var anim in gltfRuntime.animations) {
  470. var animation = gltfRuntime.animations[anim];
  471. if (!animation.channels || !animation.samplers) {
  472. continue;
  473. }
  474. var lastAnimation = null;
  475. for (var i = 0; i < animation.channels.length; i++) {
  476. // Get parameters and load buffers
  477. var channel = animation.channels[i];
  478. var sampler = animation.samplers[channel.sampler];
  479. if (!sampler) {
  480. continue;
  481. }
  482. var inputData = null;
  483. var outputData = null;
  484. if (animation.parameters) {
  485. inputData = animation.parameters[sampler.input];
  486. outputData = animation.parameters[sampler.output];
  487. }
  488. else {
  489. inputData = sampler.input;
  490. outputData = sampler.output;
  491. }
  492. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  493. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  494. var targetID = channel.target.id;
  495. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  496. if (targetNode === null) {
  497. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  498. }
  499. if (targetNode === null) {
  500. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  501. continue;
  502. }
  503. var isBone = targetNode instanceof BABYLON.Bone;
  504. // Get target path (position, rotation or scaling)
  505. var targetPath = channel.target.path;
  506. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  507. if (targetPathIndex !== -1) {
  508. targetPath = babylonAnimationPaths[targetPathIndex];
  509. }
  510. // Determine animation type
  511. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  512. if (!isBone) {
  513. if (targetPath === "rotationQuaternion") {
  514. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  515. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  516. }
  517. else {
  518. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  519. }
  520. }
  521. // Create animation and key frames
  522. var babylonAnimation = null;
  523. var keys = [];
  524. var arrayOffset = 0;
  525. var modifyKey = false;
  526. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  527. babylonAnimation = lastAnimation;
  528. modifyKey = true;
  529. }
  530. if (!modifyKey) {
  531. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  532. }
  533. // For each frame
  534. for (var j = 0; j < bufferInput.length; j++) {
  535. var value = null;
  536. if (targetPath === "rotationQuaternion") {
  537. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  538. arrayOffset += 4;
  539. }
  540. else {
  541. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  542. arrayOffset += 3;
  543. }
  544. if (isBone) {
  545. var bone = targetNode;
  546. var translation = BABYLON.Vector3.Zero();
  547. var rotationQuaternion = new BABYLON.Quaternion();
  548. var scaling = BABYLON.Vector3.Zero();
  549. // Warning on decompose
  550. var mat = bone.getBaseMatrix();
  551. if (modifyKey && lastAnimation) {
  552. mat = lastAnimation.getKeys()[j].value;
  553. }
  554. mat.decompose(scaling, rotationQuaternion, translation);
  555. if (targetPath === "position") {
  556. translation = value;
  557. }
  558. else if (targetPath === "rotationQuaternion") {
  559. rotationQuaternion = value;
  560. }
  561. else {
  562. scaling = value;
  563. }
  564. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  565. }
  566. if (!modifyKey) {
  567. keys.push({
  568. frame: bufferInput[j],
  569. value: value
  570. });
  571. }
  572. else if (lastAnimation) {
  573. lastAnimation.getKeys()[j].value = value;
  574. }
  575. }
  576. // Finish
  577. if (!modifyKey && babylonAnimation) {
  578. babylonAnimation.setKeys(keys);
  579. targetNode.animations.push(babylonAnimation);
  580. }
  581. lastAnimation = babylonAnimation;
  582. gltfRuntime.scene.stopAnimation(targetNode);
  583. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  584. }
  585. }
  586. };
  587. /**
  588. * Returns the bones transformation matrix
  589. */
  590. var configureBoneTransformation = function (node) {
  591. var mat = null;
  592. if (node.translation || node.rotation || node.scale) {
  593. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  594. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  595. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  596. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  597. }
  598. else {
  599. mat = BABYLON.Matrix.FromArray(node.matrix);
  600. }
  601. return mat;
  602. };
  603. /**
  604. * Returns the parent bone
  605. */
  606. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  607. // Try to find
  608. for (var i = 0; i < newSkeleton.bones.length; i++) {
  609. if (newSkeleton.bones[i].name === jointName) {
  610. return newSkeleton.bones[i];
  611. }
  612. }
  613. // Not found, search in gltf nodes
  614. var nodes = gltfRuntime.nodes;
  615. for (var nde in nodes) {
  616. var node = nodes[nde];
  617. if (!node.jointName) {
  618. continue;
  619. }
  620. var children = node.children;
  621. for (var i = 0; i < children.length; i++) {
  622. var child = gltfRuntime.nodes[children[i]];
  623. if (!child.jointName) {
  624. continue;
  625. }
  626. if (child.jointName === jointName) {
  627. var mat = configureBoneTransformation(node);
  628. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  629. bone.id = nde;
  630. return bone;
  631. }
  632. }
  633. }
  634. return null;
  635. };
  636. /**
  637. * Returns the appropriate root node
  638. */
  639. var getNodeToRoot = function (nodesToRoot, id) {
  640. for (var i = 0; i < nodesToRoot.length; i++) {
  641. var nodeToRoot = nodesToRoot[i];
  642. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  643. var child = nodeToRoot.node.children[j];
  644. if (child === id) {
  645. return nodeToRoot.bone;
  646. }
  647. }
  648. }
  649. return null;
  650. };
  651. /**
  652. * Returns the node with the joint name
  653. */
  654. var getJointNode = function (gltfRuntime, jointName) {
  655. var nodes = gltfRuntime.nodes;
  656. var node = nodes[jointName];
  657. if (node) {
  658. return {
  659. node: node,
  660. id: jointName
  661. };
  662. }
  663. for (var nde in nodes) {
  664. node = nodes[nde];
  665. if (node.jointName === jointName) {
  666. return {
  667. node: node,
  668. id: nde
  669. };
  670. }
  671. }
  672. return null;
  673. };
  674. /**
  675. * Checks if a nodes is in joints
  676. */
  677. var nodeIsInJoints = function (skins, id) {
  678. for (var i = 0; i < skins.jointNames.length; i++) {
  679. if (skins.jointNames[i] === id) {
  680. return true;
  681. }
  682. }
  683. return false;
  684. };
  685. /**
  686. * Fills the nodes to root for bones and builds hierarchy
  687. */
  688. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  689. // Creates nodes for root
  690. for (var nde in gltfRuntime.nodes) {
  691. var node = gltfRuntime.nodes[nde];
  692. var id = nde;
  693. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  694. continue;
  695. }
  696. // Create node to root bone
  697. var mat = configureBoneTransformation(node);
  698. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  699. bone.id = id;
  700. nodesToRoot.push({ bone: bone, node: node, id: id });
  701. }
  702. // Parenting
  703. for (var i = 0; i < nodesToRoot.length; i++) {
  704. var nodeToRoot = nodesToRoot[i];
  705. var children = nodeToRoot.node.children;
  706. for (var j = 0; j < children.length; j++) {
  707. var child = null;
  708. for (var k = 0; k < nodesToRoot.length; k++) {
  709. if (nodesToRoot[k].id === children[j]) {
  710. child = nodesToRoot[k];
  711. break;
  712. }
  713. }
  714. if (child) {
  715. child.bone._parent = nodeToRoot.bone;
  716. nodeToRoot.bone.children.push(child.bone);
  717. }
  718. }
  719. }
  720. };
  721. /**
  722. * Imports a skeleton
  723. */
  724. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  725. if (!newSkeleton) {
  726. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  727. }
  728. if (!skins.babylonSkeleton) {
  729. return newSkeleton;
  730. }
  731. // Find the root bones
  732. var nodesToRoot = [];
  733. var nodesToRootToAdd = [];
  734. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  735. newSkeleton.bones = [];
  736. // Joints
  737. for (var i = 0; i < skins.jointNames.length; i++) {
  738. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  739. if (!jointNode) {
  740. continue;
  741. }
  742. var node = jointNode.node;
  743. if (!node) {
  744. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  745. continue;
  746. }
  747. var id = jointNode.id;
  748. // Optimize, if the bone already exists...
  749. var existingBone = gltfRuntime.scene.getBoneByID(id);
  750. if (existingBone) {
  751. newSkeleton.bones.push(existingBone);
  752. continue;
  753. }
  754. // Search for parent bone
  755. var foundBone = false;
  756. var parentBone = null;
  757. for (var j = 0; j < i; j++) {
  758. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  759. if (!jointNode_1) {
  760. continue;
  761. }
  762. var joint = jointNode_1.node;
  763. if (!joint) {
  764. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  765. continue;
  766. }
  767. var children = joint.children;
  768. if (!children) {
  769. continue;
  770. }
  771. foundBone = false;
  772. for (var k = 0; k < children.length; k++) {
  773. if (children[k] === id) {
  774. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  775. foundBone = true;
  776. break;
  777. }
  778. }
  779. if (foundBone) {
  780. break;
  781. }
  782. }
  783. // Create bone
  784. var mat = configureBoneTransformation(node);
  785. if (!parentBone && nodesToRoot.length > 0) {
  786. parentBone = getNodeToRoot(nodesToRoot, id);
  787. if (parentBone) {
  788. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  789. nodesToRootToAdd.push(parentBone);
  790. }
  791. }
  792. }
  793. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  794. bone.id = id;
  795. }
  796. // Polish
  797. var bones = newSkeleton.bones;
  798. newSkeleton.bones = [];
  799. for (var i = 0; i < skins.jointNames.length; i++) {
  800. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  801. if (!jointNode) {
  802. continue;
  803. }
  804. for (var j = 0; j < bones.length; j++) {
  805. if (bones[j].id === jointNode.id) {
  806. newSkeleton.bones.push(bones[j]);
  807. break;
  808. }
  809. }
  810. }
  811. newSkeleton.prepare();
  812. // Finish
  813. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  814. newSkeleton.bones.push(nodesToRootToAdd[i]);
  815. }
  816. return newSkeleton;
  817. };
  818. /**
  819. * Imports a mesh and its geometries
  820. */
  821. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  822. if (!newMesh) {
  823. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  824. newMesh.id = id;
  825. }
  826. if (!node.babylonNode) {
  827. return newMesh;
  828. }
  829. var subMaterials = [];
  830. var vertexData = new BABYLON.VertexData();
  831. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  832. var verticesStarts = new Array();
  833. var verticesCounts = new Array();
  834. var indexStarts = new Array();
  835. var indexCounts = new Array();
  836. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  837. var meshID = meshes[meshIndex];
  838. var mesh = gltfRuntime.meshes[meshID];
  839. if (!mesh) {
  840. continue;
  841. }
  842. // Positions, normals and UVs
  843. for (var i = 0; i < mesh.primitives.length; i++) {
  844. // Temporary vertex data
  845. var tempVertexData = new BABYLON.VertexData();
  846. var primitive = mesh.primitives[i];
  847. if (primitive.mode !== 4) {
  848. // continue;
  849. }
  850. var attributes = primitive.attributes;
  851. var accessor = null;
  852. var buffer = null;
  853. // Set positions, normal and uvs
  854. for (var semantic in attributes) {
  855. // Link accessor and buffer view
  856. accessor = gltfRuntime.accessors[attributes[semantic]];
  857. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  858. if (semantic === "NORMAL") {
  859. tempVertexData.normals = new Float32Array(buffer.length);
  860. tempVertexData.normals.set(buffer);
  861. }
  862. else if (semantic === "POSITION") {
  863. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  864. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  865. for (var j = 0; j < buffer.length; j += 4) {
  866. tempVertexData.positions[j] = buffer[j];
  867. tempVertexData.positions[j + 1] = buffer[j + 1];
  868. tempVertexData.positions[j + 2] = buffer[j + 2];
  869. }
  870. }
  871. else {
  872. tempVertexData.positions = new Float32Array(buffer.length);
  873. tempVertexData.positions.set(buffer);
  874. }
  875. verticesCounts.push(tempVertexData.positions.length);
  876. }
  877. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  878. var channel = Number(semantic.split("_")[1]);
  879. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  880. var uvs = new Float32Array(buffer.length);
  881. uvs.set(buffer);
  882. normalizeUVs(uvs);
  883. tempVertexData.set(uvs, uvKind);
  884. }
  885. else if (semantic === "JOINT") {
  886. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  887. tempVertexData.matricesIndices.set(buffer);
  888. }
  889. else if (semantic === "WEIGHT") {
  890. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  891. tempVertexData.matricesWeights.set(buffer);
  892. }
  893. else if (semantic === "COLOR") {
  894. tempVertexData.colors = new Float32Array(buffer.length);
  895. tempVertexData.colors.set(buffer);
  896. }
  897. }
  898. // Indices
  899. accessor = gltfRuntime.accessors[primitive.indices];
  900. if (accessor) {
  901. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  902. tempVertexData.indices = new Int32Array(buffer.length);
  903. tempVertexData.indices.set(buffer);
  904. indexCounts.push(tempVertexData.indices.length);
  905. }
  906. else {
  907. // Set indices on the fly
  908. var indices = [];
  909. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  910. indices.push(j);
  911. }
  912. tempVertexData.indices = new Int32Array(indices);
  913. indexCounts.push(tempVertexData.indices.length);
  914. }
  915. vertexData.merge(tempVertexData);
  916. // Sub material
  917. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  918. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  919. // Update vertices start and index start
  920. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  921. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  922. }
  923. }
  924. var material;
  925. if (subMaterials.length > 1) {
  926. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  927. material.subMaterials = subMaterials;
  928. }
  929. else {
  930. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  931. }
  932. if (subMaterials.length === 1) {
  933. material = subMaterials[0];
  934. }
  935. if (!newMesh.material) {
  936. newMesh.material = material;
  937. }
  938. // Apply geometry
  939. geometry.setAllVerticesData(vertexData, false);
  940. newMesh.computeWorldMatrix(true);
  941. // Apply submeshes
  942. newMesh.subMeshes = [];
  943. var index = 0;
  944. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  945. var meshID = meshes[meshIndex];
  946. var mesh = gltfRuntime.meshes[meshID];
  947. if (!mesh) {
  948. continue;
  949. }
  950. for (var i = 0; i < mesh.primitives.length; i++) {
  951. if (mesh.primitives[i].mode !== 4) {
  952. //continue;
  953. }
  954. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  955. index++;
  956. }
  957. }
  958. // Finish
  959. return newMesh;
  960. };
  961. /**
  962. * Configure node transformation from position, rotation and scaling
  963. */
  964. var configureNode = function (newNode, position, rotation, scaling) {
  965. if (newNode.position) {
  966. newNode.position = position;
  967. }
  968. if (newNode.rotationQuaternion || newNode.rotation) {
  969. newNode.rotationQuaternion = rotation;
  970. }
  971. if (newNode.scaling) {
  972. newNode.scaling = scaling;
  973. }
  974. };
  975. /**
  976. * Configures node from transformation matrix
  977. */
  978. var configureNodeFromMatrix = function (newNode, node, parent) {
  979. if (node.matrix) {
  980. var position = new BABYLON.Vector3(0, 0, 0);
  981. var rotation = new BABYLON.Quaternion();
  982. var scaling = new BABYLON.Vector3(0, 0, 0);
  983. var mat = BABYLON.Matrix.FromArray(node.matrix);
  984. mat.decompose(scaling, rotation, position);
  985. configureNode(newNode, position, rotation, scaling);
  986. }
  987. else if (node.translation && node.rotation && node.scale) {
  988. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  989. }
  990. newNode.computeWorldMatrix(true);
  991. };
  992. /**
  993. * Imports a node
  994. */
  995. var importNode = function (gltfRuntime, node, id, parent) {
  996. var lastNode = null;
  997. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  998. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  999. return null;
  1000. }
  1001. }
  1002. // Meshes
  1003. if (node.skin) {
  1004. if (node.meshes) {
  1005. var skin = gltfRuntime.skins[node.skin];
  1006. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1007. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1008. if (newMesh.skeleton === null) {
  1009. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1010. if (!skin.babylonSkeleton) {
  1011. skin.babylonSkeleton = newMesh.skeleton;
  1012. }
  1013. }
  1014. lastNode = newMesh;
  1015. }
  1016. }
  1017. else if (node.meshes) {
  1018. /**
  1019. * Improve meshes property
  1020. */
  1021. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1022. lastNode = newMesh;
  1023. }
  1024. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1025. var light = gltfRuntime.lights[node.light];
  1026. if (light) {
  1027. if (light.type === "ambient") {
  1028. var ambienLight = light[light.type];
  1029. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1030. hemiLight.name = node.name || "";
  1031. if (ambienLight.color) {
  1032. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1033. }
  1034. lastNode = hemiLight;
  1035. }
  1036. else if (light.type === "directional") {
  1037. var directionalLight = light[light.type];
  1038. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1039. dirLight.name = node.name || "";
  1040. if (directionalLight.color) {
  1041. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1042. }
  1043. lastNode = dirLight;
  1044. }
  1045. else if (light.type === "point") {
  1046. var pointLight = light[light.type];
  1047. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1048. ptLight.name = node.name || "";
  1049. if (pointLight.color) {
  1050. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1051. }
  1052. lastNode = ptLight;
  1053. }
  1054. else if (light.type === "spot") {
  1055. var spotLight = light[light.type];
  1056. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1057. spLight.name = node.name || "";
  1058. if (spotLight.color) {
  1059. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1060. }
  1061. if (spotLight.fallOfAngle) {
  1062. spLight.angle = spotLight.fallOfAngle;
  1063. }
  1064. if (spotLight.fallOffExponent) {
  1065. spLight.exponent = spotLight.fallOffExponent;
  1066. }
  1067. lastNode = spLight;
  1068. }
  1069. }
  1070. }
  1071. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1072. var camera = gltfRuntime.cameras[node.camera];
  1073. if (camera) {
  1074. if (camera.type === "orthographic") {
  1075. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1076. orthoCamera.name = node.name || "";
  1077. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1078. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1079. lastNode = orthoCamera;
  1080. }
  1081. else if (camera.type === "perspective") {
  1082. var perspectiveCamera = camera[camera.type];
  1083. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1084. persCamera.name = node.name || "";
  1085. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1086. if (!perspectiveCamera.aspectRatio) {
  1087. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1088. }
  1089. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1090. persCamera.maxZ = perspectiveCamera.zfar;
  1091. persCamera.minZ = perspectiveCamera.znear;
  1092. }
  1093. lastNode = persCamera;
  1094. }
  1095. }
  1096. }
  1097. // Empty node
  1098. if (!node.jointName) {
  1099. if (node.babylonNode) {
  1100. return node.babylonNode;
  1101. }
  1102. else if (lastNode === null) {
  1103. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1104. node.babylonNode = dummy;
  1105. lastNode = dummy;
  1106. }
  1107. }
  1108. if (lastNode !== null) {
  1109. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1110. configureNodeFromMatrix(lastNode, node, parent);
  1111. }
  1112. else {
  1113. var translation = node.translation || [0, 0, 0];
  1114. var rotation = node.rotation || [0, 0, 0, 1];
  1115. var scale = node.scale || [1, 1, 1];
  1116. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1117. }
  1118. lastNode.updateCache(true);
  1119. node.babylonNode = lastNode;
  1120. }
  1121. return lastNode;
  1122. };
  1123. /**
  1124. * Traverses nodes and creates them
  1125. */
  1126. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1127. if (meshIncluded === void 0) { meshIncluded = false; }
  1128. var node = gltfRuntime.nodes[id];
  1129. var newNode = null;
  1130. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1131. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1132. meshIncluded = true;
  1133. }
  1134. else {
  1135. meshIncluded = false;
  1136. }
  1137. }
  1138. else {
  1139. meshIncluded = true;
  1140. }
  1141. if (!node.jointName && meshIncluded) {
  1142. newNode = importNode(gltfRuntime, node, id, parent);
  1143. if (newNode !== null) {
  1144. newNode.id = id;
  1145. newNode.parent = parent;
  1146. }
  1147. }
  1148. if (node.children) {
  1149. for (var i = 0; i < node.children.length; i++) {
  1150. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1151. }
  1152. }
  1153. };
  1154. /**
  1155. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1156. */
  1157. var postLoad = function (gltfRuntime) {
  1158. // Nodes
  1159. var currentScene = gltfRuntime.currentScene;
  1160. if (currentScene) {
  1161. for (var i = 0; i < currentScene.nodes.length; i++) {
  1162. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1163. }
  1164. }
  1165. else {
  1166. for (var thing in gltfRuntime.scenes) {
  1167. currentScene = gltfRuntime.scenes[thing];
  1168. for (var i = 0; i < currentScene.nodes.length; i++) {
  1169. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1170. }
  1171. }
  1172. }
  1173. // Set animations
  1174. loadAnimations(gltfRuntime);
  1175. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1176. var skeleton = gltfRuntime.scene.skeletons[i];
  1177. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1178. }
  1179. };
  1180. /**
  1181. * onBind shaderrs callback to set uniforms and matrices
  1182. */
  1183. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1184. var materialValues = material.values || technique.parameters;
  1185. for (var unif in unTreatedUniforms) {
  1186. var uniform = unTreatedUniforms[unif];
  1187. var type = uniform.type;
  1188. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1189. if (uniform.semantic && !uniform.source && !uniform.node) {
  1190. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1191. }
  1192. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1193. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1194. if (source === null) {
  1195. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1196. }
  1197. if (source === null) {
  1198. continue;
  1199. }
  1200. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1201. }
  1202. }
  1203. else {
  1204. var value = materialValues[technique.uniforms[unif]];
  1205. if (!value) {
  1206. continue;
  1207. }
  1208. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1209. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1210. if (texture === null || texture === undefined) {
  1211. continue;
  1212. }
  1213. shaderMaterial.getEffect().setTexture(unif, texture);
  1214. }
  1215. else {
  1216. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1217. }
  1218. }
  1219. }
  1220. onSuccess(shaderMaterial);
  1221. };
  1222. /**
  1223. * Prepare uniforms to send the only one time
  1224. * Loads the appropriate textures
  1225. */
  1226. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1227. var materialValues = material.values || technique.parameters;
  1228. var techniqueUniforms = technique.uniforms;
  1229. /**
  1230. * Prepare values here (not matrices)
  1231. */
  1232. for (var unif in unTreatedUniforms) {
  1233. var uniform = unTreatedUniforms[unif];
  1234. var type = uniform.type;
  1235. var value = materialValues[techniqueUniforms[unif]];
  1236. if (value === undefined) {
  1237. // In case the value is the same for all materials
  1238. value = uniform.value;
  1239. }
  1240. if (!value) {
  1241. continue;
  1242. }
  1243. var onLoadTexture = function (uniformName) {
  1244. return function (texture) {
  1245. if (uniform.value && uniformName) {
  1246. // Static uniform
  1247. shaderMaterial.setTexture(uniformName, texture);
  1248. delete unTreatedUniforms[uniformName];
  1249. }
  1250. };
  1251. };
  1252. // Texture (sampler2D)
  1253. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1254. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1255. }
  1256. else {
  1257. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1258. // Static uniform
  1259. delete unTreatedUniforms[unif];
  1260. }
  1261. }
  1262. }
  1263. };
  1264. /**
  1265. * Shader compilation failed
  1266. */
  1267. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1268. return function (effect, error) {
  1269. shaderMaterial.dispose(true);
  1270. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1271. };
  1272. };
  1273. /**
  1274. * Shader compilation success
  1275. */
  1276. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1277. return function (_) {
  1278. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1279. shaderMaterial.onBind = function (mesh) {
  1280. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1281. };
  1282. };
  1283. };
  1284. /**
  1285. * Returns the appropriate uniform if already handled by babylon
  1286. */
  1287. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1288. for (var unif in technique.uniforms) {
  1289. var uniform = technique.uniforms[unif];
  1290. var uniformParameter = technique.parameters[uniform];
  1291. if (tokenizer.currentIdentifier === unif) {
  1292. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1293. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1294. if (transformIndex !== -1) {
  1295. delete unTreatedUniforms[unif];
  1296. return babylonTransforms[transformIndex];
  1297. }
  1298. }
  1299. }
  1300. }
  1301. return tokenizer.currentIdentifier;
  1302. };
  1303. /**
  1304. * All shaders loaded. Create materials one by one
  1305. */
  1306. var importMaterials = function (gltfRuntime) {
  1307. // Create materials
  1308. for (var mat in gltfRuntime.materials) {
  1309. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1310. }
  1311. };
  1312. /**
  1313. * Implementation of the base glTF spec
  1314. */
  1315. var GLTFLoaderBase = /** @class */ (function () {
  1316. function GLTFLoaderBase() {
  1317. }
  1318. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1319. var gltfRuntime = {
  1320. extensions: {},
  1321. accessors: {},
  1322. buffers: {},
  1323. bufferViews: {},
  1324. meshes: {},
  1325. lights: {},
  1326. cameras: {},
  1327. nodes: {},
  1328. images: {},
  1329. textures: {},
  1330. shaders: {},
  1331. programs: {},
  1332. samplers: {},
  1333. techniques: {},
  1334. materials: {},
  1335. animations: {},
  1336. skins: {},
  1337. extensionsUsed: [],
  1338. scenes: {},
  1339. buffersCount: 0,
  1340. shaderscount: 0,
  1341. scene: scene,
  1342. rootUrl: rootUrl,
  1343. loadedBufferCount: 0,
  1344. loadedBufferViews: {},
  1345. loadedShaderCount: 0,
  1346. importOnlyMeshes: false,
  1347. dummyNodes: []
  1348. };
  1349. // Parse
  1350. if (parsedData.extensions) {
  1351. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1352. }
  1353. if (parsedData.extensionsUsed) {
  1354. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1355. }
  1356. if (parsedData.buffers) {
  1357. parseBuffers(parsedData.buffers, gltfRuntime);
  1358. }
  1359. if (parsedData.bufferViews) {
  1360. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1361. }
  1362. if (parsedData.accessors) {
  1363. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1364. }
  1365. if (parsedData.meshes) {
  1366. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1367. }
  1368. if (parsedData.lights) {
  1369. parseObject(parsedData.lights, "lights", gltfRuntime);
  1370. }
  1371. if (parsedData.cameras) {
  1372. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1373. }
  1374. if (parsedData.nodes) {
  1375. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1376. }
  1377. if (parsedData.images) {
  1378. parseObject(parsedData.images, "images", gltfRuntime);
  1379. }
  1380. if (parsedData.textures) {
  1381. parseObject(parsedData.textures, "textures", gltfRuntime);
  1382. }
  1383. if (parsedData.shaders) {
  1384. parseShaders(parsedData.shaders, gltfRuntime);
  1385. }
  1386. if (parsedData.programs) {
  1387. parseObject(parsedData.programs, "programs", gltfRuntime);
  1388. }
  1389. if (parsedData.samplers) {
  1390. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1391. }
  1392. if (parsedData.techniques) {
  1393. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1394. }
  1395. if (parsedData.materials) {
  1396. parseObject(parsedData.materials, "materials", gltfRuntime);
  1397. }
  1398. if (parsedData.animations) {
  1399. parseObject(parsedData.animations, "animations", gltfRuntime);
  1400. }
  1401. if (parsedData.skins) {
  1402. parseObject(parsedData.skins, "skins", gltfRuntime);
  1403. }
  1404. if (parsedData.scenes) {
  1405. gltfRuntime.scenes = parsedData.scenes;
  1406. }
  1407. if (parsedData.scene && parsedData.scenes) {
  1408. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1409. }
  1410. return gltfRuntime;
  1411. };
  1412. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1413. var buffer = gltfRuntime.buffers[id];
  1414. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  1415. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  1416. }
  1417. else {
  1418. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1419. if (request) {
  1420. onError(request.status + " " + request.statusText);
  1421. }
  1422. });
  1423. }
  1424. };
  1425. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1426. var texture = gltfRuntime.textures[id];
  1427. if (!texture || !texture.source) {
  1428. onError("");
  1429. return;
  1430. }
  1431. if (texture.babylonTexture) {
  1432. onSuccess(null);
  1433. return;
  1434. }
  1435. var source = gltfRuntime.images[texture.source];
  1436. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  1437. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  1438. }
  1439. else {
  1440. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1441. if (request) {
  1442. onError(request.status + " " + request.statusText);
  1443. }
  1444. });
  1445. }
  1446. };
  1447. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1448. var texture = gltfRuntime.textures[id];
  1449. if (texture.babylonTexture) {
  1450. onSuccess(texture.babylonTexture);
  1451. return;
  1452. }
  1453. var sampler = gltfRuntime.samplers[texture.sampler];
  1454. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1455. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1456. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1457. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1458. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1459. var blob = new Blob([buffer]);
  1460. var blobURL = URL.createObjectURL(blob);
  1461. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1462. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1463. if (sampler.wrapS !== undefined) {
  1464. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1465. }
  1466. if (sampler.wrapT !== undefined) {
  1467. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1468. }
  1469. newTexture.name = id;
  1470. texture.babylonTexture = newTexture;
  1471. onSuccess(newTexture);
  1472. };
  1473. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1474. var shader = gltfRuntime.shaders[id];
  1475. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  1476. var shaderString = atob(shader.uri.split(",")[1]);
  1477. onSuccess(shaderString);
  1478. }
  1479. else {
  1480. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1481. if (request) {
  1482. onError(request.status + " " + request.statusText);
  1483. }
  1484. });
  1485. }
  1486. };
  1487. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1488. var material = gltfRuntime.materials[id];
  1489. if (!material.technique) {
  1490. if (onError) {
  1491. onError("No technique found.");
  1492. }
  1493. return;
  1494. }
  1495. var technique = gltfRuntime.techniques[material.technique];
  1496. if (!technique) {
  1497. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1498. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1499. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1500. onSuccess(defaultMaterial);
  1501. return;
  1502. }
  1503. var program = gltfRuntime.programs[technique.program];
  1504. var states = technique.states;
  1505. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1506. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1507. var newVertexShader = "";
  1508. var newPixelShader = "";
  1509. var vertexTokenizer = new Tokenizer(vertexShader);
  1510. var pixelTokenizer = new Tokenizer(pixelShader);
  1511. var unTreatedUniforms = {};
  1512. var uniforms = [];
  1513. var attributes = [];
  1514. var samplers = [];
  1515. // Fill uniform, sampler2D and attributes
  1516. for (var unif in technique.uniforms) {
  1517. var uniform = technique.uniforms[unif];
  1518. var uniformParameter = technique.parameters[uniform];
  1519. unTreatedUniforms[unif] = uniformParameter;
  1520. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1521. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1522. if (transformIndex !== -1) {
  1523. uniforms.push(babylonTransforms[transformIndex]);
  1524. delete unTreatedUniforms[unif];
  1525. }
  1526. else {
  1527. uniforms.push(unif);
  1528. }
  1529. }
  1530. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1531. samplers.push(unif);
  1532. }
  1533. else {
  1534. uniforms.push(unif);
  1535. }
  1536. }
  1537. for (var attr in technique.attributes) {
  1538. var attribute = technique.attributes[attr];
  1539. var attributeParameter = technique.parameters[attribute];
  1540. if (attributeParameter.semantic) {
  1541. attributes.push(getAttribute(attributeParameter));
  1542. }
  1543. }
  1544. // Configure vertex shader
  1545. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1546. var tokenType = vertexTokenizer.currentToken;
  1547. if (tokenType !== ETokenType.IDENTIFIER) {
  1548. newVertexShader += vertexTokenizer.currentString;
  1549. continue;
  1550. }
  1551. var foundAttribute = false;
  1552. for (var attr in technique.attributes) {
  1553. var attribute = technique.attributes[attr];
  1554. var attributeParameter = technique.parameters[attribute];
  1555. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1556. newVertexShader += getAttribute(attributeParameter);
  1557. foundAttribute = true;
  1558. break;
  1559. }
  1560. }
  1561. if (foundAttribute) {
  1562. continue;
  1563. }
  1564. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1565. }
  1566. // Configure pixel shader
  1567. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1568. var tokenType = pixelTokenizer.currentToken;
  1569. if (tokenType !== ETokenType.IDENTIFIER) {
  1570. newPixelShader += pixelTokenizer.currentString;
  1571. continue;
  1572. }
  1573. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1574. }
  1575. // Create shader material
  1576. var shaderPath = {
  1577. vertex: program.vertexShader + id,
  1578. fragment: program.fragmentShader + id
  1579. };
  1580. var options = {
  1581. attributes: attributes,
  1582. uniforms: uniforms,
  1583. samplers: samplers,
  1584. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1585. };
  1586. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1587. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1588. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1589. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1590. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1591. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1592. if (states && states.functions) {
  1593. var functions = states.functions;
  1594. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1595. shaderMaterial.backFaceCulling = false;
  1596. }
  1597. var blendFunc = functions.blendFuncSeparate;
  1598. if (blendFunc) {
  1599. 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) {
  1600. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1601. }
  1602. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1603. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1604. }
  1605. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1606. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1607. }
  1608. 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) {
  1609. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1610. }
  1611. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1612. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1613. }
  1614. 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) {
  1615. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1616. }
  1617. }
  1618. }
  1619. };
  1620. return GLTFLoaderBase;
  1621. }());
  1622. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1623. /**
  1624. * glTF V1 Loader
  1625. */
  1626. var GLTFLoader = /** @class */ (function () {
  1627. function GLTFLoader() {
  1628. }
  1629. GLTFLoader.RegisterExtension = function (extension) {
  1630. if (GLTFLoader.Extensions[extension.name]) {
  1631. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1632. return;
  1633. }
  1634. GLTFLoader.Extensions[extension.name] = extension;
  1635. };
  1636. GLTFLoader.prototype.dispose = function () {
  1637. // do nothing
  1638. };
  1639. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1640. var _this = this;
  1641. scene.useRightHandedSystem = true;
  1642. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1643. gltfRuntime.importOnlyMeshes = true;
  1644. if (meshesNames === "") {
  1645. gltfRuntime.importMeshesNames = [];
  1646. }
  1647. else if (typeof meshesNames === "string") {
  1648. gltfRuntime.importMeshesNames = [meshesNames];
  1649. }
  1650. else if (meshesNames && !(meshesNames instanceof Array)) {
  1651. gltfRuntime.importMeshesNames = [meshesNames];
  1652. }
  1653. else {
  1654. gltfRuntime.importMeshesNames = [];
  1655. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1656. }
  1657. // Create nodes
  1658. _this._createNodes(gltfRuntime);
  1659. var meshes = new Array();
  1660. var skeletons = new Array();
  1661. // Fill arrays of meshes and skeletons
  1662. for (var nde in gltfRuntime.nodes) {
  1663. var node = gltfRuntime.nodes[nde];
  1664. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1665. meshes.push(node.babylonNode);
  1666. }
  1667. }
  1668. for (var skl in gltfRuntime.skins) {
  1669. var skin = gltfRuntime.skins[skl];
  1670. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1671. skeletons.push(skin.babylonSkeleton);
  1672. }
  1673. }
  1674. // Load buffers, shaders, materials, etc.
  1675. _this._loadBuffersAsync(gltfRuntime, function () {
  1676. _this._loadShadersAsync(gltfRuntime, function () {
  1677. importMaterials(gltfRuntime);
  1678. postLoad(gltfRuntime);
  1679. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1680. onSuccess(meshes, [], skeletons);
  1681. }
  1682. });
  1683. }, onProgress);
  1684. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1685. onSuccess(meshes, [], skeletons);
  1686. }
  1687. }, onError);
  1688. return true;
  1689. };
  1690. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1691. var _this = this;
  1692. scene.useRightHandedSystem = true;
  1693. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1694. // Load runtime extensios
  1695. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1696. // Create nodes
  1697. _this._createNodes(gltfRuntime);
  1698. // Load buffers, shaders, materials, etc.
  1699. _this._loadBuffersAsync(gltfRuntime, function () {
  1700. _this._loadShadersAsync(gltfRuntime, function () {
  1701. importMaterials(gltfRuntime);
  1702. postLoad(gltfRuntime);
  1703. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1704. onSuccess();
  1705. }
  1706. });
  1707. });
  1708. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1709. onSuccess();
  1710. }
  1711. }, onError);
  1712. }, onError);
  1713. };
  1714. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1715. var hasShaders = false;
  1716. var processShader = function (sha, shader) {
  1717. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1718. gltfRuntime.loadedShaderCount++;
  1719. if (shaderString) {
  1720. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1721. }
  1722. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1723. onload();
  1724. }
  1725. }, function () {
  1726. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1727. });
  1728. };
  1729. for (var sha in gltfRuntime.shaders) {
  1730. hasShaders = true;
  1731. var shader = gltfRuntime.shaders[sha];
  1732. if (shader) {
  1733. processShader.bind(this, sha, shader)();
  1734. }
  1735. else {
  1736. BABYLON.Tools.Error("No shader named: " + sha);
  1737. }
  1738. }
  1739. if (!hasShaders) {
  1740. onload();
  1741. }
  1742. };
  1743. ;
  1744. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  1745. var hasBuffers = false;
  1746. var processBuffer = function (buf, buffer) {
  1747. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1748. gltfRuntime.loadedBufferCount++;
  1749. if (bufferView) {
  1750. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1751. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1752. }
  1753. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1754. }
  1755. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1756. onLoad();
  1757. }
  1758. }, function () {
  1759. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1760. });
  1761. };
  1762. for (var buf in gltfRuntime.buffers) {
  1763. hasBuffers = true;
  1764. var buffer = gltfRuntime.buffers[buf];
  1765. if (buffer) {
  1766. processBuffer.bind(this, buf, buffer)();
  1767. }
  1768. else {
  1769. BABYLON.Tools.Error("No buffer named: " + buf);
  1770. }
  1771. }
  1772. if (!hasBuffers) {
  1773. onLoad();
  1774. }
  1775. };
  1776. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  1777. var currentScene = gltfRuntime.currentScene;
  1778. if (currentScene) {
  1779. // Only one scene even if multiple scenes are defined
  1780. for (var i = 0; i < currentScene.nodes.length; i++) {
  1781. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1782. }
  1783. }
  1784. else {
  1785. // Load all scenes
  1786. for (var thing in gltfRuntime.scenes) {
  1787. currentScene = gltfRuntime.scenes[thing];
  1788. for (var i = 0; i < currentScene.nodes.length; i++) {
  1789. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1790. }
  1791. }
  1792. }
  1793. };
  1794. GLTFLoader.Extensions = {};
  1795. return GLTFLoader;
  1796. }());
  1797. GLTF1.GLTFLoader = GLTFLoader;
  1798. ;
  1799. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  1800. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  1801. })(BABYLON || (BABYLON = {}));
  1802. //# sourceMappingURL=babylon.glTFLoader.js.map
  1803. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1804. var BABYLON;
  1805. (function (BABYLON) {
  1806. var GLTF1;
  1807. (function (GLTF1) {
  1808. /**
  1809. * Utils functions for GLTF
  1810. */
  1811. var GLTFUtils = /** @class */ (function () {
  1812. function GLTFUtils() {
  1813. }
  1814. /**
  1815. * Sets the given "parameter" matrix
  1816. * @param scene: the {BABYLON.Scene} object
  1817. * @param source: the source node where to pick the matrix
  1818. * @param parameter: the GLTF technique parameter
  1819. * @param uniformName: the name of the shader's uniform
  1820. * @param shaderMaterial: the shader material
  1821. */
  1822. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  1823. var mat = null;
  1824. if (parameter.semantic === "MODEL") {
  1825. mat = source.getWorldMatrix();
  1826. }
  1827. else if (parameter.semantic === "PROJECTION") {
  1828. mat = scene.getProjectionMatrix();
  1829. }
  1830. else if (parameter.semantic === "VIEW") {
  1831. mat = scene.getViewMatrix();
  1832. }
  1833. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  1834. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  1835. }
  1836. else if (parameter.semantic === "MODELVIEW") {
  1837. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  1838. }
  1839. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  1840. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  1841. }
  1842. else if (parameter.semantic === "MODELINVERSE") {
  1843. mat = source.getWorldMatrix().invert();
  1844. }
  1845. else if (parameter.semantic === "VIEWINVERSE") {
  1846. mat = scene.getViewMatrix().invert();
  1847. }
  1848. else if (parameter.semantic === "PROJECTIONINVERSE") {
  1849. mat = scene.getProjectionMatrix().invert();
  1850. }
  1851. else if (parameter.semantic === "MODELVIEWINVERSE") {
  1852. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  1853. }
  1854. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  1855. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  1856. }
  1857. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  1858. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  1859. }
  1860. else {
  1861. debugger;
  1862. }
  1863. if (mat) {
  1864. switch (parameter.type) {
  1865. case GLTF1.EParameterType.FLOAT_MAT2:
  1866. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  1867. break;
  1868. case GLTF1.EParameterType.FLOAT_MAT3:
  1869. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  1870. break;
  1871. case GLTF1.EParameterType.FLOAT_MAT4:
  1872. shaderMaterial.setMatrix(uniformName, mat);
  1873. break;
  1874. default: break;
  1875. }
  1876. }
  1877. };
  1878. /**
  1879. * Sets the given "parameter" matrix
  1880. * @param shaderMaterial: the shader material
  1881. * @param uniform: the name of the shader's uniform
  1882. * @param value: the value of the uniform
  1883. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  1884. */
  1885. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  1886. switch (type) {
  1887. case GLTF1.EParameterType.FLOAT:
  1888. shaderMaterial.setFloat(uniform, value);
  1889. return true;
  1890. case GLTF1.EParameterType.FLOAT_VEC2:
  1891. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  1892. return true;
  1893. case GLTF1.EParameterType.FLOAT_VEC3:
  1894. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  1895. return true;
  1896. case GLTF1.EParameterType.FLOAT_VEC4:
  1897. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  1898. return true;
  1899. default: return false;
  1900. }
  1901. };
  1902. /**
  1903. * If the uri is a base64 string
  1904. * @param uri: the uri to test
  1905. */
  1906. GLTFUtils.IsBase64 = function (uri) {
  1907. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1908. };
  1909. /**
  1910. * Decode the base64 uri
  1911. * @param uri: the uri to decode
  1912. */
  1913. GLTFUtils.DecodeBase64 = function (uri) {
  1914. var decodedString = atob(uri.split(",")[1]);
  1915. var bufferLength = decodedString.length;
  1916. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1917. for (var i = 0; i < bufferLength; i++) {
  1918. bufferView[i] = decodedString.charCodeAt(i);
  1919. }
  1920. return bufferView.buffer;
  1921. };
  1922. /**
  1923. * Returns the wrap mode of the texture
  1924. * @param mode: the mode value
  1925. */
  1926. GLTFUtils.GetWrapMode = function (mode) {
  1927. switch (mode) {
  1928. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1929. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1930. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1931. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1932. }
  1933. };
  1934. /**
  1935. * Returns the byte stride giving an accessor
  1936. * @param accessor: the GLTF accessor objet
  1937. */
  1938. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1939. // Needs this function since "byteStride" isn't requiered in glTF format
  1940. var type = accessor.type;
  1941. switch (type) {
  1942. case "VEC2": return 2;
  1943. case "VEC3": return 3;
  1944. case "VEC4": return 4;
  1945. case "MAT2": return 4;
  1946. case "MAT3": return 9;
  1947. case "MAT4": return 16;
  1948. default: return 1;
  1949. }
  1950. };
  1951. /**
  1952. * Returns the texture filter mode giving a mode value
  1953. * @param mode: the filter mode value
  1954. */
  1955. GLTFUtils.GetTextureFilterMode = function (mode) {
  1956. switch (mode) {
  1957. case GLTF1.ETextureFilterType.LINEAR:
  1958. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  1959. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1960. case GLTF1.ETextureFilterType.NEAREST:
  1961. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1962. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1963. }
  1964. };
  1965. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  1966. var byteOffset = bufferView.byteOffset + byteOffset;
  1967. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  1968. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1969. throw new Error("Buffer access is out of range");
  1970. }
  1971. var buffer = loadedBufferView.buffer;
  1972. byteOffset += loadedBufferView.byteOffset;
  1973. switch (componentType) {
  1974. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1975. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1976. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1977. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1978. default: return new Float32Array(buffer, byteOffset, byteLength);
  1979. }
  1980. };
  1981. /**
  1982. * Returns a buffer from its accessor
  1983. * @param gltfRuntime: the GLTF runtime
  1984. * @param accessor: the GLTF accessor
  1985. */
  1986. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  1987. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  1988. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1989. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1990. };
  1991. /**
  1992. * Decodes a buffer view into a string
  1993. * @param view: the buffer view
  1994. */
  1995. GLTFUtils.DecodeBufferToText = function (view) {
  1996. var result = "";
  1997. var length = view.byteLength;
  1998. for (var i = 0; i < length; ++i) {
  1999. result += String.fromCharCode(view[i]);
  2000. }
  2001. return result;
  2002. };
  2003. /**
  2004. * Returns the default material of gltf. Related to
  2005. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2006. * @param scene: the Babylon.js scene
  2007. */
  2008. GLTFUtils.GetDefaultMaterial = function (scene) {
  2009. if (!GLTFUtils._DefaultMaterial) {
  2010. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2011. "precision highp float;",
  2012. "",
  2013. "uniform mat4 worldView;",
  2014. "uniform mat4 projection;",
  2015. "",
  2016. "attribute vec3 position;",
  2017. "",
  2018. "void main(void)",
  2019. "{",
  2020. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2021. "}"
  2022. ].join("\n");
  2023. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2024. "precision highp float;",
  2025. "",
  2026. "uniform vec4 u_emission;",
  2027. "",
  2028. "void main(void)",
  2029. "{",
  2030. " gl_FragColor = u_emission;",
  2031. "}"
  2032. ].join("\n");
  2033. var shaderPath = {
  2034. vertex: "GLTFDefaultMaterial",
  2035. fragment: "GLTFDefaultMaterial"
  2036. };
  2037. var options = {
  2038. attributes: ["position"],
  2039. uniforms: ["worldView", "projection", "u_emission"],
  2040. samplers: new Array(),
  2041. needAlphaBlending: false
  2042. };
  2043. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2044. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2045. }
  2046. return GLTFUtils._DefaultMaterial;
  2047. };
  2048. // The GLTF default material
  2049. GLTFUtils._DefaultMaterial = null;
  2050. return GLTFUtils;
  2051. }());
  2052. GLTF1.GLTFUtils = GLTFUtils;
  2053. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2054. })(BABYLON || (BABYLON = {}));
  2055. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2056. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2057. var BABYLON;
  2058. (function (BABYLON) {
  2059. var GLTF1;
  2060. (function (GLTF1) {
  2061. var GLTFLoaderExtension = /** @class */ (function () {
  2062. function GLTFLoaderExtension(name) {
  2063. this._name = name;
  2064. }
  2065. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2066. get: function () {
  2067. return this._name;
  2068. },
  2069. enumerable: true,
  2070. configurable: true
  2071. });
  2072. /**
  2073. * Defines an override for loading the runtime
  2074. * Return true to stop further extensions from loading the runtime
  2075. */
  2076. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2077. return false;
  2078. };
  2079. /**
  2080. * Defines an onverride for creating gltf runtime
  2081. * Return true to stop further extensions from creating the runtime
  2082. */
  2083. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2084. return false;
  2085. };
  2086. /**
  2087. * Defines an override for loading buffers
  2088. * Return true to stop further extensions from loading this buffer
  2089. */
  2090. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2091. return false;
  2092. };
  2093. /**
  2094. * Defines an override for loading texture buffers
  2095. * Return true to stop further extensions from loading this texture data
  2096. */
  2097. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2098. return false;
  2099. };
  2100. /**
  2101. * Defines an override for creating textures
  2102. * Return true to stop further extensions from loading this texture
  2103. */
  2104. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2105. return false;
  2106. };
  2107. /**
  2108. * Defines an override for loading shader strings
  2109. * Return true to stop further extensions from loading this shader data
  2110. */
  2111. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2112. return false;
  2113. };
  2114. /**
  2115. * Defines an override for loading materials
  2116. * Return true to stop further extensions from loading this material
  2117. */
  2118. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2119. return false;
  2120. };
  2121. // ---------
  2122. // Utilities
  2123. // ---------
  2124. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2125. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2126. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2127. }, function () {
  2128. setTimeout(function () {
  2129. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2130. });
  2131. });
  2132. };
  2133. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2134. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2135. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2136. }, function () {
  2137. setTimeout(function () {
  2138. onSuccess();
  2139. });
  2140. });
  2141. };
  2142. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2143. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2144. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2145. }, function () {
  2146. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2147. });
  2148. };
  2149. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2150. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  2151. };
  2152. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2153. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2154. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2155. }, function () {
  2156. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2157. });
  2158. };
  2159. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2160. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2161. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2162. }, function () {
  2163. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2164. });
  2165. };
  2166. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2167. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2168. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2169. }, function () {
  2170. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2171. });
  2172. };
  2173. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2174. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2175. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2176. }, function () {
  2177. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2178. });
  2179. };
  2180. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2181. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2182. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2183. if (func(loaderExtension)) {
  2184. return;
  2185. }
  2186. }
  2187. defaultFunc();
  2188. };
  2189. return GLTFLoaderExtension;
  2190. }());
  2191. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2192. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2193. })(BABYLON || (BABYLON = {}));
  2194. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2195. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2196. var __extends = (this && this.__extends) || (function () {
  2197. var extendStatics = Object.setPrototypeOf ||
  2198. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2199. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2200. return function (d, b) {
  2201. extendStatics(d, b);
  2202. function __() { this.constructor = d; }
  2203. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2204. };
  2205. })();
  2206. var BABYLON;
  2207. (function (BABYLON) {
  2208. var GLTF1;
  2209. (function (GLTF1) {
  2210. var BinaryExtensionBufferName = "binary_glTF";
  2211. ;
  2212. ;
  2213. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2214. __extends(GLTFBinaryExtension, _super);
  2215. function GLTFBinaryExtension() {
  2216. return _super.call(this, "KHR_binary_glTF") || this;
  2217. }
  2218. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2219. var extensionsUsed = data.json.extensionsUsed;
  2220. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2221. return false;
  2222. }
  2223. this._bin = data.bin;
  2224. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2225. return true;
  2226. };
  2227. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2228. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2229. return false;
  2230. }
  2231. if (id !== BinaryExtensionBufferName) {
  2232. return false;
  2233. }
  2234. onSuccess(this._bin);
  2235. return true;
  2236. };
  2237. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2238. var texture = gltfRuntime.textures[id];
  2239. var source = gltfRuntime.images[texture.source];
  2240. if (!source.extensions || !(this.name in source.extensions)) {
  2241. return false;
  2242. }
  2243. var sourceExt = source.extensions[this.name];
  2244. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2245. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2246. onSuccess(buffer);
  2247. return true;
  2248. };
  2249. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2250. var shader = gltfRuntime.shaders[id];
  2251. if (!shader.extensions || !(this.name in shader.extensions)) {
  2252. return false;
  2253. }
  2254. var binaryExtensionShader = shader.extensions[this.name];
  2255. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2256. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2257. setTimeout(function () {
  2258. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2259. onSuccess(shaderString);
  2260. });
  2261. return true;
  2262. };
  2263. return GLTFBinaryExtension;
  2264. }(GLTF1.GLTFLoaderExtension));
  2265. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2266. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2267. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2268. })(BABYLON || (BABYLON = {}));
  2269. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2270. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2271. var __extends = (this && this.__extends) || (function () {
  2272. var extendStatics = Object.setPrototypeOf ||
  2273. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2274. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2275. return function (d, b) {
  2276. extendStatics(d, b);
  2277. function __() { this.constructor = d; }
  2278. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2279. };
  2280. })();
  2281. var BABYLON;
  2282. (function (BABYLON) {
  2283. var GLTF1;
  2284. (function (GLTF1) {
  2285. ;
  2286. ;
  2287. ;
  2288. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2289. __extends(GLTFMaterialsCommonExtension, _super);
  2290. function GLTFMaterialsCommonExtension() {
  2291. return _super.call(this, "KHR_materials_common") || this;
  2292. }
  2293. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2294. if (!gltfRuntime.extensions)
  2295. return false;
  2296. var extension = gltfRuntime.extensions[this.name];
  2297. if (!extension)
  2298. return false;
  2299. // Create lights
  2300. var lights = extension.lights;
  2301. if (lights) {
  2302. for (var thing in lights) {
  2303. var light = lights[thing];
  2304. switch (light.type) {
  2305. case "ambient":
  2306. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2307. var ambient = light.ambient;
  2308. if (ambient) {
  2309. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2310. }
  2311. break;
  2312. case "point":
  2313. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2314. var point = light.point;
  2315. if (point) {
  2316. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2317. }
  2318. break;
  2319. case "directional":
  2320. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2321. var directional = light.directional;
  2322. if (directional) {
  2323. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2324. }
  2325. break;
  2326. case "spot":
  2327. var spot = light.spot;
  2328. if (spot) {
  2329. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2330. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2331. }
  2332. break;
  2333. default:
  2334. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2335. break;
  2336. }
  2337. }
  2338. }
  2339. return false;
  2340. };
  2341. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2342. var material = gltfRuntime.materials[id];
  2343. if (!material || !material.extensions)
  2344. return false;
  2345. var extension = material.extensions[this.name];
  2346. if (!extension)
  2347. return false;
  2348. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2349. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2350. if (extension.technique === "CONSTANT") {
  2351. standardMaterial.disableLighting = true;
  2352. }
  2353. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2354. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2355. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2356. // Ambient
  2357. if (typeof extension.values.ambient === "string") {
  2358. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2359. }
  2360. else {
  2361. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2362. }
  2363. // Diffuse
  2364. if (typeof extension.values.diffuse === "string") {
  2365. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2366. }
  2367. else {
  2368. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2369. }
  2370. // Emission
  2371. if (typeof extension.values.emission === "string") {
  2372. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2373. }
  2374. else {
  2375. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2376. }
  2377. // Specular
  2378. if (typeof extension.values.specular === "string") {
  2379. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2380. }
  2381. else {
  2382. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2383. }
  2384. return true;
  2385. };
  2386. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2387. // Create buffer from texture url
  2388. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2389. // Create texture from buffer
  2390. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2391. }, onError);
  2392. };
  2393. return GLTFMaterialsCommonExtension;
  2394. }(GLTF1.GLTFLoaderExtension));
  2395. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2396. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2397. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2398. })(BABYLON || (BABYLON = {}));
  2399. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map