babylon.glTF2FileLoader.js 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. /**
  5. * Coordinate system mode that will be used when loading from the gltf file
  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. * Animation mode that determines which animations should be started when a file is loaded
  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. * Loading 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. /** File loader to load gltf files into a babylon scene */
  55. var GLTFFileLoader = /** @class */ (function () {
  56. function GLTFFileLoader() {
  57. // #region Common options
  58. /**
  59. * Raised when the asset has been parsed.
  60. * The data.json property stores the glTF JSON.
  61. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  62. */
  63. this.onParsedObservable = new BABYLON.Observable();
  64. // #endregion
  65. // #region V2 options
  66. /**
  67. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED). Defaults to AUTO.
  68. * - AUTO - Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  69. * - FORCE_RIGHT_HANDED - Sets the useRightHandedSystem flag on the scene.
  70. */
  71. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  72. /**
  73. * The animation start mode (NONE, FIRST, ALL). Defaults to FIRST.
  74. * - NONE - No animation will start.
  75. * - FIRST - The first animation will start.
  76. * - ALL - All animations will start.
  77. */
  78. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  79. /**
  80. * Set to true to compile materials before raising the success callback. Defaults to false.
  81. */
  82. this.compileMaterials = false;
  83. /**
  84. * Set to true to also compile materials with clip planes. Defaults to false.
  85. */
  86. this.useClipPlane = false;
  87. /**
  88. * Set to true to compile shadow generators before raising the success callback. Defaults to false.
  89. */
  90. this.compileShadowGenerators = false;
  91. /**
  92. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  93. */
  94. this.onMeshLoadedObservable = new BABYLON.Observable();
  95. /**
  96. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  97. */
  98. this.onTextureLoadedObservable = new BABYLON.Observable();
  99. /**
  100. * Raised when the loader creates a material after parsing the glTF properties of the material.
  101. */
  102. this.onMaterialLoadedObservable = new BABYLON.Observable();
  103. /**
  104. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  105. * For assets with LODs, raised when all of the LODs are complete.
  106. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  107. */
  108. this.onCompleteObservable = new BABYLON.Observable();
  109. /**
  110. * Raised after the loader is disposed.
  111. */
  112. this.onDisposeObservable = new BABYLON.Observable();
  113. /**
  114. * Raised after a loader extension is created.
  115. * Set additional options for a loader extension in this event.
  116. */
  117. this.onExtensionLoadedObservable = new BABYLON.Observable();
  118. // #endregion
  119. this._loader = null;
  120. /**
  121. * Name of the loader ("gltf")
  122. */
  123. this.name = "gltf";
  124. /**
  125. * Supported file extensions of the loader (.gltf, .glb)
  126. */
  127. this.extensions = {
  128. ".gltf": { isBinary: false },
  129. ".glb": { isBinary: true }
  130. };
  131. }
  132. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  133. /** Raised when the asset has been parsed. */
  134. set: function (callback) {
  135. if (this._onParsedObserver) {
  136. this.onParsedObservable.remove(this._onParsedObserver);
  137. }
  138. this._onParsedObserver = this.onParsedObservable.add(callback);
  139. },
  140. enumerable: true,
  141. configurable: true
  142. });
  143. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  144. /**
  145. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh. (onMeshLoadedObservable is likely desired instead.)
  146. */
  147. set: function (callback) {
  148. if (this._onMeshLoadedObserver) {
  149. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  150. }
  151. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  152. },
  153. enumerable: true,
  154. configurable: true
  155. });
  156. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  157. /**
  158. * Method called when a texture has been loaded (onTextureLoadedObservable is likely desired instead.)
  159. */
  160. set: function (callback) {
  161. if (this._onTextureLoadedObserver) {
  162. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  163. }
  164. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  165. },
  166. enumerable: true,
  167. configurable: true
  168. });
  169. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  170. /**
  171. * Method when the loader creates a material after parsing the glTF properties of the material. (onMaterialLoadedObservable is likely desired instead.)
  172. */
  173. set: function (callback) {
  174. if (this._onMaterialLoadedObserver) {
  175. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  176. }
  177. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  178. },
  179. enumerable: true,
  180. configurable: true
  181. });
  182. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  183. /**
  184. * Raised when the asset is completely loaded, immediately before the loader is disposed. (onCompleteObservable is likely desired instead.)
  185. */
  186. set: function (callback) {
  187. if (this._onCompleteObserver) {
  188. this.onCompleteObservable.remove(this._onCompleteObserver);
  189. }
  190. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  191. },
  192. enumerable: true,
  193. configurable: true
  194. });
  195. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  196. /**
  197. * Raised after the loader is disposed. (onDisposeObservable is likely desired instead.)
  198. */
  199. set: function (callback) {
  200. if (this._onDisposeObserver) {
  201. this.onDisposeObservable.remove(this._onDisposeObserver);
  202. }
  203. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  204. },
  205. enumerable: true,
  206. configurable: true
  207. });
  208. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  209. /**
  210. * Raised after a loader extension is created. (onExtensionLoadedObservable is likely desired instead.)
  211. */
  212. set: function (callback) {
  213. if (this._onExtensionLoadedObserver) {
  214. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  215. }
  216. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  217. },
  218. enumerable: true,
  219. configurable: true
  220. });
  221. /**
  222. * Returns a promise that resolves when the asset is completely loaded.
  223. * @returns A promise that resolves when the asset is completely loaded.
  224. */
  225. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  226. var _this = this;
  227. return new Promise(function (resolve) {
  228. _this.onCompleteObservable.add(function () {
  229. resolve();
  230. }, undefined, undefined, undefined, true);
  231. });
  232. };
  233. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  234. /**
  235. * The loader state (LOADING, READY, COMPLETE) or null if the loader is not active.
  236. */
  237. get: function () {
  238. return this._loader ? this._loader.state : null;
  239. },
  240. enumerable: true,
  241. configurable: true
  242. });
  243. /**
  244. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  245. */
  246. GLTFFileLoader.prototype.dispose = function () {
  247. if (this._loader) {
  248. this._loader.dispose();
  249. this._loader = null;
  250. }
  251. this.onMeshLoadedObservable.clear();
  252. this.onTextureLoadedObservable.clear();
  253. this.onMaterialLoadedObservable.clear();
  254. this.onDisposeObservable.notifyObservers(this);
  255. this.onDisposeObservable.clear();
  256. };
  257. /**
  258. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  259. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  260. * @param scene the scene the meshes should be added to
  261. * @param data gltf data containing information of the meshes in a loaded file
  262. * @param rootUrl root url to load from
  263. * @param onProgress event that fires when loading progress has occured
  264. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  265. */
  266. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  267. var _this = this;
  268. return Promise.resolve().then(function () {
  269. var loaderData = _this._parse(data);
  270. _this._loader = _this._getLoader(loaderData);
  271. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  272. });
  273. };
  274. /**
  275. * Imports all objects from a loaded gltf file and adds them to the scene
  276. * @param scene the scene the objects should be added to
  277. * @param data gltf data containing information of the meshes in a loaded file
  278. * @param rootUrl root url to load from
  279. * @param onProgress event that fires when loading progress has occured
  280. * @returns a promise which completes when objects have been loaded to the scene
  281. */
  282. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  283. var _this = this;
  284. return Promise.resolve().then(function () {
  285. var loaderData = _this._parse(data);
  286. _this._loader = _this._getLoader(loaderData);
  287. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  288. });
  289. };
  290. /**
  291. * Load into an asset container.
  292. * @param scene The scene to load into
  293. * @param data The data to import
  294. * @param rootUrl The root url for scene and resources
  295. * @param onProgress The callback when the load progresses
  296. * @returns The loaded asset container
  297. */
  298. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  299. var _this = this;
  300. return Promise.resolve().then(function () {
  301. var loaderData = _this._parse(data);
  302. _this._loader = _this._getLoader(loaderData);
  303. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  304. var container = new BABYLON.AssetContainer(scene);
  305. Array.prototype.push.apply(container.meshes, result.meshes);
  306. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  307. Array.prototype.push.apply(container.skeletons, result.skeletons);
  308. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  309. container.removeAllFromScene();
  310. return container;
  311. });
  312. });
  313. };
  314. /**
  315. * If the data string can be loaded directly
  316. * @param data string contianing the file data
  317. * @returns if the data can be loaded directly
  318. */
  319. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  320. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  321. };
  322. /**
  323. * Instantiates a gltf file loader plugin
  324. * @returns the created plugin
  325. */
  326. GLTFFileLoader.prototype.createPlugin = function () {
  327. return new GLTFFileLoader();
  328. };
  329. GLTFFileLoader.prototype._parse = function (data) {
  330. var parsedData;
  331. if (data instanceof ArrayBuffer) {
  332. parsedData = GLTFFileLoader._parseBinary(data);
  333. }
  334. else {
  335. parsedData = {
  336. json: JSON.parse(data),
  337. bin: null
  338. };
  339. }
  340. this.onParsedObservable.notifyObservers(parsedData);
  341. this.onParsedObservable.clear();
  342. return parsedData;
  343. };
  344. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  345. var _this = this;
  346. var loaderVersion = { major: 2, minor: 0 };
  347. var asset = loaderData.json.asset || {};
  348. var version = GLTFFileLoader._parseVersion(asset.version);
  349. if (!version) {
  350. throw new Error("Invalid version: " + asset.version);
  351. }
  352. if (asset.minVersion !== undefined) {
  353. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  354. if (!minVersion) {
  355. throw new Error("Invalid minimum version: " + asset.minVersion);
  356. }
  357. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  358. throw new Error("Incompatible minimum version: " + asset.minVersion);
  359. }
  360. }
  361. var createLoaders = {
  362. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  363. 2: GLTFFileLoader.CreateGLTFLoaderV2
  364. };
  365. var createLoader = createLoaders[version.major];
  366. if (!createLoader) {
  367. throw new Error("Unsupported version: " + asset.version);
  368. }
  369. var loader = createLoader();
  370. loader.coordinateSystemMode = this.coordinateSystemMode;
  371. loader.animationStartMode = this.animationStartMode;
  372. loader.compileMaterials = this.compileMaterials;
  373. loader.useClipPlane = this.useClipPlane;
  374. loader.compileShadowGenerators = this.compileShadowGenerators;
  375. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  376. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  377. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  378. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  379. loader.onCompleteObservable.add(function () {
  380. _this.onMeshLoadedObservable.clear();
  381. _this.onTextureLoadedObservable.clear();
  382. _this.onMaterialLoadedObservable.clear();
  383. _this.onCompleteObservable.notifyObservers(_this);
  384. _this.onCompleteObservable.clear();
  385. });
  386. return loader;
  387. };
  388. GLTFFileLoader._parseBinary = function (data) {
  389. var Binary = {
  390. Magic: 0x46546C67
  391. };
  392. var binaryReader = new BinaryReader(data);
  393. var magic = binaryReader.readUint32();
  394. if (magic !== Binary.Magic) {
  395. throw new Error("Unexpected magic: " + magic);
  396. }
  397. var version = binaryReader.readUint32();
  398. switch (version) {
  399. case 1: return GLTFFileLoader._parseV1(binaryReader);
  400. case 2: return GLTFFileLoader._parseV2(binaryReader);
  401. }
  402. throw new Error("Unsupported version: " + version);
  403. };
  404. GLTFFileLoader._parseV1 = function (binaryReader) {
  405. var ContentFormat = {
  406. JSON: 0
  407. };
  408. var length = binaryReader.readUint32();
  409. if (length != binaryReader.getLength()) {
  410. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  411. }
  412. var contentLength = binaryReader.readUint32();
  413. var contentFormat = binaryReader.readUint32();
  414. var content;
  415. switch (contentFormat) {
  416. case ContentFormat.JSON: {
  417. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  418. break;
  419. }
  420. default: {
  421. throw new Error("Unexpected content format: " + contentFormat);
  422. }
  423. }
  424. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  425. var body = binaryReader.readUint8Array(bytesRemaining);
  426. return {
  427. json: content,
  428. bin: body
  429. };
  430. };
  431. GLTFFileLoader._parseV2 = function (binaryReader) {
  432. var ChunkFormat = {
  433. JSON: 0x4E4F534A,
  434. BIN: 0x004E4942
  435. };
  436. var length = binaryReader.readUint32();
  437. if (length !== binaryReader.getLength()) {
  438. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  439. }
  440. // JSON chunk
  441. var chunkLength = binaryReader.readUint32();
  442. var chunkFormat = binaryReader.readUint32();
  443. if (chunkFormat !== ChunkFormat.JSON) {
  444. throw new Error("First chunk format is not JSON");
  445. }
  446. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  447. // Look for BIN chunk
  448. var bin = null;
  449. while (binaryReader.getPosition() < binaryReader.getLength()) {
  450. var chunkLength_1 = binaryReader.readUint32();
  451. var chunkFormat_1 = binaryReader.readUint32();
  452. switch (chunkFormat_1) {
  453. case ChunkFormat.JSON: {
  454. throw new Error("Unexpected JSON chunk");
  455. }
  456. case ChunkFormat.BIN: {
  457. bin = binaryReader.readUint8Array(chunkLength_1);
  458. break;
  459. }
  460. default: {
  461. // ignore unrecognized chunkFormat
  462. binaryReader.skipBytes(chunkLength_1);
  463. break;
  464. }
  465. }
  466. }
  467. return {
  468. json: json,
  469. bin: bin
  470. };
  471. };
  472. GLTFFileLoader._parseVersion = function (version) {
  473. if (version === "1.0" || version === "1.0.1") {
  474. return {
  475. major: 1,
  476. minor: 0
  477. };
  478. }
  479. var match = (version + "").match(/^(\d+)\.(\d+)/);
  480. if (!match) {
  481. return null;
  482. }
  483. return {
  484. major: parseInt(match[1]),
  485. minor: parseInt(match[2])
  486. };
  487. };
  488. GLTFFileLoader._compareVersion = function (a, b) {
  489. if (a.major > b.major)
  490. return 1;
  491. if (a.major < b.major)
  492. return -1;
  493. if (a.minor > b.minor)
  494. return 1;
  495. if (a.minor < b.minor)
  496. return -1;
  497. return 0;
  498. };
  499. GLTFFileLoader._decodeBufferToText = function (buffer) {
  500. var result = "";
  501. var length = buffer.byteLength;
  502. for (var i = 0; i < length; i++) {
  503. result += String.fromCharCode(buffer[i]);
  504. }
  505. return result;
  506. };
  507. // #endregion
  508. // #region V1 options
  509. /**
  510. * 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. Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled. Defaults to true.
  511. */
  512. GLTFFileLoader.IncrementalLoading = true;
  513. /**
  514. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters. Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates
  515. */
  516. GLTFFileLoader.HomogeneousCoordinates = false;
  517. return GLTFFileLoader;
  518. }());
  519. BABYLON.GLTFFileLoader = GLTFFileLoader;
  520. var BinaryReader = /** @class */ (function () {
  521. function BinaryReader(arrayBuffer) {
  522. this._arrayBuffer = arrayBuffer;
  523. this._dataView = new DataView(arrayBuffer);
  524. this._byteOffset = 0;
  525. }
  526. BinaryReader.prototype.getPosition = function () {
  527. return this._byteOffset;
  528. };
  529. BinaryReader.prototype.getLength = function () {
  530. return this._arrayBuffer.byteLength;
  531. };
  532. BinaryReader.prototype.readUint32 = function () {
  533. var value = this._dataView.getUint32(this._byteOffset, true);
  534. this._byteOffset += 4;
  535. return value;
  536. };
  537. BinaryReader.prototype.readUint8Array = function (length) {
  538. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  539. this._byteOffset += length;
  540. return value;
  541. };
  542. BinaryReader.prototype.skipBytes = function (length) {
  543. this._byteOffset += length;
  544. };
  545. return BinaryReader;
  546. }());
  547. if (BABYLON.SceneLoader) {
  548. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  549. }
  550. })(BABYLON || (BABYLON = {}));
  551. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  552. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  553. var BABYLON;
  554. (function (BABYLON) {
  555. var GLTF2;
  556. (function (GLTF2) {
  557. /** Array item helper methods */
  558. var ArrayItem = /** @class */ (function () {
  559. function ArrayItem() {
  560. }
  561. /** Sets the index of each array element to its index in the array */
  562. ArrayItem.Assign = function (values) {
  563. if (values) {
  564. for (var index = 0; index < values.length; index++) {
  565. values[index]._index = index;
  566. }
  567. }
  568. };
  569. return ArrayItem;
  570. }());
  571. GLTF2.ArrayItem = ArrayItem;
  572. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  573. })(BABYLON || (BABYLON = {}));
  574. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  575. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  576. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  577. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  578. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  579. /**
  580. * Defines the GLTF2 module used to import/export GLTF 2.0 files
  581. */
  582. var BABYLON;
  583. (function (BABYLON) {
  584. var GLTF2;
  585. (function (GLTF2) {
  586. /**
  587. * Used to load from a GLTF2 file
  588. */
  589. var GLTFLoader = /** @class */ (function () {
  590. function GLTFLoader() {
  591. /**
  592. * @ignore
  593. */
  594. this._completePromises = new Array();
  595. this._disposed = false;
  596. this._state = null;
  597. this._extensions = {};
  598. this._defaultSampler = {};
  599. this._defaultBabylonMaterials = {};
  600. this._requests = new Array();
  601. /**
  602. * Coordinate system that will be used when loading from the gltf file
  603. */
  604. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  605. /**
  606. * Animation mode that determines which animations should be started when a file is loaded
  607. */
  608. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  609. /**
  610. * If the materials in the file should automatically be compiled
  611. */
  612. this.compileMaterials = false;
  613. /**
  614. * If a clip plane should be usede when loading meshes in the file
  615. */
  616. this.useClipPlane = false;
  617. /**
  618. * If shadow generators should automatically be compiled
  619. */
  620. this.compileShadowGenerators = false;
  621. /**
  622. * Observable that fires when the loader is disposed
  623. */
  624. this.onDisposeObservable = new BABYLON.Observable();
  625. /**
  626. * Observable that fires each time a mesh is loaded
  627. */
  628. this.onMeshLoadedObservable = new BABYLON.Observable();
  629. /**
  630. * Observable that fires each time a texture is loaded
  631. */
  632. this.onTextureLoadedObservable = new BABYLON.Observable();
  633. /**
  634. * Observable that fires each time a material is loaded
  635. */
  636. this.onMaterialLoadedObservable = new BABYLON.Observable();
  637. /**
  638. * Observable that fires each time an extension is loaded
  639. */
  640. this.onExtensionLoadedObservable = new BABYLON.Observable();
  641. /**
  642. * Observable that fires when the load has completed
  643. */
  644. this.onCompleteObservable = new BABYLON.Observable();
  645. }
  646. /**
  647. * @ignore, registers the loader
  648. * @param name name of the loader
  649. * @param factory function that converts a loader to a loader extension
  650. */
  651. GLTFLoader._Register = function (name, factory) {
  652. if (GLTFLoader._Factories[name]) {
  653. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  654. return;
  655. }
  656. GLTFLoader._Factories[name] = factory;
  657. // Keep the order of registration so that extensions registered first are called first.
  658. GLTFLoader._Names.push(name);
  659. };
  660. Object.defineProperty(GLTFLoader.prototype, "state", {
  661. /**
  662. * The current state of the loader
  663. */
  664. get: function () {
  665. return this._state;
  666. },
  667. enumerable: true,
  668. configurable: true
  669. });
  670. /**
  671. * Disposes of the loader
  672. */
  673. GLTFLoader.prototype.dispose = function () {
  674. if (this._disposed) {
  675. return;
  676. }
  677. this._disposed = true;
  678. this.onDisposeObservable.notifyObservers(this);
  679. this.onDisposeObservable.clear();
  680. this._clear();
  681. };
  682. /**
  683. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  684. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  685. * @param scene the scene the meshes should be added to
  686. * @param data gltf data containing information of the meshes in a loaded file
  687. * @param rootUrl root url to load from
  688. * @param onProgress event that fires when loading progress has occured
  689. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  690. */
  691. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  692. var _this = this;
  693. return Promise.resolve().then(function () {
  694. var nodes = null;
  695. if (meshesNames) {
  696. var nodeMap_1 = {};
  697. if (_this._gltf.nodes) {
  698. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  699. var node = _a[_i];
  700. if (node.name) {
  701. nodeMap_1[node.name] = node;
  702. }
  703. }
  704. }
  705. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  706. nodes = names.map(function (name) {
  707. var node = nodeMap_1[name];
  708. if (!node) {
  709. throw new Error("Failed to find node '" + name + "'");
  710. }
  711. return node;
  712. });
  713. }
  714. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  715. return {
  716. meshes: _this._getMeshes(),
  717. particleSystems: [],
  718. skeletons: _this._getSkeletons(),
  719. animationGroups: _this._getAnimationGroups()
  720. };
  721. });
  722. });
  723. };
  724. /**
  725. * Imports all objects from a loaded gltf file and adds them to the scene
  726. * @param scene the scene the objects should be added to
  727. * @param data gltf data containing information of the meshes in a loaded file
  728. * @param rootUrl root url to load from
  729. * @param onProgress event that fires when loading progress has occured
  730. * @returns a promise which completes when objects have been loaded to the scene
  731. */
  732. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  733. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  734. };
  735. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  736. var _this = this;
  737. return Promise.resolve().then(function () {
  738. _this._loadExtensions();
  739. _this._babylonScene = scene;
  740. _this._rootUrl = rootUrl;
  741. _this._progressCallback = onProgress;
  742. _this._state = BABYLON.GLTFLoaderState.LOADING;
  743. _this._loadData(data);
  744. _this._checkExtensions();
  745. var promises = new Array();
  746. if (nodes) {
  747. promises.push(_this._loadNodesAsync(nodes));
  748. }
  749. else {
  750. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  751. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  752. }
  753. if (_this.compileMaterials) {
  754. promises.push(_this._compileMaterialsAsync());
  755. }
  756. if (_this.compileShadowGenerators) {
  757. promises.push(_this._compileShadowGeneratorsAsync());
  758. }
  759. var resultPromise = Promise.all(promises).then(function () {
  760. _this._state = BABYLON.GLTFLoaderState.READY;
  761. _this._startAnimations();
  762. });
  763. resultPromise.then(function () {
  764. _this._rootBabylonMesh.setEnabled(true);
  765. BABYLON.Tools.SetImmediate(function () {
  766. if (!_this._disposed) {
  767. Promise.all(_this._completePromises).then(function () {
  768. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  769. _this.onCompleteObservable.notifyObservers(_this);
  770. _this.onCompleteObservable.clear();
  771. _this._clear();
  772. }).catch(function (error) {
  773. BABYLON.Tools.Error("glTF Loader: " + error.message);
  774. _this._clear();
  775. });
  776. }
  777. });
  778. });
  779. return resultPromise;
  780. }).catch(function (error) {
  781. BABYLON.Tools.Error("glTF Loader: " + error.message);
  782. _this._clear();
  783. throw error;
  784. });
  785. };
  786. GLTFLoader.prototype._loadExtensions = function () {
  787. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  788. var name_1 = _a[_i];
  789. var extension = GLTFLoader._Factories[name_1](this);
  790. this._extensions[name_1] = extension;
  791. this.onExtensionLoadedObservable.notifyObservers(extension);
  792. }
  793. this.onExtensionLoadedObservable.clear();
  794. };
  795. GLTFLoader.prototype._loadData = function (data) {
  796. this._gltf = data.json;
  797. this._setupData();
  798. if (data.bin) {
  799. var buffers = this._gltf.buffers;
  800. if (buffers && buffers[0] && !buffers[0].uri) {
  801. var binaryBuffer = buffers[0];
  802. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  803. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  804. }
  805. binaryBuffer._data = Promise.resolve(data.bin);
  806. }
  807. else {
  808. BABYLON.Tools.Warn("Unexpected BIN chunk");
  809. }
  810. }
  811. };
  812. GLTFLoader.prototype._setupData = function () {
  813. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  814. GLTF2.ArrayItem.Assign(this._gltf.animations);
  815. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  816. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  817. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  818. GLTF2.ArrayItem.Assign(this._gltf.images);
  819. GLTF2.ArrayItem.Assign(this._gltf.materials);
  820. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  821. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  822. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  823. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  824. GLTF2.ArrayItem.Assign(this._gltf.skins);
  825. GLTF2.ArrayItem.Assign(this._gltf.textures);
  826. if (this._gltf.nodes) {
  827. var nodeParents = {};
  828. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  829. var node = _a[_i];
  830. if (node.children) {
  831. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  832. var index = _c[_b];
  833. nodeParents[index] = node._index;
  834. }
  835. }
  836. }
  837. var rootNode = this._createRootNode();
  838. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  839. var node = _e[_d];
  840. var parentIndex = nodeParents[node._index];
  841. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  842. }
  843. }
  844. };
  845. GLTFLoader.prototype._checkExtensions = function () {
  846. if (this._gltf.extensionsRequired) {
  847. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  848. var name_2 = _a[_i];
  849. var extension = this._extensions[name_2];
  850. if (!extension || !extension.enabled) {
  851. throw new Error("Require extension " + name_2 + " is not available");
  852. }
  853. }
  854. }
  855. };
  856. GLTFLoader.prototype._createRootNode = function () {
  857. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  858. this._rootBabylonMesh.setEnabled(false);
  859. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  860. switch (this.coordinateSystemMode) {
  861. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  862. if (!this._babylonScene.useRightHandedSystem) {
  863. rootNode.rotation = [0, 1, 0, 0];
  864. rootNode.scale = [1, 1, -1];
  865. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  866. }
  867. break;
  868. }
  869. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  870. this._babylonScene.useRightHandedSystem = true;
  871. break;
  872. }
  873. default: {
  874. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  875. }
  876. }
  877. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  878. return rootNode;
  879. };
  880. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  881. var promises = new Array();
  882. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  883. var node = nodes_1[_i];
  884. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  885. }
  886. promises.push(this._loadAnimationsAsync());
  887. return Promise.all(promises).then(function () { });
  888. };
  889. /**
  890. * @ignore
  891. */
  892. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  893. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  894. if (promise) {
  895. return promise;
  896. }
  897. var promises = new Array();
  898. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  899. var index = _a[_i];
  900. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  901. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  902. }
  903. promises.push(this._loadAnimationsAsync());
  904. return Promise.all(promises).then(function () { });
  905. };
  906. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  907. if (node._primitiveBabylonMeshes) {
  908. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  909. var babylonMesh = _a[_i];
  910. callback(babylonMesh);
  911. }
  912. }
  913. else {
  914. callback(node._babylonMesh);
  915. }
  916. };
  917. GLTFLoader.prototype._getMeshes = function () {
  918. var meshes = new Array();
  919. // Root mesh is always first.
  920. meshes.push(this._rootBabylonMesh);
  921. var nodes = this._gltf.nodes;
  922. if (nodes) {
  923. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  924. var node = nodes_2[_i];
  925. if (node._babylonMesh) {
  926. meshes.push(node._babylonMesh);
  927. }
  928. if (node._primitiveBabylonMeshes) {
  929. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  930. var babylonMesh = _b[_a];
  931. meshes.push(babylonMesh);
  932. }
  933. }
  934. }
  935. }
  936. return meshes;
  937. };
  938. GLTFLoader.prototype._getSkeletons = function () {
  939. var skeletons = new Array();
  940. var skins = this._gltf.skins;
  941. if (skins) {
  942. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  943. var skin = skins_1[_i];
  944. if (skin._babylonSkeleton) {
  945. skeletons.push(skin._babylonSkeleton);
  946. }
  947. }
  948. }
  949. return skeletons;
  950. };
  951. GLTFLoader.prototype._getAnimationGroups = function () {
  952. var animationGroups = new Array();
  953. var animations = this._gltf.animations;
  954. if (animations) {
  955. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  956. var animation = animations_1[_i];
  957. if (animation._babylonAnimationGroup) {
  958. animationGroups.push(animation._babylonAnimationGroup);
  959. }
  960. }
  961. }
  962. return animationGroups;
  963. };
  964. GLTFLoader.prototype._startAnimations = function () {
  965. switch (this.animationStartMode) {
  966. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  967. // do nothing
  968. break;
  969. }
  970. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  971. var babylonAnimationGroups = this._getAnimationGroups();
  972. if (babylonAnimationGroups.length !== 0) {
  973. babylonAnimationGroups[0].start(true);
  974. }
  975. break;
  976. }
  977. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  978. var babylonAnimationGroups = this._getAnimationGroups();
  979. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  980. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  981. babylonAnimationGroup.start(true);
  982. }
  983. break;
  984. }
  985. default: {
  986. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  987. return;
  988. }
  989. }
  990. };
  991. /**
  992. * @ignore
  993. */
  994. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  995. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  996. if (promise) {
  997. return promise;
  998. }
  999. if (node._babylonMesh) {
  1000. throw new Error(context + ": Invalid recursive node hierarchy");
  1001. }
  1002. var promises = new Array();
  1003. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  1004. node._babylonMesh = babylonMesh;
  1005. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  1006. node._babylonAnimationTargets.push(babylonMesh);
  1007. GLTFLoader._LoadTransform(node, babylonMesh);
  1008. if (node.mesh != undefined) {
  1009. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  1010. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  1011. }
  1012. if (node.children) {
  1013. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  1014. var index = _a[_i];
  1015. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  1016. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  1017. }
  1018. }
  1019. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  1020. return Promise.all(promises).then(function () { });
  1021. };
  1022. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  1023. // TODO: instancing
  1024. var _this = this;
  1025. var promises = new Array();
  1026. var primitives = mesh.primitives;
  1027. if (!primitives || primitives.length === 0) {
  1028. throw new Error(context + ": Primitives are missing");
  1029. }
  1030. GLTF2.ArrayItem.Assign(primitives);
  1031. if (primitives.length === 1) {
  1032. var primitive = primitives[0];
  1033. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  1034. }
  1035. else {
  1036. node._primitiveBabylonMeshes = [];
  1037. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  1038. var primitive = primitives_1[_i];
  1039. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  1040. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  1041. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  1042. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  1043. }
  1044. }
  1045. if (node.skin != undefined) {
  1046. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  1047. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  1048. }
  1049. return Promise.all(promises).then(function () {
  1050. _this._forEachPrimitive(node, function (babylonMesh) {
  1051. babylonMesh._refreshBoundingInfo(true);
  1052. });
  1053. });
  1054. };
  1055. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  1056. var _this = this;
  1057. var promises = new Array();
  1058. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  1059. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  1060. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  1061. babylonGeometry.applyToMesh(babylonMesh);
  1062. });
  1063. }));
  1064. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  1065. if (primitive.material == undefined) {
  1066. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  1067. }
  1068. else {
  1069. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  1070. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  1071. babylonMesh.material = babylonMaterial;
  1072. }));
  1073. }
  1074. return Promise.all(promises).then(function () { });
  1075. };
  1076. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  1077. var _this = this;
  1078. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  1079. if (promise) {
  1080. return promise;
  1081. }
  1082. var attributes = primitive.attributes;
  1083. if (!attributes) {
  1084. throw new Error(context + ": Attributes are missing");
  1085. }
  1086. var promises = new Array();
  1087. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  1088. if (primitive.indices == undefined) {
  1089. babylonMesh.isUnIndexed = true;
  1090. }
  1091. else {
  1092. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  1093. promises.push(this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  1094. babylonGeometry.setIndices(data);
  1095. }));
  1096. }
  1097. var loadAttribute = function (attribute, kind, callback) {
  1098. if (attributes[attribute] == undefined) {
  1099. return;
  1100. }
  1101. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  1102. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  1103. babylonMesh._delayInfo.push(kind);
  1104. }
  1105. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  1106. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  1107. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  1108. }));
  1109. if (callback) {
  1110. callback(accessor);
  1111. }
  1112. };
  1113. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  1114. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  1115. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  1116. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  1117. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  1118. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  1119. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  1120. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  1121. if (accessor.type === "VEC4" /* VEC4 */) {
  1122. babylonMesh.hasVertexAlpha = true;
  1123. }
  1124. });
  1125. return Promise.all(promises).then(function () {
  1126. return babylonGeometry;
  1127. });
  1128. };
  1129. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  1130. if (!primitive.targets) {
  1131. return;
  1132. }
  1133. if (node._numMorphTargets == undefined) {
  1134. node._numMorphTargets = primitive.targets.length;
  1135. }
  1136. else if (primitive.targets.length !== node._numMorphTargets) {
  1137. throw new Error(context + ": Primitives do not have the same number of targets");
  1138. }
  1139. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  1140. for (var index = 0; index < primitive.targets.length; index++) {
  1141. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  1142. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  1143. // TODO: tell the target whether it has positions, normals, tangents
  1144. }
  1145. };
  1146. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  1147. if (!primitive.targets) {
  1148. return Promise.resolve();
  1149. }
  1150. var promises = new Array();
  1151. var morphTargetManager = babylonMesh.morphTargetManager;
  1152. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  1153. var babylonMorphTarget = morphTargetManager.getTarget(index);
  1154. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  1155. }
  1156. return Promise.all(promises).then(function () { });
  1157. };
  1158. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  1159. var _this = this;
  1160. var promises = new Array();
  1161. var loadAttribute = function (attribute, kind, setData) {
  1162. if (attributes[attribute] == undefined) {
  1163. return;
  1164. }
  1165. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  1166. if (!babylonVertexBuffer) {
  1167. return;
  1168. }
  1169. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  1170. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  1171. if (!(data instanceof Float32Array)) {
  1172. throw new Error(context + ": Morph target accessor must have float data");
  1173. }
  1174. setData(babylonVertexBuffer, data);
  1175. }));
  1176. };
  1177. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  1178. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1179. data[index] += value;
  1180. });
  1181. babylonMorphTarget.setPositions(data);
  1182. });
  1183. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  1184. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1185. data[index] += value;
  1186. });
  1187. babylonMorphTarget.setNormals(data);
  1188. });
  1189. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  1190. var dataIndex = 0;
  1191. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1192. // Tangent data for morph targets is stored as xyz delta.
  1193. // The vertexData.tangent is stored as xyzw.
  1194. // So we need to skip every fourth vertexData.tangent.
  1195. if (((index + 1) % 4) !== 0) {
  1196. data[dataIndex++] += value;
  1197. }
  1198. });
  1199. babylonMorphTarget.setTangents(data);
  1200. });
  1201. return Promise.all(promises).then(function () { });
  1202. };
  1203. GLTFLoader._LoadTransform = function (node, babylonNode) {
  1204. var position = BABYLON.Vector3.Zero();
  1205. var rotation = BABYLON.Quaternion.Identity();
  1206. var scaling = BABYLON.Vector3.One();
  1207. if (node.matrix) {
  1208. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  1209. matrix.decompose(scaling, rotation, position);
  1210. }
  1211. else {
  1212. if (node.translation)
  1213. position = BABYLON.Vector3.FromArray(node.translation);
  1214. if (node.rotation)
  1215. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  1216. if (node.scale)
  1217. scaling = BABYLON.Vector3.FromArray(node.scale);
  1218. }
  1219. babylonNode.position = position;
  1220. babylonNode.rotationQuaternion = rotation;
  1221. babylonNode.scaling = scaling;
  1222. };
  1223. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  1224. var _this = this;
  1225. var assignSkeleton = function () {
  1226. _this._forEachPrimitive(node, function (babylonMesh) {
  1227. babylonMesh.skeleton = skin._babylonSkeleton;
  1228. });
  1229. // Ignore the TRS of skinned nodes.
  1230. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1231. node._babylonMesh.parent = _this._rootBabylonMesh;
  1232. node._babylonMesh.position = BABYLON.Vector3.Zero();
  1233. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  1234. node._babylonMesh.scaling = BABYLON.Vector3.One();
  1235. };
  1236. if (skin._loaded) {
  1237. return skin._loaded.then(function () {
  1238. assignSkeleton();
  1239. });
  1240. }
  1241. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  1242. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  1243. var skeletonId = "skeleton" + skin._index;
  1244. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  1245. skin._babylonSkeleton = babylonSkeleton;
  1246. _this._loadBones(context, skin, inverseBindMatricesData);
  1247. assignSkeleton();
  1248. }));
  1249. };
  1250. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  1251. if (skin.inverseBindMatrices == undefined) {
  1252. return Promise.resolve(null);
  1253. }
  1254. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  1255. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  1256. return data;
  1257. });
  1258. };
  1259. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  1260. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  1261. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  1262. node._babylonAnimationTargets.push(babylonBone);
  1263. return babylonBone;
  1264. };
  1265. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  1266. var babylonBones = {};
  1267. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  1268. var index = _a[_i];
  1269. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  1270. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  1271. }
  1272. };
  1273. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  1274. var babylonBone = babylonBones[node._index];
  1275. if (babylonBone) {
  1276. return babylonBone;
  1277. }
  1278. var boneIndex = skin.joints.indexOf(node._index);
  1279. var baseMatrix = BABYLON.Matrix.Identity();
  1280. if (inverseBindMatricesData && boneIndex !== -1) {
  1281. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  1282. baseMatrix.invertToRef(baseMatrix);
  1283. }
  1284. var babylonParentBone = null;
  1285. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  1286. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  1287. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  1288. }
  1289. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  1290. babylonBones[node._index] = babylonBone;
  1291. return babylonBone;
  1292. };
  1293. GLTFLoader.prototype._getNodeMatrix = function (node) {
  1294. return node.matrix ?
  1295. BABYLON.Matrix.FromArray(node.matrix) :
  1296. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  1297. };
  1298. GLTFLoader.prototype._loadAnimationsAsync = function () {
  1299. var animations = this._gltf.animations;
  1300. if (!animations) {
  1301. return Promise.resolve();
  1302. }
  1303. var promises = new Array();
  1304. for (var index = 0; index < animations.length; index++) {
  1305. var animation = animations[index];
  1306. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  1307. }
  1308. return Promise.all(promises).then(function () { });
  1309. };
  1310. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  1311. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  1312. animation._babylonAnimationGroup = babylonAnimationGroup;
  1313. var promises = new Array();
  1314. GLTF2.ArrayItem.Assign(animation.channels);
  1315. GLTF2.ArrayItem.Assign(animation.samplers);
  1316. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  1317. var channel = _a[_i];
  1318. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  1319. }
  1320. return Promise.all(promises).then(function () {
  1321. babylonAnimationGroup.normalize();
  1322. });
  1323. };
  1324. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  1325. var _this = this;
  1326. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  1327. if (!targetNode._babylonMesh) {
  1328. return Promise.resolve();
  1329. }
  1330. // Ignore animations targeting TRS of skinned nodes.
  1331. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1332. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  1333. return Promise.resolve();
  1334. }
  1335. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  1336. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  1337. var targetPath;
  1338. var animationType;
  1339. switch (channel.target.path) {
  1340. case "translation" /* TRANSLATION */: {
  1341. targetPath = "position";
  1342. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1343. break;
  1344. }
  1345. case "rotation" /* ROTATION */: {
  1346. targetPath = "rotationQuaternion";
  1347. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1348. break;
  1349. }
  1350. case "scale" /* SCALE */: {
  1351. targetPath = "scaling";
  1352. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1353. break;
  1354. }
  1355. case "weights" /* WEIGHTS */: {
  1356. targetPath = "influence";
  1357. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  1358. break;
  1359. }
  1360. default: {
  1361. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  1362. }
  1363. }
  1364. var outputBufferOffset = 0;
  1365. var getNextOutputValue;
  1366. switch (targetPath) {
  1367. case "position": {
  1368. getNextOutputValue = function () {
  1369. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  1370. outputBufferOffset += 3;
  1371. return value;
  1372. };
  1373. break;
  1374. }
  1375. case "rotationQuaternion": {
  1376. getNextOutputValue = function () {
  1377. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  1378. outputBufferOffset += 4;
  1379. return value;
  1380. };
  1381. break;
  1382. }
  1383. case "scaling": {
  1384. getNextOutputValue = function () {
  1385. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  1386. outputBufferOffset += 3;
  1387. return value;
  1388. };
  1389. break;
  1390. }
  1391. case "influence": {
  1392. getNextOutputValue = function () {
  1393. var value = new Array(targetNode._numMorphTargets);
  1394. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  1395. value[i] = data.output[outputBufferOffset++];
  1396. }
  1397. return value;
  1398. };
  1399. break;
  1400. }
  1401. }
  1402. var getNextKey;
  1403. switch (data.interpolation) {
  1404. case "STEP" /* STEP */: {
  1405. getNextKey = function (frameIndex) { return ({
  1406. frame: data.input[frameIndex],
  1407. value: getNextOutputValue(),
  1408. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  1409. }); };
  1410. break;
  1411. }
  1412. case "LINEAR" /* LINEAR */: {
  1413. getNextKey = function (frameIndex) { return ({
  1414. frame: data.input[frameIndex],
  1415. value: getNextOutputValue()
  1416. }); };
  1417. break;
  1418. }
  1419. case "CUBICSPLINE" /* CUBICSPLINE */: {
  1420. getNextKey = function (frameIndex) { return ({
  1421. frame: data.input[frameIndex],
  1422. inTangent: getNextOutputValue(),
  1423. value: getNextOutputValue(),
  1424. outTangent: getNextOutputValue()
  1425. }); };
  1426. break;
  1427. }
  1428. }
  1429. var keys = new Array(data.input.length);
  1430. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  1431. keys[frameIndex] = getNextKey(frameIndex);
  1432. }
  1433. if (targetPath === "influence") {
  1434. var _loop_1 = function (targetIndex) {
  1435. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  1436. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1437. babylonAnimation.setKeys(keys.map(function (key) { return ({
  1438. frame: key.frame,
  1439. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1440. value: key.value[targetIndex],
  1441. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1442. }); }));
  1443. var morphTargets = new Array();
  1444. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  1445. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  1446. morphTarget.animations.push(babylonAnimation);
  1447. morphTargets.push(morphTarget);
  1448. });
  1449. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTargets);
  1450. };
  1451. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  1452. _loop_1(targetIndex);
  1453. }
  1454. }
  1455. else {
  1456. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  1457. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1458. babylonAnimation.setKeys(keys);
  1459. if (targetNode._babylonAnimationTargets) {
  1460. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  1461. var babylonAnimationTarget = _a[_i];
  1462. babylonAnimationTarget.animations.push(babylonAnimation);
  1463. }
  1464. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonAnimationTargets);
  1465. }
  1466. }
  1467. });
  1468. };
  1469. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  1470. if (sampler._data) {
  1471. return sampler._data;
  1472. }
  1473. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  1474. switch (interpolation) {
  1475. case "STEP" /* STEP */:
  1476. case "LINEAR" /* LINEAR */:
  1477. case "CUBICSPLINE" /* CUBICSPLINE */: {
  1478. break;
  1479. }
  1480. default: {
  1481. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  1482. }
  1483. }
  1484. var inputData;
  1485. var outputData;
  1486. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  1487. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  1488. sampler._data = Promise.all([
  1489. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  1490. inputData = data;
  1491. }),
  1492. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  1493. outputData = data;
  1494. })
  1495. ]).then(function () {
  1496. return {
  1497. input: inputData,
  1498. interpolation: interpolation,
  1499. output: outputData,
  1500. };
  1501. });
  1502. return sampler._data;
  1503. };
  1504. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  1505. if (buffer._data) {
  1506. return buffer._data;
  1507. }
  1508. if (!buffer.uri) {
  1509. throw new Error(context + ": Uri is missing");
  1510. }
  1511. buffer._data = this._loadUriAsync(context, buffer.uri);
  1512. return buffer._data;
  1513. };
  1514. /**
  1515. * @ignore
  1516. */
  1517. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  1518. if (bufferView._data) {
  1519. return bufferView._data;
  1520. }
  1521. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  1522. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  1523. try {
  1524. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1525. }
  1526. catch (e) {
  1527. throw new Error(context + ": " + e.message);
  1528. }
  1529. });
  1530. return bufferView._data;
  1531. };
  1532. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  1533. if (accessor.sparse) {
  1534. throw new Error(context + ": Sparse accessors are not currently supported");
  1535. }
  1536. if (accessor._data) {
  1537. return accessor._data;
  1538. }
  1539. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  1540. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  1541. var buffer = data.buffer;
  1542. var byteOffset = data.byteOffset + (accessor.byteOffset || 0);
  1543. var length = GLTFLoader._GetNumComponents(context, accessor.type) * accessor.count;
  1544. try {
  1545. switch (accessor.componentType) {
  1546. case 5120 /* BYTE */: {
  1547. return new Int8Array(buffer, byteOffset, length);
  1548. }
  1549. case 5121 /* UNSIGNED_BYTE */: {
  1550. return new Uint8Array(buffer, byteOffset, length);
  1551. }
  1552. case 5122 /* SHORT */: {
  1553. return new Int16Array(buffer, byteOffset, length);
  1554. }
  1555. case 5123 /* UNSIGNED_SHORT */: {
  1556. return new Uint16Array(buffer, byteOffset, length);
  1557. }
  1558. case 5125 /* UNSIGNED_INT */: {
  1559. return new Uint32Array(buffer, byteOffset, length);
  1560. }
  1561. case 5126 /* FLOAT */: {
  1562. return new Float32Array(buffer, byteOffset, length);
  1563. }
  1564. default: {
  1565. throw new Error(context + ": Invalid accessor component type " + accessor.componentType);
  1566. }
  1567. }
  1568. }
  1569. catch (e) {
  1570. throw new Error(context + ": " + e);
  1571. }
  1572. });
  1573. return accessor._data;
  1574. };
  1575. /**
  1576. * @ignore
  1577. */
  1578. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  1579. var _this = this;
  1580. if (bufferView._babylonBuffer) {
  1581. return bufferView._babylonBuffer;
  1582. }
  1583. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  1584. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  1585. });
  1586. return bufferView._babylonBuffer;
  1587. };
  1588. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  1589. var _this = this;
  1590. if (accessor.sparse) {
  1591. throw new Error(context + ": Sparse accessors are not currently supported");
  1592. }
  1593. if (accessor._babylonVertexBuffer) {
  1594. return accessor._babylonVertexBuffer;
  1595. }
  1596. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  1597. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView, kind).then(function (buffer) {
  1598. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  1599. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  1600. });
  1601. return accessor._babylonVertexBuffer;
  1602. };
  1603. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  1604. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  1605. if (!babylonMaterial) {
  1606. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  1607. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  1608. babylonMaterial.metallic = 1;
  1609. babylonMaterial.roughness = 1;
  1610. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1611. }
  1612. return babylonMaterial;
  1613. };
  1614. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  1615. var promises = new Array();
  1616. // Ensure metallic workflow
  1617. babylonMaterial.metallic = 1;
  1618. babylonMaterial.roughness = 1;
  1619. var properties = material.pbrMetallicRoughness;
  1620. if (properties) {
  1621. if (properties.baseColorFactor) {
  1622. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  1623. babylonMaterial.alpha = properties.baseColorFactor[3];
  1624. }
  1625. else {
  1626. babylonMaterial.albedoColor = BABYLON.Color3.White();
  1627. }
  1628. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  1629. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  1630. if (properties.baseColorTexture) {
  1631. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  1632. babylonMaterial.albedoTexture = texture;
  1633. }));
  1634. }
  1635. if (properties.metallicRoughnessTexture) {
  1636. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  1637. babylonMaterial.metallicTexture = texture;
  1638. }));
  1639. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1640. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1641. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1642. }
  1643. }
  1644. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  1645. return Promise.all(promises).then(function () { });
  1646. };
  1647. /**
  1648. * @ignore
  1649. */
  1650. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  1651. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  1652. if (promise) {
  1653. return promise;
  1654. }
  1655. material._babylonData = material._babylonData || {};
  1656. var babylonData = material._babylonData[babylonDrawMode];
  1657. if (!babylonData) {
  1658. var promises = new Array();
  1659. var name_3 = material.name || "materialSG_" + material._index;
  1660. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  1661. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  1662. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  1663. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1664. babylonData = {
  1665. material: babylonMaterial,
  1666. meshes: [],
  1667. loaded: Promise.all(promises).then(function () { })
  1668. };
  1669. material._babylonData[babylonDrawMode] = babylonData;
  1670. }
  1671. babylonData.meshes.push(babylonMesh);
  1672. assign(babylonData.material);
  1673. return babylonData.loaded;
  1674. };
  1675. /**
  1676. * @ignore
  1677. */
  1678. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  1679. var babylonMaterial = new type(name, this._babylonScene);
  1680. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  1681. babylonMaterial.fillMode = drawMode;
  1682. return babylonMaterial;
  1683. };
  1684. /**
  1685. * @ignore
  1686. */
  1687. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  1688. var promises = new Array();
  1689. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1690. if (material.doubleSided) {
  1691. babylonMaterial.backFaceCulling = false;
  1692. babylonMaterial.twoSidedLighting = true;
  1693. }
  1694. if (material.normalTexture) {
  1695. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  1696. babylonMaterial.bumpTexture = texture;
  1697. }));
  1698. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1699. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1700. if (material.normalTexture.scale != undefined) {
  1701. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1702. }
  1703. }
  1704. if (material.occlusionTexture) {
  1705. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  1706. babylonMaterial.ambientTexture = texture;
  1707. }));
  1708. babylonMaterial.useAmbientInGrayScale = true;
  1709. if (material.occlusionTexture.strength != undefined) {
  1710. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1711. }
  1712. }
  1713. if (material.emissiveTexture) {
  1714. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  1715. babylonMaterial.emissiveTexture = texture;
  1716. }));
  1717. }
  1718. return Promise.all(promises).then(function () { });
  1719. };
  1720. /**
  1721. * @ignore
  1722. */
  1723. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  1724. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  1725. switch (alphaMode) {
  1726. case "OPAQUE" /* OPAQUE */: {
  1727. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  1728. break;
  1729. }
  1730. case "MASK" /* MASK */: {
  1731. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  1732. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  1733. if (babylonMaterial.albedoTexture) {
  1734. babylonMaterial.albedoTexture.hasAlpha = true;
  1735. }
  1736. break;
  1737. }
  1738. case "BLEND" /* BLEND */: {
  1739. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  1740. if (babylonMaterial.albedoTexture) {
  1741. babylonMaterial.albedoTexture.hasAlpha = true;
  1742. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1743. }
  1744. break;
  1745. }
  1746. default: {
  1747. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  1748. }
  1749. }
  1750. };
  1751. /**
  1752. * @ignore
  1753. */
  1754. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  1755. var _this = this;
  1756. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  1757. context = "#/textures/" + textureInfo.index;
  1758. var promises = new Array();
  1759. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  1760. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  1761. var deferred = new BABYLON.Deferred();
  1762. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  1763. if (!_this._disposed) {
  1764. deferred.resolve();
  1765. }
  1766. }, function (message, exception) {
  1767. if (!_this._disposed) {
  1768. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  1769. }
  1770. });
  1771. promises.push(deferred.promise);
  1772. babylonTexture.name = texture.name || "texture" + texture._index;
  1773. babylonTexture.wrapU = samplerData.wrapU;
  1774. babylonTexture.wrapV = samplerData.wrapV;
  1775. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  1776. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  1777. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  1778. babylonTexture.updateURL(objectURL);
  1779. }));
  1780. assign(babylonTexture);
  1781. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  1782. return Promise.all(promises).then(function () { });
  1783. };
  1784. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  1785. if (!sampler._data) {
  1786. sampler._data = {
  1787. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  1788. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  1789. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  1790. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  1791. };
  1792. }
  1793. ;
  1794. return sampler._data;
  1795. };
  1796. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  1797. if (image._objectURL) {
  1798. return image._objectURL;
  1799. }
  1800. var promise;
  1801. if (image.uri) {
  1802. promise = this._loadUriAsync(context, image.uri);
  1803. }
  1804. else {
  1805. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  1806. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  1807. }
  1808. image._objectURL = promise.then(function (data) {
  1809. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  1810. });
  1811. return image._objectURL;
  1812. };
  1813. /**
  1814. * @ignore
  1815. */
  1816. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  1817. var _this = this;
  1818. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  1819. if (promise) {
  1820. return promise;
  1821. }
  1822. if (!GLTFLoader._ValidateUri(uri)) {
  1823. throw new Error(context + ": Uri '" + uri + "' is invalid");
  1824. }
  1825. if (BABYLON.Tools.IsBase64(uri)) {
  1826. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  1827. }
  1828. return new Promise(function (resolve, reject) {
  1829. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  1830. if (!_this._disposed) {
  1831. resolve(new Uint8Array(data));
  1832. }
  1833. }, function (event) {
  1834. if (!_this._disposed) {
  1835. try {
  1836. if (request && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  1837. request._lengthComputable = event.lengthComputable;
  1838. request._loaded = event.loaded;
  1839. request._total = event.total;
  1840. _this._onProgress();
  1841. }
  1842. }
  1843. catch (e) {
  1844. reject(e);
  1845. }
  1846. }
  1847. }, _this._babylonScene.database, true, function (request, exception) {
  1848. if (!_this._disposed) {
  1849. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  1850. }
  1851. });
  1852. _this._requests.push(request);
  1853. });
  1854. };
  1855. GLTFLoader.prototype._onProgress = function () {
  1856. if (!this._progressCallback) {
  1857. return;
  1858. }
  1859. var lengthComputable = true;
  1860. var loaded = 0;
  1861. var total = 0;
  1862. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  1863. var request = _a[_i];
  1864. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  1865. return;
  1866. }
  1867. lengthComputable = lengthComputable && request._lengthComputable;
  1868. loaded += request._loaded;
  1869. total += request._total;
  1870. }
  1871. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  1872. };
  1873. /**
  1874. * @ignore
  1875. */
  1876. GLTFLoader._GetProperty = function (context, array, index) {
  1877. if (!array || index == undefined || !array[index]) {
  1878. throw new Error(context + ": Failed to find index (" + index + ")");
  1879. }
  1880. return array[index];
  1881. };
  1882. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  1883. // Set defaults if undefined
  1884. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  1885. switch (mode) {
  1886. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1887. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1888. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1889. default:
  1890. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  1891. return BABYLON.Texture.WRAP_ADDRESSMODE;
  1892. }
  1893. };
  1894. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  1895. // Set defaults if undefined
  1896. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  1897. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  1898. if (magFilter === 9729 /* LINEAR */) {
  1899. switch (minFilter) {
  1900. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  1901. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  1902. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  1903. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  1904. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  1905. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1906. default:
  1907. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  1908. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1909. }
  1910. }
  1911. else {
  1912. if (magFilter !== 9728 /* NEAREST */) {
  1913. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  1914. }
  1915. switch (minFilter) {
  1916. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  1917. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  1918. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1919. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  1920. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  1921. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  1922. default:
  1923. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  1924. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1925. }
  1926. }
  1927. };
  1928. GLTFLoader._GetNumComponents = function (context, type) {
  1929. switch (type) {
  1930. case "SCALAR": return 1;
  1931. case "VEC2": return 2;
  1932. case "VEC3": return 3;
  1933. case "VEC4": return 4;
  1934. case "MAT2": return 4;
  1935. case "MAT3": return 9;
  1936. case "MAT4": return 16;
  1937. }
  1938. throw new Error(context + ": Invalid type (" + type + ")");
  1939. };
  1940. GLTFLoader._ValidateUri = function (uri) {
  1941. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  1942. };
  1943. GLTFLoader._GetDrawMode = function (context, mode) {
  1944. if (mode == undefined) {
  1945. mode = 4 /* TRIANGLES */;
  1946. }
  1947. switch (mode) {
  1948. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  1949. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  1950. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  1951. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  1952. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  1953. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  1954. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  1955. }
  1956. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  1957. };
  1958. GLTFLoader.prototype._compileMaterialsAsync = function () {
  1959. var promises = new Array();
  1960. if (this._gltf.materials) {
  1961. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  1962. var material = _a[_i];
  1963. if (material._babylonData) {
  1964. for (var babylonDrawMode in material._babylonData) {
  1965. var babylonData = material._babylonData[babylonDrawMode];
  1966. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  1967. var babylonMesh = _c[_b];
  1968. // Ensure nonUniformScaling is set if necessary.
  1969. babylonMesh.computeWorldMatrix(true);
  1970. var babylonMaterial = babylonData.material;
  1971. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  1972. if (this.useClipPlane) {
  1973. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  1974. }
  1975. }
  1976. }
  1977. }
  1978. }
  1979. }
  1980. return Promise.all(promises).then(function () { });
  1981. };
  1982. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  1983. var promises = new Array();
  1984. var lights = this._babylonScene.lights;
  1985. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  1986. var light = lights_1[_i];
  1987. var generator = light.getShadowGenerator();
  1988. if (generator) {
  1989. promises.push(generator.forceCompilationAsync());
  1990. }
  1991. }
  1992. return Promise.all(promises).then(function () { });
  1993. };
  1994. GLTFLoader.prototype._clear = function () {
  1995. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  1996. var request = _a[_i];
  1997. request.abort();
  1998. }
  1999. this._requests.length = 0;
  2000. if (this._gltf && this._gltf.images) {
  2001. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  2002. var image = _c[_b];
  2003. if (image._objectURL) {
  2004. image._objectURL.then(function (value) {
  2005. URL.revokeObjectURL(value);
  2006. });
  2007. image._objectURL = undefined;
  2008. }
  2009. }
  2010. }
  2011. delete this._gltf;
  2012. delete this._babylonScene;
  2013. this._completePromises.length = 0;
  2014. for (var name_4 in this._extensions) {
  2015. this._extensions[name_4].dispose();
  2016. }
  2017. this._extensions = {};
  2018. delete this._rootBabylonMesh;
  2019. delete this._progressCallback;
  2020. this.onMeshLoadedObservable.clear();
  2021. this.onTextureLoadedObservable.clear();
  2022. this.onMaterialLoadedObservable.clear();
  2023. };
  2024. /**
  2025. * @ignore
  2026. */
  2027. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  2028. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  2029. var name_5 = _a[_i];
  2030. var extension = this._extensions[name_5];
  2031. if (extension.enabled) {
  2032. var promise = actionAsync(extension);
  2033. if (promise) {
  2034. return promise;
  2035. }
  2036. }
  2037. }
  2038. return null;
  2039. };
  2040. GLTFLoader._Names = new Array();
  2041. GLTFLoader._Factories = {};
  2042. return GLTFLoader;
  2043. }());
  2044. GLTF2.GLTFLoader = GLTFLoader;
  2045. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  2046. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2047. })(BABYLON || (BABYLON = {}));
  2048. //# sourceMappingURL=babylon.glTFLoader.js.map
  2049. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2050. var BABYLON;
  2051. (function (BABYLON) {
  2052. var GLTF2;
  2053. (function (GLTF2) {
  2054. /**
  2055. * Abstract class that can be implemented to extend existing gltf loader behavior.
  2056. */
  2057. var GLTFLoaderExtension = /** @class */ (function () {
  2058. function GLTFLoaderExtension(loader) {
  2059. this.enabled = true;
  2060. this._loader = loader;
  2061. }
  2062. GLTFLoaderExtension.prototype.dispose = function () {
  2063. delete this._loader;
  2064. };
  2065. // #region Overridable Methods
  2066. /** Override this method to modify the default behavior for loading scenes. */
  2067. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  2068. /** Override this method to modify the default behavior for loading nodes. */
  2069. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  2070. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  2071. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  2072. /** Override this method to modify the default behavior for loading materials. */
  2073. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  2074. /** Override this method to modify the default behavior for loading uris. */
  2075. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  2076. // #endregion
  2077. /** Helper method called by a loader extension to load an glTF extension. */
  2078. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  2079. if (!property.extensions) {
  2080. return null;
  2081. }
  2082. var extensions = property.extensions;
  2083. var extension = extensions[this.name];
  2084. if (!extension) {
  2085. return null;
  2086. }
  2087. // Clear out the extension before executing the action to avoid recursing into the same property.
  2088. delete extensions[this.name];
  2089. try {
  2090. return actionAsync(context + "/extensions/" + this.name, extension);
  2091. }
  2092. finally {
  2093. // Restore the extension after executing the action.
  2094. extensions[this.name] = extension;
  2095. }
  2096. };
  2097. /** Helper method called by the loader to allow extensions to override loading scenes. */
  2098. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  2099. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  2100. };
  2101. /** Helper method called by the loader to allow extensions to override loading nodes. */
  2102. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  2103. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  2104. };
  2105. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  2106. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  2107. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  2108. };
  2109. /** Helper method called by the loader to allow extensions to override loading materials. */
  2110. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  2111. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  2112. };
  2113. /** Helper method called by the loader to allow extensions to override loading uris. */
  2114. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  2115. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  2116. };
  2117. return GLTFLoaderExtension;
  2118. }());
  2119. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  2120. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2121. })(BABYLON || (BABYLON = {}));
  2122. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2123. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2124. var __extends = (this && this.__extends) || (function () {
  2125. var extendStatics = Object.setPrototypeOf ||
  2126. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2127. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2128. return function (d, b) {
  2129. extendStatics(d, b);
  2130. function __() { this.constructor = d; }
  2131. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2132. };
  2133. })();
  2134. var BABYLON;
  2135. (function (BABYLON) {
  2136. var GLTF2;
  2137. (function (GLTF2) {
  2138. var Extensions;
  2139. (function (Extensions) {
  2140. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod
  2141. var NAME = "MSFT_lod";
  2142. var MSFT_lod = /** @class */ (function (_super) {
  2143. __extends(MSFT_lod, _super);
  2144. function MSFT_lod() {
  2145. var _this = _super !== null && _super.apply(this, arguments) || this;
  2146. _this.name = NAME;
  2147. /**
  2148. * Maximum number of LODs to load, starting from the lowest LOD.
  2149. */
  2150. _this.maxLODsToLoad = Number.MAX_VALUE;
  2151. _this._loadingNodeLOD = null;
  2152. _this._loadNodeSignals = {};
  2153. _this._loadingMaterialLOD = null;
  2154. _this._loadMaterialSignals = {};
  2155. return _this;
  2156. }
  2157. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  2158. var _this = this;
  2159. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  2160. var firstPromise;
  2161. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  2162. var _loop_1 = function (indexLOD) {
  2163. var nodeLOD = nodeLODs[indexLOD];
  2164. if (indexLOD !== 0) {
  2165. _this._loadingNodeLOD = nodeLOD;
  2166. if (!_this._loadNodeSignals[nodeLOD._index]) {
  2167. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  2168. }
  2169. }
  2170. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  2171. if (indexLOD !== 0) {
  2172. var previousNodeLOD = nodeLODs[indexLOD - 1];
  2173. if (previousNodeLOD._babylonMesh) {
  2174. previousNodeLOD._babylonMesh.dispose(false, true);
  2175. delete previousNodeLOD._babylonMesh;
  2176. }
  2177. }
  2178. if (indexLOD !== nodeLODs.length - 1) {
  2179. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  2180. if (_this._loadNodeSignals[nodeIndex]) {
  2181. _this._loadNodeSignals[nodeIndex].resolve();
  2182. delete _this._loadNodeSignals[nodeIndex];
  2183. }
  2184. }
  2185. });
  2186. if (indexLOD === 0) {
  2187. firstPromise = promise;
  2188. }
  2189. else {
  2190. _this._loader._completePromises.push(promise);
  2191. _this._loadingNodeLOD = null;
  2192. }
  2193. };
  2194. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  2195. _loop_1(indexLOD);
  2196. }
  2197. return firstPromise;
  2198. });
  2199. };
  2200. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2201. var _this = this;
  2202. // Don't load material LODs if already loading a node LOD.
  2203. if (this._loadingNodeLOD) {
  2204. return null;
  2205. }
  2206. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  2207. var firstPromise;
  2208. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  2209. var _loop_2 = function (indexLOD) {
  2210. var materialLOD = materialLODs[indexLOD];
  2211. if (indexLOD !== 0) {
  2212. _this._loadingMaterialLOD = materialLOD;
  2213. if (!_this._loadMaterialSignals[materialLOD._index]) {
  2214. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  2215. }
  2216. }
  2217. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  2218. if (indexLOD !== 0) {
  2219. var babylonDataLOD = materialLOD._babylonData;
  2220. assign(babylonDataLOD[babylonDrawMode].material);
  2221. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  2222. if (previousBabylonDataLOD[babylonDrawMode]) {
  2223. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  2224. delete previousBabylonDataLOD[babylonDrawMode];
  2225. }
  2226. }
  2227. if (indexLOD !== materialLODs.length - 1) {
  2228. var materialIndex = materialLODs[indexLOD + 1]._index;
  2229. if (_this._loadMaterialSignals[materialIndex]) {
  2230. _this._loadMaterialSignals[materialIndex].resolve();
  2231. delete _this._loadMaterialSignals[materialIndex];
  2232. }
  2233. }
  2234. });
  2235. if (indexLOD === 0) {
  2236. firstPromise = promise;
  2237. }
  2238. else {
  2239. _this._loader._completePromises.push(promise);
  2240. _this._loadingMaterialLOD = null;
  2241. }
  2242. };
  2243. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  2244. _loop_2(indexLOD);
  2245. }
  2246. return firstPromise;
  2247. });
  2248. };
  2249. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  2250. var _this = this;
  2251. // Defer the loading of uris if loading a material or node LOD.
  2252. if (this._loadingMaterialLOD) {
  2253. var index = this._loadingMaterialLOD._index;
  2254. return this._loadMaterialSignals[index].promise.then(function () {
  2255. return _this._loader._loadUriAsync(context, uri);
  2256. });
  2257. }
  2258. else if (this._loadingNodeLOD) {
  2259. var index = this._loadingNodeLOD._index;
  2260. return this._loadNodeSignals[index].promise.then(function () {
  2261. return _this._loader._loadUriAsync(context, uri);
  2262. });
  2263. }
  2264. return null;
  2265. };
  2266. /**
  2267. * Gets an array of LOD properties from lowest to highest.
  2268. */
  2269. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  2270. if (this.maxLODsToLoad <= 0) {
  2271. throw new Error("maxLODsToLoad must be greater than zero");
  2272. }
  2273. var properties = new Array();
  2274. for (var i = ids.length - 1; i >= 0; i--) {
  2275. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  2276. if (properties.length === this.maxLODsToLoad) {
  2277. return properties;
  2278. }
  2279. }
  2280. properties.push(property);
  2281. return properties;
  2282. };
  2283. return MSFT_lod;
  2284. }(GLTF2.GLTFLoaderExtension));
  2285. Extensions.MSFT_lod = MSFT_lod;
  2286. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  2287. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2288. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2289. })(BABYLON || (BABYLON = {}));
  2290. //# sourceMappingURL=MSFT_lod.js.map
  2291. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2292. var __extends = (this && this.__extends) || (function () {
  2293. var extendStatics = Object.setPrototypeOf ||
  2294. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2295. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2296. return function (d, b) {
  2297. extendStatics(d, b);
  2298. function __() { this.constructor = d; }
  2299. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2300. };
  2301. })();
  2302. /** Module defining extensions to gltf */
  2303. var BABYLON;
  2304. (function (BABYLON) {
  2305. var GLTF2;
  2306. (function (GLTF2) {
  2307. var Extensions;
  2308. (function (Extensions) {
  2309. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  2310. var NAME = "KHR_draco_mesh_compression";
  2311. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  2312. __extends(KHR_draco_mesh_compression, _super);
  2313. function KHR_draco_mesh_compression(loader) {
  2314. var _this = _super.call(this, loader) || this;
  2315. _this.name = NAME;
  2316. _this._dracoCompression = null;
  2317. // Disable extension if decoder is not available.
  2318. if (!BABYLON.DracoCompression.DecoderAvailable) {
  2319. _this.enabled = false;
  2320. }
  2321. return _this;
  2322. }
  2323. KHR_draco_mesh_compression.prototype.dispose = function () {
  2324. if (this._dracoCompression) {
  2325. this._dracoCompression.dispose();
  2326. }
  2327. _super.prototype.dispose.call(this);
  2328. };
  2329. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  2330. var _this = this;
  2331. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  2332. if (primitive.mode != undefined) {
  2333. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  2334. primitive.mode !== 4 /* TRIANGLES */) {
  2335. throw new Error(context + ": Unsupported mode " + primitive.mode);
  2336. }
  2337. // TODO: handle triangle strips
  2338. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  2339. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  2340. }
  2341. }
  2342. var attributes = {};
  2343. var loadAttribute = function (name, kind) {
  2344. var uniqueId = extension.attributes[name];
  2345. if (uniqueId == undefined) {
  2346. return;
  2347. }
  2348. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  2349. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  2350. babylonMesh._delayInfo.push(kind);
  2351. }
  2352. attributes[kind] = uniqueId;
  2353. };
  2354. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  2355. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  2356. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  2357. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  2358. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  2359. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  2360. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  2361. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  2362. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  2363. if (!bufferView._dracoBabylonGeometry) {
  2364. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  2365. if (!_this._dracoCompression) {
  2366. _this._dracoCompression = new BABYLON.DracoCompression();
  2367. }
  2368. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  2369. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  2370. babylonVertexData.applyToGeometry(babylonGeometry);
  2371. return babylonGeometry;
  2372. }).catch(function (error) {
  2373. throw new Error(context + ": " + error.message);
  2374. });
  2375. });
  2376. }
  2377. return bufferView._dracoBabylonGeometry;
  2378. });
  2379. };
  2380. return KHR_draco_mesh_compression;
  2381. }(GLTF2.GLTFLoaderExtension));
  2382. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  2383. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  2384. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2385. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2386. })(BABYLON || (BABYLON = {}));
  2387. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  2388. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2389. var __extends = (this && this.__extends) || (function () {
  2390. var extendStatics = Object.setPrototypeOf ||
  2391. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2392. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2393. return function (d, b) {
  2394. extendStatics(d, b);
  2395. function __() { this.constructor = d; }
  2396. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2397. };
  2398. })();
  2399. var BABYLON;
  2400. (function (BABYLON) {
  2401. var GLTF2;
  2402. (function (GLTF2) {
  2403. var Extensions;
  2404. (function (Extensions) {
  2405. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  2406. var NAME = "KHR_materials_pbrSpecularGlossiness";
  2407. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  2408. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  2409. function KHR_materials_pbrSpecularGlossiness() {
  2410. var _this = _super !== null && _super.apply(this, arguments) || this;
  2411. _this.name = NAME;
  2412. return _this;
  2413. }
  2414. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2415. var _this = this;
  2416. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  2417. material._babylonData = material._babylonData || {};
  2418. var babylonData = material._babylonData[babylonDrawMode];
  2419. if (!babylonData) {
  2420. var promises = new Array();
  2421. var name_1 = material.name || "materialSG_" + material._index;
  2422. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  2423. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  2424. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  2425. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  2426. babylonData = {
  2427. material: babylonMaterial,
  2428. meshes: [],
  2429. loaded: Promise.all(promises).then(function () { })
  2430. };
  2431. material._babylonData[babylonDrawMode] = babylonData;
  2432. }
  2433. babylonData.meshes.push(babylonMesh);
  2434. assign(babylonData.material);
  2435. return babylonData.loaded;
  2436. });
  2437. };
  2438. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  2439. var promises = new Array();
  2440. if (properties.diffuseFactor) {
  2441. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  2442. babylonMaterial.alpha = properties.diffuseFactor[3];
  2443. }
  2444. else {
  2445. babylonMaterial.albedoColor = BABYLON.Color3.White();
  2446. }
  2447. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  2448. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  2449. if (properties.diffuseTexture) {
  2450. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  2451. babylonMaterial.albedoTexture = texture;
  2452. }));
  2453. }
  2454. if (properties.specularGlossinessTexture) {
  2455. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  2456. babylonMaterial.reflectivityTexture = texture;
  2457. }));
  2458. babylonMaterial.reflectivityTexture.hasAlpha = true;
  2459. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  2460. }
  2461. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  2462. return Promise.all(promises).then(function () { });
  2463. };
  2464. return KHR_materials_pbrSpecularGlossiness;
  2465. }(GLTF2.GLTFLoaderExtension));
  2466. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  2467. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  2468. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2469. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2470. })(BABYLON || (BABYLON = {}));
  2471. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  2472. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2473. var __extends = (this && this.__extends) || (function () {
  2474. var extendStatics = Object.setPrototypeOf ||
  2475. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2476. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2477. return function (d, b) {
  2478. extendStatics(d, b);
  2479. function __() { this.constructor = d; }
  2480. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2481. };
  2482. })();
  2483. var BABYLON;
  2484. (function (BABYLON) {
  2485. var GLTF2;
  2486. (function (GLTF2) {
  2487. var Extensions;
  2488. (function (Extensions) {
  2489. // https://github.com/donmccurdy/glTF/tree/feat-khr-materials-cmnConstant/extensions/2.0/Khronos/KHR_materials_unlit
  2490. var NAME = "KHR_materials_unlit";
  2491. var KHR_materials_unlit = /** @class */ (function (_super) {
  2492. __extends(KHR_materials_unlit, _super);
  2493. function KHR_materials_unlit() {
  2494. var _this = _super !== null && _super.apply(this, arguments) || this;
  2495. _this.name = NAME;
  2496. return _this;
  2497. }
  2498. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2499. var _this = this;
  2500. return this._loadExtensionAsync(context, material, function () {
  2501. material._babylonData = material._babylonData || {};
  2502. var babylonData = material._babylonData[babylonDrawMode];
  2503. if (!babylonData) {
  2504. var name_1 = material.name || "materialUnlit_" + material._index;
  2505. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  2506. babylonMaterial.unlit = true;
  2507. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  2508. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  2509. babylonData = {
  2510. material: babylonMaterial,
  2511. meshes: [],
  2512. loaded: promise
  2513. };
  2514. material._babylonData[babylonDrawMode] = babylonData;
  2515. }
  2516. babylonData.meshes.push(babylonMesh);
  2517. assign(babylonData.material);
  2518. return babylonData.loaded;
  2519. });
  2520. };
  2521. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  2522. var promises = new Array();
  2523. // Ensure metallic workflow
  2524. babylonMaterial.metallic = 1;
  2525. babylonMaterial.roughness = 1;
  2526. var properties = material.pbrMetallicRoughness;
  2527. if (properties) {
  2528. if (properties.baseColorFactor) {
  2529. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  2530. babylonMaterial.alpha = properties.baseColorFactor[3];
  2531. }
  2532. else {
  2533. babylonMaterial.albedoColor = BABYLON.Color3.White();
  2534. }
  2535. if (properties.baseColorTexture) {
  2536. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  2537. babylonMaterial.albedoTexture = texture;
  2538. }));
  2539. }
  2540. }
  2541. if (material.doubleSided) {
  2542. babylonMaterial.backFaceCulling = false;
  2543. babylonMaterial.twoSidedLighting = true;
  2544. }
  2545. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  2546. return Promise.all(promises).then(function () { });
  2547. };
  2548. return KHR_materials_unlit;
  2549. }(GLTF2.GLTFLoaderExtension));
  2550. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  2551. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  2552. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2553. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2554. })(BABYLON || (BABYLON = {}));
  2555. //# sourceMappingURL=KHR_materials_unlit.js.map
  2556. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2557. var __extends = (this && this.__extends) || (function () {
  2558. var extendStatics = Object.setPrototypeOf ||
  2559. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2560. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2561. return function (d, b) {
  2562. extendStatics(d, b);
  2563. function __() { this.constructor = d; }
  2564. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2565. };
  2566. })();
  2567. var BABYLON;
  2568. (function (BABYLON) {
  2569. var GLTF2;
  2570. (function (GLTF2) {
  2571. var Extensions;
  2572. (function (Extensions) {
  2573. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  2574. var NAME = "KHR_lights";
  2575. var LightType;
  2576. (function (LightType) {
  2577. LightType["AMBIENT"] = "ambient";
  2578. LightType["DIRECTIONAL"] = "directional";
  2579. LightType["POINT"] = "point";
  2580. LightType["SPOT"] = "spot";
  2581. })(LightType || (LightType = {}));
  2582. var KHR_lights = /** @class */ (function (_super) {
  2583. __extends(KHR_lights, _super);
  2584. function KHR_lights() {
  2585. var _this = _super !== null && _super.apply(this, arguments) || this;
  2586. _this.name = NAME;
  2587. return _this;
  2588. }
  2589. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  2590. var _this = this;
  2591. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  2592. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  2593. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  2594. if (light.type !== LightType.AMBIENT) {
  2595. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  2596. }
  2597. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  2598. return promise;
  2599. });
  2600. };
  2601. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  2602. var _this = this;
  2603. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  2604. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  2605. var babylonLight;
  2606. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  2607. var name = node._babylonMesh.name;
  2608. switch (light.type) {
  2609. case LightType.AMBIENT: {
  2610. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  2611. }
  2612. case LightType.DIRECTIONAL: {
  2613. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  2614. break;
  2615. }
  2616. case LightType.POINT: {
  2617. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  2618. break;
  2619. }
  2620. case LightType.SPOT: {
  2621. var spotLight = light;
  2622. // TODO: support inner and outer cone angles
  2623. //const innerConeAngle = spotLight.innerConeAngle || 0;
  2624. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  2625. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  2626. break;
  2627. }
  2628. default: {
  2629. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  2630. }
  2631. }
  2632. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  2633. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  2634. babylonLight.parent = node._babylonMesh;
  2635. return promise;
  2636. });
  2637. };
  2638. Object.defineProperty(KHR_lights.prototype, "_lights", {
  2639. get: function () {
  2640. var extensions = this._loader._gltf.extensions;
  2641. if (!extensions || !extensions[this.name]) {
  2642. throw new Error("#/extensions: '" + this.name + "' not found");
  2643. }
  2644. var extension = extensions[this.name];
  2645. return extension.lights;
  2646. },
  2647. enumerable: true,
  2648. configurable: true
  2649. });
  2650. return KHR_lights;
  2651. }(GLTF2.GLTFLoaderExtension));
  2652. Extensions.KHR_lights = KHR_lights;
  2653. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  2654. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2655. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2656. })(BABYLON || (BABYLON = {}));
  2657. //# sourceMappingURL=KHR_lights.js.map