babylon.glTFFileLoader.js 194 KB

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