babylon.glTF1FileLoader.js 129 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671
  1. "use strict";
  2. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  3. var BABYLON;
  4. (function (BABYLON) {
  5. var GLTFLoaderCoordinateSystemMode;
  6. (function (GLTFLoaderCoordinateSystemMode) {
  7. /**
  8. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  9. */
  10. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  11. /**
  12. * Sets the useRightHandedSystem flag on the scene.
  13. */
  14. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  15. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  16. var GLTFLoaderAnimationStartMode;
  17. (function (GLTFLoaderAnimationStartMode) {
  18. /**
  19. * No animation will start.
  20. */
  21. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  22. /**
  23. * The first animation will start.
  24. */
  25. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  26. /**
  27. * All animations will start.
  28. */
  29. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  30. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  31. var GLTFLoaderState;
  32. (function (GLTFLoaderState) {
  33. /**
  34. * The asset is loading.
  35. */
  36. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  37. /**
  38. * The asset is ready for rendering.
  39. */
  40. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  41. /**
  42. * The asset is completely loaded.
  43. */
  44. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  45. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  46. var GLTFFileLoader = /** @class */ (function () {
  47. function GLTFFileLoader() {
  48. // #region Common options
  49. /**
  50. * Raised when the asset has been parsed.
  51. * The data.json property stores the glTF JSON.
  52. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  53. */
  54. this.onParsedObservable = new BABYLON.Observable();
  55. // #endregion
  56. // #region V2 options
  57. /**
  58. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  59. */
  60. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  61. /**
  62. * The animation start mode (NONE, FIRST, ALL).
  63. */
  64. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  65. /**
  66. * Set to true to compile materials before raising the success callback.
  67. */
  68. this.compileMaterials = false;
  69. /**
  70. * Set to true to also compile materials with clip planes.
  71. */
  72. this.useClipPlane = false;
  73. /**
  74. * Set to true to compile shadow generators before raising the success callback.
  75. */
  76. this.compileShadowGenerators = false;
  77. /**
  78. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  79. */
  80. this.onMeshLoadedObservable = new BABYLON.Observable();
  81. /**
  82. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  83. */
  84. this.onTextureLoadedObservable = new BABYLON.Observable();
  85. /**
  86. * Raised when the loader creates a material after parsing the glTF properties of the material.
  87. */
  88. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89. /**
  90. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  91. * For assets with LODs, raised when all of the LODs are complete.
  92. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  93. */
  94. this.onCompleteObservable = new BABYLON.Observable();
  95. /**
  96. * Raised after the loader is disposed.
  97. */
  98. this.onDisposeObservable = new BABYLON.Observable();
  99. /**
  100. * Raised after a loader extension is created.
  101. * Set additional options for a loader extension in this event.
  102. */
  103. this.onExtensionLoadedObservable = new BABYLON.Observable();
  104. // #endregion
  105. this._loader = null;
  106. this.name = "gltf";
  107. this.extensions = {
  108. ".gltf": { isBinary: false },
  109. ".glb": { isBinary: true }
  110. };
  111. }
  112. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  113. set: function (callback) {
  114. if (this._onParsedObserver) {
  115. this.onParsedObservable.remove(this._onParsedObserver);
  116. }
  117. this._onParsedObserver = this.onParsedObservable.add(callback);
  118. },
  119. enumerable: true,
  120. configurable: true
  121. });
  122. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  123. set: function (callback) {
  124. if (this._onMeshLoadedObserver) {
  125. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  126. }
  127. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  128. },
  129. enumerable: true,
  130. configurable: true
  131. });
  132. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  133. set: function (callback) {
  134. if (this._onTextureLoadedObserver) {
  135. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  136. }
  137. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  138. },
  139. enumerable: true,
  140. configurable: true
  141. });
  142. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  143. set: function (callback) {
  144. if (this._onMaterialLoadedObserver) {
  145. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  146. }
  147. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  148. },
  149. enumerable: true,
  150. configurable: true
  151. });
  152. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  153. set: function (callback) {
  154. if (this._onCompleteObserver) {
  155. this.onCompleteObservable.remove(this._onCompleteObserver);
  156. }
  157. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  158. },
  159. enumerable: true,
  160. configurable: true
  161. });
  162. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  163. set: function (callback) {
  164. if (this._onDisposeObserver) {
  165. this.onDisposeObservable.remove(this._onDisposeObserver);
  166. }
  167. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  168. },
  169. enumerable: true,
  170. configurable: true
  171. });
  172. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  173. set: function (callback) {
  174. if (this._onExtensionLoadedObserver) {
  175. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  176. }
  177. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  178. },
  179. enumerable: true,
  180. configurable: true
  181. });
  182. /**
  183. * Returns a promise that resolves when the asset is completely loaded.
  184. * @returns A promise that resolves when the asset is completely loaded.
  185. */
  186. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  187. var _this = this;
  188. return new Promise(function (resolve) {
  189. _this.onCompleteObservable.add(function () {
  190. resolve();
  191. }, undefined, undefined, undefined, true);
  192. });
  193. };
  194. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  195. /**
  196. * The loader state (LOADING, READY, COMPLETE) or null if the loader is not active.
  197. */
  198. get: function () {
  199. return this._loader ? this._loader.state : null;
  200. },
  201. enumerable: true,
  202. configurable: true
  203. });
  204. /**
  205. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  206. */
  207. GLTFFileLoader.prototype.dispose = function () {
  208. if (this._loader) {
  209. this._loader.dispose();
  210. this._loader = null;
  211. }
  212. this.onMeshLoadedObservable.clear();
  213. this.onTextureLoadedObservable.clear();
  214. this.onMaterialLoadedObservable.clear();
  215. this.onDisposeObservable.notifyObservers(this);
  216. this.onDisposeObservable.clear();
  217. };
  218. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  219. var _this = this;
  220. return Promise.resolve().then(function () {
  221. var loaderData = _this._parse(data);
  222. _this._loader = _this._getLoader(loaderData);
  223. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  224. });
  225. };
  226. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  227. var _this = this;
  228. return Promise.resolve().then(function () {
  229. var loaderData = _this._parse(data);
  230. _this._loader = _this._getLoader(loaderData);
  231. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  232. });
  233. };
  234. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  235. var _this = this;
  236. return Promise.resolve().then(function () {
  237. var loaderData = _this._parse(data);
  238. _this._loader = _this._getLoader(loaderData);
  239. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  240. var container = new BABYLON.AssetContainer(scene);
  241. Array.prototype.push.apply(container.meshes, result.meshes);
  242. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  243. Array.prototype.push.apply(container.skeletons, result.skeletons);
  244. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  245. container.removeAllFromScene();
  246. return container;
  247. });
  248. });
  249. };
  250. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  251. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  252. };
  253. GLTFFileLoader.prototype.createPlugin = function () {
  254. return new GLTFFileLoader();
  255. };
  256. GLTFFileLoader.prototype._parse = function (data) {
  257. var parsedData;
  258. if (data instanceof ArrayBuffer) {
  259. parsedData = GLTFFileLoader._parseBinary(data);
  260. }
  261. else {
  262. parsedData = {
  263. json: JSON.parse(data),
  264. bin: null
  265. };
  266. }
  267. this.onParsedObservable.notifyObservers(parsedData);
  268. this.onParsedObservable.clear();
  269. return parsedData;
  270. };
  271. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  272. var _this = this;
  273. var loaderVersion = { major: 2, minor: 0 };
  274. var asset = loaderData.json.asset || {};
  275. var version = GLTFFileLoader._parseVersion(asset.version);
  276. if (!version) {
  277. throw new Error("Invalid version: " + asset.version);
  278. }
  279. if (asset.minVersion !== undefined) {
  280. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  281. if (!minVersion) {
  282. throw new Error("Invalid minimum version: " + asset.minVersion);
  283. }
  284. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  285. throw new Error("Incompatible minimum version: " + asset.minVersion);
  286. }
  287. }
  288. var createLoaders = {
  289. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  290. 2: GLTFFileLoader.CreateGLTFLoaderV2
  291. };
  292. var createLoader = createLoaders[version.major];
  293. if (!createLoader) {
  294. throw new Error("Unsupported version: " + asset.version);
  295. }
  296. var loader = createLoader();
  297. loader.coordinateSystemMode = this.coordinateSystemMode;
  298. loader.animationStartMode = this.animationStartMode;
  299. loader.compileMaterials = this.compileMaterials;
  300. loader.useClipPlane = this.useClipPlane;
  301. loader.compileShadowGenerators = this.compileShadowGenerators;
  302. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  303. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  304. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  305. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  306. loader.onCompleteObservable.add(function () {
  307. _this.onMeshLoadedObservable.clear();
  308. _this.onTextureLoadedObservable.clear();
  309. _this.onMaterialLoadedObservable.clear();
  310. _this.onCompleteObservable.notifyObservers(_this);
  311. _this.onCompleteObservable.clear();
  312. });
  313. return loader;
  314. };
  315. GLTFFileLoader._parseBinary = function (data) {
  316. var Binary = {
  317. Magic: 0x46546C67
  318. };
  319. var binaryReader = new BinaryReader(data);
  320. var magic = binaryReader.readUint32();
  321. if (magic !== Binary.Magic) {
  322. throw new Error("Unexpected magic: " + magic);
  323. }
  324. var version = binaryReader.readUint32();
  325. switch (version) {
  326. case 1: return GLTFFileLoader._parseV1(binaryReader);
  327. case 2: return GLTFFileLoader._parseV2(binaryReader);
  328. }
  329. throw new Error("Unsupported version: " + version);
  330. };
  331. GLTFFileLoader._parseV1 = function (binaryReader) {
  332. var ContentFormat = {
  333. JSON: 0
  334. };
  335. var length = binaryReader.readUint32();
  336. if (length != binaryReader.getLength()) {
  337. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  338. }
  339. var contentLength = binaryReader.readUint32();
  340. var contentFormat = binaryReader.readUint32();
  341. var content;
  342. switch (contentFormat) {
  343. case ContentFormat.JSON: {
  344. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  345. break;
  346. }
  347. default: {
  348. throw new Error("Unexpected content format: " + contentFormat);
  349. }
  350. }
  351. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  352. var body = binaryReader.readUint8Array(bytesRemaining);
  353. return {
  354. json: content,
  355. bin: body
  356. };
  357. };
  358. GLTFFileLoader._parseV2 = function (binaryReader) {
  359. var ChunkFormat = {
  360. JSON: 0x4E4F534A,
  361. BIN: 0x004E4942
  362. };
  363. var length = binaryReader.readUint32();
  364. if (length !== binaryReader.getLength()) {
  365. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  366. }
  367. // JSON chunk
  368. var chunkLength = binaryReader.readUint32();
  369. var chunkFormat = binaryReader.readUint32();
  370. if (chunkFormat !== ChunkFormat.JSON) {
  371. throw new Error("First chunk format is not JSON");
  372. }
  373. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  374. // Look for BIN chunk
  375. var bin = null;
  376. while (binaryReader.getPosition() < binaryReader.getLength()) {
  377. var chunkLength_1 = binaryReader.readUint32();
  378. var chunkFormat_1 = binaryReader.readUint32();
  379. switch (chunkFormat_1) {
  380. case ChunkFormat.JSON: {
  381. throw new Error("Unexpected JSON chunk");
  382. }
  383. case ChunkFormat.BIN: {
  384. bin = binaryReader.readUint8Array(chunkLength_1);
  385. break;
  386. }
  387. default: {
  388. // ignore unrecognized chunkFormat
  389. binaryReader.skipBytes(chunkLength_1);
  390. break;
  391. }
  392. }
  393. }
  394. return {
  395. json: json,
  396. bin: bin
  397. };
  398. };
  399. GLTFFileLoader._parseVersion = function (version) {
  400. if (version === "1.0" || version === "1.0.1") {
  401. return {
  402. major: 1,
  403. minor: 0
  404. };
  405. }
  406. var match = (version + "").match(/^(\d+)\.(\d+)/);
  407. if (!match) {
  408. return null;
  409. }
  410. return {
  411. major: parseInt(match[1]),
  412. minor: parseInt(match[2])
  413. };
  414. };
  415. GLTFFileLoader._compareVersion = function (a, b) {
  416. if (a.major > b.major)
  417. return 1;
  418. if (a.major < b.major)
  419. return -1;
  420. if (a.minor > b.minor)
  421. return 1;
  422. if (a.minor < b.minor)
  423. return -1;
  424. return 0;
  425. };
  426. GLTFFileLoader._decodeBufferToText = function (buffer) {
  427. var result = "";
  428. var length = buffer.byteLength;
  429. for (var i = 0; i < length; i++) {
  430. result += String.fromCharCode(buffer[i]);
  431. }
  432. return result;
  433. };
  434. // #endregion
  435. // #region V1 options
  436. GLTFFileLoader.IncrementalLoading = true;
  437. GLTFFileLoader.HomogeneousCoordinates = false;
  438. return GLTFFileLoader;
  439. }());
  440. BABYLON.GLTFFileLoader = GLTFFileLoader;
  441. var BinaryReader = /** @class */ (function () {
  442. function BinaryReader(arrayBuffer) {
  443. this._arrayBuffer = arrayBuffer;
  444. this._dataView = new DataView(arrayBuffer);
  445. this._byteOffset = 0;
  446. }
  447. BinaryReader.prototype.getPosition = function () {
  448. return this._byteOffset;
  449. };
  450. BinaryReader.prototype.getLength = function () {
  451. return this._arrayBuffer.byteLength;
  452. };
  453. BinaryReader.prototype.readUint32 = function () {
  454. var value = this._dataView.getUint32(this._byteOffset, true);
  455. this._byteOffset += 4;
  456. return value;
  457. };
  458. BinaryReader.prototype.readUint8Array = function (length) {
  459. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  460. this._byteOffset += length;
  461. return value;
  462. };
  463. BinaryReader.prototype.skipBytes = function (length) {
  464. this._byteOffset += length;
  465. };
  466. return BinaryReader;
  467. }());
  468. if (BABYLON.SceneLoader) {
  469. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  470. }
  471. })(BABYLON || (BABYLON = {}));
  472. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  473. "use strict";
  474. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  475. var BABYLON;
  476. (function (BABYLON) {
  477. var GLTF1;
  478. (function (GLTF1) {
  479. /**
  480. * Enums
  481. */
  482. var EComponentType;
  483. (function (EComponentType) {
  484. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  485. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  486. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  487. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  488. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  489. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  490. var EShaderType;
  491. (function (EShaderType) {
  492. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  493. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  494. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  495. var EParameterType;
  496. (function (EParameterType) {
  497. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  498. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  499. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  500. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  501. EParameterType[EParameterType["INT"] = 5124] = "INT";
  502. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  503. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  504. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  505. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  506. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  507. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  508. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  509. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  510. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  511. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  512. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  513. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  514. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  515. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  516. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  517. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  518. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  519. var ETextureWrapMode;
  520. (function (ETextureWrapMode) {
  521. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  522. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  523. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  524. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  525. var ETextureFilterType;
  526. (function (ETextureFilterType) {
  527. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  528. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  529. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  530. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  531. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  532. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  533. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  534. var ETextureFormat;
  535. (function (ETextureFormat) {
  536. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  537. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  538. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  539. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  540. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  541. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  542. var ECullingType;
  543. (function (ECullingType) {
  544. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  545. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  546. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  547. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  548. var EBlendingFunction;
  549. (function (EBlendingFunction) {
  550. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  551. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  552. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  553. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  554. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  555. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  556. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  557. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  558. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  559. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  560. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  561. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  562. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  563. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  564. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  565. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  566. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  567. })(BABYLON || (BABYLON = {}));
  568. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  569. "use strict";
  570. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  571. var BABYLON;
  572. (function (BABYLON) {
  573. var GLTF1;
  574. (function (GLTF1) {
  575. /**
  576. * Tokenizer. Used for shaders compatibility
  577. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  578. */
  579. var ETokenType;
  580. (function (ETokenType) {
  581. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  582. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  583. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  584. })(ETokenType || (ETokenType = {}));
  585. var Tokenizer = /** @class */ (function () {
  586. function Tokenizer(toParse) {
  587. this._pos = 0;
  588. this.currentToken = ETokenType.UNKNOWN;
  589. this.currentIdentifier = "";
  590. this.currentString = "";
  591. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  592. this._toParse = toParse;
  593. this._maxPos = toParse.length;
  594. }
  595. Tokenizer.prototype.getNextToken = function () {
  596. if (this.isEnd())
  597. return ETokenType.END_OF_INPUT;
  598. this.currentString = this.read();
  599. this.currentToken = ETokenType.UNKNOWN;
  600. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  601. this.currentToken = ETokenType.IDENTIFIER;
  602. this.currentIdentifier = this.currentString;
  603. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  604. this.currentIdentifier += this.currentString;
  605. this.forward();
  606. }
  607. }
  608. return this.currentToken;
  609. };
  610. Tokenizer.prototype.peek = function () {
  611. return this._toParse[this._pos];
  612. };
  613. Tokenizer.prototype.read = function () {
  614. return this._toParse[this._pos++];
  615. };
  616. Tokenizer.prototype.forward = function () {
  617. this._pos++;
  618. };
  619. Tokenizer.prototype.isEnd = function () {
  620. return this._pos >= this._maxPos;
  621. };
  622. return Tokenizer;
  623. }());
  624. /**
  625. * Values
  626. */
  627. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  628. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  629. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  630. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  631. /**
  632. * Parse
  633. */
  634. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  635. for (var buf in parsedBuffers) {
  636. var parsedBuffer = parsedBuffers[buf];
  637. gltfRuntime.buffers[buf] = parsedBuffer;
  638. gltfRuntime.buffersCount++;
  639. }
  640. };
  641. var parseShaders = function (parsedShaders, gltfRuntime) {
  642. for (var sha in parsedShaders) {
  643. var parsedShader = parsedShaders[sha];
  644. gltfRuntime.shaders[sha] = parsedShader;
  645. gltfRuntime.shaderscount++;
  646. }
  647. };
  648. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  649. for (var object in parsedObjects) {
  650. var parsedObject = parsedObjects[object];
  651. gltfRuntime[runtimeProperty][object] = parsedObject;
  652. }
  653. };
  654. /**
  655. * Utils
  656. */
  657. var normalizeUVs = function (buffer) {
  658. if (!buffer) {
  659. return;
  660. }
  661. for (var i = 0; i < buffer.length / 2; i++) {
  662. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  663. }
  664. };
  665. var getAttribute = function (attributeParameter) {
  666. if (attributeParameter.semantic === "NORMAL") {
  667. return "normal";
  668. }
  669. else if (attributeParameter.semantic === "POSITION") {
  670. return "position";
  671. }
  672. else if (attributeParameter.semantic === "JOINT") {
  673. return "matricesIndices";
  674. }
  675. else if (attributeParameter.semantic === "WEIGHT") {
  676. return "matricesWeights";
  677. }
  678. else if (attributeParameter.semantic === "COLOR") {
  679. return "color";
  680. }
  681. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  682. var channel = Number(attributeParameter.semantic.split("_")[1]);
  683. return "uv" + (channel === 0 ? "" : channel + 1);
  684. }
  685. return null;
  686. };
  687. /**
  688. * Loads and creates animations
  689. */
  690. var loadAnimations = function (gltfRuntime) {
  691. for (var anim in gltfRuntime.animations) {
  692. var animation = gltfRuntime.animations[anim];
  693. if (!animation.channels || !animation.samplers) {
  694. continue;
  695. }
  696. var lastAnimation = null;
  697. for (var i = 0; i < animation.channels.length; i++) {
  698. // Get parameters and load buffers
  699. var channel = animation.channels[i];
  700. var sampler = animation.samplers[channel.sampler];
  701. if (!sampler) {
  702. continue;
  703. }
  704. var inputData = null;
  705. var outputData = null;
  706. if (animation.parameters) {
  707. inputData = animation.parameters[sampler.input];
  708. outputData = animation.parameters[sampler.output];
  709. }
  710. else {
  711. inputData = sampler.input;
  712. outputData = sampler.output;
  713. }
  714. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  715. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  716. var targetID = channel.target.id;
  717. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  718. if (targetNode === null) {
  719. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  720. }
  721. if (targetNode === null) {
  722. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  723. continue;
  724. }
  725. var isBone = targetNode instanceof BABYLON.Bone;
  726. // Get target path (position, rotation or scaling)
  727. var targetPath = channel.target.path;
  728. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  729. if (targetPathIndex !== -1) {
  730. targetPath = babylonAnimationPaths[targetPathIndex];
  731. }
  732. // Determine animation type
  733. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  734. if (!isBone) {
  735. if (targetPath === "rotationQuaternion") {
  736. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  737. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  738. }
  739. else {
  740. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  741. }
  742. }
  743. // Create animation and key frames
  744. var babylonAnimation = null;
  745. var keys = [];
  746. var arrayOffset = 0;
  747. var modifyKey = false;
  748. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  749. babylonAnimation = lastAnimation;
  750. modifyKey = true;
  751. }
  752. if (!modifyKey) {
  753. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  754. }
  755. // For each frame
  756. for (var j = 0; j < bufferInput.length; j++) {
  757. var value = null;
  758. if (targetPath === "rotationQuaternion") {
  759. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  760. arrayOffset += 4;
  761. }
  762. else {
  763. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  764. arrayOffset += 3;
  765. }
  766. if (isBone) {
  767. var bone = targetNode;
  768. var translation = BABYLON.Vector3.Zero();
  769. var rotationQuaternion = new BABYLON.Quaternion();
  770. var scaling = BABYLON.Vector3.Zero();
  771. // Warning on decompose
  772. var mat = bone.getBaseMatrix();
  773. if (modifyKey && lastAnimation) {
  774. mat = lastAnimation.getKeys()[j].value;
  775. }
  776. mat.decompose(scaling, rotationQuaternion, translation);
  777. if (targetPath === "position") {
  778. translation = value;
  779. }
  780. else if (targetPath === "rotationQuaternion") {
  781. rotationQuaternion = value;
  782. }
  783. else {
  784. scaling = value;
  785. }
  786. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  787. }
  788. if (!modifyKey) {
  789. keys.push({
  790. frame: bufferInput[j],
  791. value: value
  792. });
  793. }
  794. else if (lastAnimation) {
  795. lastAnimation.getKeys()[j].value = value;
  796. }
  797. }
  798. // Finish
  799. if (!modifyKey && babylonAnimation) {
  800. babylonAnimation.setKeys(keys);
  801. targetNode.animations.push(babylonAnimation);
  802. }
  803. lastAnimation = babylonAnimation;
  804. gltfRuntime.scene.stopAnimation(targetNode);
  805. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  806. }
  807. }
  808. };
  809. /**
  810. * Returns the bones transformation matrix
  811. */
  812. var configureBoneTransformation = function (node) {
  813. var mat = null;
  814. if (node.translation || node.rotation || node.scale) {
  815. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  816. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  817. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  818. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  819. }
  820. else {
  821. mat = BABYLON.Matrix.FromArray(node.matrix);
  822. }
  823. return mat;
  824. };
  825. /**
  826. * Returns the parent bone
  827. */
  828. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  829. // Try to find
  830. for (var i = 0; i < newSkeleton.bones.length; i++) {
  831. if (newSkeleton.bones[i].name === jointName) {
  832. return newSkeleton.bones[i];
  833. }
  834. }
  835. // Not found, search in gltf nodes
  836. var nodes = gltfRuntime.nodes;
  837. for (var nde in nodes) {
  838. var node = nodes[nde];
  839. if (!node.jointName) {
  840. continue;
  841. }
  842. var children = node.children;
  843. for (var i = 0; i < children.length; i++) {
  844. var child = gltfRuntime.nodes[children[i]];
  845. if (!child.jointName) {
  846. continue;
  847. }
  848. if (child.jointName === jointName) {
  849. var mat = configureBoneTransformation(node);
  850. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  851. bone.id = nde;
  852. return bone;
  853. }
  854. }
  855. }
  856. return null;
  857. };
  858. /**
  859. * Returns the appropriate root node
  860. */
  861. var getNodeToRoot = function (nodesToRoot, id) {
  862. for (var i = 0; i < nodesToRoot.length; i++) {
  863. var nodeToRoot = nodesToRoot[i];
  864. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  865. var child = nodeToRoot.node.children[j];
  866. if (child === id) {
  867. return nodeToRoot.bone;
  868. }
  869. }
  870. }
  871. return null;
  872. };
  873. /**
  874. * Returns the node with the joint name
  875. */
  876. var getJointNode = function (gltfRuntime, jointName) {
  877. var nodes = gltfRuntime.nodes;
  878. var node = nodes[jointName];
  879. if (node) {
  880. return {
  881. node: node,
  882. id: jointName
  883. };
  884. }
  885. for (var nde in nodes) {
  886. node = nodes[nde];
  887. if (node.jointName === jointName) {
  888. return {
  889. node: node,
  890. id: nde
  891. };
  892. }
  893. }
  894. return null;
  895. };
  896. /**
  897. * Checks if a nodes is in joints
  898. */
  899. var nodeIsInJoints = function (skins, id) {
  900. for (var i = 0; i < skins.jointNames.length; i++) {
  901. if (skins.jointNames[i] === id) {
  902. return true;
  903. }
  904. }
  905. return false;
  906. };
  907. /**
  908. * Fills the nodes to root for bones and builds hierarchy
  909. */
  910. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  911. // Creates nodes for root
  912. for (var nde in gltfRuntime.nodes) {
  913. var node = gltfRuntime.nodes[nde];
  914. var id = nde;
  915. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  916. continue;
  917. }
  918. // Create node to root bone
  919. var mat = configureBoneTransformation(node);
  920. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  921. bone.id = id;
  922. nodesToRoot.push({ bone: bone, node: node, id: id });
  923. }
  924. // Parenting
  925. for (var i = 0; i < nodesToRoot.length; i++) {
  926. var nodeToRoot = nodesToRoot[i];
  927. var children = nodeToRoot.node.children;
  928. for (var j = 0; j < children.length; j++) {
  929. var child = null;
  930. for (var k = 0; k < nodesToRoot.length; k++) {
  931. if (nodesToRoot[k].id === children[j]) {
  932. child = nodesToRoot[k];
  933. break;
  934. }
  935. }
  936. if (child) {
  937. child.bone._parent = nodeToRoot.bone;
  938. nodeToRoot.bone.children.push(child.bone);
  939. }
  940. }
  941. }
  942. };
  943. /**
  944. * Imports a skeleton
  945. */
  946. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  947. if (!newSkeleton) {
  948. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  949. }
  950. if (!skins.babylonSkeleton) {
  951. return newSkeleton;
  952. }
  953. // Find the root bones
  954. var nodesToRoot = [];
  955. var nodesToRootToAdd = [];
  956. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  957. newSkeleton.bones = [];
  958. // Joints
  959. for (var i = 0; i < skins.jointNames.length; i++) {
  960. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  961. if (!jointNode) {
  962. continue;
  963. }
  964. var node = jointNode.node;
  965. if (!node) {
  966. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  967. continue;
  968. }
  969. var id = jointNode.id;
  970. // Optimize, if the bone already exists...
  971. var existingBone = gltfRuntime.scene.getBoneByID(id);
  972. if (existingBone) {
  973. newSkeleton.bones.push(existingBone);
  974. continue;
  975. }
  976. // Search for parent bone
  977. var foundBone = false;
  978. var parentBone = null;
  979. for (var j = 0; j < i; j++) {
  980. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  981. if (!jointNode_1) {
  982. continue;
  983. }
  984. var joint = jointNode_1.node;
  985. if (!joint) {
  986. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  987. continue;
  988. }
  989. var children = joint.children;
  990. if (!children) {
  991. continue;
  992. }
  993. foundBone = false;
  994. for (var k = 0; k < children.length; k++) {
  995. if (children[k] === id) {
  996. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  997. foundBone = true;
  998. break;
  999. }
  1000. }
  1001. if (foundBone) {
  1002. break;
  1003. }
  1004. }
  1005. // Create bone
  1006. var mat = configureBoneTransformation(node);
  1007. if (!parentBone && nodesToRoot.length > 0) {
  1008. parentBone = getNodeToRoot(nodesToRoot, id);
  1009. if (parentBone) {
  1010. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  1011. nodesToRootToAdd.push(parentBone);
  1012. }
  1013. }
  1014. }
  1015. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  1016. bone.id = id;
  1017. }
  1018. // Polish
  1019. var bones = newSkeleton.bones;
  1020. newSkeleton.bones = [];
  1021. for (var i = 0; i < skins.jointNames.length; i++) {
  1022. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1023. if (!jointNode) {
  1024. continue;
  1025. }
  1026. for (var j = 0; j < bones.length; j++) {
  1027. if (bones[j].id === jointNode.id) {
  1028. newSkeleton.bones.push(bones[j]);
  1029. break;
  1030. }
  1031. }
  1032. }
  1033. newSkeleton.prepare();
  1034. // Finish
  1035. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1036. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1037. }
  1038. return newSkeleton;
  1039. };
  1040. /**
  1041. * Imports a mesh and its geometries
  1042. */
  1043. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1044. if (!newMesh) {
  1045. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1046. newMesh.id = id;
  1047. }
  1048. if (!node.babylonNode) {
  1049. return newMesh;
  1050. }
  1051. var subMaterials = [];
  1052. var vertexData = null;
  1053. var verticesStarts = new Array();
  1054. var verticesCounts = new Array();
  1055. var indexStarts = new Array();
  1056. var indexCounts = new Array();
  1057. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1058. var meshID = meshes[meshIndex];
  1059. var mesh = gltfRuntime.meshes[meshID];
  1060. if (!mesh) {
  1061. continue;
  1062. }
  1063. // Positions, normals and UVs
  1064. for (var i = 0; i < mesh.primitives.length; i++) {
  1065. // Temporary vertex data
  1066. var tempVertexData = new BABYLON.VertexData();
  1067. var primitive = mesh.primitives[i];
  1068. if (primitive.mode !== 4) {
  1069. // continue;
  1070. }
  1071. var attributes = primitive.attributes;
  1072. var accessor = null;
  1073. var buffer = null;
  1074. // Set positions, normal and uvs
  1075. for (var semantic in attributes) {
  1076. // Link accessor and buffer view
  1077. accessor = gltfRuntime.accessors[attributes[semantic]];
  1078. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1079. if (semantic === "NORMAL") {
  1080. tempVertexData.normals = new Float32Array(buffer.length);
  1081. tempVertexData.normals.set(buffer);
  1082. }
  1083. else if (semantic === "POSITION") {
  1084. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  1085. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  1086. for (var j = 0; j < buffer.length; j += 4) {
  1087. tempVertexData.positions[j] = buffer[j];
  1088. tempVertexData.positions[j + 1] = buffer[j + 1];
  1089. tempVertexData.positions[j + 2] = buffer[j + 2];
  1090. }
  1091. }
  1092. else {
  1093. tempVertexData.positions = new Float32Array(buffer.length);
  1094. tempVertexData.positions.set(buffer);
  1095. }
  1096. verticesCounts.push(tempVertexData.positions.length);
  1097. }
  1098. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  1099. var channel = Number(semantic.split("_")[1]);
  1100. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  1101. var uvs = new Float32Array(buffer.length);
  1102. uvs.set(buffer);
  1103. normalizeUVs(uvs);
  1104. tempVertexData.set(uvs, uvKind);
  1105. }
  1106. else if (semantic === "JOINT") {
  1107. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  1108. tempVertexData.matricesIndices.set(buffer);
  1109. }
  1110. else if (semantic === "WEIGHT") {
  1111. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  1112. tempVertexData.matricesWeights.set(buffer);
  1113. }
  1114. else if (semantic === "COLOR") {
  1115. tempVertexData.colors = new Float32Array(buffer.length);
  1116. tempVertexData.colors.set(buffer);
  1117. }
  1118. }
  1119. // Indices
  1120. accessor = gltfRuntime.accessors[primitive.indices];
  1121. if (accessor) {
  1122. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1123. tempVertexData.indices = new Int32Array(buffer.length);
  1124. tempVertexData.indices.set(buffer);
  1125. indexCounts.push(tempVertexData.indices.length);
  1126. }
  1127. else {
  1128. // Set indices on the fly
  1129. var indices = [];
  1130. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  1131. indices.push(j);
  1132. }
  1133. tempVertexData.indices = new Int32Array(indices);
  1134. indexCounts.push(tempVertexData.indices.length);
  1135. }
  1136. if (!vertexData) {
  1137. vertexData = tempVertexData;
  1138. }
  1139. else {
  1140. vertexData.merge(tempVertexData);
  1141. }
  1142. // Sub material
  1143. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  1144. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  1145. // Update vertices start and index start
  1146. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  1147. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  1148. }
  1149. }
  1150. var material;
  1151. if (subMaterials.length > 1) {
  1152. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  1153. material.subMaterials = subMaterials;
  1154. }
  1155. else {
  1156. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  1157. }
  1158. if (subMaterials.length === 1) {
  1159. material = subMaterials[0];
  1160. }
  1161. if (!newMesh.material) {
  1162. newMesh.material = material;
  1163. }
  1164. // Apply geometry
  1165. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  1166. newMesh.computeWorldMatrix(true);
  1167. // Apply submeshes
  1168. newMesh.subMeshes = [];
  1169. var index = 0;
  1170. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1171. var meshID = meshes[meshIndex];
  1172. var mesh = gltfRuntime.meshes[meshID];
  1173. if (!mesh) {
  1174. continue;
  1175. }
  1176. for (var i = 0; i < mesh.primitives.length; i++) {
  1177. if (mesh.primitives[i].mode !== 4) {
  1178. //continue;
  1179. }
  1180. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  1181. index++;
  1182. }
  1183. }
  1184. // Finish
  1185. return newMesh;
  1186. };
  1187. /**
  1188. * Configure node transformation from position, rotation and scaling
  1189. */
  1190. var configureNode = function (newNode, position, rotation, scaling) {
  1191. if (newNode.position) {
  1192. newNode.position = position;
  1193. }
  1194. if (newNode.rotationQuaternion || newNode.rotation) {
  1195. newNode.rotationQuaternion = rotation;
  1196. }
  1197. if (newNode.scaling) {
  1198. newNode.scaling = scaling;
  1199. }
  1200. };
  1201. /**
  1202. * Configures node from transformation matrix
  1203. */
  1204. var configureNodeFromMatrix = function (newNode, node, parent) {
  1205. if (node.matrix) {
  1206. var position = new BABYLON.Vector3(0, 0, 0);
  1207. var rotation = new BABYLON.Quaternion();
  1208. var scaling = new BABYLON.Vector3(0, 0, 0);
  1209. var mat = BABYLON.Matrix.FromArray(node.matrix);
  1210. mat.decompose(scaling, rotation, position);
  1211. configureNode(newNode, position, rotation, scaling);
  1212. }
  1213. else if (node.translation && node.rotation && node.scale) {
  1214. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  1215. }
  1216. newNode.computeWorldMatrix(true);
  1217. };
  1218. /**
  1219. * Imports a node
  1220. */
  1221. var importNode = function (gltfRuntime, node, id, parent) {
  1222. var lastNode = null;
  1223. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  1224. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  1225. return null;
  1226. }
  1227. }
  1228. // Meshes
  1229. if (node.skin) {
  1230. if (node.meshes) {
  1231. var skin = gltfRuntime.skins[node.skin];
  1232. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1233. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1234. if (newMesh.skeleton === null) {
  1235. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1236. if (!skin.babylonSkeleton) {
  1237. skin.babylonSkeleton = newMesh.skeleton;
  1238. }
  1239. }
  1240. lastNode = newMesh;
  1241. }
  1242. }
  1243. else if (node.meshes) {
  1244. /**
  1245. * Improve meshes property
  1246. */
  1247. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1248. lastNode = newMesh;
  1249. }
  1250. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1251. var light = gltfRuntime.lights[node.light];
  1252. if (light) {
  1253. if (light.type === "ambient") {
  1254. var ambienLight = light[light.type];
  1255. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1256. hemiLight.name = node.name || "";
  1257. if (ambienLight.color) {
  1258. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1259. }
  1260. lastNode = hemiLight;
  1261. }
  1262. else if (light.type === "directional") {
  1263. var directionalLight = light[light.type];
  1264. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1265. dirLight.name = node.name || "";
  1266. if (directionalLight.color) {
  1267. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1268. }
  1269. lastNode = dirLight;
  1270. }
  1271. else if (light.type === "point") {
  1272. var pointLight = light[light.type];
  1273. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1274. ptLight.name = node.name || "";
  1275. if (pointLight.color) {
  1276. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1277. }
  1278. lastNode = ptLight;
  1279. }
  1280. else if (light.type === "spot") {
  1281. var spotLight = light[light.type];
  1282. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1283. spLight.name = node.name || "";
  1284. if (spotLight.color) {
  1285. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1286. }
  1287. if (spotLight.fallOfAngle) {
  1288. spLight.angle = spotLight.fallOfAngle;
  1289. }
  1290. if (spotLight.fallOffExponent) {
  1291. spLight.exponent = spotLight.fallOffExponent;
  1292. }
  1293. lastNode = spLight;
  1294. }
  1295. }
  1296. }
  1297. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1298. var camera = gltfRuntime.cameras[node.camera];
  1299. if (camera) {
  1300. if (camera.type === "orthographic") {
  1301. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1302. orthoCamera.name = node.name || "";
  1303. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1304. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1305. lastNode = orthoCamera;
  1306. }
  1307. else if (camera.type === "perspective") {
  1308. var perspectiveCamera = camera[camera.type];
  1309. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1310. persCamera.name = node.name || "";
  1311. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1312. if (!perspectiveCamera.aspectRatio) {
  1313. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1314. }
  1315. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1316. persCamera.maxZ = perspectiveCamera.zfar;
  1317. persCamera.minZ = perspectiveCamera.znear;
  1318. }
  1319. lastNode = persCamera;
  1320. }
  1321. }
  1322. }
  1323. // Empty node
  1324. if (!node.jointName) {
  1325. if (node.babylonNode) {
  1326. return node.babylonNode;
  1327. }
  1328. else if (lastNode === null) {
  1329. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1330. node.babylonNode = dummy;
  1331. lastNode = dummy;
  1332. }
  1333. }
  1334. if (lastNode !== null) {
  1335. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1336. configureNodeFromMatrix(lastNode, node, parent);
  1337. }
  1338. else {
  1339. var translation = node.translation || [0, 0, 0];
  1340. var rotation = node.rotation || [0, 0, 0, 1];
  1341. var scale = node.scale || [1, 1, 1];
  1342. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1343. }
  1344. lastNode.updateCache(true);
  1345. node.babylonNode = lastNode;
  1346. }
  1347. return lastNode;
  1348. };
  1349. /**
  1350. * Traverses nodes and creates them
  1351. */
  1352. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1353. if (meshIncluded === void 0) { meshIncluded = false; }
  1354. var node = gltfRuntime.nodes[id];
  1355. var newNode = null;
  1356. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1357. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1358. meshIncluded = true;
  1359. }
  1360. else {
  1361. meshIncluded = false;
  1362. }
  1363. }
  1364. else {
  1365. meshIncluded = true;
  1366. }
  1367. if (!node.jointName && meshIncluded) {
  1368. newNode = importNode(gltfRuntime, node, id, parent);
  1369. if (newNode !== null) {
  1370. newNode.id = id;
  1371. newNode.parent = parent;
  1372. }
  1373. }
  1374. if (node.children) {
  1375. for (var i = 0; i < node.children.length; i++) {
  1376. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1377. }
  1378. }
  1379. };
  1380. /**
  1381. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1382. */
  1383. var postLoad = function (gltfRuntime) {
  1384. // Nodes
  1385. var currentScene = gltfRuntime.currentScene;
  1386. if (currentScene) {
  1387. for (var i = 0; i < currentScene.nodes.length; i++) {
  1388. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1389. }
  1390. }
  1391. else {
  1392. for (var thing in gltfRuntime.scenes) {
  1393. currentScene = gltfRuntime.scenes[thing];
  1394. for (var i = 0; i < currentScene.nodes.length; i++) {
  1395. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1396. }
  1397. }
  1398. }
  1399. // Set animations
  1400. loadAnimations(gltfRuntime);
  1401. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1402. var skeleton = gltfRuntime.scene.skeletons[i];
  1403. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1404. }
  1405. };
  1406. /**
  1407. * onBind shaderrs callback to set uniforms and matrices
  1408. */
  1409. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1410. var materialValues = material.values || technique.parameters;
  1411. for (var unif in unTreatedUniforms) {
  1412. var uniform = unTreatedUniforms[unif];
  1413. var type = uniform.type;
  1414. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1415. if (uniform.semantic && !uniform.source && !uniform.node) {
  1416. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1417. }
  1418. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1419. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1420. if (source === null) {
  1421. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1422. }
  1423. if (source === null) {
  1424. continue;
  1425. }
  1426. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1427. }
  1428. }
  1429. else {
  1430. var value = materialValues[technique.uniforms[unif]];
  1431. if (!value) {
  1432. continue;
  1433. }
  1434. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1435. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1436. if (texture === null || texture === undefined) {
  1437. continue;
  1438. }
  1439. shaderMaterial.getEffect().setTexture(unif, texture);
  1440. }
  1441. else {
  1442. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1443. }
  1444. }
  1445. }
  1446. onSuccess(shaderMaterial);
  1447. };
  1448. /**
  1449. * Prepare uniforms to send the only one time
  1450. * Loads the appropriate textures
  1451. */
  1452. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1453. var materialValues = material.values || technique.parameters;
  1454. var techniqueUniforms = technique.uniforms;
  1455. /**
  1456. * Prepare values here (not matrices)
  1457. */
  1458. for (var unif in unTreatedUniforms) {
  1459. var uniform = unTreatedUniforms[unif];
  1460. var type = uniform.type;
  1461. var value = materialValues[techniqueUniforms[unif]];
  1462. if (value === undefined) {
  1463. // In case the value is the same for all materials
  1464. value = uniform.value;
  1465. }
  1466. if (!value) {
  1467. continue;
  1468. }
  1469. var onLoadTexture = function (uniformName) {
  1470. return function (texture) {
  1471. if (uniform.value && uniformName) {
  1472. // Static uniform
  1473. shaderMaterial.setTexture(uniformName, texture);
  1474. delete unTreatedUniforms[uniformName];
  1475. }
  1476. };
  1477. };
  1478. // Texture (sampler2D)
  1479. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1480. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1481. }
  1482. else {
  1483. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1484. // Static uniform
  1485. delete unTreatedUniforms[unif];
  1486. }
  1487. }
  1488. }
  1489. };
  1490. /**
  1491. * Shader compilation failed
  1492. */
  1493. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1494. return function (effect, error) {
  1495. shaderMaterial.dispose(true);
  1496. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1497. };
  1498. };
  1499. /**
  1500. * Shader compilation success
  1501. */
  1502. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1503. return function (_) {
  1504. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1505. shaderMaterial.onBind = function (mesh) {
  1506. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1507. };
  1508. };
  1509. };
  1510. /**
  1511. * Returns the appropriate uniform if already handled by babylon
  1512. */
  1513. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1514. for (var unif in technique.uniforms) {
  1515. var uniform = technique.uniforms[unif];
  1516. var uniformParameter = technique.parameters[uniform];
  1517. if (tokenizer.currentIdentifier === unif) {
  1518. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1519. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1520. if (transformIndex !== -1) {
  1521. delete unTreatedUniforms[unif];
  1522. return babylonTransforms[transformIndex];
  1523. }
  1524. }
  1525. }
  1526. }
  1527. return tokenizer.currentIdentifier;
  1528. };
  1529. /**
  1530. * All shaders loaded. Create materials one by one
  1531. */
  1532. var importMaterials = function (gltfRuntime) {
  1533. // Create materials
  1534. for (var mat in gltfRuntime.materials) {
  1535. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1536. }
  1537. };
  1538. /**
  1539. * Implementation of the base glTF spec
  1540. */
  1541. var GLTFLoaderBase = /** @class */ (function () {
  1542. function GLTFLoaderBase() {
  1543. }
  1544. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1545. var gltfRuntime = {
  1546. extensions: {},
  1547. accessors: {},
  1548. buffers: {},
  1549. bufferViews: {},
  1550. meshes: {},
  1551. lights: {},
  1552. cameras: {},
  1553. nodes: {},
  1554. images: {},
  1555. textures: {},
  1556. shaders: {},
  1557. programs: {},
  1558. samplers: {},
  1559. techniques: {},
  1560. materials: {},
  1561. animations: {},
  1562. skins: {},
  1563. extensionsUsed: [],
  1564. scenes: {},
  1565. buffersCount: 0,
  1566. shaderscount: 0,
  1567. scene: scene,
  1568. rootUrl: rootUrl,
  1569. loadedBufferCount: 0,
  1570. loadedBufferViews: {},
  1571. loadedShaderCount: 0,
  1572. importOnlyMeshes: false,
  1573. dummyNodes: []
  1574. };
  1575. // Parse
  1576. if (parsedData.extensions) {
  1577. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1578. }
  1579. if (parsedData.extensionsUsed) {
  1580. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1581. }
  1582. if (parsedData.buffers) {
  1583. parseBuffers(parsedData.buffers, gltfRuntime);
  1584. }
  1585. if (parsedData.bufferViews) {
  1586. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1587. }
  1588. if (parsedData.accessors) {
  1589. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1590. }
  1591. if (parsedData.meshes) {
  1592. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1593. }
  1594. if (parsedData.lights) {
  1595. parseObject(parsedData.lights, "lights", gltfRuntime);
  1596. }
  1597. if (parsedData.cameras) {
  1598. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1599. }
  1600. if (parsedData.nodes) {
  1601. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1602. }
  1603. if (parsedData.images) {
  1604. parseObject(parsedData.images, "images", gltfRuntime);
  1605. }
  1606. if (parsedData.textures) {
  1607. parseObject(parsedData.textures, "textures", gltfRuntime);
  1608. }
  1609. if (parsedData.shaders) {
  1610. parseShaders(parsedData.shaders, gltfRuntime);
  1611. }
  1612. if (parsedData.programs) {
  1613. parseObject(parsedData.programs, "programs", gltfRuntime);
  1614. }
  1615. if (parsedData.samplers) {
  1616. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1617. }
  1618. if (parsedData.techniques) {
  1619. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1620. }
  1621. if (parsedData.materials) {
  1622. parseObject(parsedData.materials, "materials", gltfRuntime);
  1623. }
  1624. if (parsedData.animations) {
  1625. parseObject(parsedData.animations, "animations", gltfRuntime);
  1626. }
  1627. if (parsedData.skins) {
  1628. parseObject(parsedData.skins, "skins", gltfRuntime);
  1629. }
  1630. if (parsedData.scenes) {
  1631. gltfRuntime.scenes = parsedData.scenes;
  1632. }
  1633. if (parsedData.scene && parsedData.scenes) {
  1634. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1635. }
  1636. return gltfRuntime;
  1637. };
  1638. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1639. var buffer = gltfRuntime.buffers[id];
  1640. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  1641. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  1642. }
  1643. else {
  1644. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1645. if (request) {
  1646. onError(request.status + " " + request.statusText);
  1647. }
  1648. });
  1649. }
  1650. };
  1651. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1652. var texture = gltfRuntime.textures[id];
  1653. if (!texture || !texture.source) {
  1654. onError("");
  1655. return;
  1656. }
  1657. if (texture.babylonTexture) {
  1658. onSuccess(null);
  1659. return;
  1660. }
  1661. var source = gltfRuntime.images[texture.source];
  1662. if (BABYLON.Tools.IsBase64(source.uri)) {
  1663. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  1664. }
  1665. else {
  1666. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1667. if (request) {
  1668. onError(request.status + " " + request.statusText);
  1669. }
  1670. });
  1671. }
  1672. };
  1673. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1674. var texture = gltfRuntime.textures[id];
  1675. if (texture.babylonTexture) {
  1676. onSuccess(texture.babylonTexture);
  1677. return;
  1678. }
  1679. var sampler = gltfRuntime.samplers[texture.sampler];
  1680. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1681. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1682. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1683. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1684. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1685. var blob = new Blob([buffer]);
  1686. var blobURL = URL.createObjectURL(blob);
  1687. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1688. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1689. if (sampler.wrapS !== undefined) {
  1690. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1691. }
  1692. if (sampler.wrapT !== undefined) {
  1693. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1694. }
  1695. newTexture.name = id;
  1696. texture.babylonTexture = newTexture;
  1697. onSuccess(newTexture);
  1698. };
  1699. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1700. var shader = gltfRuntime.shaders[id];
  1701. if (BABYLON.Tools.IsBase64(shader.uri)) {
  1702. var shaderString = atob(shader.uri.split(",")[1]);
  1703. if (onSuccess) {
  1704. onSuccess(shaderString);
  1705. }
  1706. }
  1707. else {
  1708. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1709. if (request && onError) {
  1710. onError(request.status + " " + request.statusText);
  1711. }
  1712. });
  1713. }
  1714. };
  1715. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1716. var material = gltfRuntime.materials[id];
  1717. if (!material.technique) {
  1718. if (onError) {
  1719. onError("No technique found.");
  1720. }
  1721. return;
  1722. }
  1723. var technique = gltfRuntime.techniques[material.technique];
  1724. if (!technique) {
  1725. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1726. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1727. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1728. onSuccess(defaultMaterial);
  1729. return;
  1730. }
  1731. var program = gltfRuntime.programs[technique.program];
  1732. var states = technique.states;
  1733. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1734. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1735. var newVertexShader = "";
  1736. var newPixelShader = "";
  1737. var vertexTokenizer = new Tokenizer(vertexShader);
  1738. var pixelTokenizer = new Tokenizer(pixelShader);
  1739. var unTreatedUniforms = {};
  1740. var uniforms = [];
  1741. var attributes = [];
  1742. var samplers = [];
  1743. // Fill uniform, sampler2D and attributes
  1744. for (var unif in technique.uniforms) {
  1745. var uniform = technique.uniforms[unif];
  1746. var uniformParameter = technique.parameters[uniform];
  1747. unTreatedUniforms[unif] = uniformParameter;
  1748. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1749. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1750. if (transformIndex !== -1) {
  1751. uniforms.push(babylonTransforms[transformIndex]);
  1752. delete unTreatedUniforms[unif];
  1753. }
  1754. else {
  1755. uniforms.push(unif);
  1756. }
  1757. }
  1758. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1759. samplers.push(unif);
  1760. }
  1761. else {
  1762. uniforms.push(unif);
  1763. }
  1764. }
  1765. for (var attr in technique.attributes) {
  1766. var attribute = technique.attributes[attr];
  1767. var attributeParameter = technique.parameters[attribute];
  1768. if (attributeParameter.semantic) {
  1769. attributes.push(getAttribute(attributeParameter));
  1770. }
  1771. }
  1772. // Configure vertex shader
  1773. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1774. var tokenType = vertexTokenizer.currentToken;
  1775. if (tokenType !== ETokenType.IDENTIFIER) {
  1776. newVertexShader += vertexTokenizer.currentString;
  1777. continue;
  1778. }
  1779. var foundAttribute = false;
  1780. for (var attr in technique.attributes) {
  1781. var attribute = technique.attributes[attr];
  1782. var attributeParameter = technique.parameters[attribute];
  1783. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1784. newVertexShader += getAttribute(attributeParameter);
  1785. foundAttribute = true;
  1786. break;
  1787. }
  1788. }
  1789. if (foundAttribute) {
  1790. continue;
  1791. }
  1792. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1793. }
  1794. // Configure pixel shader
  1795. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1796. var tokenType = pixelTokenizer.currentToken;
  1797. if (tokenType !== ETokenType.IDENTIFIER) {
  1798. newPixelShader += pixelTokenizer.currentString;
  1799. continue;
  1800. }
  1801. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1802. }
  1803. // Create shader material
  1804. var shaderPath = {
  1805. vertex: program.vertexShader + id,
  1806. fragment: program.fragmentShader + id
  1807. };
  1808. var options = {
  1809. attributes: attributes,
  1810. uniforms: uniforms,
  1811. samplers: samplers,
  1812. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1813. };
  1814. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1815. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1816. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1817. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1818. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1819. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1820. if (states && states.functions) {
  1821. var functions = states.functions;
  1822. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1823. shaderMaterial.backFaceCulling = false;
  1824. }
  1825. var blendFunc = functions.blendFuncSeparate;
  1826. if (blendFunc) {
  1827. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1828. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1829. }
  1830. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1831. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1832. }
  1833. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1834. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1835. }
  1836. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1837. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1838. }
  1839. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1840. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1841. }
  1842. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1843. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1844. }
  1845. }
  1846. }
  1847. };
  1848. return GLTFLoaderBase;
  1849. }());
  1850. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1851. /**
  1852. * glTF V1 Loader
  1853. */
  1854. var GLTFLoader = /** @class */ (function () {
  1855. function GLTFLoader() {
  1856. // #region Stubs for IGLTFLoader interface
  1857. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  1858. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  1859. this.compileMaterials = false;
  1860. this.useClipPlane = false;
  1861. this.compileShadowGenerators = false;
  1862. this.onDisposeObservable = new BABYLON.Observable();
  1863. this.onMeshLoadedObservable = new BABYLON.Observable();
  1864. this.onTextureLoadedObservable = new BABYLON.Observable();
  1865. this.onMaterialLoadedObservable = new BABYLON.Observable();
  1866. this.onCompleteObservable = new BABYLON.Observable();
  1867. this.onExtensionLoadedObservable = new BABYLON.Observable();
  1868. this.state = null;
  1869. }
  1870. GLTFLoader.RegisterExtension = function (extension) {
  1871. if (GLTFLoader.Extensions[extension.name]) {
  1872. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1873. return;
  1874. }
  1875. GLTFLoader.Extensions[extension.name] = extension;
  1876. };
  1877. GLTFLoader.prototype.dispose = function () { };
  1878. // #endregion
  1879. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1880. var _this = this;
  1881. scene.useRightHandedSystem = true;
  1882. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1883. gltfRuntime.importOnlyMeshes = true;
  1884. if (meshesNames === "") {
  1885. gltfRuntime.importMeshesNames = [];
  1886. }
  1887. else if (typeof meshesNames === "string") {
  1888. gltfRuntime.importMeshesNames = [meshesNames];
  1889. }
  1890. else if (meshesNames && !(meshesNames instanceof Array)) {
  1891. gltfRuntime.importMeshesNames = [meshesNames];
  1892. }
  1893. else {
  1894. gltfRuntime.importMeshesNames = [];
  1895. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1896. }
  1897. // Create nodes
  1898. _this._createNodes(gltfRuntime);
  1899. var meshes = new Array();
  1900. var skeletons = new Array();
  1901. // Fill arrays of meshes and skeletons
  1902. for (var nde in gltfRuntime.nodes) {
  1903. var node = gltfRuntime.nodes[nde];
  1904. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1905. meshes.push(node.babylonNode);
  1906. }
  1907. }
  1908. for (var skl in gltfRuntime.skins) {
  1909. var skin = gltfRuntime.skins[skl];
  1910. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1911. skeletons.push(skin.babylonSkeleton);
  1912. }
  1913. }
  1914. // Load buffers, shaders, materials, etc.
  1915. _this._loadBuffersAsync(gltfRuntime, function () {
  1916. _this._loadShadersAsync(gltfRuntime, function () {
  1917. importMaterials(gltfRuntime);
  1918. postLoad(gltfRuntime);
  1919. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1920. onSuccess(meshes, skeletons);
  1921. }
  1922. });
  1923. }, onProgress);
  1924. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1925. onSuccess(meshes, skeletons);
  1926. }
  1927. }, onError);
  1928. return true;
  1929. };
  1930. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1931. var _this = this;
  1932. return new Promise(function (resolve, reject) {
  1933. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  1934. resolve({
  1935. meshes: meshes,
  1936. particleSystems: [],
  1937. skeletons: skeletons,
  1938. animationGroups: []
  1939. });
  1940. }, onProgress, function (message) {
  1941. reject(new Error(message));
  1942. });
  1943. });
  1944. };
  1945. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1946. var _this = this;
  1947. scene.useRightHandedSystem = true;
  1948. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1949. // Load runtime extensios
  1950. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1951. // Create nodes
  1952. _this._createNodes(gltfRuntime);
  1953. // Load buffers, shaders, materials, etc.
  1954. _this._loadBuffersAsync(gltfRuntime, function () {
  1955. _this._loadShadersAsync(gltfRuntime, function () {
  1956. importMaterials(gltfRuntime);
  1957. postLoad(gltfRuntime);
  1958. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1959. onSuccess();
  1960. }
  1961. });
  1962. });
  1963. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1964. onSuccess();
  1965. }
  1966. }, onError);
  1967. }, onError);
  1968. };
  1969. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1970. var _this = this;
  1971. return new Promise(function (resolve, reject) {
  1972. _this._loadAsync(scene, data, rootUrl, function () {
  1973. resolve();
  1974. }, onProgress, function (message) {
  1975. reject(new Error(message));
  1976. });
  1977. });
  1978. };
  1979. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1980. var hasShaders = false;
  1981. var processShader = function (sha, shader) {
  1982. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1983. if (shaderString instanceof ArrayBuffer) {
  1984. return;
  1985. }
  1986. gltfRuntime.loadedShaderCount++;
  1987. if (shaderString) {
  1988. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1989. }
  1990. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1991. onload();
  1992. }
  1993. }, function () {
  1994. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1995. });
  1996. };
  1997. for (var sha in gltfRuntime.shaders) {
  1998. hasShaders = true;
  1999. var shader = gltfRuntime.shaders[sha];
  2000. if (shader) {
  2001. processShader.bind(this, sha, shader)();
  2002. }
  2003. else {
  2004. BABYLON.Tools.Error("No shader named: " + sha);
  2005. }
  2006. }
  2007. if (!hasShaders) {
  2008. onload();
  2009. }
  2010. };
  2011. ;
  2012. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  2013. var hasBuffers = false;
  2014. var processBuffer = function (buf, buffer) {
  2015. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  2016. gltfRuntime.loadedBufferCount++;
  2017. if (bufferView) {
  2018. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  2019. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  2020. }
  2021. gltfRuntime.loadedBufferViews[buf] = bufferView;
  2022. }
  2023. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  2024. onLoad();
  2025. }
  2026. }, function () {
  2027. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  2028. });
  2029. };
  2030. for (var buf in gltfRuntime.buffers) {
  2031. hasBuffers = true;
  2032. var buffer = gltfRuntime.buffers[buf];
  2033. if (buffer) {
  2034. processBuffer.bind(this, buf, buffer)();
  2035. }
  2036. else {
  2037. BABYLON.Tools.Error("No buffer named: " + buf);
  2038. }
  2039. }
  2040. if (!hasBuffers) {
  2041. onLoad();
  2042. }
  2043. };
  2044. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2045. var currentScene = gltfRuntime.currentScene;
  2046. if (currentScene) {
  2047. // Only one scene even if multiple scenes are defined
  2048. for (var i = 0; i < currentScene.nodes.length; i++) {
  2049. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2050. }
  2051. }
  2052. else {
  2053. // Load all scenes
  2054. for (var thing in gltfRuntime.scenes) {
  2055. currentScene = gltfRuntime.scenes[thing];
  2056. for (var i = 0; i < currentScene.nodes.length; i++) {
  2057. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2058. }
  2059. }
  2060. }
  2061. };
  2062. GLTFLoader.Extensions = {};
  2063. return GLTFLoader;
  2064. }());
  2065. GLTF1.GLTFLoader = GLTFLoader;
  2066. ;
  2067. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2068. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2069. })(BABYLON || (BABYLON = {}));
  2070. //# sourceMappingURL=babylon.glTFLoader.js.map
  2071. "use strict";
  2072. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2073. var BABYLON;
  2074. (function (BABYLON) {
  2075. var GLTF1;
  2076. (function (GLTF1) {
  2077. /**
  2078. * Utils functions for GLTF
  2079. */
  2080. var GLTFUtils = /** @class */ (function () {
  2081. function GLTFUtils() {
  2082. }
  2083. /**
  2084. * Sets the given "parameter" matrix
  2085. * @param scene: the {BABYLON.Scene} object
  2086. * @param source: the source node where to pick the matrix
  2087. * @param parameter: the GLTF technique parameter
  2088. * @param uniformName: the name of the shader's uniform
  2089. * @param shaderMaterial: the shader material
  2090. */
  2091. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2092. var mat = null;
  2093. if (parameter.semantic === "MODEL") {
  2094. mat = source.getWorldMatrix();
  2095. }
  2096. else if (parameter.semantic === "PROJECTION") {
  2097. mat = scene.getProjectionMatrix();
  2098. }
  2099. else if (parameter.semantic === "VIEW") {
  2100. mat = scene.getViewMatrix();
  2101. }
  2102. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2103. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2104. }
  2105. else if (parameter.semantic === "MODELVIEW") {
  2106. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2107. }
  2108. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2109. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2110. }
  2111. else if (parameter.semantic === "MODELINVERSE") {
  2112. mat = source.getWorldMatrix().invert();
  2113. }
  2114. else if (parameter.semantic === "VIEWINVERSE") {
  2115. mat = scene.getViewMatrix().invert();
  2116. }
  2117. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2118. mat = scene.getProjectionMatrix().invert();
  2119. }
  2120. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2121. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2122. }
  2123. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2124. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2125. }
  2126. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2127. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2128. }
  2129. else {
  2130. debugger;
  2131. }
  2132. if (mat) {
  2133. switch (parameter.type) {
  2134. case GLTF1.EParameterType.FLOAT_MAT2:
  2135. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2136. break;
  2137. case GLTF1.EParameterType.FLOAT_MAT3:
  2138. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2139. break;
  2140. case GLTF1.EParameterType.FLOAT_MAT4:
  2141. shaderMaterial.setMatrix(uniformName, mat);
  2142. break;
  2143. default: break;
  2144. }
  2145. }
  2146. };
  2147. /**
  2148. * Sets the given "parameter" matrix
  2149. * @param shaderMaterial: the shader material
  2150. * @param uniform: the name of the shader's uniform
  2151. * @param value: the value of the uniform
  2152. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2153. */
  2154. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2155. switch (type) {
  2156. case GLTF1.EParameterType.FLOAT:
  2157. shaderMaterial.setFloat(uniform, value);
  2158. return true;
  2159. case GLTF1.EParameterType.FLOAT_VEC2:
  2160. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2161. return true;
  2162. case GLTF1.EParameterType.FLOAT_VEC3:
  2163. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2164. return true;
  2165. case GLTF1.EParameterType.FLOAT_VEC4:
  2166. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2167. return true;
  2168. default: return false;
  2169. }
  2170. };
  2171. /**
  2172. * Returns the wrap mode of the texture
  2173. * @param mode: the mode value
  2174. */
  2175. GLTFUtils.GetWrapMode = function (mode) {
  2176. switch (mode) {
  2177. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2178. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2179. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2180. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2181. }
  2182. };
  2183. /**
  2184. * Returns the byte stride giving an accessor
  2185. * @param accessor: the GLTF accessor objet
  2186. */
  2187. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2188. // Needs this function since "byteStride" isn't requiered in glTF format
  2189. var type = accessor.type;
  2190. switch (type) {
  2191. case "VEC2": return 2;
  2192. case "VEC3": return 3;
  2193. case "VEC4": return 4;
  2194. case "MAT2": return 4;
  2195. case "MAT3": return 9;
  2196. case "MAT4": return 16;
  2197. default: return 1;
  2198. }
  2199. };
  2200. /**
  2201. * Returns the texture filter mode giving a mode value
  2202. * @param mode: the filter mode value
  2203. */
  2204. GLTFUtils.GetTextureFilterMode = function (mode) {
  2205. switch (mode) {
  2206. case GLTF1.ETextureFilterType.LINEAR:
  2207. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2208. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2209. case GLTF1.ETextureFilterType.NEAREST:
  2210. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2211. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2212. }
  2213. };
  2214. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2215. var byteOffset = bufferView.byteOffset + byteOffset;
  2216. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2217. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2218. throw new Error("Buffer access is out of range");
  2219. }
  2220. var buffer = loadedBufferView.buffer;
  2221. byteOffset += loadedBufferView.byteOffset;
  2222. switch (componentType) {
  2223. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2224. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2225. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2226. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2227. default: return new Float32Array(buffer, byteOffset, byteLength);
  2228. }
  2229. };
  2230. /**
  2231. * Returns a buffer from its accessor
  2232. * @param gltfRuntime: the GLTF runtime
  2233. * @param accessor: the GLTF accessor
  2234. */
  2235. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2236. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2237. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2238. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2239. };
  2240. /**
  2241. * Decodes a buffer view into a string
  2242. * @param view: the buffer view
  2243. */
  2244. GLTFUtils.DecodeBufferToText = function (view) {
  2245. var result = "";
  2246. var length = view.byteLength;
  2247. for (var i = 0; i < length; ++i) {
  2248. result += String.fromCharCode(view[i]);
  2249. }
  2250. return result;
  2251. };
  2252. /**
  2253. * Returns the default material of gltf. Related to
  2254. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2255. * @param scene: the Babylon.js scene
  2256. */
  2257. GLTFUtils.GetDefaultMaterial = function (scene) {
  2258. if (!GLTFUtils._DefaultMaterial) {
  2259. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2260. "precision highp float;",
  2261. "",
  2262. "uniform mat4 worldView;",
  2263. "uniform mat4 projection;",
  2264. "",
  2265. "attribute vec3 position;",
  2266. "",
  2267. "void main(void)",
  2268. "{",
  2269. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2270. "}"
  2271. ].join("\n");
  2272. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2273. "precision highp float;",
  2274. "",
  2275. "uniform vec4 u_emission;",
  2276. "",
  2277. "void main(void)",
  2278. "{",
  2279. " gl_FragColor = u_emission;",
  2280. "}"
  2281. ].join("\n");
  2282. var shaderPath = {
  2283. vertex: "GLTFDefaultMaterial",
  2284. fragment: "GLTFDefaultMaterial"
  2285. };
  2286. var options = {
  2287. attributes: ["position"],
  2288. uniforms: ["worldView", "projection", "u_emission"],
  2289. samplers: new Array(),
  2290. needAlphaBlending: false
  2291. };
  2292. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2293. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2294. }
  2295. return GLTFUtils._DefaultMaterial;
  2296. };
  2297. // The GLTF default material
  2298. GLTFUtils._DefaultMaterial = null;
  2299. return GLTFUtils;
  2300. }());
  2301. GLTF1.GLTFUtils = GLTFUtils;
  2302. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2303. })(BABYLON || (BABYLON = {}));
  2304. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2305. "use strict";
  2306. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2307. var BABYLON;
  2308. (function (BABYLON) {
  2309. var GLTF1;
  2310. (function (GLTF1) {
  2311. var GLTFLoaderExtension = /** @class */ (function () {
  2312. function GLTFLoaderExtension(name) {
  2313. this._name = name;
  2314. }
  2315. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2316. get: function () {
  2317. return this._name;
  2318. },
  2319. enumerable: true,
  2320. configurable: true
  2321. });
  2322. /**
  2323. * Defines an override for loading the runtime
  2324. * Return true to stop further extensions from loading the runtime
  2325. */
  2326. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2327. return false;
  2328. };
  2329. /**
  2330. * Defines an onverride for creating gltf runtime
  2331. * Return true to stop further extensions from creating the runtime
  2332. */
  2333. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2334. return false;
  2335. };
  2336. /**
  2337. * Defines an override for loading buffers
  2338. * Return true to stop further extensions from loading this buffer
  2339. */
  2340. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2341. return false;
  2342. };
  2343. /**
  2344. * Defines an override for loading texture buffers
  2345. * Return true to stop further extensions from loading this texture data
  2346. */
  2347. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2348. return false;
  2349. };
  2350. /**
  2351. * Defines an override for creating textures
  2352. * Return true to stop further extensions from loading this texture
  2353. */
  2354. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2355. return false;
  2356. };
  2357. /**
  2358. * Defines an override for loading shader strings
  2359. * Return true to stop further extensions from loading this shader data
  2360. */
  2361. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2362. return false;
  2363. };
  2364. /**
  2365. * Defines an override for loading materials
  2366. * Return true to stop further extensions from loading this material
  2367. */
  2368. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2369. return false;
  2370. };
  2371. // ---------
  2372. // Utilities
  2373. // ---------
  2374. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2375. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2376. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2377. }, function () {
  2378. setTimeout(function () {
  2379. if (!onSuccess) {
  2380. return;
  2381. }
  2382. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2383. });
  2384. });
  2385. };
  2386. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2387. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2388. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2389. }, function () {
  2390. setTimeout(function () {
  2391. onSuccess();
  2392. });
  2393. });
  2394. };
  2395. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2396. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2397. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2398. }, function () {
  2399. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2400. });
  2401. };
  2402. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2403. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2404. if (buffer) {
  2405. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2406. }
  2407. }, onError);
  2408. };
  2409. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2410. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2411. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2412. }, function () {
  2413. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2414. });
  2415. };
  2416. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2417. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2418. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2419. }, function () {
  2420. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2421. });
  2422. };
  2423. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2424. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2425. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2426. }, function () {
  2427. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2428. });
  2429. };
  2430. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2431. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2432. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2433. }, function () {
  2434. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2435. });
  2436. };
  2437. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2438. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2439. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2440. if (func(loaderExtension)) {
  2441. return;
  2442. }
  2443. }
  2444. defaultFunc();
  2445. };
  2446. return GLTFLoaderExtension;
  2447. }());
  2448. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2449. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2450. })(BABYLON || (BABYLON = {}));
  2451. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2452. "use strict";
  2453. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2454. var __extends = (this && this.__extends) || (function () {
  2455. var extendStatics = Object.setPrototypeOf ||
  2456. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2457. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2458. return function (d, b) {
  2459. extendStatics(d, b);
  2460. function __() { this.constructor = d; }
  2461. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2462. };
  2463. })();
  2464. var BABYLON;
  2465. (function (BABYLON) {
  2466. var GLTF1;
  2467. (function (GLTF1) {
  2468. var BinaryExtensionBufferName = "binary_glTF";
  2469. ;
  2470. ;
  2471. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2472. __extends(GLTFBinaryExtension, _super);
  2473. function GLTFBinaryExtension() {
  2474. return _super.call(this, "KHR_binary_glTF") || this;
  2475. }
  2476. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2477. var extensionsUsed = data.json.extensionsUsed;
  2478. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2479. return false;
  2480. }
  2481. this._bin = data.bin;
  2482. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2483. return true;
  2484. };
  2485. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2486. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2487. return false;
  2488. }
  2489. if (id !== BinaryExtensionBufferName) {
  2490. return false;
  2491. }
  2492. onSuccess(this._bin);
  2493. return true;
  2494. };
  2495. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2496. var texture = gltfRuntime.textures[id];
  2497. var source = gltfRuntime.images[texture.source];
  2498. if (!source.extensions || !(this.name in source.extensions)) {
  2499. return false;
  2500. }
  2501. var sourceExt = source.extensions[this.name];
  2502. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2503. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2504. onSuccess(buffer);
  2505. return true;
  2506. };
  2507. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2508. var shader = gltfRuntime.shaders[id];
  2509. if (!shader.extensions || !(this.name in shader.extensions)) {
  2510. return false;
  2511. }
  2512. var binaryExtensionShader = shader.extensions[this.name];
  2513. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2514. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2515. setTimeout(function () {
  2516. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2517. onSuccess(shaderString);
  2518. });
  2519. return true;
  2520. };
  2521. return GLTFBinaryExtension;
  2522. }(GLTF1.GLTFLoaderExtension));
  2523. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2524. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2525. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2526. })(BABYLON || (BABYLON = {}));
  2527. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2528. "use strict";
  2529. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2530. var __extends = (this && this.__extends) || (function () {
  2531. var extendStatics = Object.setPrototypeOf ||
  2532. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2533. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2534. return function (d, b) {
  2535. extendStatics(d, b);
  2536. function __() { this.constructor = d; }
  2537. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2538. };
  2539. })();
  2540. var BABYLON;
  2541. (function (BABYLON) {
  2542. var GLTF1;
  2543. (function (GLTF1) {
  2544. ;
  2545. ;
  2546. ;
  2547. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2548. __extends(GLTFMaterialsCommonExtension, _super);
  2549. function GLTFMaterialsCommonExtension() {
  2550. return _super.call(this, "KHR_materials_common") || this;
  2551. }
  2552. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2553. if (!gltfRuntime.extensions)
  2554. return false;
  2555. var extension = gltfRuntime.extensions[this.name];
  2556. if (!extension)
  2557. return false;
  2558. // Create lights
  2559. var lights = extension.lights;
  2560. if (lights) {
  2561. for (var thing in lights) {
  2562. var light = lights[thing];
  2563. switch (light.type) {
  2564. case "ambient":
  2565. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2566. var ambient = light.ambient;
  2567. if (ambient) {
  2568. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2569. }
  2570. break;
  2571. case "point":
  2572. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2573. var point = light.point;
  2574. if (point) {
  2575. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2576. }
  2577. break;
  2578. case "directional":
  2579. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2580. var directional = light.directional;
  2581. if (directional) {
  2582. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2583. }
  2584. break;
  2585. case "spot":
  2586. var spot = light.spot;
  2587. if (spot) {
  2588. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2589. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2590. }
  2591. break;
  2592. default:
  2593. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2594. break;
  2595. }
  2596. }
  2597. }
  2598. return false;
  2599. };
  2600. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2601. var material = gltfRuntime.materials[id];
  2602. if (!material || !material.extensions)
  2603. return false;
  2604. var extension = material.extensions[this.name];
  2605. if (!extension)
  2606. return false;
  2607. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2608. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2609. if (extension.technique === "CONSTANT") {
  2610. standardMaterial.disableLighting = true;
  2611. }
  2612. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2613. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2614. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2615. // Ambient
  2616. if (typeof extension.values.ambient === "string") {
  2617. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2618. }
  2619. else {
  2620. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2621. }
  2622. // Diffuse
  2623. if (typeof extension.values.diffuse === "string") {
  2624. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2625. }
  2626. else {
  2627. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2628. }
  2629. // Emission
  2630. if (typeof extension.values.emission === "string") {
  2631. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2632. }
  2633. else {
  2634. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2635. }
  2636. // Specular
  2637. if (typeof extension.values.specular === "string") {
  2638. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2639. }
  2640. else {
  2641. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2642. }
  2643. return true;
  2644. };
  2645. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2646. // Create buffer from texture url
  2647. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2648. // Create texture from buffer
  2649. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2650. }, onError);
  2651. };
  2652. return GLTFMaterialsCommonExtension;
  2653. }(GLTF1.GLTFLoaderExtension));
  2654. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2655. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2656. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2657. })(BABYLON || (BABYLON = {}));
  2658. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map