babylon.glTF2FileLoader.js 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351
  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. return skin._loaded.then(function () {
  1072. assignSkeleton();
  1073. });
  1074. }
  1075. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  1076. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  1077. var skeletonId = "skeleton" + skin._index;
  1078. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  1079. skin._babylonSkeleton = babylonSkeleton;
  1080. _this._loadBones(context, skin, inverseBindMatricesData);
  1081. assignSkeleton();
  1082. }));
  1083. };
  1084. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  1085. if (skin.inverseBindMatrices == undefined) {
  1086. return Promise.resolve(null);
  1087. }
  1088. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  1089. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  1090. return data;
  1091. });
  1092. };
  1093. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  1094. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  1095. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  1096. node._babylonAnimationTargets.push(babylonBone);
  1097. return babylonBone;
  1098. };
  1099. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  1100. var babylonBones = {};
  1101. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  1102. var index = _a[_i];
  1103. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  1104. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  1105. }
  1106. };
  1107. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  1108. var babylonBone = babylonBones[node._index];
  1109. if (babylonBone) {
  1110. return babylonBone;
  1111. }
  1112. var boneIndex = skin.joints.indexOf(node._index);
  1113. var baseMatrix = BABYLON.Matrix.Identity();
  1114. if (inverseBindMatricesData && boneIndex !== -1) {
  1115. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  1116. baseMatrix.invertToRef(baseMatrix);
  1117. }
  1118. var babylonParentBone = null;
  1119. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  1120. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  1121. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  1122. }
  1123. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  1124. babylonBones[node._index] = babylonBone;
  1125. return babylonBone;
  1126. };
  1127. GLTFLoader.prototype._getNodeMatrix = function (node) {
  1128. return node.matrix ?
  1129. BABYLON.Matrix.FromArray(node.matrix) :
  1130. 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());
  1131. };
  1132. GLTFLoader.prototype._loadAnimationsAsync = function () {
  1133. var animations = this._gltf.animations;
  1134. if (!animations) {
  1135. return Promise.resolve();
  1136. }
  1137. var promises = new Array();
  1138. for (var index = 0; index < animations.length; index++) {
  1139. var animation = animations[index];
  1140. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  1141. }
  1142. return Promise.all(promises).then(function () { });
  1143. };
  1144. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  1145. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  1146. animation._babylonAnimationGroup = babylonAnimationGroup;
  1147. var promises = new Array();
  1148. GLTF2.ArrayItem.Assign(animation.channels);
  1149. GLTF2.ArrayItem.Assign(animation.samplers);
  1150. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  1151. var channel = _a[_i];
  1152. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  1153. }
  1154. return Promise.all(promises).then(function () {
  1155. babylonAnimationGroup.normalize();
  1156. });
  1157. };
  1158. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  1159. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  1160. if (!targetNode._babylonMesh) {
  1161. return Promise.resolve();
  1162. }
  1163. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  1164. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  1165. var targetPath;
  1166. var animationType;
  1167. switch (channel.target.path) {
  1168. case "translation" /* TRANSLATION */: {
  1169. targetPath = "position";
  1170. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1171. break;
  1172. }
  1173. case "rotation" /* ROTATION */: {
  1174. targetPath = "rotationQuaternion";
  1175. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1176. break;
  1177. }
  1178. case "scale" /* SCALE */: {
  1179. targetPath = "scaling";
  1180. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1181. break;
  1182. }
  1183. case "weights" /* WEIGHTS */: {
  1184. targetPath = "influence";
  1185. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  1186. break;
  1187. }
  1188. default: {
  1189. throw new Error(context + ": Invalid target path " + channel.target.path);
  1190. }
  1191. }
  1192. var outputBufferOffset = 0;
  1193. var getNextOutputValue;
  1194. switch (targetPath) {
  1195. case "position": {
  1196. getNextOutputValue = function () {
  1197. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  1198. outputBufferOffset += 3;
  1199. return value;
  1200. };
  1201. break;
  1202. }
  1203. case "rotationQuaternion": {
  1204. getNextOutputValue = function () {
  1205. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  1206. outputBufferOffset += 4;
  1207. return value;
  1208. };
  1209. break;
  1210. }
  1211. case "scaling": {
  1212. getNextOutputValue = function () {
  1213. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  1214. outputBufferOffset += 3;
  1215. return value;
  1216. };
  1217. break;
  1218. }
  1219. case "influence": {
  1220. getNextOutputValue = function () {
  1221. var value = new Array(targetNode._numMorphTargets);
  1222. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  1223. value[i] = data.output[outputBufferOffset++];
  1224. }
  1225. return value;
  1226. };
  1227. break;
  1228. }
  1229. }
  1230. var getNextKey;
  1231. switch (data.interpolation) {
  1232. case "STEP" /* STEP */: {
  1233. getNextKey = function (frameIndex) { return ({
  1234. frame: data.input[frameIndex],
  1235. value: getNextOutputValue(),
  1236. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  1237. }); };
  1238. break;
  1239. }
  1240. case "LINEAR" /* LINEAR */: {
  1241. getNextKey = function (frameIndex) { return ({
  1242. frame: data.input[frameIndex],
  1243. value: getNextOutputValue()
  1244. }); };
  1245. break;
  1246. }
  1247. case "CUBICSPLINE" /* CUBICSPLINE */: {
  1248. getNextKey = function (frameIndex) { return ({
  1249. frame: data.input[frameIndex],
  1250. inTangent: getNextOutputValue(),
  1251. value: getNextOutputValue(),
  1252. outTangent: getNextOutputValue()
  1253. }); };
  1254. break;
  1255. }
  1256. }
  1257. var keys;
  1258. if (data.input.length === 1) {
  1259. var key = getNextKey(0);
  1260. keys = [
  1261. { frame: key.frame, value: key.value },
  1262. { frame: key.frame + 1, value: key.value }
  1263. ];
  1264. }
  1265. else {
  1266. keys = new Array(data.input.length);
  1267. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  1268. keys[frameIndex] = getNextKey(frameIndex);
  1269. }
  1270. }
  1271. if (targetPath === "influence") {
  1272. var _loop_1 = function (targetIndex) {
  1273. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  1274. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1275. babylonAnimation.setKeys(keys.map(function (key) { return ({
  1276. frame: key.frame,
  1277. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1278. value: key.value[targetIndex],
  1279. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1280. }); }));
  1281. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  1282. var babylonMesh = _a[_i];
  1283. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  1284. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  1285. }
  1286. };
  1287. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  1288. _loop_1(targetIndex);
  1289. }
  1290. }
  1291. else {
  1292. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  1293. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1294. babylonAnimation.setKeys(keys);
  1295. if (targetNode._babylonAnimationTargets) {
  1296. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  1297. var target = _a[_i];
  1298. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  1299. }
  1300. }
  1301. }
  1302. });
  1303. };
  1304. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  1305. if (sampler._data) {
  1306. return sampler._data;
  1307. }
  1308. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  1309. switch (interpolation) {
  1310. case "STEP" /* STEP */:
  1311. case "LINEAR" /* LINEAR */:
  1312. case "CUBICSPLINE" /* CUBICSPLINE */: {
  1313. break;
  1314. }
  1315. default: {
  1316. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  1317. }
  1318. }
  1319. var inputData;
  1320. var outputData;
  1321. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  1322. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  1323. sampler._data = Promise.all([
  1324. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  1325. inputData = data;
  1326. }),
  1327. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  1328. outputData = data;
  1329. })
  1330. ]).then(function () {
  1331. return {
  1332. input: inputData,
  1333. interpolation: interpolation,
  1334. output: outputData,
  1335. };
  1336. });
  1337. return sampler._data;
  1338. };
  1339. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  1340. if (buffer._data) {
  1341. return buffer._data;
  1342. }
  1343. if (!buffer.uri) {
  1344. throw new Error(context + ": Uri is missing");
  1345. }
  1346. buffer._data = this._loadUriAsync(context, buffer.uri);
  1347. return buffer._data;
  1348. };
  1349. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  1350. if (bufferView._data) {
  1351. return bufferView._data;
  1352. }
  1353. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  1354. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  1355. try {
  1356. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1357. }
  1358. catch (e) {
  1359. throw new Error(context + ": " + e.message);
  1360. }
  1361. });
  1362. return bufferView._data;
  1363. };
  1364. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  1365. var _this = this;
  1366. if (accessor.sparse) {
  1367. throw new Error(context + ": Sparse accessors are not currently supported");
  1368. }
  1369. if (accessor._data) {
  1370. return accessor._data;
  1371. }
  1372. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  1373. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  1374. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  1375. var byteOffset = accessor.byteOffset || 0;
  1376. var byteStride = bufferView.byteStride;
  1377. if (byteStride === 0) {
  1378. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  1379. }
  1380. try {
  1381. switch (accessor.componentType) {
  1382. case 5120 /* BYTE */: {
  1383. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1384. }
  1385. case 5121 /* UNSIGNED_BYTE */: {
  1386. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1387. }
  1388. case 5122 /* SHORT */: {
  1389. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1390. }
  1391. case 5123 /* UNSIGNED_SHORT */: {
  1392. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1393. }
  1394. case 5125 /* UNSIGNED_INT */: {
  1395. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1396. }
  1397. case 5126 /* FLOAT */: {
  1398. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1399. }
  1400. default: {
  1401. throw new Error(context + ": Invalid component type " + accessor.componentType);
  1402. }
  1403. }
  1404. }
  1405. catch (e) {
  1406. throw new Error(context + ": " + e);
  1407. }
  1408. });
  1409. return accessor._data;
  1410. };
  1411. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  1412. byteOffset += data.byteOffset;
  1413. var targetLength = count * numComponents;
  1414. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  1415. return new typedArray(data.buffer, byteOffset, targetLength);
  1416. }
  1417. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  1418. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  1419. var targetBuffer = new typedArray(targetLength);
  1420. var sourceIndex = 0;
  1421. var targetIndex = 0;
  1422. while (targetIndex < targetLength) {
  1423. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1424. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  1425. targetIndex++;
  1426. }
  1427. sourceIndex += elementStride;
  1428. }
  1429. return targetBuffer;
  1430. };
  1431. GLTFLoader.prototype._getDefaultMaterial = function () {
  1432. var id = "__gltf_default";
  1433. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  1434. if (!babylonMaterial) {
  1435. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  1436. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  1437. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  1438. babylonMaterial.metallic = 1;
  1439. babylonMaterial.roughness = 1;
  1440. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1441. }
  1442. return babylonMaterial;
  1443. };
  1444. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  1445. var promises = new Array();
  1446. var babylonMaterial = material._babylonMaterial;
  1447. // Ensure metallic workflow
  1448. babylonMaterial.metallic = 1;
  1449. babylonMaterial.roughness = 1;
  1450. var properties = material.pbrMetallicRoughness;
  1451. if (properties) {
  1452. if (properties.baseColorFactor) {
  1453. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  1454. babylonMaterial.alpha = properties.baseColorFactor[3];
  1455. }
  1456. else {
  1457. babylonMaterial.albedoColor = BABYLON.Color3.White();
  1458. }
  1459. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  1460. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  1461. if (properties.baseColorTexture) {
  1462. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  1463. babylonMaterial.albedoTexture = texture;
  1464. }));
  1465. }
  1466. if (properties.metallicRoughnessTexture) {
  1467. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  1468. babylonMaterial.metallicTexture = texture;
  1469. }));
  1470. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1471. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1472. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1473. }
  1474. }
  1475. this._loadMaterialAlphaProperties(context, material);
  1476. return Promise.all(promises).then(function () { });
  1477. };
  1478. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  1479. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  1480. if (promise) {
  1481. return promise;
  1482. }
  1483. material._babylonMeshes = material._babylonMeshes || [];
  1484. material._babylonMeshes.push(babylonMesh);
  1485. if (material._loaded) {
  1486. babylonMesh.material = material._babylonMaterial;
  1487. return material._loaded;
  1488. }
  1489. var promises = new Array();
  1490. var babylonMaterial = this._createMaterial(material);
  1491. material._babylonMaterial = babylonMaterial;
  1492. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  1493. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  1494. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1495. babylonMesh.material = babylonMaterial;
  1496. return (material._loaded = Promise.all(promises).then(function () { }));
  1497. };
  1498. GLTFLoader.prototype._createMaterial = function (material) {
  1499. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  1500. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  1501. return babylonMaterial;
  1502. };
  1503. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  1504. var promises = new Array();
  1505. var babylonMaterial = material._babylonMaterial;
  1506. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1507. if (material.doubleSided) {
  1508. babylonMaterial.backFaceCulling = false;
  1509. babylonMaterial.twoSidedLighting = true;
  1510. }
  1511. if (material.normalTexture) {
  1512. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  1513. babylonMaterial.bumpTexture = texture;
  1514. }));
  1515. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1516. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1517. if (material.normalTexture.scale != undefined) {
  1518. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1519. }
  1520. }
  1521. if (material.occlusionTexture) {
  1522. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  1523. babylonMaterial.ambientTexture = texture;
  1524. }));
  1525. babylonMaterial.useAmbientInGrayScale = true;
  1526. if (material.occlusionTexture.strength != undefined) {
  1527. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1528. }
  1529. }
  1530. if (material.emissiveTexture) {
  1531. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  1532. babylonMaterial.emissiveTexture = texture;
  1533. }));
  1534. }
  1535. return Promise.all(promises).then(function () { });
  1536. };
  1537. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  1538. var babylonMaterial = material._babylonMaterial;
  1539. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  1540. switch (alphaMode) {
  1541. case "OPAQUE" /* OPAQUE */: {
  1542. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  1543. break;
  1544. }
  1545. case "MASK" /* MASK */: {
  1546. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  1547. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  1548. if (babylonMaterial.alpha) {
  1549. if (babylonMaterial.alpha === 0) {
  1550. babylonMaterial.alphaCutOff = 1;
  1551. }
  1552. else {
  1553. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  1554. }
  1555. babylonMaterial.alpha = 1;
  1556. }
  1557. if (babylonMaterial.albedoTexture) {
  1558. babylonMaterial.albedoTexture.hasAlpha = true;
  1559. }
  1560. break;
  1561. }
  1562. case "BLEND" /* BLEND */: {
  1563. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  1564. if (babylonMaterial.albedoTexture) {
  1565. babylonMaterial.albedoTexture.hasAlpha = true;
  1566. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1567. }
  1568. break;
  1569. }
  1570. default: {
  1571. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  1572. }
  1573. }
  1574. };
  1575. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  1576. var _this = this;
  1577. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  1578. context = "#/textures/" + textureInfo.index;
  1579. var promises = new Array();
  1580. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  1581. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  1582. var deferred = new BABYLON.Deferred();
  1583. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  1584. if (!_this._disposed) {
  1585. deferred.resolve();
  1586. }
  1587. }, function (message, exception) {
  1588. if (!_this._disposed) {
  1589. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  1590. }
  1591. });
  1592. promises.push(deferred.promise);
  1593. babylonTexture.name = texture.name || "texture" + texture._index;
  1594. babylonTexture.wrapU = samplerData.wrapU;
  1595. babylonTexture.wrapV = samplerData.wrapV;
  1596. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  1597. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  1598. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  1599. babylonTexture.updateURL(objectURL);
  1600. }));
  1601. assign(babylonTexture);
  1602. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  1603. return Promise.all(promises).then(function () { });
  1604. };
  1605. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  1606. if (!sampler._data) {
  1607. sampler._data = {
  1608. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  1609. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  1610. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  1611. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  1612. };
  1613. }
  1614. ;
  1615. return sampler._data;
  1616. };
  1617. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  1618. if (image._objectURL) {
  1619. return image._objectURL;
  1620. }
  1621. var promise;
  1622. if (image.uri) {
  1623. promise = this._loadUriAsync(context, image.uri);
  1624. }
  1625. else {
  1626. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  1627. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  1628. }
  1629. image._objectURL = promise.then(function (data) {
  1630. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  1631. });
  1632. return image._objectURL;
  1633. };
  1634. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  1635. var _this = this;
  1636. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  1637. if (promise) {
  1638. return promise;
  1639. }
  1640. if (!GLTFLoader._ValidateUri(uri)) {
  1641. throw new Error(context + ": Uri '" + uri + "' is invalid");
  1642. }
  1643. if (BABYLON.Tools.IsBase64(uri)) {
  1644. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  1645. }
  1646. return new Promise(function (resolve, reject) {
  1647. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  1648. if (!_this._disposed) {
  1649. resolve(new Uint8Array(data));
  1650. }
  1651. }, function (event) {
  1652. if (!_this._disposed) {
  1653. try {
  1654. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  1655. request._lengthComputable = event.lengthComputable;
  1656. request._loaded = event.loaded;
  1657. request._total = event.total;
  1658. _this._onProgress();
  1659. }
  1660. }
  1661. catch (e) {
  1662. reject(e);
  1663. }
  1664. }
  1665. }, _this._babylonScene.database, true, function (request, exception) {
  1666. if (!_this._disposed) {
  1667. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  1668. }
  1669. });
  1670. _this._requests.push(request);
  1671. });
  1672. };
  1673. GLTFLoader.prototype._onProgress = function () {
  1674. if (!this._progressCallback) {
  1675. return;
  1676. }
  1677. var lengthComputable = true;
  1678. var loaded = 0;
  1679. var total = 0;
  1680. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  1681. var request = _a[_i];
  1682. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  1683. return;
  1684. }
  1685. lengthComputable = lengthComputable && request._lengthComputable;
  1686. loaded += request._loaded;
  1687. total += request._total;
  1688. }
  1689. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  1690. };
  1691. GLTFLoader._GetProperty = function (context, array, index) {
  1692. if (!array || index == undefined || !array[index]) {
  1693. throw new Error(context + ": Failed to find index " + index);
  1694. }
  1695. return array[index];
  1696. };
  1697. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  1698. // Set defaults if undefined
  1699. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  1700. switch (mode) {
  1701. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1702. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1703. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1704. default:
  1705. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  1706. return BABYLON.Texture.WRAP_ADDRESSMODE;
  1707. }
  1708. };
  1709. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  1710. // Set defaults if undefined
  1711. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  1712. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  1713. if (magFilter === 9729 /* LINEAR */) {
  1714. switch (minFilter) {
  1715. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  1716. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  1717. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  1718. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  1719. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  1720. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1721. default:
  1722. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  1723. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1724. }
  1725. }
  1726. else {
  1727. if (magFilter !== 9728 /* NEAREST */) {
  1728. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  1729. }
  1730. switch (minFilter) {
  1731. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  1732. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  1733. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1734. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  1735. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  1736. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  1737. default:
  1738. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  1739. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1740. }
  1741. }
  1742. };
  1743. GLTFLoader._GetNumComponents = function (context, type) {
  1744. switch (type) {
  1745. case "SCALAR": return 1;
  1746. case "VEC2": return 2;
  1747. case "VEC3": return 3;
  1748. case "VEC4": return 4;
  1749. case "MAT2": return 4;
  1750. case "MAT3": return 9;
  1751. case "MAT4": return 16;
  1752. }
  1753. throw new Error(context + ": Invalid type " + type);
  1754. };
  1755. GLTFLoader._ValidateUri = function (uri) {
  1756. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  1757. };
  1758. GLTFLoader.prototype._compileMaterialsAsync = function () {
  1759. var promises = new Array();
  1760. if (this._gltf.materials) {
  1761. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  1762. var material = _a[_i];
  1763. var babylonMaterial = material._babylonMaterial;
  1764. var babylonMeshes = material._babylonMeshes;
  1765. if (babylonMaterial && babylonMeshes) {
  1766. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  1767. var babylonMesh = babylonMeshes_1[_b];
  1768. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  1769. if (this.useClipPlane) {
  1770. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  1771. }
  1772. }
  1773. }
  1774. }
  1775. }
  1776. return Promise.all(promises).then(function () { });
  1777. };
  1778. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  1779. var promises = new Array();
  1780. var lights = this._babylonScene.lights;
  1781. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  1782. var light = lights_1[_i];
  1783. var generator = light.getShadowGenerator();
  1784. if (generator) {
  1785. promises.push(generator.forceCompilationAsync());
  1786. }
  1787. }
  1788. return Promise.all(promises).then(function () { });
  1789. };
  1790. GLTFLoader.prototype._clear = function () {
  1791. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  1792. var request = _a[_i];
  1793. request.abort();
  1794. }
  1795. this._requests.length = 0;
  1796. if (this._gltf && this._gltf.images) {
  1797. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  1798. var image = _c[_b];
  1799. if (image._objectURL) {
  1800. image._objectURL.then(function (value) {
  1801. URL.revokeObjectURL(value);
  1802. });
  1803. image._objectURL = undefined;
  1804. }
  1805. }
  1806. }
  1807. delete this._gltf;
  1808. delete this._babylonScene;
  1809. this._completePromises.length = 0;
  1810. for (var name_3 in this._extensions) {
  1811. this._extensions[name_3].dispose();
  1812. }
  1813. this._extensions = {};
  1814. delete this._rootBabylonMesh;
  1815. delete this._progressCallback;
  1816. this.onMeshLoadedObservable.clear();
  1817. this.onTextureLoadedObservable.clear();
  1818. this.onMaterialLoadedObservable.clear();
  1819. };
  1820. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  1821. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  1822. var name_4 = _a[_i];
  1823. var extension = this._extensions[name_4];
  1824. if (extension.enabled) {
  1825. var promise = actionAsync(extension);
  1826. if (promise) {
  1827. return promise;
  1828. }
  1829. }
  1830. }
  1831. return null;
  1832. };
  1833. GLTFLoader._Names = new Array();
  1834. GLTFLoader._Factories = {};
  1835. return GLTFLoader;
  1836. }());
  1837. GLTF2.GLTFLoader = GLTFLoader;
  1838. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  1839. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1840. })(BABYLON || (BABYLON = {}));
  1841. //# sourceMappingURL=babylon.glTFLoader.js.map
  1842. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1843. var BABYLON;
  1844. (function (BABYLON) {
  1845. var GLTF2;
  1846. (function (GLTF2) {
  1847. var GLTFLoaderExtension = /** @class */ (function () {
  1848. function GLTFLoaderExtension(loader) {
  1849. this.enabled = true;
  1850. this._loader = loader;
  1851. }
  1852. GLTFLoaderExtension.prototype.dispose = function () {
  1853. delete this._loader;
  1854. };
  1855. // #region Overridable Methods
  1856. /** Override this method to modify the default behavior for loading scenes. */
  1857. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  1858. /** Override this method to modify the default behavior for loading nodes. */
  1859. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  1860. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  1861. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  1862. /** Override this method to modify the default behavior for loading materials. */
  1863. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  1864. /** Override this method to modify the default behavior for loading uris. */
  1865. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  1866. // #endregion
  1867. /** Helper method called by a loader extension to load an glTF extension. */
  1868. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  1869. if (!property.extensions) {
  1870. return null;
  1871. }
  1872. var extensions = property.extensions;
  1873. var extension = extensions[this.name];
  1874. if (!extension) {
  1875. return null;
  1876. }
  1877. // Clear out the extension before executing the action to avoid recursing into the same property.
  1878. delete extensions[this.name];
  1879. try {
  1880. return actionAsync(context + "/extensions/" + this.name, extension);
  1881. }
  1882. finally {
  1883. // Restore the extension after executing the action.
  1884. extensions[this.name] = extension;
  1885. }
  1886. };
  1887. /** Helper method called by the loader to allow extensions to override loading scenes. */
  1888. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  1889. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  1890. };
  1891. /** Helper method called by the loader to allow extensions to override loading nodes. */
  1892. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  1893. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  1894. };
  1895. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  1896. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  1897. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  1898. };
  1899. /** Helper method called by the loader to allow extensions to override loading materials. */
  1900. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  1901. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  1902. };
  1903. /** Helper method called by the loader to allow extensions to override loading uris. */
  1904. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  1905. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  1906. };
  1907. return GLTFLoaderExtension;
  1908. }());
  1909. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1910. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1911. })(BABYLON || (BABYLON = {}));
  1912. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1913. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1914. var __extends = (this && this.__extends) || (function () {
  1915. var extendStatics = Object.setPrototypeOf ||
  1916. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1917. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1918. return function (d, b) {
  1919. extendStatics(d, b);
  1920. function __() { this.constructor = d; }
  1921. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1922. };
  1923. })();
  1924. var BABYLON;
  1925. (function (BABYLON) {
  1926. var GLTF2;
  1927. (function (GLTF2) {
  1928. var Extensions;
  1929. (function (Extensions) {
  1930. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  1931. var NAME = "MSFT_lod";
  1932. var MSFT_lod = /** @class */ (function (_super) {
  1933. __extends(MSFT_lod, _super);
  1934. function MSFT_lod() {
  1935. var _this = _super !== null && _super.apply(this, arguments) || this;
  1936. _this.name = NAME;
  1937. /**
  1938. * Maximum number of LODs to load, starting from the lowest LOD.
  1939. */
  1940. _this.maxLODsToLoad = Number.MAX_VALUE;
  1941. _this._loadingNodeLOD = null;
  1942. _this._loadNodeSignals = {};
  1943. _this._loadingMaterialLOD = null;
  1944. _this._loadMaterialSignals = {};
  1945. return _this;
  1946. }
  1947. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  1948. var _this = this;
  1949. return this._loadExtensionAsync(context, node, function (context, extension) {
  1950. var firstPromise;
  1951. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  1952. var _loop_1 = function (indexLOD) {
  1953. var nodeLOD = nodeLODs[indexLOD];
  1954. if (indexLOD !== 0) {
  1955. _this._loadingNodeLOD = nodeLOD;
  1956. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  1957. }
  1958. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  1959. if (indexLOD !== 0) {
  1960. var previousNodeLOD = nodeLODs[indexLOD - 1];
  1961. previousNodeLOD._babylonMesh.setEnabled(false);
  1962. }
  1963. if (indexLOD !== nodeLODs.length - 1) {
  1964. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  1965. _this._loadNodeSignals[nodeIndex].resolve();
  1966. delete _this._loadNodeSignals[nodeIndex];
  1967. }
  1968. });
  1969. if (indexLOD === 0) {
  1970. firstPromise = promise;
  1971. }
  1972. else {
  1973. _this._loader._completePromises.push(promise);
  1974. _this._loadingNodeLOD = null;
  1975. }
  1976. };
  1977. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  1978. _loop_1(indexLOD);
  1979. }
  1980. return firstPromise;
  1981. });
  1982. };
  1983. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  1984. var _this = this;
  1985. // Don't load material LODs if already loading a node LOD.
  1986. if (this._loadingNodeLOD) {
  1987. return null;
  1988. }
  1989. return this._loadExtensionAsync(context, material, function (context, extension) {
  1990. var firstPromise;
  1991. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  1992. var _loop_2 = function (indexLOD) {
  1993. var materialLOD = materialLODs[indexLOD];
  1994. if (indexLOD !== 0) {
  1995. _this._loadingMaterialLOD = materialLOD;
  1996. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  1997. }
  1998. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  1999. if (indexLOD !== materialLODs.length - 1) {
  2000. var materialIndex = materialLODs[indexLOD + 1]._index;
  2001. _this._loadMaterialSignals[materialIndex].resolve();
  2002. delete _this._loadMaterialSignals[materialIndex];
  2003. }
  2004. });
  2005. if (indexLOD === 0) {
  2006. firstPromise = promise;
  2007. }
  2008. else {
  2009. _this._loader._completePromises.push(promise);
  2010. _this._loadingMaterialLOD = null;
  2011. }
  2012. };
  2013. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  2014. _loop_2(indexLOD);
  2015. }
  2016. return firstPromise;
  2017. });
  2018. };
  2019. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  2020. var _this = this;
  2021. // Defer the loading of uris if loading a material or node LOD.
  2022. if (this._loadingMaterialLOD) {
  2023. var index = this._loadingMaterialLOD._index;
  2024. return this._loadMaterialSignals[index].promise.then(function () {
  2025. return _this._loader._loadUriAsync(context, uri);
  2026. });
  2027. }
  2028. else if (this._loadingNodeLOD) {
  2029. var index = this._loadingNodeLOD._index;
  2030. return this._loadNodeSignals[index].promise.then(function () {
  2031. return _this._loader._loadUriAsync(context, uri);
  2032. });
  2033. }
  2034. return null;
  2035. };
  2036. /**
  2037. * Gets an array of LOD properties from lowest to highest.
  2038. */
  2039. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  2040. if (this.maxLODsToLoad <= 0) {
  2041. throw new Error("maxLODsToLoad must be greater than zero");
  2042. }
  2043. var properties = new Array();
  2044. for (var i = ids.length - 1; i >= 0; i--) {
  2045. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  2046. if (properties.length === this.maxLODsToLoad) {
  2047. return properties;
  2048. }
  2049. }
  2050. properties.push(property);
  2051. return properties;
  2052. };
  2053. return MSFT_lod;
  2054. }(GLTF2.GLTFLoaderExtension));
  2055. Extensions.MSFT_lod = MSFT_lod;
  2056. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  2057. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2058. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2059. })(BABYLON || (BABYLON = {}));
  2060. //# sourceMappingURL=MSFT_lod.js.map
  2061. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2062. var __extends = (this && this.__extends) || (function () {
  2063. var extendStatics = Object.setPrototypeOf ||
  2064. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2065. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2066. return function (d, b) {
  2067. extendStatics(d, b);
  2068. function __() { this.constructor = d; }
  2069. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2070. };
  2071. })();
  2072. var BABYLON;
  2073. (function (BABYLON) {
  2074. var GLTF2;
  2075. (function (GLTF2) {
  2076. var Extensions;
  2077. (function (Extensions) {
  2078. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  2079. var NAME = "KHR_draco_mesh_compression";
  2080. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  2081. __extends(KHR_draco_mesh_compression, _super);
  2082. function KHR_draco_mesh_compression(loader) {
  2083. var _this = _super.call(this, loader) || this;
  2084. _this.name = NAME;
  2085. _this._dracoCompression = null;
  2086. // Disable extension if decoder is not available.
  2087. if (!BABYLON.DracoCompression.DecoderUrl) {
  2088. _this.enabled = false;
  2089. }
  2090. return _this;
  2091. }
  2092. KHR_draco_mesh_compression.prototype.dispose = function () {
  2093. if (this._dracoCompression) {
  2094. this._dracoCompression.dispose();
  2095. }
  2096. _super.prototype.dispose.call(this);
  2097. };
  2098. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  2099. var _this = this;
  2100. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  2101. if (primitive.mode != undefined) {
  2102. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  2103. primitive.mode !== 4 /* TRIANGLES */) {
  2104. throw new Error(context + ": Unsupported mode " + primitive.mode);
  2105. }
  2106. // TODO: handle triangle strips
  2107. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  2108. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  2109. }
  2110. }
  2111. var attributes = {};
  2112. var loadAttribute = function (name, kind) {
  2113. var uniqueId = extension.attributes[name];
  2114. if (uniqueId == undefined) {
  2115. return;
  2116. }
  2117. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  2118. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  2119. babylonMesh._delayInfo.push(kind);
  2120. }
  2121. attributes[kind] = uniqueId;
  2122. };
  2123. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  2124. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  2125. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  2126. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  2127. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  2128. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  2129. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  2130. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  2131. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  2132. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  2133. try {
  2134. if (!_this._dracoCompression) {
  2135. _this._dracoCompression = new BABYLON.DracoCompression();
  2136. }
  2137. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  2138. }
  2139. catch (e) {
  2140. throw new Error(context + ": " + e.message);
  2141. }
  2142. });
  2143. });
  2144. };
  2145. return KHR_draco_mesh_compression;
  2146. }(GLTF2.GLTFLoaderExtension));
  2147. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  2148. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  2149. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2150. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2151. })(BABYLON || (BABYLON = {}));
  2152. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  2153. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2154. var __extends = (this && this.__extends) || (function () {
  2155. var extendStatics = Object.setPrototypeOf ||
  2156. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2157. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2158. return function (d, b) {
  2159. extendStatics(d, b);
  2160. function __() { this.constructor = d; }
  2161. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2162. };
  2163. })();
  2164. var BABYLON;
  2165. (function (BABYLON) {
  2166. var GLTF2;
  2167. (function (GLTF2) {
  2168. var Extensions;
  2169. (function (Extensions) {
  2170. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  2171. var NAME = "KHR_materials_pbrSpecularGlossiness";
  2172. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  2173. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  2174. function KHR_materials_pbrSpecularGlossiness() {
  2175. var _this = _super !== null && _super.apply(this, arguments) || this;
  2176. _this.name = NAME;
  2177. return _this;
  2178. }
  2179. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  2180. var _this = this;
  2181. return this._loadExtensionAsync(context, material, function (context, extension) {
  2182. material._babylonMeshes = material._babylonMeshes || [];
  2183. material._babylonMeshes.push(babylonMesh);
  2184. if (material._loaded) {
  2185. babylonMesh.material = material._babylonMaterial;
  2186. return material._loaded;
  2187. }
  2188. var promises = new Array();
  2189. var babylonMaterial = _this._loader._createMaterial(material);
  2190. material._babylonMaterial = babylonMaterial;
  2191. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  2192. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  2193. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  2194. babylonMesh.material = babylonMaterial;
  2195. return (material._loaded = Promise.all(promises).then(function () { }));
  2196. });
  2197. };
  2198. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  2199. var promises = new Array();
  2200. var babylonMaterial = material._babylonMaterial;
  2201. if (properties.diffuseFactor) {
  2202. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  2203. babylonMaterial.alpha = properties.diffuseFactor[3];
  2204. }
  2205. else {
  2206. babylonMaterial.albedoColor = BABYLON.Color3.White();
  2207. }
  2208. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  2209. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  2210. if (properties.diffuseTexture) {
  2211. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  2212. babylonMaterial.albedoTexture = texture;
  2213. }));
  2214. }
  2215. if (properties.specularGlossinessTexture) {
  2216. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  2217. babylonMaterial.reflectivityTexture = texture;
  2218. }));
  2219. babylonMaterial.reflectivityTexture.hasAlpha = true;
  2220. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  2221. }
  2222. loader._loadMaterialAlphaProperties(context, material);
  2223. return Promise.all(promises).then(function () { });
  2224. };
  2225. return KHR_materials_pbrSpecularGlossiness;
  2226. }(GLTF2.GLTFLoaderExtension));
  2227. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  2228. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  2229. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2230. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2231. })(BABYLON || (BABYLON = {}));
  2232. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  2233. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2234. var __extends = (this && this.__extends) || (function () {
  2235. var extendStatics = Object.setPrototypeOf ||
  2236. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2237. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2238. return function (d, b) {
  2239. extendStatics(d, b);
  2240. function __() { this.constructor = d; }
  2241. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2242. };
  2243. })();
  2244. var BABYLON;
  2245. (function (BABYLON) {
  2246. var GLTF2;
  2247. (function (GLTF2) {
  2248. var Extensions;
  2249. (function (Extensions) {
  2250. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  2251. var NAME = "KHR_lights";
  2252. var LightType;
  2253. (function (LightType) {
  2254. LightType["AMBIENT"] = "ambient";
  2255. LightType["DIRECTIONAL"] = "directional";
  2256. LightType["POINT"] = "point";
  2257. LightType["SPOT"] = "spot";
  2258. })(LightType || (LightType = {}));
  2259. var KHR_lights = /** @class */ (function (_super) {
  2260. __extends(KHR_lights, _super);
  2261. function KHR_lights() {
  2262. var _this = _super !== null && _super.apply(this, arguments) || this;
  2263. _this.name = NAME;
  2264. return _this;
  2265. }
  2266. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  2267. var _this = this;
  2268. return this._loadExtensionAsync(context, scene, function (context, extension) {
  2269. var promise = _this._loader._loadSceneAsync(context, scene);
  2270. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  2271. if (light.type !== LightType.AMBIENT) {
  2272. throw new Error(context + ": Only ambient lights are allowed on a scene");
  2273. }
  2274. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  2275. return promise;
  2276. });
  2277. };
  2278. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  2279. var _this = this;
  2280. return this._loadExtensionAsync(context, node, function (context, extension) {
  2281. var promise = _this._loader._loadNodeAsync(context, node);
  2282. var babylonLight;
  2283. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  2284. var name = node._babylonMesh.name;
  2285. switch (light.type) {
  2286. case LightType.AMBIENT: {
  2287. throw new Error(context + ": Ambient lights are not allowed on a node");
  2288. }
  2289. case LightType.DIRECTIONAL: {
  2290. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  2291. break;
  2292. }
  2293. case LightType.POINT: {
  2294. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  2295. break;
  2296. }
  2297. case LightType.SPOT: {
  2298. var spotLight = light;
  2299. // TODO: support inner and outer cone angles
  2300. //const innerConeAngle = spotLight.innerConeAngle || 0;
  2301. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  2302. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  2303. break;
  2304. }
  2305. default: {
  2306. throw new Error(context + ": Invalid light type " + light.type);
  2307. }
  2308. }
  2309. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  2310. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  2311. babylonLight.parent = node._babylonMesh;
  2312. return promise;
  2313. });
  2314. };
  2315. Object.defineProperty(KHR_lights.prototype, "_lights", {
  2316. get: function () {
  2317. var extensions = this._loader._gltf.extensions;
  2318. if (!extensions || !extensions[this.name]) {
  2319. throw new Error("#/extensions: " + this.name + " not found");
  2320. }
  2321. var extension = extensions[this.name];
  2322. return extension.lights;
  2323. },
  2324. enumerable: true,
  2325. configurable: true
  2326. });
  2327. return KHR_lights;
  2328. }(GLTF2.GLTFLoaderExtension));
  2329. Extensions.KHR_lights = KHR_lights;
  2330. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  2331. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2332. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2333. })(BABYLON || (BABYLON = {}));
  2334. //# sourceMappingURL=KHR_lights.js.map