babylon.glTF1FileLoader.js 134 KB

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