babylon.glTF1FileLoader.js 141 KB

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