babylon.glTF1FileLoader.js 135 KB

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