babylon.glTF1FileLoader.js 137 KB

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