babylon.glTF1FileLoader.js 116 KB

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