babylon.glTF2FileLoader.js 122 KB

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