babylon.glTF2FileLoader.js 146 KB

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