babylon.glTFFileLoader.js 222 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFLoaderCoordinateSystemMode;
  5. (function (GLTFLoaderCoordinateSystemMode) {
  6. /**
  7. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  8. */
  9. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  10. /**
  11. * Sets the useRightHandedSystem flag on the scene.
  12. */
  13. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  14. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  15. var GLTFLoaderAnimationStartMode;
  16. (function (GLTFLoaderAnimationStartMode) {
  17. /**
  18. * No animation will start.
  19. */
  20. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  21. /**
  22. * The first animation will start.
  23. */
  24. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  25. /**
  26. * All animations will start.
  27. */
  28. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  29. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  30. var GLTFLoaderState;
  31. (function (GLTFLoaderState) {
  32. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  33. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  34. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  35. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  36. var GLTFFileLoader = /** @class */ (function () {
  37. function GLTFFileLoader() {
  38. // #region Common options
  39. /**
  40. * Raised when the asset has been parsed.
  41. * The data.json property stores the glTF JSON.
  42. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  43. */
  44. this.onParsedObservable = new BABYLON.Observable();
  45. // #endregion
  46. // #region V2 options
  47. /**
  48. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  49. */
  50. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  51. /**
  52. * The animation start mode (NONE, FIRST, ALL).
  53. */
  54. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  55. /**
  56. * Set to true to compile materials before raising the success callback.
  57. */
  58. this.compileMaterials = false;
  59. /**
  60. * Set to true to also compile materials with clip planes.
  61. */
  62. this.useClipPlane = false;
  63. /**
  64. * Set to true to compile shadow generators before raising the success callback.
  65. */
  66. this.compileShadowGenerators = false;
  67. /**
  68. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  69. */
  70. this.onMeshLoadedObservable = new BABYLON.Observable();
  71. /**
  72. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  73. */
  74. this.onTextureLoadedObservable = new BABYLON.Observable();
  75. /**
  76. * Raised when the loader creates a material after parsing the glTF properties of the material.
  77. */
  78. this.onMaterialLoadedObservable = new BABYLON.Observable();
  79. /**
  80. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  81. * For assets with LODs, raised when all of the LODs are complete.
  82. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  83. */
  84. this.onCompleteObservable = new BABYLON.Observable();
  85. /**
  86. * Raised when the loader is disposed.
  87. */
  88. this.onDisposeObservable = new BABYLON.Observable();
  89. // #endregion
  90. this._loader = null;
  91. this.name = "gltf";
  92. this.extensions = {
  93. ".gltf": { isBinary: false },
  94. ".glb": { isBinary: true }
  95. };
  96. }
  97. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  98. set: function (callback) {
  99. if (this._onParsedObserver) {
  100. this.onParsedObservable.remove(this._onParsedObserver);
  101. }
  102. this._onParsedObserver = this.onParsedObservable.add(callback);
  103. },
  104. enumerable: true,
  105. configurable: true
  106. });
  107. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  108. set: function (callback) {
  109. if (this._onMeshLoadedObserver) {
  110. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  111. }
  112. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  113. },
  114. enumerable: true,
  115. configurable: true
  116. });
  117. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  118. set: function (callback) {
  119. if (this._onTextureLoadedObserver) {
  120. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  121. }
  122. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  123. },
  124. enumerable: true,
  125. configurable: true
  126. });
  127. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  128. set: function (callback) {
  129. if (this._onMaterialLoadedObserver) {
  130. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  131. }
  132. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  133. },
  134. enumerable: true,
  135. configurable: true
  136. });
  137. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  138. set: function (callback) {
  139. if (this._onCompleteObserver) {
  140. this.onCompleteObservable.remove(this._onCompleteObserver);
  141. }
  142. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  143. },
  144. enumerable: true,
  145. configurable: true
  146. });
  147. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  148. set: function (callback) {
  149. if (this._onDisposeObserver) {
  150. this.onDisposeObservable.remove(this._onDisposeObserver);
  151. }
  152. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  153. },
  154. enumerable: true,
  155. configurable: true
  156. });
  157. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  158. /**
  159. * The loader state or null if not active.
  160. */
  161. get: function () {
  162. return this._loader ? this._loader.state : null;
  163. },
  164. enumerable: true,
  165. configurable: true
  166. });
  167. Object.defineProperty(GLTFFileLoader.prototype, "loaderExtensions", {
  168. /**
  169. * The loader extensions or null if not active.
  170. */
  171. get: function () {
  172. return this._loader ? this._loader.extensions : null;
  173. },
  174. enumerable: true,
  175. configurable: true
  176. });
  177. /**
  178. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  179. */
  180. GLTFFileLoader.prototype.dispose = function () {
  181. if (this._loader) {
  182. this._loader.dispose();
  183. this._loader = null;
  184. }
  185. this.onParsedObservable.clear();
  186. this.onMeshLoadedObservable.clear();
  187. this.onTextureLoadedObservable.clear();
  188. this.onMaterialLoadedObservable.clear();
  189. this.onCompleteObservable.clear();
  190. this.onDisposeObservable.notifyObservers(this);
  191. this.onDisposeObservable.clear();
  192. };
  193. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  194. var _this = this;
  195. return Promise.resolve().then(function () {
  196. var loaderData = _this._parse(data);
  197. _this._loader = _this._getLoader(loaderData);
  198. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  199. });
  200. };
  201. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  202. var _this = this;
  203. return Promise.resolve().then(function () {
  204. var loaderData = _this._parse(data);
  205. _this._loader = _this._getLoader(loaderData);
  206. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  207. });
  208. };
  209. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  210. var _this = this;
  211. return Promise.resolve().then(function () {
  212. var loaderData = _this._parse(data);
  213. _this._loader = _this._getLoader(loaderData);
  214. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  215. var container = new BABYLON.AssetContainer(scene);
  216. Array.prototype.push.apply(container.meshes, result.meshes);
  217. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  218. Array.prototype.push.apply(container.skeletons, result.skeletons);
  219. container.removeAllFromScene();
  220. return container;
  221. });
  222. });
  223. };
  224. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  225. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  226. };
  227. GLTFFileLoader.prototype.createPlugin = function () {
  228. return new GLTFFileLoader();
  229. };
  230. GLTFFileLoader.prototype._parse = function (data) {
  231. var parsedData;
  232. if (data instanceof ArrayBuffer) {
  233. parsedData = GLTFFileLoader._parseBinary(data);
  234. }
  235. else {
  236. parsedData = {
  237. json: JSON.parse(data),
  238. bin: null
  239. };
  240. }
  241. this.onParsedObservable.notifyObservers(parsedData);
  242. return parsedData;
  243. };
  244. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  245. var _this = this;
  246. var loaderVersion = { major: 2, minor: 0 };
  247. var asset = loaderData.json.asset || {};
  248. var version = GLTFFileLoader._parseVersion(asset.version);
  249. if (!version) {
  250. throw new Error("Invalid version: " + asset.version);
  251. }
  252. if (asset.minVersion !== undefined) {
  253. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  254. if (!minVersion) {
  255. throw new Error("Invalid minimum version: " + asset.minVersion);
  256. }
  257. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  258. throw new Error("Incompatible minimum version: " + asset.minVersion);
  259. }
  260. }
  261. var createLoaders = {
  262. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  263. 2: GLTFFileLoader.CreateGLTFLoaderV2
  264. };
  265. var createLoader = createLoaders[version.major];
  266. if (!createLoader) {
  267. throw new Error("Unsupported version: " + asset.version);
  268. }
  269. var loader = createLoader();
  270. loader.coordinateSystemMode = this.coordinateSystemMode;
  271. loader.animationStartMode = this.animationStartMode;
  272. loader.compileMaterials = this.compileMaterials;
  273. loader.useClipPlane = this.useClipPlane;
  274. loader.compileShadowGenerators = this.compileShadowGenerators;
  275. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  276. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  277. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  278. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  279. return loader;
  280. };
  281. GLTFFileLoader._parseBinary = function (data) {
  282. var Binary = {
  283. Magic: 0x46546C67
  284. };
  285. var binaryReader = new BinaryReader(data);
  286. var magic = binaryReader.readUint32();
  287. if (magic !== Binary.Magic) {
  288. throw new Error("Unexpected magic: " + magic);
  289. }
  290. var version = binaryReader.readUint32();
  291. switch (version) {
  292. case 1: return GLTFFileLoader._parseV1(binaryReader);
  293. case 2: return GLTFFileLoader._parseV2(binaryReader);
  294. }
  295. throw new Error("Unsupported version: " + version);
  296. };
  297. GLTFFileLoader._parseV1 = function (binaryReader) {
  298. var ContentFormat = {
  299. JSON: 0
  300. };
  301. var length = binaryReader.readUint32();
  302. if (length != binaryReader.getLength()) {
  303. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  304. }
  305. var contentLength = binaryReader.readUint32();
  306. var contentFormat = binaryReader.readUint32();
  307. var content;
  308. switch (contentFormat) {
  309. case ContentFormat.JSON: {
  310. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  311. break;
  312. }
  313. default: {
  314. throw new Error("Unexpected content format: " + contentFormat);
  315. }
  316. }
  317. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  318. var body = binaryReader.readUint8Array(bytesRemaining);
  319. return {
  320. json: content,
  321. bin: body
  322. };
  323. };
  324. GLTFFileLoader._parseV2 = function (binaryReader) {
  325. var ChunkFormat = {
  326. JSON: 0x4E4F534A,
  327. BIN: 0x004E4942
  328. };
  329. var length = binaryReader.readUint32();
  330. if (length !== binaryReader.getLength()) {
  331. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  332. }
  333. // JSON chunk
  334. var chunkLength = binaryReader.readUint32();
  335. var chunkFormat = binaryReader.readUint32();
  336. if (chunkFormat !== ChunkFormat.JSON) {
  337. throw new Error("First chunk format is not JSON");
  338. }
  339. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  340. // Look for BIN chunk
  341. var bin = null;
  342. while (binaryReader.getPosition() < binaryReader.getLength()) {
  343. var chunkLength_1 = binaryReader.readUint32();
  344. var chunkFormat_1 = binaryReader.readUint32();
  345. switch (chunkFormat_1) {
  346. case ChunkFormat.JSON: {
  347. throw new Error("Unexpected JSON chunk");
  348. }
  349. case ChunkFormat.BIN: {
  350. bin = binaryReader.readUint8Array(chunkLength_1);
  351. break;
  352. }
  353. default: {
  354. // ignore unrecognized chunkFormat
  355. binaryReader.skipBytes(chunkLength_1);
  356. break;
  357. }
  358. }
  359. }
  360. return {
  361. json: json,
  362. bin: bin
  363. };
  364. };
  365. GLTFFileLoader._parseVersion = function (version) {
  366. if (version === "1.0" || version === "1.0.1") {
  367. return {
  368. major: 1,
  369. minor: 0
  370. };
  371. }
  372. var match = (version + "").match(/^(\d+)\.(\d+)/);
  373. if (!match) {
  374. return null;
  375. }
  376. return {
  377. major: parseInt(match[1]),
  378. minor: parseInt(match[2])
  379. };
  380. };
  381. GLTFFileLoader._compareVersion = function (a, b) {
  382. if (a.major > b.major)
  383. return 1;
  384. if (a.major < b.major)
  385. return -1;
  386. if (a.minor > b.minor)
  387. return 1;
  388. if (a.minor < b.minor)
  389. return -1;
  390. return 0;
  391. };
  392. GLTFFileLoader._decodeBufferToText = function (buffer) {
  393. var result = "";
  394. var length = buffer.byteLength;
  395. for (var i = 0; i < length; i++) {
  396. result += String.fromCharCode(buffer[i]);
  397. }
  398. return result;
  399. };
  400. // #endregion
  401. // #region V1 options
  402. GLTFFileLoader.IncrementalLoading = true;
  403. GLTFFileLoader.HomogeneousCoordinates = false;
  404. return GLTFFileLoader;
  405. }());
  406. BABYLON.GLTFFileLoader = GLTFFileLoader;
  407. var BinaryReader = /** @class */ (function () {
  408. function BinaryReader(arrayBuffer) {
  409. this._arrayBuffer = arrayBuffer;
  410. this._dataView = new DataView(arrayBuffer);
  411. this._byteOffset = 0;
  412. }
  413. BinaryReader.prototype.getPosition = function () {
  414. return this._byteOffset;
  415. };
  416. BinaryReader.prototype.getLength = function () {
  417. return this._arrayBuffer.byteLength;
  418. };
  419. BinaryReader.prototype.readUint32 = function () {
  420. var value = this._dataView.getUint32(this._byteOffset, true);
  421. this._byteOffset += 4;
  422. return value;
  423. };
  424. BinaryReader.prototype.readUint8Array = function (length) {
  425. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  426. this._byteOffset += length;
  427. return value;
  428. };
  429. BinaryReader.prototype.skipBytes = function (length) {
  430. this._byteOffset += length;
  431. };
  432. return BinaryReader;
  433. }());
  434. if (BABYLON.SceneLoader) {
  435. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  436. }
  437. })(BABYLON || (BABYLON = {}));
  438. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  439. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  440. var BABYLON;
  441. (function (BABYLON) {
  442. var GLTF1;
  443. (function (GLTF1) {
  444. /**
  445. * Enums
  446. */
  447. var EComponentType;
  448. (function (EComponentType) {
  449. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  450. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  451. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  452. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  453. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  454. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  455. var EShaderType;
  456. (function (EShaderType) {
  457. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  458. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  459. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  460. var EParameterType;
  461. (function (EParameterType) {
  462. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  463. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  464. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  465. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  466. EParameterType[EParameterType["INT"] = 5124] = "INT";
  467. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  468. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  469. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  470. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  471. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  472. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  473. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  474. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  475. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  476. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  477. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  478. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  479. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  480. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  481. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  482. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  483. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  484. var ETextureWrapMode;
  485. (function (ETextureWrapMode) {
  486. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  487. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  488. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  489. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  490. var ETextureFilterType;
  491. (function (ETextureFilterType) {
  492. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  493. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  494. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  495. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  496. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  497. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  498. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  499. var ETextureFormat;
  500. (function (ETextureFormat) {
  501. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  502. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  503. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  504. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  505. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  506. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  507. var ECullingType;
  508. (function (ECullingType) {
  509. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  510. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  511. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  512. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  513. var EBlendingFunction;
  514. (function (EBlendingFunction) {
  515. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  516. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  517. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  518. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  519. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  520. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  521. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  522. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  523. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  524. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  525. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  526. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  527. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  528. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  529. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  530. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  531. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  532. })(BABYLON || (BABYLON = {}));
  533. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  534. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  535. var BABYLON;
  536. (function (BABYLON) {
  537. var GLTF1;
  538. (function (GLTF1) {
  539. /**
  540. * Tokenizer. Used for shaders compatibility
  541. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  542. */
  543. var ETokenType;
  544. (function (ETokenType) {
  545. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  546. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  547. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  548. })(ETokenType || (ETokenType = {}));
  549. var Tokenizer = /** @class */ (function () {
  550. function Tokenizer(toParse) {
  551. this._pos = 0;
  552. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  553. this._toParse = toParse;
  554. this._maxPos = toParse.length;
  555. }
  556. Tokenizer.prototype.getNextToken = function () {
  557. if (this.isEnd())
  558. return ETokenType.END_OF_INPUT;
  559. this.currentString = this.read();
  560. this.currentToken = ETokenType.UNKNOWN;
  561. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  562. this.currentToken = ETokenType.IDENTIFIER;
  563. this.currentIdentifier = this.currentString;
  564. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  565. this.currentIdentifier += this.currentString;
  566. this.forward();
  567. }
  568. }
  569. return this.currentToken;
  570. };
  571. Tokenizer.prototype.peek = function () {
  572. return this._toParse[this._pos];
  573. };
  574. Tokenizer.prototype.read = function () {
  575. return this._toParse[this._pos++];
  576. };
  577. Tokenizer.prototype.forward = function () {
  578. this._pos++;
  579. };
  580. Tokenizer.prototype.isEnd = function () {
  581. return this._pos >= this._maxPos;
  582. };
  583. return Tokenizer;
  584. }());
  585. /**
  586. * Values
  587. */
  588. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  589. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  590. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  591. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  592. /**
  593. * Parse
  594. */
  595. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  596. for (var buf in parsedBuffers) {
  597. var parsedBuffer = parsedBuffers[buf];
  598. gltfRuntime.buffers[buf] = parsedBuffer;
  599. gltfRuntime.buffersCount++;
  600. }
  601. };
  602. var parseShaders = function (parsedShaders, gltfRuntime) {
  603. for (var sha in parsedShaders) {
  604. var parsedShader = parsedShaders[sha];
  605. gltfRuntime.shaders[sha] = parsedShader;
  606. gltfRuntime.shaderscount++;
  607. }
  608. };
  609. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  610. for (var object in parsedObjects) {
  611. var parsedObject = parsedObjects[object];
  612. gltfRuntime[runtimeProperty][object] = parsedObject;
  613. }
  614. };
  615. /**
  616. * Utils
  617. */
  618. var normalizeUVs = function (buffer) {
  619. if (!buffer) {
  620. return;
  621. }
  622. for (var i = 0; i < buffer.length / 2; i++) {
  623. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  624. }
  625. };
  626. var getAttribute = function (attributeParameter) {
  627. if (attributeParameter.semantic === "NORMAL") {
  628. return "normal";
  629. }
  630. else if (attributeParameter.semantic === "POSITION") {
  631. return "position";
  632. }
  633. else if (attributeParameter.semantic === "JOINT") {
  634. return "matricesIndices";
  635. }
  636. else if (attributeParameter.semantic === "WEIGHT") {
  637. return "matricesWeights";
  638. }
  639. else if (attributeParameter.semantic === "COLOR") {
  640. return "color";
  641. }
  642. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  643. var channel = Number(attributeParameter.semantic.split("_")[1]);
  644. return "uv" + (channel === 0 ? "" : channel + 1);
  645. }
  646. return null;
  647. };
  648. /**
  649. * Loads and creates animations
  650. */
  651. var loadAnimations = function (gltfRuntime) {
  652. for (var anim in gltfRuntime.animations) {
  653. var animation = gltfRuntime.animations[anim];
  654. if (!animation.channels || !animation.samplers) {
  655. continue;
  656. }
  657. var lastAnimation = null;
  658. for (var i = 0; i < animation.channels.length; i++) {
  659. // Get parameters and load buffers
  660. var channel = animation.channels[i];
  661. var sampler = animation.samplers[channel.sampler];
  662. if (!sampler) {
  663. continue;
  664. }
  665. var inputData = null;
  666. var outputData = null;
  667. if (animation.parameters) {
  668. inputData = animation.parameters[sampler.input];
  669. outputData = animation.parameters[sampler.output];
  670. }
  671. else {
  672. inputData = sampler.input;
  673. outputData = sampler.output;
  674. }
  675. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  676. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  677. var targetID = channel.target.id;
  678. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  679. if (targetNode === null) {
  680. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  681. }
  682. if (targetNode === null) {
  683. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  684. continue;
  685. }
  686. var isBone = targetNode instanceof BABYLON.Bone;
  687. // Get target path (position, rotation or scaling)
  688. var targetPath = channel.target.path;
  689. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  690. if (targetPathIndex !== -1) {
  691. targetPath = babylonAnimationPaths[targetPathIndex];
  692. }
  693. // Determine animation type
  694. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  695. if (!isBone) {
  696. if (targetPath === "rotationQuaternion") {
  697. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  698. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  699. }
  700. else {
  701. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  702. }
  703. }
  704. // Create animation and key frames
  705. var babylonAnimation = null;
  706. var keys = [];
  707. var arrayOffset = 0;
  708. var modifyKey = false;
  709. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  710. babylonAnimation = lastAnimation;
  711. modifyKey = true;
  712. }
  713. if (!modifyKey) {
  714. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  715. }
  716. // For each frame
  717. for (var j = 0; j < bufferInput.length; j++) {
  718. var value = null;
  719. if (targetPath === "rotationQuaternion") {
  720. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  721. arrayOffset += 4;
  722. }
  723. else {
  724. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  725. arrayOffset += 3;
  726. }
  727. if (isBone) {
  728. var bone = targetNode;
  729. var translation = BABYLON.Vector3.Zero();
  730. var rotationQuaternion = new BABYLON.Quaternion();
  731. var scaling = BABYLON.Vector3.Zero();
  732. // Warning on decompose
  733. var mat = bone.getBaseMatrix();
  734. if (modifyKey && lastAnimation) {
  735. mat = lastAnimation.getKeys()[j].value;
  736. }
  737. mat.decompose(scaling, rotationQuaternion, translation);
  738. if (targetPath === "position") {
  739. translation = value;
  740. }
  741. else if (targetPath === "rotationQuaternion") {
  742. rotationQuaternion = value;
  743. }
  744. else {
  745. scaling = value;
  746. }
  747. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  748. }
  749. if (!modifyKey) {
  750. keys.push({
  751. frame: bufferInput[j],
  752. value: value
  753. });
  754. }
  755. else if (lastAnimation) {
  756. lastAnimation.getKeys()[j].value = value;
  757. }
  758. }
  759. // Finish
  760. if (!modifyKey && babylonAnimation) {
  761. babylonAnimation.setKeys(keys);
  762. targetNode.animations.push(babylonAnimation);
  763. }
  764. lastAnimation = babylonAnimation;
  765. gltfRuntime.scene.stopAnimation(targetNode);
  766. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  767. }
  768. }
  769. };
  770. /**
  771. * Returns the bones transformation matrix
  772. */
  773. var configureBoneTransformation = function (node) {
  774. var mat = null;
  775. if (node.translation || node.rotation || node.scale) {
  776. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  777. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  778. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  779. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  780. }
  781. else {
  782. mat = BABYLON.Matrix.FromArray(node.matrix);
  783. }
  784. return mat;
  785. };
  786. /**
  787. * Returns the parent bone
  788. */
  789. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  790. // Try to find
  791. for (var i = 0; i < newSkeleton.bones.length; i++) {
  792. if (newSkeleton.bones[i].name === jointName) {
  793. return newSkeleton.bones[i];
  794. }
  795. }
  796. // Not found, search in gltf nodes
  797. var nodes = gltfRuntime.nodes;
  798. for (var nde in nodes) {
  799. var node = nodes[nde];
  800. if (!node.jointName) {
  801. continue;
  802. }
  803. var children = node.children;
  804. for (var i = 0; i < children.length; i++) {
  805. var child = gltfRuntime.nodes[children[i]];
  806. if (!child.jointName) {
  807. continue;
  808. }
  809. if (child.jointName === jointName) {
  810. var mat = configureBoneTransformation(node);
  811. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  812. bone.id = nde;
  813. return bone;
  814. }
  815. }
  816. }
  817. return null;
  818. };
  819. /**
  820. * Returns the appropriate root node
  821. */
  822. var getNodeToRoot = function (nodesToRoot, id) {
  823. for (var i = 0; i < nodesToRoot.length; i++) {
  824. var nodeToRoot = nodesToRoot[i];
  825. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  826. var child = nodeToRoot.node.children[j];
  827. if (child === id) {
  828. return nodeToRoot.bone;
  829. }
  830. }
  831. }
  832. return null;
  833. };
  834. /**
  835. * Returns the node with the joint name
  836. */
  837. var getJointNode = function (gltfRuntime, jointName) {
  838. var nodes = gltfRuntime.nodes;
  839. var node = nodes[jointName];
  840. if (node) {
  841. return {
  842. node: node,
  843. id: jointName
  844. };
  845. }
  846. for (var nde in nodes) {
  847. node = nodes[nde];
  848. if (node.jointName === jointName) {
  849. return {
  850. node: node,
  851. id: nde
  852. };
  853. }
  854. }
  855. return null;
  856. };
  857. /**
  858. * Checks if a nodes is in joints
  859. */
  860. var nodeIsInJoints = function (skins, id) {
  861. for (var i = 0; i < skins.jointNames.length; i++) {
  862. if (skins.jointNames[i] === id) {
  863. return true;
  864. }
  865. }
  866. return false;
  867. };
  868. /**
  869. * Fills the nodes to root for bones and builds hierarchy
  870. */
  871. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  872. // Creates nodes for root
  873. for (var nde in gltfRuntime.nodes) {
  874. var node = gltfRuntime.nodes[nde];
  875. var id = nde;
  876. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  877. continue;
  878. }
  879. // Create node to root bone
  880. var mat = configureBoneTransformation(node);
  881. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  882. bone.id = id;
  883. nodesToRoot.push({ bone: bone, node: node, id: id });
  884. }
  885. // Parenting
  886. for (var i = 0; i < nodesToRoot.length; i++) {
  887. var nodeToRoot = nodesToRoot[i];
  888. var children = nodeToRoot.node.children;
  889. for (var j = 0; j < children.length; j++) {
  890. var child = null;
  891. for (var k = 0; k < nodesToRoot.length; k++) {
  892. if (nodesToRoot[k].id === children[j]) {
  893. child = nodesToRoot[k];
  894. break;
  895. }
  896. }
  897. if (child) {
  898. child.bone._parent = nodeToRoot.bone;
  899. nodeToRoot.bone.children.push(child.bone);
  900. }
  901. }
  902. }
  903. };
  904. /**
  905. * Imports a skeleton
  906. */
  907. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  908. if (!newSkeleton) {
  909. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  910. }
  911. if (!skins.babylonSkeleton) {
  912. return newSkeleton;
  913. }
  914. // Find the root bones
  915. var nodesToRoot = [];
  916. var nodesToRootToAdd = [];
  917. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  918. newSkeleton.bones = [];
  919. // Joints
  920. for (var i = 0; i < skins.jointNames.length; i++) {
  921. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  922. if (!jointNode) {
  923. continue;
  924. }
  925. var node = jointNode.node;
  926. if (!node) {
  927. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  928. continue;
  929. }
  930. var id = jointNode.id;
  931. // Optimize, if the bone already exists...
  932. var existingBone = gltfRuntime.scene.getBoneByID(id);
  933. if (existingBone) {
  934. newSkeleton.bones.push(existingBone);
  935. continue;
  936. }
  937. // Search for parent bone
  938. var foundBone = false;
  939. var parentBone = null;
  940. for (var j = 0; j < i; j++) {
  941. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  942. if (!jointNode_1) {
  943. continue;
  944. }
  945. var joint = jointNode_1.node;
  946. if (!joint) {
  947. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  948. continue;
  949. }
  950. var children = joint.children;
  951. if (!children) {
  952. continue;
  953. }
  954. foundBone = false;
  955. for (var k = 0; k < children.length; k++) {
  956. if (children[k] === id) {
  957. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  958. foundBone = true;
  959. break;
  960. }
  961. }
  962. if (foundBone) {
  963. break;
  964. }
  965. }
  966. // Create bone
  967. var mat = configureBoneTransformation(node);
  968. if (!parentBone && nodesToRoot.length > 0) {
  969. parentBone = getNodeToRoot(nodesToRoot, id);
  970. if (parentBone) {
  971. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  972. nodesToRootToAdd.push(parentBone);
  973. }
  974. }
  975. }
  976. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  977. bone.id = id;
  978. }
  979. // Polish
  980. var bones = newSkeleton.bones;
  981. newSkeleton.bones = [];
  982. for (var i = 0; i < skins.jointNames.length; i++) {
  983. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  984. if (!jointNode) {
  985. continue;
  986. }
  987. for (var j = 0; j < bones.length; j++) {
  988. if (bones[j].id === jointNode.id) {
  989. newSkeleton.bones.push(bones[j]);
  990. break;
  991. }
  992. }
  993. }
  994. newSkeleton.prepare();
  995. // Finish
  996. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  997. newSkeleton.bones.push(nodesToRootToAdd[i]);
  998. }
  999. return newSkeleton;
  1000. };
  1001. /**
  1002. * Imports a mesh and its geometries
  1003. */
  1004. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1005. if (!newMesh) {
  1006. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1007. newMesh.id = id;
  1008. }
  1009. if (!node.babylonNode) {
  1010. return newMesh;
  1011. }
  1012. var subMaterials = [];
  1013. var vertexData = null;
  1014. var verticesStarts = new Array();
  1015. var verticesCounts = new Array();
  1016. var indexStarts = new Array();
  1017. var indexCounts = new Array();
  1018. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1019. var meshID = meshes[meshIndex];
  1020. var mesh = gltfRuntime.meshes[meshID];
  1021. if (!mesh) {
  1022. continue;
  1023. }
  1024. // Positions, normals and UVs
  1025. for (var i = 0; i < mesh.primitives.length; i++) {
  1026. // Temporary vertex data
  1027. var tempVertexData = new BABYLON.VertexData();
  1028. var primitive = mesh.primitives[i];
  1029. if (primitive.mode !== 4) {
  1030. // continue;
  1031. }
  1032. var attributes = primitive.attributes;
  1033. var accessor = null;
  1034. var buffer = null;
  1035. // Set positions, normal and uvs
  1036. for (var semantic in attributes) {
  1037. // Link accessor and buffer view
  1038. accessor = gltfRuntime.accessors[attributes[semantic]];
  1039. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1040. if (semantic === "NORMAL") {
  1041. tempVertexData.normals = new Float32Array(buffer.length);
  1042. tempVertexData.normals.set(buffer);
  1043. }
  1044. else if (semantic === "POSITION") {
  1045. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  1046. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  1047. for (var j = 0; j < buffer.length; j += 4) {
  1048. tempVertexData.positions[j] = buffer[j];
  1049. tempVertexData.positions[j + 1] = buffer[j + 1];
  1050. tempVertexData.positions[j + 2] = buffer[j + 2];
  1051. }
  1052. }
  1053. else {
  1054. tempVertexData.positions = new Float32Array(buffer.length);
  1055. tempVertexData.positions.set(buffer);
  1056. }
  1057. verticesCounts.push(tempVertexData.positions.length);
  1058. }
  1059. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  1060. var channel = Number(semantic.split("_")[1]);
  1061. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  1062. var uvs = new Float32Array(buffer.length);
  1063. uvs.set(buffer);
  1064. normalizeUVs(uvs);
  1065. tempVertexData.set(uvs, uvKind);
  1066. }
  1067. else if (semantic === "JOINT") {
  1068. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  1069. tempVertexData.matricesIndices.set(buffer);
  1070. }
  1071. else if (semantic === "WEIGHT") {
  1072. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  1073. tempVertexData.matricesWeights.set(buffer);
  1074. }
  1075. else if (semantic === "COLOR") {
  1076. tempVertexData.colors = new Float32Array(buffer.length);
  1077. tempVertexData.colors.set(buffer);
  1078. }
  1079. }
  1080. // Indices
  1081. accessor = gltfRuntime.accessors[primitive.indices];
  1082. if (accessor) {
  1083. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1084. tempVertexData.indices = new Int32Array(buffer.length);
  1085. tempVertexData.indices.set(buffer);
  1086. indexCounts.push(tempVertexData.indices.length);
  1087. }
  1088. else {
  1089. // Set indices on the fly
  1090. var indices = [];
  1091. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  1092. indices.push(j);
  1093. }
  1094. tempVertexData.indices = new Int32Array(indices);
  1095. indexCounts.push(tempVertexData.indices.length);
  1096. }
  1097. if (!vertexData) {
  1098. vertexData = tempVertexData;
  1099. }
  1100. else {
  1101. vertexData.merge(tempVertexData);
  1102. }
  1103. // Sub material
  1104. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  1105. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  1106. // Update vertices start and index start
  1107. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  1108. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  1109. }
  1110. }
  1111. var material;
  1112. if (subMaterials.length > 1) {
  1113. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  1114. material.subMaterials = subMaterials;
  1115. }
  1116. else {
  1117. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  1118. }
  1119. if (subMaterials.length === 1) {
  1120. material = subMaterials[0];
  1121. }
  1122. if (!newMesh.material) {
  1123. newMesh.material = material;
  1124. }
  1125. // Apply geometry
  1126. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  1127. newMesh.computeWorldMatrix(true);
  1128. // Apply submeshes
  1129. newMesh.subMeshes = [];
  1130. var index = 0;
  1131. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1132. var meshID = meshes[meshIndex];
  1133. var mesh = gltfRuntime.meshes[meshID];
  1134. if (!mesh) {
  1135. continue;
  1136. }
  1137. for (var i = 0; i < mesh.primitives.length; i++) {
  1138. if (mesh.primitives[i].mode !== 4) {
  1139. //continue;
  1140. }
  1141. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  1142. index++;
  1143. }
  1144. }
  1145. // Finish
  1146. return newMesh;
  1147. };
  1148. /**
  1149. * Configure node transformation from position, rotation and scaling
  1150. */
  1151. var configureNode = function (newNode, position, rotation, scaling) {
  1152. if (newNode.position) {
  1153. newNode.position = position;
  1154. }
  1155. if (newNode.rotationQuaternion || newNode.rotation) {
  1156. newNode.rotationQuaternion = rotation;
  1157. }
  1158. if (newNode.scaling) {
  1159. newNode.scaling = scaling;
  1160. }
  1161. };
  1162. /**
  1163. * Configures node from transformation matrix
  1164. */
  1165. var configureNodeFromMatrix = function (newNode, node, parent) {
  1166. if (node.matrix) {
  1167. var position = new BABYLON.Vector3(0, 0, 0);
  1168. var rotation = new BABYLON.Quaternion();
  1169. var scaling = new BABYLON.Vector3(0, 0, 0);
  1170. var mat = BABYLON.Matrix.FromArray(node.matrix);
  1171. mat.decompose(scaling, rotation, position);
  1172. configureNode(newNode, position, rotation, scaling);
  1173. }
  1174. else if (node.translation && node.rotation && node.scale) {
  1175. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  1176. }
  1177. newNode.computeWorldMatrix(true);
  1178. };
  1179. /**
  1180. * Imports a node
  1181. */
  1182. var importNode = function (gltfRuntime, node, id, parent) {
  1183. var lastNode = null;
  1184. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  1185. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  1186. return null;
  1187. }
  1188. }
  1189. // Meshes
  1190. if (node.skin) {
  1191. if (node.meshes) {
  1192. var skin = gltfRuntime.skins[node.skin];
  1193. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1194. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1195. if (newMesh.skeleton === null) {
  1196. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1197. if (!skin.babylonSkeleton) {
  1198. skin.babylonSkeleton = newMesh.skeleton;
  1199. }
  1200. }
  1201. lastNode = newMesh;
  1202. }
  1203. }
  1204. else if (node.meshes) {
  1205. /**
  1206. * Improve meshes property
  1207. */
  1208. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1209. lastNode = newMesh;
  1210. }
  1211. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1212. var light = gltfRuntime.lights[node.light];
  1213. if (light) {
  1214. if (light.type === "ambient") {
  1215. var ambienLight = light[light.type];
  1216. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1217. hemiLight.name = node.name || "";
  1218. if (ambienLight.color) {
  1219. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1220. }
  1221. lastNode = hemiLight;
  1222. }
  1223. else if (light.type === "directional") {
  1224. var directionalLight = light[light.type];
  1225. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1226. dirLight.name = node.name || "";
  1227. if (directionalLight.color) {
  1228. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1229. }
  1230. lastNode = dirLight;
  1231. }
  1232. else if (light.type === "point") {
  1233. var pointLight = light[light.type];
  1234. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1235. ptLight.name = node.name || "";
  1236. if (pointLight.color) {
  1237. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1238. }
  1239. lastNode = ptLight;
  1240. }
  1241. else if (light.type === "spot") {
  1242. var spotLight = light[light.type];
  1243. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1244. spLight.name = node.name || "";
  1245. if (spotLight.color) {
  1246. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1247. }
  1248. if (spotLight.fallOfAngle) {
  1249. spLight.angle = spotLight.fallOfAngle;
  1250. }
  1251. if (spotLight.fallOffExponent) {
  1252. spLight.exponent = spotLight.fallOffExponent;
  1253. }
  1254. lastNode = spLight;
  1255. }
  1256. }
  1257. }
  1258. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1259. var camera = gltfRuntime.cameras[node.camera];
  1260. if (camera) {
  1261. if (camera.type === "orthographic") {
  1262. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1263. orthoCamera.name = node.name || "";
  1264. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1265. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1266. lastNode = orthoCamera;
  1267. }
  1268. else if (camera.type === "perspective") {
  1269. var perspectiveCamera = camera[camera.type];
  1270. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1271. persCamera.name = node.name || "";
  1272. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1273. if (!perspectiveCamera.aspectRatio) {
  1274. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1275. }
  1276. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1277. persCamera.maxZ = perspectiveCamera.zfar;
  1278. persCamera.minZ = perspectiveCamera.znear;
  1279. }
  1280. lastNode = persCamera;
  1281. }
  1282. }
  1283. }
  1284. // Empty node
  1285. if (!node.jointName) {
  1286. if (node.babylonNode) {
  1287. return node.babylonNode;
  1288. }
  1289. else if (lastNode === null) {
  1290. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1291. node.babylonNode = dummy;
  1292. lastNode = dummy;
  1293. }
  1294. }
  1295. if (lastNode !== null) {
  1296. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1297. configureNodeFromMatrix(lastNode, node, parent);
  1298. }
  1299. else {
  1300. var translation = node.translation || [0, 0, 0];
  1301. var rotation = node.rotation || [0, 0, 0, 1];
  1302. var scale = node.scale || [1, 1, 1];
  1303. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1304. }
  1305. lastNode.updateCache(true);
  1306. node.babylonNode = lastNode;
  1307. }
  1308. return lastNode;
  1309. };
  1310. /**
  1311. * Traverses nodes and creates them
  1312. */
  1313. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1314. if (meshIncluded === void 0) { meshIncluded = false; }
  1315. var node = gltfRuntime.nodes[id];
  1316. var newNode = null;
  1317. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1318. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1319. meshIncluded = true;
  1320. }
  1321. else {
  1322. meshIncluded = false;
  1323. }
  1324. }
  1325. else {
  1326. meshIncluded = true;
  1327. }
  1328. if (!node.jointName && meshIncluded) {
  1329. newNode = importNode(gltfRuntime, node, id, parent);
  1330. if (newNode !== null) {
  1331. newNode.id = id;
  1332. newNode.parent = parent;
  1333. }
  1334. }
  1335. if (node.children) {
  1336. for (var i = 0; i < node.children.length; i++) {
  1337. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1338. }
  1339. }
  1340. };
  1341. /**
  1342. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1343. */
  1344. var postLoad = function (gltfRuntime) {
  1345. // Nodes
  1346. var currentScene = gltfRuntime.currentScene;
  1347. if (currentScene) {
  1348. for (var i = 0; i < currentScene.nodes.length; i++) {
  1349. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1350. }
  1351. }
  1352. else {
  1353. for (var thing in gltfRuntime.scenes) {
  1354. currentScene = gltfRuntime.scenes[thing];
  1355. for (var i = 0; i < currentScene.nodes.length; i++) {
  1356. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1357. }
  1358. }
  1359. }
  1360. // Set animations
  1361. loadAnimations(gltfRuntime);
  1362. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1363. var skeleton = gltfRuntime.scene.skeletons[i];
  1364. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1365. }
  1366. };
  1367. /**
  1368. * onBind shaderrs callback to set uniforms and matrices
  1369. */
  1370. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1371. var materialValues = material.values || technique.parameters;
  1372. for (var unif in unTreatedUniforms) {
  1373. var uniform = unTreatedUniforms[unif];
  1374. var type = uniform.type;
  1375. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1376. if (uniform.semantic && !uniform.source && !uniform.node) {
  1377. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1378. }
  1379. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1380. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1381. if (source === null) {
  1382. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1383. }
  1384. if (source === null) {
  1385. continue;
  1386. }
  1387. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1388. }
  1389. }
  1390. else {
  1391. var value = materialValues[technique.uniforms[unif]];
  1392. if (!value) {
  1393. continue;
  1394. }
  1395. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1396. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1397. if (texture === null || texture === undefined) {
  1398. continue;
  1399. }
  1400. shaderMaterial.getEffect().setTexture(unif, texture);
  1401. }
  1402. else {
  1403. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1404. }
  1405. }
  1406. }
  1407. onSuccess(shaderMaterial);
  1408. };
  1409. /**
  1410. * Prepare uniforms to send the only one time
  1411. * Loads the appropriate textures
  1412. */
  1413. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1414. var materialValues = material.values || technique.parameters;
  1415. var techniqueUniforms = technique.uniforms;
  1416. /**
  1417. * Prepare values here (not matrices)
  1418. */
  1419. for (var unif in unTreatedUniforms) {
  1420. var uniform = unTreatedUniforms[unif];
  1421. var type = uniform.type;
  1422. var value = materialValues[techniqueUniforms[unif]];
  1423. if (value === undefined) {
  1424. // In case the value is the same for all materials
  1425. value = uniform.value;
  1426. }
  1427. if (!value) {
  1428. continue;
  1429. }
  1430. var onLoadTexture = function (uniformName) {
  1431. return function (texture) {
  1432. if (uniform.value && uniformName) {
  1433. // Static uniform
  1434. shaderMaterial.setTexture(uniformName, texture);
  1435. delete unTreatedUniforms[uniformName];
  1436. }
  1437. };
  1438. };
  1439. // Texture (sampler2D)
  1440. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1441. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1442. }
  1443. else {
  1444. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1445. // Static uniform
  1446. delete unTreatedUniforms[unif];
  1447. }
  1448. }
  1449. }
  1450. };
  1451. /**
  1452. * Shader compilation failed
  1453. */
  1454. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1455. return function (effect, error) {
  1456. shaderMaterial.dispose(true);
  1457. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1458. };
  1459. };
  1460. /**
  1461. * Shader compilation success
  1462. */
  1463. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1464. return function (_) {
  1465. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1466. shaderMaterial.onBind = function (mesh) {
  1467. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1468. };
  1469. };
  1470. };
  1471. /**
  1472. * Returns the appropriate uniform if already handled by babylon
  1473. */
  1474. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1475. for (var unif in technique.uniforms) {
  1476. var uniform = technique.uniforms[unif];
  1477. var uniformParameter = technique.parameters[uniform];
  1478. if (tokenizer.currentIdentifier === unif) {
  1479. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1480. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1481. if (transformIndex !== -1) {
  1482. delete unTreatedUniforms[unif];
  1483. return babylonTransforms[transformIndex];
  1484. }
  1485. }
  1486. }
  1487. }
  1488. return tokenizer.currentIdentifier;
  1489. };
  1490. /**
  1491. * All shaders loaded. Create materials one by one
  1492. */
  1493. var importMaterials = function (gltfRuntime) {
  1494. // Create materials
  1495. for (var mat in gltfRuntime.materials) {
  1496. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1497. }
  1498. };
  1499. /**
  1500. * Implementation of the base glTF spec
  1501. */
  1502. var GLTFLoaderBase = /** @class */ (function () {
  1503. function GLTFLoaderBase() {
  1504. }
  1505. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1506. var gltfRuntime = {
  1507. extensions: {},
  1508. accessors: {},
  1509. buffers: {},
  1510. bufferViews: {},
  1511. meshes: {},
  1512. lights: {},
  1513. cameras: {},
  1514. nodes: {},
  1515. images: {},
  1516. textures: {},
  1517. shaders: {},
  1518. programs: {},
  1519. samplers: {},
  1520. techniques: {},
  1521. materials: {},
  1522. animations: {},
  1523. skins: {},
  1524. extensionsUsed: [],
  1525. scenes: {},
  1526. buffersCount: 0,
  1527. shaderscount: 0,
  1528. scene: scene,
  1529. rootUrl: rootUrl,
  1530. loadedBufferCount: 0,
  1531. loadedBufferViews: {},
  1532. loadedShaderCount: 0,
  1533. importOnlyMeshes: false,
  1534. dummyNodes: []
  1535. };
  1536. // Parse
  1537. if (parsedData.extensions) {
  1538. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1539. }
  1540. if (parsedData.extensionsUsed) {
  1541. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1542. }
  1543. if (parsedData.buffers) {
  1544. parseBuffers(parsedData.buffers, gltfRuntime);
  1545. }
  1546. if (parsedData.bufferViews) {
  1547. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1548. }
  1549. if (parsedData.accessors) {
  1550. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1551. }
  1552. if (parsedData.meshes) {
  1553. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1554. }
  1555. if (parsedData.lights) {
  1556. parseObject(parsedData.lights, "lights", gltfRuntime);
  1557. }
  1558. if (parsedData.cameras) {
  1559. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1560. }
  1561. if (parsedData.nodes) {
  1562. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1563. }
  1564. if (parsedData.images) {
  1565. parseObject(parsedData.images, "images", gltfRuntime);
  1566. }
  1567. if (parsedData.textures) {
  1568. parseObject(parsedData.textures, "textures", gltfRuntime);
  1569. }
  1570. if (parsedData.shaders) {
  1571. parseShaders(parsedData.shaders, gltfRuntime);
  1572. }
  1573. if (parsedData.programs) {
  1574. parseObject(parsedData.programs, "programs", gltfRuntime);
  1575. }
  1576. if (parsedData.samplers) {
  1577. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1578. }
  1579. if (parsedData.techniques) {
  1580. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1581. }
  1582. if (parsedData.materials) {
  1583. parseObject(parsedData.materials, "materials", gltfRuntime);
  1584. }
  1585. if (parsedData.animations) {
  1586. parseObject(parsedData.animations, "animations", gltfRuntime);
  1587. }
  1588. if (parsedData.skins) {
  1589. parseObject(parsedData.skins, "skins", gltfRuntime);
  1590. }
  1591. if (parsedData.scenes) {
  1592. gltfRuntime.scenes = parsedData.scenes;
  1593. }
  1594. if (parsedData.scene && parsedData.scenes) {
  1595. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1596. }
  1597. return gltfRuntime;
  1598. };
  1599. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1600. var buffer = gltfRuntime.buffers[id];
  1601. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  1602. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  1603. }
  1604. else {
  1605. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1606. if (request) {
  1607. onError(request.status + " " + request.statusText);
  1608. }
  1609. });
  1610. }
  1611. };
  1612. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1613. var texture = gltfRuntime.textures[id];
  1614. if (!texture || !texture.source) {
  1615. onError("");
  1616. return;
  1617. }
  1618. if (texture.babylonTexture) {
  1619. onSuccess(null);
  1620. return;
  1621. }
  1622. var source = gltfRuntime.images[texture.source];
  1623. if (BABYLON.Tools.IsBase64(source.uri)) {
  1624. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  1625. }
  1626. else {
  1627. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1628. if (request) {
  1629. onError(request.status + " " + request.statusText);
  1630. }
  1631. });
  1632. }
  1633. };
  1634. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1635. var texture = gltfRuntime.textures[id];
  1636. if (texture.babylonTexture) {
  1637. onSuccess(texture.babylonTexture);
  1638. return;
  1639. }
  1640. var sampler = gltfRuntime.samplers[texture.sampler];
  1641. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1642. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1643. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1644. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1645. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1646. var blob = new Blob([buffer]);
  1647. var blobURL = URL.createObjectURL(blob);
  1648. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1649. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1650. if (sampler.wrapS !== undefined) {
  1651. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1652. }
  1653. if (sampler.wrapT !== undefined) {
  1654. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1655. }
  1656. newTexture.name = id;
  1657. texture.babylonTexture = newTexture;
  1658. onSuccess(newTexture);
  1659. };
  1660. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1661. var shader = gltfRuntime.shaders[id];
  1662. if (BABYLON.Tools.IsBase64(shader.uri)) {
  1663. var shaderString = atob(shader.uri.split(",")[1]);
  1664. onSuccess(shaderString);
  1665. }
  1666. else {
  1667. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1668. if (request) {
  1669. onError(request.status + " " + request.statusText);
  1670. }
  1671. });
  1672. }
  1673. };
  1674. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1675. var material = gltfRuntime.materials[id];
  1676. if (!material.technique) {
  1677. if (onError) {
  1678. onError("No technique found.");
  1679. }
  1680. return;
  1681. }
  1682. var technique = gltfRuntime.techniques[material.technique];
  1683. if (!technique) {
  1684. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1685. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1686. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1687. onSuccess(defaultMaterial);
  1688. return;
  1689. }
  1690. var program = gltfRuntime.programs[technique.program];
  1691. var states = technique.states;
  1692. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1693. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1694. var newVertexShader = "";
  1695. var newPixelShader = "";
  1696. var vertexTokenizer = new Tokenizer(vertexShader);
  1697. var pixelTokenizer = new Tokenizer(pixelShader);
  1698. var unTreatedUniforms = {};
  1699. var uniforms = [];
  1700. var attributes = [];
  1701. var samplers = [];
  1702. // Fill uniform, sampler2D and attributes
  1703. for (var unif in technique.uniforms) {
  1704. var uniform = technique.uniforms[unif];
  1705. var uniformParameter = technique.parameters[uniform];
  1706. unTreatedUniforms[unif] = uniformParameter;
  1707. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1708. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1709. if (transformIndex !== -1) {
  1710. uniforms.push(babylonTransforms[transformIndex]);
  1711. delete unTreatedUniforms[unif];
  1712. }
  1713. else {
  1714. uniforms.push(unif);
  1715. }
  1716. }
  1717. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1718. samplers.push(unif);
  1719. }
  1720. else {
  1721. uniforms.push(unif);
  1722. }
  1723. }
  1724. for (var attr in technique.attributes) {
  1725. var attribute = technique.attributes[attr];
  1726. var attributeParameter = technique.parameters[attribute];
  1727. if (attributeParameter.semantic) {
  1728. attributes.push(getAttribute(attributeParameter));
  1729. }
  1730. }
  1731. // Configure vertex shader
  1732. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1733. var tokenType = vertexTokenizer.currentToken;
  1734. if (tokenType !== ETokenType.IDENTIFIER) {
  1735. newVertexShader += vertexTokenizer.currentString;
  1736. continue;
  1737. }
  1738. var foundAttribute = false;
  1739. for (var attr in technique.attributes) {
  1740. var attribute = technique.attributes[attr];
  1741. var attributeParameter = technique.parameters[attribute];
  1742. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1743. newVertexShader += getAttribute(attributeParameter);
  1744. foundAttribute = true;
  1745. break;
  1746. }
  1747. }
  1748. if (foundAttribute) {
  1749. continue;
  1750. }
  1751. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1752. }
  1753. // Configure pixel shader
  1754. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1755. var tokenType = pixelTokenizer.currentToken;
  1756. if (tokenType !== ETokenType.IDENTIFIER) {
  1757. newPixelShader += pixelTokenizer.currentString;
  1758. continue;
  1759. }
  1760. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1761. }
  1762. // Create shader material
  1763. var shaderPath = {
  1764. vertex: program.vertexShader + id,
  1765. fragment: program.fragmentShader + id
  1766. };
  1767. var options = {
  1768. attributes: attributes,
  1769. uniforms: uniforms,
  1770. samplers: samplers,
  1771. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1772. };
  1773. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1774. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1775. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1776. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1777. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1778. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1779. if (states && states.functions) {
  1780. var functions = states.functions;
  1781. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1782. shaderMaterial.backFaceCulling = false;
  1783. }
  1784. var blendFunc = functions.blendFuncSeparate;
  1785. if (blendFunc) {
  1786. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1787. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1788. }
  1789. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1790. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1791. }
  1792. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1793. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1794. }
  1795. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1796. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1797. }
  1798. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1799. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1800. }
  1801. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1802. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1803. }
  1804. }
  1805. }
  1806. };
  1807. return GLTFLoaderBase;
  1808. }());
  1809. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1810. /**
  1811. * glTF V1 Loader
  1812. */
  1813. var GLTFLoader = /** @class */ (function () {
  1814. function GLTFLoader() {
  1815. // #region Stubs for IGLTFLoader interface
  1816. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  1817. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  1818. this.compileMaterials = false;
  1819. this.useClipPlane = false;
  1820. this.compileShadowGenerators = false;
  1821. this.onDisposeObservable = new BABYLON.Observable();
  1822. this.onMeshLoadedObservable = new BABYLON.Observable();
  1823. this.onTextureLoadedObservable = new BABYLON.Observable();
  1824. this.onMaterialLoadedObservable = new BABYLON.Observable();
  1825. this.onCompleteObservable = new BABYLON.Observable();
  1826. this.state = null;
  1827. this.extensions = null;
  1828. }
  1829. GLTFLoader.RegisterExtension = function (extension) {
  1830. if (GLTFLoader.Extensions[extension.name]) {
  1831. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1832. return;
  1833. }
  1834. GLTFLoader.Extensions[extension.name] = extension;
  1835. };
  1836. GLTFLoader.prototype.dispose = function () { };
  1837. // #endregion
  1838. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1839. var _this = this;
  1840. scene.useRightHandedSystem = true;
  1841. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1842. gltfRuntime.importOnlyMeshes = true;
  1843. if (meshesNames === "") {
  1844. gltfRuntime.importMeshesNames = [];
  1845. }
  1846. else if (typeof meshesNames === "string") {
  1847. gltfRuntime.importMeshesNames = [meshesNames];
  1848. }
  1849. else if (meshesNames && !(meshesNames instanceof Array)) {
  1850. gltfRuntime.importMeshesNames = [meshesNames];
  1851. }
  1852. else {
  1853. gltfRuntime.importMeshesNames = [];
  1854. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1855. }
  1856. // Create nodes
  1857. _this._createNodes(gltfRuntime);
  1858. var meshes = new Array();
  1859. var skeletons = new Array();
  1860. // Fill arrays of meshes and skeletons
  1861. for (var nde in gltfRuntime.nodes) {
  1862. var node = gltfRuntime.nodes[nde];
  1863. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1864. meshes.push(node.babylonNode);
  1865. }
  1866. }
  1867. for (var skl in gltfRuntime.skins) {
  1868. var skin = gltfRuntime.skins[skl];
  1869. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1870. skeletons.push(skin.babylonSkeleton);
  1871. }
  1872. }
  1873. // Load buffers, shaders, materials, etc.
  1874. _this._loadBuffersAsync(gltfRuntime, function () {
  1875. _this._loadShadersAsync(gltfRuntime, function () {
  1876. importMaterials(gltfRuntime);
  1877. postLoad(gltfRuntime);
  1878. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1879. onSuccess(meshes, [], skeletons);
  1880. }
  1881. });
  1882. }, onProgress);
  1883. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1884. onSuccess(meshes, [], skeletons);
  1885. }
  1886. }, onError);
  1887. return true;
  1888. };
  1889. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1890. var _this = this;
  1891. return new Promise(function (resolve, reject) {
  1892. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  1893. resolve({
  1894. meshes: meshes,
  1895. particleSystems: particleSystems,
  1896. skeletons: skeletons
  1897. });
  1898. }, onProgress, function (message) {
  1899. reject(new Error(message));
  1900. });
  1901. });
  1902. };
  1903. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1904. var _this = this;
  1905. scene.useRightHandedSystem = true;
  1906. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1907. // Load runtime extensios
  1908. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1909. // Create nodes
  1910. _this._createNodes(gltfRuntime);
  1911. // Load buffers, shaders, materials, etc.
  1912. _this._loadBuffersAsync(gltfRuntime, function () {
  1913. _this._loadShadersAsync(gltfRuntime, function () {
  1914. importMaterials(gltfRuntime);
  1915. postLoad(gltfRuntime);
  1916. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1917. onSuccess();
  1918. }
  1919. });
  1920. });
  1921. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1922. onSuccess();
  1923. }
  1924. }, onError);
  1925. }, onError);
  1926. };
  1927. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1928. var _this = this;
  1929. return new Promise(function (resolve, reject) {
  1930. _this._loadAsync(scene, data, rootUrl, function () {
  1931. resolve();
  1932. }, onProgress, function (message) {
  1933. reject(new Error(message));
  1934. });
  1935. });
  1936. };
  1937. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1938. var hasShaders = false;
  1939. var processShader = function (sha, shader) {
  1940. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1941. gltfRuntime.loadedShaderCount++;
  1942. if (shaderString) {
  1943. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1944. }
  1945. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1946. onload();
  1947. }
  1948. }, function () {
  1949. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1950. });
  1951. };
  1952. for (var sha in gltfRuntime.shaders) {
  1953. hasShaders = true;
  1954. var shader = gltfRuntime.shaders[sha];
  1955. if (shader) {
  1956. processShader.bind(this, sha, shader)();
  1957. }
  1958. else {
  1959. BABYLON.Tools.Error("No shader named: " + sha);
  1960. }
  1961. }
  1962. if (!hasShaders) {
  1963. onload();
  1964. }
  1965. };
  1966. ;
  1967. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  1968. var hasBuffers = false;
  1969. var processBuffer = function (buf, buffer) {
  1970. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1971. gltfRuntime.loadedBufferCount++;
  1972. if (bufferView) {
  1973. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1974. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1975. }
  1976. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1977. }
  1978. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1979. onLoad();
  1980. }
  1981. }, function () {
  1982. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1983. });
  1984. };
  1985. for (var buf in gltfRuntime.buffers) {
  1986. hasBuffers = true;
  1987. var buffer = gltfRuntime.buffers[buf];
  1988. if (buffer) {
  1989. processBuffer.bind(this, buf, buffer)();
  1990. }
  1991. else {
  1992. BABYLON.Tools.Error("No buffer named: " + buf);
  1993. }
  1994. }
  1995. if (!hasBuffers) {
  1996. onLoad();
  1997. }
  1998. };
  1999. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2000. var currentScene = gltfRuntime.currentScene;
  2001. if (currentScene) {
  2002. // Only one scene even if multiple scenes are defined
  2003. for (var i = 0; i < currentScene.nodes.length; i++) {
  2004. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2005. }
  2006. }
  2007. else {
  2008. // Load all scenes
  2009. for (var thing in gltfRuntime.scenes) {
  2010. currentScene = gltfRuntime.scenes[thing];
  2011. for (var i = 0; i < currentScene.nodes.length; i++) {
  2012. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2013. }
  2014. }
  2015. }
  2016. };
  2017. GLTFLoader.Extensions = {};
  2018. return GLTFLoader;
  2019. }());
  2020. GLTF1.GLTFLoader = GLTFLoader;
  2021. ;
  2022. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2023. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2024. })(BABYLON || (BABYLON = {}));
  2025. //# sourceMappingURL=babylon.glTFLoader.js.map
  2026. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2027. var BABYLON;
  2028. (function (BABYLON) {
  2029. var GLTF1;
  2030. (function (GLTF1) {
  2031. /**
  2032. * Utils functions for GLTF
  2033. */
  2034. var GLTFUtils = /** @class */ (function () {
  2035. function GLTFUtils() {
  2036. }
  2037. /**
  2038. * Sets the given "parameter" matrix
  2039. * @param scene: the {BABYLON.Scene} object
  2040. * @param source: the source node where to pick the matrix
  2041. * @param parameter: the GLTF technique parameter
  2042. * @param uniformName: the name of the shader's uniform
  2043. * @param shaderMaterial: the shader material
  2044. */
  2045. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2046. var mat = null;
  2047. if (parameter.semantic === "MODEL") {
  2048. mat = source.getWorldMatrix();
  2049. }
  2050. else if (parameter.semantic === "PROJECTION") {
  2051. mat = scene.getProjectionMatrix();
  2052. }
  2053. else if (parameter.semantic === "VIEW") {
  2054. mat = scene.getViewMatrix();
  2055. }
  2056. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2057. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2058. }
  2059. else if (parameter.semantic === "MODELVIEW") {
  2060. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2061. }
  2062. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2063. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2064. }
  2065. else if (parameter.semantic === "MODELINVERSE") {
  2066. mat = source.getWorldMatrix().invert();
  2067. }
  2068. else if (parameter.semantic === "VIEWINVERSE") {
  2069. mat = scene.getViewMatrix().invert();
  2070. }
  2071. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2072. mat = scene.getProjectionMatrix().invert();
  2073. }
  2074. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2075. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2076. }
  2077. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2078. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2079. }
  2080. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2081. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2082. }
  2083. else {
  2084. debugger;
  2085. }
  2086. if (mat) {
  2087. switch (parameter.type) {
  2088. case GLTF1.EParameterType.FLOAT_MAT2:
  2089. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2090. break;
  2091. case GLTF1.EParameterType.FLOAT_MAT3:
  2092. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2093. break;
  2094. case GLTF1.EParameterType.FLOAT_MAT4:
  2095. shaderMaterial.setMatrix(uniformName, mat);
  2096. break;
  2097. default: break;
  2098. }
  2099. }
  2100. };
  2101. /**
  2102. * Sets the given "parameter" matrix
  2103. * @param shaderMaterial: the shader material
  2104. * @param uniform: the name of the shader's uniform
  2105. * @param value: the value of the uniform
  2106. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2107. */
  2108. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2109. switch (type) {
  2110. case GLTF1.EParameterType.FLOAT:
  2111. shaderMaterial.setFloat(uniform, value);
  2112. return true;
  2113. case GLTF1.EParameterType.FLOAT_VEC2:
  2114. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2115. return true;
  2116. case GLTF1.EParameterType.FLOAT_VEC3:
  2117. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2118. return true;
  2119. case GLTF1.EParameterType.FLOAT_VEC4:
  2120. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2121. return true;
  2122. default: return false;
  2123. }
  2124. };
  2125. /**
  2126. * Returns the wrap mode of the texture
  2127. * @param mode: the mode value
  2128. */
  2129. GLTFUtils.GetWrapMode = function (mode) {
  2130. switch (mode) {
  2131. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2132. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2133. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2134. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2135. }
  2136. };
  2137. /**
  2138. * Returns the byte stride giving an accessor
  2139. * @param accessor: the GLTF accessor objet
  2140. */
  2141. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2142. // Needs this function since "byteStride" isn't requiered in glTF format
  2143. var type = accessor.type;
  2144. switch (type) {
  2145. case "VEC2": return 2;
  2146. case "VEC3": return 3;
  2147. case "VEC4": return 4;
  2148. case "MAT2": return 4;
  2149. case "MAT3": return 9;
  2150. case "MAT4": return 16;
  2151. default: return 1;
  2152. }
  2153. };
  2154. /**
  2155. * Returns the texture filter mode giving a mode value
  2156. * @param mode: the filter mode value
  2157. */
  2158. GLTFUtils.GetTextureFilterMode = function (mode) {
  2159. switch (mode) {
  2160. case GLTF1.ETextureFilterType.LINEAR:
  2161. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2162. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2163. case GLTF1.ETextureFilterType.NEAREST:
  2164. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2165. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2166. }
  2167. };
  2168. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2169. var byteOffset = bufferView.byteOffset + byteOffset;
  2170. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2171. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2172. throw new Error("Buffer access is out of range");
  2173. }
  2174. var buffer = loadedBufferView.buffer;
  2175. byteOffset += loadedBufferView.byteOffset;
  2176. switch (componentType) {
  2177. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2178. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2179. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2180. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2181. default: return new Float32Array(buffer, byteOffset, byteLength);
  2182. }
  2183. };
  2184. /**
  2185. * Returns a buffer from its accessor
  2186. * @param gltfRuntime: the GLTF runtime
  2187. * @param accessor: the GLTF accessor
  2188. */
  2189. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2190. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2191. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2192. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2193. };
  2194. /**
  2195. * Decodes a buffer view into a string
  2196. * @param view: the buffer view
  2197. */
  2198. GLTFUtils.DecodeBufferToText = function (view) {
  2199. var result = "";
  2200. var length = view.byteLength;
  2201. for (var i = 0; i < length; ++i) {
  2202. result += String.fromCharCode(view[i]);
  2203. }
  2204. return result;
  2205. };
  2206. /**
  2207. * Returns the default material of gltf. Related to
  2208. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2209. * @param scene: the Babylon.js scene
  2210. */
  2211. GLTFUtils.GetDefaultMaterial = function (scene) {
  2212. if (!GLTFUtils._DefaultMaterial) {
  2213. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2214. "precision highp float;",
  2215. "",
  2216. "uniform mat4 worldView;",
  2217. "uniform mat4 projection;",
  2218. "",
  2219. "attribute vec3 position;",
  2220. "",
  2221. "void main(void)",
  2222. "{",
  2223. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2224. "}"
  2225. ].join("\n");
  2226. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2227. "precision highp float;",
  2228. "",
  2229. "uniform vec4 u_emission;",
  2230. "",
  2231. "void main(void)",
  2232. "{",
  2233. " gl_FragColor = u_emission;",
  2234. "}"
  2235. ].join("\n");
  2236. var shaderPath = {
  2237. vertex: "GLTFDefaultMaterial",
  2238. fragment: "GLTFDefaultMaterial"
  2239. };
  2240. var options = {
  2241. attributes: ["position"],
  2242. uniforms: ["worldView", "projection", "u_emission"],
  2243. samplers: new Array(),
  2244. needAlphaBlending: false
  2245. };
  2246. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2247. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2248. }
  2249. return GLTFUtils._DefaultMaterial;
  2250. };
  2251. // The GLTF default material
  2252. GLTFUtils._DefaultMaterial = null;
  2253. return GLTFUtils;
  2254. }());
  2255. GLTF1.GLTFUtils = GLTFUtils;
  2256. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2257. })(BABYLON || (BABYLON = {}));
  2258. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2259. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2260. var BABYLON;
  2261. (function (BABYLON) {
  2262. var GLTF1;
  2263. (function (GLTF1) {
  2264. var GLTFLoaderExtension = /** @class */ (function () {
  2265. function GLTFLoaderExtension(name) {
  2266. this._name = name;
  2267. }
  2268. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2269. get: function () {
  2270. return this._name;
  2271. },
  2272. enumerable: true,
  2273. configurable: true
  2274. });
  2275. /**
  2276. * Defines an override for loading the runtime
  2277. * Return true to stop further extensions from loading the runtime
  2278. */
  2279. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2280. return false;
  2281. };
  2282. /**
  2283. * Defines an onverride for creating gltf runtime
  2284. * Return true to stop further extensions from creating the runtime
  2285. */
  2286. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2287. return false;
  2288. };
  2289. /**
  2290. * Defines an override for loading buffers
  2291. * Return true to stop further extensions from loading this buffer
  2292. */
  2293. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2294. return false;
  2295. };
  2296. /**
  2297. * Defines an override for loading texture buffers
  2298. * Return true to stop further extensions from loading this texture data
  2299. */
  2300. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2301. return false;
  2302. };
  2303. /**
  2304. * Defines an override for creating textures
  2305. * Return true to stop further extensions from loading this texture
  2306. */
  2307. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2308. return false;
  2309. };
  2310. /**
  2311. * Defines an override for loading shader strings
  2312. * Return true to stop further extensions from loading this shader data
  2313. */
  2314. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2315. return false;
  2316. };
  2317. /**
  2318. * Defines an override for loading materials
  2319. * Return true to stop further extensions from loading this material
  2320. */
  2321. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2322. return false;
  2323. };
  2324. // ---------
  2325. // Utilities
  2326. // ---------
  2327. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2328. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2329. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2330. }, function () {
  2331. setTimeout(function () {
  2332. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2333. });
  2334. });
  2335. };
  2336. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2337. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2338. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2339. }, function () {
  2340. setTimeout(function () {
  2341. onSuccess();
  2342. });
  2343. });
  2344. };
  2345. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2346. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2347. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2348. }, function () {
  2349. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2350. });
  2351. };
  2352. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2353. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  2354. };
  2355. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2356. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2357. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2358. }, function () {
  2359. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2360. });
  2361. };
  2362. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2363. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2364. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2365. }, function () {
  2366. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2367. });
  2368. };
  2369. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2370. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2371. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2372. }, function () {
  2373. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2374. });
  2375. };
  2376. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2377. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2378. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2379. }, function () {
  2380. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2381. });
  2382. };
  2383. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2384. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2385. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2386. if (func(loaderExtension)) {
  2387. return;
  2388. }
  2389. }
  2390. defaultFunc();
  2391. };
  2392. return GLTFLoaderExtension;
  2393. }());
  2394. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2395. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2396. })(BABYLON || (BABYLON = {}));
  2397. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2398. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2399. var __extends = (this && this.__extends) || (function () {
  2400. var extendStatics = Object.setPrototypeOf ||
  2401. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2402. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2403. return function (d, b) {
  2404. extendStatics(d, b);
  2405. function __() { this.constructor = d; }
  2406. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2407. };
  2408. })();
  2409. var BABYLON;
  2410. (function (BABYLON) {
  2411. var GLTF1;
  2412. (function (GLTF1) {
  2413. var BinaryExtensionBufferName = "binary_glTF";
  2414. ;
  2415. ;
  2416. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2417. __extends(GLTFBinaryExtension, _super);
  2418. function GLTFBinaryExtension() {
  2419. return _super.call(this, "KHR_binary_glTF") || this;
  2420. }
  2421. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2422. var extensionsUsed = data.json.extensionsUsed;
  2423. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2424. return false;
  2425. }
  2426. this._bin = data.bin;
  2427. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2428. return true;
  2429. };
  2430. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2431. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2432. return false;
  2433. }
  2434. if (id !== BinaryExtensionBufferName) {
  2435. return false;
  2436. }
  2437. onSuccess(this._bin);
  2438. return true;
  2439. };
  2440. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2441. var texture = gltfRuntime.textures[id];
  2442. var source = gltfRuntime.images[texture.source];
  2443. if (!source.extensions || !(this.name in source.extensions)) {
  2444. return false;
  2445. }
  2446. var sourceExt = source.extensions[this.name];
  2447. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2448. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2449. onSuccess(buffer);
  2450. return true;
  2451. };
  2452. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2453. var shader = gltfRuntime.shaders[id];
  2454. if (!shader.extensions || !(this.name in shader.extensions)) {
  2455. return false;
  2456. }
  2457. var binaryExtensionShader = shader.extensions[this.name];
  2458. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2459. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2460. setTimeout(function () {
  2461. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2462. onSuccess(shaderString);
  2463. });
  2464. return true;
  2465. };
  2466. return GLTFBinaryExtension;
  2467. }(GLTF1.GLTFLoaderExtension));
  2468. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2469. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2470. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2471. })(BABYLON || (BABYLON = {}));
  2472. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2473. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2474. var __extends = (this && this.__extends) || (function () {
  2475. var extendStatics = Object.setPrototypeOf ||
  2476. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2477. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2478. return function (d, b) {
  2479. extendStatics(d, b);
  2480. function __() { this.constructor = d; }
  2481. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2482. };
  2483. })();
  2484. var BABYLON;
  2485. (function (BABYLON) {
  2486. var GLTF1;
  2487. (function (GLTF1) {
  2488. ;
  2489. ;
  2490. ;
  2491. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2492. __extends(GLTFMaterialsCommonExtension, _super);
  2493. function GLTFMaterialsCommonExtension() {
  2494. return _super.call(this, "KHR_materials_common") || this;
  2495. }
  2496. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2497. if (!gltfRuntime.extensions)
  2498. return false;
  2499. var extension = gltfRuntime.extensions[this.name];
  2500. if (!extension)
  2501. return false;
  2502. // Create lights
  2503. var lights = extension.lights;
  2504. if (lights) {
  2505. for (var thing in lights) {
  2506. var light = lights[thing];
  2507. switch (light.type) {
  2508. case "ambient":
  2509. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2510. var ambient = light.ambient;
  2511. if (ambient) {
  2512. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2513. }
  2514. break;
  2515. case "point":
  2516. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2517. var point = light.point;
  2518. if (point) {
  2519. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2520. }
  2521. break;
  2522. case "directional":
  2523. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2524. var directional = light.directional;
  2525. if (directional) {
  2526. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2527. }
  2528. break;
  2529. case "spot":
  2530. var spot = light.spot;
  2531. if (spot) {
  2532. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2533. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2534. }
  2535. break;
  2536. default:
  2537. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2538. break;
  2539. }
  2540. }
  2541. }
  2542. return false;
  2543. };
  2544. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2545. var material = gltfRuntime.materials[id];
  2546. if (!material || !material.extensions)
  2547. return false;
  2548. var extension = material.extensions[this.name];
  2549. if (!extension)
  2550. return false;
  2551. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2552. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2553. if (extension.technique === "CONSTANT") {
  2554. standardMaterial.disableLighting = true;
  2555. }
  2556. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2557. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2558. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2559. // Ambient
  2560. if (typeof extension.values.ambient === "string") {
  2561. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2562. }
  2563. else {
  2564. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2565. }
  2566. // Diffuse
  2567. if (typeof extension.values.diffuse === "string") {
  2568. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2569. }
  2570. else {
  2571. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2572. }
  2573. // Emission
  2574. if (typeof extension.values.emission === "string") {
  2575. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2576. }
  2577. else {
  2578. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2579. }
  2580. // Specular
  2581. if (typeof extension.values.specular === "string") {
  2582. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2583. }
  2584. else {
  2585. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2586. }
  2587. return true;
  2588. };
  2589. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2590. // Create buffer from texture url
  2591. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2592. // Create texture from buffer
  2593. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2594. }, onError);
  2595. };
  2596. return GLTFMaterialsCommonExtension;
  2597. }(GLTF1.GLTFLoaderExtension));
  2598. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2599. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2600. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2601. })(BABYLON || (BABYLON = {}));
  2602. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  2603. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2604. var BABYLON;
  2605. (function (BABYLON) {
  2606. var GLTF2;
  2607. (function (GLTF2) {
  2608. var ArrayItem = /** @class */ (function () {
  2609. function ArrayItem() {
  2610. }
  2611. ArrayItem.Assign = function (values) {
  2612. if (values) {
  2613. for (var index = 0; index < values.length; index++) {
  2614. values[index]._index = index;
  2615. }
  2616. }
  2617. };
  2618. return ArrayItem;
  2619. }());
  2620. GLTF2.ArrayItem = ArrayItem;
  2621. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2622. })(BABYLON || (BABYLON = {}));
  2623. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  2624. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2625. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  2626. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  2627. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2628. var BABYLON;
  2629. (function (BABYLON) {
  2630. var GLTF2;
  2631. (function (GLTF2) {
  2632. var GLTFLoader = /** @class */ (function () {
  2633. function GLTFLoader() {
  2634. this._completePromises = new Array();
  2635. this._disposed = false;
  2636. this._state = null;
  2637. this._extensions = {};
  2638. this._defaultSampler = {};
  2639. this._requests = new Array();
  2640. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  2641. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  2642. this.compileMaterials = false;
  2643. this.useClipPlane = false;
  2644. this.compileShadowGenerators = false;
  2645. this.onDisposeObservable = new BABYLON.Observable();
  2646. this.onMeshLoadedObservable = new BABYLON.Observable();
  2647. this.onTextureLoadedObservable = new BABYLON.Observable();
  2648. this.onMaterialLoadedObservable = new BABYLON.Observable();
  2649. this.onCompleteObservable = new BABYLON.Observable();
  2650. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  2651. var name_1 = _a[_i];
  2652. var extension = GLTFLoader._Factories[name_1](this);
  2653. this._extensions[name_1] = extension;
  2654. }
  2655. }
  2656. GLTFLoader._Register = function (name, factory) {
  2657. if (GLTFLoader._Factories[name]) {
  2658. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  2659. return;
  2660. }
  2661. GLTFLoader._Factories[name] = factory;
  2662. // Keep the order of registration so that extensions registered first are called first.
  2663. GLTFLoader._Names.push(name);
  2664. };
  2665. Object.defineProperty(GLTFLoader.prototype, "state", {
  2666. get: function () {
  2667. return this._state;
  2668. },
  2669. enumerable: true,
  2670. configurable: true
  2671. });
  2672. Object.defineProperty(GLTFLoader.prototype, "extensions", {
  2673. get: function () {
  2674. return this.extensions;
  2675. },
  2676. enumerable: true,
  2677. configurable: true
  2678. });
  2679. GLTFLoader.prototype.dispose = function () {
  2680. if (this._disposed) {
  2681. return;
  2682. }
  2683. this._disposed = true;
  2684. this._abortRequests();
  2685. this._releaseResources();
  2686. this.onDisposeObservable.notifyObservers(this);
  2687. };
  2688. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  2689. var _this = this;
  2690. return Promise.resolve().then(function () {
  2691. var nodes = null;
  2692. if (meshesNames) {
  2693. var nodeMap_1 = {};
  2694. if (_this._gltf.nodes) {
  2695. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  2696. var node = _a[_i];
  2697. if (node.name) {
  2698. nodeMap_1[node.name] = node;
  2699. }
  2700. }
  2701. }
  2702. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  2703. nodes = names.map(function (name) {
  2704. var node = nodeMap_1[name];
  2705. if (!node) {
  2706. throw new Error("Failed to find node " + name);
  2707. }
  2708. return node;
  2709. });
  2710. }
  2711. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  2712. return {
  2713. meshes: _this._getMeshes(),
  2714. particleSystems: [],
  2715. skeletons: _this._getSkeletons(),
  2716. };
  2717. });
  2718. });
  2719. };
  2720. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  2721. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  2722. };
  2723. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  2724. var _this = this;
  2725. return Promise.resolve().then(function () {
  2726. _this._babylonScene = scene;
  2727. _this._rootUrl = rootUrl;
  2728. _this._progressCallback = onProgress;
  2729. _this._state = BABYLON.GLTFLoaderState.Loading;
  2730. _this._loadData(data);
  2731. var promises = new Array();
  2732. if (nodes) {
  2733. promises.push(_this._loadNodesAsync(nodes));
  2734. }
  2735. else {
  2736. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  2737. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  2738. }
  2739. if (_this.compileMaterials) {
  2740. promises.push(_this._compileMaterialsAsync());
  2741. }
  2742. if (_this.compileShadowGenerators) {
  2743. promises.push(_this._compileShadowGeneratorsAsync());
  2744. }
  2745. return Promise.all(promises).then(function () {
  2746. _this._state = BABYLON.GLTFLoaderState.Ready;
  2747. _this._startAnimations();
  2748. BABYLON.Tools.SetImmediate(function () {
  2749. Promise.all(_this._completePromises).then(function () {
  2750. _this._releaseResources();
  2751. _this._state = BABYLON.GLTFLoaderState.Complete;
  2752. _this.onCompleteObservable.notifyObservers(_this);
  2753. }).catch(function (error) {
  2754. BABYLON.Tools.Error("glTF Loader: " + error.message);
  2755. _this.dispose();
  2756. });
  2757. });
  2758. }).catch(function (error) {
  2759. BABYLON.Tools.Error("glTF Loader: " + error.message);
  2760. _this.dispose();
  2761. throw error;
  2762. });
  2763. });
  2764. };
  2765. GLTFLoader.prototype._loadData = function (data) {
  2766. this._gltf = data.json;
  2767. this._setupData();
  2768. if (data.bin) {
  2769. var buffers = this._gltf.buffers;
  2770. if (buffers && buffers[0] && !buffers[0].uri) {
  2771. var binaryBuffer = buffers[0];
  2772. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  2773. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  2774. }
  2775. binaryBuffer._data = Promise.resolve(data.bin);
  2776. }
  2777. else {
  2778. BABYLON.Tools.Warn("Unexpected BIN chunk");
  2779. }
  2780. }
  2781. };
  2782. GLTFLoader.prototype._setupData = function () {
  2783. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  2784. GLTF2.ArrayItem.Assign(this._gltf.animations);
  2785. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  2786. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  2787. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  2788. GLTF2.ArrayItem.Assign(this._gltf.images);
  2789. GLTF2.ArrayItem.Assign(this._gltf.materials);
  2790. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  2791. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  2792. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  2793. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  2794. GLTF2.ArrayItem.Assign(this._gltf.skins);
  2795. GLTF2.ArrayItem.Assign(this._gltf.textures);
  2796. if (this._gltf.nodes) {
  2797. var nodeParents = {};
  2798. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  2799. var node = _a[_i];
  2800. if (node.children) {
  2801. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  2802. var index = _c[_b];
  2803. nodeParents[index] = node._index;
  2804. }
  2805. }
  2806. }
  2807. var rootNode = this._createRootNode();
  2808. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  2809. var node = _e[_d];
  2810. var parentIndex = nodeParents[node._index];
  2811. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  2812. }
  2813. }
  2814. };
  2815. GLTFLoader.prototype._createRootNode = function () {
  2816. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  2817. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  2818. switch (this.coordinateSystemMode) {
  2819. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  2820. if (!this._babylonScene.useRightHandedSystem) {
  2821. rootNode.rotation = [0, 1, 0, 0];
  2822. rootNode.scale = [1, 1, -1];
  2823. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  2824. }
  2825. break;
  2826. }
  2827. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  2828. this._babylonScene.useRightHandedSystem = true;
  2829. break;
  2830. }
  2831. default: {
  2832. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  2833. }
  2834. }
  2835. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  2836. return rootNode;
  2837. };
  2838. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  2839. var promises = new Array();
  2840. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  2841. var node = nodes_1[_i];
  2842. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  2843. }
  2844. promises.push(this._loadAnimationsAsync());
  2845. return Promise.all(promises).then(function () { });
  2846. };
  2847. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  2848. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  2849. if (promise) {
  2850. return promise;
  2851. }
  2852. var promises = new Array();
  2853. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  2854. var index = _a[_i];
  2855. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  2856. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  2857. }
  2858. promises.push(this._loadAnimationsAsync());
  2859. return Promise.all(promises).then(function () { });
  2860. };
  2861. GLTFLoader.prototype._getMeshes = function () {
  2862. var meshes = new Array();
  2863. // Root mesh is always first.
  2864. meshes.push(this._rootBabylonMesh);
  2865. var nodes = this._gltf.nodes;
  2866. if (nodes) {
  2867. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  2868. var node = nodes_2[_i];
  2869. if (node._babylonMesh) {
  2870. meshes.push(node._babylonMesh);
  2871. }
  2872. }
  2873. }
  2874. return meshes;
  2875. };
  2876. GLTFLoader.prototype._getSkeletons = function () {
  2877. var skeletons = new Array();
  2878. var skins = this._gltf.skins;
  2879. if (skins) {
  2880. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  2881. var skin = skins_1[_i];
  2882. if (skin._babylonSkeleton) {
  2883. skeletons.push(skin._babylonSkeleton);
  2884. }
  2885. }
  2886. }
  2887. return skeletons;
  2888. };
  2889. GLTFLoader.prototype._startAnimations = function () {
  2890. var animations = this._gltf.animations;
  2891. if (!animations) {
  2892. return;
  2893. }
  2894. switch (this.animationStartMode) {
  2895. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  2896. // do nothing
  2897. break;
  2898. }
  2899. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  2900. var animation = animations[0];
  2901. animation._babylonAnimationGroup.start(true);
  2902. break;
  2903. }
  2904. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  2905. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  2906. var animation = animations_1[_i];
  2907. animation._babylonAnimationGroup.start(true);
  2908. }
  2909. break;
  2910. }
  2911. default: {
  2912. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  2913. return;
  2914. }
  2915. }
  2916. };
  2917. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  2918. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  2919. if (promise) {
  2920. return promise;
  2921. }
  2922. if (node._babylonMesh) {
  2923. throw new Error(context + ": Invalid recursive node hierarchy");
  2924. }
  2925. var promises = new Array();
  2926. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  2927. node._babylonMesh = babylonMesh;
  2928. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  2929. node._babylonAnimationTargets.push(babylonMesh);
  2930. GLTFLoader._LoadTransform(node, babylonMesh);
  2931. if (node.mesh != undefined) {
  2932. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  2933. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  2934. }
  2935. if (node.children) {
  2936. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  2937. var index = _a[_i];
  2938. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  2939. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  2940. }
  2941. }
  2942. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  2943. return Promise.all(promises).then(function () { });
  2944. };
  2945. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  2946. // TODO: instancing
  2947. var promises = new Array();
  2948. var primitives = mesh.primitives;
  2949. if (!primitives || primitives.length === 0) {
  2950. throw new Error(context + ": Primitives are missing");
  2951. }
  2952. GLTF2.ArrayItem.Assign(primitives);
  2953. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  2954. var primitive = primitives_1[_i];
  2955. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  2956. }
  2957. if (node.skin != undefined) {
  2958. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  2959. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  2960. }
  2961. return Promise.all(promises).then(function () {
  2962. if (node._primitiveBabylonMeshes) {
  2963. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  2964. var primitiveBabylonMesh = _a[_i];
  2965. primitiveBabylonMesh._refreshBoundingInfo(true);
  2966. }
  2967. }
  2968. });
  2969. };
  2970. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  2971. var _this = this;
  2972. var promises = new Array();
  2973. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  2974. babylonMesh.setEnabled(false);
  2975. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  2976. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  2977. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  2978. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  2979. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  2980. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  2981. }));
  2982. if (primitive.material == undefined) {
  2983. babylonMesh.material = this._getDefaultMaterial();
  2984. }
  2985. else {
  2986. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  2987. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  2988. }
  2989. return Promise.all(promises).then(function () {
  2990. babylonMesh.setEnabled(true);
  2991. });
  2992. };
  2993. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  2994. var _this = this;
  2995. var attributes = primitive.attributes;
  2996. if (!attributes) {
  2997. throw new Error(context + ": Attributes are missing");
  2998. }
  2999. if (primitive.mode && primitive.mode !== 4 /* TRIANGLES */) {
  3000. // TODO: handle other primitive modes
  3001. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  3002. }
  3003. var promises = new Array();
  3004. var babylonVertexData = new BABYLON.VertexData();
  3005. if (primitive.indices == undefined) {
  3006. var positionAccessorIndex = attributes["POSITION"];
  3007. if (positionAccessorIndex != undefined) {
  3008. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  3009. babylonVertexData.indices = new Uint32Array(accessor.count);
  3010. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  3011. babylonVertexData.indices[i] = i;
  3012. }
  3013. }
  3014. }
  3015. else {
  3016. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  3017. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  3018. babylonVertexData.indices = data;
  3019. }));
  3020. }
  3021. var loadAttribute = function (attribute, kind) {
  3022. if (attributes[attribute] == undefined) {
  3023. return;
  3024. }
  3025. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3026. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3027. babylonMesh._delayInfo.push(kind);
  3028. }
  3029. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3030. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3031. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  3032. if (attribute === "COLOR_0") {
  3033. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  3034. babylonMesh.hasVertexAlpha = true;
  3035. if (accessor.type === "VEC3") {
  3036. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  3037. }
  3038. }
  3039. babylonVertexData.set(attributeData, kind);
  3040. }));
  3041. };
  3042. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  3043. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  3044. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  3045. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  3046. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  3047. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  3048. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  3049. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  3050. return Promise.all(promises).then(function () {
  3051. return babylonVertexData;
  3052. });
  3053. };
  3054. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  3055. if (!primitive.targets) {
  3056. return;
  3057. }
  3058. if (node._numMorphTargets == undefined) {
  3059. node._numMorphTargets = primitive.targets.length;
  3060. }
  3061. else if (primitive.targets.length !== node._numMorphTargets) {
  3062. throw new Error(context + ": Primitives do not have the same number of targets");
  3063. }
  3064. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  3065. for (var index = 0; index < primitive.targets.length; index++) {
  3066. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  3067. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  3068. // TODO: tell the target whether it has positions, normals, tangents
  3069. }
  3070. };
  3071. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  3072. if (!primitive.targets) {
  3073. return Promise.resolve();
  3074. }
  3075. var promises = new Array();
  3076. var morphTargetManager = babylonMesh.morphTargetManager;
  3077. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  3078. var babylonMorphTarget = morphTargetManager.getTarget(index);
  3079. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  3080. }
  3081. return Promise.all(promises).then(function () { });
  3082. };
  3083. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  3084. var _this = this;
  3085. var promises = new Array();
  3086. var loadAttribute = function (attribute, setData) {
  3087. if (attributes[attribute] == undefined) {
  3088. return;
  3089. }
  3090. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3091. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3092. setData(data);
  3093. }));
  3094. };
  3095. loadAttribute("POSITION", function (data) {
  3096. if (babylonVertexData.positions) {
  3097. for (var i = 0; i < data.length; i++) {
  3098. data[i] += babylonVertexData.positions[i];
  3099. }
  3100. babylonMorphTarget.setPositions(data);
  3101. }
  3102. });
  3103. loadAttribute("NORMAL", function (data) {
  3104. if (babylonVertexData.normals) {
  3105. for (var i = 0; i < data.length; i++) {
  3106. data[i] += babylonVertexData.normals[i];
  3107. }
  3108. babylonMorphTarget.setNormals(data);
  3109. }
  3110. });
  3111. loadAttribute("TANGENT", function (data) {
  3112. if (babylonVertexData.tangents) {
  3113. // Tangent data for morph targets is stored as xyz delta.
  3114. // The vertexData.tangent is stored as xyzw.
  3115. // So we need to skip every fourth vertexData.tangent.
  3116. for (var i = 0, j = 0; i < data.length; i++) {
  3117. data[i] += babylonVertexData.tangents[j++];
  3118. if ((i + 1) % 3 == 0) {
  3119. j++;
  3120. }
  3121. }
  3122. babylonMorphTarget.setTangents(data);
  3123. }
  3124. });
  3125. return Promise.all(promises).then(function () { });
  3126. };
  3127. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  3128. if (accessor.componentType == 5126 /* FLOAT */) {
  3129. return data;
  3130. }
  3131. var factor = 1;
  3132. if (accessor.normalized) {
  3133. switch (accessor.componentType) {
  3134. case 5121 /* UNSIGNED_BYTE */: {
  3135. factor = 1 / 255;
  3136. break;
  3137. }
  3138. case 5123 /* UNSIGNED_SHORT */: {
  3139. factor = 1 / 65535;
  3140. break;
  3141. }
  3142. default: {
  3143. throw new Error(context + ": Invalid component type " + accessor.componentType);
  3144. }
  3145. }
  3146. }
  3147. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  3148. for (var i = 0; i < result.length; i++) {
  3149. result[i] = data[i] * factor;
  3150. }
  3151. return result;
  3152. };
  3153. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  3154. var result = new Float32Array(data.length / 3 * 4);
  3155. var offset = 0;
  3156. for (var i = 0; i < result.length; i++) {
  3157. if ((i + 1) % 4 === 0) {
  3158. result[i] = 1;
  3159. }
  3160. else {
  3161. result[i] = data[offset++];
  3162. }
  3163. }
  3164. return result;
  3165. };
  3166. GLTFLoader._LoadTransform = function (node, babylonNode) {
  3167. var position = BABYLON.Vector3.Zero();
  3168. var rotation = BABYLON.Quaternion.Identity();
  3169. var scaling = BABYLON.Vector3.One();
  3170. if (node.matrix) {
  3171. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  3172. matrix.decompose(scaling, rotation, position);
  3173. }
  3174. else {
  3175. if (node.translation)
  3176. position = BABYLON.Vector3.FromArray(node.translation);
  3177. if (node.rotation)
  3178. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  3179. if (node.scale)
  3180. scaling = BABYLON.Vector3.FromArray(node.scale);
  3181. }
  3182. babylonNode.position = position;
  3183. babylonNode.rotationQuaternion = rotation;
  3184. babylonNode.scaling = scaling;
  3185. };
  3186. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  3187. var _this = this;
  3188. var assignSkeleton = function () {
  3189. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  3190. var babylonMesh = _a[_i];
  3191. babylonMesh.skeleton = skin._babylonSkeleton;
  3192. }
  3193. node._babylonMesh.parent = _this._rootBabylonMesh;
  3194. node._babylonMesh.position = BABYLON.Vector3.Zero();
  3195. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  3196. node._babylonMesh.scaling = BABYLON.Vector3.One();
  3197. };
  3198. if (skin._loaded) {
  3199. assignSkeleton();
  3200. return skin._loaded;
  3201. }
  3202. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  3203. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  3204. var skeletonId = "skeleton" + skin._index;
  3205. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  3206. skin._babylonSkeleton = babylonSkeleton;
  3207. _this._loadBones(context, skin, inverseBindMatricesData);
  3208. assignSkeleton();
  3209. }));
  3210. };
  3211. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  3212. if (skin.inverseBindMatrices == undefined) {
  3213. return Promise.resolve(null);
  3214. }
  3215. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  3216. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3217. return data;
  3218. });
  3219. };
  3220. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  3221. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  3222. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  3223. node._babylonAnimationTargets.push(babylonBone);
  3224. return babylonBone;
  3225. };
  3226. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  3227. var babylonBones = {};
  3228. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  3229. var index = _a[_i];
  3230. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  3231. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  3232. }
  3233. };
  3234. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  3235. var babylonBone = babylonBones[node._index];
  3236. if (babylonBone) {
  3237. return babylonBone;
  3238. }
  3239. var boneIndex = skin.joints.indexOf(node._index);
  3240. var baseMatrix = BABYLON.Matrix.Identity();
  3241. if (inverseBindMatricesData && boneIndex !== -1) {
  3242. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  3243. baseMatrix.invertToRef(baseMatrix);
  3244. }
  3245. var babylonParentBone = null;
  3246. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  3247. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  3248. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  3249. }
  3250. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  3251. babylonBones[node._index] = babylonBone;
  3252. return babylonBone;
  3253. };
  3254. GLTFLoader.prototype._getNodeMatrix = function (node) {
  3255. return node.matrix ?
  3256. BABYLON.Matrix.FromArray(node.matrix) :
  3257. 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());
  3258. };
  3259. GLTFLoader.prototype._loadAnimationsAsync = function () {
  3260. var animations = this._gltf.animations;
  3261. if (!animations) {
  3262. return Promise.resolve();
  3263. }
  3264. var promises = new Array();
  3265. for (var index = 0; index < animations.length; index++) {
  3266. var animation = animations[index];
  3267. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  3268. }
  3269. return Promise.all(promises).then(function () { });
  3270. };
  3271. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  3272. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  3273. animation._babylonAnimationGroup = babylonAnimationGroup;
  3274. var promises = new Array();
  3275. GLTF2.ArrayItem.Assign(animation.channels);
  3276. GLTF2.ArrayItem.Assign(animation.samplers);
  3277. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  3278. var channel = _a[_i];
  3279. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  3280. }
  3281. return Promise.all(promises).then(function () {
  3282. babylonAnimationGroup.normalize();
  3283. });
  3284. };
  3285. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  3286. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  3287. if (!targetNode._babylonMesh) {
  3288. return Promise.resolve();
  3289. }
  3290. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  3291. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  3292. var targetPath;
  3293. var animationType;
  3294. switch (channel.target.path) {
  3295. case "translation" /* TRANSLATION */: {
  3296. targetPath = "position";
  3297. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3298. break;
  3299. }
  3300. case "rotation" /* ROTATION */: {
  3301. targetPath = "rotationQuaternion";
  3302. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  3303. break;
  3304. }
  3305. case "scale" /* SCALE */: {
  3306. targetPath = "scaling";
  3307. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3308. break;
  3309. }
  3310. case "weights" /* WEIGHTS */: {
  3311. targetPath = "influence";
  3312. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  3313. break;
  3314. }
  3315. default: {
  3316. throw new Error(context + ": Invalid target path " + channel.target.path);
  3317. }
  3318. }
  3319. var outputBufferOffset = 0;
  3320. var getNextOutputValue;
  3321. switch (targetPath) {
  3322. case "position": {
  3323. getNextOutputValue = function () {
  3324. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3325. outputBufferOffset += 3;
  3326. return value;
  3327. };
  3328. break;
  3329. }
  3330. case "rotationQuaternion": {
  3331. getNextOutputValue = function () {
  3332. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  3333. outputBufferOffset += 4;
  3334. return value;
  3335. };
  3336. break;
  3337. }
  3338. case "scaling": {
  3339. getNextOutputValue = function () {
  3340. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3341. outputBufferOffset += 3;
  3342. return value;
  3343. };
  3344. break;
  3345. }
  3346. case "influence": {
  3347. getNextOutputValue = function () {
  3348. var value = new Array(targetNode._numMorphTargets);
  3349. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  3350. value[i] = data.output[outputBufferOffset++];
  3351. }
  3352. return value;
  3353. };
  3354. break;
  3355. }
  3356. }
  3357. var getNextKey;
  3358. switch (data.interpolation) {
  3359. case "STEP" /* STEP */: {
  3360. getNextKey = function (frameIndex) { return ({
  3361. frame: data.input[frameIndex],
  3362. value: getNextOutputValue(),
  3363. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  3364. }); };
  3365. break;
  3366. }
  3367. case "LINEAR" /* LINEAR */: {
  3368. getNextKey = function (frameIndex) { return ({
  3369. frame: data.input[frameIndex],
  3370. value: getNextOutputValue()
  3371. }); };
  3372. break;
  3373. }
  3374. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3375. getNextKey = function (frameIndex) { return ({
  3376. frame: data.input[frameIndex],
  3377. inTangent: getNextOutputValue(),
  3378. value: getNextOutputValue(),
  3379. outTangent: getNextOutputValue()
  3380. }); };
  3381. break;
  3382. }
  3383. }
  3384. var keys;
  3385. if (data.input.length === 1) {
  3386. var key = getNextKey(0);
  3387. keys = [
  3388. { frame: key.frame, value: key.value },
  3389. { frame: key.frame + 1, value: key.value }
  3390. ];
  3391. }
  3392. else {
  3393. keys = new Array(data.input.length);
  3394. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  3395. keys[frameIndex] = getNextKey(frameIndex);
  3396. }
  3397. }
  3398. if (targetPath === "influence") {
  3399. var _loop_1 = function (targetIndex) {
  3400. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3401. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3402. babylonAnimation.setKeys(keys.map(function (key) { return ({
  3403. frame: key.frame,
  3404. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  3405. value: key.value[targetIndex],
  3406. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  3407. }); }));
  3408. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  3409. var babylonMesh = _a[_i];
  3410. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  3411. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  3412. }
  3413. };
  3414. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  3415. _loop_1(targetIndex);
  3416. }
  3417. }
  3418. else {
  3419. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3420. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3421. babylonAnimation.setKeys(keys);
  3422. if (targetNode._babylonAnimationTargets) {
  3423. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  3424. var target = _a[_i];
  3425. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  3426. }
  3427. }
  3428. }
  3429. });
  3430. };
  3431. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  3432. if (sampler._data) {
  3433. return sampler._data;
  3434. }
  3435. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  3436. switch (interpolation) {
  3437. case "STEP" /* STEP */:
  3438. case "LINEAR" /* LINEAR */:
  3439. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3440. break;
  3441. }
  3442. default: {
  3443. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  3444. }
  3445. }
  3446. var inputData;
  3447. var outputData;
  3448. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  3449. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  3450. sampler._data = Promise.all([
  3451. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  3452. inputData = data;
  3453. }),
  3454. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  3455. outputData = data;
  3456. })
  3457. ]).then(function () {
  3458. return {
  3459. input: inputData,
  3460. interpolation: interpolation,
  3461. output: outputData,
  3462. };
  3463. });
  3464. return sampler._data;
  3465. };
  3466. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  3467. if (buffer._data) {
  3468. return buffer._data;
  3469. }
  3470. if (!buffer.uri) {
  3471. throw new Error(context + ": Uri is missing");
  3472. }
  3473. buffer._data = this._loadUriAsync(context, buffer.uri);
  3474. return buffer._data;
  3475. };
  3476. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  3477. if (bufferView._data) {
  3478. return bufferView._data;
  3479. }
  3480. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  3481. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  3482. try {
  3483. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  3484. }
  3485. catch (e) {
  3486. throw new Error(context + ": " + e.message);
  3487. }
  3488. });
  3489. return bufferView._data;
  3490. };
  3491. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  3492. var _this = this;
  3493. if (accessor.sparse) {
  3494. throw new Error(context + ": Sparse accessors are not currently supported");
  3495. }
  3496. if (accessor._data) {
  3497. return accessor._data;
  3498. }
  3499. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  3500. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  3501. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  3502. var byteOffset = accessor.byteOffset || 0;
  3503. var byteStride = bufferView.byteStride;
  3504. if (byteStride === 0) {
  3505. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  3506. }
  3507. try {
  3508. switch (accessor.componentType) {
  3509. case 5120 /* BYTE */: {
  3510. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3511. }
  3512. case 5121 /* UNSIGNED_BYTE */: {
  3513. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3514. }
  3515. case 5122 /* SHORT */: {
  3516. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3517. }
  3518. case 5123 /* UNSIGNED_SHORT */: {
  3519. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3520. }
  3521. case 5125 /* UNSIGNED_INT */: {
  3522. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3523. }
  3524. case 5126 /* FLOAT */: {
  3525. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3526. }
  3527. default: {
  3528. throw new Error(context + ": Invalid component type " + accessor.componentType);
  3529. }
  3530. }
  3531. }
  3532. catch (e) {
  3533. throw new Error(context + ": " + e);
  3534. }
  3535. });
  3536. return accessor._data;
  3537. };
  3538. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  3539. byteOffset += data.byteOffset;
  3540. var targetLength = count * numComponents;
  3541. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  3542. return new typedArray(data.buffer, byteOffset, targetLength);
  3543. }
  3544. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  3545. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  3546. var targetBuffer = new typedArray(targetLength);
  3547. var sourceIndex = 0;
  3548. var targetIndex = 0;
  3549. while (targetIndex < targetLength) {
  3550. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  3551. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  3552. targetIndex++;
  3553. }
  3554. sourceIndex += elementStride;
  3555. }
  3556. return targetBuffer;
  3557. };
  3558. GLTFLoader.prototype._getDefaultMaterial = function () {
  3559. var id = "__gltf_default";
  3560. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  3561. if (!babylonMaterial) {
  3562. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  3563. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  3564. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  3565. babylonMaterial.metallic = 1;
  3566. babylonMaterial.roughness = 1;
  3567. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3568. }
  3569. return babylonMaterial;
  3570. };
  3571. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  3572. var promises = new Array();
  3573. var babylonMaterial = material._babylonMaterial;
  3574. // Ensure metallic workflow
  3575. babylonMaterial.metallic = 1;
  3576. babylonMaterial.roughness = 1;
  3577. var properties = material.pbrMetallicRoughness;
  3578. if (properties) {
  3579. if (properties.baseColorFactor) {
  3580. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  3581. babylonMaterial.alpha = properties.baseColorFactor[3];
  3582. }
  3583. else {
  3584. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3585. }
  3586. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  3587. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  3588. if (properties.baseColorTexture) {
  3589. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  3590. babylonMaterial.albedoTexture = texture;
  3591. }));
  3592. }
  3593. if (properties.metallicRoughnessTexture) {
  3594. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  3595. babylonMaterial.metallicTexture = texture;
  3596. }));
  3597. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  3598. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  3599. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  3600. }
  3601. }
  3602. this._loadMaterialAlphaProperties(context, material);
  3603. return Promise.all(promises).then(function () { });
  3604. };
  3605. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  3606. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  3607. if (promise) {
  3608. return promise;
  3609. }
  3610. material._babylonMeshes = material._babylonMeshes || [];
  3611. material._babylonMeshes.push(babylonMesh);
  3612. if (material._loaded) {
  3613. babylonMesh.material = material._babylonMaterial;
  3614. return material._loaded;
  3615. }
  3616. var promises = new Array();
  3617. var babylonMaterial = this._createMaterial(material);
  3618. material._babylonMaterial = babylonMaterial;
  3619. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  3620. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  3621. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3622. babylonMesh.material = babylonMaterial;
  3623. return (material._loaded = Promise.all(promises).then(function () { }));
  3624. };
  3625. GLTFLoader.prototype._createMaterial = function (material) {
  3626. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  3627. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  3628. return babylonMaterial;
  3629. };
  3630. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  3631. var promises = new Array();
  3632. var babylonMaterial = material._babylonMaterial;
  3633. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  3634. if (material.doubleSided) {
  3635. babylonMaterial.backFaceCulling = false;
  3636. babylonMaterial.twoSidedLighting = true;
  3637. }
  3638. if (material.normalTexture) {
  3639. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  3640. babylonMaterial.bumpTexture = texture;
  3641. }));
  3642. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  3643. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  3644. if (material.normalTexture.scale != undefined) {
  3645. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  3646. }
  3647. }
  3648. if (material.occlusionTexture) {
  3649. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  3650. babylonMaterial.ambientTexture = texture;
  3651. }));
  3652. babylonMaterial.useAmbientInGrayScale = true;
  3653. if (material.occlusionTexture.strength != undefined) {
  3654. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  3655. }
  3656. }
  3657. if (material.emissiveTexture) {
  3658. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  3659. babylonMaterial.emissiveTexture = texture;
  3660. }));
  3661. }
  3662. return Promise.all(promises).then(function () { });
  3663. };
  3664. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  3665. var babylonMaterial = material._babylonMaterial;
  3666. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  3667. switch (alphaMode) {
  3668. case "OPAQUE" /* OPAQUE */: {
  3669. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  3670. break;
  3671. }
  3672. case "MASK" /* MASK */: {
  3673. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  3674. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  3675. if (babylonMaterial.alpha) {
  3676. if (babylonMaterial.alpha === 0) {
  3677. babylonMaterial.alphaCutOff = 1;
  3678. }
  3679. else {
  3680. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  3681. }
  3682. babylonMaterial.alpha = 1;
  3683. }
  3684. if (babylonMaterial.albedoTexture) {
  3685. babylonMaterial.albedoTexture.hasAlpha = true;
  3686. }
  3687. break;
  3688. }
  3689. case "BLEND" /* BLEND */: {
  3690. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  3691. if (babylonMaterial.albedoTexture) {
  3692. babylonMaterial.albedoTexture.hasAlpha = true;
  3693. babylonMaterial.useAlphaFromAlbedoTexture = true;
  3694. }
  3695. break;
  3696. }
  3697. default: {
  3698. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  3699. }
  3700. }
  3701. };
  3702. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  3703. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  3704. context = "#/textures/" + textureInfo.index;
  3705. var promises = new Array();
  3706. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  3707. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  3708. var deferred = new BABYLON.Deferred();
  3709. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  3710. deferred.resolve();
  3711. }, function (message, exception) {
  3712. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  3713. });
  3714. promises.push(deferred.promise);
  3715. babylonTexture.name = texture.name || "texture" + texture._index;
  3716. babylonTexture.wrapU = samplerData.wrapU;
  3717. babylonTexture.wrapV = samplerData.wrapV;
  3718. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  3719. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  3720. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  3721. babylonTexture.updateURL(objectURL);
  3722. }));
  3723. assign(babylonTexture);
  3724. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  3725. return Promise.all(promises).then(function () { });
  3726. };
  3727. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  3728. if (!sampler._data) {
  3729. sampler._data = {
  3730. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  3731. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  3732. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  3733. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  3734. };
  3735. }
  3736. ;
  3737. return sampler._data;
  3738. };
  3739. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  3740. if (image._objectURL) {
  3741. return image._objectURL;
  3742. }
  3743. var promise;
  3744. if (image.uri) {
  3745. promise = this._loadUriAsync(context, image.uri);
  3746. }
  3747. else {
  3748. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  3749. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  3750. }
  3751. image._objectURL = promise.then(function (data) {
  3752. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  3753. });
  3754. return image._objectURL;
  3755. };
  3756. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  3757. var _this = this;
  3758. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  3759. if (promise) {
  3760. return promise;
  3761. }
  3762. if (!GLTFLoader._ValidateUri(uri)) {
  3763. throw new Error(context + ": Uri '" + uri + "' is invalid");
  3764. }
  3765. if (BABYLON.Tools.IsBase64(uri)) {
  3766. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  3767. }
  3768. return new Promise(function (resolve, reject) {
  3769. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  3770. resolve(new Uint8Array(data));
  3771. }, function (event) {
  3772. try {
  3773. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  3774. request._lengthComputable = event.lengthComputable;
  3775. request._loaded = event.loaded;
  3776. request._total = event.total;
  3777. _this._onProgress();
  3778. }
  3779. }
  3780. catch (e) {
  3781. reject(e);
  3782. }
  3783. }, _this._babylonScene.database, true, function (request, exception) {
  3784. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  3785. });
  3786. _this._requests.push(request);
  3787. });
  3788. };
  3789. GLTFLoader.prototype._onProgress = function () {
  3790. if (!this._progressCallback) {
  3791. return;
  3792. }
  3793. var lengthComputable = true;
  3794. var loaded = 0;
  3795. var total = 0;
  3796. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  3797. var request = _a[_i];
  3798. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  3799. return;
  3800. }
  3801. lengthComputable = lengthComputable && request._lengthComputable;
  3802. loaded += request._loaded;
  3803. total += request._total;
  3804. }
  3805. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  3806. };
  3807. GLTFLoader._GetProperty = function (context, array, index) {
  3808. if (!array || index == undefined || !array[index]) {
  3809. throw new Error(context + ": Failed to find index " + index);
  3810. }
  3811. return array[index];
  3812. };
  3813. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  3814. // Set defaults if undefined
  3815. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  3816. switch (mode) {
  3817. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  3818. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  3819. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3820. default:
  3821. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  3822. return BABYLON.Texture.WRAP_ADDRESSMODE;
  3823. }
  3824. };
  3825. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  3826. // Set defaults if undefined
  3827. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  3828. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  3829. if (magFilter === 9729 /* LINEAR */) {
  3830. switch (minFilter) {
  3831. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  3832. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  3833. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  3834. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  3835. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  3836. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  3837. default:
  3838. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  3839. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  3840. }
  3841. }
  3842. else {
  3843. if (magFilter !== 9728 /* NEAREST */) {
  3844. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  3845. }
  3846. switch (minFilter) {
  3847. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  3848. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  3849. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  3850. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  3851. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  3852. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  3853. default:
  3854. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  3855. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  3856. }
  3857. }
  3858. };
  3859. GLTFLoader._GetNumComponents = function (context, type) {
  3860. switch (type) {
  3861. case "SCALAR": return 1;
  3862. case "VEC2": return 2;
  3863. case "VEC3": return 3;
  3864. case "VEC4": return 4;
  3865. case "MAT2": return 4;
  3866. case "MAT3": return 9;
  3867. case "MAT4": return 16;
  3868. }
  3869. throw new Error(context + ": Invalid type " + type);
  3870. };
  3871. GLTFLoader._ValidateUri = function (uri) {
  3872. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  3873. };
  3874. GLTFLoader.prototype._compileMaterialsAsync = function () {
  3875. var promises = new Array();
  3876. if (this._gltf.materials) {
  3877. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  3878. var material = _a[_i];
  3879. var babylonMaterial = material._babylonMaterial;
  3880. var babylonMeshes = material._babylonMeshes;
  3881. if (babylonMaterial && babylonMeshes) {
  3882. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  3883. var babylonMesh = babylonMeshes_1[_b];
  3884. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  3885. if (this.useClipPlane) {
  3886. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  3887. }
  3888. }
  3889. }
  3890. }
  3891. }
  3892. return Promise.all(promises).then(function () { });
  3893. };
  3894. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  3895. var promises = new Array();
  3896. var lights = this._babylonScene.lights;
  3897. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  3898. var light = lights_1[_i];
  3899. var generator = light.getShadowGenerator();
  3900. if (generator) {
  3901. promises.push(generator.forceCompilationAsync());
  3902. }
  3903. }
  3904. return Promise.all(promises).then(function () { });
  3905. };
  3906. GLTFLoader.prototype._abortRequests = function () {
  3907. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  3908. var request = _a[_i];
  3909. request.abort();
  3910. }
  3911. this._requests.length = 0;
  3912. };
  3913. GLTFLoader.prototype._releaseResources = function () {
  3914. if (this._gltf.images) {
  3915. for (var _i = 0, _a = this._gltf.images; _i < _a.length; _i++) {
  3916. var image = _a[_i];
  3917. if (image._objectURL) {
  3918. image._objectURL.then(function (value) {
  3919. URL.revokeObjectURL(value);
  3920. });
  3921. image._objectURL = undefined;
  3922. }
  3923. }
  3924. }
  3925. };
  3926. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  3927. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  3928. var name_2 = _a[_i];
  3929. var extension = this._extensions[name_2];
  3930. if (extension.enabled) {
  3931. var promise = actionAsync(extension);
  3932. if (promise) {
  3933. return promise;
  3934. }
  3935. }
  3936. }
  3937. return null;
  3938. };
  3939. GLTFLoader._Names = new Array();
  3940. GLTFLoader._Factories = {};
  3941. return GLTFLoader;
  3942. }());
  3943. GLTF2.GLTFLoader = GLTFLoader;
  3944. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  3945. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3946. })(BABYLON || (BABYLON = {}));
  3947. //# sourceMappingURL=babylon.glTFLoader.js.map
  3948. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  3949. var BABYLON;
  3950. (function (BABYLON) {
  3951. var GLTF2;
  3952. (function (GLTF2) {
  3953. var GLTFLoaderExtension = /** @class */ (function () {
  3954. function GLTFLoaderExtension(loader) {
  3955. this.enabled = true;
  3956. this._loader = loader;
  3957. }
  3958. // #region Overridable Methods
  3959. /** Override this method to modify the default behavior for loading scenes. */
  3960. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  3961. /** Override this method to modify the default behavior for loading nodes. */
  3962. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  3963. /** Override this method to modify the default behavior for loading materials. */
  3964. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  3965. /** Override this method to modify the default behavior for loading uris. */
  3966. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  3967. // #endregion
  3968. /** Helper method called by a loader extension to load an glTF extension. */
  3969. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  3970. var _this = this;
  3971. if (!property.extensions) {
  3972. return null;
  3973. }
  3974. var extensions = property.extensions;
  3975. var extension = extensions[this._name];
  3976. if (!extension) {
  3977. return null;
  3978. }
  3979. // Clear out the extension before executing the action to avoid recursing into the same property.
  3980. delete extensions[this._name];
  3981. return actionAsync(context + "extensions/" + this._name, extension).then(function () {
  3982. // Restore the extension after completing the action.
  3983. extensions[_this._name] = extension;
  3984. });
  3985. };
  3986. /** Helper method called by the loader to allow extensions to override loading scenes. */
  3987. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  3988. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  3989. };
  3990. /** Helper method called by the loader to allow extensions to override loading nodes. */
  3991. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  3992. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  3993. };
  3994. /** Helper method called by the loader to allow extensions to override loading materials. */
  3995. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  3996. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  3997. };
  3998. /** Helper method called by the loader to allow extensions to override loading uris. */
  3999. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  4000. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  4001. };
  4002. return GLTFLoaderExtension;
  4003. }());
  4004. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  4005. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4006. })(BABYLON || (BABYLON = {}));
  4007. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  4008. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4009. var __extends = (this && this.__extends) || (function () {
  4010. var extendStatics = Object.setPrototypeOf ||
  4011. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4012. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4013. return function (d, b) {
  4014. extendStatics(d, b);
  4015. function __() { this.constructor = d; }
  4016. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4017. };
  4018. })();
  4019. var BABYLON;
  4020. (function (BABYLON) {
  4021. var GLTF2;
  4022. (function (GLTF2) {
  4023. var Extensions;
  4024. (function (Extensions) {
  4025. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  4026. var NAME = "MSFT_lod";
  4027. var MSFTLOD = /** @class */ (function (_super) {
  4028. __extends(MSFTLOD, _super);
  4029. function MSFTLOD() {
  4030. var _this = _super !== null && _super.apply(this, arguments) || this;
  4031. _this._loadingNodeLOD = null;
  4032. _this._loadNodeSignals = {};
  4033. _this._loadingMaterialLOD = null;
  4034. _this._loadMaterialSignals = {};
  4035. return _this;
  4036. }
  4037. Object.defineProperty(MSFTLOD.prototype, "_name", {
  4038. get: function () {
  4039. return NAME;
  4040. },
  4041. enumerable: true,
  4042. configurable: true
  4043. });
  4044. MSFTLOD.prototype._loadNodeAsync = function (context, node) {
  4045. var _this = this;
  4046. return this._loadExtensionAsync(context, node, function (context, extension) {
  4047. var firstPromise;
  4048. var nodeLODs = MSFTLOD._GetLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  4049. var _loop_1 = function (indexLOD) {
  4050. var nodeLOD = nodeLODs[indexLOD];
  4051. if (indexLOD !== 0) {
  4052. _this._loadingNodeLOD = nodeLOD;
  4053. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  4054. }
  4055. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  4056. if (indexLOD !== 0) {
  4057. var previousNodeLOD = nodeLODs[indexLOD - 1];
  4058. previousNodeLOD._babylonMesh.setEnabled(false);
  4059. }
  4060. if (indexLOD !== nodeLODs.length - 1) {
  4061. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  4062. _this._loadNodeSignals[nodeIndex].resolve();
  4063. delete _this._loadNodeSignals[nodeIndex];
  4064. }
  4065. });
  4066. if (indexLOD === 0) {
  4067. firstPromise = promise;
  4068. }
  4069. else {
  4070. _this._loader._completePromises.push(promise);
  4071. _this._loadingNodeLOD = null;
  4072. }
  4073. };
  4074. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  4075. _loop_1(indexLOD);
  4076. }
  4077. return firstPromise;
  4078. });
  4079. };
  4080. MSFTLOD.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  4081. var _this = this;
  4082. return this._loadExtensionAsync(context, material, function (context, extension) {
  4083. var firstPromise;
  4084. var materialLODs = MSFTLOD._GetLODs(context, material, _this._loader._gltf.materials, extension.ids);
  4085. var _loop_2 = function (indexLOD) {
  4086. var materialLOD = materialLODs[indexLOD];
  4087. if (indexLOD !== 0) {
  4088. _this._loadingMaterialLOD = materialLOD;
  4089. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  4090. }
  4091. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  4092. if (indexLOD !== materialLODs.length - 1) {
  4093. var materialIndex = materialLODs[indexLOD + 1]._index;
  4094. _this._loadMaterialSignals[materialIndex].resolve();
  4095. delete _this._loadMaterialSignals[materialIndex];
  4096. }
  4097. });
  4098. if (indexLOD === 0) {
  4099. firstPromise = promise;
  4100. }
  4101. else {
  4102. _this._loader._completePromises.push(promise);
  4103. _this._loadingMaterialLOD = null;
  4104. }
  4105. };
  4106. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  4107. _loop_2(indexLOD);
  4108. }
  4109. return firstPromise;
  4110. });
  4111. };
  4112. MSFTLOD.prototype._loadUriAsync = function (context, uri) {
  4113. var _this = this;
  4114. // Defer the loading of uris if loading a material or node LOD.
  4115. if (this._loadingMaterialLOD) {
  4116. var index = this._loadingMaterialLOD._index;
  4117. return this._loadMaterialSignals[index].promise.then(function () {
  4118. return _this._loader._loadUriAsync(context, uri);
  4119. });
  4120. }
  4121. else if (this._loadingNodeLOD) {
  4122. var index = this._loadingNodeLOD._index;
  4123. return this._loadNodeSignals[index].promise.then(function () {
  4124. return _this._loader._loadUriAsync(context, uri);
  4125. });
  4126. }
  4127. return null;
  4128. };
  4129. /**
  4130. * Gets an array of LOD properties from lowest to highest.
  4131. */
  4132. MSFTLOD._GetLODs = function (context, property, array, ids) {
  4133. var properties = [property];
  4134. for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
  4135. var id = ids_1[_i];
  4136. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + id, array, id));
  4137. }
  4138. return properties.reverse();
  4139. };
  4140. return MSFTLOD;
  4141. }(GLTF2.GLTFLoaderExtension));
  4142. Extensions.MSFTLOD = MSFTLOD;
  4143. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFTLOD(loader); });
  4144. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4145. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4146. })(BABYLON || (BABYLON = {}));
  4147. //# sourceMappingURL=MSFT_lod.js.map
  4148. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4149. var __extends = (this && this.__extends) || (function () {
  4150. var extendStatics = Object.setPrototypeOf ||
  4151. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4152. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4153. return function (d, b) {
  4154. extendStatics(d, b);
  4155. function __() { this.constructor = d; }
  4156. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4157. };
  4158. })();
  4159. var BABYLON;
  4160. (function (BABYLON) {
  4161. var GLTF2;
  4162. (function (GLTF2) {
  4163. var Extensions;
  4164. (function (Extensions) {
  4165. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  4166. var NAME = "KHR_materials_pbrSpecularGlossiness";
  4167. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  4168. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  4169. function KHRMaterialsPbrSpecularGlossiness() {
  4170. return _super !== null && _super.apply(this, arguments) || this;
  4171. }
  4172. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "_name", {
  4173. get: function () {
  4174. return NAME;
  4175. },
  4176. enumerable: true,
  4177. configurable: true
  4178. });
  4179. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  4180. var _this = this;
  4181. return this._loadExtensionAsync(context, material, function (context, extension) {
  4182. material._babylonMeshes = material._babylonMeshes || [];
  4183. material._babylonMeshes.push(babylonMesh);
  4184. if (material._loaded) {
  4185. babylonMesh.material = material._babylonMaterial;
  4186. return material._loaded;
  4187. }
  4188. var promises = new Array();
  4189. var babylonMaterial = _this._loader._createMaterial(material);
  4190. material._babylonMaterial = babylonMaterial;
  4191. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  4192. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  4193. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4194. babylonMesh.material = babylonMaterial;
  4195. return (material._loaded = Promise.all(promises).then(function () { }));
  4196. });
  4197. };
  4198. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  4199. var promises = new Array();
  4200. var babylonMaterial = material._babylonMaterial;
  4201. if (properties.diffuseFactor) {
  4202. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  4203. babylonMaterial.alpha = properties.diffuseFactor[3];
  4204. }
  4205. else {
  4206. babylonMaterial.albedoColor = BABYLON.Color3.White();
  4207. }
  4208. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  4209. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  4210. if (properties.diffuseTexture) {
  4211. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  4212. babylonMaterial.albedoTexture = texture;
  4213. }));
  4214. }
  4215. if (properties.specularGlossinessTexture) {
  4216. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  4217. babylonMaterial.reflectivityTexture = texture;
  4218. }));
  4219. babylonMaterial.reflectivityTexture.hasAlpha = true;
  4220. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  4221. }
  4222. loader._loadMaterialAlphaProperties(context, material);
  4223. return Promise.all(promises).then(function () { });
  4224. };
  4225. return KHRMaterialsPbrSpecularGlossiness;
  4226. }(GLTF2.GLTFLoaderExtension));
  4227. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  4228. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHRMaterialsPbrSpecularGlossiness(loader); });
  4229. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4230. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4231. })(BABYLON || (BABYLON = {}));
  4232. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  4233. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4234. var __extends = (this && this.__extends) || (function () {
  4235. var extendStatics = Object.setPrototypeOf ||
  4236. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4237. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4238. return function (d, b) {
  4239. extendStatics(d, b);
  4240. function __() { this.constructor = d; }
  4241. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4242. };
  4243. })();
  4244. var BABYLON;
  4245. (function (BABYLON) {
  4246. var GLTF2;
  4247. (function (GLTF2) {
  4248. var Extensions;
  4249. (function (Extensions) {
  4250. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  4251. var NAME = "KHR_lights";
  4252. var LightType;
  4253. (function (LightType) {
  4254. LightType["AMBIENT"] = "ambient";
  4255. LightType["DIRECTIONAL"] = "directional";
  4256. LightType["POINT"] = "point";
  4257. LightType["SPOT"] = "spot";
  4258. })(LightType || (LightType = {}));
  4259. var KHRLights = /** @class */ (function (_super) {
  4260. __extends(KHRLights, _super);
  4261. function KHRLights() {
  4262. return _super !== null && _super.apply(this, arguments) || this;
  4263. }
  4264. Object.defineProperty(KHRLights.prototype, "_name", {
  4265. get: function () {
  4266. return NAME;
  4267. },
  4268. enumerable: true,
  4269. configurable: true
  4270. });
  4271. KHRLights.prototype._loadSceneAsync = function (context, scene) {
  4272. var _this = this;
  4273. return this._loadExtensionAsync(context, scene, function (context, extension) {
  4274. var promise = _this._loader._loadSceneAsync(context, scene);
  4275. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  4276. if (light.type !== LightType.AMBIENT) {
  4277. throw new Error(context + ": Only ambient lights are allowed on a scene");
  4278. }
  4279. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  4280. return promise;
  4281. });
  4282. };
  4283. KHRLights.prototype._loadNodeAsync = function (context, node) {
  4284. var _this = this;
  4285. return this._loadExtensionAsync(context, node, function (context, extension) {
  4286. var promise = _this._loader._loadNodeAsync(context, node);
  4287. var babylonLight;
  4288. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  4289. var name = node._babylonMesh.name;
  4290. switch (light.type) {
  4291. case LightType.AMBIENT: {
  4292. throw new Error(context + ": Ambient lights are not allowed on a node");
  4293. }
  4294. case LightType.DIRECTIONAL: {
  4295. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  4296. break;
  4297. }
  4298. case LightType.POINT: {
  4299. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  4300. break;
  4301. }
  4302. case LightType.SPOT: {
  4303. var spotLight = light;
  4304. // TODO: support inner and outer cone angles
  4305. //const innerConeAngle = spotLight.innerConeAngle || 0;
  4306. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  4307. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  4308. break;
  4309. }
  4310. default: {
  4311. throw new Error(context + ": Invalid light type " + light.type);
  4312. }
  4313. }
  4314. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  4315. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  4316. babylonLight.parent = node._babylonMesh;
  4317. return promise;
  4318. });
  4319. };
  4320. Object.defineProperty(KHRLights.prototype, "_lights", {
  4321. get: function () {
  4322. var extensions = this._loader._gltf.extensions;
  4323. if (!extensions || !extensions[this._name]) {
  4324. throw new Error("#/extensions: " + this._name + " not found");
  4325. }
  4326. var extension = extensions[this._name];
  4327. return extension.lights;
  4328. },
  4329. enumerable: true,
  4330. configurable: true
  4331. });
  4332. return KHRLights;
  4333. }(GLTF2.GLTFLoaderExtension));
  4334. Extensions.KHRLights = KHRLights;
  4335. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHRLights(loader); });
  4336. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4337. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4338. })(BABYLON || (BABYLON = {}));
  4339. //# sourceMappingURL=KHR_lights.js.map