babylon.glTF1FileLoader.js 116 KB

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