babylon.glTF1FileLoader.js 128 KB

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