babylon.glTFFileLoader.js 219 KB

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