babylon.glTF1FileLoader.js 129 KB

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