babylon.glTF1FileLoader.js 124 KB

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