babylon.glTFFileLoader.js 221 KB

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