babylon.glTF1FileLoader.js 135 KB

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