babylon.glTFFileLoader.js 262 KB

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