babylon.glTF2FileLoader.js 202 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757
  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. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  755. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  756. /**
  757. * Defines the module for importing and exporting glTF 2.0 assets
  758. */
  759. var BABYLON;
  760. (function (BABYLON) {
  761. var GLTF2;
  762. (function (GLTF2) {
  763. /**
  764. * Helper class for working with arrays when loading the glTF asset
  765. */
  766. var ArrayItem = /** @class */ (function () {
  767. function ArrayItem() {
  768. }
  769. /**
  770. * Gets an item from the given array.
  771. * @param context The context when loading the asset
  772. * @param array The array to get the item from
  773. * @param index The index to the array
  774. * @returns The array item
  775. */
  776. ArrayItem.Get = function (context, array, index) {
  777. if (!array || index == undefined || !array[index]) {
  778. throw new Error(context + ": Failed to find index (" + index + ")");
  779. }
  780. return array[index];
  781. };
  782. /**
  783. * Assign an `index` field to each item of the given array.
  784. * @param array The array of items
  785. */
  786. ArrayItem.Assign = function (array) {
  787. if (array) {
  788. for (var index = 0; index < array.length; index++) {
  789. array[index].index = index;
  790. }
  791. }
  792. };
  793. return ArrayItem;
  794. }());
  795. GLTF2.ArrayItem = ArrayItem;
  796. /**
  797. * The glTF 2.0 loader
  798. */
  799. var GLTFLoader = /** @class */ (function () {
  800. /** @hidden */
  801. function GLTFLoader(parent) {
  802. /** @hidden */
  803. this._completePromises = new Array();
  804. this._disposed = false;
  805. this._state = null;
  806. this._extensions = {};
  807. this._defaultBabylonMaterialData = {};
  808. this._requests = new Array();
  809. this._parent = parent;
  810. }
  811. /**
  812. * Registers a loader extension.
  813. * @param name The name of the loader extension.
  814. * @param factory The factory function that creates the loader extension.
  815. */
  816. GLTFLoader.RegisterExtension = function (name, factory) {
  817. if (GLTFLoader.UnregisterExtension(name)) {
  818. BABYLON.Tools.Warn("Extension with the name '" + name + "' already exists");
  819. }
  820. GLTFLoader._ExtensionFactories[name] = factory;
  821. // Keep the order of registration so that extensions registered first are called first.
  822. GLTFLoader._ExtensionNames.push(name);
  823. };
  824. /**
  825. * Unregisters a loader extension.
  826. * @param name The name of the loader extenion.
  827. * @returns A boolean indicating whether the extension has been unregistered
  828. */
  829. GLTFLoader.UnregisterExtension = function (name) {
  830. if (!GLTFLoader._ExtensionFactories[name]) {
  831. return false;
  832. }
  833. delete GLTFLoader._ExtensionFactories[name];
  834. var index = GLTFLoader._ExtensionNames.indexOf(name);
  835. if (index !== -1) {
  836. GLTFLoader._ExtensionNames.splice(index, 1);
  837. }
  838. return true;
  839. };
  840. Object.defineProperty(GLTFLoader.prototype, "state", {
  841. /**
  842. * Gets the loader state.
  843. */
  844. get: function () {
  845. return this._state;
  846. },
  847. enumerable: true,
  848. configurable: true
  849. });
  850. /** @hidden */
  851. GLTFLoader.prototype.dispose = function () {
  852. if (this._disposed) {
  853. return;
  854. }
  855. this._disposed = true;
  856. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  857. var request = _a[_i];
  858. request.abort();
  859. }
  860. this._requests.length = 0;
  861. delete this.gltf;
  862. delete this.babylonScene;
  863. this._completePromises.length = 0;
  864. for (var name_1 in this._extensions) {
  865. var extension = this._extensions[name_1];
  866. if (extension.dispose) {
  867. this._extensions[name_1].dispose();
  868. }
  869. }
  870. this._extensions = {};
  871. delete this._rootBabylonMesh;
  872. delete this._progressCallback;
  873. this._parent._clear();
  874. };
  875. /** @hidden */
  876. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  877. var _this = this;
  878. return Promise.resolve().then(function () {
  879. _this.babylonScene = scene;
  880. _this._rootUrl = rootUrl;
  881. _this._fileName = fileName || "scene";
  882. _this._progressCallback = onProgress;
  883. _this._loadData(data);
  884. var nodes = null;
  885. if (meshesNames) {
  886. var nodeMap_1 = {};
  887. if (_this.gltf.nodes) {
  888. for (var _i = 0, _a = _this.gltf.nodes; _i < _a.length; _i++) {
  889. var node = _a[_i];
  890. if (node.name) {
  891. nodeMap_1[node.name] = node.index;
  892. }
  893. }
  894. }
  895. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  896. nodes = names.map(function (name) {
  897. var node = nodeMap_1[name];
  898. if (node === undefined) {
  899. throw new Error("Failed to find node '" + name + "'");
  900. }
  901. return node;
  902. });
  903. }
  904. return _this._loadAsync(nodes, function () {
  905. return {
  906. meshes: _this._getMeshes(),
  907. particleSystems: [],
  908. skeletons: _this._getSkeletons(),
  909. animationGroups: _this._getAnimationGroups()
  910. };
  911. });
  912. });
  913. };
  914. /** @hidden */
  915. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  916. var _this = this;
  917. return Promise.resolve().then(function () {
  918. _this.babylonScene = scene;
  919. _this._rootUrl = rootUrl;
  920. _this._fileName = fileName || "scene";
  921. _this._progressCallback = onProgress;
  922. _this._loadData(data);
  923. return _this._loadAsync(null, function () { return undefined; });
  924. });
  925. };
  926. GLTFLoader.prototype._loadAsync = function (nodes, resultFunc) {
  927. var _this = this;
  928. return Promise.resolve().then(function () {
  929. _this._uniqueRootUrl = (_this._rootUrl.indexOf("file:") === -1 && _this._fileName) ? _this._rootUrl : "" + _this._rootUrl + Date.now() + "/";
  930. _this._loadExtensions();
  931. _this._checkExtensions();
  932. var loadingToReadyCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.READY];
  933. var loadingToCompleteCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.COMPLETE];
  934. _this._parent._startPerformanceCounter(loadingToReadyCounterName);
  935. _this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  936. _this._setState(BABYLON.GLTFLoaderState.LOADING);
  937. _this._extensionsOnLoading();
  938. var promises = new Array();
  939. if (nodes) {
  940. promises.push(_this.loadSceneAsync("/nodes", { nodes: nodes, index: -1 }));
  941. }
  942. else {
  943. var scene = ArrayItem.Get("/scene", _this.gltf.scenes, _this.gltf.scene || 0);
  944. promises.push(_this.loadSceneAsync("/scenes/" + scene.index, scene));
  945. }
  946. if (_this._parent.compileMaterials) {
  947. promises.push(_this._compileMaterialsAsync());
  948. }
  949. if (_this._parent.compileShadowGenerators) {
  950. promises.push(_this._compileShadowGeneratorsAsync());
  951. }
  952. var resultPromise = Promise.all(promises).then(function () {
  953. if (_this._rootBabylonMesh) {
  954. _this._rootBabylonMesh.setEnabled(true);
  955. }
  956. _this._setState(BABYLON.GLTFLoaderState.READY);
  957. _this._extensionsOnReady();
  958. _this._startAnimations();
  959. return resultFunc();
  960. });
  961. resultPromise.then(function () {
  962. _this._parent._endPerformanceCounter(loadingToReadyCounterName);
  963. BABYLON.Tools.SetImmediate(function () {
  964. if (!_this._disposed) {
  965. Promise.all(_this._completePromises).then(function () {
  966. _this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  967. _this._setState(BABYLON.GLTFLoaderState.COMPLETE);
  968. _this._parent.onCompleteObservable.notifyObservers(undefined);
  969. _this._parent.onCompleteObservable.clear();
  970. _this.dispose();
  971. }, function (error) {
  972. _this._parent.onErrorObservable.notifyObservers(error);
  973. _this._parent.onErrorObservable.clear();
  974. _this.dispose();
  975. });
  976. }
  977. });
  978. });
  979. return resultPromise;
  980. }, function (error) {
  981. if (!_this._disposed) {
  982. _this._parent.onErrorObservable.notifyObservers(error);
  983. _this._parent.onErrorObservable.clear();
  984. _this.dispose();
  985. }
  986. throw error;
  987. });
  988. };
  989. GLTFLoader.prototype._loadData = function (data) {
  990. this.gltf = data.json;
  991. this._setupData();
  992. if (data.bin) {
  993. var buffers = this.gltf.buffers;
  994. if (buffers && buffers[0] && !buffers[0].uri) {
  995. var binaryBuffer = buffers[0];
  996. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  997. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  998. }
  999. binaryBuffer._data = Promise.resolve(data.bin);
  1000. }
  1001. else {
  1002. BABYLON.Tools.Warn("Unexpected BIN chunk");
  1003. }
  1004. }
  1005. };
  1006. GLTFLoader.prototype._setupData = function () {
  1007. ArrayItem.Assign(this.gltf.accessors);
  1008. ArrayItem.Assign(this.gltf.animations);
  1009. ArrayItem.Assign(this.gltf.buffers);
  1010. ArrayItem.Assign(this.gltf.bufferViews);
  1011. ArrayItem.Assign(this.gltf.cameras);
  1012. ArrayItem.Assign(this.gltf.images);
  1013. ArrayItem.Assign(this.gltf.materials);
  1014. ArrayItem.Assign(this.gltf.meshes);
  1015. ArrayItem.Assign(this.gltf.nodes);
  1016. ArrayItem.Assign(this.gltf.samplers);
  1017. ArrayItem.Assign(this.gltf.scenes);
  1018. ArrayItem.Assign(this.gltf.skins);
  1019. ArrayItem.Assign(this.gltf.textures);
  1020. if (this.gltf.nodes) {
  1021. var nodeParents = {};
  1022. for (var _i = 0, _a = this.gltf.nodes; _i < _a.length; _i++) {
  1023. var node = _a[_i];
  1024. if (node.children) {
  1025. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  1026. var index = _c[_b];
  1027. nodeParents[index] = node.index;
  1028. }
  1029. }
  1030. }
  1031. var rootNode = this._createRootNode();
  1032. for (var _d = 0, _e = this.gltf.nodes; _d < _e.length; _d++) {
  1033. var node = _e[_d];
  1034. var parentIndex = nodeParents[node.index];
  1035. node.parent = parentIndex === undefined ? rootNode : this.gltf.nodes[parentIndex];
  1036. }
  1037. }
  1038. };
  1039. GLTFLoader.prototype._loadExtensions = function () {
  1040. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  1041. var name_2 = _a[_i];
  1042. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  1043. this._extensions[name_2] = extension;
  1044. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  1045. }
  1046. this._parent.onExtensionLoadedObservable.clear();
  1047. };
  1048. GLTFLoader.prototype._checkExtensions = function () {
  1049. if (this.gltf.extensionsRequired) {
  1050. for (var _i = 0, _a = this.gltf.extensionsRequired; _i < _a.length; _i++) {
  1051. var name_3 = _a[_i];
  1052. var extension = this._extensions[name_3];
  1053. if (!extension || !extension.enabled) {
  1054. throw new Error("Require extension " + name_3 + " is not available");
  1055. }
  1056. }
  1057. }
  1058. };
  1059. GLTFLoader.prototype._setState = function (state) {
  1060. this._state = state;
  1061. this.log(BABYLON.GLTFLoaderState[this._state]);
  1062. };
  1063. GLTFLoader.prototype._createRootNode = function () {
  1064. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this.babylonScene);
  1065. this._rootBabylonMesh.setEnabled(false);
  1066. var rootNode = {
  1067. _babylonTransformNode: this._rootBabylonMesh,
  1068. index: -1
  1069. };
  1070. switch (this._parent.coordinateSystemMode) {
  1071. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  1072. if (!this.babylonScene.useRightHandedSystem) {
  1073. rootNode.rotation = [0, 1, 0, 0];
  1074. rootNode.scale = [1, 1, -1];
  1075. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  1076. }
  1077. break;
  1078. }
  1079. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  1080. this.babylonScene.useRightHandedSystem = true;
  1081. break;
  1082. }
  1083. default: {
  1084. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  1085. }
  1086. }
  1087. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  1088. return rootNode;
  1089. };
  1090. /**
  1091. * Loads a glTF scene.
  1092. * @param context The context when loading the asset
  1093. * @param scene The glTF scene property
  1094. * @returns A promise that resolves when the load is complete
  1095. */
  1096. GLTFLoader.prototype.loadSceneAsync = function (context, scene) {
  1097. var _this = this;
  1098. var extensionPromise = this._extensionsLoadSceneAsync(context, scene);
  1099. if (extensionPromise) {
  1100. return extensionPromise;
  1101. }
  1102. var promises = new Array();
  1103. this.logOpen(context + " " + (scene.name || ""));
  1104. if (scene.nodes) {
  1105. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  1106. var index = _a[_i];
  1107. var node = ArrayItem.Get(context + "/nodes/" + index, this.gltf.nodes, index);
  1108. promises.push(this.loadNodeAsync("/nodes/" + node.index, node, function (babylonMesh) {
  1109. babylonMesh.parent = _this._rootBabylonMesh;
  1110. }));
  1111. }
  1112. }
  1113. // Link all Babylon bones for each glTF node with the corresponding Babylon transform node.
  1114. // A glTF joint is a pointer to a glTF node in the glTF node hierarchy similar to Unity3D.
  1115. if (this.gltf.nodes) {
  1116. for (var _b = 0, _c = this.gltf.nodes; _b < _c.length; _b++) {
  1117. var node = _c[_b];
  1118. if (node._babylonTransformNode && node._babylonBones) {
  1119. for (var _d = 0, _e = node._babylonBones; _d < _e.length; _d++) {
  1120. var babylonBone = _e[_d];
  1121. babylonBone.linkTransformNode(node._babylonTransformNode);
  1122. }
  1123. }
  1124. }
  1125. }
  1126. promises.push(this._loadAnimationsAsync());
  1127. this.logClose();
  1128. return Promise.all(promises).then(function () { });
  1129. };
  1130. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  1131. if (node._primitiveBabylonMeshes) {
  1132. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  1133. var babylonMesh = _a[_i];
  1134. callback(babylonMesh);
  1135. }
  1136. }
  1137. };
  1138. GLTFLoader.prototype._getMeshes = function () {
  1139. var meshes = new Array();
  1140. // Root mesh is always first.
  1141. meshes.push(this._rootBabylonMesh);
  1142. var nodes = this.gltf.nodes;
  1143. if (nodes) {
  1144. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  1145. var node = nodes_1[_i];
  1146. this._forEachPrimitive(node, function (babylonMesh) {
  1147. meshes.push(babylonMesh);
  1148. });
  1149. }
  1150. }
  1151. return meshes;
  1152. };
  1153. GLTFLoader.prototype._getSkeletons = function () {
  1154. var skeletons = new Array();
  1155. var skins = this.gltf.skins;
  1156. if (skins) {
  1157. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  1158. var skin = skins_1[_i];
  1159. if (skin._data) {
  1160. skeletons.push(skin._data.babylonSkeleton);
  1161. }
  1162. }
  1163. }
  1164. return skeletons;
  1165. };
  1166. GLTFLoader.prototype._getAnimationGroups = function () {
  1167. var animationGroups = new Array();
  1168. var animations = this.gltf.animations;
  1169. if (animations) {
  1170. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  1171. var animation = animations_1[_i];
  1172. if (animation._babylonAnimationGroup) {
  1173. animationGroups.push(animation._babylonAnimationGroup);
  1174. }
  1175. }
  1176. }
  1177. return animationGroups;
  1178. };
  1179. GLTFLoader.prototype._startAnimations = function () {
  1180. switch (this._parent.animationStartMode) {
  1181. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  1182. // do nothing
  1183. break;
  1184. }
  1185. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  1186. var babylonAnimationGroups = this._getAnimationGroups();
  1187. if (babylonAnimationGroups.length !== 0) {
  1188. babylonAnimationGroups[0].start(true);
  1189. }
  1190. break;
  1191. }
  1192. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  1193. var babylonAnimationGroups = this._getAnimationGroups();
  1194. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  1195. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  1196. babylonAnimationGroup.start(true);
  1197. }
  1198. break;
  1199. }
  1200. default: {
  1201. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  1202. return;
  1203. }
  1204. }
  1205. };
  1206. /**
  1207. * Loads a glTF node.
  1208. * @param context The context when loading the asset
  1209. * @param node The glTF node property
  1210. * @param assign A function called synchronously after parsing the glTF properties
  1211. * @returns A promise that resolves with the loaded Babylon mesh when the load is complete
  1212. */
  1213. GLTFLoader.prototype.loadNodeAsync = function (context, node, assign) {
  1214. var _this = this;
  1215. if (assign === void 0) { assign = function () { }; }
  1216. var extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
  1217. if (extensionPromise) {
  1218. return extensionPromise;
  1219. }
  1220. if (node._babylonTransformNode) {
  1221. throw new Error(context + ": Invalid recursive node hierarchy");
  1222. }
  1223. var promises = new Array();
  1224. this.logOpen(context + " " + (node.name || ""));
  1225. var loadNode = function (babylonTransformNode) {
  1226. GLTFLoader.AddPointerMetadata(babylonTransformNode, context);
  1227. GLTFLoader._LoadTransform(node, babylonTransformNode);
  1228. if (node.camera != undefined) {
  1229. var camera = ArrayItem.Get(context + "/camera", _this.gltf.cameras, node.camera);
  1230. promises.push(_this.loadCameraAsync("/cameras/" + camera.index, camera, function (babylonCamera) {
  1231. babylonCamera.parent = babylonTransformNode;
  1232. }));
  1233. }
  1234. if (node.children) {
  1235. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  1236. var index = _a[_i];
  1237. var childNode = ArrayItem.Get(context + "/children/" + index, _this.gltf.nodes, index);
  1238. promises.push(_this.loadNodeAsync("/nodes/" + childNode.index, childNode, function (childBabylonMesh) {
  1239. childBabylonMesh.parent = babylonTransformNode;
  1240. }));
  1241. }
  1242. }
  1243. assign(babylonTransformNode);
  1244. };
  1245. if (node.mesh == undefined) {
  1246. var nodeName = node.name || "node" + node.index;
  1247. node._babylonTransformNode = new BABYLON.TransformNode(nodeName, this.babylonScene);
  1248. loadNode(node._babylonTransformNode);
  1249. }
  1250. else {
  1251. var mesh = ArrayItem.Get(context + "/mesh", this.gltf.meshes, node.mesh);
  1252. promises.push(this._loadMeshAsync("/meshes/" + mesh.index, node, mesh, loadNode));
  1253. }
  1254. this.logClose();
  1255. return Promise.all(promises).then(function () {
  1256. _this._forEachPrimitive(node, function (babylonMesh) {
  1257. babylonMesh.refreshBoundingInfo(true);
  1258. });
  1259. return node._babylonTransformNode;
  1260. });
  1261. };
  1262. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, assign) {
  1263. var primitives = mesh.primitives;
  1264. if (!primitives || !primitives.length) {
  1265. throw new Error(context + ": Primitives are missing");
  1266. }
  1267. if (primitives[0].index == undefined) {
  1268. ArrayItem.Assign(primitives);
  1269. }
  1270. var promises = new Array();
  1271. this.logOpen(context + " " + (mesh.name || ""));
  1272. var name = node.name || "node" + node.index;
  1273. if (primitives.length === 1) {
  1274. var primitive = mesh.primitives[0];
  1275. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, name, node, mesh, primitive, function (babylonMesh) {
  1276. node._babylonTransformNode = babylonMesh;
  1277. node._primitiveBabylonMeshes = [babylonMesh];
  1278. }));
  1279. }
  1280. else {
  1281. node._babylonTransformNode = new BABYLON.TransformNode(name, this.babylonScene);
  1282. node._primitiveBabylonMeshes = [];
  1283. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  1284. var primitive = primitives_1[_i];
  1285. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, name + "_primitive" + primitive.index, node, mesh, primitive, function (babylonMesh) {
  1286. babylonMesh.parent = node._babylonTransformNode;
  1287. node._primitiveBabylonMeshes.push(babylonMesh);
  1288. }));
  1289. }
  1290. }
  1291. if (node.skin != undefined) {
  1292. var skin = ArrayItem.Get(context + "/skin", this.gltf.skins, node.skin);
  1293. promises.push(this._loadSkinAsync("/skins/" + skin.index, node, skin));
  1294. }
  1295. assign(node._babylonTransformNode);
  1296. this.logClose();
  1297. return Promise.all(promises).then(function () {
  1298. return node._babylonTransformNode;
  1299. });
  1300. };
  1301. GLTFLoader.prototype._loadMeshPrimitiveAsync = function (context, name, node, mesh, primitive, assign) {
  1302. var _this = this;
  1303. this.logOpen("" + context);
  1304. var canInstance = (node.skin == undefined && !mesh.primitives[0].targets);
  1305. var babylonAbstractMesh;
  1306. var promise;
  1307. var instanceData = primitive._instanceData;
  1308. if (canInstance && instanceData) {
  1309. babylonAbstractMesh = instanceData.babylonSourceMesh.createInstance(name);
  1310. promise = instanceData.promise;
  1311. }
  1312. else {
  1313. var promises = new Array();
  1314. var babylonMesh_1 = new BABYLON.Mesh(name, this.babylonScene);
  1315. this._createMorphTargets(context, node, mesh, primitive, babylonMesh_1);
  1316. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh_1).then(function (babylonGeometry) {
  1317. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh_1, babylonGeometry).then(function () {
  1318. babylonGeometry.applyToMesh(babylonMesh_1);
  1319. });
  1320. }));
  1321. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  1322. if (primitive.material == undefined) {
  1323. var babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
  1324. if (!babylonMaterial) {
  1325. babylonMaterial = this._createDefaultMaterial("__gltf_default", babylonDrawMode);
  1326. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1327. this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
  1328. }
  1329. babylonMesh_1.material = babylonMaterial;
  1330. }
  1331. else {
  1332. var material = ArrayItem.Get(context + "/material", this.gltf.materials, primitive.material);
  1333. promises.push(this._loadMaterialAsync("/materials/" + material.index, material, babylonMesh_1, babylonDrawMode, function (babylonMaterial) {
  1334. babylonMesh_1.material = babylonMaterial;
  1335. }));
  1336. }
  1337. promise = Promise.all(promises);
  1338. if (canInstance) {
  1339. primitive._instanceData = {
  1340. babylonSourceMesh: babylonMesh_1,
  1341. promise: promise
  1342. };
  1343. }
  1344. babylonAbstractMesh = babylonMesh_1;
  1345. }
  1346. GLTFLoader.AddPointerMetadata(babylonAbstractMesh, context);
  1347. this._parent.onMeshLoadedObservable.notifyObservers(babylonAbstractMesh);
  1348. assign(babylonAbstractMesh);
  1349. this.logClose();
  1350. return promise.then(function () {
  1351. return babylonAbstractMesh;
  1352. });
  1353. };
  1354. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  1355. var _this = this;
  1356. var extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
  1357. if (extensionPromise) {
  1358. return extensionPromise;
  1359. }
  1360. var attributes = primitive.attributes;
  1361. if (!attributes) {
  1362. throw new Error(context + ": Attributes are missing");
  1363. }
  1364. var promises = new Array();
  1365. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this.babylonScene);
  1366. if (primitive.indices == undefined) {
  1367. babylonMesh.isUnIndexed = true;
  1368. }
  1369. else {
  1370. var accessor = ArrayItem.Get(context + "/indices", this.gltf.accessors, primitive.indices);
  1371. promises.push(this._loadIndicesAccessorAsync("/accessors/" + accessor.index, accessor).then(function (data) {
  1372. babylonGeometry.setIndices(data);
  1373. }));
  1374. }
  1375. var loadAttribute = function (attribute, kind, callback) {
  1376. if (attributes[attribute] == undefined) {
  1377. return;
  1378. }
  1379. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  1380. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  1381. babylonMesh._delayInfo.push(kind);
  1382. }
  1383. var accessor = ArrayItem.Get(context + "/attributes/" + attribute, _this.gltf.accessors, attributes[attribute]);
  1384. promises.push(_this._loadVertexAccessorAsync("/accessors/" + accessor.index, accessor, kind).then(function (babylonVertexBuffer) {
  1385. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  1386. }));
  1387. if (callback) {
  1388. callback(accessor);
  1389. }
  1390. };
  1391. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  1392. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  1393. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  1394. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  1395. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  1396. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  1397. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  1398. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  1399. if (accessor.type === "VEC4" /* VEC4 */) {
  1400. babylonMesh.hasVertexAlpha = true;
  1401. }
  1402. });
  1403. return Promise.all(promises).then(function () {
  1404. return babylonGeometry;
  1405. });
  1406. };
  1407. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  1408. if (!primitive.targets) {
  1409. return;
  1410. }
  1411. if (node._numMorphTargets == undefined) {
  1412. node._numMorphTargets = primitive.targets.length;
  1413. }
  1414. else if (primitive.targets.length !== node._numMorphTargets) {
  1415. throw new Error(context + ": Primitives do not have the same number of targets");
  1416. }
  1417. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  1418. for (var index = 0; index < primitive.targets.length; index++) {
  1419. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  1420. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  1421. // TODO: tell the target whether it has positions, normals, tangents
  1422. }
  1423. };
  1424. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  1425. if (!primitive.targets) {
  1426. return Promise.resolve();
  1427. }
  1428. var promises = new Array();
  1429. var morphTargetManager = babylonMesh.morphTargetManager;
  1430. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  1431. var babylonMorphTarget = morphTargetManager.getTarget(index);
  1432. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  1433. }
  1434. return Promise.all(promises).then(function () { });
  1435. };
  1436. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  1437. var _this = this;
  1438. var promises = new Array();
  1439. var loadAttribute = function (attribute, kind, setData) {
  1440. if (attributes[attribute] == undefined) {
  1441. return;
  1442. }
  1443. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  1444. if (!babylonVertexBuffer) {
  1445. return;
  1446. }
  1447. var accessor = ArrayItem.Get(context + "/" + attribute, _this.gltf.accessors, attributes[attribute]);
  1448. promises.push(_this._loadFloatAccessorAsync("/accessors/" + accessor.index, accessor).then(function (data) {
  1449. setData(babylonVertexBuffer, data);
  1450. }));
  1451. };
  1452. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  1453. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1454. data[index] += value;
  1455. });
  1456. babylonMorphTarget.setPositions(data);
  1457. });
  1458. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  1459. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1460. data[index] += value;
  1461. });
  1462. babylonMorphTarget.setNormals(data);
  1463. });
  1464. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  1465. var dataIndex = 0;
  1466. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  1467. // Tangent data for morph targets is stored as xyz delta.
  1468. // The vertexData.tangent is stored as xyzw.
  1469. // So we need to skip every fourth vertexData.tangent.
  1470. if (((index + 1) % 4) !== 0) {
  1471. data[dataIndex++] += value;
  1472. }
  1473. });
  1474. babylonMorphTarget.setTangents(data);
  1475. });
  1476. return Promise.all(promises).then(function () { });
  1477. };
  1478. GLTFLoader._LoadTransform = function (node, babylonNode) {
  1479. // Ignore the TRS of skinned nodes.
  1480. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1481. if (node.skin != undefined) {
  1482. return;
  1483. }
  1484. var position = BABYLON.Vector3.Zero();
  1485. var rotation = BABYLON.Quaternion.Identity();
  1486. var scaling = BABYLON.Vector3.One();
  1487. if (node.matrix) {
  1488. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  1489. matrix.decompose(scaling, rotation, position);
  1490. }
  1491. else {
  1492. if (node.translation) {
  1493. position = BABYLON.Vector3.FromArray(node.translation);
  1494. }
  1495. if (node.rotation) {
  1496. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  1497. }
  1498. if (node.scale) {
  1499. scaling = BABYLON.Vector3.FromArray(node.scale);
  1500. }
  1501. }
  1502. babylonNode.position = position;
  1503. babylonNode.rotationQuaternion = rotation;
  1504. babylonNode.scaling = scaling;
  1505. };
  1506. GLTFLoader.prototype._loadSkinAsync = function (context, node, skin) {
  1507. var _this = this;
  1508. var assignSkeleton = function (skeleton) {
  1509. _this._forEachPrimitive(node, function (babylonMesh) {
  1510. babylonMesh.skeleton = skeleton;
  1511. });
  1512. };
  1513. if (skin._data) {
  1514. assignSkeleton(skin._data.babylonSkeleton);
  1515. return skin._data.promise;
  1516. }
  1517. var skeletonId = "skeleton" + skin.index;
  1518. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this.babylonScene);
  1519. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1520. babylonSkeleton.overrideMesh = this._rootBabylonMesh;
  1521. this._loadBones(context, skin, babylonSkeleton);
  1522. assignSkeleton(babylonSkeleton);
  1523. var promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  1524. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  1525. });
  1526. skin._data = {
  1527. babylonSkeleton: babylonSkeleton,
  1528. promise: promise
  1529. };
  1530. return promise;
  1531. };
  1532. GLTFLoader.prototype._loadBones = function (context, skin, babylonSkeleton) {
  1533. var babylonBones = {};
  1534. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  1535. var index = _a[_i];
  1536. var node = ArrayItem.Get(context + "/joints/" + index, this.gltf.nodes, index);
  1537. this._loadBone(node, skin, babylonSkeleton, babylonBones);
  1538. }
  1539. };
  1540. GLTFLoader.prototype._loadBone = function (node, skin, babylonSkeleton, babylonBones) {
  1541. var babylonBone = babylonBones[node.index];
  1542. if (babylonBone) {
  1543. return babylonBone;
  1544. }
  1545. var babylonParentBone = null;
  1546. if (node.parent && node.parent._babylonTransformNode !== this._rootBabylonMesh) {
  1547. babylonParentBone = this._loadBone(node.parent, skin, babylonSkeleton, babylonBones);
  1548. }
  1549. var boneIndex = skin.joints.indexOf(node.index);
  1550. babylonBone = new BABYLON.Bone(node.name || "joint" + node.index, babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  1551. babylonBones[node.index] = babylonBone;
  1552. node._babylonBones = node._babylonBones || [];
  1553. node._babylonBones.push(babylonBone);
  1554. return babylonBone;
  1555. };
  1556. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  1557. if (skin.inverseBindMatrices == undefined) {
  1558. return Promise.resolve(null);
  1559. }
  1560. var accessor = ArrayItem.Get(context + "/inverseBindMatrices", this.gltf.accessors, skin.inverseBindMatrices);
  1561. return this._loadFloatAccessorAsync("/accessors/" + accessor.index, accessor);
  1562. };
  1563. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  1564. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  1565. var babylonBone = _a[_i];
  1566. var baseMatrix = BABYLON.Matrix.Identity();
  1567. var boneIndex = babylonBone._index;
  1568. if (inverseBindMatricesData && boneIndex !== -1) {
  1569. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  1570. baseMatrix.invertToRef(baseMatrix);
  1571. }
  1572. var babylonParentBone = babylonBone.getParent();
  1573. if (babylonParentBone) {
  1574. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  1575. }
  1576. babylonBone.updateMatrix(baseMatrix, false, false);
  1577. babylonBone._updateDifferenceMatrix(undefined, false);
  1578. }
  1579. };
  1580. GLTFLoader.prototype._getNodeMatrix = function (node) {
  1581. return node.matrix ?
  1582. BABYLON.Matrix.FromArray(node.matrix) :
  1583. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  1584. };
  1585. /**
  1586. * Loads a glTF camera.
  1587. * @param context The context when loading the asset
  1588. * @param camera The glTF camera property
  1589. * @param assign A function called synchronously after parsing the glTF properties
  1590. * @returns A promise that resolves with the loaded Babylon camera when the load is complete
  1591. */
  1592. GLTFLoader.prototype.loadCameraAsync = function (context, camera, assign) {
  1593. if (assign === void 0) { assign = function () { }; }
  1594. var extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
  1595. if (extensionPromise) {
  1596. return extensionPromise;
  1597. }
  1598. var promises = new Array();
  1599. this.logOpen(context + " " + (camera.name || ""));
  1600. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera.index, BABYLON.Vector3.Zero(), this.babylonScene, false);
  1601. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  1602. switch (camera.type) {
  1603. case "perspective" /* PERSPECTIVE */: {
  1604. var perspective = camera.perspective;
  1605. if (!perspective) {
  1606. throw new Error(context + ": Camera perspective properties are missing");
  1607. }
  1608. babylonCamera.fov = perspective.yfov;
  1609. babylonCamera.minZ = perspective.znear;
  1610. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  1611. break;
  1612. }
  1613. case "orthographic" /* ORTHOGRAPHIC */: {
  1614. if (!camera.orthographic) {
  1615. throw new Error(context + ": Camera orthographic properties are missing");
  1616. }
  1617. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1618. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  1619. babylonCamera.orthoRight = camera.orthographic.xmag;
  1620. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  1621. babylonCamera.orthoTop = camera.orthographic.ymag;
  1622. babylonCamera.minZ = camera.orthographic.znear;
  1623. babylonCamera.maxZ = camera.orthographic.zfar;
  1624. break;
  1625. }
  1626. default: {
  1627. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  1628. }
  1629. }
  1630. GLTFLoader.AddPointerMetadata(babylonCamera, context);
  1631. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  1632. assign(babylonCamera);
  1633. return Promise.all(promises).then(function () {
  1634. return babylonCamera;
  1635. });
  1636. };
  1637. GLTFLoader.prototype._loadAnimationsAsync = function () {
  1638. var animations = this.gltf.animations;
  1639. if (!animations) {
  1640. return Promise.resolve();
  1641. }
  1642. var promises = new Array();
  1643. for (var index = 0; index < animations.length; index++) {
  1644. var animation = animations[index];
  1645. promises.push(this.loadAnimationAsync("/animations/" + animation.index, animation));
  1646. }
  1647. return Promise.all(promises).then(function () { });
  1648. };
  1649. /**
  1650. * Loads a glTF animation.
  1651. * @param context The context when loading the asset
  1652. * @param animation The glTF animation property
  1653. * @returns A promise that resolves with the loaded Babylon animation group when the load is complete
  1654. */
  1655. GLTFLoader.prototype.loadAnimationAsync = function (context, animation) {
  1656. var promise = this._extensionsLoadAnimationAsync(context, animation);
  1657. if (promise) {
  1658. return promise;
  1659. }
  1660. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this.babylonScene);
  1661. animation._babylonAnimationGroup = babylonAnimationGroup;
  1662. var promises = new Array();
  1663. ArrayItem.Assign(animation.channels);
  1664. ArrayItem.Assign(animation.samplers);
  1665. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  1666. var channel = _a[_i];
  1667. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel.index, context, animation, channel, babylonAnimationGroup));
  1668. }
  1669. return Promise.all(promises).then(function () {
  1670. babylonAnimationGroup.normalize(0);
  1671. return babylonAnimationGroup;
  1672. });
  1673. };
  1674. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  1675. var _this = this;
  1676. if (channel.target.node == undefined) {
  1677. return Promise.resolve();
  1678. }
  1679. var targetNode = ArrayItem.Get(context + "/target/node", this.gltf.nodes, channel.target.node);
  1680. // Ignore animations that have no animation targets.
  1681. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  1682. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonTransformNode)) {
  1683. return Promise.resolve();
  1684. }
  1685. var sampler = ArrayItem.Get(context + "/sampler", animation.samplers, channel.sampler);
  1686. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  1687. var targetPath;
  1688. var animationType;
  1689. switch (channel.target.path) {
  1690. case "translation" /* TRANSLATION */: {
  1691. targetPath = "position";
  1692. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1693. break;
  1694. }
  1695. case "rotation" /* ROTATION */: {
  1696. targetPath = "rotationQuaternion";
  1697. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1698. break;
  1699. }
  1700. case "scale" /* SCALE */: {
  1701. targetPath = "scaling";
  1702. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1703. break;
  1704. }
  1705. case "weights" /* WEIGHTS */: {
  1706. targetPath = "influence";
  1707. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  1708. break;
  1709. }
  1710. default: {
  1711. throw new Error(context + "/target/path: Invalid value (" + channel.target.path + ")");
  1712. }
  1713. }
  1714. var outputBufferOffset = 0;
  1715. var getNextOutputValue;
  1716. switch (targetPath) {
  1717. case "position": {
  1718. getNextOutputValue = function () {
  1719. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  1720. outputBufferOffset += 3;
  1721. return value;
  1722. };
  1723. break;
  1724. }
  1725. case "rotationQuaternion": {
  1726. getNextOutputValue = function () {
  1727. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  1728. outputBufferOffset += 4;
  1729. return value;
  1730. };
  1731. break;
  1732. }
  1733. case "scaling": {
  1734. getNextOutputValue = function () {
  1735. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  1736. outputBufferOffset += 3;
  1737. return value;
  1738. };
  1739. break;
  1740. }
  1741. case "influence": {
  1742. getNextOutputValue = function () {
  1743. var value = new Array(targetNode._numMorphTargets);
  1744. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  1745. value[i] = data.output[outputBufferOffset++];
  1746. }
  1747. return value;
  1748. };
  1749. break;
  1750. }
  1751. }
  1752. var getNextKey;
  1753. switch (data.interpolation) {
  1754. case "STEP" /* STEP */: {
  1755. getNextKey = function (frameIndex) { return ({
  1756. frame: data.input[frameIndex],
  1757. value: getNextOutputValue(),
  1758. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  1759. }); };
  1760. break;
  1761. }
  1762. case "LINEAR" /* LINEAR */: {
  1763. getNextKey = function (frameIndex) { return ({
  1764. frame: data.input[frameIndex],
  1765. value: getNextOutputValue()
  1766. }); };
  1767. break;
  1768. }
  1769. case "CUBICSPLINE" /* CUBICSPLINE */: {
  1770. getNextKey = function (frameIndex) { return ({
  1771. frame: data.input[frameIndex],
  1772. inTangent: getNextOutputValue(),
  1773. value: getNextOutputValue(),
  1774. outTangent: getNextOutputValue()
  1775. }); };
  1776. break;
  1777. }
  1778. }
  1779. var keys = new Array(data.input.length);
  1780. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  1781. keys[frameIndex] = getNextKey(frameIndex);
  1782. }
  1783. if (targetPath === "influence") {
  1784. var _loop_1 = function (targetIndex) {
  1785. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  1786. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1787. babylonAnimation.setKeys(keys.map(function (key) { return ({
  1788. frame: key.frame,
  1789. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1790. value: key.value[targetIndex],
  1791. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1792. }); }));
  1793. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  1794. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  1795. var babylonAnimationClone = babylonAnimation.clone();
  1796. morphTarget.animations.push(babylonAnimationClone);
  1797. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  1798. });
  1799. };
  1800. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  1801. _loop_1(targetIndex);
  1802. }
  1803. }
  1804. else {
  1805. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  1806. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1807. babylonAnimation.setKeys(keys);
  1808. targetNode._babylonTransformNode.animations.push(babylonAnimation);
  1809. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonTransformNode);
  1810. }
  1811. });
  1812. };
  1813. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  1814. if (sampler._data) {
  1815. return sampler._data;
  1816. }
  1817. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  1818. switch (interpolation) {
  1819. case "STEP" /* STEP */:
  1820. case "LINEAR" /* LINEAR */:
  1821. case "CUBICSPLINE" /* CUBICSPLINE */: {
  1822. break;
  1823. }
  1824. default: {
  1825. throw new Error(context + "/interpolation: Invalid value (" + sampler.interpolation + ")");
  1826. }
  1827. }
  1828. var inputAccessor = ArrayItem.Get(context + "/input", this.gltf.accessors, sampler.input);
  1829. var outputAccessor = ArrayItem.Get(context + "/output", this.gltf.accessors, sampler.output);
  1830. sampler._data = Promise.all([
  1831. this._loadFloatAccessorAsync("/accessors/" + inputAccessor.index, inputAccessor),
  1832. this._loadFloatAccessorAsync("/accessors/" + outputAccessor.index, outputAccessor)
  1833. ]).then(function (_a) {
  1834. var inputData = _a[0], outputData = _a[1];
  1835. return {
  1836. input: inputData,
  1837. interpolation: interpolation,
  1838. output: outputData,
  1839. };
  1840. });
  1841. return sampler._data;
  1842. };
  1843. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  1844. if (buffer._data) {
  1845. return buffer._data;
  1846. }
  1847. if (!buffer.uri) {
  1848. throw new Error(context + "/uri: Value is missing");
  1849. }
  1850. buffer._data = this.loadUriAsync(context + "/uri", buffer.uri);
  1851. return buffer._data;
  1852. };
  1853. /**
  1854. * Loads a glTF buffer view.
  1855. * @param context The context when loading the asset
  1856. * @param bufferView The glTF buffer view property
  1857. * @returns A promise that resolves with the loaded data when the load is complete
  1858. */
  1859. GLTFLoader.prototype.loadBufferViewAsync = function (context, bufferView) {
  1860. if (bufferView._data) {
  1861. return bufferView._data;
  1862. }
  1863. var buffer = ArrayItem.Get(context + "/buffer", this.gltf.buffers, bufferView.buffer);
  1864. bufferView._data = this._loadBufferAsync("/buffers/" + buffer.index, buffer).then(function (data) {
  1865. try {
  1866. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1867. }
  1868. catch (e) {
  1869. throw new Error(context + ": " + e.message);
  1870. }
  1871. });
  1872. return bufferView._data;
  1873. };
  1874. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  1875. if (accessor.type !== "SCALAR" /* SCALAR */) {
  1876. throw new Error(context + "/type: Invalid value " + accessor.type);
  1877. }
  1878. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  1879. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  1880. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  1881. throw new Error(context + "/componentType: Invalid value " + accessor.componentType);
  1882. }
  1883. if (accessor._data) {
  1884. return accessor._data;
  1885. }
  1886. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  1887. accessor._data = this.loadBufferViewAsync("/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  1888. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  1889. });
  1890. return accessor._data;
  1891. };
  1892. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  1893. // TODO: support normalized and stride
  1894. var _this = this;
  1895. if (accessor.componentType !== 5126 /* FLOAT */) {
  1896. throw new Error("Invalid component type " + accessor.componentType);
  1897. }
  1898. if (accessor._data) {
  1899. return accessor._data;
  1900. }
  1901. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  1902. var length = numComponents * accessor.count;
  1903. if (accessor.bufferView == undefined) {
  1904. accessor._data = Promise.resolve(new Float32Array(length));
  1905. }
  1906. else {
  1907. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  1908. accessor._data = this.loadBufferViewAsync("/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  1909. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  1910. });
  1911. }
  1912. if (accessor.sparse) {
  1913. var sparse_1 = accessor.sparse;
  1914. accessor._data = accessor._data.then(function (data) {
  1915. var indicesBufferView = ArrayItem.Get(context + "/sparse/indices/bufferView", _this.gltf.bufferViews, sparse_1.indices.bufferView);
  1916. var valuesBufferView = ArrayItem.Get(context + "/sparse/values/bufferView", _this.gltf.bufferViews, sparse_1.values.bufferView);
  1917. return Promise.all([
  1918. _this.loadBufferViewAsync("/bufferViews/" + indicesBufferView.index, indicesBufferView),
  1919. _this.loadBufferViewAsync("/bufferViews/" + valuesBufferView.index, valuesBufferView)
  1920. ]).then(function (_a) {
  1921. var indicesData = _a[0], valuesData = _a[1];
  1922. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  1923. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  1924. var valuesIndex = 0;
  1925. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  1926. var dataIndex = indices[indicesIndex] * numComponents;
  1927. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1928. data[dataIndex++] = values[valuesIndex++];
  1929. }
  1930. }
  1931. return data;
  1932. });
  1933. });
  1934. }
  1935. return accessor._data;
  1936. };
  1937. GLTFLoader.prototype._loadVertexBufferViewAsync = function (bufferView, kind) {
  1938. var _this = this;
  1939. if (bufferView._babylonBuffer) {
  1940. return bufferView._babylonBuffer;
  1941. }
  1942. bufferView._babylonBuffer = this.loadBufferViewAsync("/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  1943. return new BABYLON.Buffer(_this.babylonScene.getEngine(), data, false);
  1944. });
  1945. return bufferView._babylonBuffer;
  1946. };
  1947. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  1948. var _this = this;
  1949. if (accessor._babylonVertexBuffer) {
  1950. return accessor._babylonVertexBuffer;
  1951. }
  1952. if (accessor.sparse) {
  1953. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("/accessors/" + accessor.index, accessor).then(function (data) {
  1954. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  1955. });
  1956. }
  1957. // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
  1958. else if (accessor.byteOffset && accessor.byteOffset % BABYLON.VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
  1959. BABYLON.Tools.Warn("Accessor byte offset is not a multiple of component type byte length");
  1960. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("/accessors/" + accessor.index, accessor).then(function (data) {
  1961. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  1962. });
  1963. }
  1964. else {
  1965. var bufferView_1 = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  1966. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView_1, kind).then(function (babylonBuffer) {
  1967. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  1968. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  1969. });
  1970. }
  1971. return accessor._babylonVertexBuffer;
  1972. };
  1973. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, properties, babylonMaterial) {
  1974. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  1975. throw new Error(context + ": Material type not supported");
  1976. }
  1977. var promises = new Array();
  1978. if (properties) {
  1979. if (properties.baseColorFactor) {
  1980. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  1981. babylonMaterial.alpha = properties.baseColorFactor[3];
  1982. }
  1983. else {
  1984. babylonMaterial.albedoColor = BABYLON.Color3.White();
  1985. }
  1986. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  1987. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  1988. if (properties.baseColorTexture) {
  1989. promises.push(this.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  1990. texture.name = babylonMaterial.name + " (Base Color)";
  1991. babylonMaterial.albedoTexture = texture;
  1992. }));
  1993. }
  1994. if (properties.metallicRoughnessTexture) {
  1995. promises.push(this.loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  1996. texture.name = babylonMaterial.name + " (Metallic Roughness)";
  1997. babylonMaterial.metallicTexture = texture;
  1998. }));
  1999. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  2000. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  2001. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  2002. }
  2003. }
  2004. return Promise.all(promises).then(function () { });
  2005. };
  2006. /** @hidden */
  2007. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2008. if (assign === void 0) { assign = function () { }; }
  2009. var extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
  2010. if (extensionPromise) {
  2011. return extensionPromise;
  2012. }
  2013. material._data = material._data || {};
  2014. var babylonData = material._data[babylonDrawMode];
  2015. if (!babylonData) {
  2016. this.logOpen(context + " " + (material.name || ""));
  2017. var babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
  2018. babylonData = {
  2019. babylonMaterial: babylonMaterial,
  2020. babylonMeshes: [],
  2021. promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
  2022. };
  2023. material._data[babylonDrawMode] = babylonData;
  2024. GLTFLoader.AddPointerMetadata(babylonMaterial, context);
  2025. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  2026. this.logClose();
  2027. }
  2028. babylonData.babylonMeshes.push(babylonMesh);
  2029. babylonMesh.onDisposeObservable.addOnce(function () {
  2030. var index = babylonData.babylonMeshes.indexOf(babylonMesh);
  2031. if (index !== -1) {
  2032. babylonData.babylonMeshes.splice(index, 1);
  2033. }
  2034. });
  2035. assign(babylonData.babylonMaterial);
  2036. return babylonData.promise.then(function () {
  2037. return babylonData.babylonMaterial;
  2038. });
  2039. };
  2040. GLTFLoader.prototype._createDefaultMaterial = function (name, babylonDrawMode) {
  2041. var babylonMaterial = new BABYLON.PBRMaterial(name, this.babylonScene);
  2042. babylonMaterial.sideOrientation = this.babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  2043. babylonMaterial.fillMode = babylonDrawMode;
  2044. babylonMaterial.enableSpecularAntiAliasing = true;
  2045. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  2046. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  2047. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  2048. babylonMaterial.metallic = 1;
  2049. babylonMaterial.roughness = 1;
  2050. return babylonMaterial;
  2051. };
  2052. /**
  2053. * Creates a Babylon material from a glTF material.
  2054. * @param context The context when loading the asset
  2055. * @param material The glTF material property
  2056. * @param babylonDrawMode The draw mode for the Babylon material
  2057. * @returns The Babylon material
  2058. */
  2059. GLTFLoader.prototype.createMaterial = function (context, material, babylonDrawMode) {
  2060. var extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
  2061. if (extensionPromise) {
  2062. return extensionPromise;
  2063. }
  2064. var name = material.name || "material" + material.index;
  2065. var babylonMaterial = this._createDefaultMaterial(name, babylonDrawMode);
  2066. return babylonMaterial;
  2067. };
  2068. /**
  2069. * Loads properties from a glTF material into a Babylon material.
  2070. * @param context The context when loading the asset
  2071. * @param material The glTF material property
  2072. * @param babylonMaterial The Babylon material
  2073. * @returns A promise that resolves when the load is complete
  2074. */
  2075. GLTFLoader.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2076. var extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
  2077. if (extensionPromise) {
  2078. return extensionPromise;
  2079. }
  2080. var promises = new Array();
  2081. promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  2082. if (material.pbrMetallicRoughness) {
  2083. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context + "/pbrMetallicRoughness", material.pbrMetallicRoughness, babylonMaterial));
  2084. }
  2085. this.loadMaterialAlphaProperties(context, material, babylonMaterial);
  2086. return Promise.all(promises).then(function () { });
  2087. };
  2088. /**
  2089. * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
  2090. * @param context The context when loading the asset
  2091. * @param material The glTF material property
  2092. * @param babylonMaterial The Babylon material
  2093. * @returns A promise that resolves when the load is complete
  2094. */
  2095. GLTFLoader.prototype.loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  2096. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  2097. throw new Error(context + ": Material type not supported");
  2098. }
  2099. var promises = new Array();
  2100. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  2101. if (material.doubleSided) {
  2102. babylonMaterial.backFaceCulling = false;
  2103. babylonMaterial.twoSidedLighting = true;
  2104. }
  2105. if (material.normalTexture) {
  2106. promises.push(this.loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  2107. texture.name = babylonMaterial.name + " (Normal)";
  2108. babylonMaterial.bumpTexture = texture;
  2109. }));
  2110. babylonMaterial.invertNormalMapX = !this.babylonScene.useRightHandedSystem;
  2111. babylonMaterial.invertNormalMapY = this.babylonScene.useRightHandedSystem;
  2112. if (material.normalTexture.scale != undefined) {
  2113. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  2114. }
  2115. }
  2116. if (material.occlusionTexture) {
  2117. promises.push(this.loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  2118. texture.name = babylonMaterial.name + " (Occlusion)";
  2119. babylonMaterial.ambientTexture = texture;
  2120. }));
  2121. babylonMaterial.useAmbientInGrayScale = true;
  2122. if (material.occlusionTexture.strength != undefined) {
  2123. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  2124. }
  2125. }
  2126. if (material.emissiveTexture) {
  2127. promises.push(this.loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  2128. texture.name = babylonMaterial.name + " (Emissive)";
  2129. babylonMaterial.emissiveTexture = texture;
  2130. }));
  2131. }
  2132. return Promise.all(promises).then(function () { });
  2133. };
  2134. /**
  2135. * Loads the alpha properties from a glTF material into a Babylon material.
  2136. * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
  2137. * @param context The context when loading the asset
  2138. * @param material The glTF material property
  2139. * @param babylonMaterial The Babylon material
  2140. */
  2141. GLTFLoader.prototype.loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  2142. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  2143. throw new Error(context + ": Material type not supported");
  2144. }
  2145. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  2146. switch (alphaMode) {
  2147. case "OPAQUE" /* OPAQUE */: {
  2148. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  2149. break;
  2150. }
  2151. case "MASK" /* MASK */: {
  2152. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  2153. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  2154. if (babylonMaterial.albedoTexture) {
  2155. babylonMaterial.albedoTexture.hasAlpha = true;
  2156. }
  2157. break;
  2158. }
  2159. case "BLEND" /* BLEND */: {
  2160. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  2161. if (babylonMaterial.albedoTexture) {
  2162. babylonMaterial.albedoTexture.hasAlpha = true;
  2163. babylonMaterial.useAlphaFromAlbedoTexture = true;
  2164. }
  2165. break;
  2166. }
  2167. default: {
  2168. throw new Error(context + "/alphaMode: Invalid value (" + material.alphaMode + ")");
  2169. }
  2170. }
  2171. };
  2172. /**
  2173. * Loads a glTF texture info.
  2174. * @param context The context when loading the asset
  2175. * @param textureInfo The glTF texture info property
  2176. * @param assign A function called synchronously after parsing the glTF properties
  2177. * @returns A promise that resolves with the loaded Babylon texture when the load is complete
  2178. */
  2179. GLTFLoader.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  2180. var _this = this;
  2181. if (assign === void 0) { assign = function () { }; }
  2182. var extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
  2183. if (extensionPromise) {
  2184. return extensionPromise;
  2185. }
  2186. this.logOpen("" + context);
  2187. var texture = ArrayItem.Get(context + "/index", this.gltf.textures, textureInfo.index);
  2188. var promise = this._loadTextureAsync("/textures/" + textureInfo.index, texture, function (babylonTexture) {
  2189. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  2190. GLTFLoader.AddPointerMetadata(babylonTexture, context);
  2191. _this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  2192. assign(babylonTexture);
  2193. });
  2194. this.logClose();
  2195. return promise;
  2196. };
  2197. GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) {
  2198. var _this = this;
  2199. if (assign === void 0) { assign = function () { }; }
  2200. var promises = new Array();
  2201. this.logOpen(context + " " + (texture.name || ""));
  2202. var sampler = (texture.sampler == undefined ? GLTFLoader._DefaultSampler : ArrayItem.Get(context + "/sampler", this.gltf.samplers, texture.sampler));
  2203. var samplerData = this._loadSampler("/samplers/" + sampler.index, sampler);
  2204. var image = ArrayItem.Get(context + "/source", this.gltf.images, texture.source);
  2205. var url = null;
  2206. if (image.uri) {
  2207. if (BABYLON.Tools.IsBase64(image.uri)) {
  2208. url = image.uri;
  2209. }
  2210. else if (this.babylonScene.getEngine().textureFormatInUse) {
  2211. // If an image uri and a texture format is set like (eg. KTX) load from url instead of blob to support texture format and fallback
  2212. url = this._rootUrl + image.uri;
  2213. }
  2214. }
  2215. var deferred = new BABYLON.Deferred();
  2216. var babylonTexture = new BABYLON.Texture(url, this.babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  2217. if (!_this._disposed) {
  2218. deferred.resolve();
  2219. }
  2220. }, function (message, exception) {
  2221. if (!_this._disposed) {
  2222. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  2223. }
  2224. });
  2225. promises.push(deferred.promise);
  2226. if (!url) {
  2227. promises.push(this.loadImageAsync("/images/" + image.index, image).then(function (data) {
  2228. var name = image.uri || _this._fileName + "#image" + image.index;
  2229. var dataUrl = "data:" + _this._uniqueRootUrl + name;
  2230. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  2231. }));
  2232. }
  2233. babylonTexture.wrapU = samplerData.wrapU;
  2234. babylonTexture.wrapV = samplerData.wrapV;
  2235. assign(babylonTexture);
  2236. this.logClose();
  2237. return Promise.all(promises).then(function () {
  2238. return babylonTexture;
  2239. });
  2240. };
  2241. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  2242. if (!sampler._data) {
  2243. sampler._data = {
  2244. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  2245. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler),
  2246. wrapU: GLTFLoader._GetTextureWrapMode(context + "/wrapS", sampler.wrapS),
  2247. wrapV: GLTFLoader._GetTextureWrapMode(context + "/wrapT", sampler.wrapT)
  2248. };
  2249. }
  2250. return sampler._data;
  2251. };
  2252. /**
  2253. * Loads a glTF image.
  2254. * @param context The context when loading the asset
  2255. * @param image The glTF image property
  2256. * @returns A promise that resolves with the loaded data when the load is complete
  2257. */
  2258. GLTFLoader.prototype.loadImageAsync = function (context, image) {
  2259. if (!image._data) {
  2260. this.logOpen(context + " " + (image.name || ""));
  2261. if (image.uri) {
  2262. image._data = this.loadUriAsync(context + "/uri", image.uri);
  2263. }
  2264. else {
  2265. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, image.bufferView);
  2266. image._data = this.loadBufferViewAsync("/bufferViews/" + bufferView.index, bufferView);
  2267. }
  2268. this.logClose();
  2269. }
  2270. return image._data;
  2271. };
  2272. /**
  2273. * Loads a glTF uri.
  2274. * @param context The context when loading the asset
  2275. * @param uri The base64 or relative uri
  2276. * @returns A promise that resolves with the loaded data when the load is complete
  2277. */
  2278. GLTFLoader.prototype.loadUriAsync = function (context, uri) {
  2279. var _this = this;
  2280. var extensionPromise = this._extensionsLoadUriAsync(context, uri);
  2281. if (extensionPromise) {
  2282. return extensionPromise;
  2283. }
  2284. if (!GLTFLoader._ValidateUri(uri)) {
  2285. throw new Error(context + ": '" + uri + "' is invalid");
  2286. }
  2287. if (BABYLON.Tools.IsBase64(uri)) {
  2288. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  2289. this.log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  2290. return Promise.resolve(data);
  2291. }
  2292. this.log("Loading " + uri);
  2293. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  2294. return new Promise(function (resolve, reject) {
  2295. if (!_this._disposed) {
  2296. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  2297. if (!_this._disposed) {
  2298. var data = new Uint8Array(fileData);
  2299. _this.log("Loaded " + uri + " (" + data.length + " bytes)");
  2300. resolve(data);
  2301. }
  2302. }, function (event) {
  2303. if (!_this._disposed) {
  2304. if (request_1) {
  2305. request_1._lengthComputable = event.lengthComputable;
  2306. request_1._loaded = event.loaded;
  2307. request_1._total = event.total;
  2308. }
  2309. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  2310. try {
  2311. _this._onProgress();
  2312. }
  2313. catch (e) {
  2314. reject(e);
  2315. }
  2316. }
  2317. }
  2318. }, _this.babylonScene.offlineProvider, true, function (request, exception) {
  2319. if (!_this._disposed) {
  2320. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  2321. }
  2322. });
  2323. _this._requests.push(request_1);
  2324. }
  2325. });
  2326. });
  2327. };
  2328. GLTFLoader.prototype._onProgress = function () {
  2329. if (!this._progressCallback) {
  2330. return;
  2331. }
  2332. var lengthComputable = true;
  2333. var loaded = 0;
  2334. var total = 0;
  2335. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  2336. var request = _a[_i];
  2337. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  2338. return;
  2339. }
  2340. lengthComputable = lengthComputable && request._lengthComputable;
  2341. loaded += request._loaded;
  2342. total += request._total;
  2343. }
  2344. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  2345. };
  2346. /**
  2347. * Adds a JSON pointer to the metadata of the Babylon object at `<object>.metadata.gltf.pointers`.
  2348. * @param babylonObject the Babylon object with metadata
  2349. * @param pointer the JSON pointer
  2350. */
  2351. GLTFLoader.AddPointerMetadata = function (babylonObject, pointer) {
  2352. var metadata = (babylonObject.metadata = babylonObject.metadata || {});
  2353. var gltf = (metadata.gltf = metadata.gltf || {});
  2354. var pointers = (gltf.pointers = gltf.pointers || []);
  2355. pointers.push(pointer);
  2356. };
  2357. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  2358. // Set defaults if undefined
  2359. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  2360. switch (mode) {
  2361. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2362. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2363. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2364. default:
  2365. BABYLON.Tools.Warn(context + ": Invalid value (" + mode + ")");
  2366. return BABYLON.Texture.WRAP_ADDRESSMODE;
  2367. }
  2368. };
  2369. GLTFLoader._GetTextureSamplingMode = function (context, sampler) {
  2370. // Set defaults if undefined
  2371. var magFilter = sampler.magFilter == undefined ? 9729 /* LINEAR */ : sampler.magFilter;
  2372. var minFilter = sampler.minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : sampler.minFilter;
  2373. if (magFilter === 9729 /* LINEAR */) {
  2374. switch (minFilter) {
  2375. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  2376. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  2377. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  2378. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  2379. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  2380. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  2381. default:
  2382. BABYLON.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  2383. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  2384. }
  2385. }
  2386. else {
  2387. if (magFilter !== 9728 /* NEAREST */) {
  2388. BABYLON.Tools.Warn(context + "/magFilter: Invalid value (" + magFilter + ")");
  2389. }
  2390. switch (minFilter) {
  2391. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  2392. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  2393. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  2394. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  2395. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  2396. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  2397. default:
  2398. BABYLON.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  2399. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  2400. }
  2401. }
  2402. };
  2403. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  2404. var buffer = bufferView.buffer;
  2405. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  2406. try {
  2407. switch (componentType) {
  2408. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  2409. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  2410. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  2411. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  2412. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  2413. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  2414. default: throw new Error("Invalid component type " + componentType);
  2415. }
  2416. }
  2417. catch (e) {
  2418. throw new Error(context + ": " + e);
  2419. }
  2420. };
  2421. GLTFLoader._GetNumComponents = function (context, type) {
  2422. switch (type) {
  2423. case "SCALAR": return 1;
  2424. case "VEC2": return 2;
  2425. case "VEC3": return 3;
  2426. case "VEC4": return 4;
  2427. case "MAT2": return 4;
  2428. case "MAT3": return 9;
  2429. case "MAT4": return 16;
  2430. }
  2431. throw new Error(context + ": Invalid type (" + type + ")");
  2432. };
  2433. GLTFLoader._ValidateUri = function (uri) {
  2434. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  2435. };
  2436. GLTFLoader._GetDrawMode = function (context, mode) {
  2437. if (mode == undefined) {
  2438. mode = 4 /* TRIANGLES */;
  2439. }
  2440. switch (mode) {
  2441. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  2442. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  2443. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  2444. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  2445. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  2446. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  2447. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  2448. }
  2449. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  2450. };
  2451. GLTFLoader.prototype._compileMaterialsAsync = function () {
  2452. var _this = this;
  2453. this._parent._startPerformanceCounter("Compile materials");
  2454. var promises = new Array();
  2455. if (this.gltf.materials) {
  2456. for (var _i = 0, _a = this.gltf.materials; _i < _a.length; _i++) {
  2457. var material = _a[_i];
  2458. if (material._data) {
  2459. for (var babylonDrawMode in material._data) {
  2460. var babylonData = material._data[babylonDrawMode];
  2461. for (var _b = 0, _c = babylonData.babylonMeshes; _b < _c.length; _b++) {
  2462. var babylonMesh = _c[_b];
  2463. // Ensure nonUniformScaling is set if necessary.
  2464. babylonMesh.computeWorldMatrix(true);
  2465. var babylonMaterial = babylonData.babylonMaterial;
  2466. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  2467. if (this._parent.useClipPlane) {
  2468. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  2469. }
  2470. }
  2471. }
  2472. }
  2473. }
  2474. }
  2475. return Promise.all(promises).then(function () {
  2476. _this._parent._endPerformanceCounter("Compile materials");
  2477. });
  2478. };
  2479. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  2480. var _this = this;
  2481. this._parent._startPerformanceCounter("Compile shadow generators");
  2482. var promises = new Array();
  2483. var lights = this.babylonScene.lights;
  2484. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  2485. var light = lights_1[_i];
  2486. var generator = light.getShadowGenerator();
  2487. if (generator) {
  2488. promises.push(generator.forceCompilationAsync());
  2489. }
  2490. }
  2491. return Promise.all(promises).then(function () {
  2492. _this._parent._endPerformanceCounter("Compile shadow generators");
  2493. });
  2494. };
  2495. GLTFLoader.prototype._forEachExtensions = function (action) {
  2496. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  2497. var name_4 = _a[_i];
  2498. var extension = this._extensions[name_4];
  2499. if (extension.enabled) {
  2500. action(extension);
  2501. }
  2502. }
  2503. };
  2504. GLTFLoader.prototype._applyExtensions = function (property, actionAsync) {
  2505. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  2506. var name_5 = _a[_i];
  2507. var extension = this._extensions[name_5];
  2508. if (extension.enabled) {
  2509. var loaderProperty = property;
  2510. loaderProperty._activeLoaderExtensions = loaderProperty._activeLoaderExtensions || {};
  2511. var activeLoaderExtensions = loaderProperty._activeLoaderExtensions;
  2512. if (!activeLoaderExtensions[name_5]) {
  2513. activeLoaderExtensions[name_5] = true;
  2514. try {
  2515. var result = actionAsync(extension);
  2516. if (result) {
  2517. return result;
  2518. }
  2519. }
  2520. finally {
  2521. delete activeLoaderExtensions[name_5];
  2522. }
  2523. }
  2524. }
  2525. }
  2526. return null;
  2527. };
  2528. GLTFLoader.prototype._extensionsOnLoading = function () {
  2529. this._forEachExtensions(function (extension) { return extension.onLoading && extension.onLoading(); });
  2530. };
  2531. GLTFLoader.prototype._extensionsOnReady = function () {
  2532. this._forEachExtensions(function (extension) { return extension.onReady && extension.onReady(); });
  2533. };
  2534. GLTFLoader.prototype._extensionsLoadSceneAsync = function (context, scene) {
  2535. return this._applyExtensions(scene, function (extension) { return extension.loadSceneAsync && extension.loadSceneAsync(context, scene); });
  2536. };
  2537. GLTFLoader.prototype._extensionsLoadNodeAsync = function (context, node, assign) {
  2538. return this._applyExtensions(node, function (extension) { return extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign); });
  2539. };
  2540. GLTFLoader.prototype._extensionsLoadCameraAsync = function (context, camera, assign) {
  2541. return this._applyExtensions(camera, function (extension) { return extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign); });
  2542. };
  2543. GLTFLoader.prototype._extensionsLoadVertexDataAsync = function (context, primitive, babylonMesh) {
  2544. return this._applyExtensions(primitive, function (extension) { return extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  2545. };
  2546. GLTFLoader.prototype._extensionsLoadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2547. return this._applyExtensions(material, function (extension) { return extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  2548. };
  2549. GLTFLoader.prototype._extensionsCreateMaterial = function (context, material, babylonDrawMode) {
  2550. return this._applyExtensions({}, function (extension) { return extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode); });
  2551. };
  2552. GLTFLoader.prototype._extensionsLoadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2553. return this._applyExtensions(material, function (extension) { return extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  2554. };
  2555. GLTFLoader.prototype._extensionsLoadTextureInfoAsync = function (context, textureInfo, assign) {
  2556. return this._applyExtensions(textureInfo, function (extension) { return extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign); });
  2557. };
  2558. GLTFLoader.prototype._extensionsLoadAnimationAsync = function (context, animation) {
  2559. return this._applyExtensions(animation, function (extension) { return extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation); });
  2560. };
  2561. GLTFLoader.prototype._extensionsLoadUriAsync = function (context, uri) {
  2562. return this._applyExtensions({}, function (extension) { return extension._loadUriAsync && extension._loadUriAsync(context, uri); });
  2563. };
  2564. /**
  2565. * Helper method called by a loader extension to load an glTF extension.
  2566. * @param context The context when loading the asset
  2567. * @param property The glTF property to load the extension from
  2568. * @param extensionName The name of the extension to load
  2569. * @param actionAsync The action to run
  2570. * @returns The promise returned by actionAsync or null if the extension does not exist
  2571. */
  2572. GLTFLoader.LoadExtensionAsync = function (context, property, extensionName, actionAsync) {
  2573. if (!property.extensions) {
  2574. return null;
  2575. }
  2576. var extensions = property.extensions;
  2577. var extension = extensions[extensionName];
  2578. if (!extension) {
  2579. return null;
  2580. }
  2581. return actionAsync(context + "/extensions/" + extensionName, extension);
  2582. };
  2583. /**
  2584. * Helper method called by a loader extension to load a glTF extra.
  2585. * @param context The context when loading the asset
  2586. * @param property The glTF property to load the extra from
  2587. * @param extensionName The name of the extension to load
  2588. * @param actionAsync The action to run
  2589. * @returns The promise returned by actionAsync or null if the extra does not exist
  2590. */
  2591. GLTFLoader.LoadExtraAsync = function (context, property, extensionName, actionAsync) {
  2592. if (!property.extras) {
  2593. return null;
  2594. }
  2595. var extras = property.extras;
  2596. var extra = extras[extensionName];
  2597. if (!extra) {
  2598. return null;
  2599. }
  2600. return actionAsync(context + "/extras/" + extensionName, extra);
  2601. };
  2602. /**
  2603. * Increments the indentation level and logs a message.
  2604. * @param message The message to log
  2605. */
  2606. GLTFLoader.prototype.logOpen = function (message) {
  2607. this._parent._logOpen(message);
  2608. };
  2609. /**
  2610. * Decrements the indentation level.
  2611. */
  2612. GLTFLoader.prototype.logClose = function () {
  2613. this._parent._logClose();
  2614. };
  2615. /**
  2616. * Logs a message
  2617. * @param message The message to log
  2618. */
  2619. GLTFLoader.prototype.log = function (message) {
  2620. this._parent._log(message);
  2621. };
  2622. /**
  2623. * Starts a performance counter.
  2624. * @param counterName The name of the performance counter
  2625. */
  2626. GLTFLoader.prototype.startPerformanceCounter = function (counterName) {
  2627. this._parent._startPerformanceCounter(counterName);
  2628. };
  2629. /**
  2630. * Ends a performance counter.
  2631. * @param counterName The name of the performance counter
  2632. */
  2633. GLTFLoader.prototype.endPerformanceCounter = function (counterName) {
  2634. this._parent._endPerformanceCounter(counterName);
  2635. };
  2636. GLTFLoader._DefaultSampler = { index: -1 };
  2637. GLTFLoader._ExtensionNames = new Array();
  2638. GLTFLoader._ExtensionFactories = {};
  2639. return GLTFLoader;
  2640. }());
  2641. GLTF2.GLTFLoader = GLTFLoader;
  2642. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  2643. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2644. })(BABYLON || (BABYLON = {}));
  2645. //# sourceMappingURL=babylon.glTFLoader.js.map
  2646. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2647. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2648. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2649. var BABYLON;
  2650. (function (BABYLON) {
  2651. var GLTF2;
  2652. (function (GLTF2) {
  2653. var Loader;
  2654. (function (Loader) {
  2655. var Extensions;
  2656. (function (Extensions) {
  2657. var NAME = "MSFT_lod";
  2658. /**
  2659. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  2660. */
  2661. var MSFT_lod = /** @class */ (function () {
  2662. /** @hidden */
  2663. function MSFT_lod(loader) {
  2664. /** The name of this extension. */
  2665. this.name = NAME;
  2666. /** Defines whether this extension is enabled. */
  2667. this.enabled = true;
  2668. /**
  2669. * Maximum number of LODs to load, starting from the lowest LOD.
  2670. */
  2671. this.maxLODsToLoad = Number.MAX_VALUE;
  2672. /**
  2673. * Observable raised when all node LODs of one level are loaded.
  2674. * The event data is the index of the loaded LOD starting from zero.
  2675. * Dispose the loader to cancel the loading of the next level of LODs.
  2676. */
  2677. this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  2678. /**
  2679. * Observable raised when all material LODs of one level are loaded.
  2680. * The event data is the index of the loaded LOD starting from zero.
  2681. * Dispose the loader to cancel the loading of the next level of LODs.
  2682. */
  2683. this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  2684. this._nodeIndexLOD = null;
  2685. this._nodeSignalLODs = new Array();
  2686. this._nodePromiseLODs = new Array();
  2687. this._materialIndexLOD = null;
  2688. this._materialSignalLODs = new Array();
  2689. this._materialPromiseLODs = new Array();
  2690. this._loader = loader;
  2691. }
  2692. /** @hidden */
  2693. MSFT_lod.prototype.dispose = function () {
  2694. delete this._loader;
  2695. this._nodeIndexLOD = null;
  2696. this._nodeSignalLODs.length = 0;
  2697. this._nodePromiseLODs.length = 0;
  2698. this._materialIndexLOD = null;
  2699. this._materialSignalLODs.length = 0;
  2700. this._materialPromiseLODs.length = 0;
  2701. this.onMaterialLODsLoadedObservable.clear();
  2702. this.onNodeLODsLoadedObservable.clear();
  2703. };
  2704. /** @hidden */
  2705. MSFT_lod.prototype.onReady = function () {
  2706. var _this = this;
  2707. var _loop_1 = function (indexLOD) {
  2708. var promise = Promise.all(this_1._nodePromiseLODs[indexLOD]).then(function () {
  2709. if (indexLOD !== 0) {
  2710. _this._loader.endPerformanceCounter("Node LOD " + indexLOD);
  2711. }
  2712. _this._loader.log("Loaded node LOD " + indexLOD);
  2713. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  2714. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  2715. _this._loader.startPerformanceCounter("Node LOD " + (indexLOD + 1));
  2716. if (_this._nodeSignalLODs[indexLOD]) {
  2717. _this._nodeSignalLODs[indexLOD].resolve();
  2718. }
  2719. }
  2720. });
  2721. this_1._loader._completePromises.push(promise);
  2722. };
  2723. var this_1 = this;
  2724. for (var indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {
  2725. _loop_1(indexLOD);
  2726. }
  2727. var _loop_2 = function (indexLOD) {
  2728. var promise = Promise.all(this_2._materialPromiseLODs[indexLOD]).then(function () {
  2729. if (indexLOD !== 0) {
  2730. _this._loader.endPerformanceCounter("Material LOD " + indexLOD);
  2731. }
  2732. _this._loader.log("Loaded material LOD " + indexLOD);
  2733. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  2734. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  2735. _this._loader.startPerformanceCounter("Material LOD " + (indexLOD + 1));
  2736. if (_this._materialSignalLODs[indexLOD]) {
  2737. _this._materialSignalLODs[indexLOD].resolve();
  2738. }
  2739. }
  2740. });
  2741. this_2._loader._completePromises.push(promise);
  2742. };
  2743. var this_2 = this;
  2744. for (var indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {
  2745. _loop_2(indexLOD);
  2746. }
  2747. };
  2748. /** @hidden */
  2749. MSFT_lod.prototype.loadNodeAsync = function (context, node, assign) {
  2750. var _this = this;
  2751. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  2752. var firstPromise;
  2753. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader.gltf.nodes, extension.ids);
  2754. _this._loader.logOpen("" + extensionContext);
  2755. var _loop_3 = function (indexLOD) {
  2756. var nodeLOD = nodeLODs[indexLOD];
  2757. if (indexLOD !== 0) {
  2758. _this._nodeIndexLOD = indexLOD;
  2759. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  2760. }
  2761. var assign_1 = function (babylonTransformNode) { babylonTransformNode.setEnabled(false); };
  2762. var promise = _this._loader.loadNodeAsync("#/nodes/" + nodeLOD.index, nodeLOD, assign_1).then(function (babylonMesh) {
  2763. if (indexLOD !== 0) {
  2764. // TODO: should not rely on _babylonMesh
  2765. var previousNodeLOD = nodeLODs[indexLOD - 1];
  2766. if (previousNodeLOD._babylonTransformNode) {
  2767. previousNodeLOD._babylonTransformNode.dispose();
  2768. delete previousNodeLOD._babylonTransformNode;
  2769. _this._disposeUnusedMaterials();
  2770. }
  2771. }
  2772. babylonMesh.setEnabled(true);
  2773. return babylonMesh;
  2774. });
  2775. if (indexLOD === 0) {
  2776. firstPromise = promise;
  2777. }
  2778. else {
  2779. _this._nodeIndexLOD = null;
  2780. }
  2781. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  2782. _this._nodePromiseLODs[indexLOD].push(promise);
  2783. };
  2784. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  2785. _loop_3(indexLOD);
  2786. }
  2787. _this._loader.logClose();
  2788. return firstPromise;
  2789. });
  2790. };
  2791. /** @hidden */
  2792. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2793. var _this = this;
  2794. // Don't load material LODs if already loading a node LOD.
  2795. if (this._nodeIndexLOD) {
  2796. return null;
  2797. }
  2798. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  2799. var firstPromise;
  2800. var materialLODs = _this._getLODs(extensionContext, material, _this._loader.gltf.materials, extension.ids);
  2801. _this._loader.logOpen("" + extensionContext);
  2802. var _loop_4 = function (indexLOD) {
  2803. var materialLOD = materialLODs[indexLOD];
  2804. if (indexLOD !== 0) {
  2805. _this._materialIndexLOD = indexLOD;
  2806. }
  2807. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD.index, materialLOD, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  2808. if (indexLOD === 0) {
  2809. assign(babylonMaterial);
  2810. }
  2811. }).then(function (babylonMaterial) {
  2812. if (indexLOD !== 0) {
  2813. assign(babylonMaterial);
  2814. // TODO: should not rely on _data
  2815. var previousDataLOD = materialLODs[indexLOD - 1]._data;
  2816. if (previousDataLOD[babylonDrawMode]) {
  2817. previousDataLOD[babylonDrawMode].babylonMaterial.dispose();
  2818. delete previousDataLOD[babylonDrawMode];
  2819. }
  2820. }
  2821. return babylonMaterial;
  2822. });
  2823. if (indexLOD === 0) {
  2824. firstPromise = promise;
  2825. }
  2826. else {
  2827. _this._materialIndexLOD = null;
  2828. }
  2829. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  2830. _this._materialPromiseLODs[indexLOD].push(promise);
  2831. };
  2832. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  2833. _loop_4(indexLOD);
  2834. }
  2835. _this._loader.logClose();
  2836. return firstPromise;
  2837. });
  2838. };
  2839. /** @hidden */
  2840. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  2841. var _this = this;
  2842. // Defer the loading of uris if loading a material or node LOD.
  2843. if (this._materialIndexLOD !== null) {
  2844. this._loader.log("deferred");
  2845. var previousIndexLOD = this._materialIndexLOD - 1;
  2846. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  2847. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  2848. return _this._loader.loadUriAsync(context, uri);
  2849. });
  2850. }
  2851. else if (this._nodeIndexLOD !== null) {
  2852. this._loader.log("deferred");
  2853. var previousIndexLOD = this._nodeIndexLOD - 1;
  2854. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  2855. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  2856. return _this._loader.loadUriAsync(context, uri);
  2857. });
  2858. }
  2859. return null;
  2860. };
  2861. /**
  2862. * Gets an array of LOD properties from lowest to highest.
  2863. */
  2864. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  2865. if (this.maxLODsToLoad <= 0) {
  2866. throw new Error("maxLODsToLoad must be greater than zero");
  2867. }
  2868. var properties = new Array();
  2869. for (var i = ids.length - 1; i >= 0; i--) {
  2870. properties.push(GLTF2.ArrayItem.Get(context + "/ids/" + ids[i], array, ids[i]));
  2871. if (properties.length === this.maxLODsToLoad) {
  2872. return properties;
  2873. }
  2874. }
  2875. properties.push(property);
  2876. return properties;
  2877. };
  2878. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  2879. // TODO: should not rely on _data
  2880. var materials = this._loader.gltf.materials;
  2881. if (materials) {
  2882. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  2883. var material = materials_1[_i];
  2884. if (material._data) {
  2885. for (var drawMode in material._data) {
  2886. var data = material._data[drawMode];
  2887. if (data.babylonMeshes.length === 0) {
  2888. data.babylonMaterial.dispose(false, true);
  2889. delete material._data[drawMode];
  2890. }
  2891. }
  2892. }
  2893. }
  2894. }
  2895. };
  2896. return MSFT_lod;
  2897. }());
  2898. Extensions.MSFT_lod = MSFT_lod;
  2899. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_lod(loader); });
  2900. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  2901. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  2902. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2903. })(BABYLON || (BABYLON = {}));
  2904. //# sourceMappingURL=MSFT_lod.js.map
  2905. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2906. var BABYLON;
  2907. (function (BABYLON) {
  2908. var GLTF2;
  2909. (function (GLTF2) {
  2910. var Loader;
  2911. (function (Loader) {
  2912. var Extensions;
  2913. (function (Extensions) {
  2914. var NAME = "MSFT_minecraftMesh";
  2915. /** @hidden */
  2916. var MSFT_minecraftMesh = /** @class */ (function () {
  2917. function MSFT_minecraftMesh(loader) {
  2918. this.name = NAME;
  2919. this.enabled = true;
  2920. this._loader = loader;
  2921. }
  2922. MSFT_minecraftMesh.prototype.dispose = function () {
  2923. delete this._loader;
  2924. };
  2925. MSFT_minecraftMesh.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2926. var _this = this;
  2927. return GLTF2.GLTFLoader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  2928. if (extra) {
  2929. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  2930. throw new Error(extraContext + ": Material type not supported");
  2931. }
  2932. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  2933. if (babylonMaterial.needAlphaBlending()) {
  2934. babylonMaterial.forceDepthWrite = true;
  2935. babylonMaterial.separateCullingPass = true;
  2936. }
  2937. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  2938. babylonMaterial.twoSidedLighting = true;
  2939. return promise;
  2940. }
  2941. return null;
  2942. });
  2943. };
  2944. return MSFT_minecraftMesh;
  2945. }());
  2946. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  2947. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  2948. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  2949. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  2950. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2951. })(BABYLON || (BABYLON = {}));
  2952. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  2953. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2954. var BABYLON;
  2955. (function (BABYLON) {
  2956. var GLTF2;
  2957. (function (GLTF2) {
  2958. var Loader;
  2959. (function (Loader) {
  2960. var Extensions;
  2961. (function (Extensions) {
  2962. var NAME = "MSFT_sRGBFactors";
  2963. /** @hidden */
  2964. var MSFT_sRGBFactors = /** @class */ (function () {
  2965. function MSFT_sRGBFactors(loader) {
  2966. this.name = NAME;
  2967. this.enabled = true;
  2968. this._loader = loader;
  2969. }
  2970. MSFT_sRGBFactors.prototype.dispose = function () {
  2971. delete this._loader;
  2972. };
  2973. MSFT_sRGBFactors.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2974. var _this = this;
  2975. return GLTF2.GLTFLoader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  2976. if (extra) {
  2977. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  2978. throw new Error(extraContext + ": Material type not supported");
  2979. }
  2980. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  2981. if (!babylonMaterial.albedoTexture) {
  2982. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  2983. }
  2984. if (!babylonMaterial.reflectivityTexture) {
  2985. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  2986. }
  2987. return promise;
  2988. }
  2989. return null;
  2990. });
  2991. };
  2992. return MSFT_sRGBFactors;
  2993. }());
  2994. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  2995. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  2996. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  2997. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  2998. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2999. })(BABYLON || (BABYLON = {}));
  3000. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  3001. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3002. var BABYLON;
  3003. (function (BABYLON) {
  3004. var GLTF2;
  3005. (function (GLTF2) {
  3006. var Loader;
  3007. (function (Loader) {
  3008. var Extensions;
  3009. (function (Extensions) {
  3010. var NAME = "MSFT_audio_emitter";
  3011. /**
  3012. * [Specification](https://github.com/najadojo/glTF/tree/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter)
  3013. */
  3014. var MSFT_audio_emitter = /** @class */ (function () {
  3015. /** @hidden */
  3016. function MSFT_audio_emitter(loader) {
  3017. /** The name of this extension. */
  3018. this.name = NAME;
  3019. /** Defines whether this extension is enabled. */
  3020. this.enabled = true;
  3021. this._loader = loader;
  3022. }
  3023. /** @hidden */
  3024. MSFT_audio_emitter.prototype.dispose = function () {
  3025. delete this._loader;
  3026. delete this._clips;
  3027. delete this._emitters;
  3028. };
  3029. /** @hidden */
  3030. MSFT_audio_emitter.prototype.onLoading = function () {
  3031. var extensions = this._loader.gltf.extensions;
  3032. if (extensions && extensions[this.name]) {
  3033. var extension = extensions[this.name];
  3034. this._clips = extension.clips;
  3035. this._emitters = extension.emitters;
  3036. GLTF2.ArrayItem.Assign(this._clips);
  3037. GLTF2.ArrayItem.Assign(this._emitters);
  3038. }
  3039. };
  3040. /** @hidden */
  3041. MSFT_audio_emitter.prototype.loadSceneAsync = function (context, scene) {
  3042. var _this = this;
  3043. return GLTF2.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  3044. var promises = new Array();
  3045. promises.push(_this._loader.loadSceneAsync(context, scene));
  3046. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  3047. var emitterIndex = _a[_i];
  3048. var emitter = GLTF2.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  3049. if (emitter.refDistance != undefined || emitter.maxDistance != undefined || emitter.rolloffFactor != undefined ||
  3050. emitter.distanceModel != undefined || emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  3051. throw new Error(extensionContext + ": Direction or Distance properties are not allowed on emitters attached to a scene");
  3052. }
  3053. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter));
  3054. }
  3055. return Promise.all(promises).then(function () { });
  3056. });
  3057. };
  3058. /** @hidden */
  3059. MSFT_audio_emitter.prototype.loadNodeAsync = function (context, node, assign) {
  3060. var _this = this;
  3061. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  3062. var promises = new Array();
  3063. return _this._loader.loadNodeAsync(extensionContext, node, function (babylonMesh) {
  3064. var _loop_1 = function (emitterIndex) {
  3065. var emitter = GLTF2.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  3066. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter).then(function () {
  3067. for (var _i = 0, _a = emitter._babylonSounds; _i < _a.length; _i++) {
  3068. var sound = _a[_i];
  3069. sound.attachToMesh(babylonMesh);
  3070. if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  3071. sound.setLocalDirectionToMesh(BABYLON.Vector3.Forward());
  3072. sound.setDirectionalCone(2 * BABYLON.Tools.ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle), 2 * BABYLON.Tools.ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle), 0);
  3073. }
  3074. }
  3075. }));
  3076. };
  3077. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  3078. var emitterIndex = _a[_i];
  3079. _loop_1(emitterIndex);
  3080. }
  3081. assign(babylonMesh);
  3082. }).then(function (babylonMesh) {
  3083. return Promise.all(promises).then(function () {
  3084. return babylonMesh;
  3085. });
  3086. });
  3087. });
  3088. };
  3089. /** @hidden */
  3090. MSFT_audio_emitter.prototype.loadAnimationAsync = function (context, animation) {
  3091. var _this = this;
  3092. return GLTF2.GLTFLoader.LoadExtensionAsync(context, animation, this.name, function (extensionContext, extension) {
  3093. return _this._loader.loadAnimationAsync(context, animation).then(function (babylonAnimationGroup) {
  3094. var promises = new Array();
  3095. GLTF2.ArrayItem.Assign(extension.events);
  3096. for (var _i = 0, _a = extension.events; _i < _a.length; _i++) {
  3097. var event_1 = _a[_i];
  3098. promises.push(_this._loadAnimationEventAsync(extensionContext + "/events/" + event_1.index, context, animation, event_1, babylonAnimationGroup));
  3099. }
  3100. return Promise.all(promises).then(function () {
  3101. return babylonAnimationGroup;
  3102. });
  3103. });
  3104. });
  3105. };
  3106. MSFT_audio_emitter.prototype._loadClipAsync = function (context, clip) {
  3107. if (clip._objectURL) {
  3108. return clip._objectURL;
  3109. }
  3110. var promise;
  3111. if (clip.uri) {
  3112. promise = this._loader.loadUriAsync(context, clip.uri);
  3113. }
  3114. else {
  3115. var bufferView = GLTF2.ArrayItem.Get(context + "/bufferView", this._loader.gltf.bufferViews, clip.bufferView);
  3116. promise = this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  3117. }
  3118. clip._objectURL = promise.then(function (data) {
  3119. return URL.createObjectURL(new Blob([data], { type: clip.mimeType }));
  3120. });
  3121. return clip._objectURL;
  3122. };
  3123. MSFT_audio_emitter.prototype._loadEmitterAsync = function (context, emitter) {
  3124. var _this = this;
  3125. emitter._babylonSounds = emitter._babylonSounds || [];
  3126. if (!emitter._babylonData) {
  3127. var clipPromises = new Array();
  3128. var name_1 = emitter.name || "emitter" + emitter.index;
  3129. var options_1 = {
  3130. loop: false,
  3131. autoplay: false,
  3132. volume: emitter.volume == undefined ? 1 : emitter.volume,
  3133. };
  3134. var _loop_2 = function (i) {
  3135. var clipContext = "#/extensions/" + this_1.name + "/clips";
  3136. var clip = GLTF2.ArrayItem.Get(clipContext, this_1._clips, emitter.clips[i].clip);
  3137. clipPromises.push(this_1._loadClipAsync(clipContext + "/" + emitter.clips[i].clip, clip).then(function (objectURL) {
  3138. var sound = emitter._babylonSounds[i] = new BABYLON.Sound(name_1, objectURL, _this._loader.babylonScene, null, options_1);
  3139. sound.refDistance = emitter.refDistance || 1;
  3140. sound.maxDistance = emitter.maxDistance || 256;
  3141. sound.rolloffFactor = emitter.rolloffFactor || 1;
  3142. sound.distanceModel = emitter.distanceModel || 'exponential';
  3143. sound._positionInEmitterSpace = true;
  3144. }));
  3145. };
  3146. var this_1 = this;
  3147. for (var i = 0; i < emitter.clips.length; i++) {
  3148. _loop_2(i);
  3149. }
  3150. var promise = Promise.all(clipPromises).then(function () {
  3151. var weights = emitter.clips.map(function (clip) { return clip.weight || 1; });
  3152. var weightedSound = new BABYLON.WeightedSound(emitter.loop || false, emitter._babylonSounds, weights);
  3153. if (emitter.innerAngle) {
  3154. weightedSound.directionalConeInnerAngle = 2 * BABYLON.Tools.ToDegrees(emitter.innerAngle);
  3155. }
  3156. if (emitter.outerAngle) {
  3157. weightedSound.directionalConeOuterAngle = 2 * BABYLON.Tools.ToDegrees(emitter.outerAngle);
  3158. }
  3159. if (emitter.volume) {
  3160. weightedSound.volume = emitter.volume;
  3161. }
  3162. emitter._babylonData.sound = weightedSound;
  3163. });
  3164. emitter._babylonData = {
  3165. loaded: promise
  3166. };
  3167. }
  3168. return emitter._babylonData.loaded;
  3169. };
  3170. MSFT_audio_emitter.prototype._getEventAction = function (context, sound, action, time, startOffset) {
  3171. switch (action) {
  3172. case "play" /* play */: {
  3173. return function (currentFrame) {
  3174. var frameOffset = (startOffset || 0) + (currentFrame - time);
  3175. sound.play(frameOffset);
  3176. };
  3177. }
  3178. case "stop" /* stop */: {
  3179. return function (currentFrame) {
  3180. sound.stop();
  3181. };
  3182. }
  3183. case "pause" /* pause */: {
  3184. return function (currentFrame) {
  3185. sound.pause();
  3186. };
  3187. }
  3188. default: {
  3189. throw new Error(context + ": Unsupported action " + action);
  3190. }
  3191. }
  3192. };
  3193. MSFT_audio_emitter.prototype._loadAnimationEventAsync = function (context, animationContext, animation, event, babylonAnimationGroup) {
  3194. var _this = this;
  3195. if (babylonAnimationGroup.targetedAnimations.length == 0) {
  3196. return Promise.resolve();
  3197. }
  3198. var babylonAnimation = babylonAnimationGroup.targetedAnimations[0];
  3199. var emitterIndex = event.emitter;
  3200. var emitter = GLTF2.ArrayItem.Get("#/extensions/" + this.name + "/emitters", this._emitters, emitterIndex);
  3201. return this._loadEmitterAsync(context, emitter).then(function () {
  3202. var sound = emitter._babylonData.sound;
  3203. if (sound) {
  3204. var babylonAnimationEvent = new BABYLON.AnimationEvent(event.time, _this._getEventAction(context, sound, event.action, event.time, event.startOffset));
  3205. babylonAnimation.animation.addEvent(babylonAnimationEvent);
  3206. // Make sure all started audio stops when this animation is terminated.
  3207. babylonAnimationGroup.onAnimationGroupEndObservable.add(function () {
  3208. sound.stop();
  3209. });
  3210. babylonAnimationGroup.onAnimationGroupPauseObservable.add(function () {
  3211. sound.pause();
  3212. });
  3213. }
  3214. });
  3215. };
  3216. return MSFT_audio_emitter;
  3217. }());
  3218. Extensions.MSFT_audio_emitter = MSFT_audio_emitter;
  3219. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_audio_emitter(loader); });
  3220. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  3221. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  3222. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3223. })(BABYLON || (BABYLON = {}));
  3224. //# sourceMappingURL=MSFT_audio_emitter.js.map
  3225. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3226. var BABYLON;
  3227. (function (BABYLON) {
  3228. var GLTF2;
  3229. (function (GLTF2) {
  3230. var Loader;
  3231. (function (Loader) {
  3232. var Extensions;
  3233. (function (Extensions) {
  3234. var NAME = "KHR_draco_mesh_compression";
  3235. /**
  3236. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  3237. */
  3238. var KHR_draco_mesh_compression = /** @class */ (function () {
  3239. /** @hidden */
  3240. function KHR_draco_mesh_compression(loader) {
  3241. /** The name of this extension. */
  3242. this.name = NAME;
  3243. /** Defines whether this extension is enabled. */
  3244. this.enabled = BABYLON.DracoCompression.DecoderAvailable;
  3245. this._loader = loader;
  3246. }
  3247. /** @hidden */
  3248. KHR_draco_mesh_compression.prototype.dispose = function () {
  3249. if (this._dracoCompression) {
  3250. this._dracoCompression.dispose();
  3251. delete this._dracoCompression;
  3252. }
  3253. delete this._loader;
  3254. };
  3255. /** @hidden */
  3256. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  3257. var _this = this;
  3258. return GLTF2.GLTFLoader.LoadExtensionAsync(context, primitive, this.name, function (extensionContext, extension) {
  3259. if (primitive.mode != undefined) {
  3260. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  3261. primitive.mode !== 4 /* TRIANGLES */) {
  3262. throw new Error(context + ": Unsupported mode " + primitive.mode);
  3263. }
  3264. // TODO: handle triangle strips
  3265. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  3266. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  3267. }
  3268. }
  3269. var attributes = {};
  3270. var loadAttribute = function (name, kind) {
  3271. var uniqueId = extension.attributes[name];
  3272. if (uniqueId == undefined) {
  3273. return;
  3274. }
  3275. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3276. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3277. babylonMesh._delayInfo.push(kind);
  3278. }
  3279. attributes[kind] = uniqueId;
  3280. };
  3281. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  3282. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  3283. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  3284. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  3285. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  3286. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  3287. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  3288. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  3289. var bufferView = GLTF2.ArrayItem.Get(extensionContext, _this._loader.gltf.bufferViews, extension.bufferView);
  3290. if (!bufferView._dracoBabylonGeometry) {
  3291. bufferView._dracoBabylonGeometry = _this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  3292. if (!_this._dracoCompression) {
  3293. _this._dracoCompression = new BABYLON.DracoCompression();
  3294. }
  3295. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  3296. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader.babylonScene);
  3297. babylonVertexData.applyToGeometry(babylonGeometry);
  3298. return babylonGeometry;
  3299. }).catch(function (error) {
  3300. throw new Error(context + ": " + error.message);
  3301. });
  3302. });
  3303. }
  3304. return bufferView._dracoBabylonGeometry;
  3305. });
  3306. };
  3307. return KHR_draco_mesh_compression;
  3308. }());
  3309. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  3310. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  3311. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  3312. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  3313. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3314. })(BABYLON || (BABYLON = {}));
  3315. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  3316. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3317. var BABYLON;
  3318. (function (BABYLON) {
  3319. var GLTF2;
  3320. (function (GLTF2) {
  3321. var Loader;
  3322. (function (Loader) {
  3323. var Extensions;
  3324. (function (Extensions) {
  3325. var NAME = "KHR_materials_pbrSpecularGlossiness";
  3326. /**
  3327. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  3328. */
  3329. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function () {
  3330. /** @hidden */
  3331. function KHR_materials_pbrSpecularGlossiness(loader) {
  3332. /** The name of this extension. */
  3333. this.name = NAME;
  3334. /** Defines whether this extension is enabled. */
  3335. this.enabled = true;
  3336. this._loader = loader;
  3337. }
  3338. /** @hidden */
  3339. KHR_materials_pbrSpecularGlossiness.prototype.dispose = function () {
  3340. delete this._loader;
  3341. };
  3342. /** @hidden */
  3343. KHR_materials_pbrSpecularGlossiness.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  3344. var _this = this;
  3345. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  3346. var promises = new Array();
  3347. promises.push(_this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  3348. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  3349. _this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  3350. return Promise.all(promises).then(function () { });
  3351. });
  3352. };
  3353. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  3354. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  3355. throw new Error(context + ": Material type not supported");
  3356. }
  3357. var promises = new Array();
  3358. babylonMaterial.metallic = null;
  3359. babylonMaterial.roughness = null;
  3360. if (properties.diffuseFactor) {
  3361. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  3362. babylonMaterial.alpha = properties.diffuseFactor[3];
  3363. }
  3364. else {
  3365. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3366. }
  3367. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  3368. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  3369. if (properties.diffuseTexture) {
  3370. promises.push(this._loader.loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  3371. texture.name = babylonMaterial.name + " (Diffuse)";
  3372. babylonMaterial.albedoTexture = texture;
  3373. }));
  3374. }
  3375. if (properties.specularGlossinessTexture) {
  3376. promises.push(this._loader.loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  3377. texture.name = babylonMaterial.name + " (Specular Glossiness)";
  3378. babylonMaterial.reflectivityTexture = texture;
  3379. }));
  3380. babylonMaterial.reflectivityTexture.hasAlpha = true;
  3381. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  3382. }
  3383. return Promise.all(promises).then(function () { });
  3384. };
  3385. return KHR_materials_pbrSpecularGlossiness;
  3386. }());
  3387. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  3388. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  3389. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  3390. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  3391. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3392. })(BABYLON || (BABYLON = {}));
  3393. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  3394. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3395. var BABYLON;
  3396. (function (BABYLON) {
  3397. var GLTF2;
  3398. (function (GLTF2) {
  3399. var Loader;
  3400. (function (Loader) {
  3401. var Extensions;
  3402. (function (Extensions) {
  3403. var NAME = "KHR_materials_unlit";
  3404. /**
  3405. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  3406. */
  3407. var KHR_materials_unlit = /** @class */ (function () {
  3408. /** @hidden */
  3409. function KHR_materials_unlit(loader) {
  3410. /** The name of this extension. */
  3411. this.name = NAME;
  3412. /** Defines whether this extension is enabled. */
  3413. this.enabled = true;
  3414. this._loader = loader;
  3415. }
  3416. /** @hidden */
  3417. KHR_materials_unlit.prototype.dispose = function () {
  3418. delete this._loader;
  3419. };
  3420. /** @hidden */
  3421. KHR_materials_unlit.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  3422. var _this = this;
  3423. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function () {
  3424. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  3425. });
  3426. };
  3427. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  3428. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  3429. throw new Error(context + ": Material type not supported");
  3430. }
  3431. var promises = new Array();
  3432. babylonMaterial.unlit = true;
  3433. var properties = material.pbrMetallicRoughness;
  3434. if (properties) {
  3435. if (properties.baseColorFactor) {
  3436. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  3437. babylonMaterial.alpha = properties.baseColorFactor[3];
  3438. }
  3439. else {
  3440. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3441. }
  3442. if (properties.baseColorTexture) {
  3443. promises.push(this._loader.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  3444. texture.name = babylonMaterial.name + " (Base Color)";
  3445. babylonMaterial.albedoTexture = texture;
  3446. }));
  3447. }
  3448. }
  3449. if (material.doubleSided) {
  3450. babylonMaterial.backFaceCulling = false;
  3451. babylonMaterial.twoSidedLighting = true;
  3452. }
  3453. this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  3454. return Promise.all(promises).then(function () { });
  3455. };
  3456. return KHR_materials_unlit;
  3457. }());
  3458. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  3459. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  3460. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  3461. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  3462. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3463. })(BABYLON || (BABYLON = {}));
  3464. //# sourceMappingURL=KHR_materials_unlit.js.map
  3465. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3466. var BABYLON;
  3467. (function (BABYLON) {
  3468. var GLTF2;
  3469. (function (GLTF2) {
  3470. var Loader;
  3471. (function (Loader) {
  3472. var Extensions;
  3473. (function (Extensions) {
  3474. var NAME = "KHR_lights_punctual";
  3475. var LightType;
  3476. (function (LightType) {
  3477. LightType["DIRECTIONAL"] = "directional";
  3478. LightType["POINT"] = "point";
  3479. LightType["SPOT"] = "spot";
  3480. })(LightType || (LightType = {}));
  3481. /**
  3482. * [Specification](https://github.com/KhronosGroup/glTF/blob/1048d162a44dbcb05aefc1874bfd423cf60135a6/extensions/2.0/Khronos/KHR_lights_punctual/README.md) (Experimental)
  3483. */
  3484. var KHR_lights = /** @class */ (function () {
  3485. /** @hidden */
  3486. function KHR_lights(loader) {
  3487. /** The name of this extension. */
  3488. this.name = NAME;
  3489. /** Defines whether this extension is enabled. */
  3490. this.enabled = true;
  3491. this._loader = loader;
  3492. }
  3493. /** @hidden */
  3494. KHR_lights.prototype.dispose = function () {
  3495. delete this._loader;
  3496. delete this._lights;
  3497. };
  3498. /** @hidden */
  3499. KHR_lights.prototype.onLoading = function () {
  3500. var extensions = this._loader.gltf.extensions;
  3501. if (extensions && extensions[this.name]) {
  3502. var extension = extensions[this.name];
  3503. this._lights = extension.lights;
  3504. }
  3505. };
  3506. /** @hidden */
  3507. KHR_lights.prototype.loadNodeAsync = function (context, node, assign) {
  3508. var _this = this;
  3509. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  3510. return _this._loader.loadNodeAsync(context, node, function (babylonMesh) {
  3511. var babylonLight;
  3512. var light = GLTF2.ArrayItem.Get(extensionContext, _this._lights, extension.light);
  3513. var name = light.name || babylonMesh.name;
  3514. switch (light.type) {
  3515. case LightType.DIRECTIONAL: {
  3516. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Backward(), _this._loader.babylonScene);
  3517. break;
  3518. }
  3519. case LightType.POINT: {
  3520. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader.babylonScene);
  3521. break;
  3522. }
  3523. case LightType.SPOT: {
  3524. var babylonSpotLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Backward(), 0, 1, _this._loader.babylonScene);
  3525. babylonSpotLight.angle = ((light.spot && light.spot.outerConeAngle) || Math.PI / 4) * 2;
  3526. babylonSpotLight.innerAngle = ((light.spot && light.spot.innerConeAngle) || 0) * 2;
  3527. babylonLight = babylonSpotLight;
  3528. break;
  3529. }
  3530. default: {
  3531. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  3532. }
  3533. }
  3534. babylonLight.falloffType = BABYLON.Light.FALLOFF_GLTF;
  3535. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  3536. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  3537. babylonLight.range = light.range == undefined ? Number.MAX_VALUE : light.range;
  3538. babylonLight.parent = babylonMesh;
  3539. GLTF2.GLTFLoader.AddPointerMetadata(babylonLight, extensionContext);
  3540. assign(babylonMesh);
  3541. });
  3542. });
  3543. };
  3544. return KHR_lights;
  3545. }());
  3546. Extensions.KHR_lights = KHR_lights;
  3547. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_lights(loader); });
  3548. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  3549. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  3550. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3551. })(BABYLON || (BABYLON = {}));
  3552. //# sourceMappingURL=KHR_lights_punctual.js.map
  3553. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3554. var BABYLON;
  3555. (function (BABYLON) {
  3556. var GLTF2;
  3557. (function (GLTF2) {
  3558. var Loader;
  3559. (function (Loader) {
  3560. var Extensions;
  3561. (function (Extensions) {
  3562. var NAME = "KHR_texture_transform";
  3563. /**
  3564. * [Specification](https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_transform/README.md)
  3565. */
  3566. var KHR_texture_transform = /** @class */ (function () {
  3567. /** @hidden */
  3568. function KHR_texture_transform(loader) {
  3569. /** The name of this extension. */
  3570. this.name = NAME;
  3571. /** Defines whether this extension is enabled. */
  3572. this.enabled = true;
  3573. this._loader = loader;
  3574. }
  3575. /** @hidden */
  3576. KHR_texture_transform.prototype.dispose = function () {
  3577. delete this._loader;
  3578. };
  3579. /** @hidden */
  3580. KHR_texture_transform.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  3581. var _this = this;
  3582. return GLTF2.GLTFLoader.LoadExtensionAsync(context, textureInfo, this.name, function (extensionContext, extension) {
  3583. return _this._loader.loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {
  3584. if (!(babylonTexture instanceof BABYLON.Texture)) {
  3585. throw new Error(extensionContext + ": Texture type not supported");
  3586. }
  3587. if (extension.offset) {
  3588. babylonTexture.uOffset = extension.offset[0];
  3589. babylonTexture.vOffset = extension.offset[1];
  3590. }
  3591. // Always rotate around the origin.
  3592. babylonTexture.uRotationCenter = 0;
  3593. babylonTexture.vRotationCenter = 0;
  3594. if (extension.rotation) {
  3595. babylonTexture.wAng = -extension.rotation;
  3596. }
  3597. if (extension.scale) {
  3598. babylonTexture.uScale = extension.scale[0];
  3599. babylonTexture.vScale = extension.scale[1];
  3600. }
  3601. if (extension.texCoord != undefined) {
  3602. babylonTexture.coordinatesIndex = extension.texCoord;
  3603. }
  3604. assign(babylonTexture);
  3605. });
  3606. });
  3607. };
  3608. return KHR_texture_transform;
  3609. }());
  3610. Extensions.KHR_texture_transform = KHR_texture_transform;
  3611. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_texture_transform(loader); });
  3612. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  3613. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  3614. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3615. })(BABYLON || (BABYLON = {}));
  3616. //# sourceMappingURL=KHR_texture_transform.js.map
  3617. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3618. var BABYLON;
  3619. (function (BABYLON) {
  3620. var GLTF2;
  3621. (function (GLTF2) {
  3622. var Loader;
  3623. (function (Loader) {
  3624. var Extensions;
  3625. (function (Extensions) {
  3626. var NAME = "EXT_lights_image_based";
  3627. /**
  3628. * [Specification](https://github.com/KhronosGroup/glTF/blob/eb3e32332042e04691a5f35103f8c261e50d8f1e/extensions/2.0/Khronos/EXT_lights_image_based/README.md) (Experimental)
  3629. */
  3630. var EXT_lights_image_based = /** @class */ (function () {
  3631. /** @hidden */
  3632. function EXT_lights_image_based(loader) {
  3633. /** The name of this extension. */
  3634. this.name = NAME;
  3635. /** Defines whether this extension is enabled. */
  3636. this.enabled = true;
  3637. this._loader = loader;
  3638. }
  3639. /** @hidden */
  3640. EXT_lights_image_based.prototype.dispose = function () {
  3641. delete this._loader;
  3642. delete this._lights;
  3643. };
  3644. /** @hidden */
  3645. EXT_lights_image_based.prototype.onLoading = function () {
  3646. var extensions = this._loader.gltf.extensions;
  3647. if (extensions && extensions[this.name]) {
  3648. var extension = extensions[this.name];
  3649. this._lights = extension.lights;
  3650. }
  3651. };
  3652. /** @hidden */
  3653. EXT_lights_image_based.prototype.loadSceneAsync = function (context, scene) {
  3654. var _this = this;
  3655. return GLTF2.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  3656. var promises = new Array();
  3657. promises.push(_this._loader.loadSceneAsync(context, scene));
  3658. _this._loader.logOpen("" + extensionContext);
  3659. var light = GLTF2.ArrayItem.Get(extensionContext + "/light", _this._lights, extension.light);
  3660. promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) {
  3661. _this._loader.babylonScene.environmentTexture = texture;
  3662. }));
  3663. _this._loader.logClose();
  3664. return Promise.all(promises).then(function () { });
  3665. });
  3666. };
  3667. EXT_lights_image_based.prototype._loadLightAsync = function (context, light) {
  3668. var _this = this;
  3669. if (!light._loaded) {
  3670. var promises = new Array();
  3671. this._loader.logOpen("" + context);
  3672. var imageData_1 = new Array(light.specularImages.length);
  3673. var _loop_1 = function (mipmap) {
  3674. var faces = light.specularImages[mipmap];
  3675. imageData_1[mipmap] = new Array(faces.length);
  3676. var _loop_2 = function (face) {
  3677. var specularImageContext = context + "/specularImages/" + mipmap + "/" + face;
  3678. this_1._loader.logOpen("" + specularImageContext);
  3679. var index = faces[face];
  3680. var image = GLTF2.ArrayItem.Get(specularImageContext, this_1._loader.gltf.images, index);
  3681. promises.push(this_1._loader.loadImageAsync("#/images/" + index, image).then(function (data) {
  3682. imageData_1[mipmap][face] = data;
  3683. }));
  3684. this_1._loader.logClose();
  3685. };
  3686. for (var face = 0; face < faces.length; face++) {
  3687. _loop_2(face);
  3688. }
  3689. };
  3690. var this_1 = this;
  3691. for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {
  3692. _loop_1(mipmap);
  3693. }
  3694. this._loader.logClose();
  3695. light._loaded = Promise.all(promises).then(function () {
  3696. var babylonTexture = new BABYLON.RawCubeTexture(_this._loader.babylonScene, null, light.specularImageSize);
  3697. light._babylonTexture = babylonTexture;
  3698. if (light.intensity != undefined) {
  3699. babylonTexture.level = light.intensity;
  3700. }
  3701. if (light.rotation) {
  3702. var rotation = BABYLON.Quaternion.FromArray(light.rotation);
  3703. // Invert the rotation so that positive rotation is counter-clockwise.
  3704. if (!_this._loader.babylonScene.useRightHandedSystem) {
  3705. rotation = BABYLON.Quaternion.Inverse(rotation);
  3706. }
  3707. BABYLON.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());
  3708. }
  3709. var sphericalHarmonics = BABYLON.SphericalHarmonics.FromArray(light.irradianceCoefficients);
  3710. sphericalHarmonics.scale(light.intensity);
  3711. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  3712. var sphericalPolynomial = BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  3713. // Compute the lod generation scale to fit exactly to the number of levels available.
  3714. var lodGenerationScale = (imageData_1.length - 1) / BABYLON.Scalar.Log2(light.specularImageSize);
  3715. return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);
  3716. });
  3717. }
  3718. return light._loaded.then(function () {
  3719. return light._babylonTexture;
  3720. });
  3721. };
  3722. return EXT_lights_image_based;
  3723. }());
  3724. Extensions.EXT_lights_image_based = EXT_lights_image_based;
  3725. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new EXT_lights_image_based(loader); });
  3726. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  3727. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  3728. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3729. })(BABYLON || (BABYLON = {}));
  3730. //# sourceMappingURL=EXT_lights_image_based.js.map