babylon.glTFFileLoader.js 203 KB

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