babylon.glTF2FileLoader.js 142 KB

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