babylon.glTFFileLoader.js 184 KB

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